                </div>
        </main>
    </div>
    <style>
        .menuits{
                width: 90%;
                margin: 5%;
                border-radius: 1%;
                }
     </style>
    <!-- Footer - Hidden on Mobile, Sticky on Desktop -->
    <footer style="background: linear-gradient(135deg, <?php echo htmlspecialchars(config('app.ui.primary_color') ?? '#2563eb'); ?> 0%, <?php echo htmlspecialchars(config('app.ui.primary_color') ?? '#2563eb'); ?> 100%);" class="hidden md:flex text-white fixed bottom-0 w-full z-50 right-0 shadow-lg">
        <div class="w-full max-w-7xl mx-auto px-6 py-4">
            <div class="flex justify-between items-center">
                <div class="flex space-x-4">
                    <a href="?page=dashboard" class="text-white/80 hover:text-white transition-colors text-sm"><i class="fas fa-home mr-2"></i><?php echo trans('dashboard'); ?></a>
                    <a href="?page=profile" class="text-white/80 hover:text-white transition-colors text-sm"><i class="fas fa-user mr-2"></i><?php echo trans('profile'); ?></a>
                    <?php if ($_SESSION['role'] === 'admin'): ?>
                    <a href="?page=settings" class="text-white/80 hover:text-white transition-colors text-sm"><i class="fas fa-cog mr-2"></i><?php echo trans('settings'); ?></a>
                    <?php endif; ?>
                </div>
                <div class="text-xs text-white/60">
                    &copy; <?php echo date('Y'); ?> <?php echo config('app.company'); ?> - <?php echo trans('all_rights_reserved'); ?>
                </div>
            </div>
        </div>
    </footer>
    
    <!-- Mobile Bottom Navigation - Fixed Footer for Mobile Only -->
    <nav style="background: linear-gradient(135deg, <?php echo htmlspecialchars(config('app.ui.primary_color') ?? '#2563eb'); ?> 0%, <?php echo htmlspecialchars(config('app.ui.primary_color') ?? '#2563eb'); ?> 100%);" class="md:hidden fixed bottom-0 left-0 right-0 text-white shadow-2xl z-40">
        <div class="flex justify-between items-center h-16">
            <?php
            $userRole = $_SESSION['role'] ?? null;
            
            // Build dynamic menu based on user role
            if ($userRole === 'client') {
                $mobilePages = [
                    'clients/dashboard' => ['icon' => 'fa-chart-line', 'label' => 'my_dashboard'],
                    'clients/my-invoices' => ['icon' => 'fa-file-invoice-dollar', 'label' => 'my_invoices'],
                    'clients/payments' => ['icon' => 'fa-credit-card', 'label' => 'payments'],
                    'clients/messages' => ['icon' => 'fa-envelope', 'label' => 'messages'],
                ];
            } elseif ($userRole === 'guard') {
                $mobilePages = [
                    'guards-patrols' => ['icon' => 'fa-qrcode', 'label' => 'start_patrol'],
                    'guards-dashboard' => ['icon' => 'fa-chart-line', 'label' => 'my_dashboard'],
                    'guards-posts' => ['icon' => 'fa-map-pin', 'label' => 'my_post'],
                    'guards-messages' => ['icon' => 'fa-envelope', 'label' => 'messages'],
                ];
            } elseif ($userRole === 'controller') {
                $mobilePages = [
                    'controllers-dashboard' => ['icon' => 'fa-chart-line', 'label' => 'my_dashboard'],
                    'controllers-posts' => ['icon' => 'fa-map-pin', 'label' => 'posts_in_zone'],
                    'controllers-payments' => ['icon' => 'fa-credit-card', 'label' => 'my_payments'],
                    'controllers-messages' => ['icon' => 'fa-envelope', 'label' => 'messages'],
                ];
            } else {
                $mobilePages = [
                    'dashboard' => ['icon' => 'fa-home', 'label' => 'dashboard'],
                    'clients' => ['icon' => 'fa-users', 'label' => 'clients'],
                    'staff' => ['icon' => 'fa-people-group', 'label' => 'staff'],
                    'invoices' => ['icon' => 'fa-file-invoice-dollar', 'label' => 'invoices'],
                    'messages' => ['icon' => 'fa-envelope', 'label' => 'messages'],
                ];
            }
            
            $count = 0;
            foreach ($mobilePages as $pageName => $pageInfo):
                if ($auth->canAccessPage($pageName) && $count < 4):
                    $isActive = ($_GET['page'] ?? 'dashboard') === $pageName;
                    ?>
            <a href="?page=<?php echo $pageName; ?>" class="flex flex-col items-center justify-center flex-1 h-full text-white/80 hover:text-white transition-colors <?php echo $isActive ? 'bg-white/20' : ''; ?>">
                <i class="fas <?php echo $pageInfo['icon']; ?> text-lg"></i>
                <span class="text-xs mt-1"><?php echo trans($pageInfo['label']); ?></span>
            </a>
                    <?php
                    $count++;
                endif;
            endforeach;
            ?>
            <button id="mobileMenuBtn" class="flex flex-col items-center justify-center flex-1 h-full text-white/80 hover:text-white transition-colors">
                <i class="fas fa-ellipsis-v text-lg"></i>
                <span class="text-xs mt-1"><?php echo trans('more') ?? 'More'; ?></span>
            </button>
        </div>
    </nav>

    <!-- Mobile Menu Modal - Megamenu Grid Layout -->
    <div id="mobileMenuModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 md:hidden">
        <div class="menuits fixed bottom-16 left-0 right-0 bg-white rounded-t-lg shadow-lg z-50 max-h-[calc(100vh-4rem)] overflow-y-auto">
            <div class="p-4 space-y-4">
                <!-- Header -->
                <div class="flex items-center justify-between px-2 pb-4 border-b">
                    <h3 class="font-bold text-lg text-gray-800"><?php echo trans('menu'); ?></h3>
                    <button onclick="document.getElementById('mobileMenuModal').classList.add('hidden')" class="text-gray-500 hover:text-gray-700 text-2xl">×</button>
                </div>

                <!-- Menu Grid - Dynamic based on role -->
                <div class="grid grid-cols-2 gap-2">
                    <?php
                    $userRole = $_SESSION['role'] ?? null;
                    
                    if ($userRole === 'client') {
                        $allPages = [
                            'clients/dashboard' => ['icon' => 'fa-chart-line', 'label' => 'my_dashboard'],
                            'clients/profile' => ['icon' => 'fa-user-circle', 'label' => 'profile'],
                            'clients/my-posts' => ['icon' => 'fa-file-contract', 'label' => 'my_posts'],
                            'clients/contract' => ['icon' => 'fa-handshake', 'label' => 'contract'],
                            'clients/site-assessment' => ['icon' => 'fa-clipboard-list', 'label' => 'assessment'],
                            'clients/my-guards' => ['icon' => 'fa-people-group', 'label' => 'my_guards'],
                            'clients/my-controls' => ['icon' => 'fa-list-check', 'label' => 'my_controls'],
                            'clients/my-feedbacks' => ['icon' => 'fa-star', 'label' => 'feedbacks'],
                            'clients/my-patrols' => ['icon' => 'fa-map-location-dot', 'label' => 'patrols'],
                            'clients/my-invoices' => ['icon' => 'fa-file-invoice-dollar', 'label' => 'my_invoices'],
                            'clients/payments' => ['icon' => 'fa-credit-card', 'label' => 'payments'],
                            'clients/messages' => ['icon' => 'fa-envelope', 'label' => 'messages'],
                        ];
                    } elseif ($userRole === 'guard') {
                        $allPages = [
                            'guards-dashboard' => ['icon' => 'fa-chart-line', 'label' => 'my_dashboard'],
                            'guards-profile' => ['icon' => 'fa-user-circle', 'label' => 'profile'],
                            'guards-posts' => ['icon' => 'fa-map-pin', 'label' => 'my_post'],
                            'guards-patrols' => ['icon' => 'fa-map-location-dot', 'label' => 'my_patrols'],
                            'guards-controls' => ['icon' => 'fa-list-check', 'label' => 'my_controls'],
                            'guards-payments' => ['icon' => 'fa-credit-card', 'label' => 'my_payments'],
                            'guards-messages' => ['icon' => 'fa-envelope', 'label' => 'messages'],
                        ];
                    } elseif ($userRole === 'controller') {
                        $allPages = [
                            'controllers-dashboard' => ['icon' => 'fa-chart-line', 'label' => 'my_dashboard'],
                            'controllers-profile' => ['icon' => 'fa-user-circle', 'label' => 'profile'],
                            'controllers-posts' => ['icon' => 'fa-map-pin', 'label' => 'posts_in_zone'],
                            'controllers-patrols' => ['icon' => 'fa-map-location-dot', 'label' => 'patrols'],
                            'controllers-controls' => ['icon' => 'fa-list-check', 'label' => 'controls'],
                            'controllers-payments' => ['icon' => 'fa-credit-card', 'label' => 'my_payments'],
                            'controllers-messages' => ['icon' => 'fa-envelope', 'label' => 'messages'],
                        ];
                    } else {
                        $allPages = [
                            'dashboard' => ['icon' => 'fa-home', 'label' => 'dashboard'],
                            'clients' => ['icon' => 'fa-users', 'label' => 'clients'],
                            'staff' => ['icon' => 'fa-people-group', 'label' => 'staff'],
                            'posts' => ['icon' => 'fa-building', 'label' => 'posts'],
                            'guards' => ['icon' => 'fa-shield', 'label' => 'guards'],
                            'evaluations' => ['icon' => 'fa-clipboard-list', 'label' => 'evaluations'],
                            'messages' => ['icon' => 'fa-envelope', 'label' => 'messages'],
                            'finances' => ['icon' => 'fa-chart-line', 'label' => 'finances'],
                            'invoices' => ['icon' => 'fa-file-invoice-dollar', 'label' => 'invoices'],
                            'payments' => ['icon' => 'fa-credit-card', 'label' => 'payments'],
                            'controls' => ['icon' => 'fa-shield-alt', 'label' => 'controls'],
                            'patrols' => ['icon' => 'fa-walking', 'label' => 'patrols'],
                            'salaries' => ['icon' => 'fa-money-check', 'label' => 'salaries'],
                            'roles' => ['icon' => 'fa-users-cog', 'label' => 'user_management'],
                            'settings' => ['icon' => 'fa-cog', 'label' => 'settings'],
                        ];
                    }
                    
                    foreach($allPages as $pageName => $pageInfo):
                        if($auth->canAccessPage($pageName)):
                            $isActive = ($_GET['page'] ?? 'dashboard') === $pageName;
                            ?>
                    <a href="?page=<?php echo $pageName; ?>" class="flex flex-col items-center gap-2 px-3 py-4 text-gray-700 hover:bg-blue-50 rounded-lg transition-colors <?php echo $isActive ? 'bg-blue-50 text-blue-600 font-semibold' : ''; ?>">
                        <i class="fas <?php echo $pageInfo['icon']; ?> text-lg"></i>
                        <span class="text-xs text-center"><?php echo trans($pageInfo['label']); ?></span>
                    </a>
                            <?php
                        endif;
                    endforeach;
                    ?>
                </div>

                <!-- Account Section -->
                <div class="pt-4 border-t">
                    <p class="text-xs font-semibold text-gray-500 uppercase mb-2 px-2"><?php echo trans('account'); ?></p>
                    <div class="space-y-1">
                        <a href="?page=profile" class="block px-4 py-3 text-gray-700 hover:bg-blue-50 rounded-lg transition-colors <?php echo ($_GET['page'] ?? '') === 'profile' ? 'bg-blue-50 text-blue-600 font-semibold' : ''; ?>">
                            <i class="fas fa-user mr-3"></i><?php echo trans('profile'); ?>
                        </a>
                        <a href="?page=settings" class="block px-4 py-3 text-gray-700 hover:bg-blue-50 rounded-lg transition-colors <?php echo ($_GET['page'] ?? '') === 'settings' ? 'bg-blue-50 text-blue-600 font-semibold' : ''; ?>">
                            <i class="fas fa-cog mr-3"></i><?php echo trans('settings'); ?>
                        </a>
                        <a href="?action=logout" class="block px-4 py-3 text-red-600 hover:bg-red-50 rounded-lg transition-colors font-semibold">
                            <i class="fas fa-sign-out-alt mr-3"></i><?php echo trans('logout'); ?>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // Mobile menu toggle
        document.getElementById('mobileMenuBtn').addEventListener('click', function(e) {
            e.preventDefault();
            const modal = document.getElementById('mobileMenuModal');
            modal.classList.toggle('hidden');
        });
        document.getElementById('mobileMenuModal').addEventListener('click', function(e) {
            if (e.target === this) {
                this.classList.add('hidden');
            }
        });
    </script>
    
    <!-- Offline Banner -->
    <div id="offlineBanner" class="hidden fixed bottom-0 left-0 right-0 bg-yellow-500 text-white p-4 text-center z-40">
        <i class="fas fa-wifi-slash"></i>
        <span><?php echo trans('offline_mode'); ?> - <?php echo trans('last_sync'); ?>: <span id="lastSyncTime">--:--</span>
    </div>
    
    <!-- Main JS - Embedded to avoid static file serving issues -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.js"></script>
    
    <!-- Core Application JavaScript - Embedded Inline -->
    <script>
