<?php
// includes/header.php
// This file contains the opening HTML tags, head section, and the main navigation bar.

// Ensure session is started for access to user data.
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// *** CRITICAL: Include the database configuration file ***
require_once 'config/database.php';

// Get user data from session for dynamic navigation links
$current_username = $_SESSION['username'] ?? '';
$current_user_role = $_SESSION['user_role'] ?? 'guest'; // Default to 'guest' if not logged in
$is_logged_in = isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true;
$current_user_id = $_SESSION['user_id'] ?? 0;

// --- PHP Logic to Fetch Unread Count (Student Role Only) ---
$unread_count = 0;
// Check if $pdo is defined before attempting a database query
if ($is_logged_in && $current_user_role === 'student' && $current_user_id > 0 && isset($pdo)) {
    try {
        $stmt = $pdo->prepare("SELECT COUNT(id) AS unread_count FROM notifications WHERE user_id = :user_id AND is_read = 0");
        $stmt->execute([':user_id' => $current_user_id]);
        $unread_count = $stmt->fetchColumn();
    } catch (PDOException $e) {
        error_log("Database error in header: " . $e->getMessage());
        $unread_count = 0;
    }
}
$badge_display_class = ($unread_count > 0) ? '' : 'hidden';

// --- Centralized Navigation Links ---
$nav_links = [
    'admin' => [
        'Dashboard' => 'index.php?page=admin_dashboard',
        'Payments' => 'index.php?page=admin_verify_payments',
        'Financials' => 'index.php?page=admin_financial_dashboard',
        'Batches' => 'index.php?page=manage_batches',
        'Users' => 'index.php?page=manage_users',
    ],
    'instructor' => [
        'Dashboard' => 'index.php?page=admin_dashboard',
        'Create Course' => 'index.php?page=create_course',
        'Create Batch' => 'index.php?page=create_batch',
    ],
    'student' => [
        'Explore' => 'index.php?page=student_dashboard',
        'My Courses' => 'index.php?page=my_courses',
        'My Payments' => 'index.php?page=my_monthly_payments',
    ],
    'guest' => [
        'Home' => 'index.php?page=home',
        'Login' => 'index.php?page=login',
        
    ]
];

