<?php
/**
 * ============================================================================
 * includes/header.php (Bootstrap-Based PWA Header)
 * ============================================================================
 */
?>
<!-- Top Navigation Bar -->
<nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm sticky-top">
    <div class="container-fluid">
        <!-- Brand Logo -->
        <a class="navbar-brand d-flex align-items-center" href="<?php echo APP_URL; ?>/dashboard/">
            <span class="fs-3 me-2">🌾</span>
            <div>
                <span class="fw-bold text-success">AIMS</span>
                <small class="d-none d-sm-block text-muted" style="font-size: 0.65rem; margin-top: -4px;">Agricultural Info System</small>
            </div>
        </a>
        
        <!-- Mobile-Only Actions (No Hamburger) -->
        <div class="d-flex d-lg-none align-items-center gap-2">
            <!-- AI Assistant -->
            <a href="<?php echo APP_URL; ?>/ai-assistant/" class="btn btn-sm btn-light rounded-3 p-2 mobile-icon">
                <i class="bi bi-robot fs-5 text-primary"></i>
            </a>
            
            <!-- Messages -->
            <a href="<?php echo APP_URL; ?>/chat/" class="btn btn-sm btn-light rounded-3 p-2 position-relative mobile-icon">
                <i class="bi bi-chat-dots fs-5"></i>
                <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-primary" 
                      id="messagesBadgeMobile" style="display: none; font-size: 0.6rem;">0</span>
            </a>
            
            <!-- Notifications Dropdown -->
            <div class="dropdown">
                <button class="btn btn-sm btn-light rounded-3 p-2 position-relative mobile-icon" 
                        type="button" id="notifDropdownMobile" data-bs-toggle="dropdown">
                    <i class="bi bi-bell fs-5"></i>
                    <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" 
                          id="notifBadgeMobile" style="display: none; font-size: 0.6rem;">0</span>
                </button>
                <ul class="dropdown-menu dropdown-menu-end shadow-lg border-0 rounded-3" 
                    style="width: 92vw; max-width: 320px; max-height: 70vh; overflow-y: auto;">
                    <li class="px-3 py-3 bg-light">
                        <div class="d-flex justify-content-between align-items-center">
                            <h6 class="mb-0 fw-bold">
                                <i class="bi bi-bell-fill me-2 text-primary"></i>Notifications
                            </h6>
                            <button class="btn btn-sm btn-outline-secondary border-0" onclick="markAllAsRead()">
                                <i class="bi bi-check-all"></i>
                            </button>
                        </div>
                    </li>
                    <li><hr class="dropdown-divider m-0"></li>
                    <li id="notifListMobile">
                        <div class="text-center py-4 text-muted">
                            <div class="spinner-border spinner-border-sm text-success"></div>
                            <p class="mb-0 mt-2 small">Loading...</p>
                        </div>
                    </li>
                </ul>
            </div>
            
            <!-- Profile Dropdown -->
            <div class="dropdown">
                <button class="btn btn-sm btn-light rounded-3 p-1 mobile-icon border-0" 
                        type="button" id="userDropdownMobile" data-bs-toggle="dropdown">
                    <img src="<?php echo getAvatarUrl($_SESSION['profile_picture'] ?? null); ?>" 
                         alt="Profile" class="rounded-2" width="32" height="32" style="object-fit: cover;">
                </button>
                <ul class="dropdown-menu dropdown-menu-end shadow-lg border-0 rounded-3" 
                    style="width: 92vw; max-width: 280px;">
                    <li class="px-3 py-3 bg-light">
                        <div class="d-flex align-items-center">
                            <img src="<?php echo getAvatarUrl($_SESSION['profile_picture'] ?? null); ?>" 
                                 alt="Profile" class="rounded-circle me-3" width="48" height="48">
                            <div>
                                <div class="fw-bold"><?php echo getUserName(); ?></div>
                                <small class="text-muted"><?php echo getUserEmail(); ?></small>
                            </div>
                        </div>
                    </li>
                    <li><hr class="dropdown-divider m-0"></li>
                    <li>
                        <a class="dropdown-item py-3" href="<?php echo APP_URL; ?>/profile/">
                            <i class="bi bi-person text-primary me-3 fs-5"></i> My Profile
                        </a>
                    </li>
                    <li>
                        <a class="dropdown-item py-3" href="<?php echo APP_URL; ?>/profile/settings.php">
                            <i class="bi bi-gear text-secondary me-3 fs-5"></i> Settings
                        </a>
                    </li>
                    <?php if (getUserType() === 'admin'): ?>
                    <li><hr class="dropdown-divider"></li>
                    <li>
                        <a class="dropdown-item py-3" href="<?php echo APP_URL; ?>/admin/">
                            <i class="bi bi-shield-lock text-warning me-3 fs-5"></i> Admin Panel
                        </a>
                    </li>
                    <?php endif; ?>
                    <li><hr class="dropdown-divider"></li>
                    <li>
                        <a class="dropdown-item py-3 text-danger" href="#" onclick="logout(); return false;">
                            <i class="bi bi-box-arrow-right me-3 fs-5"></i> Logout
                        </a>
                    </li>
                </ul>
            </div>
        </div>
        
        <!-- Desktop Navigation -->
        <button class="navbar-toggler d-none" type="button" data-bs-toggle="collapse" data-bs-target="#navbarMain">
            <span class="navbar-toggler-icon"></span>
        </button>
        
        <div class="collapse navbar-collapse d-none d-lg-block" id="navbarMain">
            <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                <li class="nav-item">
                    <a class="nav-link" href="<?php echo APP_URL; ?>/dashboard/">
                        <i class="bi bi-speedometer2 me-1"></i> Dashboard
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="<?php echo APP_URL; ?>/marketplace/">
                        <i class="bi bi-shop me-1"></i> Marketplace
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="<?php echo APP_URL; ?>/prices/">
                        <i class="bi bi-graph-up me-1"></i> Prices
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="<?php echo APP_URL; ?>/posts/">
                        <i class="bi bi-people me-1"></i> Community
                    </a>
                </li>
                <?php if (getUserType() === 'farmer'): ?>
                <li class="nav-item">
                    <a class="nav-link" href="<?php echo APP_URL; ?>/farm/">
                        <i class="bi bi-tree me-1"></i> My Farm
                    </a>
                </li>
                <?php endif; ?>
            </ul>
            
            <ul class="navbar-nav">
                <!-- AIM AI Assistant -->
                <li class="nav-item">
                    <a class="nav-link" href="<?php echo APP_URL; ?>/ai-assistant/" title="AIM AI Assistant">
                        <i class="bi bi-robot fs-5 text-primary"></i>
                        <span class="d-none d-xl-inline ms-1">AIM AI</span>
                    </a>
                </li>
                
                <!-- Messages/Chat -->
                <li class="nav-item">
                    <a class="nav-link position-relative" href="<?php echo APP_URL; ?>/chat/" title="Messages">
                        <i class="bi bi-chat-dots fs-5"></i>
                        <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-primary" 
                              id="messagesBadge" style="display: none; font-size: 0.65rem;">0</span>
                    </a>
                </li>
                
                <!-- Notifications Dropdown -->
                <li class="nav-item dropdown">
                    <a class="nav-link position-relative" href="#" id="notificationsDropdown" 
                       role="button" data-bs-toggle="dropdown" aria-expanded="false" title="Notifications">
                        <i class="bi bi-bell fs-5"></i>
                        <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" 
                              id="notificationsBadge" style="display: none; font-size: 0.65rem;">0</span>
                    </a>
                    <ul class="dropdown-menu dropdown-menu-end shadow-lg border-0 rounded-3" 
                        style="width: 350px; max-height: 400px; overflow-y: auto;">
                        <li>
                            <h6 class="dropdown-header d-flex justify-content-between align-items-center">
                                <span><i class="bi bi-bell me-2"></i>Notifications</span>
                                <button class="btn btn-sm btn-link text-decoration-none p-0" 
                                        onclick="markAllAsRead()" style="font-size: 0.75rem;">
                                    <i class="bi bi-check-all"></i>
                                </button>
                            </h6>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        <li id="notificationsList">
                            <div class="text-center py-3 text-muted">
                                <div class="spinner-border spinner-border-sm"></div>
                                <p class="mb-0 mt-2 small">Loading notifications...</p>
                            </div>
                        </li>
                    </ul>
                </li>
                
                <!-- User Profile Dropdown -->
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle d-flex align-items-center" href="#" 
                       id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                        <img src="<?php echo getAvatarUrl($_SESSION['profile_picture'] ?? null); ?>" 
                             alt="Profile" class="rounded-circle me-2" width="35" height="35">
                        <span class="d-none d-lg-inline"><?php echo getUserName(); ?></span>
                    </a>
                    <ul class="dropdown-menu dropdown-menu-end shadow-lg border-0 rounded-3">
                        <li>
                            <a class="dropdown-item" href="<?php echo APP_URL; ?>/profile/">
                                <i class="bi bi-person me-2"></i> My Profile
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item" href="<?php echo APP_URL; ?>/profile/settings.php">
                                <i class="bi bi-gear me-2"></i> Settings
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        <?php if (getUserType() === 'admin'): ?>
                        <li>
                            <a class="dropdown-item" href="<?php echo APP_URL; ?>/admin/">
                                <i class="bi bi-shield-lock me-2"></i> Admin Panel
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        <?php endif; ?>
                        <li>
                            <a class="dropdown-item text-danger" href="#" onclick="logout(); return false;">
                                <i class="bi bi-box-arrow-right me-2"></i> Logout
                            </a>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>

