// Purchase Manager Sidebar JavaScript

document.addEventListener('DOMContentLoaded', function() {
    const pmHamburger = document.getElementById('pmSidebarToggle');
    const pmSidebar = document.querySelector('.pm-sidebar');
    const pmOverlay = document.getElementById('pmSidebarOverlay');

    // Toggle sidebar on hamburger click
    if (pmHamburger && pmSidebar) {
        pmHamburger.addEventListener('click', function(e) {
            e.stopPropagation();
            pmHamburger.classList.toggle('active');
            pmSidebar.classList.toggle('active');
            pmOverlay.classList.toggle('active');
        });

        // Close sidebar when a link is clicked (except logout)
        const sidebarLinks = pmSidebar.querySelectorAll('.pm-nav-link');
        sidebarLinks.forEach(link => {
            link.addEventListener('click', function() {
                if (!this.href.includes('javascript')) {
                    pmHamburger.classList.remove('active');
                    pmSidebar.classList.remove('active');
                    pmOverlay.classList.remove('active');
                }
            });
        });

        // Close sidebar when overlay is clicked
        if (pmOverlay) {
            pmOverlay.addEventListener('click', function() {
                pmHamburger.classList.remove('active');
                pmSidebar.classList.remove('active');
                pmOverlay.classList.remove('active');
            });
        }

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

            if (!isClickInsideSidebar && !isClickOnHamburger && pmSidebar.classList.contains('active')) {
                pmHamburger.classList.remove('active');
                pmSidebar.classList.remove('active');
                pmOverlay.classList.remove('active');
            }
        });
    }

    // Update badge counts
    updateBadgeCounts();

    // Update badges every 30 seconds
    setInterval(updateBadgeCounts, 30000);
});

// Update badge counts for new ingredients and low stock
function updateBadgeCounts() {
    // Update new ingredients count
    updateNewIngredientsBadge();

    // Update low stock count
    updateLowStockBadge();
}

// Update new ingredients badge
function updateNewIngredientsBadge() {
    try {
        fetch('../backend/admin_new_ingredient_request_api.php?action=get_requests&status=pending', {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        })
        .then(response => response.json())
        .then(data => {
            const count = data.count || 0;
            const badge = document.getElementById('newIngredientsCount');

            if (badge) {
                if (count > 0) {
                    badge.textContent = count;
                    badge.style.display = 'inline-flex';
                } else {
                    badge.style.display = 'none';
                }
            }
        })
        .catch(error => console.log('Could not load new ingredients count'));
    } catch (error) {
        console.log('Could not load new ingredients count');
    }
}

// Update low stock badge
function updateLowStockBadge() {
    try {
        fetch('../backend/supplier_products_api.php?action=get_low_stock_ingredients', {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        })
        .then(response => response.json())
        .then(data => {
            const count = data.ingredients?.length || 0;
            const badge = document.getElementById('lowStockBadge');

            if (badge) {
                if (count > 0) {
                    badge.textContent = count;
                    badge.style.display = 'inline-flex';
                } else {
                    badge.style.display = 'none';
                }
            }
        })
        .catch(error => console.log('Could not load low stock count'));
    } catch (error) {
        console.log('Could not load low stock count');
    }
}

// Handle logout
async function handleLogout() {
    const logoutUrl = '../backend/purchase_manager_logout.php';
    const Swal = window.Swal;
    if (Swal) {
        const result = await Swal.fire({
            title: 'Logout',
            text: 'Are you sure you want to logout?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, logout',
            confirmButtonColor: '#dc2626'
        });

        if (result.isConfirmed) {
            // Let backend destroy session and perform server-side redirect to purchase_manager/index.php
            window.location.replace(logoutUrl);
        }
    } else {
        if (confirm('Are you sure you want to logout?')) {
            window.location.replace(logoutUrl);
        }
    }
}
