// Hamburger Menu Toggle
document.addEventListener('DOMContentLoaded', function() {
    const hamburger = document.getElementById('sidebarToggle');
    const sidebar = document.querySelector('.sidebar');

    if (hamburger && sidebar) {
        hamburger.addEventListener('click', function() {
            hamburger.classList.toggle('active');
            sidebar.classList.toggle('active');
        });

        // Close sidebar when a link is clicked
        const sidebarLinks = sidebar.querySelectorAll('a');
        sidebarLinks.forEach(link => {
            link.addEventListener('click', function() {
                // Only close if not a logout link
                if (!this.href.includes('javascript')) {
                    hamburger.classList.remove('active');
                    sidebar.classList.remove('active');
                }
            });
        });

        // Close sidebar when clicking outside
        document.addEventListener('click', function(event) {
            const isClickInsideSidebar = sidebar.contains(event.target);
            const isClickOnHamburger = hamburger.contains(event.target);

            if (!isClickInsideSidebar && !isClickOnHamburger && sidebar.classList.contains('active')) {
                hamburger.classList.remove('active');
                sidebar.classList.remove('active');
            }
        });
    }
});

// Shared manager logout for all pages that include sidebar.php
function logout() {
    const performLogout = function() {
        const clearAndRedirect = function() {
            localStorage.removeItem('manager_id');
            localStorage.removeItem('manager_name');
            localStorage.removeItem('manager_email');
            localStorage.removeItem('manager_shift');
            window.location.href = 'login.php';
        };

        if (window.jQuery) {
            $.ajax({
                url: '../backend/manager_logout.php',
                method: 'POST',
                complete: clearAndRedirect
            });
            return;
        }

        fetch('../backend/manager_logout.php', {
            method: 'POST'
        }).finally(clearAndRedirect);
    };

    if (window.Swal) {
        Swal.fire({
            title: 'Logout Confirmation',
            text: 'Are you sure you want to logout?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, logout'
        }).then((result) => {
            if (result.isConfirmed) {
                performLogout();
            }
        });
        return;
    }

    if (window.confirm('Are you sure you want to logout?')) {
        performLogout();
    }
}
