/**

 * SchoolFinance Pro - Main JavaScript

 * Complete Sidebar Toggle & Mobile Responsiveness

 */



$(document).ready(function() {

    // State variables

    let sidebarVisible = true;

    let touchStartX = 0;

    let touchEndX = 0;

    

    // Initialize sidebar state based on screen size

    initSidebar();

    

    // Handle window resize

    let resizeTimer;

    $(window).on('resize', function() {

        clearTimeout(resizeTimer);

        resizeTimer = setTimeout(function() {

            initSidebar();

        }, 250);

    });

    

    /**

     * Initialize sidebar based on screen size

     */

    function initSidebar() {

        const width = $(window).width();

        

        // Remove any existing overlay

        $('.sidebar-overlay').remove();

        

        // Create overlay for mobile

        if (width <= 991) {

            $('body').append('<div class="sidebar-overlay"></div>');

            

            // Ensure sidebar starts hidden on mobile/tablet

            $('#sidebar').removeClass('active hidden');

            sidebarVisible = false;

        } else {

            // On desktop, sidebar starts visible

            $('#sidebar').removeClass('active hidden');

            sidebarVisible = true;

            $('.main-content').removeClass('expanded');

        }

    }

    

    /**

     * Toggle sidebar function

     */

    window.toggleSidebar = function(show) {

        const width = $(window).width();

        const $sidebar = $('#sidebar');

        const $overlay = $('.sidebar-overlay');

        const $mainContent = $('.main-content');

        

        if (width <= 991) {

            // Mobile/Tablet: slide sidebar

            if (show !== undefined) {

                if (show) {

                    $sidebar.addClass('active');

                    $overlay.addClass('active');

                    $('body').addClass('sidebar-open');

                    sidebarVisible = true;

                } else {

                    $sidebar.removeClass('active');

                    $overlay.removeClass('active');

                    $('body').removeClass('sidebar-open');

                    sidebarVisible = false;

                }

            } else {

                // Toggle

                if ($sidebar.hasClass('active')) {

                    $sidebar.removeClass('active');

                    $overlay.removeClass('active');

                    $('body').removeClass('sidebar-open');

                    sidebarVisible = false;

                } else {

                    $sidebar.addClass('active');

                    $overlay.addClass('active');

                    $('body').addClass('sidebar-open');

                    sidebarVisible = true;

                }

            }

        } else {

            // Desktop: adjust margin

            if (show !== undefined) {

                if (!show) {

                    $sidebar.addClass('hidden');

                    $mainContent.addClass('expanded');

                    sidebarVisible = false;

                } else {

                    $sidebar.removeClass('hidden');

                    $mainContent.removeClass('expanded');

                    sidebarVisible = true;

                }

            } else {

                // Toggle

                if ($sidebar.hasClass('hidden')) {

                    $sidebar.removeClass('hidden');

                    $mainContent.removeClass('expanded');

                    sidebarVisible = true;

                } else {

                    $sidebar.addClass('hidden');

                    $mainContent.addClass('expanded');

                    sidebarVisible = false;

                }

            }

        }

    };

    

    // Sidebar toggle button click

    $('#sidebarToggle').on('click', function(e) {

        e.preventDefault();

        e.stopPropagation();

        toggleSidebar();

    });

    

    // Close sidebar when clicking overlay

    $(document).on('click', '.sidebar-overlay', function() {

        toggleSidebar(false);

    });

    

    // Close sidebar with Escape key

    $(document).on('keyup', function(e) {

        if (e.key === 'Escape' && $(window).width() <= 991) {

            if ($('#sidebar').hasClass('active')) {

                toggleSidebar(false);

            }

        }

    });

    

    // Touch events for swipe to close on mobile

    $(document).on('touchstart', function(e) {

        touchStartX = e.originalEvent.touches[0].clientX;

    });

    

    $(document).on('touchend', function(e) {

        if ($(window).width() <= 991 && $('#sidebar').hasClass('active')) {

            touchEndX = e.originalEvent.changedTouches[0].clientX;

            handleSwipe();

        }

    });

    

    function handleSwipe() {

        const swipeDistance = touchEndX - touchStartX;

        // If swiped left more than 50px, close sidebar

        if (swipeDistance < -50) {

            toggleSidebar(false);

        }

    }

    

    // Prevent clicks inside sidebar from closing it

    $('#sidebar').on('click', function(e) {

        e.stopPropagation();

    });

    

    // NOTE: Dropdowns are handled natively by Bootstrap 5 (data-bs-toggle="dropdown").
    // A previous custom implementation here bound a global document click handler
    // that stripped .show from every .dropdown-menu — including on the very click
    // that opened it — which cancelled Bootstrap's toggle and left the profile
    // dropdown unable to open above 767px. Bootstrap already handles toggling,
    // outside-click close, Escape and keyboard nav, so no custom code is needed.

    // Initialize tooltips

    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));

    var tooltipList = tooltipTriggerList.map(function(tooltipTriggerEl) {

        return new bootstrap.Tooltip(tooltipTriggerEl);

    });

    

    // Auto-dismiss alerts

    window.setTimeout(function() {

        $('.alert').fadeTo(500, 0).slideUp(500, function() {

            $(this).remove();

        });

    }, 5000);

    

    // Phone number validation

    $('input[type="tel"]').on('input', function() {

        this.value = this.value.replace(/[^0-9+]/g, '');

    });

    

    // Number-only input

    $('input[type="number"]').on('input', function() {

        this.value = this.value.replace(/[^0-9.]/g, '');

    });

});