// ============================================
// PWA HANDLER - Global Object (Must be defined first)
// ============================================
const pwaHandler = {
    deferredPrompt: null,
    isAppInstalled: false,
    promptInstall: function() {
        if (this.deferredPrompt) {
            this.deferredPrompt.prompt();
            this.deferredPrompt.userChoice.then((choiceResult) => {
                if (choiceResult.outcome === 'accepted') {
                    console.log('✓ User accepted the install prompt');
                    this.isAppInstalled = true;
                } else {
                    console.log('User dismissed the install prompt');
                }
                pwaHandler.deferredPrompt = null;
            });
        } else {
            // Show fallback message
            Swal.fire({
                icon: 'info',
                title: 'Installation not available',
                text: 'PWA installation is not supported on your device or browser. Try Chrome, Edge, or Firefox on desktop/mobile.',
                confirmButtonText: 'Got it'
            });
        }
    }
};

// Listen for install prompt
window.addEventListener('beforeinstallprompt', (e) => {
    e.preventDefault();
    pwaHandler.deferredPrompt = e;
    console.log('✓ Install prompt is available');
});

// Check if app is already installed
window.addEventListener('appinstalled', () => {
    pwaHandler.isAppInstalled = true;
    const installBtn = document.getElementById('installAppBtn');
    if (installBtn) {
        installBtn.classList.add('hidden');
    }
    console.log('✓ App installed as PWA');
});

