<?php
// Fetch Settings
$school_name_header = "CBT System";
$school_logo_header = "";
$ui_theme_default = "";
$ui_animations_default = "on";
$ui_background_default = "";

if (isset($pdo)) {
    $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('school_name', 'school_logo', 'ui_theme', 'ui_animations', 'ui_background')");
    $stmt->execute();
    while ($row = $stmt->fetch()) {
        if ($row['setting_key'] == 'school_name') $school_name_header = $row['setting_value'];
        if ($row['setting_key'] == 'school_logo') $school_logo_header = $row['setting_value'];
        if ($row['setting_key'] == 'ui_theme') $ui_theme_default = $row['setting_value'];
        if ($row['setting_key'] == 'ui_animations') $ui_animations_default = $row['setting_value'] ?: 'on';
        if ($row['setting_key'] == 'ui_background') $ui_background_default = $row['setting_value'];
    }
}

// Determine relative path prefix based on current script directory
$path_prefix = "";
if (basename(dirname($_SERVER['PHP_SELF'])) == 'admin' || basename(dirname($_SERVER['PHP_SELF'])) == 'student') {
    $path_prefix = "../";
}
?>
<div class="main-header">
    <button id="sidebarToggle" class="header-toggle" style="background:none; border:none; font-size: 24px; cursor: pointer; color: #334155;">
        &#9776;
    </button>
    <?php if ($school_logo_header): ?>
        <img src="<?php echo $path_prefix . htmlspecialchars($school_logo_header); ?>" alt="Logo" style="height: 50px; width: auto;">
    <?php endif; ?>
    <h2 class="header-title"><?php echo htmlspecialchars($school_name_header); ?></h2>
    <div style="margin-left: auto;"></div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const toggle = document.getElementById('sidebarToggle');
        const sidebar = document.querySelector('.sidebar');
        const content = document.querySelector('.content');
        const root = document.documentElement;
        const pathPrefix = "<?php echo $path_prefix; ?>";
        const heroExists = <?php echo file_exists(__DIR__ . '/../assets/img/student-hero.jpg') ? 'true' : 'false'; ?>;
        const defaultTheme = "<?php echo $ui_theme_default; ?>";
        const defaultAnimations = "<?php echo $ui_animations_default; ?>";
        const defaultBackground = "<?php echo $ui_background_default; ?>";
        // Prepare media sources for flying pictures
        const mediaSources = <?php
            $media = [];
            if (isset($pdo)) {
                $stmt = $pdo->query("SELECT file_path FROM media_library ORDER BY media_id DESC LIMIT 8");
                while ($m = $stmt->fetch()) {
                    $media[] = $path_prefix . $m['file_path'];
                }
            }
            echo json_encode($media);
        ?>;

        if (toggle && sidebar) {
            toggle.addEventListener('click', function() {
                if (window.innerWidth <= 768) {
                    sidebar.classList.toggle('active');
                } else {
                    sidebar.classList.toggle('hidden');
                    if (content) {
                        content.classList.toggle('full-width');
                    }
                }
            });
        }

        // Apply defaults from settings
        root.classList.remove('theme-indigo', 'theme-emerald', 'theme-rose');
        root.classList.remove('theme-sky','theme-amber','theme-violet','theme-teal','theme-slate');
        if (defaultTheme) {
            root.classList.add(defaultTheme);
        }
        if (defaultAnimations === 'off') {
            root.classList.add('no-animations');
        } else {
            root.classList.remove('no-animations');
        }
        root.classList.remove('bg-gradient', 'bg-hero', 'bg-hero-unsplash');
        if (defaultBackground) {
            if (defaultBackground === 'bg-hero' && !heroExists) {
                root.classList.add('bg-hero-unsplash');
                root.style.setProperty('--bg-image', 'url(https://source.unsplash.com/1600x900/?students,exam,classroom)');
            } else {
                root.classList.add(defaultBackground);
                if (defaultBackground === 'bg-hero') {
                    root.style.setProperty('--bg-image', 'url(' + pathPrefix + 'assets/img/student-hero.jpg)');
                } else if (defaultBackground === 'bg-hero-unsplash') {
                    root.style.setProperty('--bg-image', 'url(https://source.unsplash.com/1600x900/?students,exam,classroom)');
                } else {
                    root.style.removeProperty('--bg-image');
                }
            }
        } else {
            root.style.removeProperty('--bg-image');
        }

        // Flying pictures layer
        const enableFlying = defaultBackground === 'bg-hero' || defaultBackground === 'bg-hero-unsplash';
        if (enableFlying) {
            let layer = document.getElementById('flyingPicturesLayer');
            if (!layer) {
                layer = document.createElement('div');
                layer.id = 'flyingPicturesLayer';
                layer.className = 'flying-pictures';
                document.body.appendChild(layer);
                const sources = (mediaSources && mediaSources.length) ? mediaSources : [
                    'https://images.unsplash.com/photo-1531482615713-2afd69097998?auto=format&fit=crop&w=200&q=80', // Student Computer
                    'https://images.unsplash.com/photo-1522202176988-66273c2fd55f?auto=format&fit=crop&w=200&q=80', // Students Computer Group
                    'https://images.unsplash.com/photo-1427504746696-ea5abd7dfe4d?auto=format&fit=crop&w=200&q=80', // Library Study
                    'https://images.unsplash.com/photo-1581091226825-a6a2a5aee158?auto=format&fit=crop&w=200&q=80', // Laptop Work
                    'https://images.unsplash.com/photo-1516321318423-f06f85e504b3?auto=format&fit=crop&w=200&q=80'  // Digital Classroom
                ];
                for (let i=0; i<6; i++) {
                    const d = document.createElement('div');
                    d.className = 'fp-item';
                    const img = sources[Math.floor(Math.random()*sources.length)];
                    d.style.backgroundImage = 'url('+img+')';
                    d.style.top = Math.floor(Math.random()*80 + 10) + '%';
                    d.style.animationDuration = Math.floor(Math.random()*20 + 20) + 's';
                    d.style.animationDelay = Math.floor(Math.random()*10) + 's';
                    d.style.opacity = (Math.random()*0.3 + 0.2).toFixed(2);
                    layer.appendChild(d);
                }
            }
        }
    });
</script>