// ── Defensive guard: clear any accidentally-active overlay on full page load ──

window.addEventListener('load', function () {

    if (typeof $ !== 'undefined' && !$('#sidebar').hasClass('active')) {

        $('.sidebar-overlay').removeClass('active');

    }

});



// Toast Notification Function

function showToast(message, type = 'success') {

    // Create toast container if needed

    if ($('.toast-container').length === 0) {

        $('body').append('<div class="toast-container" style="position: fixed; top: 20px; right: 20px; z-index: 9999;"></div>');

    }

    

    const icon = type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'exclamation-triangle';

    const bgColor = type === 'error' ? '#fee' : '#fff';

    const borderColor = type === 'error' ? '#E74C3C' : '#27AE60';

    const iconColor = type === 'error' ? '#E74C3C' : '#27AE60';

    

    const toast = $(`

        <div class="toast toast-${type}" style="display: block; background: ${bgColor}; border-left: 4px solid ${borderColor}; border-radius: 8px; padding: 15px 20px; margin-bottom: 10px; min-width: 300px; max-width: 400px; box-shadow: 0 5px 15px rgba(0,0,0,0.2); animation: slideIn 0.3s ease; position: relative;">

            <div style="display: flex; align-items: center; gap: 10px;">

                <i class="fas fa-${icon}" style="color: ${iconColor}; font-size: 1.2rem;"></i>

                <span style="color: #2C3E50; flex: 1;">${message}</span>

                <button type="button" class="btn-close" style="background: none; border: none; font-size: 1.2rem; cursor: pointer; padding: 0 5px;" onclick="$(this).closest('.toast').fadeOut(function(){$(this).remove();})">&times;</button>

            </div>

        </div>

    `);

    

    $('.toast-container').append(toast);

    

    setTimeout(function() {

        toast.fadeOut(function() {

            $(this).remove();

        });

    }, 5000);

}



// Loading Spinner

function showLoader() {

    if ($('.spinner-overlay').length === 0) {

        $('body').append('<div class="spinner-overlay" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255,255,255,0.9); display: none; align-items: center; justify-content: center; z-index: 9999;"><div class="spinner-border text-primary" style="width: 50px; height: 50px;" role="status"><span class="visually-hidden">Loading...</span></div></div>');

    }

    $('.spinner-overlay').css('display', 'flex');

}



function hideLoader() {

    $('.spinner-overlay').css('display', 'none');

}



// Format Currency - Ghana Cedi

function formatCurrency(amount) {

    if (isNaN(amount)) amount = 0;

    return '₵' + parseFloat(amount).toLocaleString('en-US', {

        minimumFractionDigits: 2,

        maximumFractionDigits: 2

    });

}



// Format Date

function formatDate(dateString) {

    if (!dateString) return '';

    const date = new Date(dateString);

    if (isNaN(date.getTime())) return dateString;

    const options = { day: '2-digit', month: 'short', year: 'numeric' };

    return date.toLocaleDateString('en-US', options);

}



// Confirm Delete

function confirmDelete(message = 'Are you sure you want to delete this record?') {

    return confirm(message);

}



// Print Content

function printContent(elementId) {

    const content = document.getElementById(elementId).innerHTML;

    const printWindow = window.open('', '', 'height=600,width=800');

    printWindow.document.write('<html><head><title>Print</title>');

    printWindow.document.write('<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">');

    printWindow.document.write('<link rel="stylesheet" href="css/style.css">');

    printWindow.document.write('</head><body>');

    printWindow.document.write('<div class="container-fluid mt-4">' + content + '</div>');

    printWindow.document.write('</body></html>');

    printWindow.document.close();

    printWindow.print();

}



// Copy to Clipboard

function copyToClipboard(text) {

    navigator.clipboard.writeText(text).then(function() {

        showToast('Copied to clipboard', 'success');

    }, function(err) {

        showToast('Failed to copy', 'error');

    });

}