<?php
// Filename: form6_dashboard.php
require 'config.php';

// --- HELPER: AUTO CACHE CLEAR ---
// FIX: Added function_exists check to prevent Fatal Error
if (!function_exists('rrmdir')) {
    function rrmdir($dir) { 
        if (is_dir($dir)) { 
            $objects = scandir($dir); 
            foreach ($objects as $object) { 
                if ($object != "." && $object != "..") { 
                    if (is_dir($dir. DIRECTORY_SEPARATOR .$object) && !is_link($dir."/".$object))
                        rrmdir($dir. DIRECTORY_SEPARATOR .$object);
                    else
                        unlink($dir. DIRECTORY_SEPARATOR .$object); 
                } 
            }
        } 
    }
}

function checkAndAutoClearCache($pdo) {
    if (getSetting('auto_cache_clear', '0') === '1') {
        $last_clear = intval(getSetting('last_cache_clear', '0'));
        if (time() - $last_clear > 86400) { // 24 Hours
            rrmdir('cache');
            $pdo->prepare("INSERT INTO system_settings (setting_key, setting_value) VALUES ('last_cache_clear', ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)")->execute([time()]);
        }
    }
}

requireLogin();

// --- 1. STRICT PERMISSION CHECK ---
$my_roles = explode(',', $_SESSION['role'] ?? '');
if (!in_array('form6_teacher', $my_roles) && !in_array('admin', $my_roles)) {
    header("Location: dashboard.php"); 
    exit;
}

$user_id = $_SESSION['user_id'];

// --- USER DATA ---
$user_stmt = $pdo->prepare("SELECT full_name, role, avatar, username FROM users WHERE id = ?");
$user_stmt->execute([$user_id]);
$user_data = $user_stmt->fetch();

// FIX: Define variables BEFORE they are used in HTML or birthday logic
$full_name = $user_data['full_name'] ?? 'User';
$user_avatar = $user_data['avatar'] ?? '';
$user_ic = $user_data['username'] ?? ''; 

// --- CHECK BIRTHDAY ---
// Moved here so $user_ic is already defined
$is_my_birthday = false;
if (!empty($user_ic) && strlen($user_ic) >= 6 && is_numeric(substr($user_ic, 0, 6))) {
    if (substr($user_ic, 2, 4) === date('md')) $is_my_birthday = true;
}

// --- INITIAL DATA FETCHING ---
$today = date('Y-m-d');
$now_time = date('H:i:s');
$server_time_js = date('Y-m-d H:i:s'); 
$day_num = date('N'); 

// Class Teacher Check (Form 6 Class)
$ct_stmt = $pdo->prepare("SELECT id, class_name FROM classes WHERE class_teacher_id = ?");
$ct_stmt->execute([$user_id]);
$my_class_info = $ct_stmt->fetch();

// --- FETCH SCHEDULE (Timetable + Relief) ---
$sched_stmt = $pdo->prepare("SELECT t.*, c.class_name, 'regular' as type FROM timetable t JOIN classes c ON t.class_id = c.id WHERE t.teacher_id = ? AND t.day_of_week = ? UNION ALL SELECT t.*, c.class_name, 'relief' as type FROM relief_assignments r JOIN timetable t ON r.timetable_id = t.id JOIN classes c ON t.class_id = c.id WHERE r.reliever_id = ? AND r.assignment_date = ? ORDER BY start_time");
$sched_stmt->execute([$user_id, $day_num, $user_id, $today]);
$classes = $sched_stmt->fetchAll();

// --- STATUS LOGIC ---
$status_text = "Free Period";
$status_sub = "No class right now";
$active_class_id = null;
$missed_classes = [];      
$ending_soon_alert = null; 