// Determine which links to show based on user role
$user_nav_links = $nav_links[$current_user_role] ?? $nav_links['guest'];

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ORINSTO - LMS</title>
    
    <script src="https://cdn.tailwindcss.com"></script> 
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    
    <link rel="manifest" href="/olms/manifest.json">
    
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="mobile-web-app-capable" content="yes"> 
    
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <link rel="apple-touch-icon" href="/olms/assets/icons/icon-192x192.png">

    <meta name="theme-color" content="#2563EB">
    <link rel="icon" href="/olms/favicon.ico"> 

    <script>
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', () => {
                // FIX: Setting the 'scope' explicitly to the application subdirectory for better Android compatibility
                navigator.serviceWorker.register('/olms/service-worker.js', {
                    scope: '/olms/' // Explicit scope added
                })
                .then(registration => {
                    console.log('Service Worker registered:', registration.scope);
                })
                .catch(error => {
                    console.error('Service Worker registration failed:', error);
                });
            });
        }
    </script>

    <script>
        // Variable to store the deferred prompt event
        let deferredPrompt;

        // 1. CAPTURE THE BROWSER EVENT (Fires when the browser decides the site is installable)
        window.addEventListener('beforeinstallprompt', (e) => {
            e.preventDefault();
            deferredPrompt = e;
            console.log('PWA: beforeinstallprompt event deferred.');
            // Note: If you want to show a custom button instead of an auto-popup, 
            // you'd make the button visible here.
        });

        // 2. SHOW THE PROMPT ONLY WHEN LOGGED IN AND ON THE DASHBOARD
        window.addEventListener('load', () => {
            const currentPage = new URLSearchParams(window.location.search).get('page');
            
            // PHP check ensures this only runs when a student is logged in
            <?php if ($is_logged_in && $current_user_role === 'student'): ?>
                // Check if the prompt is available and the current page is the dashboard
                if (deferredPrompt && currentPage === 'student_dashboard') {
                    console.log('PWA: Showing deferred prompt...');
                    
                    // Show the browser prompt immediately
                    deferredPrompt.prompt();
                    
                    // Wait for the user to respond
                    deferredPrompt.userChoice.then((choiceResult) => {
                        if (choiceResult.outcome === 'accepted') {
                            console.log('PWA: User accepted the install prompt.');
                        } else {
                            console.log('PWA: User dismissed the install prompt.');
                        }
                        // Clear the deferredPrompt so it doesn't show again
                        deferredPrompt = null;
                    });
                }
            <?php endif; ?>
        });

        // 3. LISTEN FOR APP INSTALLATION (Optional: For analytics or hiding custom buttons)
        window.addEventListener('appinstalled', () => {
            console.log('PWA: App was successfully installed.');
            deferredPrompt = null;
        });
    </script>
    <style>
        body { font-family: 'Inter', sans-serif; }
        /* Custom scrollbar and nav-item-hover styles */
        body::-webkit-scrollbar { width: 8px; }
        body::-webkit-scrollbar-track { background: #f1f1f1; }
        body::-webkit-scrollbar-thumb { background: #888; border-radius: 10px; }
        body::-webkit-scrollbar-thumb:hover { background: #555; }
        .nav-item-hover { transition: color 0.3s ease, background-color 0.3s ease; }
        .notification-badge { position: absolute; top: -4px; right: -8px; font-size: 0.75rem; font-weight: bold; line-height: 1; padding: 2px 6px; border-radius: 9999px; }
        /* Fix for notification icon alignment */
        .notification-container { position: relative; display: flex; align-items: center; } 
    </style>

    
</head>
<body class="bg-gray-100 min-h-screen flex flex-col">

    <nav class="bg-white shadow-md">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center h-16">
                <div class="flex-shrink-0">
                    <a href="index.php?page=home" class="text-gray-800 text-2xl font-bold tracking-wide">
                        ORINSTO <span class="text-blue-600">LMS</span>
                    </a>
                </div>

                <div class="hidden md:flex md:items-center md:space-x-8">
                    <?php if ($is_logged_in && $current_user_role === 'student'): ?>
                        <a href="index.php?page=notifications" class="text-gray-600 hover:text-blue-700 nav-item-hover notification-container flex items-center">
                            <i class="fas fa-bell text-lg"></i>
                            <span class="notification-badge bg-red-500 text-white <?php echo $badge_display_class; ?>">
                                <?php echo htmlspecialchars($unread_count); ?>
                            </span>
                        </a>
                    <?php endif; ?>

                    <?php foreach ($user_nav_links as $label => $url): ?>
                        <a href="<?php echo htmlspecialchars($url); ?>" class="text-gray-600 hover:text-blue-700 text-sm font-medium nav-item-hover">
                            <?php echo htmlspecialchars($label); ?>
                        </a>
                    <?php endforeach; ?>
                </div>

                <div class="hidden md:flex md:items-center">
                    <?php if ($is_logged_in): ?>
                        <div class="relative group">
                            <button class="flex items-center text-gray-700 hover:text-gray-900 transition-colors duration-200">
                                <span class="font-semibold mr-2 hidden lg:inline-block"><?php echo htmlspecialchars($current_username); ?></span>
                                <i class="fas fa-user-circle text-2xl"></i>
                            </button>
                            <div class="absolute right-0 mt-2 w-48 bg-white border border-gray-200 rounded-md shadow-lg py-1 opacity-0 group-hover:opacity-100 invisible group-hover:visible transition-all duration-300 transform scale-95 group-hover:scale-100 z-10">
                                <a href="index.php?page=student_profile" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">My Profile</a>
                                <div class="border-t border-gray-100"></div>
                                <a href="index.php?page=logout" class="block px-4 py-2 text-sm text-red-500 hover:bg-gray-100">Logout</a>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>

                <div class="-mr-2 flex md:hidden">
                    <button type="button" class="inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-gray-600 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-blue-500" aria-controls="mobile-menu" aria-expanded="false" onclick="document.getElementById('mobile-menu').classList.toggle('hidden');">
                        <span class="sr-only">Open main menu</span>
                        <svg class="block h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" /></svg>
                        <svg class="hidden h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" /></svg>
                    </button>
                </div>
            </div>
        </div>

        <div class="md:hidden hidden bg-white shadow-lg" id="mobile-menu">
            <div class="px-2 pt-2 pb-3 space-y-1 sm:px-3">
                <?php if ($is_logged_in && $current_user_role === 'student'): ?>
                    <a href="index.php?page=notifications" class="text-gray-600 hover:bg-gray-100 block px-3 py-2 rounded-md text-base font-medium">
                        Notifications
                        <?php if ($unread_count > 0): ?>
                            <span class="bg-red-500 text-white text-xs font-bold px-2 py-1 rounded-full ml-2"><?php echo htmlspecialchars($unread_count); ?> New</span>
                        <?php endif; ?>
                    </a>
                <?php endif; ?>
                <?php foreach ($user_nav_links as $label => $url): ?>
                    <a href="<?php echo htmlspecialchars($url); ?>" class="text-gray-600 hover:bg-gray-100 block px-3 py-2 rounded-md text-base font-medium">
                        <?php echo htmlspecialchars($label); ?>
                    </a>
                <?php endforeach; ?>
                <?php if ($is_logged_in): ?>
                    <a href="index.php?page=logout" class="bg-red-500 text-white hover:bg-red-600 block px-3 py-2 rounded-md text-base font-medium mt-1">Logout</a>
                <?php endif; ?>
            </div>
        </div>
    </nav>
    <main class="flex-grow container mx-auto px-4 py-8">