<!DOCTYPE html>
<html lang="en" data-bs-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= isset($title) ? $title : 'Labourdnhdd - CMS' ?></title>
    <!-- CSRF Token -->
    <meta name="X-CSRF-TOKEN" content="<?= csrf_hash() ?>">
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-light: #5EC9F8;
            --primary-medium: #3A82D4;
            --primary-dark: #214D8C;
            --accent-saffron: #FF9933;
            --accent-green: #138808;
            --jtech-blue: linear-gradient(135deg, #5EC9F8 0%, #3A82D4 50%, #214D8C 100%);
        }
        
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            transition: background-color 0.3s, color 0.3s;
        }
        
        body[data-bs-theme="dark"] {
            background-color: #121212;
            color: #e0e0e0;
        }
        
        .sidebar {
            background-color: #fff;
            box-shadow: 0 0 15px rgba(0,0,0,0.08);
            height: 100vh;
            position: fixed;
            z-index: 1000;
            transition: all 0.3s ease;
        }
        
        body[data-bs-theme="dark"] .sidebar {
            background-color: #1e1e1e;
            box-shadow: 0 0 15px rgba(0,0,0,0.3);
        }
        
        .top-header {
            background-color: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
            z-index: 1000;
        }
        
        body[data-bs-theme="dark"] .top-header {
            background-color: #1e1e1e;
            box-shadow: 0 2px 10px rgba(0,0,0,0.3);
        }
        
        .main-content {
            margin-top: 70px;
            margin-left: 0;
            margin-bottom: 70px; /* Height of bottom nav */
            transition: all 0.3s ease;
        }
        
        .sidebar .nav-link {
            color: #495057;
            border-radius: 0.5rem;
            margin: 0.25rem 0.75rem;
            padding: 0.75rem 1rem;
            transition: all 0.2s ease;
            position: relative;
        }
        
        body[data-bs-theme="dark"] .sidebar .nav-link {
            color: #e0e0e0;
        }
        
        .sidebar .nav-link:hover {
            background-color: #e9ecef;
            color: var(--primary-medium);
        }
        
        body[data-bs-theme="dark"] .sidebar .nav-link:hover {
            background-color: #2d2d2d;
            color: var(--primary-medium);
        }
        
        .sidebar .nav-link.active {
            background: var(--jtech-blue);
            color: white !important;
        }
        
        .sidebar .nav-link.active::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            width: 4px;
            background-color: white;
            border-radius: 0 4px 4px 0;
        }
        
        .notification-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background-color: #dc3545;
            color: white;
            border-radius: 50%;
            padding: 2px 6px;
            font-size: 0.75rem;
            min-width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .bottom-nav {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background-color: white;
            box-shadow: 0 -4px 10px rgba(0,0,0,0.08);
            z-index: 1000;
            padding: 0.5rem 0;
        }
        
        body[data-bs-theme="dark"] .bottom-nav {
            background-color: #1e1e1e;
            box-shadow: 0 -4px 10px rgba(0,0,0,0.3);
        }
        
        .bottom-nav .nav-link {
            color: #6c757d;
            text-align: center;
            padding: 0.5rem 0;
            font-size: 0.75rem;
            transition: all 0.2s ease;
        }
        
        body[data-bs-theme="dark"] .bottom-nav .nav-link {
            color: #a0a0a0;
        }
        
        .bottom-nav .nav-link.active {
            color: var(--primary-medium);
            font-weight: 600;
        }
        
        .bottom-nav .nav-link:hover {
            color: var(--primary-medium);
        }
        
        /* Make bottom nav visible on desktop */
        .bottom-nav {
            display: block !important;
        }
        
        /* Adjust main content to account for bottom nav */
        .main-content {
            margin-bottom: 70px; /* Height of bottom nav */
        }
        
        @media (max-width: 767.98px) {
            .sidebar {
                width: 100%;
                height: auto;
                position: relative;
                transform: translateY(-100%);
                display: none;
            }
            
            .sidebar.active {
                display: block;
                transform: translateY(0);
            }
            
            .main-content {
                margin-left: 0;
            }
            
            .top-header {
                padding: 0.75rem 1rem;
            }
            
            /* Adjust notification dropdown for mobile */
            #notificationDropdown {
                width: 300px;
                right: -50px;
            }
            
            /* Adjust search results for mobile */
            #searchResults {
                width: 300px;
                left: -50px;
            }
        }
        
        @media (min-width: 768px) {
            .sidebar {
                width: 250px;
            }
            
            /* Since sidebar is removed, no need to adjust margin */
            .main-content {
                margin-left: 0;
            }
        }
        
        .brand-logo {
            background: var(--jtech-blue);
        }
        
        .bg-gradient-primary {
            background: var(--jtech-blue) !important;
        }
        
        .btn-primary {
            background: var(--jtech-blue);
            border: none;
        }
        
        .btn-primary:hover {
            background: #214D8C;
        }
        
        .progress {
            background-color: #e9ecef;
        }
        
        body[data-bs-theme="dark"] .progress {
            background-color: #333;
        }
        
        .card {
            border-radius: 1rem;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
            border: none;
        }
        
        body[data-bs-theme="dark"] .card {
            background-color: #1e1e1e;
            border: 1px solid #333;
        }
        
        .card:hover {
            transform: translateY(-3px);
            box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.15) !important;
        }
        
        body[data-bs-theme="dark"] .card:hover {
            box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.3) !important;
        }
        
        .rounded-circle {
            border-radius: 50% !important;
        }
        
        .theme-toggle-btn {
            background: transparent;
            border: 1px solid #dee2e6;
            color: #495057;
        }
        
        body[data-bs-theme="dark"] .theme-toggle-btn {
            border: 1px solid #333;
            color: #e0e0e0;
        }
        
        .search-input {
            border-radius: 2rem;
            padding-left: 2.5rem;
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
        }
        
        body[data-bs-theme="dark"] .search-input {
            background-color: #2d2d2d;
            border: 1px solid #333;
            color: #e0e0e0;
        }
        
        .form-control {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
        }
        
        body[data-bs-theme="dark"] .form-control {
            background-color: #2d2d2d;
            border: 1px solid #333;
            color: #e0e0e0;
        }
        
        .btn-light {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            color: #495057;
        }
        
        body[data-bs-theme="dark"] .btn-light {
            background-color: #2d2d2d;
            border: 1px solid #333;
            color: #e0e0e0;
        }
        
        .mobile-menu-toggle {
            background: var(--jtech-blue);
            color: white;
            border: none;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .search-input {
            border-radius: 2rem;
            padding-left: 2.5rem;
        }
        
        .search-icon {
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
        }
        
        .text-muted {
            color: #6c757d !important;
        }
        
        body[data-bs-theme="dark"] .text-muted {
            color: #a0a0a0 !important;
        }
        
        .alert {
            border: none;
            border-radius: 0.5rem;
        }
        
        body[data-bs-theme="dark"] .alert-primary {
            background-color: rgba(58, 130, 212, 0.2);
            color: #a0c8f0;
        }
        
        body[data-bs-theme="dark"] .alert-success {
            background-color: rgba(25, 135, 84, 0.2);
            color: #a3dba3;
        }
        
        body[data-bs-theme="dark"] .alert-warning {
            background-color: rgba(255, 193, 7, 0.2);
            color: #f0d8a0;
        }
        
        body[data-bs-theme="dark"] .alert-danger {
            background-color: rgba(220, 53, 69, 0.2);
            color: #f0a3a3;
        }
        
        .list-group-item {
            border-color: #dee2e6;
        }
        
        body[data-bs-theme="dark"] .list-group-item {
            background-color: #1e1e1e;
            border-color: #333;
            color: #e0e0e0;
        }
        
        .nav-pills .nav-link.active {
            background: var(--jtech-blue);
        }
        
        .pre {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            color: #212529;
        }
        
        body[data-bs-theme="dark"] .pre {
            background-color: #2d2d2d;
            border: 1px solid #333;
            color: #e0e0e0;
        }
        
        /* Notification Dropdown Styles */
        .dropdown-menu {
            background-color: #fff;
            border: 1px solid #dee2e6;
        }
        
        body[data-bs-theme="dark"] .dropdown-menu {
            background-color: #1e1e1e;
            border: 1px solid #333;
        }
        
        .card-header {
            border-bottom: 1px solid #dee2e6;
        }
        
        body[data-bs-theme="dark"] .card-header {
            border-bottom: 1px solid #333;
        }
        
        .card-footer {
            border-top: 1px solid #dee2e6;
        }
        
        body[data-bs-theme="dark"] .card-footer {
            border-top: 1px solid #333;
        }
        
        body[data-bs-theme="dark"] .dropdown-menu a {
            color: #e0e0e0;
        }
        
        body[data-bs-theme="dark"] .dropdown-menu a:hover {
            color: #3A82D4;
        }
        
        /* Search Results Styles */
        #searchResults .list-group-item {
            border: none;
            border-radius: 0;
        }
        
        #searchResults .list-group-item:hover {
            background-color: #f8f9fa;
        }
        
        body[data-bs-theme="dark"] #searchResults .list-group-item:hover {
            background-color: #2d2d2d;
        }
        
        body[data-bs-theme="dark"] #searchResults .card-header {
            background-color: #214D8C;
        }
        
        /* Logout Loader Styles */
        #logoutLoader {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 10000;
        }
        
        #logoutLoader .loader-content {
            background-color: white;
            border-radius: 0.5rem;
            padding: 2rem;
            text-align: center;
            box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.15);
        }
        
        body[data-bs-theme="dark"] #logoutLoader .loader-content {
            background-color: #1e1e1e;
            color: #e0e0e0;
        }
    </style>
