<?php
// This file assumes config.php and helpers.php are included before it.

// Define constants and session variables for demonstration purposes if not set
if (!defined('APP_NAME')) {
    define('APP_NAME', 'Class Key App');
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    // Mock Session data for demonstration (Only if not already set)
    if (!isset($_SESSION['user_name'])) {
        $_SESSION['user_name'] = 'Demo User';
        $_SESSION['profile_image_url'] = 'https://placehold.co/40x40/6366f1/ffffff?text=DU';
        $_SESSION['user_role'] = 'admin'; 
    }
}

// NEW: Helper function to check feature status from DB
function is_feature_active($featureKey) {
    global $conn; // Assumes $conn is your DB connection from config.php
    
    // If no DB connection, return false (fail safe)
    if (!isset($conn) || !($conn instanceof mysqli)) {
        return false; 
    }

    $stmt = $conn->prepare("SELECT is_active FROM system_features WHERE feature_key = ? LIMIT 1");
    $stmt->bind_param("s", $featureKey);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_assoc()) {
        return (bool)$row['is_active'];
    }
    return false;
}

// Helper function to define menus for both roles
function get_menu_items($userRole) {
    if ($userRole === 'admin') {
        return [
            'Dashboard' => ['url' => 'dashboard.php', 'icon' => 'fa-solid fa-chart-line', 'color' => 'icon-color-1'],
            'Lesson Packs' => ['url' => 'addpack.php', 'icon' => 'fa-solid fa-box-open', 'color' => 'icon-color-2'],
            'Add Lessons' => ['url' => 'addclass.php', 'icon' => 'fa-solid fa-book', 'color' => 'icon-color-3'],
            'Add Quizzes' => ['url' => 'addquiz.php', 'icon' => 'fa-solid fa-question', 'color' => 'icon-color-6'],
            'Add Notice' => ['url' => 'addnotice.php', 'icon' => 'fa-solid fa-bullhorn', 'color' => 'icon-color-4'],
            'User Management' => ['url' => 'usermanage.php', 'icon' => 'fa-solid fa-users', 'color' => 'icon-color-5'],
            'Slip Requests' => ['url' => 'sliprequests.php', 'icon' => 'fa-solid fa-receipt', 'color' => 'icon-color-default'],
            // NEW: Admin Feature Control
            'Features' => ['url' => 'admin_features.php', 'icon' => 'fa-solid fa-wand-magic-sparkles', 'color' => 'icon-color-1'],
        ];
    } else {
        // Student menu structure
        return [
            'Dashboard' => ['url' => 'studentdash.php', 'icon' => 'fa-solid fa-home', 'color' => 'icon-color-1'],
            'My Classes' => ['url' => 'myclass.php', 'icon' => 'fa-solid fa-book', 'color' => 'icon-color-2'],
            'Take Quiz' => ['url' => 'studentquiz.php', 'icon' => 'fa-solid fa-pen-to-square', 'color' => 'icon-color-4'],
            'Notices' => ['url' => 'notices.php', 'icon' => 'fa-solid fa-bell', 'color' => 'icon-color-3'],
            'Buy Classes' => ['url' => 'buyclass.php', 'icon' => 'fa-solid fa-store', 'color' => 'icon-color-5'],
            'Profile' => ['url' => 'profile.php', 'icon' => 'fa-solid fa-user-circle', 'color' => 'icon-color-default'],
        ];
    }
}

