<?php
// Filename: admin_dashboard.php
require 'config.php';
requireLogin();

// --- 1. ROBUST ACCESS CHECK ---
$uid = $_SESSION['user_id'];
$stmt = $pdo->prepare("SELECT role, full_name, avatar FROM users WHERE id = ?");
$stmt->execute([$uid]);
$user_data = $stmt->fetch();

if ($user_data) {
    $_SESSION['role'] = $user_data['role'];
    $current_roles_str = $user_data['role'];
    $full_name = $user_data['full_name'];
    $user_avatar = $user_data['avatar'];
} else {
    $current_roles_str = $_SESSION['role'] ?? 'teacher';
    $full_name = $_SESSION['full_name'] ?? 'User';
    $user_avatar = $_SESSION['avatar'] ?? '';
}

$name_parts = explode(' ', trim($full_name));
$first_name = $name_parts[0]; 

$user_roles = array_map('trim', explode(',', $current_roles_str));
$allowed_admin_dashboard = ['admin', 'principal', 'assistant', 'assistant_hem', 'timetable_coord', 'discipline_teacher', 'admin_booking'];

if (empty(array_intersect($user_roles, $allowed_admin_dashboard))) {
    header("Location: dashboard.php");
    exit;
}

// --- FETCH CLASS TEACHER INFO ---
$ct_stmt = $pdo->prepare("SELECT id, class_name FROM classes WHERE class_teacher_id = ?");
$ct_stmt->execute([$uid]);
$my_class_info = $ct_stmt->fetch();

$s_name = getSetting('school_name', 'SAS');
$public_enabled = getSetting('public_portal_enabled', '1');

// --- 2. NOTIFICATIONS LOGIC ---
if (isset($_GET['read_all'])) {
    $pdo->prepare("UPDATE notifications SET is_read = 1 WHERE user_id = ?")->execute([$uid]);
    header("Location: admin_dashboard.php"); exit;
}
$notif_stmt = $pdo->prepare("SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5");
$notif_stmt->execute([$uid]);
$my_notifs = $notif_stmt->fetchAll();
$notif_count = count($my_notifs);