foreach ($classes as $key => $cls) {
    $chk = $pdo->prepare("SELECT id FROM attendance_logs WHERE timetable_id=? AND DATE(scan_time)=? LIMIT 1");
    $chk->execute([$cls['id'], $today]); 
    $is_done = (bool)$chk->fetch();
    $classes[$key]['is_done'] = $is_done;

    if (!$is_done && $now_time > $cls['end_time']) {
        $missed_classes[] = $cls;
    }

    if ($now_time >= $cls['start_time'] && $now_time <= $cls['end_time']) {
        $status_text = $cls['subject'];
        $status_sub = $cls['class_name'] . " • Ends " . substr($cls['end_time'], 0, 5);
        $active_class_id = $cls['id'];
        
        if (!$is_done) {
            $mins_left = (strtotime($cls['end_time']) - strtotime($now_time)) / 60;
            if ($mins_left <= 15) $ending_soon_alert = $cls;
        }
    } elseif ($now_time < $cls['start_time'] && !$active_class_id) {
        $status_text = "Next: " . $cls['subject'];
        $status_sub = "Starts " . substr($cls['start_time'], 0, 5);
    }
}

// Notifications
$notif_stmt = $pdo->prepare("SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5");
$notif_stmt->execute([$user_id]);
$my_notifs = $notif_stmt->fetchAll();
$notif_count = count($my_notifs);

// Announcements
$announce_sql = "SELECT * FROM announcements WHERE type = 'global' AND start_date <= NOW() AND (end_date IS NULL OR end_date >= NOW()) ORDER BY created_at DESC LIMIT 1";
$latest_announcement = $pdo->query($announce_sql)->fetch(PDO::FETCH_ASSOC);

// Quote
$daily_quote = null;
try { $daily_quote = $pdo->query("SELECT * FROM quotes ORDER BY RAND() LIMIT 1")->fetch(); } catch (Exception $e) {}