<style>
/* Minimal Bootstrap Enhancement CSS */

/* Navbar border */
.navbar {
    border-bottom: 1px solid rgba(0,0,0,0.05);
}

/* Mobile icon buttons - using Bootstrap btn classes */
.mobile-icon {
    width: 40px;
    height: 40px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    transition: transform 0.2s ease;
}

.mobile-icon:active {
    transform: scale(0.92);
}

/* Desktop nav link enhancements */
@media (min-width: 992px) {
    .navbar-nav .nav-link {
        font-weight: 500;
        padding: 0.5rem 1rem;
        border-radius: 0.5rem;
        transition: all 0.2s ease;
        margin: 0 0.125rem;
    }

    .navbar-nav .nav-link:hover {
        background-color: rgba(5, 150, 105, 0.1);
        color: var(--primary-color) !important;
    }

    .navbar-nav .nav-link.active {
        background-color: rgba(5, 150, 105, 0.15);
        color: var(--primary-color) !important;
    }

    .navbar-nav .nav-link.active::after {
        content: '';
        position: absolute;
        bottom: -12px;
        left: 50%;
        transform: translateX(-50%);
        width: 30px;
        height: 3px;
        background: var(--success-color);
        border-radius: 2px;
    }

    /* Profile image hover */
    .navbar-nav .dropdown-toggle img {
        border: 2px solid #e5e7eb;
        transition: all 0.2s ease;
        object-fit: cover;
    }

    .navbar-nav .dropdown-toggle:hover img {
        border-color: var(--primary-color);
        transform: scale(1.05);
    }

    /* Desktop dropdown items */
    .dropdown-item {
        border-radius: 0.5rem;
        padding: 0.65rem 1rem;
        transition: all 0.2s ease;
        font-weight: 500;
    }

    .dropdown-item:hover {
        background-color: rgba(59, 130, 246, 0.1);
        color: var(--info-color);
        transform: translateX(4px);
    }

    .dropdown-item.text-danger:hover {
        background-color: rgba(239, 68, 68, 0.1);
    }

    .dropdown-header {
        font-weight: 700;
        padding: 0.75rem 1rem;
        background-color: #f9fafb;
        border-radius: 0.5rem 0.5rem 0 0;
    }
}