// ============================================
// MAIN APPLICATION JAVASCRIPT
// ============================================

// Initialize app on DOM ready
document.addEventListener('DOMContentLoaded', function() {
    initializeMenus();
    initializeNotifications();
    initializeSidebar();
    setupLanguageSwitcher();
    setupOfflineDetection();
});

/**
 * Initialize dropdown menus
 */
function initializeMenus() {
    // Helper function to close all menus
    function closeAllMenus() {
        document.getElementById('languageMenu')?.classList.add('hidden');
        document.getElementById('notificationPanel')?.classList.add('hidden');
        document.getElementById('userMenu')?.classList.add('hidden');
    }

    // Language menu toggle
    const languageBtn = document.getElementById('languageBtn');
    const languageMenu = document.getElementById('languageMenu');
    if (languageBtn && languageMenu) {
        languageBtn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            closeAllMenus();
            languageMenu.classList.toggle('hidden');
        });
        languageMenu.addEventListener('click', (e) => {
            e.stopPropagation();
            // Close menu when clicking on a link
            if (e.target.tagName === 'A') {
                closeAllMenus();
            }
        });
    }

    // Notification menu toggle
    const notificationBtn = document.getElementById('notificationBtn');
    const notificationPanel = document.getElementById('notificationPanel');
    if (notificationBtn && notificationPanel) {
        notificationBtn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            closeAllMenus();
            notificationPanel.classList.toggle('hidden');
        });
        notificationPanel.addEventListener('click', (e) => {
            e.stopPropagation();
            // Keep panel open when clicking inside
        });
    }

    // User menu toggle
    const userMenuBtn = document.getElementById('userMenuBtn');
    const userMenu = document.getElementById('userMenu');
    if (userMenuBtn && userMenu) {
        userMenuBtn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            closeAllMenus();
            userMenu.classList.toggle('hidden');
        });
        userMenu.addEventListener('click', (e) => {
            e.stopPropagation();
            // Close menu when clicking on a link
            if (e.target.tagName === 'A' || e.target.closest('a')) {
                closeAllMenus();
            }
        });
    }

    // Close all menus when clicking outside
    document.addEventListener('click', (e) => {
        // Don't close if clicking on header elements
        if (!e.target.closest('header')) {
            closeAllMenus();
        }
    });
}