// Statistics
$total_teachers = $pdo->query("SELECT COUNT(*) FROM users WHERE role LIKE '%teacher%'")->fetchColumn();
$total_students = $pdo->query("SELECT COUNT(*) FROM students")->fetchColumn();
$total_classes  = $pdo->query("SELECT COUNT(*) FROM classes")->fetchColumn();
?>
<!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>Management Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <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); color: var(--text-dark); padding-bottom: 120px; }
        
        /* HEADER */
        .app-header { background: var(--primary-grad); padding: 20px 20px 80px 20px; border-radius: 0 0 35px 35px; color: white; position: relative; z-index: 5; }
        
        /* THE FIX: Higher z-index and relative position for the top bar */
        .header-top { 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            margin-bottom: 25px; 
            position: relative; 
            z-index: 50; 
        }
        
        .avatar-ring { border: 2px solid rgba(255,255,255,0.8); padding: 2px; border-radius: 50%; width: 54px; height: 54px; flex-shrink: 0; }
        .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: 48px; height: 48px; display: flex; align-items: center; justify-content: center;
            border-radius: 12px; background: rgba(255,255,255,0.15); backdrop-filter: blur(8px); 
            transition: all 0.2s; border: 1px solid rgba(255,255,255,0.1);
        }
        .notif-btn:active { background: rgba(255,255,255,0.3); transform: scale(0.92); }
        .notif-badge { 
            position: absolute; top: 10px; right: 10px; background: #ff4d4d; 
            width: 10px; height: 10px; border-radius: 50%; border: 2px solid white; 
        }

        /* FLOATING CARD */
        .floating-card {
            background: white; margin: -50px 20px 20px 20px;
            border-radius: 24px; padding: 20px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.08);
            position: relative; z-index: 10;
        }

        .stat-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; text-align: center; margin-bottom: 20px; border-bottom: 1px solid #f1f5f9; padding-bottom: 15px;}
        .stat-item h4 { margin: 0; font-weight: 700; color: var(--text-dark); }
        .stat-label { font-size: 0.65rem; color: var(--text-gray); text-transform: uppercase; font-weight: 700; }

        .admin-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; text-align: center; }
        .admin-item { display: flex; flex-direction: column; align-items: center; text-decoration: none; color: var(--text-dark); font-size: 0.75rem; font-weight: 600; transition: 0.2s; }
        .admin-item:active { transform: scale(0.95); }
        .icon-box { width: 50px; height: 50px; border-radius: 16px; margin-bottom: 8px; display: flex; align-items: center; justify-content: center; font-size: 1.4rem; box-shadow: 0 4px 10px rgba(0,0,0,0.05); }

        /* THEMES */
        .theme-blue { background: #e0f2fe; color: #0ea5e9; }
        .theme-purple { background: #f3e8ff; color: #8B5CF6; }
        .theme-green { background: #dcfce7; color: #10b981; }
        .theme-orange { background: #ffedd5; color: #f97316; }
        .theme-red { background: #fee2e2; color: #ef4444; }
        .theme-gray { background: #f1f5f9; color: #64748b; }
        .theme-cyan { background: #cffafe; color: #06b6d4; }
        .theme-rose { background: #fff1f2; color: #e11d48; }

        .collapse-btn { width: 100%; border: none; background: transparent; display: flex; justify-content: space-between; align-items: center; padding: 10px 0; color: #64748b; font-weight: 700; font-size: 0.85rem; text-transform: uppercase; }
    </style>
</head>
<body>

    <div class="app-header">
        <div class="header-top">
            <button class="btn btn-link text-white p-0 border-0 shadow-none" 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>
                <?php if($notif_count > 0): ?><div class="notif-badge"></div><?php endif; ?>
            </div>
        </div>
        
        <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">Management Portal</div>
                <h5 class="mb-0 fw-bold"><?= $full_name ?></h5>
                <small class="opacity-50 text-uppercase" style="font-size: 0.65rem;"><?= $user_roles[0] ?></small>
            </div>
        </div>
    </div>

    <div class="floating-card">
        <div class="stat-grid">
            <div class="stat-item"><h4><?= $total_teachers ?></h4><div class="stat-label">Staff</div></div>
            <div class="stat-item border-start border-end"><h4><?= $total_students ?></h4><div class="stat-label">Students</div></div>
            <div class="stat-item"><h4><?= $total_classes ?></h4><div class="stat-label">Classes</div></div>
        </div>

        <div class="admin-grid">
            <?php 
            $main_buttons = [
                ['label'=>'Timetable', 'icon'=>'bi-calendar-week', 'url'=>'admin_timetable.php', 'theme'=>'theme-blue', 'roles'=>['admin', 'timetable_coord', 'principal', 'assistant']],
                ['label'=>'Booking', 'icon'=>'bi-calendar-check', 'url'=>'booking/admin/manage.php', 'theme'=>'theme-cyan', 'roles'=>['admin', 'admin_booking']],
                ['label'=>'Staff', 'icon'=>'bi-person-badge', 'url'=>'admin_teachers.php', 'theme'=>'theme-purple', 'roles'=>['admin']],
                ['label'=>'Students', 'icon'=>'bi-backpack', 'url'=>'admin_students.php', 'theme'=>'theme-green', 'roles'=>['admin']],
                ['label'=>'Relief', 'icon'=>'bi-arrow-left-right', 'url'=>'admin_relief.php', 'theme'=>'theme-orange', 'roles'=>['admin', 'timetable_coord', 'principal', 'assistant']],
                ['label'=>'Absence', 'icon'=>'bi-bandaid', 'url'=>'absent_management.php', 'theme'=>'theme-red', 'roles'=>['admin', 'principal', 'assistant', 'timetable_coord']], 
                ['label'=>'Discipline', 'icon'=>'bi-shield-exclamation', 'url'=>'admin_discipline.php', 'theme'=>'theme-red', 'roles'=>['admin', 'discipline_teacher']],
                ['label'=>'Classes', 'icon'=>'bi-buildings', 'url'=>'admin_classes.php', 'theme'=>'theme-blue', 'roles'=>['admin', 'timetable_coord']],
                ['label'=>'Subjects', 'icon'=>'bi-book', 'url'=>'admin_subjects.php', 'theme'=>'theme-purple', 'roles'=>['admin', 'timetable_coord']],
                ['label'=>'Promotion', 'icon'=>'bi-arrow-up-circle', 'url'=>'admin_promotion.php', 'theme'=>'theme-rose', 'roles'=>['admin', 'principal', 'assistant', 'timetable_coord']],
            ];

            foreach($main_buttons as $btn) {
                if (!empty(array_intersect($user_roles, $btn['roles']))) {
                    echo "<a href='{$btn['url']}' class='admin-item'>
                            <div class='icon-box {$btn['theme']}'><i class='bi {$btn['icon']}'></i></div>
                            <span>{$btn['label']}</span>
                          </a>";
                }
            }
            ?>
        </div>
    </div>

    <div class="px-3 mt-3">
        <button class="collapse-btn" type="button" data-bs-toggle="collapse" data-bs-target="#moreTools">
            <span>Advanced Tools</span><i class="bi bi-chevron-down"></i>
        </button>
        <div class="collapse show" id="moreTools">
            <div class="bg-white rounded-4 p-3 shadow-sm mt-2">
                <div class="admin-grid">
                    <?php 
                    $adv_buttons = [
                        ['label'=>'Announce', 'icon'=>'bi-megaphone', 'url'=>'admin_announcements.php', 'theme'=>'theme-gray', 'roles'=>['admin', 'principal', 'assistant']],
                        // --- NEW LINKS BUTTON ADDED HERE ---
                        ['label'=>'Links', 'icon'=>'bi-link-45deg', 'url'=>'admin_links.php', 'theme'=>'theme-cyan', 'roles'=>['admin', 'assistant']],
                        ['label'=>'Settings', 'icon'=>'bi-sliders', 'url'=>'admin_settings.php', 'theme'=>'theme-gray', 'roles'=>['admin']],
                        ['label'=>'QR Codes', 'icon'=>'bi-qr-code', 'url'=>'admin_qrcodes.php', 'theme'=>'theme-gray', 'roles'=>['admin']],
                        ['label'=>'Holidays', 'icon'=>'bi-calendar-date', 'url'=>'admin_holidays.php', 'theme'=>'theme-gray', 'roles'=>['admin', 'principal', 'assistant', 'timetable_coord']],
                        ['label'=>'Std Stats', 'icon'=>'bi-mortarboard', 'url'=>'student_reports_admin.php', 'theme'=>'theme-blue', 'roles'=>['admin', 'assistant', 'principal']], 
                        ['label'=>'Tch Stats', 'icon'=>'bi-bar-chart-line', 'url'=>'reports.php', 'theme'=>'theme-blue', 'roles'=>['admin', 'assistant', 'principal']], 
                        ['label'=>'System', 'icon'=>'bi-hdd-network', 'url'=>'admin_system.php', 'theme'=>'theme-red', 'roles'=>['admin']],
                        ['label'=>'Quotes', 'icon'=>'bi-chat-quote', 'url'=>'admin_quotes.php', 'theme'=>'theme-purple', 'roles'=>['admin', 'principal', 'assistant']],
                        ['label'=>'Feedback', 'icon'=>'bi-envelope', 'url'=>'admin_feedback.php', 'theme'=>'theme-green', 'roles'=>['admin']],
                    ];
                    if($public_enabled === '1') $adv_buttons[] = ['label'=>'Portal', 'icon'=>'bi-globe', 'url'=>'admin_public.php', 'theme'=>'theme-orange', 'roles'=>['admin']];

                    foreach($adv_buttons as $btn) {
                        if (!empty(array_intersect($user_roles, $btn['roles']))) {
                            echo "<a href='{$btn['url']}' class='admin-item'>
                                    <div class='icon-box {$btn['theme']}'><i class='bi {$btn['icon']}'></i></div>
                                    <span>{$btn['label']}</span>
                                  </a>";
                        }
                    }
                    ?>
                </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">
                <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 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="admin_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="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"><?= $user_roles[0] ?></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="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>
    
    <?php include 'menu.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>