$s_name = getSetting('school_name', 'SAS');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>Form 6 Dashboard</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
    
    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; --bg-color: #f8f9fd; --text-dark: #1e293b; --text-gray: #64748b; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }
        
        .app-header { background: var(--primary-grad); padding: 20px 20px 80px 20px; border-radius: 0 0 35px 35px; color: white; position: relative; }
        .header-top { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 20px; }
        .avatar-ring { border: 2px solid rgba(255,255,255,0.8); padding: 2px; border-radius: 50%; width: 54px; height: 54px; }
        .avatar-img { width: 100%; height: 100%; border-radius: 50%; object-fit: cover; background: #fff; }
        
        .notif-btn { position: relative; color: white; font-size: 1.5rem; cursor: pointer; width: 50px; height: 50px; display: flex; align-items: center; justify-content: center; border-radius: 50%; background: rgba(255,255,255,0.15); backdrop-filter: blur(4px); transition: 0.2s; }
        .notif-btn:active { background: rgba(255,255,255,0.3); transform: scale(0.95); }
        .notif-badge { position: absolute; top: 12px; right: 12px; background: #ef4444; width: 10px; height: 10px; border-radius: 50%; border: 2px solid rgba(255,255,255,0.9); display: none; }
        .notif-badge.active { display: block; }

        .floating-card { background: white; margin: -60px 20px 0 20px; border-radius: 24px; padding: 20px; box-shadow: 0 15px 35px rgba(0,0,0,0.08); position: relative; z-index: 10; }
        .status-label { color: var(--text-gray); font-size: 0.85rem; margin-bottom: 4px; }
        .status-value { color: var(--text-dark); font-size: 1.25rem; font-weight: 700; }
        .status-sub { color: #8B5CF6; font-size: 0.8rem; font-weight: 600; background: #f3e8ff; padding: 2px 8px; border-radius: 10px; display: inline-block; margin-top: 5px;}

        .action-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin-top: 15px; } 
        .action-item { display: flex; flex-direction: column; align-items: center; text-decoration: none; color: var(--text-dark); }
        .icon-circle { width: 48px; height: 48px; border-radius: 16px; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; margin-bottom: 8px; transition: transform 0.2s; }
        .action-item:active .icon-circle { transform: scale(0.9); }
        .icon-label { font-size: 0.75rem; font-weight: 500; color: var(--text-gray); }
        .bg-purple { background: #f3e8ff; color: #8B5CF6; }
        .bg-blue   { background: #e0f2fe; color: #0ea5e9; }
        .bg-pink   { background: #fce7f3; color: #ec4899; }
        .bg-green  { background: #dcfce7; color: #10b981; }

        .collapse-btn { border: none; background: transparent; width: 100%; display: flex; justify-content: space-between; align-items: center; padding: 15px 20px 5px 20px; color: var(--text-gray); font-weight: 700; font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.5px; margin-top: 10px; }
        .menu-list { padding: 0 20px 10px 20px; }
        .menu-item { display: flex; align-items: center; padding: 8px 0; text-decoration: none; border-bottom: 1px solid #f1f5f9; }
        .menu-item:last-child { border-bottom: none; }
        .menu-icon { width: 40px; height: 40px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.1rem; margin-right: 15px; }
        .menu-text { flex-grow: 1; color: var(--text-dark); font-weight: 500; }
        .menu-arrow { color: #cbd5e1; font-size: 0.9rem; }

        .dashboard-card { background: white; border: none; border-radius: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.05); margin: 0 20px; overflow: hidden; }

        .promo-banner { 
            margin: 20px 20px 10px 20px; 
            background: linear-gradient(135deg, #6366f1 0%, #8B5CF6 100%); 
            border-radius: 20px; padding: 20px; color: white; 
            display: flex; align-items: center; 
            box-shadow: 0 10px 20px rgba(99, 102, 241, 0.2); 
            cursor: pointer; 
        }
    </style>
</head>
<body>

    <div class="app-header">
        <div class="header-top">
            <button class="btn btn-link text-white p-0 border-0" type="button" data-bs-toggle="offcanvas" data-bs-target="#sidebarMenu">
                <i class="bi bi-list fs-1"></i>
            </button>
            <div class="notif-btn" data-bs-toggle="modal" data-bs-target="#notifModal">
                <i class="bi bi-bell"></i>
                <div class="notif-badge <?= $notif_count > 0 ? 'active' : '' ?>" id="notifBadge"></div>
            </div>
        </div>
        
        <?php if($is_my_birthday): ?>
            <div id="teacherBirthdayBanner" class="alert bg-white border-0 shadow text-center rounded-4 mb-4 animate__animated animate__bounceIn">
                <div class="fw-bold fs-4 text-dark">?? Happy Birthday! ??</div>
                <div class="small opacity-75 text-dark">Have a wonderful day, <?= explode(' ', trim($full_name))[0] ?>!</div>
            </div>
        <?php endif; ?>

        <div class="d-flex align-items-center">
            <div class="avatar-ring me-3">
                <?php if(!empty($user_avatar)): ?><img src="<?= $user_avatar ?>" class="avatar-img"><?php else: ?><div class="avatar-img d-flex align-items-center justify-content-center text-primary fw-bold bg-white"><?= substr($full_name,0,1) ?></div><?php endif; ?>
            </div>
            <div>
                <div class="opacity-75 small">Welcome back,</div>
                <h5 class="mb-0 fw-bold"><?= $full_name ?></h5>
                <small class="opacity-50">Form 6 Teacher</small>
            </div>
        </div>
    </div>

    <div class="floating-card">
        
        <div id="alertContainer">
        <?php if (!empty($missed_classes)): ?>
            <div class="alert alert-danger border-0 shadow-sm rounded-4 d-flex justify-content-between align-items-center p-2 mb-3 animate__animated animate__pulse">
                <div class="small lh-sm ps-1">
                    <div class="fw-bold"><i class="bi bi-exclamation-octagon-fill me-1"></i> Missed Class</div>
                    <span style="font-size:0.7rem">You missed <?= count($missed_classes) ?> session(s).</span>
                </div>
                <a href="class_session.php?timetable_id=<?= $missed_classes[0]['id'] ?>" class="btn btn-light text-danger fw-bold btn-sm rounded-pill shadow-sm" style="font-size:0.7rem">Fix Now</a>
            </div>
        <?php elseif ($ending_soon_alert): ?>
            <div class="alert alert-warning border-0 shadow-sm rounded-4 d-flex justify-content-between align-items-center p-2 mb-3 animate__animated animate__pulse">
                <div class="small lh-sm ps-1">
                    <div class="fw-bold text-dark"><i class="bi bi-clock-history me-1"></i> Ending Soon</div>
                    <span style="font-size:0.7rem" class="text-dark">Attendace needed!</span>
                </div>
                <a href="scanner_view.php" class="btn btn-light text-warning fw-bold btn-sm rounded-pill shadow-sm" style="font-size:0.7rem">Scan</a>
            </div>
        <?php endif; ?>
        </div>

        <div class="border-bottom pb-3 mb-3">
            <div class="status-label">Current Status</div>
            <div class="d-flex justify-content-between align-items-center">
                <div class="status-value" id="statusValue"><?= $status_text ?></div>
            </div>
            <div class="status-sub" id="statusSub"><?= $status_sub ?></div>
        </div>

        <div class="action-grid">
            <a href="teacher_timetable.php" class="action-item"><div class="icon-circle bg-purple"><i class="bi bi-calendar-week"></i></div><span class="icon-label">Timetable</span></a>
            <a href="scanner_view.php" class="action-item" id="btnScan"><div class="icon-circle bg-blue"><i class="bi bi-qr-code-scan"></i></div><span class="icon-label">Scan</span></a>
            <a href="booking/index.php" class="action-item"><div class="icon-circle bg-pink"><i class="bi bi-door-open"></i></div><span class="icon-label">Booking</span></a>
            <a href="teacher_leave.php" class="action-item"><div class="icon-circle bg-green"><i class="bi bi-briefcase"></i></div><span class="icon-label">Leave</span></a>
        </div>
    </div>

    <?php if(!empty($latest_announcement)): ?>
    <div class="promo-banner" id="promoBanner">
        <div class="me-3"><div style="background: rgba(255,255,255,0.2); padding: 10px; border-radius: 12px;"><i class="bi bi-megaphone-fill fs-3"></i></div></div>
        <div style="flex-grow: 1; overflow: hidden;"><div class="fw-bold mb-1" id="bannerTitle"><?= htmlspecialchars($latest_announcement['title']) ?></div><div class="small opacity-75 text-truncate" id="bannerMsg"><?= htmlspecialchars($latest_announcement['message']) ?></div></div><i class="bi bi-chevron-right ms-2 opacity-50"></i>
    </div>
    <?php endif; ?>

    <div class="mt-2">
        <button class="collapse-btn" type="button" data-bs-toggle="collapse" data-bs-target="#quickAccessMenu"><span>Form 6 Actions</span><i class="bi bi-chevron-down"></i></button>
        <div class="collapse show" id="quickAccessMenu">
            <div class="menu-list">
                <?php if(!empty($my_class_info)): ?>
                <a href="teacher_students.php" class="menu-item"><div class="menu-icon" style="background: #fdf2f8; color: #db2777;"><i class="bi bi-people-fill"></i></div><div class="menu-text">My Students</div><i class="bi bi-chevron-right menu-arrow"></i></a>
                <?php endif; ?>
                
                <a href="student_reports.php" class="menu-item"><div class="menu-icon" style="background: #e0f2fe; color: #0284c7;"><i class="bi bi-mortarboard-fill"></i></div><div class="menu-text">Sem Reports</div><i class="bi bi-chevron-right menu-arrow"></i></a>
                
                <a href="calendar.php" class="menu-item"><div class="menu-icon" style="background: #eff6ff; color: #2563eb;"><i class="bi bi-calendar-event"></i></div><div class="menu-text">School Calendar</div><i class="bi bi-chevron-right menu-arrow"></i></a>
                
                <a href="booking/index.php" class="menu-item"><div class="menu-icon" style="background: #f0fdf4; color: #16a34a;"><i class="bi bi-calendar-plus"></i></div><div class="menu-text">Room Booking</div><i class="bi bi-chevron-right menu-arrow"></i></a>
                
                <a href="public_directory.php" class="menu-item"><div class="menu-icon" style="background: #f0fdfa; color: #0d9488;"><i class="bi bi-journal-album"></i></div><div class="menu-text">Staff Directory</div><i class="bi bi-chevron-right menu-arrow"></i></a>

                <a href="profile.php" class="menu-item"><div class="menu-icon" style="background: #f1f5f9; color: #475569;"><i class="bi bi-gear-fill"></i></div><div class="menu-text">Profile Settings</div><i class="bi bi-chevron-right menu-arrow"></i></a>
            </div>
        </div>
    </div>

    <div class="mt-auto pb-4">
        <?php if($daily_quote): ?>
            <div class="text-center mt-4 mb-3 px-4"><i class="bi bi-quote fs-1 text-primary opacity-25"></i><figure class="mt-2"><blockquote class="blockquote fs-6"><p class="mb-2 text-dark font-italic small fw-bold">"<?= htmlspecialchars($daily_quote['content']) ?>"</p></blockquote><figcaption class="blockquote-footer mt-1 mb-0 small"><?= htmlspecialchars($daily_quote['author']) ?></figcaption></figure></div>
        <?php endif; ?>
    </div>

    <div class="modal fade" id="notifModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered modal-sm"><div class="modal-content"><div class="modal-header border-0 pb-0"><h5 class="modal-title fw-bold">Notifications</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><?php if(empty($my_notifs)): ?><div class="text-center text-muted py-4"><i class="bi bi-bell-slash fs-1 d-block mb-2 opacity-25"></i><small>No new notifications</small></div><?php else: ?><div class="list-group list-group-flush"><?php foreach($my_notifs as $n): ?><div class="list-group-item px-0 border-0 mb-2"><div class="d-flex align-items-start"><div class="me-3 mt-1"><div class="bg-primary rounded-circle" style="width:8px; height:8px;"></div></div><div><div class="small text-dark mb-1"><?= htmlspecialchars($n['message']) ?></div><div class="text-muted" style="font-size: 0.65rem;"><?= date('d M h:i A', strtotime($n['created_at'])) ?></div></div></div></div><?php endforeach; ?></div><a href="dashboard.php?read_all=1" class="btn btn-light btn-sm w-100 rounded-pill mt-3">Mark all as read</a><?php endif; ?></div></div></div></div>
    <div class="modal fade" id="announcementModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered modal-sm"><div class="modal-content rounded-4 shadow-lg border-0"><div class="modal-body text-center p-4"><div style="width: 60px; height: 60px; background: rgba(139, 92, 246, 0.1); color: #8B5CF6; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 1.8rem; margin: 0 auto 15px auto;"><i class="bi bi-megaphone-fill"></i></div><h4 class="fw-bold mb-2" id="modalAnnounceTitle">Title</h4><p class="text-muted small" id="modalAnnounceBody">Message goes here...</p><button type="button" class="btn btn-primary w-100 rounded-pill mt-3" data-bs-dismiss="modal">Okay</button></div></div></div></div>

    <?php include 'menu.php'; ?>

    <div class="offcanvas offcanvas-start" tabindex="-1" id="sidebarMenu" style="width: 280px;"><div class="offcanvas-header border-bottom"><h5 class="offcanvas-title fw-bold">Menu</h5><button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button></div><div class="offcanvas-body p-0"><div class="bg-light p-3 mb-2 text-center"><div class="fw-bold"><?= $full_name ?></div><small class="text-muted">Form 6 Teacher</small></div><div class="list-group list-group-flush"><a href="form6_dashboard.php" class="list-group-item list-group-item-action py-3 border-0"><i class="bi bi-grid-fill me-3 text-primary"></i>Dashboard</a><a href="teacher_timetable.php" class="list-group-item list-group-item-action py-3 border-0"><i class="bi bi-calendar-week me-3 text-primary"></i>My Schedule</a><a href="student_reports.php" class="list-group-item list-group-item-action py-3 border-0"><i class="bi bi-file-earmark-bar-graph me-3 text-primary"></i>Reports</a><a href="booking/index.php" class="list-group-item list-group-item-action py-3 border-0"><i class="bi bi-door-open me-3 text-primary"></i>Room Booking</a><a href="profile.php" class="list-group-item list-group-item-action py-3 border-0"><i class="bi bi-gear-fill me-3 text-secondary"></i>Settings</a><a href="logout.php" class="list-group-item list-group-item-action py-3 border-0 text-danger"><i class="bi bi-box-arrow-right me-3"></i>Logout</a></div></div></div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const urlParams = new URLSearchParams(window.location.search);
            if (urlParams.has('open_agenda')) {
                const newUrl = window.location.pathname;
                window.history.replaceState({}, document.title, newUrl);
                // The agenda modal is inside menu.php
                const agModal = document.getElementById('agendaModal');
                if(agModal) new bootstrap.Modal(agModal).show();
            }
        });
        // (Copy the rest of the Notification/Banner JS logic from dashboard.php if needed)
    </script>
</body>
</html>