/**
 * Initialize sidebar collapse/expand
 */
function initializeSidebar() {
    const sidebarToggle = document.getElementById('sidebarToggle');
    const sidebar = document.getElementById('sidebar');
    
    if (sidebarToggle && sidebar) {
        sidebarToggle.addEventListener('click', () => {
            sidebar.classList.toggle('collapsed');
            // Save state to localStorage
            const isCollapsed = sidebar.classList.contains('collapsed');
            localStorage.setItem('sidebarCollapsed', isCollapsed);
        });
        
        // Restore previous state
        if (localStorage.getItem('sidebarCollapsed') === 'true') {
            sidebar.classList.add('collapsed');
        }
    }
}

/**
 * Initialize notifications
 */
function initializeNotifications() {
    // Load unread notifications
    fetchNotifications();
    
    // Poll for new notifications every 30 seconds
    setInterval(fetchNotifications, 30000);
    
    // Mark all as read button
    const markAllReadBtn = document.getElementById('markAllRead');
    if (markAllReadBtn) {
        markAllReadBtn.addEventListener('click', markAllNotificationsAsRead);
    }
    
    // Setup Install App button
    setupInstallAppButton();
}

/**
 * Fetch user notifications
 */
function fetchNotifications() {
    fetch('?page=api&endpoint=notifications/get')
        .then(response => response.json())
        .then(data => {
            if (data && data.notifications) {
                displayNotifications(data.notifications);
            }
        })
        .catch(error => {
            console.error('Error fetching notifications:', error);
        });
}