/* Badge animation */
.badge {
    animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {
    0%, 100% { transform: scale(1); }
    50% { transform: scale(1.1); }
}

/* Scrolled state */
.navbar.scrolled {
    box-shadow: 0 4px 12px rgba(0,0,0,0.1) !important;
}

/* PWA - Safe area support */
@supports (padding: env(safe-area-inset-top)) {
    .navbar {
        padding-top: calc(0.5rem + env(safe-area-inset-top));
    }
}

/* Touch feedback - prevent tap highlight */
@media (max-width: 991.98px) {
    .navbar * {
        -webkit-tap-highlight-color: transparent;
    }
}

/* Smooth scrollbar */
.dropdown-menu {
    scrollbar-width: thin;
}

.dropdown-menu::-webkit-scrollbar {
    width: 4px;
}

.dropdown-menu::-webkit-scrollbar-track {
    background: #f3f4f6;
}

.dropdown-menu::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 2px;
}
</style>

<script>
// Bootstrap-based JavaScript
document.addEventListener('DOMContentLoaded', function() {
    // Navbar scroll effect
    const navbar = document.querySelector('.navbar');
    
    window.addEventListener('scroll', function() {
        if (window.pageYOffset > 20) {
            navbar.classList.add('scrolled');
        } else {
            navbar.classList.remove('scrolled');
        }
    }, { passive: true });
    
    // Set active nav link (desktop only)
    const currentPath = window.location.pathname;
    document.querySelectorAll('.navbar-nav .nav-link:not([data-bs-toggle])').forEach(link => {
        const href = link.getAttribute('href');
        if (href && currentPath.includes(href.split('/').filter(Boolean).pop())) {
            link.classList.add('active');
        }
    });
    
    // Initialize Bootstrap tooltips (desktop only)
    if (window.innerWidth >= 992) {
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[title]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }
    
    // Sync mobile and desktop badges
    function syncBadges() {
        // Messages
        const deskMsg = document.getElementById('messagesBadge');
        const mobMsg = document.getElementById('messagesBadgeMobile');
        if (deskMsg && mobMsg) {
            mobMsg.textContent = deskMsg.textContent;
            mobMsg.style.display = deskMsg.style.display;
        }
        
        // Notifications
        const deskNotif = document.getElementById('notificationsBadge');
        const mobNotif = document.getElementById('notifBadgeMobile');
        if (deskNotif && mobNotif) {
            mobNotif.textContent = deskNotif.textContent;
            mobNotif.style.display = deskNotif.style.display;
        }
        
        // Lists
        const deskList = document.getElementById('notificationsList');
        const mobList = document.getElementById('notifListMobile');
        if (deskList && mobList) {
            mobList.innerHTML = deskList.innerHTML;
        }
    }
    
    // Observe badge changes
    const observer = new MutationObserver(syncBadges);
    
    ['notificationsList', 'messagesBadge', 'notificationsBadge'].forEach(id => {
        const el = document.getElementById(id);
        if (el) {
            observer.observe(el, { attributes: true, childList: true, subtree: true });
        }
    });
    
    // Initial sync
    setTimeout(syncBadges, 500);
});

// Function to mark all notifications as read
function markAllAsRead() {
    $.ajax({
        url: '<?php echo APP_URL; ?>/ajax/mark-all-notifications-read.php',
        type: 'POST',
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                loadNotifications();
                showToast('All notifications marked as read', 'success');
            }
        },
        error: function() {
            showToast('Failed to mark notifications as read', 'error');
        }
    });
}
</script>