<?php
/**
 * ============================================================================
 * includes/header.php (App-Like PWA Header - Mobile Optimized)
 * ============================================================================
 */
?>

<!-- App-Like 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 class="d-none d-sm-flex flex-column">
                <span class="fw-bold text-success">AIMS</span>
                <small class="text-muted" style="font-size: 0.65rem; margin-top: -4px;">Agricultural Info System</small>
            </div>
            <span class="d-sm-none fw-bold text-success">AIMS</span>
        </a>
        
        <!-- Mobile Icons Only (No Hamburger Menu) -->
        <div class="d-lg-none d-flex align-items-center gap-2">
            <!-- AI Assistant - Mobile -->
            <a class="mobile-icon-btn ai-btn" href="<?php echo APP_URL; ?>/ai-assistant/">
                <i class="bi bi-robot"></i>
            </a>
            
            <!-- Messages - Mobile -->
            <a class="mobile-icon-btn position-relative" href="<?php echo APP_URL; ?>/chat/">
                <i class="bi bi-chat-dots"></i>
                <span class="mobile-badge bg-primary" id="messagesBadgeMobile" style="display: none;">0</span>
            </a>
            
            <!-- Notifications - Mobile -->
            <div class="dropdown">
                <button class="mobile-icon-btn position-relative" type="button" id="notificationsDropdownMobile" 
                        data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="bi bi-bell"></i>
                    <span class="mobile-badge bg-danger" id="notificationsBadgeMobile" style="display: none;">0</span>
                </button>
                <ul class="dropdown-menu dropdown-menu-end mobile-dropdown" 
                    aria-labelledby="notificationsDropdownMobile">
                    <li>
                        <div class="dropdown-header d-flex justify-content-between align-items-center py-3 px-3 bg-light">
                            <h6 class="mb-0 fw-bold fs-6">
                                <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="notificationsListMobile">
                        <div class="text-center py-4 text-muted">
                            <div class="spinner-border spinner-border-sm text-success" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mb-0 mt-2 small">Loading...</p>
                        </div>
                    </li>
                </ul>
            </div>
            
            <!-- User Profile - Mobile -->
            <div class="dropdown">
                <button class="mobile-profile-btn dropdown-toggle" type="button" id="userDropdownMobile" 
                        data-bs-toggle="dropdown" aria-expanded="false">
                    <img src="<?php echo getAvatarUrl($_SESSION['profile_picture'] ?? null); ?>" 
                         alt="Profile">
                </button>
                <ul class="dropdown-menu dropdown-menu-end mobile-dropdown" aria-labelledby="userDropdownMobile">
                    <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 (Hidden on Mobile - No Hamburger) -->
        <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" style="width: 350px; max-height: 400px; overflow-y: auto;" 
                        aria-labelledby="notificationsDropdown">
                        <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;"
                                        title="Mark all as read">
                                    <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" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </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" aria-labelledby="userDropdown">
                        <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>

<!-- Mobile Bottom Navigation -->
<nav class="mobile-nav d-lg-none">
    <a href="<?php echo APP_URL; ?>/dashboard/" class="mobile-nav-item" data-page="dashboard">
        <i class="bi bi-house-door"></i>
        <span>Home</span>
    </a>
    <a href="<?php echo APP_URL; ?>/marketplace/" class="mobile-nav-item" data-page="marketplace">
        <i class="bi bi-shop"></i>
        <span>Market</span>
    </a>
    <a href="<?php echo APP_URL; ?>/posts/" class="mobile-nav-item" data-page="community">
        <i class="bi bi-people"></i>
        <span>Community</span>
    </a>
    <a href="<?php echo APP_URL; ?>/chat/" class="mobile-nav-item" data-page="chat">
        <i class="bi bi-chat-dots"></i>
        <span>Chat</span>
        <span class="badge" id="mobileMessagesBadge" style="display: none;">0</span>
    </a>
    <a href="<?php echo APP_URL; ?>/ai-assistant/" class="mobile-nav-item ai" data-page="ai">
        <i class="bi bi-robot"></i>
        <span>AI</span>
    </a>
</nav>

<!-- Mobile Nav Spacer -->
<div class="mobile-nav-spacer d-lg-none"></div>

<style>
/* ===================================
   APP-LIKE PWA HEADER STYLES
   =================================== */

/* Navbar base */
.navbar {
    padding-top: 0.5rem;
    padding-bottom: 0.5rem;
    border-bottom: 1px solid rgba(0,0,0,0.05);
    -webkit-user-select: none;
    user-select: none;
}

/* Brand on mobile - compact */
.navbar-brand {
    font-size: 1.5rem;
    transition: transform 0.2s ease;
    padding: 0;
}

.navbar-brand:active {
    transform: scale(0.95);
}

/* ===================================
   MOBILE ICON BUTTONS (App-like)
   =================================== */

.mobile-icon-btn {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f3f4f6;
    border: none;
    border-radius: 10px;
    color: #6b7280;
    font-size: 18px;
    transition: all 0.2s ease;
    position: relative;
    text-decoration: none;
}

.mobile-icon-btn:active {
    transform: scale(0.92);
    background: #e5e7eb;
}

.mobile-icon-btn.ai-btn {
    background: rgba(99, 102, 241, 0.1);
    color: #6366f1;
}

.mobile-icon-btn.ai-btn:active {
    background: rgba(99, 102, 241, 0.2);
}