/**
 * Display notifications in the panel
 */
function displayNotifications(notifications) {
    const list = document.getElementById('notificationList');
    const badge = document.getElementById('notificationBadge');
    
    if (!list) return;
    
    // Count unread notifications
    const unreadCount = notifications.filter(n => !n.read_at).length;
    
    // Update badge
    if (badge) {
        if (unreadCount > 0) {
            badge.textContent = unreadCount > 9 ? '9+' : unreadCount;
            badge.classList.remove('hidden');
        } else {
            badge.classList.add('hidden');
        }
    }
    
    // Display notifications
    if (notifications.length === 0) {
        list.innerHTML = '<div class="p-4 text-center text-gray-500 text-sm"><?php echo trans("no_notifications") ?? "No notifications"; ?></div>';
        return;
    }
    
    list.innerHTML = notifications.map(notification => {
        const created = new Date(notification.created_at);
        const timeAgo = getTimeAgo(created);
        const isUnread = !notification.read_at;
        const bgClass = isUnread ? 'bg-blue-50 border-l-4 border-blue-500' : 'bg-white';
        
        // Color based on type
        let typeIcon = 'fa-info-circle text-blue-500';
        if (notification.type === 'success') typeIcon = 'fa-check-circle text-green-500';
        if (notification.type === 'error') typeIcon = 'fa-exclamation-circle text-red-500';
        if (notification.type === 'warning') typeIcon = 'fa-exclamation-triangle text-yellow-500';
        
        return `
            <div class="px-4 py-3 border-b border-gray-100 ${bgClass} hover:bg-gray-50 transition cursor-pointer" onclick="markNotificationRead(${notification.id})">
                <div class="flex items-start gap-3">
                    <i class="fas ${typeIcon} flex-shrink-0 mt-1"></i>
                    <div class="flex-1 min-w-0">
                        <p class="font-semibold text-gray-800 text-sm truncate">${notification.title || 'Notification'}</p>
                        <p class="text-gray-600 text-xs mt-1 line-clamp-2">${notification.message || ''}</p>
                        <p class="text-gray-400 text-xs mt-2">${timeAgo}</p>
                    </div>
                    ${isUnread ? '<div class="flex-shrink-0 w-2 h-2 bg-blue-500 rounded-full mt-2"></div>' : ''}
                </div>
            </div>
        `;
    }).join('');
}

/**
 * Get human-readable time difference
 */
function getTimeAgo(date) {
    const now = new Date();
    const seconds = Math.floor((now - date) / 1000);
    
    if (seconds < 60) return 'just now';
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60) return minutes + 'm ago';
    const hours = Math.floor(minutes / 60);
    if (hours < 24) return hours + 'h ago';
    const days = Math.floor(hours / 24);
    if (days < 7) return days + 'd ago';
    
    return date.toLocaleDateString();
}

/**
 * Mark notification as read
 */
function markNotificationRead(notificationId) {
    fetch('?page=api&endpoint=notifications/mark-read&id=' + notificationId, {
        method: 'POST'
    })
    .then(() => {
        fetchNotifications();
    })
    .catch(error => console.error('Error marking notification as read:', error));
}

/**
 * Mark all notifications as read
 */
function markAllNotificationsAsRead() {
    fetch('?page=api&endpoint=notifications/mark-all-read', {
        method: 'POST'
    })
    .then(() => {
        fetchNotifications();
    })
    .catch(error => console.error('Error marking all notifications as read:', error));
}