</head>
<body data-bs-theme="light">
    <!-- Logout Loader Overlay -->
    <div id="logoutLoader">
        <div class="loader-content">
            <div class="spinner-border text-primary mb-3" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mb-0 fw-medium">Logging out...</p>
        </div>
    </div>
    
    <!-- Top Header -->
    <header class="top-header py-3 px-4 fixed-top">
        <div class="d-flex justify-content-between align-items-center">
            <!-- Left side: Logo + App name + Role -->
            <div class="d-flex align-items-center">
                <button class="mobile-menu-toggle d-md-none me-3" id="mobileMenuToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="brand-logo rounded-circle p-2 me-3" style="width: 40px; height: 40px; display: flex; align-items: center; justify-content: center;">
                    <span class="text-white fw-bold">J</span>
                </div>
                <div>
                    <h1 class="h5 fw-bold mb-0">Labourdnhdd - CMS</h1>
                    <span class="text-muted small">
                        <?= session()->get('role') === 'superadmin' ? 'Super Admin' : 'Admin' ?>
                    </span>
                </div>
            </div>
            
            <!-- Center: Page title (hidden on mobile) -->
            <div class="d-none d-md-block text-center">
                <h2 class="h5 fw-semibold mb-0"><?= isset($title) ? $title : 'Dashboard' ?></h2>
            </div>
            
            <!-- Right side: Search, Notifications, Theme Toggle, Logout -->
            <div class="d-flex align-items-center">
                <!-- Search -->
                <div class="position-relative d-none d-md-block me-3">
                    <input type="text" placeholder="Search..." class="form-control search-input" id="searchInput" style="width: 200px;">
                    <i class="fas fa-search position-absolute search-icon text-muted"></i>
                    <!-- Search Results Dropdown -->
                    <div class="dropdown-menu dropdown-menu-end p-0 shadow" id="searchResults" style="width: 350px; display: none; position: absolute; top: 100%; left: 0; z-index: 1000;">
                        <div class="card border-0">
                            <div class="card-header bg-primary text-white">
                                <h6 class="mb-0">Search Results</h6>
                            </div>
                            <div class="card-body p-0" style="max-height: 300px; overflow-y: auto;">
                                <div id="searchResultsList">
                                    <!-- Search results will be populated here -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Mobile search icon -->
                <button class="btn btn-sm btn-light d-md-none me-2" id="mobileSearchToggle">
                    <i class="fas fa-search"></i>
                </button>
                
                <!-- Notifications -->
                <div class="position-relative me-3">
                    <button class="btn btn-sm btn-light position-relative" id="notificationBell">
                        <i class="fas fa-bell"></i>
                        <span class="notification-badge" id="notificationCount">3</span>
                    </button>
                    <!-- Notification Dropdown -->
                    <div class="dropdown-menu dropdown-menu-end p-0 shadow" id="notificationDropdown" style="width: 350px; display: none; position: absolute; top: 100%; right: 0; z-index: 1000;">
                        <div class="card border-0">
                            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                                <h6 class="mb-0">Notifications</h6>
                                <button class="btn btn-sm btn-light" id="markAllRead">
                                    <i class="fas fa-check-circle"></i> Mark all as read
                                </button>
                            </div>
                            <div class="card-body p-0" style="max-height: 300px; overflow-y: auto;">
                                <div class="list-group list-group-flush" id="notificationList">
                                    <!-- Notifications will be populated here dynamically -->
                                </div>
                            </div>
                            <div class="card-footer text-center">
                                <a href="<?= base_url('/notifications') ?>" class="text-decoration-none">View all notifications</a>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Theme Toggle -->
                <button class="btn btn-sm theme-toggle-btn me-2" id="themeToggle">
                    <i class="fas fa-moon"></i>
                </button>
                
                <!-- Logout Button -->
                <a href="<?= base_url('/logout') ?>" id="logoutButton" class="btn btn-sm btn-light">
                    <i class="fas fa-sign-out-alt"></i>
                </a>
            </div>
        </div>
    </header>
    
    <div class="container-fluid">
        <div class="row">
            <!-- Main Content (full width since sidebar is removed) -->
            <main class="col-12 px-md-4 main-content">
                <div class="pt-4">
                    <?= $this->renderSection('content') ?>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Bottom Navigation (visible on all screens) -->
    <nav class="bottom-nav" id="bottomNav">
        <div class="d-flex">
            <a class="flex-fill nav-link <?= (service('uri')->getPath() === '/dashboard') ? 'active' : '' ?>" href="<?= base_url('/dashboard') ?>">
                <i class="fas fa-home d-block fs-5"></i>
                <span>Dashboard</span>
            </a>
            <a class="flex-fill nav-link <?= (strpos(service('uri')->getPath(), '/companies') === 0) ? 'active' : '' ?>" href="<?= base_url('/companies') ?>">
                <i class="fas fa-building d-block fs-5"></i>
                <span>Companies</span>
            </a>
            <a class="flex-fill nav-link <?= (service('uri')->getPath() === '/settings' || strpos(service('uri')->getPath(), '/settings/') === 0) ? 'active' : '' ?>" href="<?= base_url('/settings') ?>">
                <i class="fas fa-cog d-block fs-5"></i>
                <span>Settings</span>
            </a>
            <a class="flex-fill nav-link <?= (strpos(service('uri')->getPath(), '/contractors') === 0) ? 'active' : '' ?>" href="<?= base_url('/contractors') ?>">
                <i class="fas fa-hard-hat d-block fs-5"></i>
                <span>Contractors</span>
            </a>
            <a class="flex-fill nav-link <?= (strpos(service('uri')->getPath(), '/personnel') === 0) ? 'active' : '' ?>" href="<?= base_url('/personnel') ?>">
                <i class="fas fa-users d-block fs-5"></i>
                <span>Personnel</span>
            </a>
            <a class="flex-fill nav-link <?= (strpos(service('uri')->getPath(), '/units') === 0) ? 'active' : '' ?>" href="<?= base_url('/units') ?>">
                <i class="fas fa-industry d-block fs-5"></i>
                <span>Units</span>
            </a>
            <?php if (session()->get('role') === 'superadmin'): ?>
                <a class="flex-fill nav-link <?= (strpos(service('uri')->getPath(), '/admin') === 0) ? 'active' : '' ?>" href="<?= base_url('/admin') ?>">
                    <i class="fas fa-user-shield d-block fs-5"></i>
                    <span>Admins</span>
                </a>
            <?php endif; ?>
        </div>
    </nav>

    <!-- Bootstrap 5 JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Theme toggle functionality
        document.addEventListener('DOMContentLoaded', function() {
            const themeToggle = document.getElementById('themeToggle');
            const mobileMenuToggle = document.getElementById('mobileMenuToggle');
            const sidebar = document.getElementById('sidebar');
            const logoutButton = document.getElementById('logoutButton');
            const logoutLoader = document.getElementById('logoutLoader');
            const body = document.body;
            
            // Load saved theme preference
            const savedTheme = localStorage.getItem('theme');
            if (savedTheme) {
                body.setAttribute('data-bs-theme', savedTheme);
                updateThemeIcon(savedTheme);
            }
            
            // Theme toggle button
            if (themeToggle) {
                themeToggle.addEventListener('click', function() {
                    const currentTheme = body.getAttribute('data-bs-theme');
                    const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
                    
                    body.setAttribute('data-bs-theme', newTheme);
                    localStorage.setItem('theme', newTheme);
                    updateThemeIcon(newTheme);
                });
            }
            
            // Update theme icon based on current theme
            function updateThemeIcon(theme) {
                const icon = themeToggle.querySelector('i');
                if (theme === 'dark') {
                    icon.classList.remove('fa-moon');
                    icon.classList.add('fa-sun');
                } else {
                    icon.classList.remove('fa-sun');
                    icon.classList.add('fa-moon');
                }
            }
            
            // Logout functionality with loader
            if (logoutButton) {
                logoutButton.addEventListener('click', function(e) {
                    e.preventDefault();
                    
                    // Show loader
                    logoutLoader.style.display = 'flex';
                    
                    // Redirect to logout after a short delay to show the loader
                    setTimeout(() => {
                        window.location.href = this.href;
                    }, 500);
                });
            }
            
            // Notification functionality
            const notificationBell = document.getElementById('notificationBell');
            const notificationDropdown = document.getElementById('notificationDropdown');
            const markAllReadBtn = document.getElementById('markAllRead');
            const notificationCount = document.getElementById('notificationCount');
            const notificationList = document.getElementById('notificationList');
            
            // Load notifications when bell is clicked
            if (notificationBell) {
                notificationBell.addEventListener('click', function(e) {
                    e.stopPropagation();
                    const isVisible = notificationDropdown.style.display === 'block';
                    
                    if (!isVisible) {
                        // Load notifications
                        loadNotifications();
                    }
                    
                    notificationDropdown.style.display = isVisible ? 'none' : 'block';
                });
                
                // Close dropdown when clicking outside
                document.addEventListener('click', function(e) {
                    if (!notificationDropdown.contains(e.target) && !notificationBell.contains(e.target)) {
                        notificationDropdown.style.display = 'none';
                    }
                });
            }
            
            // Load notifications from server
            function loadNotifications() {
                fetch('/dashboard/notifications')
                    .then(response => response.json())
                    .then(data => {
                        displayNotifications(data.notifications);
                        updateNotificationCount(data.unreadCount);
                    })
                    .catch(error => {
                        console.error('Error loading notifications:', error);
                        // Fallback to hardcoded notifications if there's an error
                        displayFallbackNotifications();
                    });
            }
            
            // Display notifications in the dropdown
            function displayNotifications(notifications) {
                if (!notificationList) return;
                
                if (!notifications || notifications.length === 0) {
                    notificationList.innerHTML = '<div class="p-3 text-center text-muted">No notifications</div>';
                    return;
                }
                
                let html = '';
                notifications.forEach(notification => {
                    let iconClass = 'fa-bell';
                    let iconBgClass = 'bg-primary';
                    let iconTextClass = 'text-primary';
                    
                    if (notification.type === 'company') {
                        iconClass = 'fa-building';
                        iconBgClass = 'bg-primary';
                        iconTextClass = 'text-primary';
                    } else if (notification.type === 'personnel') {
                        iconClass = 'fa-user-plus';
                        iconBgClass = 'bg-success';
                        iconTextClass = 'text-success';
                    } else if (notification.type === 'system') {
                        iconClass = 'fa-info-circle';
                        iconBgClass = 'bg-info';
                        iconTextClass = 'text-info';
                    }
                    
                    html += `
                        <div class="list-group-item border-0 notification-item" data-id="${notification.id}">
                            <div class="d-flex">
                                <div class="me-3">
                                    <div class="p-2 rounded-circle ${iconBgClass} bg-opacity-10">
                                        <i class="fas ${iconClass} ${iconTextClass}"></i>
                                    </div>
                                </div>
                                <div class="flex-grow-1">
                                    <div class="d-flex justify-content-between">
                                        <h6 class="mb-1">${notification.title}</h6>
                                        <small class="text-muted">${notification.timestamp}</small>
                                    </div>
                                    <p class="mb-1 text-muted">${notification.message}</p>
                                    ${!notification.read ? '<span class="badge bg-primary bg-opacity-10 text-primary">New</span>' : ''}
                                </div>
                            </div>
                        </div>
                    `;
                });
                
                notificationList.innerHTML = html;
            }
            
            // Fallback for hardcoded notifications
            function displayFallbackNotifications() {
                const fallbackNotifications = [
                    {
                        id: 1,
                        title: 'New Company Registered',
                        message: 'Tech Solutions Inc. was added to the system',
                        timestamp: '2 hours ago',
                        read: false,
                        type: 'company'
                    },
                    {
                        id: 2,
                        title: 'New Employee Added',
                        message: 'John Doe was added to ABC Corporation',
                        timestamp: '5 hours ago',
                        read: false,
                        type: 'personnel'
                    },
                    {
                        id: 3,
                        title: 'Contract Expiring Soon',
                        message: 'Contract for XYZ Ltd expires in 7 days',
                        timestamp: '2 days ago',
                        read: false,
                        type: 'system'
                    }
                ];
                
                displayNotifications(fallbackNotifications);
                updateNotificationCount(3);
            }
            
            // Update notification count badge
            function updateNotificationCount(count) {
                if (notificationCount) {
                    if (count > 0) {
                        notificationCount.textContent = count;
                        notificationCount.style.display = 'flex';
                    } else {
                        notificationCount.style.display = 'none';
                    }
                }
            }
            
            // Mark all notifications as read
            if (markAllReadBtn) {
                markAllReadBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    
                    // Get CSRF token
                    const csrfToken = document.querySelector('meta[name="X-CSRF-TOKEN"]');
                    const csrfHash = csrfToken ? csrfToken.getAttribute('content') : '';
                    
                    // Send request to mark all as read
                    fetch('/dashboard/notifications/mark-read', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-CSRF-TOKEN': csrfHash
                        },
                        body: JSON.stringify({action: 'mark_all_read'})
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Update UI
                            document.querySelectorAll('.notification-item .badge').forEach(badge => {
                                badge.remove();
                            });
                            updateNotificationCount(0);
                        }
                    })
                    .catch(error => {
                        console.error('Error marking notifications as read:', error);
                    });
                });
            }
            
            // Search functionality
            const searchInput = document.getElementById('searchInput');
            const searchResults = document.getElementById('searchResults');
            const searchResultsList = document.getElementById('searchResultsList');
            const mobileSearchToggle = document.getElementById('mobileSearchToggle');
            
            if (searchInput) {
                let searchTimeout;
                
                searchInput.addEventListener('input', function() {
                    const query = this.value.trim();
                    
                    if (query.length < 2) {
                        searchResults.style.display = 'none';
                        return;
                    }
                    
                    // Debounce search requests
                    clearTimeout(searchTimeout);
                    searchTimeout = setTimeout(() => {
                        fetchSearchResults(query);
                    }, 300);
                });
                
                // Close search results when clicking outside
                document.addEventListener('click', function(e) {
                    if (!searchInput.contains(e.target) && !searchResults.contains(e.target)) {
                        searchResults.style.display = 'none';
                    }
                });
            }
            
            // Mobile search toggle
            if (mobileSearchToggle) {
                mobileSearchToggle.addEventListener('click', function() {
                    // For mobile, we could show a modal or expand the search bar
                    // For now, we'll just focus the search input if it exists
                    if (searchInput) {
                        searchInput.focus();
                    }
                });
            }
            
            // Fetch search results from server
            function fetchSearchResults(query) {
                fetch(`/dashboard/search?q=${encodeURIComponent(query)}`)
                    .then(response => response.json())
                    .then(data => {
                        displaySearchResults(data.results);
                    })
                    .catch(error => {
                        console.error('Search error:', error);
                        displaySearchResults([]);
                    });
            }
            
            // Display search results
            function displaySearchResults(results) {
                if (!searchResultsList) return;
                
                if (!results || results.length === 0) {
                    searchResultsList.innerHTML = '<div class="p-3 text-center text-muted">No results found</div>';
                    searchResults.style.display = 'block';
                    return;
                }
                
                let html = '';
                results.forEach(item => {
                    let icon = 'fa-building';
                    let url = '#';
                    let typeName = 'Company';
                    
                    if (item.type === 'company') {
                        icon = 'fa-building';
                        url = `/companies/view/${item.id}`;
                        typeName = 'Company';
                    } else if (item.type === 'personnel') {
                        icon = 'fa-user';
                        url = `/personnel/view/${item.id}`;
                        typeName = 'Employee';
                    }
                    
                    html += `
                        <a href="${url}" class="list-group-item list-group-item-action border-0">
                            <div class="d-flex align-items-center">
                                <div class="me-3">
                                    <div class="p-2 rounded-circle bg-primary bg-opacity-10">
                                        <i class="fas ${icon} text-primary"></i>
                                    </div>
                                </div>
                                <div class="flex-grow-1">
                                    <h6 class="mb-0">${item.name}</h6>
                                    <small class="text-muted">${typeName}</small>
                                </div>
                            </div>
                        </a>
                    `;
                });
                
                searchResultsList.innerHTML = html;
                searchResults.style.display = 'block';
            }
        });
    </script>
    <?= $this->renderSection('scripts') ?>
</body>
</html>