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

// --- HELPERS ---
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 . DIRECTORY_SEPARATOR . $object)) rrmdir($dir . DIRECTORY_SEPARATOR . $object); else @unlink($dir . DIRECTORY_SEPARATOR . $object); } } rmdir($dir); } } }
if (getSetting('auto_cache_clear', '0') === '1') { $last_clear = (int)getSetting('last_cache_clear', '0'); if (time() - $last_clear > 86400) { if(is_dir('cache')) { 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();
if(function_exists('checkAndSendBirthdayWishes')) { checkAndSendBirthdayWishes(); }
$user_id = (int)($_SESSION['user_id'] ?? 0);
if ($user_id <= 0) { die("Invalid session"); }
try { checkAndAutoClearCache($pdo); } catch (Throwable $e) {}

// --- POST HANDLING ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $token = $_POST['csrf_token'] ?? '';
    if (empty($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $token)) die("CSRF Error");
    if ($_POST['action'] === 'correct_attendance' && isset($_POST['att_id'])) {
        $pdo->prepare("UPDATE student_attendance SET status = 'present', reason = NULL, recorded_by = ? WHERE id = ?")->execute([$user_id, (int)$_POST['att_id']]);
        header("Location: dashboard.php"); exit;
    }
    if ($_POST['action'] === 'notif_mark_all_read') { $pdo->prepare("UPDATE notifications SET is_read = 1 WHERE user_id = ?")->execute([$user_id]); header("Location: dashboard.php"); exit; }
    if ($_POST['action'] === 'notif_clear_all') { $pdo->prepare("DELETE FROM notifications WHERE user_id = ?")->execute([$user_id]); header("Location: dashboard.php"); exit; }
}

// --- DATA FETCH ---
$s_name = getSetting('school_name', 'SAS');
$sys_mode = getSetting('system_mode', 'live');
$today = date('Y-m-d');
$now_time = date('H:i:s');
$day_num = date('N');

// Holiday Logic
$is_weekend = ($day_num >= 6);
$is_holiday = false;
$holiday_name = "";
$holiday_type = "holiday";
try {
    $holiday_stmt = $pdo->prepare("SELECT description, type FROM school_holidays WHERE ? BETWEEN start_date AND end_date LIMIT 1");
    $holiday_stmt->execute([$today]);
    $holiday_data = $holiday_stmt->fetch(PDO::FETCH_ASSOC);
    if ($holiday_data) {
        $is_holiday = true;
        $holiday_name = $holiday_data['description'] ?? '';
    }
} catch (PDOException $e) { $is_holiday = false; }
$is_school_off = $is_weekend || $is_holiday;

// User Data
$user_stmt = $pdo->prepare("SELECT full_name, role, avatar FROM users WHERE id = ?");
$user_stmt->execute([$user_id]);
$user_data = $user_stmt->fetch(PDO::FETCH_ASSOC) ?: [];
$full_name = $user_data['full_name'] ?? 'User';
$user_roles = array_map('trim', explode(',', $user_data['role'] ?? 'teacher'));
$hour = (int)date('H');
$greeting = ($hour < 12) ? "Good Morning" : (($hour < 17) ? "Good Afternoon" : "Good Evening");

// Schedule
$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(PDO::FETCH_ASSOC);

$active_class_id = null;
$completed_count = 0;
$total_classes = count($classes);
$status_text = "Free Period";
$status_sub = "Enjoy your break";

// Batch Fetch Attendance
$completed_ids = [];
if (!empty($classes)) {
    $timetable_ids = array_column($classes, 'id');
    $placeholders = str_repeat('?,', count($timetable_ids) - 1) . '?';
    $log_stmt = $pdo->prepare("SELECT timetable_id FROM attendance_logs WHERE timetable_id IN ($placeholders) AND DATE(scan_time) = ?");
    $log_stmt->execute(array_merge($timetable_ids, [$today]));
    $completed_ids = $log_stmt->fetchAll(PDO::FETCH_COLUMN);
}

foreach ($classes as $key => $cls) {
    $is_done = in_array($cls['id'], $completed_ids);
    $classes[$key]['is_done'] = $is_done;
    if ($is_done) $completed_count++;
    if ($now_time >= $cls['start_time'] && $now_time <= $cls['end_time']) {
        $status_text = $cls['subject'];
        $status_sub = ($cls['type'] === 'relief' ? "? RELIEF: " : "") . $cls['class_name'] . " � Ends " . substr($cls['end_time'], 0, 5);
        $active_class_id = (int)$cls['id'];
    }
}
if ($is_school_off) {
    $status_text = $is_holiday ? $holiday_name : "Weekend Break";
    $status_sub = "No classes scheduled today";
}
$progress_percent = ($total_classes > 0) ? round(($completed_count / $total_classes) * 100) : 0;

// Class Teacher Info
$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(PDO::FETCH_ASSOC);

$absentees_map = [];
if ($my_class_info) {
    $abs_stmt = $pdo->prepare("SELECT s.full_name, s.id as student_id, sa.id as aid, sa.reason, t.start_time, u.full_name as recorder_name, t.subject FROM student_attendance sa JOIN students s ON sa.student_id = s.id JOIN timetable t ON sa.timetable_id = t.id LEFT JOIN users u ON sa.recorded_by = u.id WHERE s.class_id = ? AND sa.date = ? AND sa.status = 'absent' ORDER BY t.start_time ASC");
    $abs_stmt->execute([(int)$my_class_info['id'], $today]);
    foreach ($abs_stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
        $sid = (int)$r['student_id'];
        $absentees_map[$sid]['name'] = $r['full_name'];
        $absentees_map[$sid]['reason'] = $r['reason'] ?: 'Unknown';
        $absentees_map[$sid]['slots'][] = ['aid' => (int)$r['aid'], 'time' => substr($r['start_time'], 0, 5), 'subj' => $r['subject']];
    }
}
$daily_quote = null;
try { $daily_quote = $pdo->query("SELECT * FROM quotes ORDER BY RAND() LIMIT 1")->fetch(PDO::FETCH_ASSOC); } catch (Throwable $e) {}
?>
<!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><?= htmlspecialchars($s_name) ?></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; overflow-x: hidden; }
        .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; }

        /* LOADER */
        #page-loader { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: #f8f9fd; z-index: 9999; display: flex; flex-direction: column; align-items: center; justify-content: center; transition: opacity 0.4s ease-out; }
        .loader-progress { width: 180px; height: 6px; background: #e2e8f0; border-radius: 10px; overflow: hidden; margin-top: 20px; position: relative; }
        .loader-bar { position: absolute; top: 0; left: 0; bottom: 0; width: 50%; background: var(--primary-grad); border-radius: 10px; animation: loading-slide 1.5s infinite ease-in-out; }
        @keyframes loading-slide { 0% { left: -50%; width: 50%; } 50% { left: 25%; width: 75%; } 100% { left: 100%; width: 50%; } }
        .loader-hidden { opacity: 0; pointer-events: none; }

        /* Notification Badge Logic - CRITICAL */
        .notif-btn { position: relative; color: white; font-size: 1.6rem; cursor: pointer; width: 52px; height: 52px; display: flex; align-items: center; justify-content: center; border-radius: 16px; background: rgba(255, 255, 255, 0.2); backdrop-filter: blur(8px); border: 1px solid rgba(255, 255, 255, 0.3); box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1); z-index: 1061; transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); }
        .notif-btn:active { transform: scale(0.92); background: rgba(255, 255, 255, 0.3); }
        .notif-badge { 
            position: absolute; top: -5px; right: -5px; 
            background: #ef4444; min-width: 20px; height: 20px; 
            padding: 0 4px; border-radius: 10px; border: 2px solid #fff; 
            font-size: 0.7rem; font-weight: 800; color: #fff; 
            display: none; /* Hidden by default */
            align-items: center; justify-content: center; 
            z-index: 1062; pointer-events: none; 
            box-shadow: 0 2px 5px rgba(239, 68, 68, 0.4); 
        }
        .notif-badge.is-visible { display: flex !important; }

        .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; }
        .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-value { color: var(--text-dark); font-size: 1.25rem; font-weight: 700; transition: color 0.3s; }
        .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; transition: all 0.3s; }
        .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; }
        .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; }
        .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; }
        .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; }
        .menu-list { padding: 0 20px 10px 20px; }
        .menu-item { display: flex; align-items: center; padding: 12px 0; text-decoration: none; border-bottom: 1px solid #f1f5f9; }
        .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; }
        .absent-chart-container { position: relative; width: 45px; height: 45px; display: flex; align-items: center; justify-content: center; }
        .chart-ring { transform: rotate(-90deg); }
        .chart-bg { fill: none; stroke: #f1f5f9; stroke-width: 4; }
        .chart-progress { fill: none; stroke: #ef4444; stroke-width: 4; stroke-linecap: round; transition: stroke-dashoffset 1s ease-out; }
        .chart-text { position: absolute; font-size: 0.7rem; font-weight: 700; color: #ef4444; }
        .timeline-item { position: relative; padding-left: 45px; padding-bottom: 25px; }
        .timeline-item::before { content: ""; position: absolute; left: 17px; top: 5px; bottom: 0; width: 2px; background: #e2e8f0; }
        .timeline-item:last-child::before { display: none; }
        .timeline-marker { position: absolute; left: 0; top: 0; width: 34px; height: 34px; border-radius: 50%; background: white; border: 3px solid #cbd5e1; display: flex; align-items: center; justify-content: center; z-index: 1; font-size: 0.8rem; }
        .timeline-active .timeline-marker { background: #8B5CF6; border-color: #ddd6fe; color: white; box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.2); }
        .timeline-active::before { background: #8B5CF6; opacity: 0.3; }
        .timeline-done .timeline-marker { background: #10b981; border-color: #d1fae5; color: white; }
        .agenda-card { background: #f8fafc; border-radius: 16px; padding: 12px 16px; transition: 0.3s; }
        .timeline-active .agenda-card { background: white; box-shadow: 0 4px 12px rgba(0,0,0,0.05); border: 1px solid rgba(139, 92, 246, 0.1); }
        .time-tag { font-size: 0.7rem; font-weight: 700; color: var(--text-gray); margin-bottom: 2px; }
        .bell-ring { animation: bellRing 0.7s ease-in-out; transform-origin: top center; }
        @keyframes bellRing { 0% { transform: rotate(0deg); } 15% { transform: rotate(18deg); } 30% { transform: rotate(-18deg); } 45% { transform: rotate(12deg); } 60% { transform: rotate(-12deg); } 75% { transform: rotate(6deg); } 100% { transform: rotate(0deg); } }

        /* --- WIDGET STYLES --- */
        .info-widget { background: white; border-radius: 16px; padding: 12px; display: flex; align-items: center; box-shadow: 0 4px 15px rgba(0,0,0,0.03); margin-bottom: 10px; cursor: pointer; transition: transform 0.2s; }
        .info-widget:active { transform: scale(0.98); }
        .widget-icon { width: 40px; height: 40px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.1rem; margin-right: 12px; flex-shrink: 0; }
        
        /* --- TICKER STYLES --- */
        .ticker-wrap { background: #1e293b; color: white; padding: 10px 0; overflow: hidden; white-space: nowrap; font-size: 0.8rem; font-weight: 600; margin-bottom: 10px; border-radius: 8px; }
        .ticker-move { display: inline-block; padding-left: 100%; animation: ticker 25s linear infinite; }
        @keyframes ticker { 0% { transform: translate3d(0, 0, 0); } 100% { transform: translate3d(-100%, 0, 0); } }
        
        /* --- TREND BADGE --- */
        .health-badge { font-size: 0.65rem; padding: 3px 8px; border-radius: 12px; margin-left: 8px; font-weight: 700; }
        .health-up { background: #dcfce7; color: #166534; }
        .health-down { background: #fee2e2; color: #991b1b; }
    </style>
</head>
<body>

    <div id="page-loader">
        <div class="spinner-border text-primary" role="status" style="width: 2.5rem; height: 2.5rem; --bs-spinner-border-width: 0.2rem;"></div>
        <div class="loader-progress"><div class="loader-bar"></div></div>
        <div class="small text-muted fw-bold mt-2 text-uppercase" style="letter-spacing:1px; font-size:0.7rem;">Loading Dashboard...</div>
    </div>

    <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 id="bellIcon" class="bi bi-bell-fill"></i>
                <div class="notif-badge" id="notifBadge"></div>
            </div>
        </div>
        <div class="d-flex align-items-center">
            <div class="avatar-ring me-3">
                <?php if(!empty($user_data['avatar'])): ?>
                    <img src="<?= htmlspecialchars($user_data['avatar']) ?>" class="avatar-img">
                <?php else: ?>
                    <div class="avatar-img d-flex align-items-center justify-content-center text-primary fw-bold bg-white">
                        <?= htmlspecialchars(substr($full_name,0,1)) ?>
                    </div>
                <?php endif; ?>
            </div>
            <div>
                <div class="opacity-75 small"><?= $greeting ?>,</div>
                <h5 class="mb-0 fw-bold"><?= htmlspecialchars($full_name) ?></h5>
                <small class="opacity-50"><?= htmlspecialchars($user_roles[0] ?? 'teacher') ?></small>
            </div>
        </div>
    </div>

    <div class="floating-card">
        <div class="d-flex justify-content-between align-items-start border-bottom pb-3 mb-3">
            <div>
                <div class="status-label text-muted small"><?= $is_school_off ? 'Today' : 'Current Class' ?></div>
                <div class="status-value" id="statusText"><?= htmlspecialchars($status_text) ?></div>
                <div class="status-sub" id="statusSub"><?= htmlspecialchars($status_sub) ?></div>
            </div>
            <button class="btn btn-light rounded-pill border shadow-sm btn-sm px-3 fw-bold text-primary" data-bs-toggle="modal" data-bs-target="#agendaModal">
                <i class="bi bi-journal-text me-1"></i> Agenda
            </button>
        </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">Schedule</span></a>
            <a href="<?= ($sys_mode == 'live') ? 'scanner_view.php' : ($active_class_id ? 'class_session.php?timetable_id='.$active_class_id : 'class_session.php') ?>" class="action-item"><div class="icon-circle bg-blue"><i class="bi bi-qr-code-scan"></i></div><span class="icon-label">Scan</span></a>
            <a href="dashboard_discipline.php" class="action-item"><div class="icon-circle bg-pink"><i class="bi bi-shield-exclamation"></i></div><span class="icon-label">Report</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>

    <div id="widgetContainer" class="px-3 mt-3"></div>

    <?php if($my_class_info): 
        $count_stmt = $pdo->prepare("SELECT COUNT(*) FROM students WHERE class_id = ?");
        $count_stmt->execute([(int)$my_class_info['id']]);
        $total_students = (int)$count_stmt->fetchColumn();
        $absent_count = count($absentees_map);
        $present_count = $total_students - $absent_count;
        $absent_percent = ($total_students > 0) ? ($absent_count / $total_students) * 100 : 0;
        $circumference = 2 * pi() * 18;
        $offset = $circumference - ($absent_percent / 100) * $circumference;
    ?>
    <div class="mt-4">
        <button class="collapse-btn" type="button" data-bs-toggle="collapse" data-bs-target="#classInfoCollapse">
           <div class="d-flex align-items-center">
               <span>My Class: <?= htmlspecialchars($my_class_info['class_name']) ?></span>
               <span id="attTrend" class="health-badge d-none"></span>
           </div>
        </button>
        <div class="collapse show" id="classInfoCollapse">
            <div class="dashboard-card p-3 border-start border-5 border-primary mt-2">
                <div class="d-flex align-items-center mb-3">
                    <div class="absent-chart-container me-3">
                        <svg width="40" height="40" class="chart-ring">
                            <circle class="chart-bg" cx="20" cy="20" r="18" />
                            <circle class="chart-progress" cx="20" cy="20" r="18" style="stroke-dasharray: <?= $circumference ?>; stroke-dashoffset: <?= $offset ?>;" />
                        </svg>
                        <div class="chart-text"><?= $absent_count ?></div>
                    </div>
                    <div><h6 class="fw-bold text-dark mb-0">Today's Summary</h6><small class="text-muted"><?= $present_count ?> / <?= $total_students ?> Present</small></div>
                </div>
                <?php if($absentees_map): ?>
                    <div class="list-group list-group-flush">
                        <?php foreach($absentees_map as $sid => $data): ?>
                            <div class="list-group-item bg-transparent px-0 py-2 d-flex justify-content-between align-items-center" onclick="openCorrection('<?= (int)$sid ?>')" style="cursor:pointer;">
                                <div><div class="fw-bold text-dark small"><?= htmlspecialchars($data['name']) ?></div><span class="badge bg-danger bg-opacity-10 text-danger border-0 badge-sm" style="font-size:0.6rem;"><?= htmlspecialchars($data['reason']) ?></span>
                                <input type="hidden" id="name_<?= (int)$sid ?>" value="<?= htmlspecialchars($data['name']) ?>"><textarea id="slots_json_<?= (int)$sid ?>" style="display:none;"><?= htmlspecialchars(json_encode($data['slots'])) ?></textarea></div><i class="bi bi-pencil-square text-secondary"></i>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?><div class="text-center text-success py-2 fw-bold small">All students present!</div><?php endif; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div id="announcementContainer" class="px-3 d-none">
        <div class="ticker-wrap"><div class="ticker-move" id="tickerText"></div></div>
    </div>

    <div class="mt-2">
        <button class="collapse-btn" type="button" data-bs-toggle="collapse" data-bs-target="#quickAccessMenu"><span>Quick Access</span><i class="bi bi-chevron-down"></i></button>
        <div class="collapse" id="quickAccessMenu">
            <div class="menu-list">
                <div class="text-muted small fw-bold mt-2 mb-1 opacity-50 text-uppercase" style="font-size:0.65rem; letter-spacing: 0.5px;">Academic</div>
                <?php if($my_class_info): ?>
                    <a href="teacher_students.php" class="menu-item"><div class="menu-icon shadow-sm" style="background: #fff1f2; color: #e11d48;"><i class="bi bi-people-fill"></i></div><div class="menu-text fw-600">Student List</div><i class="bi bi-chevron-right menu-arrow"></i></a>
                    <a href="daily_report.php" class="menu-item"><div class="menu-icon shadow-sm" style="background: #f0fdf4; color: #16a34a;"><i class="bi bi-clipboard-data-fill"></i></div><div class="menu-text fw-600">Daily Report</div><i class="bi bi-chevron-right menu-arrow"></i></a>
                    <a href="student_reports.php" class="menu-item"><div class="menu-icon shadow-sm" style="background: #ecfeff; color: #0891b2;"><i class="bi bi-mortarboard-fill"></i></div><div class="menu-text fw-600">Class Report</div><i class="bi bi-chevron-right menu-arrow"></i></a>
                <?php endif; ?>
                <a href="calendar.php" class="menu-item"><div class="menu-icon shadow-sm" style="background: #eef2ff; color: #4f46e5;"><i class="bi bi-calendar3"></i></div><div class="menu-text fw-600">School Calendar</div><i class="bi bi-chevron-right menu-arrow"></i></a>
                <?php if(!empty(array_intersect($user_roles, ['admin', 'principal', 'assistant', 'assistant_hem', 'Ffbooking']))): ?>
                    <div class="text-muted small fw-bold mt-4 mb-1 opacity-50 text-uppercase" style="font-size:0.65rem; letter-spacing: 0.5px;">Administration</div>
                    <a href="admin_dashboard.php" class="menu-item"><div class="menu-icon shadow-sm" style="background: #fff7ed; color: #ea580c;"><i class="bi bi-speedometer2"></i></div><div class="menu-text">Admin Dashboard</div><i class="bi bi-chevron-right menu-arrow"></i></a>
                    <a href="admin_system.php" class="menu-item"><div class="menu-icon shadow-sm" style="background: #f8fafc; color: #475569;"><i class="bi bi-sliders"></i></div><div class="menu-text">System Settings</div><i class="bi bi-chevron-right menu-arrow"></i></a>
                    <a href="admin_settings.php" class="menu-item"><div class="menu-icon shadow-sm" style="background: #f1f5f9; color: #64748b;"><i class="bi bi-gear-wide-connected"></i></div><div class="menu-text">Admin Settings</div><i class="bi bi-chevron-right menu-arrow"></i></a>
                <?php endif; ?>
            </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 class="text-center mt-4 mb-5"><div class="text-muted small fw-bold">Copyright &copy; 2025 Shaiffulnizam Mohamad</div></div>
    </div>

    <div class="offcanvas offcanvas-start" tabindex="-1" id="sidebarMenu" style="width: 280px;">
        <div class="offcanvas-header border-bottom">
            <h5 class="offcanvas-title fw-bold">Main 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"><?= htmlspecialchars($full_name) ?></div>
                <small class="text-muted"><?= htmlspecialchars($user_roles[0] ?? 'teacher') ?></small>
            </div>
            <div class="list-group list-group-flush">
                <a href="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="news.php" class="list-group-item list-group-item-action py-3 border-0">
                    <i class="bi bi-newspaper me-3 text-primary"></i>MOE News
                </a>
                <a href="public_directory.php" class="list-group-item list-group-item-action py-3 border-0">
                    <i class="bi bi-journal-album me-3 text-primary"></i>Staff Directory
                </a>
                <a href="links.php" class="list-group-item list-group-item-action py-3 border-0">
                <i class="bi bi-link-45deg me-3 text-primary"></i>Important Links
                </a>
                <a href="profile.php" class="list-group-item list-group-item-action py-3 border-0">
                    <i class="bi bi-person-gear me-3 text-secondary"></i>Profile Settings
                </a>
                <a href="about.php" class="list-group-item list-group-item-action py-3 border-0">
                    <i class="bi bi-info-circle-fill me-3 text-info"></i>About Developer
                </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> 
    <div class="modal fade" id="birthdayModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered modal-sm"><div class="modal-content border-0 shadow-lg rounded-4"><div class="modal-header border-0 bg-danger text-white pb-2"><h6 class="modal-title fw-bold"><i class="bi bi-cake2-fill me-2"></i>Birthdays Today</h6><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body p-3 bg-light" id="birthdayList"></div></div></div></div>

    <div class="modal fade" id="notifModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered modal-sm"><div class="modal-content border-0 shadow-lg" style="border-radius:24px;"><div class="modal-header border-0 pb-0"><h5 class="fw-bold">Alerts</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><div id="notifList"></div><form method="POST" class="mt-2"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token'] ?? '') ?>"><input type="hidden" name="action" value="notif_mark_all_read"><button type="submit" class="btn btn-primary btn-sm w-100 rounded-pill mt-2">Mark All Read</button></form><form method="POST" class="mt-2" onsubmit="return confirm('Delete all alerts permanently?');"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token'] ?? '') ?>"><input type="hidden" name="action" value="notif_clear_all"><button type="submit" class="btn btn-outline-danger btn-sm w-100 rounded-pill mt-2">Clear All History</button></form></div></div></div></div>

    <div class="modal fade animate__animated animate__fadeIn" id="agendaModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered modal-dialog-scrollable"><div class="modal-content border-0 shadow-lg" style="border-radius:30px;"><div class="modal-header border-0 pb-0 px-4 pt-4"><div class="w-100"><div class="d-flex justify-content-between align-items-center mb-2"><div><h5 class="fw-bold mb-0">Daily Agenda</h5><small class="text-muted"><?= date('l, d M') ?></small></div><span class="badge bg-primary-subtle text-primary rounded-pill"><?= $progress_percent ?>% Done</span></div><div class="progress" style="height: 8px; border-radius: 10px; background-color: #f1f5f9;"><div class="progress-bar progress-bar-striped progress-bar-animated bg-primary" role="progressbar" style="width: <?= $progress_percent ?>%;"></div></div></div></div><div class="modal-body px-4"><div class="timeline-container mt-4"><?php if ($is_school_off || empty($classes)): ?><?php $holidayClass = $is_holiday ? 'holiday-bg' : ''; ?><div class="text-center py-5 <?= $holidayClass ?>"><div class="icon-circle bg-blue mx-auto mb-3" style="width: 70px; height: 70px; font-size: 1.8rem;"><i class="bi <?= $is_holiday ? 'bi-stars' : 'bi-cup-hot-fill' ?>"></i></div><?php if ($is_holiday): ?><h6 class="fw-bold mb-1">Now Cuti la Cikgu</h6><p class="small text-muted mt-1 mb-0">Get a good rest and recharge.</p><?php if (!empty($holiday_name)): ?><div class="mt-3 small fw-bold text-dark opacity-75"><?= htmlspecialchars($holiday_name) ?></div><?php endif; ?><?php else: ?><h6 class="fw-bold">No Classes Scheduled</h6><?php endif; ?></div><?php else: ?><?php foreach ($classes as $cls): $is_active = ($now_time >= $cls['start_time'] && $now_time <= $cls['end_time']); $is_done = !empty($cls['is_done']); $status_class = $is_done ? 'timeline-done' : ($is_active ? 'timeline-active' : 'timeline-upcoming'); ?><div class="timeline-item <?= $status_class ?>"><div class="timeline-marker"><?php if ($is_done): ?><i class="bi bi-check-lg"></i><?php elseif ($is_active): ?><i class="bi bi-play-fill"></i><?php else: ?><i class="bi bi-clock"></i><?php endif; ?></div><div class="agenda-card"><div class="d-flex justify-content-between align-items-start"><div><div class="time-tag"><?= substr($cls['start_time'], 0, 5) ?> - <?= substr($cls['end_time'], 0, 5) ?></div><div class="fw-bold text-dark"><?= htmlspecialchars($cls['subject']) ?></div><div class="small text-muted"><i class="bi bi-geo-alt me-1"></i><?= htmlspecialchars($cls['class_name']) ?></div></div><?php if ($is_active): ?><span class="badge bg-primary rounded-pill animate__animated animate__pulse animate__infinite">Now</span><?php endif; ?></div></div></div><?php endforeach; ?><?php endif; ?></div></div><div class="modal-footer border-0 p-4"><button type="button" class="btn btn-light w-100 rounded-pill fw-bold" data-bs-dismiss="modal">Close</button></div></div></div></div>

    <div class="modal fade" id="correctionModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content border-0 shadow" style="border-radius:20px;"><div class="modal-header bg-light py-2"><h6 class="modal-title fw-bold">Correct Attendance</h6><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body p-0"><div class="bg-info bg-opacity-10 p-3 border-bottom"><h5 class="fw-bold text-dark mb-0" id="modalStudentName"></h5></div><div class="p-3"><div id="modalSlotsList" class="list-group small"></div></div></div></div></div></div>

    <audio id="notifSound" preload="auto"><source src="assets/sounds/bell.mp3" type="audio/mpeg"></audio>
    <?php include 'menu.php'; ?>
    <div class="position-fixed top-0 start-50 translate-middle-x p-3" style="z-index: 2000;"><div id="notifToast" class="toast align-items-center text-bg-primary border-0" role="alert"><div class="d-flex"><div class="toast-body" id="notifToastBody">New notification</div><button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button></div></div></div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // --- LOADER ---
        window.addEventListener('load', function() { const loader = document.getElementById('page-loader'); setTimeout(() => { loader.classList.add('loader-hidden'); setTimeout(() => { loader.style.display = 'none'; }, 500); }, 300); });
        document.querySelectorAll('a').forEach(link => { link.addEventListener('click', function(e) { if(this.href && !this.href.includes('javascript') && !this.href.includes('#') && !this.target) { const loader = document.getElementById('page-loader'); loader.style.display = 'flex'; loader.classList.remove('loader-hidden'); } }); });

        // Safe Initialization of Sidebar
        const sidebarEl = document.getElementById('sidebarMenu');
        
        let touchStartX = 0;
        document.addEventListener('touchstart', e => { touchStartX = e.changedTouches[0].screenX; }, {passive: true});
        document.addEventListener('touchend', e => { 
            let touchEndX = e.changedTouches[0].screenX; 
            const bsOffcanvas = bootstrap.Offcanvas.getOrCreateInstance(sidebarEl);
            if (touchStartX - touchEndX > 70 && e.target.closest('#sidebarMenu')) bsOffcanvas.hide(); 
            if (touchStartX - touchEndX < -70 && touchStartX < 50) bsOffcanvas.show(); 
        }, {passive: true});

        let lastUnreadCount = -1; 
        let birthNames = []; // Global variable for birthday names

        async function pollNotifications() {
            try {
                // Poll the updated API
                const res = await fetch('api_dashboard.php?since=' + encodeURIComponent(new Date(Date.now() - 10000).toISOString()));
                
                if(!res.ok) throw new Error("API Error");
                
                const data = await res.json();
                
                if(data.error) {
                    console.error("API Error:", data.error);
                    return;
                }

                // 1. Status Live Update
                if(data.status) {
                    const stVal = document.getElementById('statusText'); const stSub = document.getElementById('statusSub');
                    if(stVal.textContent !== data.status.text) stVal.textContent = data.status.text;
                    if(stSub.textContent !== data.status.sub) stSub.textContent = data.status.sub;
                }

                // 2. Notifications Logic (Fixed)
                const count = Number(data.notifications || 0);
                const badge = document.getElementById('notifBadge');
                if (badge) {
                    if (count > 0) { 
                        badge.textContent = count > 99 ? '99+' : count; 
                        badge.classList.add('is-visible'); 
                    } else { 
                        badge.classList.remove('is-visible'); 
                    }
                }

                // Sound & Toast
                if (lastUnreadCount !== -1 && count > lastUnreadCount) {
                    document.getElementById('bellIcon').classList.add('bell-ring');
                    const sound = document.getElementById('notifSound'); if(sound) sound.play().catch(()=>{});
                    if (data.latest_alert) { document.getElementById('notifToastBody').textContent = data.latest_alert.message; bootstrap.Toast.getOrCreateInstance(document.getElementById('notifToast')).show(); }
                }
                lastUnreadCount = count;

                // 3. Ticker
                const tick = document.getElementById('announcementContainer');
                if(data.announcement) {
                    tick.classList.remove('d-none');
                    document.getElementById('tickerText').innerHTML = `<span class="ticker-item">${data.announcement.title}: ${data.announcement.message}</span>`;
                } else { tick.classList.add('d-none'); }

                // 4. Widgets
                const wc = document.getElementById('widgetContainer');
                let html = '';
                // Birthday (Clickable)
                if(data.birthdays && data.birthdays.length > 0) {
                    birthNames = data.birthdays;
                    html += `<div class="info-widget animate__animated animate__fadeIn" onclick="showBirthdayModal()"><div class="widget-icon bg-danger bg-opacity-10 text-danger"><i class="bi bi-cake2-fill"></i></div><div><div class="small fw-bold text-muted text-uppercase" style="font-size:0.65rem;">Birthdays Today</div><div class="fw-bold text-dark">${data.birthdays.length} student(s) celebrating!</div></div></div>`;
                }
                
                // --- HOLIDAY / UPCOMING EVENT WIDGET (UPDATED) ---
                // Removed days_left limit so the Next Event is always visible.
                if(data.next_holiday) {
                    html += `<div class="info-widget animate__animated animate__fadeIn">
                        <div class="widget-icon bg-success bg-opacity-10 text-success"><i class="bi bi-calendar-heart-fill"></i></div>
                        <div>
                            <div class="small fw-bold text-muted text-uppercase" style="font-size:0.65rem;">Upcoming: ${data.next_holiday.description}</div>
                            <div class="fw-bold text-dark">in ${data.next_holiday.days_left} days</div>
                        </div>
                    </div>`;
                }
                wc.innerHTML = html;

                // 5. Attendance Trend
                const tr = document.getElementById('attTrend');
                if(tr && data.att_health) {
                    tr.classList.remove('d-none','health-up','health-down');
                    if(data.att_health.trend === 'up') { tr.classList.add('health-up'); tr.innerHTML = `<i class="bi bi-graph-up-arrow"></i> +${data.att_health.diff}%`; }
                    else { tr.classList.add('health-down'); tr.innerHTML = `<i class="bi bi-graph-down-arrow"></i> -${data.att_health.diff}%`; }
                }

            } catch(e) { console.log("Polling Error:", e); }
        }
        setInterval(pollNotifications, 10000); pollNotifications();

        function showBirthdayModal() {
            const list = document.getElementById('birthdayList');
            list.innerHTML = birthNames.map(n => `<div class="p-2 border-bottom fw-bold text-dark small">${n}</div>`).join('');
            new bootstrap.Modal(document.getElementById('birthdayModal')).show();
        }

        document.getElementById('notifModal').addEventListener('show.bs.modal', async () => {
            const res = await fetch('notifications_api.php?mode=full&limit=10'); const d = await res.json();
            document.getElementById('notifList').innerHTML = d.items?.map(n => `<div class="p-2 border-bottom ${n.is_read==0?'bg-light':''}"><div class="small fw-bold">${n.message}</div><div class="text-muted" style="font-size:0.65rem;">${n.created_at}</div></div>`).join('') || '<div class="text-center p-3 small text-muted">No alerts.</div>';
        });

        function openCorrection(sid) {
            const n = document.getElementById('name_' + sid).value;
            const s = JSON.parse(document.getElementById('slots_json_' + sid).value || '[]');
            document.getElementById('modalStudentName').innerText = n;
            document.getElementById('modalSlotsList').innerHTML = s.map(sl => `<div class="list-group-item d-flex justify-content-between align-items-center bg-light border-0 mb-2 rounded-3"><div><strong>${sl.subj}</strong><br><small>${sl.time}</small></div><form method="POST"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token'] ?? '') ?>"><input type="hidden" name="action" value="correct_attendance"><input type="hidden" name="att_id" value="${sl.aid}"><button class="btn btn-sm btn-success rounded-pill px-3">Present</button></form></div>`).join('');
            new bootstrap.Modal(document.getElementById('correctionModal')).show();
        }
    </script>
</body>
</html>