<?php
/**
 * ============================================================================
 * includes/footer.php (Common Footer Scripts)
 * ============================================================================
 */
?>
    <!-- Loading Overlay -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="spinner-border text-light" style="width: 3rem; height: 3rem;" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
    </div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    
    <!-- Bootstrap Bundle -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <!-- Toastify -->
    <script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
    
    <!-- Chart.js (if needed) -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    
    <!-- Common JavaScript Functions -->
    <script>
        // Application URL
        const APP_URL = '<?php echo APP_URL; ?>';
        
        // Show Toast Notification
        function showToast(message, type = 'info') {
            const colors = {
                success: 'linear-gradient(135deg, #22c55e 0%, #16a34a 100%)',
                error: 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)',
                warning: 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)',
                info: 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)'
            };
            
            Toastify({
                text: message,
                duration: 3000,
                gravity: "top",
                position: "right",
                style: {
                    background: colors[type] || colors.info,
                    borderRadius: "10px",
                    padding: "15px 20px",
                    fontSize: "15px",
                    fontWeight: "500"
                },
                stopOnFocus: true,
                close: true,
                onClick: function(){}
            }).showToast();
        }
        
        // Show Loading Overlay
        function showLoading() {
            $('#loadingOverlay').addClass('show');
        }
        
        // Hide Loading Overlay
        function hideLoading() {
            $('#loadingOverlay').removeClass('show');
        }
        
        // Confirm Dialog
        function confirmAction(title, text, callback) {
            Swal.fire({
                title: title,
                text: text,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#059669',
                cancelButtonColor: '#ef4444',
                confirmButtonText: 'Yes, proceed!',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    callback();
                }
            });
        }
        
        // Logout Function
        function logout() {
            confirmAction('Logout', 'Are you sure you want to logout?', function() {
                showLoading();
                $.post(APP_URL + '/api/auth.php', {
                    action: 'logout'
                }, function(response) {
                    hideLoading();
                    if (response.success) {
                        window.location.href = APP_URL + '/auth/login.php';
                    }
                });
            });
        }
        
        // Load Notifications
        function loadNotifications() {
            $.get(APP_URL + '/ajax/notifications.php', function(response) {
                if (response.success) {
                    const count = response.unread_count || 0;
                    
                    // Update badge
                    if (count > 0) {
                        $('#notificationsBadge').text(count).show();
                    } else {
                        $('#notificationsBadge').hide();
                    }
                    
                    // Update list
                    if (response.notifications && response.notifications.length > 0) {
                        let html = '';
                        response.notifications.forEach(function(notif) {
                            const iconClass = notif.icon || 'bell';
                            const typeClass = notif.type === 'success' ? 'success' : 
                                             notif.type === 'danger' ? 'danger' : 
                                             notif.type === 'warning' ? 'warning' : 'info';
                            
                            html += `
                                <li>
                                    <a class="dropdown-item py-2 ${notif.is_read ? '' : 'bg-light'}" href="${notif.link || '#'}">
                                        <div class="d-flex">
                                            <i class="bi bi-${iconClass} text-${typeClass} me-2 fs-5"></i>
                                            <div class="flex-grow-1">
                                                <div class="fw-semibold">${notif.title}</div>
                                                <small class="text-muted">${notif.message}</small>
                                                <div><small class="text-muted">${notif.time_ago}</small></div>
                                            </div>
                                        </div>
                                    </a>
                                </li>
                            `;
                        });
                        
                        html += `
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-center text-primary" href="${APP_URL}/notifications/">View All</a></li>
                        `;
                        
                        $('#notificationsList').html(html);
                    }
                }
            });
        }
        
        // Load notifications on page load
        $(document).ready(function() {
            loadNotifications();
            
            // Refresh notifications every 30 seconds
            setInterval(loadNotifications, 30000);
            
            // Check for flash messages
            <?php $flash = getFlashMessage(); if ($flash): ?>
            showToast('<?php echo addslashes($flash['message']); ?>', '<?php echo $flash['type']; ?>');
            <?php endif; ?>
        });
    </script>
    
    <!-- PWA Service Worker Registration -->
    <script>
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', function() {
                navigator.serviceWorker.register(APP_URL + '/pwa/service-worker.js')
                    .then(function(registration) {
                        console.log('ServiceWorker registered');
                    })
                    .catch(function(err) {
                        console.log('ServiceWorker registration failed: ', err);
                    });
            });
        }
    </script>
</body>
</html>