function render_header($title) {
    // Check for active features
    $isXmas = is_feature_active('xmas_mode');
    $isVesak = is_feature_active('vesak_mode');

    // Load Tailwind CSS CDN and required font
    $html = '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>' . htmlspecialchars($title) . ' | ' . APP_NAME . '</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { font-family: "Inter", sans-serif; background-color: #f4f7f9; }

        /* Custom styles for desktop Floating Sidebar */
        .super-shadow { box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1); }

        /* Desktop Sidebar */
        .floating-sidebar {
            position: fixed; top: 20px; left: 20px;
            height: calc(100vh - 40px); width: 80px;
            border-radius: 1.5rem; z-index: 30;
            padding: 1.25rem 0; transition: all 0.3s ease;
        }

        /* Mobile Navbar */
        .mobile-navbar {
            position: fixed; bottom: 0; left: 0; right: 0;
            height: 80px; z-index: 50;
            border-top-left-radius: 2.5rem; border-top-right-radius: 2.5rem;
            box-shadow: 0 -8px 25px rgba(0, 0, 0, 0.2);
        }

        /* Tooltips */
        .sidebar-link { position: relative; }
        .sidebar-link .tooltip-label {
            position: absolute; right: -10px; top: 50%;
            transform: translate(100%, -50%);
            background-color: #1f2937; color: #ffffff;
            padding: 0.5rem 0.75rem; border-radius: 0.5rem;
            white-space: nowrap; opacity: 0; pointer-events: none;
            transition: opacity 0.3s, transform 0.3s;
            z-index: 90; font-size: 0.875rem;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
        }
        .sidebar-link:hover .tooltip-label { opacity: 1; transform: translate(115%, -50%); }
        .sidebar-link .tooltip-label::before {
            content: ""; position: absolute; left: 0; top: 50%;
            width: 0; height: 0; border: 6px solid transparent;
            border-right-color: #1f2937; transform: translate(-100%, -50%);
        }

        /* More Menu Overlay */
        .more-menu-overlay {
            position: fixed; top: 0; left: 0; right: 0; bottom: 0;
            background-color: rgba(0, 0, 0, 0.7); z-index: 60;
            display: none; backdrop-filter: blur(5px);
        }
        .more-menu-content {
            position: absolute; bottom: 0; left: 0; right: 0;
            border-top-left-radius: 2rem; border-top-right-radius: 2rem;
            max-height: 85vh; overflow-y: auto;
            transform: translateY(100%); transition: transform 0.3s ease-out;
        }
        .more-menu-overlay.active { display: block; }
        .more-menu-overlay.active .more-menu-content { transform: translateY(0); }

        .active-gradient { background-image: linear-gradient(to bottom right, #6366f1, #9333ea); }
        .active-icon-shadow { box-shadow: 0 5px 15px rgba(99, 102, 241, 0.5); }

        /* Icon Gradients */
        .icon-color-1 { background-image: linear-gradient(to right, #6366f1, #3b82f6); }
        .icon-color-2 { background-image: linear-gradient(to right, #10b981, #059669); }
        .icon-color-3 { background-image: linear-gradient(to right, #f59e0b, #d97706); }
        .icon-color-4 { background-image: linear-gradient(to right, #f43f5e, #e11d48); }
        .icon-color-5 { background-image: linear-gradient(to right, #8b5cf6, #7c3aed); }
        .icon-color-6 { background-image: linear-gradient(to right, #06b6d4, #0891b2); }
        .icon-color-default { background-image: linear-gradient(to right, #fcae3c, #fccb6c); }
        ';

    // --- FEATURE SPECIFIC STYLES ---
    if ($isXmas) {
        $html .= '
        /* Xmas Snow Effect */
        .snowflake {
            position: fixed; top: 0; z-index: 9999;
            color: #fff; font-size: 1em; opacity: 0.8;
            pointer-events: none; animation: fall linear infinite;
        }
        @keyframes fall {
            0% { transform: translateY(-10vh) rotate(0deg); opacity: 1; }
            100% { transform: translateY(100vh) rotate(360deg); opacity: 0; }
        }
        /* Festive Scrollbar */
        ::-webkit-scrollbar-thumb { background: linear-gradient(to bottom, #d946ef, #ef4444); }
        ';
    }

    if ($isVesak) {
        $html .= '
        /* Vesak Lanterns */
        .lantern-string {
            position: fixed; top: 0; left: 0; width: 100%; height: 60px;
            z-index: 40; pointer-events: none;
            display: flex; justify-content: space-around;
        }
        .lantern {
            width: 30px; height: 40px; border-radius: 5px;
            background: linear-gradient(to bottom, #fca5a5, #ef4444);
            box-shadow: 0 5px 15px rgba(239, 68, 68, 0.4);
            animation: swing 3s ease-in-out infinite alternate;
            position: relative; top: -10px;
        }
        .lantern:nth-child(even) { background: linear-gradient(to bottom, #fcd34d, #f59e0b); animation-duration: 3.5s; top: -5px; }
        .lantern:nth-child(3n) { background: linear-gradient(to bottom, #67e8f9, #06b6d4); animation-duration: 4s; }
        
        @keyframes swing {
            0% { transform: rotate(-5deg); }
            100% { transform: rotate(5deg); }
        }
        .lantern::before {
            content: ""; position: absolute; top: -10px; left: 50%;
            width: 2px; height: 10px; background: #333;
        }
        ';
    }

    $html .= '
    </style>
</head>
<body class="' . ($isVesak ? 'bg-orange-50' : '') . '">'; // Vesak Background Tint

    // --- FEATURE INJECTION ---
    if ($isXmas) {
        // Javascript to generate snowflakes
        $html .= '<script>
            document.addEventListener("DOMContentLoaded", function() {
                const snowContainer = document.createElement("div");
                snowContainer.style.position = "fixed";
                snowContainer.style.top = "0";
                snowContainer.style.left = "0";
                snowContainer.style.width = "100%";
                snowContainer.style.height = "100%";
                snowContainer.style.pointerEvents = "none";
                snowContainer.style.zIndex = "9999";
                document.body.appendChild(snowContainer);

                function createSnowflake() {
                    const flake = document.createElement("div");
                    flake.innerHTML = "❄";
                    flake.classList.add("snowflake");
                    flake.style.left = Math.random() * 100 + "vw";
                    flake.style.animationDuration = Math.random() * 3 + 2 + "s";
                    flake.style.opacity = Math.random();
                    flake.style.fontSize = Math.random() * 20 + 10 + "px";
                    snowContainer.appendChild(flake);
                    setTimeout(() => { flake.remove(); }, 5000);
                }
                setInterval(createSnowflake, 100);
            });
        </script>';
    }

    if ($isVesak) {
        $html .= '
        <div class="lantern-string">
            <div class="lantern"></div>
            <div class="lantern"></div>
            <div class="lantern"></div>
            <div class="lantern"></div>
            <div class="lantern"></div>
            <div class="lantern"></div>
            <div class="lantern"></div>
            <div class="lantern"></div>
        </div>';
    }

    echo $html;
}

function render_footer() {
    echo '</body></html>';
}

function render_mobile_navbar($menu, $currentPage) {
    // Determine the visible items (e.g., first 3, leaving room for 'More')
    $visibleMenu = array_slice($menu, 0, 3, true);

    $defaultIcon = 'fa-solid fa-square';

    $mobileHtml = '<!-- Mobile Navbar (Hidden on large screens) -->
    <nav class="mobile-navbar bg-white lg:hidden flex items-center justify-around">';

    foreach ($visibleMenu as $name => $item) {
        $isActive = (basename($item['url']) === basename($currentPage));
        $icon = $item['icon'] ?? $defaultIcon;
        $colorClass = $item['color'] ?? 'icon-color-default';

        $iconBgStyle = $colorClass . ' shadow-xl';
        $iconTextClass = 'text-white';
        $linkClasses = $isActive ? 'scale-105' : 'hover:scale-[1.05]';
        $itemTextClass = $isActive ? 'text-indigo-600 font-bold' : 'text-gray-500';

        $mobileHtml .= '
            <a href="' . htmlspecialchars($item['url']) . '" class="flex flex-col items-center justify-center text-xs w-1/4 h-full transition duration-200">
                <div class="w-12 h-12 rounded-xl flex items-center justify-center ' . $iconBgStyle . ' ' . $linkClasses . ' transition duration-300">
                    <i class="' . $icon . ' text-xl ' . $iconTextClass . '"></i>
                </div>
                <span class="' . $itemTextClass . ' mt-1 truncate max-w-[80%]">' . htmlspecialchars($name) . '</span>
            </a>';
    }

    $moreColorClass = 'icon-color-4';

    $mobileHtml .= '
        <button id="open-more-menu" class="flex flex-col items-center justify-center text-xs w-1/4 h-full transition duration-200">
            <div class="w-12 h-12 rounded-xl flex items-center justify-center ' . $moreColorClass . ' shadow-xl text-white hover:scale-[1.05] transition duration-300">
                <i class="fa-solid fa-ellipsis text-xl"></i>
            </div>
            <span class="mt-1 text-gray-500 hover:text-indigo-600">More</span>
        </button>';

    $mobileHtml .= '</nav>';

    $mobileHtml .= '
    <div id="more-menu-overlay" class="more-menu-overlay">
        <div class="more-menu-content bg-white p-6 shadow-2xl">
            <h3 class="text-2xl font-bold text-gray-800 mb-6 border-b pb-3 flex justify-between items-center">
                All Menu Items
                <button id="close-more-menu" class="text-gray-400 hover:text-gray-700 transition">
                    <i class="fa-solid fa-xmark text-2xl"></i>
                </button>
            </h3>
            <div class="grid grid-cols-3 gap-4 pb-4">
    ';

    foreach ($menu as $name => $item) {
        $isActive = (basename($item['url']) === basename($currentPage));
        $icon = $item['icon'] ?? $defaultIcon;
        $colorClass = $item['color'] ?? 'icon-color-default';

        $bgStyle = $isActive ? 'active-gradient shadow-lg' : $colorClass . ' shadow-md';

        $mobileHtml .= '
            <a href="' . htmlspecialchars($item['url']) . '" class="flex flex-col items-center justify-center p-3 rounded-xl transition duration-300 shadow-sm hover:shadow-md h-28 text-white ' . $bgStyle . '">
                <i class="' . $icon . ' text-3xl mb-2"></i>
                <span class="text-sm font-medium text-center truncate w-full">' . htmlspecialchars($name) . '</span>
            </a>';
    }

    $mobileHtml .= '
            </div>
            <div class="pt-4 border-t mt-4">
                <a href="index.php?logout=true"
                    class="w-full flex items-center justify-center py-3 px-4 rounded-xl bg-red-500 text-white font-bold transition duration-300 hover:bg-red-600 shadow-lg">
                    <i class="fa-solid fa-arrow-left mr-2 transform -scale-x-100"></i> Logout
                </a>
            </div>
        </div>
    </div>';

    $mobileHtml .= '<script>
        document.addEventListener(\'DOMContentLoaded\', () => {
            const openBtn = document.getElementById(\'open-more-menu\');
            const closeBtn = document.getElementById(\'close-more-menu\');
            const overlay = document.getElementById(\'more-menu-overlay\');

            if (openBtn && closeBtn && overlay) {
                const toggleMenu = (open) => {
                    if (open) {
                        overlay.style.display = \'block\';
                        setTimeout(() => overlay.classList.add(\'active\'), 10);
                        document.body.style.overflow = \'hidden\';
                    } else {
                        overlay.classList.remove(\'active\');
                        setTimeout(() => {
                            overlay.style.display = \'none\';
                            document.body.style.overflow = \'auto\';
                        }, 300);
                    }
                };

                openBtn.addEventListener(\'click\', () => toggleMenu(true));
                closeBtn.addEventListener(\'click\', () => toggleMenu(false));
                overlay.addEventListener(\'click\', (e) => {
                    if (e.target === overlay) {
                        toggleMenu(false);
                    }
                });
                overlay.style.display = \'none\';
            }
        });
    </script>';

    echo $mobileHtml;
}


function render_sidebar($userRole, $currentPage) {
    $menu = get_menu_items($userRole);
    $defaultIcon = 'fa-solid fa-square';

    $sidebarHtml = '<div class="flex h-screen bg-gray-50">';
    $sidebarHtml .= '<!-- Floating Sidebar (Desktop Only) -->
        <aside class="floating-sidebar bg-white super-shadow flex-col justify-between z-30 hidden lg:flex">
            <!-- Navigation Icons -->
            <nav class="space-y-4">';

    foreach ($menu as $name => $item) {
        $isActive = (basename($item['url']) === basename($currentPage));
        $icon = $item['icon'] ?? $defaultIcon;
        $colorClass = $item['color'] ?? 'icon-color-default';

        if ($isActive) {
            $iconBgStyle = 'active-gradient active-icon-shadow';
            $iconTextClass = 'text-white';
            $linkClasses = 'transform scale-105';
        } else {
            $iconBgStyle = $colorClass . ' shadow-md';
            $iconTextClass = 'text-white';
            $linkClasses = '';
        }

        $sidebarHtml .= '
            <a href="' . htmlspecialchars($item['url']) . '"
                class="sidebar-link flex items-center justify-center w-full transition duration-300 ' . $linkClasses . '">
                   <div class="w-14 h-14 rounded-xl flex items-center justify-center ' . $iconBgStyle . '">
                       <i class="' . $icon . ' text-2xl ' . $iconTextClass . '"></i>
                   </div>
                   <span class="tooltip-label">' . htmlspecialchars($name) . '</span>
            </a>';
    }

    $sidebarHtml .= '
            </nav>
            <div class="flex justify-center">
                <a href="index.php?logout=true" title="Logout"
                    class="flex items-center justify-center w-14 h-14 rounded-xl bg-red-500 text-white hover:bg-red-600 transition duration-300 shadow-lg super-shadow">
                    <i class="fa-solid fa-arrow-left text-2xl transform -scale-x-100"></i>
                </a>
            </div>
        </aside>';

    $sidebarHtml .= '
        <main class="flex-1 overflow-x-hidden overflow-y-auto p-6 lg:p-10 z-10 relative lg:ml-28 pb-20 lg:pb-10">';

    echo $sidebarHtml;
    render_mobile_navbar($menu, basename($_SERVER['PHP_SELF']));
}

function render_topbar($title, $imageUrl = null) {
    $currentUserName = $_SESSION['user_name'] ?? 'Guest';
    $imageUrl = $_SESSION['profile_image_url'] ?? $imageUrl;
    $initial = strtoupper(substr($currentUserName, 0, 1));

    if ($imageUrl && strpos($imageUrl, 'placehold.co') === false) {
        $profileDisplayHtml = '
            <a href="profile.php" title="Welcome, ' . htmlspecialchars($currentUserName) . ' - Go to Profile">
                <img src="' . htmlspecialchars($imageUrl) . '" alt="Profile Picture"
                    class="w-10 h-10 rounded-full object-cover border-2 border-indigo-600 cursor-pointer transition duration-300 hover:scale-105 super-shadow"
                    onerror="this.onerror=null;this.src=\'https://placehold.co/40x40/2563EB/ffffff?text=' . $initial . '\';">
            </a>';
    } else {
        $profileDisplayHtml = '
            <a href="profile.php" title="Welcome, ' . htmlspecialchars($currentUserName) . ' - Go to Profile">
                <div class="w-10 h-10 active-gradient rounded-full flex items-center justify-center font-bold text-white cursor-pointer super-shadow transition duration-300 hover:scale-105">
                    ' . $initial . '
                </div>
            </a>';
    }

    echo '<header class="bg-white p-4 sticky top-0 z-20 super-shadow rounded-2xl flex justify-between items-center h-20 mb-8 transform transition duration-300 hover:shadow-2xl">
        <div class="flex items-center space-x-2 text-xl font-extrabold text-gray-900 min-w-[150px] lg:min-w-[200px]">
            <img src="assets/logo.png"
                 alt="CLASS KEY Logo"
                 onerror="this.onerror=null;this.src=\'https://placehold.co/150x50/F4F7F9/1D206F?text=CLASS+LOGO\'"
                 class="h-10 w-auto object-contain rounded-md">
        </div>
        <h1 class="flex-1 text-center text-xl sm:text-3xl font-extrabold text-gray-900 truncate mx-4">CLASS KEY</h1>
        <div class="flex items-center space-x-4 min-w-[150px] lg:min-w-[200px] justify-end">
            <button title="Notifications" class="w-10 h-10 rounded-full flex items-center justify-center text-gray-500 bg-gray-100 hover:bg-gray-200 hover:text-indigo-600 transition duration-200 shadow-inner">
                <i class="fa-solid fa-bell text-xl"></i>
            </button>
            ' . $profileDisplayHtml . '
        </div>
    </header>';
}

function render_admin_cards($items) {
    echo '<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">';
    foreach ($items as $item) {
        echo '<a href="' . htmlspecialchars($item['url']) . '" class="block">
            <div class="bg-white rounded-xl overflow-hidden shadow-lg hover:shadow-xl transition duration-300 transform hover:scale-[1.02]">
                <div class="p-6 flex flex-col items-center justify-center text-center">
                    <div class="text-indigo-600 mb-4">
                        <i class="' . htmlspecialchars($item['icon']) . ' text-5xl"></i>
                    </div>
                    <h3 class="text-xl font-bold text-gray-900 mb-1">' . htmlspecialchars($item['title']) . '</h3>
                    <p class="text-sm text-gray-500">' . htmlspecialchars($item['description']) . '</p>
                </div>
            </div>
        </a>';
    }
    echo '</div>';
}

function render_main_content_end() {
    echo '</main></div>';
}
?>