/**
 * Setup Install App button on dashboards
 */
function setupInstallAppButton() {
    const installBtn = document.getElementById('installAppBtn');
    if (!installBtn) return;
    
    if (typeof pwaHandler === 'undefined') return;
    
    // Check if app is already installed - show message
    if (pwaHandler.isAppInstalled || window.matchMedia('(display-mode: standalone)').matches) {
        // Hide install button and show installed status
        installBtn.classList.add('hidden');
        
        // Show installed message on page
        showInstalledMessage();
        return;
    }
    
    // Show button if app is not installed
    installBtn.classList.remove('hidden');
    
    // Add click handler
    installBtn.addEventListener('click', function(e) {
        e.preventDefault();
        
        // Show beautiful SweetAlert modal
        if (pwaHandler.deferredPrompt) {
            Swal.fire({
                icon: 'info',
                title: 'Install SSCI Office',
                html: `
                    <div class="text-left">
                        <p class="mb-4 text-gray-700">Install SSCI Office as an app on your device for:</p>
                        <ul class="list-none text-gray-600 mb-4">
                            <li class="mb-2">
                                <i class="fas fa-check-circle text-green-500 mr-2"></i>
                                <span>Offline access to your data</span>
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-bell text-blue-500 mr-2"></i>
                                <span>Push notifications for updates</span>
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-lightning-bolt text-yellow-500 mr-2"></i>
                                <span>Faster performance</span>
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-home text-purple-500 mr-2"></i>
                                <span>Access directly from your home screen</span>
                            </li>
                        </ul>
                    </div>
                `,
                showCancelButton: true,
                confirmButtonText: 'Install Now',
                cancelButtonText: 'Later',
                confirmButtonColor: '#0284c7',
                cancelButtonColor: '#6b7280',
                didOpen: () => {
                    // Add custom styling
                    const confirmBtn = Swal.getConfirmButton();
                    if (confirmBtn) {
                        confirmBtn.classList.add('bg-blue-600', 'hover:bg-blue-700', 'text-white', 'font-semibold', 'py-2', 'px-6', 'rounded-lg');
                    }
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    pwaHandler.promptInstall();
                }
            });
        } else if (!pwaHandler.isAppInstalled) {
            // PWA installation not available
            Swal.fire({
                icon: 'info',
                title: 'Installation Not Available',
                html: `
                    <div class="text-left">
                        <p class="mb-3">PWA installation is not available on your current setup.</p>
                        <p class="text-sm text-gray-600">Try using:</p>
                        <ul class="list-none text-gray-600 text-sm mt-2">
                            <li class="mb-1"><i class="fas fa-chrome mr-1 text-blue-400"></i> Google Chrome</li>
                            <li class="mb-1"><i class="fas fa-edge mr-1 text-blue-600"></i> Microsoft Edge</li>
                            <li class="mb-1"><i class="fas fa-firefox mr-1 text-orange-500"></i> Mozilla Firefox</li>
                        </ul>
                        <p class="text-xs text-gray-500 mt-3">On desktop or mobile devices.</p>
                    </div>
                `,
                confirmButtonText: 'Got it',
                confirmButtonColor: '#0284c7'
            });
        }
    });
}

/**
 * Show installed app message
 */
function showInstalledMessage() {
    // Create and show toast notification
    Swal.fire({
        icon: 'success',
        title: 'App Installed',
        text: 'SSCI Office is installed on your device',
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 3000
    });
}

/**
 * Setup language switcher
 */
function setupLanguageSwitcher() {
    // Already handled by menu initialization
}

/**
 * Setup offline detection
 */
function setupOfflineDetection() {
    const banner = document.getElementById('offlineBanner');
    
    window.addEventListener('offline', () => {
        if (banner) banner.classList.remove('hidden');
    });
    
    window.addEventListener('online', () => {
        if (banner) banner.classList.add('hidden');
    });
}

// ============================================
// PROFILE PAGE - SIMPLE CLEAN HANDLERS
// ============================================

let cropper = null;

function switchTab(tabName) {
    document.querySelectorAll('.tab-content').forEach(tab => {
        tab.classList.add('hidden');
    });
    
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('text-blue-600', 'border-b-2', 'border-blue-600');
        btn.classList.add('text-gray-600');
    });

    const tabElement = document.getElementById(tabName + '-tab');
    if (tabElement) {
        tabElement.classList.remove('hidden');
    }
    
    const activeBtn = document.querySelector('[data-tab="' + tabName + '"]');
    if (activeBtn) {
        activeBtn.classList.remove('text-gray-600');
        activeBtn.classList.add('text-blue-600', 'border-b-2', 'border-blue-600');
    }
}