/* Mobile badges */
.mobile-badge {
    position: absolute;
    top: -4px;
    right: -4px;
    min-width: 16px;
    height: 16px;
    padding: 0 4px;
    border-radius: 8px;
    font-size: 10px;
    font-weight: 700;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2px solid white;
}

/* Mobile profile button */
.mobile-profile-btn {
    width: 40px;
    height: 40px;
    padding: 0;
    background: none;
    border: none;
    transition: all 0.2s ease;
}

.mobile-profile-btn img {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    border: 2px solid #e5e7eb;
    object-fit: cover;
}

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

.mobile-profile-btn:active img {
    border-color: var(--primary-color);
}

/* Hide dropdown arrow on mobile profile */
.mobile-profile-btn.dropdown-toggle::after {
    display: none;
}

/* ===================================
   MOBILE DROPDOWN MENUS (App-like)
   =================================== */

.mobile-dropdown {
    border: none;
    box-shadow: 0 10px 40px rgba(0,0,0,0.15);
    border-radius: 16px;
    padding: 0;
    margin-top: 0.5rem !important;
    max-width: 320px;
    width: 92vw;
    max-height: 70vh;
    overflow-y: auto;
}

.mobile-dropdown .dropdown-item {
    border-radius: 0;
    padding: 0.75rem 1rem;
    transition: background-color 0.2s ease;
    font-weight: 500;
    font-size: 15px;
}

.mobile-dropdown .dropdown-item:active {
    background-color: rgba(59, 130, 246, 0.15);
}

.mobile-dropdown .dropdown-item.text-danger:active {
    background-color: rgba(239, 68, 68, 0.15);
}

/* ===================================
   DESKTOP NAVIGATION STYLES
   =================================== */

@media (min-width: 992px) {
    .navbar {
        padding-top: 0.75rem;
        padding-bottom: 0.75rem;
    }
    
    /* Navigation links */
    .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 i {
        font-size: 1.1rem;
    }

    /* Profile image */
    .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 dropdowns */
    .dropdown-menu:not(.mobile-dropdown) {
        border: none;
        box-shadow: 0 10px 30px rgba(0,0,0,0.15);
        border-radius: 0.75rem;
        padding: 0.5rem;
        margin-top: 0.5rem !important;
    }

    .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;
        margin-bottom: 0.5rem;
    }

    .dropdown-divider {
        margin: 0.5rem 0;
        opacity: 0.1;
    }

    /* Active page indicator */
    .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;
    }
}

/* Badge animation */
.badge, .mobile-badge {
    font-weight: 700;
    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 2px 8px rgba(0,0,0,0.1) !important;
}

/* ===================================
   PWA OPTIMIZATIONS
   =================================== */

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

/* Touch feedback */
@media (hover: none) and (pointer: coarse) {
    .mobile-icon-btn:active,
    .mobile-profile-btn:active {
        opacity: 0.7;
    }
}

/* Prevent text selection on mobile */
@media (max-width: 991.98px) {
    .navbar * {
        -webkit-tap-highlight-color: transparent;
    }
}

/* Smooth scrollbar for mobile dropdowns */
.mobile-dropdown::-webkit-scrollbar {
    width: 4px;
}

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

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

<script>
// Enhanced JavaScript - PWA Optimized
document.addEventListener('DOMContentLoaded', function() {
    // Navbar scroll effect
    const navbar = document.querySelector('.navbar');
    let lastScroll = 0;
    
    window.addEventListener('scroll', function() {
        const currentScroll = window.pageYOffset;
        
        if (currentScroll > 20) {
            navbar.classList.add('scrolled');
        } else {
            navbar.classList.remove('scrolled');
        }
        
        lastScroll = currentScroll;
    }, { 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 => {
        if (link.getAttribute('href') && currentPath.includes(link.getAttribute('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 badges
        const desktopMsgBadge = document.getElementById('messagesBadge');
        const mobileMsgBadge = document.getElementById('messagesBadgeMobile');
        if (desktopMsgBadge && mobileMsgBadge) {
            mobileMsgBadge.textContent = desktopMsgBadge.textContent;
            mobileMsgBadge.style.display = desktopMsgBadge.style.display;
        }
        
        // Notification badges
        const desktopNotifBadge = document.getElementById('notificationsBadge');
        const mobileNotifBadge = document.getElementById('notificationsBadgeMobile');
        if (desktopNotifBadge && mobileNotifBadge) {
            mobileNotifBadge.textContent = desktopNotifBadge.textContent;
            mobileNotifBadge.style.display = desktopNotifBadge.style.display;
        }
        
        // Sync notification lists
        const desktopList = document.getElementById('notificationsList');
        const mobileList = document.getElementById('notificationsListMobile');
        if (desktopList && mobileList) {
            mobileList.innerHTML = desktopList.innerHTML;
        }
    }
    
    // Sync badges when notifications load
    const observer = new MutationObserver(syncBadges);
    const notificationsList = document.getElementById('notificationsList');
    if (notificationsList) {
        observer.observe(notificationsList, { childList: true, subtree: true });
    }
    
    // Also sync on badge changes
    const messagesBadge = document.getElementById('messagesBadge');
    if (messagesBadge) {
        observer.observe(messagesBadge, { attributes: true, childList: true });
    }
    
    const notifBadge = document.getElementById('notificationsBadge');
    if (notifBadge) {
        observer.observe(notifBadge, { attributes: true, childList: 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>