function enable2FA() {
    Swal.fire({
        title: 'Enable 2FA',
        text: 'You will need an authenticator app',
        icon: 'info',
        confirmButtonText: 'Continue'
    });
}

function openCropperModal(imageSrc) {
    const primaryColor = document.querySelector('[style*="--primary-color"]')?.style.getPropertyValue('--primary-color') || '#2563eb';
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50';
    modal.id = 'cropperModal';
    modal.innerHTML = '<div class="bg-white rounded-lg shadow-lg max-w-2xl w-full animate__animated animate__slideInDown"><div class="flex justify-between items-center p-6 border-b border-gray-200"><h2 class="text-xl font-bold text-gray-800">Crop Photo</h2><button type="button" class="closeModal text-gray-500 hover:text-gray-700 text-2xl font-bold">&times;</button></div><div class="p-6 max-h-96 overflow-auto bg-gray-50"><img id="cropperImage" src="' + imageSrc + '" style="max-width: 100%; display: block;"></div><div class="flex gap-3 p-6 border-t border-gray-200"><button type="button" class="saveCrop flex-1 text-white py-2 rounded-lg transition font-semibold" style="background-color: ' + primaryColor + ';">✓ Save</button><button type="button" class="closeModal flex-1 bg-gray-300 text-gray-700 py-2 rounded-lg hover:bg-gray-400 transition font-semibold">Cancel</button></div></div>';
    
    document.body.appendChild(modal);
    
    document.querySelectorAll('.closeModal').forEach(btn => {
        btn.addEventListener('click', function() {
            if (cropper) {
                cropper.destroy();
                cropper = null;
            }
            modal.remove();
        });
    });
    
    document.querySelector('.saveCrop').addEventListener('click', cropImage);
    
    const image = modal.querySelector('#cropperImage');
    if (cropper) {
        cropper.destroy();
    }
    cropper = new Cropper(image, {
        aspectRatio: 1,
        viewMode: 1,
        autoCropArea: 1,
        responsive: true,
        restore: true,
        guides: true,
        center: true,
        highlight: true,
        cropBoxMovable: true,
        cropBoxResizable: true,
        toggleDragModeOnDblclick: true
    });
}

function cropImage() {
    if (!cropper) return;
    
    const canvas = cropper.getCroppedCanvas({
        maxWidth: 400,
        maxHeight: 400,
        fillColor: '#fff',
        imageSmoothingEnabled: true,
        imageSmoothingQuality: 'high'
    });
    
    const previewDiv = document.getElementById('profilePhotoPreview');
    if (previewDiv) {
        previewDiv.innerHTML = '';
        const img = new Image();
        img.src = canvas.toDataURL('image/jpeg');
        img.className = 'w-full h-full object-cover';
        previewDiv.appendChild(img);
    }
    
    document.getElementById('photoData').value = canvas.toDataURL('image/jpeg');
    
    if (cropper) {
        cropper.destroy();
        cropper = null;
    }
    
    const modal = document.getElementById('cropperModal');
    if (modal) {
        modal.remove();
    }
    
    Swal.fire({
        icon: 'success',
        title: 'Success',
        text: 'Photo updated',
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 2000
    });
}

// Wait for DOMContentLoaded for profile page setup
document.addEventListener('DOMContentLoaded', function() {
    // Tab buttons
    document.querySelectorAll('.profile-tab-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            switchTab(this.getAttribute('data-tab'));
        });
    });

    // Upload photo button
    const uploadBtn = document.querySelector('.upload-photo-btn');
    if (uploadBtn) {
        uploadBtn.addEventListener('click', function(e) {
            e.preventDefault();
            document.getElementById('photoInput').click();
        });
    }

    // Photo input change
    const photoInput = document.getElementById('photoInput');
    if (photoInput) {
        photoInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    openCropperModal(event.target.result);
                };
                reader.readAsDataURL(file);
            }
        });
    }

    // Enable 2FA button
    const enable2FABtn = document.getElementById('enable2FABtn');
    if (enable2FABtn) {
        enable2FABtn.addEventListener('click', function(e) {
            e.preventDefault();
            enable2FA();
        });
    }

    // Profile Form
    const profileForm = document.getElementById('profileForm');
    if (profileForm) {
        profileForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const photoData = document.getElementById('photoData').value;
            if (photoData) {
                formData.append('photo', photoData);
            }
            
            const submitBtn = this.querySelector('button[type="submit"]');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Saving...';
            
            fetch('?page=api&action=saveProfile', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: data.message || 'Profile updated successfully',
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 2000
                    }).then(() => setTimeout(() => location.reload(), 300));
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: data.message || 'An error occurred'
                    });
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '<i class="fas fa-save mr-2"></i>Save Changes';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'An error occurred'
                });
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fas fa-save mr-2"></i>Save Changes';
            });
        });
    }

    // Security Form
    const securityForm = document.getElementById('securityForm');
    if (securityForm) {
        securityForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const newPassword = document.querySelector('input[name="new_password"]').value;
            const confirmPassword = document.querySelector('input[name="confirm_password"]').value;
            
            if (newPassword !== confirmPassword) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Password Mismatch',
                    text: 'Passwords do not match'
                });
                return;
            }
            
            const formData = new FormData(this);
            const submitBtn = this.querySelector('button[type="submit"]');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Updating...';
            
            fetch('?page=api&action=changePassword', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: data.message || 'Password changed successfully',
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 2000
                    }).then(() => setTimeout(() => location.reload(), 300));
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: data.message || 'An error occurred'
                    });
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '<i class="fas fa-key mr-2"></i>Update Password';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'An error occurred'
                });
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fas fa-key mr-2"></i>Update Password';
            });
        });
    }

    // Preferences Form
    const preferencesForm = document.getElementById('preferencesForm');
    if (preferencesForm) {
        preferencesForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            
            // Ensure checkboxes are properly captured
            const emailNotif = this.querySelector('input[name="email_notifications"]');
            const inAppNotif = this.querySelector('input[name="in_app_notifications"]');
            const smsNotif = this.querySelector('input[name="sms_notifications"]');
            
            if (!emailNotif.checked) formData.delete('email_notifications');
            if (!inAppNotif.checked) formData.delete('in_app_notifications');
            if (!smsNotif.checked) formData.delete('sms_notifications');
            
            const submitBtn = this.querySelector('button[type="submit"]');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Saving...';
            
            fetch('?page=api&action=savePreferences', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: data.message || 'Preferences updated successfully',
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 2000
                    }).then(() => setTimeout(() => location.reload(), 300));
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: data.message || 'An error occurred'
                    });
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '<i class="fas fa-save mr-2"></i>Save Preferences';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'An error occurred'
                });
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fas fa-save mr-2"></i>Save Preferences';
            });
        });
    }
});

// ============================================
// END APPLICATION JAVASCRIPT
// ============================================
    </script>
    
    <!-- Service Worker Registration -->
    <script>
        if('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/service-worker.js', {scope: '/'})
                .then(reg => {
                    console.log('✓ Service Worker registered successfully');
                })
                .catch(err => {
                    console.log('Service Worker registration attempted');
                });
        } else {
            console.log('Service Workers not supported in this browser');
        }
    </script>
    

    
    <!-- Offline Handler -->
    <script>
        if (!navigator.onLine) {
            document.getElementById('offlineBanner')?.classList.remove('hidden');
        }
    </script>
    
    <?php if(isset($additionalJS)): ?>
        <?php foreach($additionalJS as $js): ?>
            <script src="<?php echo $js; ?>"></script>
        <?php endforeach; ?>
    <?php endif; ?>

    <!-- Toast Notification Function -->
    <script>
        function showToast(type, message, duration = 3000) {
            // Remove existing toasts
            const existing = document.querySelector('.toast-notification');
            if (existing) existing.remove();

            // Create toast element
            const toast = document.createElement('div');
            toast.className = `toast-notification fixed top-6 right-6 px-6 py-3 rounded-lg text-white font-semibold shadow-lg z-50 animate__animated animate__slideInRight`;
            
            // Set colors based on type
            const colors = {
                success: 'bg-green-500',
                error: 'bg-red-500',
                warning: 'bg-yellow-500',
                info: 'bg-blue-500'
            };
            
            toast.classList.add(colors[type] || colors.info);
            toast.textContent = message;
            document.body.appendChild(toast);

            // Auto-remove after duration
            setTimeout(() => {
                toast.classList.add('animate__slideOutRight');
                setTimeout(() => toast.remove(), 300);
            }, duration);
        }
    </script>
    
    <!-- Quill Rich Text Editor Script -->
    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
</body>
</html>
