<?php
session_start();
require_once 'config.php'; // Ensure this path is correct

// Define role constants (ensure these match your config.php or are globally defined)
if (!defined('ROLE_SUPER_ADMIN')) define('ROLE_SUPER_ADMIN', 0);
if (!defined('ROLE_ADMIN')) define('ROLE_ADMIN', 1);
if (!defined('ROLE_TEACHER')) define('ROLE_TEACHER', 2);
if (!defined('ROLE_STUDENT')) define('ROLE_STUDENT', 3);

// Function to check user role and redirect if unauthorized
function check_role_access($required_role_code) {
    if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || !isset($_SESSION["school_id"])) {
        header("location: login.php");
        exit;
    }

    if ($_SESSION["role"] !== $required_role_code) {
        switch ($_SESSION["role"]) {
            case ROLE_SUPER_ADMIN:
                header("location: super_admin_dashboard.php");
                break;
            case ROLE_TEACHER:
                header("location: teacher_dashboard.php");
                break;
            case ROLE_STUDENT:
                header("location: student_dashboard.php");
                break;
            default: // Catch-all for any other unexpected roles
                header("location: login.php");
                break;
        }
        exit;
    }
}

// !! CRITICAL: Call the check for Admin role !!
check_role_access(ROLE_ADMIN);

// Check if school is suspended
if (isset($conn) && $conn instanceof mysqli) {
    $check_school_id = $_SESSION["school_id"];
    $sql_status = "SELECT status FROM schools WHERE school_id = ?";
    if ($stmt_status = $conn->prepare($sql_status)) {
        $stmt_status->bind_param("i", $check_school_id);
        if ($stmt_status->execute()) {
            $stmt_status->bind_result($school_status);
            if ($stmt_status->fetch()) {
                if ($school_status === 'suspended') {
                    $stmt_status->close();
                    header("location: subscription_suspended.php");
                    exit;
                }
            }
        }
        $stmt_status->close();
    }
}

// User is authorized, fetch additional details for display
$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]); // Sanitize for display
$user_role_code = $_SESSION["role"]; // Get role code from session
$current_user_school_id = $_SESSION["school_id"]; // Get the school_id for the logged-in user
$phone_number = $photo = $status = ""; // Initialize variables for DB fetch

// Initialize school variables
$school_name = "School Name Not Found"; // Default value for HTML output
$school_name_for_js = "School Name Not Found"; // Default value for JavaScript output
$school_logo_path = "images/default_school_logo.png"; // Default logo path

// Initialize dashboard stats for Admin
$totalStudents = 0;
$totalTeachers = 0;
$totalClasses = 0;
$unreadMessages = 0;

// NEW: Initialize variable for exam analysis data
$examAnalysisData = [];

// Ensure $conn is available from config.php
if (isset($conn) && $conn instanceof mysqli) { // Check if $conn is set and is a mysqli object

    // Fetch additional user details from the database (phone, photo, status) from the 'users' table
    $sql = "SELECT phone_number, photo, status FROM users WHERE id = ? AND school_id = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("ii", $user_id, $current_user_school_id);
        if ($stmt->execute()) {
            $stmt->bind_result($phone_number_db, $photo_db, $status_db);
            $stmt->fetch();
            $phone_number = htmlspecialchars($phone_number_db ?? 'N/A');
            // Default photo for Admin if not set
            $photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iODAiIGhlaWdodD0iODAiIHZpZXdCb3g9IjAgMCA4MCA4MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjgwIiBoZWlnaHQ9IjgwIiBmaWxsPSIjQ0NDQ0NDIi8+Cjx0ZXh0IHg9IjQwIiB5PSI0NSIgZm9udC1mYW1pbHk9IkFyaWFsLCBzYW5zLXNlcmlmIiBmb250LXNpemU9IjE4IiBmb250LXdlaWdodD0iYm9sZCIgZmlsbD0iI0ZGRkZGRiIgdGV4dC1hbmNob3I9Im1pZGRsZSI+QUQ8L3RleHQ+Cjwvc3ZnPgo=';
            $status = htmlspecialchars($status_db ?? 'N/A');
        } else {
            error_log("Execute failed for user details query for Admin: " . $stmt->error);
        }
        $stmt->close(); // This $stmt is closed here
    } else {
        error_log("Prepare failed for user details query for Admin: " . $conn->error);
    }

    // Fetch School Name and Logo from 'schools' table
    $sql_school = "SELECT school_name, logo, subscription_expiry_date FROM schools WHERE school_id = ?";
    if ($stmt_school = $conn->prepare($sql_school)) {
        $stmt_school->bind_param("i", $current_user_school_id);
        if ($stmt_school->execute()) {
            $stmt_school->bind_result($school_name_db, $school_logo_db, $subscription_expiry_db);
            if ($stmt_school->fetch()) {
                $school_name = htmlspecialchars($school_name_db); // For direct HTML output
                $school_name_for_js = addslashes($school_name_db); // For JavaScript string literal
                $school_logo_path = !empty($school_logo_db) ? htmlspecialchars($school_logo_db) : 'images/default_school_logo.png';
                $subscription_expiry_date = $subscription_expiry_db; // Store expiry date
            } else {
                error_log("School details not found for school_id: " . $current_user_school_id);
            }
        } else {
            error_log("Execute failed for school data query: " . $stmt_school->error);
        }
        $stmt_school->close();
    } else {
        error_log("Prepare failed for school data query: " . $conn->error);
    }

    // --- Admin Specific Dashboard Statistics ---

    // Total Students (active: 'active' or empty string) in the school - Count directly from users table
    // Alternative approach to avoid bind_param reference issues
    $sql_total_students = "SELECT COUNT(id) FROM users WHERE school_id = " . (int)$current_user_school_id . " AND role = 3 AND (status = 'active' OR status = '')";
    if ($result_students = $conn->query($sql_total_students)) {
        $row = $result_students->fetch_row();
        $totalStudents = $row[0];
        $result_students->free();
    } else {
        error_log("Execute failed for total students query for Admin: " . $conn->error);
        $totalStudents = 0;
    }

    // Total Teachers (active) in the school
    $sql_total_teachers = "SELECT COUNT(t.teacher_id) FROM teachers t JOIN users u ON t.user_id = u.id WHERE u.school_id = ? AND u.status = 'active'";
    if ($stmt_teachers = $conn->prepare($sql_total_teachers)) {
        $stmt_teachers->bind_param("i", $current_user_school_id);
        if ($stmt_teachers->execute()) {
            $stmt_teachers->bind_result($count);
            $stmt_teachers->fetch();
            $totalTeachers = $count;
        } else {
            error_log("Execute failed for total teachers query for Admin: " . $stmt_teachers->error);
        }
        $stmt_teachers->close();
    } else {
        error_log("Prepare failed for total teachers query for Admin: " . $conn->error);
    }

    // Total Classes in the school
    $sql_total_classes = "SELECT COUNT(class_id) FROM classes WHERE school_id = ?";
    if ($stmt_classes = $conn->prepare($sql_total_classes)) {
        $stmt_classes->bind_param("i", $current_user_school_id);
        if ($stmt_classes->execute()) {
            $stmt_classes->bind_result($count);
            $stmt_classes->fetch();
            $totalClasses = $count;
        } else {
            error_log("Execute failed for total classes query for Admin: " . $stmt_classes->error);
        }
        $stmt_classes->close();
    } else {
        error_log("Prepare failed for total classes query for Admin: " . $conn->error);
    }

    // Unread Messages (messages where admin is receiver)
    $sql_unread_messages = "
        SELECT COUNT(id)
        FROM messages
        WHERE receiver_id = ? AND school_id = ? AND status = 'Unread'
    ";
    if ($stmt_messages = $conn->prepare($sql_unread_messages)) {
        $stmt_messages->bind_param("ii", $user_id, $current_user_school_id); // Admin's user_id as receiver
        if ($stmt_messages->execute()) {
            $stmt_messages->bind_result($count);
            $stmt_messages->fetch();
            $unreadMessages = $count;
        } else {
            error_log("Execute failed for unread messages query for Admin: " . $stmt_messages->error);
        }
        $stmt_messages->close();
    } else {
        error_log("Prepare failed for unread messages query for Admin: " . $conn->error);
    }

    // NEW: Fetch Exam Analysis Data (Average scores per Class and Subject from 'marks' table)
    $sql_exam_analysis = "
        SELECT
            c.class_name,
            s.subject_name,
            AVG(m.mark) AS average_score
        FROM
            marks m
        JOIN
            classes c ON m.stream_id = c.stream_id
        JOIN
            exams e ON m.exam_id = e.exam_id
        JOIN
            subjects s ON m.subject_id = s.subject_id
        WHERE
            e.school_id = ?
        GROUP BY
            c.class_name, s.subject_name
        ORDER BY
            c.class_name, s.subject_name
    ";
    if ($stmt_exam_analysis = $conn->prepare($sql_exam_analysis)) {
        $stmt_exam_analysis->bind_param("i", $current_user_school_id);
        if ($stmt_exam_analysis->execute()) {
            $result_exam_analysis = $stmt_exam_analysis->get_result();
            while ($row = $result_exam_analysis->fetch_assoc()) {
                $examAnalysisData[] = $row;
            }
        } else {
            error_log("Execute failed for exam analysis query: " . $stmt_exam_analysis->error);
        }
        $stmt_exam_analysis->close();
    } else {
        error_log("Prepare failed for exam analysis query: " . $conn->error);
    }

    // $conn->close(); // DO NOT CLOSE CONNECTION HERE, CLOSE IT AT THE VERY END OF THE SCRIPT IF NEEDED, OR WHEN ALL DB OPERATIONS ARE DONE
} else {
    error_log("Database connection \$conn not available in admin_dashboard.php");
    $photo = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iODAiIGhlaWdodD0iODAiIHZpZXdCb3g9IjAgMCA4MCA4MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjgwIiBoZWlnaHQ9IjgwIiBmaWxsPSIjQ0NDQ0NDIi8+Cjx0ZXh0IHg9IjQwIiB5PSI0NSIgZm9udC1mYW1pbHk9IkFyaWFsLCBzYW5zLXNlcmlmIiBmb250LXNpemU9IjE4IiBmb250LXdlaWdodD0iYm9sZCIgZmlsbD0iI0ZGRkZGRiIgdGV4dC1hbmNob3I9Im1pZGRsZSI+QUQ8L3RleHQ+Cjwvc3ZnPgo='; // Fallback photo
}

// Determine role name for display (FIXED: removed non-breaking spaces)
$role_name = "Unknown";
switch ($user_role_code) {
    case ROLE_SUPER_ADMIN: $role_name = "Super Admin"; break;
    case ROLE_ADMIN:       $role_name = "Admin";       break;
    case ROLE_TEACHER:     $role_name = "Teacher";     break;
    case ROLE_STUDENT:     $role_name = "Student";     break;
}

// NEW: Process examAnalysisData for overall class performance for JavaScript chart
$classPerformanceForChart = [];
$classScoresSum = [];
$classScoresCount = [];

foreach ($examAnalysisData as $data) {
    $className = $data['class_name'];
    $averageScore = (float)$data['average_score']; // Cast to float

    if (!isset($classScoresSum[$className])) {
        $classScoresSum[$className] = 0;
        $classScoresCount[$className] = 0;
    }
    $classScoresSum[$className] += $averageScore;
    $classScoresCount[$className]++;
}

foreach ($classScoresSum as $className => $sum) {
    $overallAverage = $sum / $classScoresCount[$className];
    $classPerformanceForChart[] = [
        'class_name' => $className,
        'average_score' => round($overallAverage, 2)
    ];
}

// Sort the data by average score (descending) for better visualization
usort($classPerformanceForChart, function($a, $b) {
    return $b['average_score'] <=> $a['average_score'];
});

// Prepare data for Chart.js
$chartLabels = json_encode(array_column($classPerformanceForChart, 'class_name'));
$chartData = json_encode(array_column($classPerformanceForChart, 'average_score'));

// Close the connection at the very end if it's still open
if (isset($conn) && $conn instanceof mysqli && $conn->ping()) {
    $conn->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?php echo $role_name; ?> Dashboard - <?php echo $school_name; ?></title>
    <link rel="stylesheet" href="style.css">
    <link rel="icon" href="<?php echo $school_logo_path; ?>" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        /* ============================================= */
        /* ADMIN DASHBOARD STYLES                       */
        /* ============================================= */
        
        /* Fixed Header and Sidebar Layout */
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
            height: 100vh;
        }

        .dashboard-container {
            display: flex;
            height: 100vh;
            overflow: hidden;
        }

        /* Fixed Sidebar */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            height: 100vh;
            width: 250px;
            overflow-y: auto;
            z-index: 1000;
            transition: transform 0.3s ease;
        }

        .sidebar.collapsed {
            transform: translateX(-250px);
        }

        /* Main Content Area */
        .main-content {
            flex: 1;
            margin-left: 250px;
            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow: hidden;
            transition: margin-left 0.3s ease;
        }

        .sidebar-collapsed .main-content {
            margin-left: 0;
        }

        /* Fixed Header */
        .header {
            position: sticky;
            top: 0;
            z-index: 999;
            background: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        /* Header Content Styling */
        .header-right {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        /* Language Selection Styles */
        .language-select {
            position: relative;
        }

        .language-select select {
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 6px;
            padding: 6px 10px;
            font-size: 0.85em;
            color: #333;
            cursor: pointer;
            min-width: 120px;
            appearance: none;
            background-image: url('data:image/svg+xml;charset=US-ASCII,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 5"><path fill="%23666" d="M2 0L0 2h4zm0 5L0 3h4z"/></svg>');
            background-repeat: no-repeat;
            background-position: right 6px center;
            background-size: 10px;
            transition: all 0.2s ease;
        }

        .language-select select:hover {
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
        }

        .language-select select:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
        }

        /* Scrollable Dashboard Content */
        .dashboard-content {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            padding: 20px;
            background: #f5f5f5;
        }

        /* Scrollbar Styling */
        .dashboard-content::-webkit-scrollbar {
            width: 8px;
        }

        .dashboard-content::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        .dashboard-content::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }

        .dashboard-content::-webkit-scrollbar-thumb:hover {
            background: #555;
        }

        .sidebar::-webkit-scrollbar {
            width: 6px;
        }

        .sidebar::-webkit-scrollbar-track {
            background: transparent;
        }

        .sidebar::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.3);
            border-radius: 3px;
        }

        .sidebar::-webkit-scrollbar-thumb:hover {
            background: rgba(255, 255, 255, 0.5);
        }

        /* Mobile Responsiveness */
        @media (max-width: 768px) {
            .main-content {
                margin-left: 0;
            }
            .dashboard-content {
                padding-bottom: 20px;
            }
            .sidebar {
                transform: translateX(-250px);
            }
            .sidebar.show {
                transform: translateX(0);
            }
        }

        /* Calendar Styles */
        .calendar-card {
            background-color: #fff;
            border-radius: 12px; 
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.08); 
            padding: 25px; 
            display: flex;
            flex-direction: column;
            gap: 20px;
            position: relative;
            overflow: hidden;
            user-select: none;
            width: 100%;
            max-width: 100%;
        }

        .calendar-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap; 
            gap: 15px; 
        }

        .calendar-controls {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .calendar-month-year {
            font-size: 1.8em; 
            font-weight: 600;
            color: #333;
            flex-grow: 1; 
            text-align: center; 
        }

        .calendar-nav-buttons button,
        .calendar-view-buttons button {
            background: none;
            border: 1px solid #ddd;
            padding: 8px 12px;
            border-radius: 6px; 
            cursor: pointer;
            font-size: 0.85em;
            color: #555;
            transition: all 0.2s ease;
            min-width: 36px;
            min-height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .calendar-nav-buttons {
            display: flex;
            gap: 8px; 
            align-items: center;
        }

        .calendar-nav-buttons button:hover,
        .calendar-view-buttons button:hover {
            background-color: #f0f0f0;
            border-color: #ccc;
            transform: scale(1.05);
        }

        .calendar-nav-buttons button:active,
        .calendar-view-buttons button:active {
            transform: scale(0.95);
        }

        .calendar-view-buttons button.active {
            background-color: #007bff; 
            color: #fff;
            border-color: #007bff;
        }

        .calendar-grid {
            display: grid;
            grid-template-columns: repeat(7, 1fr); 
            gap: 8px; 
            text-align: center;
            width: 100%;
            margin: 0 auto;
            user-select: none;
        }

        .day-name {
            font-weight: 600;
            color: #777;
            padding: 10px 0;
            background-color: #f8f9fa; 
            border-radius: 6px;
            min-height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.9em;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .day-number {
            padding: 12px 0;
            font-size: 1.1em;
            color: #333;
            border-radius: 6px;
            transition: background-color 0.2s ease, color 0.2s ease;
            position: relative; 
            cursor: pointer;
            min-height: 35px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 500;
            border: 1px solid transparent;
        }

        .day-number:hover {
            background-color: #e9ecef; 
        }

        .day-number.today {
            background-color: #007bff; 
            color: #fff;
            font-weight: 700;
            box-shadow: 0 2px 8px rgba(0, 123, 255, 0.2); 
        }

        .day-number.selected {
            background-color: #28a745;
            color: #fff;
            font-weight: 600;
            box-shadow: 0 2px 8px rgba(40, 167, 69, 0.3);
        }

        .day-number.today.selected {
            background-color: #007bff;
            box-shadow: 0 2px 8px rgba(0, 123, 255, 0.4);
        }

        .day-number.inactive { 
            color: #ccc;
            opacity: 0.6;
            cursor: default;
        }

        .day-number.inactive:hover {
            background-color: transparent;
        }

        /* Mobile-specific calendar optimizations */
        @media (max-width: 768px) {
            .calendar-card {
                padding: 20px;
                gap: 20px;
                margin: 10px 0;
                width: calc(100vw - 40px);
                max-width: none;
                min-width: 320px;
                box-sizing: border-box;
            }
            .calendar-header {
                flex-direction: column; 
                align-items: stretch; 
                gap: 20px;
            }
            .calendar-controls {
                justify-content: center;
                align-items: center;
                flex-wrap: wrap;
                gap: 15px;
            }
            .calendar-nav-buttons, .calendar-view-buttons {
                justify-content: center; 
            }
            .calendar-month-year {
                margin-bottom: 0; 
                font-size: 1.8em;
                order: -1;
                padding: 10px 0;
                text-align: center;
            }
            .calendar-nav-buttons {
                gap: 10px;
            }
            .calendar-grid {
                gap: 12px;
                touch-action: manipulation;
                padding: 15px 0;
                width: 100%;
                max-width: 100%;
            }
            .day-number {
                padding: 20px 0; 
                font-size: 1.2em;
                min-height: 55px;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 8px;
                transition: all 0.2s ease;
                font-weight: 500;
            }
            .day-name {
                font-size: 0.95em;
                font-weight: 600;
                padding: 14px 0;
                color: #666;
                min-height: 38px;
                display: flex;
                align-items: center;
                justify-content: center;
            }
        }
        
        @media (max-width: 480px) {
            .calendar-card {
                padding: 18px;
                gap: 18px;
                margin: 8px 0;
                width: calc(100vw - 32px);
                min-width: 300px;
            }
            .calendar-grid {
                gap: 10px;
                padding: 12px 0;
            }
            .calendar-month-year {
                font-size: 1.6em;
                padding: 8px 0;
            }
            .calendar-nav-buttons button,
            .calendar-view-buttons button {
                padding: 10px 14px;
                font-size: 0.8em;
                min-width: 40px;
                min-height: 40px;
            }
            .day-number {
                padding: 18px 0; 
                font-size: 1.1em;
                min-height: 50px;
                border-radius: 6px;
            }
            .day-name {
                font-size: 0.9em;
                padding: 12px 0;
                min-height: 35px;
            }
        }
        
        @media (max-width: 360px) {
            .calendar-card {
                padding: 15px;
                gap: 15px;
                margin: 5px 0;
                width: calc(100vw - 25px);
                min-width: 280px;
            }
            .calendar-grid {
                gap: 8px;
                padding: 10px 0;
            }
            .calendar-month-year {
                font-size: 1.4em;
                padding: 6px 0;
            }
            .calendar-nav-buttons button,
            .calendar-view-buttons button {
                padding: 8px 12px;
                font-size: 0.8em;
                min-width: 38px;
                min-height: 38px;
            }
            .day-name, .day-number {
                font-size: 0.85em; 
            }
            .day-number {
                padding: 16px 0;
                min-height: 45px;
                border-radius: 5px;
            }
            .day-name {
                padding: 10px 0;
                min-height: 32px;
            }
        }
        /* New styles for Exam Analysis card */
        .exam-analysis-card {
            background-color: #fff;
            border-radius: 12px;
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.08);
            padding: 25px;
            flex: 1 1 calc(50% - 20px); 
            min-width: 300px; 
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .exam-analysis-card h3 {
            color: #333;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .exam-analysis-card table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }

        .exam-analysis-card th, .exam-analysis-card td {
            border: 1px solid #eee;
            padding: 10px;
            text-align: left;
        }

        .exam-analysis-card th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #555;
        }

        .exam-analysis-card tbody tr:nth-child(even) {
            background-color: #fbfbfb;
        }

        .exam-analysis-card tbody tr:hover {
            background-color: #f0f0f0;
        }
        
        /* Adjust dashboard-sections for new card layout */
        .dashboard-sections {
            display: flex;
            flex-wrap: wrap;
            gap: 20px; 
        }
        
        /* Chart Container Responsive Heights */
        .chart-container {
            position: relative;
            height: 300px;
            width: 100%;
            margin-top: 20px;
            min-height: 300px;
        }

        @media (max-width: 768px) {
            .chart-container {
                height: 250px;
                min-height: 250px;
            }
        }

        @media (max-width: 480px) {
            .chart-container {
                height: 200px;
                min-height: 200px;
            }
        }

        /* Subscription Timer Styles */
        .subscription-timer-container {
            background: linear-gradient(135deg, #ef4444 0%, #f59e0b 25%, #eab308 50%, #84cc16 75%, #22c55e 100%) !important;
            border-radius: 12px;
            padding: 20px 30px;
            margin: 20px 0;
            box-shadow: 0 8px 25px rgba(239, 68, 68, 0.4);
            color: white;
            position: relative;
            overflow: hidden;
            animation: pulseWarning 2s infinite;
        }

        @keyframes pulseWarning {
            0%, 100% { box-shadow: 0 8px 25px rgba(239, 68, 68, 0.4); }
            50% { box-shadow: 0 8px 35px rgba(239, 68, 68, 0.6); }
        }

        .subscription-timer-container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(45deg, transparent 30%, rgba(255,255,255,0.1) 50%, transparent 70%);
            animation: shimmer 3s infinite;
        }

        @keyframes shimmer {
            0% { transform: translateX(-100%); }
            100% { transform: translateX(100%); }
        }

        .subscription-timer-header {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 15px;
            position: relative;
            z-index: 1;
        }

        .subscription-timer-header i {
            font-size: 2.5em;
            animation: bell-ring 1s infinite;
        }

        @keyframes bell-ring {
            0%, 100% { transform: rotate(0deg); }
            10%, 30% { transform: rotate(-10deg); }
            20%, 40% { transform: rotate(10deg); }
            50% { transform: rotate(0deg); }
        }

        .subscription-timer-header h3 {
            margin: 0;
            font-size: 1.5em;
            font-weight: 700;
            text-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }

        .subscription-timer-content {
            position: relative;
            z-index: 1;
        }

        .subscription-timer-content p {
            margin: 0 0 15px 0;
            font-size: 1.1em;
            opacity: 0.95;
        }

        .countdown-display {
            display: flex;
            justify-content: center;
            gap: 15px;
            flex-wrap: wrap;
        }

        .countdown-unit {
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(10px);
            border-radius: 10px;
            padding: 15px 20px;
            min-width: 90px;
            text-align: center;
            border: 2px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
        }

        .countdown-number {
            display: block;
            font-size: 2.5em;
            font-weight: 700;
            line-height: 1;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }

        .countdown-label {
            display: block;
            font-size: 0.9em;
            margin-top: 5px;
            opacity: 0.9;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .timer-expired {
            background: linear-gradient(135deg, #ef4444 0%, #f59e0b 25%, #eab308 50%, #84cc16 75%, #22c55e 100%) !important;
        }

        /* Force gradient on timer container with highest specificity */
        .dashboard-content .subscription-timer-container,
        body .subscription-timer-container {
            background: linear-gradient(135deg, #ef4444 0%, #f59e0b 25%, #eab308 50%, #84cc16 75%, #22c55e 100%) !important;
        }

        .timer-critical {
            animation: pulseWarning 1s infinite, critical-flash 0.5s infinite;
        }

        @keyframes critical-flash {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.8; }
        }

        @media (max-width: 768px) {
            .subscription-timer-container {
                padding: 15px 20px;
            }
            .subscription-timer-header h3 {
                font-size: 1.2em;
            }
            .countdown-unit {
                min-width: 70px;
                padding: 10px 15px;
            }
            .countdown-number {
                font-size: 2em;
            }
            .countdown-label {
                font-size: 0.75em;
            }
        }



        /* ============================================= */
        /* MOBILE STYLES & RESPONSIVE DESIGN           */
        /* ============================================= */

        /* Notification Box Styles */
        .notification-box {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 20px 25px;
            border-radius: 8px;
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
            z-index: 10000;
            display: flex;
            align-items: center;
            gap: 15px;
            max-width: 400px;
            animation: slideInRight 0.3s;
            transition: opacity 0.5s;
        }

        @keyframes slideInRight {
            from {
                transform: translateX(400px);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        .notification-success {
            background-color: #d1fae5;
            color: #065f46;
            border-left: 4px solid #10b981;
        }

        .notification-error {
            background-color: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }

        .notification-box i {
            font-size: 1.5em;
        }

        .notification-close {
            background: none;
            border: none;
            font-size: 1.2em;
            cursor: pointer;
            color: inherit;
            opacity: 0.7;
            margin-left: auto;
        }

        .notification-close:hover {
            opacity: 1;
        }

        /* Mobile Responsive Styles */
        @media (max-width: 768px) {
            .main-content {
                margin-left: 0;
            }
            .dashboard-content {
                padding: 15px 10px 20px;
            }
            .sidebar {
                transform: translateX(-250px);
            }
            .sidebar.show {
                transform: translateX(0);
            }
            
            /* Mobile header adjustments */
            .header-right {
                gap: 10px;
            }
            
            .language-select select {
                font-size: 0.8em;
                padding: 5px 8px;
                min-width: 100px;
            }
        }

        /* Small Mobile Devices */
        @media (max-width: 360px) {
            .dashboard-content {
                padding: 10px 5px 15px;
            }
            
            .header-right {
                gap: 8px;
            }
            
            .language-select select {
                font-size: 0.75em;
                padding: 4px 6px;
                min-width: 90px;
            }
        }

        /* Safe Area Support for Notched Devices */
        @supports(padding: max(0px)) {
            .dashboard-content {
                padding-left: max(20px, env(safe-area-inset-left));
                padding-right: max(20px, env(safe-area-inset-right));
            }
        }

        /* --- Mobile Footer Navigation (Betpawa-Style) --- */
        #mobile-footer-nav {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            height: 70px;
            background: #ffffff;
            border-top: 1px solid #e0e0e0;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
            z-index: 1000;
            padding-bottom: env(safe-area-inset-bottom, 0px);
            display: none; /* Hidden by default on desktop */
        }

        #mobile-footer-nav ul {
            display: flex;
            list-style: none;
            height: 100%;
            margin: 0;
            padding: 0;
        }

        #mobile-footer-nav li {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        #mobile-footer-nav a {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-decoration: none;
            color: #666666;
            font-size: 10px;
            font-weight: 500;
            width: 100%;
            height: 100%;
            transition: all 0.3s ease;
            position: relative;
        }

        #mobile-footer-nav a i {
            font-size: 22px;
            margin-bottom: 4px;
            transition: all 0.3s ease;
        }

        #mobile-footer-nav a.active {
            color: #4f46e5; /* Indigo color for active state */
        }

        #mobile-footer-nav a.active::after {
            content: '';
            position: absolute;
            top: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 30px;
            height: 3px;
            background: #4f46e5;
            border-radius: 2px;
        }
        
        /* --- More Menu Modal --- */
        #more-menu-modal {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            height: auto;
            max-height: 80vh;
            background-color: #fff;
            border-top-left-radius: 20px;
            border-top-right-radius: 20px;
            box-shadow: 0 -4px 15px rgba(0, 0, 0, 0.15);
            z-index: 2000; /* Higher than overlay */
            transform: translateY(100%); /* Start off-screen */
            transition: transform 0.3s ease-in-out;
            padding-bottom: env(safe-area-inset-bottom, 20px);
            overflow-y: auto; /* Enable scrolling for long lists */
            display: none; /* Hide modal initially for all screen sizes */
        }

        #more-menu-modal.show {
            transform: translateY(0); /* Slide into view */
        }
        
        #more-menu-modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
            position: sticky; /* Keep header visible when scrolling list */
            top: 0;
            background-color: #fff;
        }

        #more-menu-close-btn {
            background: none;
            border: none;
            font-size: 1.5em;
            cursor: pointer;
            color: #666;
        }

        #more-menu-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        #more-menu-list li a {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            text-decoration: none;
            color: #333;
            transition: background-color 0.2s ease;
        }

        #more-menu-list li a:hover {
            background-color: #f4f4f4;
        }

        #more-menu-list li a i {
            font-size: 1.2em;
            width: 30px;
            color: #555;
            margin-right: 15px;
        }

        /* Overlay for mobile sidebar and modal */
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1500; /* Higher than the main content */
            display: none; /* Hidden by default */
        }
        .overlay.show {
            display: block; /* Show when active */
        }

        @media (max-width: 768px) {
            #mobile-footer-nav {
                display: block;
            }
            #more-menu-modal {
                display: block;
            }
            /* Adjust main content padding to account for fixed footer */
            .dashboard-content {
                padding-bottom: 90px;
            }
            /* Hide specific items from sidebar on mobile when footer is active */
            .sidebar nav ul li.hide-on-mobile {
                display: none;
            }
        }
        
    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <!-- Sidebar is hidden on mobile via CSS but kept for desktop -->
        <aside class="sidebar" id="sidebar">
            <div class="logo">
                <img src="images/logo.png" alt="divine Logo">
               <br><H8> DIVINE REPORTS</H8></br>
            </div>
            <nav>
                <ul>
                    <li class="active"><a href="admin_dashboard.php" id="dashboardLink"><i class="fas fa-th-large"></i> Dashboard</a></li>
                    <li><a href="admin_calendar.php" id="calendarLink"><i class="far fa-calendar-alt"></i> Calendar</a></li>
                    <li><a href="admin_user_management.php" id="usersLink"><i class="fas fa-users-cog"></i> Users</a></li>
                    <li><a href="admin_students.php" id="studentsLink"><i class="fas fa-user-graduate"></i> Students</a></li>
                    <li><a href="admin_teachers.php" id="teachersLink"><i class="fas fa-chalkboard-teacher"></i> Teachers</a></li>
                    <li class="hide-on-mobile"><a href="admin_classes.php" id="classesLink"><i class="fas fa-chalkboard"></i> Classes</a></li>
                    <li class="hide-on-mobile"><a href="admin_subjects.php" id="subjectsLink"><i class="fas fa-book"></i> Subjects</a></li>
                    <li class="hide-on-mobile"><a href="admin_exams.php" id="examsLink"><i class="fas fa-file-alt"></i> Exams</a></li>
                    <li class="hide-on-mobile"><a href="admin_messages.php" id="messagesLink"><i class="fas fa-envelope"></i> Messages</a></li>
                    <li><a href="admin_reports_printouts.php" id="printoutsLink"><i class="fas fa-print"></i> Printouts</a></li>
                    <li class="hide-on-mobile"><a href="admin_system_settings.php" id="systemSettingsLink"><i class="fas fa-cog"></i> Settings</a></li>
                    <li class="hide-on-mobile"><a href="logout.php" class="logout-btn" id="logoutLink"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
                </ul>
            </nav>
        </aside>

        <div class="main-content">
            <header class="header">
                <button class="menu-toggle" id="menuToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="school-info">
                    <img src="<?php echo $school_logo_path; ?>" alt="<?php echo $school_name; ?> Logo">
                    <h1><?php echo $school_name; ?></h1>
                </div>
                <div class="header-right">
                    <div class="language-select">
                        <select id="languageSelect">
                           <option value="en">🇬🇧 English</option>
                           <option value="lg">🇺🇬 Luganda</option>
                           <option value="sw">🇹🇿 Kiswahili</option>
                        </select>
                    </div>
                    <div class="search-bar">
                        <i class="fas fa-search"></i>
                        <input type="text" placeholder="Search students/data" id="searchPlaceholder">
                    </div>
                    <div class="notifications">
                        <i class="fas fa-bell"></i>
                        <span class="badge">3</span> </div>
                    <div class="user-profile">
                        <img src="<?php echo $photo; ?>" alt="User Photo">
                        <div>
                            <div class="user-name"><?php echo $username; ?></div>
                            <div class="user-email">Logged in as: <?php echo $role_name; ?></div>
                        </div>
                        <i class="fas fa-chevron-down"></i>
                    </div>
                </div>
            </header>

            <div class="dashboard-content">
                <!-- Subscription Timer - Only shown when date is set -->
                <?php if (!empty($subscription_expiry_date)): ?>
                <div class="subscription-timer-container" id="subscriptionTimer" data-expiry="<?php echo $subscription_expiry_date; ?>">
                    <div class="subscription-timer-header">
                        <i class="fas fa-exclamation-triangle"></i>
                        <h3>Subscription Expiry Warning</h3>
                    </div>
                    <div class="subscription-timer-content">
                        <p>Your school's subscription expires on <strong><?php echo date('F j, Y', strtotime($subscription_expiry_date)); ?></strong></p>
                        <div class="countdown-display">
                            <div class="countdown-unit">
                                <span class="countdown-number" id="weeks">0</span>
                                <span class="countdown-label">Weeks</span>
                            </div>
                            <div class="countdown-unit">
                                <span class="countdown-number" id="days">0</span>
                                <span class="countdown-label">Days</span>
                            </div>
                            <div class="countdown-unit">
                                <span class="countdown-number" id="hours">0</span>
                                <span class="countdown-label">Hours</span>
                            </div>
                            <div class="countdown-unit">
                                <span class="countdown-number" id="minutes">0</span>
                                <span class="countdown-label">Minutes</span>
                            </div>
                            <div class="countdown-unit">
                                <span class="countdown-number" id="seconds">0</span>
                                <span class="countdown-label">Seconds</span>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <div class="welcome-banner">
                    <img src="<?php echo $photo; ?>" alt="User Avatar" class="user-avatar">
                    <div class="welcome-text">
                        <h3 id="welcomeHeading">Welcome <?php echo $username; ?>!</h3>
                        <p id="welcomeMessage">Manage all aspects of <?php echo $school_name; ?> school operations.</p>
                    </div>
                    <a href="admin_classes.php" class="action-button" id="welcomeActionButton">My Classes</a>
                </div>

                <div class="dashboard-stats">
                    <div class="stat-card students">
                        <i class="fas fa-user-graduate icon"></i>
                        <div class="count"><?php echo $totalStudents; ?></div>
                        <div class="label" id="totalStudentsLabel">Total Students</div>
                        <a href="admin_students.php" class="arrow"><i class="fas fa-arrow-right"></i></a>
                    </div>
                    <div class="stat-card teachers">
                        <i class="fas fa-chalkboard-teacher icon"></i>
                        <div class="count"><?php echo $totalTeachers; ?></div>
                        <div class="label" id="totalTeachersLabel">Total Teachers</div>
                        <a href="admin_teachers.php" class="arrow"><i class="fas fa-arrow-right"></i></a>
                    </div>
                    <div class="stat-card classes">
                        <i class="fas fa-chalkboard icon"></i>
                        <div class="count"><?php echo $totalClasses; ?></div>
                        <div class="label" id="totalClassesLabel">Total Classes</div>
                        <a href="admin_classes.php" class="arrow"><i class="fas fa-arrow-right"></i></a>
                    </div>
                    <div class="stat-card messages">
                        <i class="fas fa-envelope-open-text icon"></i>
                        <div class="count"><?php echo $unreadMessages; ?></div>
                        <div class="label" id="unreadMessagesLabel">Unread Messages</div>
                        <a href="admin_messages.php" class="arrow"><i class="fas fa-arrow-right"></i></a>
                    </div>
                </div>

                <div class="dashboard-sections">
                    <div class="exam-analysis-card">
                        <h3 id="examAnalysisHeading">Exam Analysis <i class="fas fa-chart-bar"></i></h3>
                        <?php if (empty($examAnalysisData)): ?>
                            <div style="text-align: center; padding: 50px; color: #666; background: #f8f9fa; border-radius: 8px; margin: 20px 0;">
                                <i class="fas fa-chart-bar" style="font-size: 3em; margin-bottom: 15px; color: #ddd;"></i>
                                <p id="noExamDataMessage" style="margin: 0; font-size: 1.1em; font-weight: 500;">No exam analysis data available for your school.</p>
                                <p id="examDataExplanation" style="margin: 10px 0 0 0; font-size: 0.9em; color: #888;">Exam data will appear here once exams are conducted and marks are entered.</p>
                            </div>
                        <?php else: ?>
                            <table>
                                <thead>
                                    <tr>
                                        <th><span id="classHeader">Class</span></th>
                                        <th><span id="subjectHeader">Subject</span></th>
                                        <th><span id="avgScoreHeader">Avg. Score</span></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($examAnalysisData as $data): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($data['class_name']); ?></td>
                                            <td><?php echo htmlspecialchars($data['subject_name']); ?></td>
                                            <td><?php echo htmlspecialchars(round($data['average_score'], 2)); ?>%</td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>

                            <h4 class="mt-4" id="overallPerformanceHeading">Overall Class Performance Graph</h4>
                            <div class="chart-container" id="classPerformanceChartContainer">
                                <canvas id="classPerformanceChart"></canvas> </div>
                        <?php endif; ?>
                    </div>

                    <div class="calendar-card">
                        <div class="calendar-header">
                            <div class="calendar-month-year" id="currentMonthYear"></div>
                            <div class="calendar-controls">
                                <div class="calendar-nav-buttons">
                                    <button id="prevMonth" title="Previous Month"><i class="fas fa-chevron-left"></i></button>
                                    <button id="nextMonth" title="Next Month"><i class="fas fa-chevron-right"></i></button>
                                </div>
                                <div class="calendar-view-buttons">
                                    <button class="active" id="monthViewButton">Month</button>
                                </div>
                            </div>
                        </div>
                        <div class="calendar-grid" id="calendarGrid">
                            <div class="day-name">Mon</div>
                            <div class="day-name">Tue</div>
                            <div class="day-name">Wed</div>
                            <div class="day-name">Thu</div>
                            <div class="day-name">Fri</div>
                            <div class="day-name">Sat</div>
                            <div class="day-name">Sun</div>
                            <!-- Day numbers generated by JavaScript -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Notification Box -->
    <div id="notificationBox" class="notification-box" style="display: none;">
        <i id="notificationIcon" class="fas fa-check-circle"></i>
        <span id="notificationMessage"></span>
        <button onclick="closeNotification()" class="notification-close"><i class="fas fa-times"></i></button>
    </div>

    <!-- Mobile Footer Navigation -->
    <div id="mobile-footer-nav">
        <ul>
            <li>
                <a href="admin_dashboard.php" class="active" data-section="dashboard">
                    <i class="fas fa-th-large"></i>
                    <span id="footerDashboard">Dashboard</span>
                </a>
            </li>
            <li>
                <a href="admin_user_management.php" data-section="user-management">
                    <i class="fas fa-users-cog"></i>
                    <span id="footerUsers">Users</span>
                </a>
            </li>
            <li>
                <a href="admin_students.php" data-section="students">
                    <i class="fas fa-user-graduate"></i>
                    <span id="footerStudents">Students</span>
                </a>
            </li>
            <li>
                <a href="#" id="moreMenuButton" data-section="more">
                    <i class="fas fa-ellipsis-h"></i>
                    <span id="footerMore">More</span>
                </a>
            </li>
        </ul>
    </div>

    <!-- More Menu Modal -->
    <div id="more-menu-modal">
        <div id="more-menu-modal-header">
            <h3 id="moreMenuTitle">More</h3>
            <button id="more-menu-close-btn"><i class="fas fa-times"></i></button>
        </div>
        <ul id="more-menu-list">
            <li><a href="admin_teachers.php"><i class="fas fa-chalkboard-teacher"></i> <span id="moreTeachers">Teachers</span></a></li>
            <li><a href="admin_classes.php"><i class="fas fa-chalkboard"></i> <span id="moreClasses">Classes</span></a></li>
            <li><a href="admin_subjects.php"><i class="fas fa-book"></i> <span id="moreSubjects">Subjects</span></a></li>
            <li><a href="admin_exams.php"><i class="fas fa-file-alt"></i> <span id="moreExams">Exams</span></a></li>
            <li><a href="admin_messages.php"><i class="fas fa-envelope"></i> <span id="moreMessages">Messages</span></a></li>
            <li><a href="admin_reports_printouts.php"><i class="fas fa-print"></i> <span id="morePrintouts">Printouts</span></a></li>
            <li><a href="admin_system_settings.php"><i class="fas fa-cog"></i> <span id="moreSettings">Settings</span></a></li>
            <li class="logout"><a href="logout.php"><i class="fas fa-sign-out-alt"></i> <span id="moreLogout">Logout</span></a></li>
        </ul>
    </div>
    <div class="overlay" id="overlay"></div>

    <script>
        // ============================================
        // ADMIN DASHBOARD JAVASCRIPT FUNCTIONALITY
        // ============================================

        document.addEventListener('DOMContentLoaded', function() {
            const sidebar = document.getElementById('sidebar');
            const menuToggle = document.getElementById('menuToggle');
            const dashboardContainer = document.getElementById('dashboardContainer');
            
            // --- 1. Sidebar Toggle (Primarily for Tablet/Desktop on smaller screens) ---
            if (menuToggle) {
                menuToggle.addEventListener('click', function() {
                    sidebar.classList.toggle('collapsed');
                    dashboardContainer.classList.toggle('sidebar-collapsed');
                });
            }
            
            // --- 2. Calendar Logic (Simple Month View) ---
            const calendarGrid = document.getElementById('calendarGrid');
            const currentMonthYear = document.getElementById('currentMonthYear');
            const prevMonthBtn = document.getElementById('prevMonth');
            const nextMonthBtn = document.getElementById('nextMonth');
            const languageSelect = document.getElementById('languageSelect');
            
            let currentDate = new Date();
            let today = new Date();
            let currentLocale = 'en-US';

            // Language mapping
            const localeMap = {
                'en': 'en-US',
                'lg': 'sw-TZ', // Using Swahili as closest available
                'sw': 'sw-TZ'
            };

            // Day names in different languages
            const dayNames = {
                'en': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                'lg': ['Bal', 'Lwa', 'Lwe', 'Lwa', 'Lwe', 'Lwo', 'Sab'],
                'sw': ['Jum', 'Jua', 'Jub', 'Juk', 'Iju', 'Jmo', 'Jmp']
            };

            function updateDayNames(language) {
                const dayElements = document.querySelectorAll('.day-name');
                const names = dayNames[language] || dayNames['en'];
                dayElements.forEach((element, index) => {
                    element.textContent = names[index];
                });
            }

            function renderCalendar(date) {
                const year = date.getFullYear();
                const month = date.getMonth(); 
                
                // Set the header text with current locale
                currentMonthYear.textContent = date.toLocaleDateString(currentLocale, { 
                    month: 'long', 
                    year: 'numeric' 
                });

                // Clear previous days (leaving day names intact)
                while (calendarGrid.children.length > 7) {
                    calendarGrid.removeChild(calendarGrid.lastChild);
                }

                // Get the day of the week for the first day of the month (0=Sunday, 1=Monday, ...)
                const firstDayOfMonth = new Date(year, month, 1).getDay();
                // Get the number of days in the month
                const daysInMonth = new Date(year, month + 1, 0).getDate();
                // Get the number of days in the previous month for padding
                const daysInPrevMonth = new Date(year, month, 0).getDate();
                
                // Adjust for Monday start (Monday=0, Sunday=6)
                // If firstDayOfMonth is Sunday (0), we treat it as 7 (or 6 blank spaces)
                let startDayIndex = (firstDayOfMonth === 0) ? 6 : firstDayOfMonth - 1; 

                // Add days from the previous month (inactive)
                for (let i = startDayIndex; i > 0; i--) {
                    const day = document.createElement('div');
                    day.classList.add('day-number', 'inactive');
                    day.textContent = daysInPrevMonth - i + 1;
                    calendarGrid.appendChild(day);
                }

                // Add current month days
                for (let day = 1; day <= daysInMonth; day++) {
                    const dayEl = document.createElement('div');
                    dayEl.classList.add('day-number');
                    dayEl.textContent = day;
                    
                    // Check for 'today' marker
                    if (year === today.getFullYear() && month === today.getMonth() && day === today.getDate()) {
                        dayEl.classList.add('today');
                    }
                    
                    // Add touch feedback for mobile
                    dayEl.addEventListener('touchstart', function() {
                        this.style.transform = 'scale(0.95)';
                        this.style.backgroundColor = '#e9ecef';
                    }, { passive: true });
                    
                    dayEl.addEventListener('touchend', function() {
                        this.style.transform = 'scale(1)';
                        if (!this.classList.contains('today')) {
                            this.style.backgroundColor = '';
                        }
                    }, { passive: true });
                    
                    // Add click handler for day selection
                    dayEl.addEventListener('click', function() {
                        // Remove previous selection
                        document.querySelectorAll('.day-number.selected').forEach(el => {
                            el.classList.remove('selected');
                        });
                        // Add selection to current day (if not inactive)
                        if (!this.classList.contains('inactive')) {
                            this.classList.add('selected');
                        }
                    });
                    
                    calendarGrid.appendChild(dayEl);
                }
                
                // Add remaining days from the next month (inactive)
                const totalCells = startDayIndex + daysInMonth;
                const remainingCells = 42 - totalCells; // Max 6 rows * 7 days = 42
                
                for (let i = 1; i <= remainingCells; i++) {
                    const day = document.createElement('div');
                    day.classList.add('day-number', 'inactive');
                    day.textContent = i;
                    calendarGrid.appendChild(day);
                    if (totalCells + i >= 42) break; // Stop after filling 6 rows
                }
            }
            
            // Navigation Handlers
            prevMonthBtn.addEventListener('click', () => {
                currentDate.setMonth(currentDate.getMonth() - 1);
                renderCalendar(currentDate);
            });

            nextMonthBtn.addEventListener('click', () => {
                currentDate.setMonth(currentDate.getMonth() + 1);
                renderCalendar(currentDate);
            });

            // Touch/Swipe gestures for mobile
            let touchStartX = 0;
            let touchEndX = 0;
            let isCalendarSwiping = false;

            calendarGrid.addEventListener('touchstart', (e) => {
                touchStartX = e.changedTouches[0].screenX;
                isCalendarSwiping = true;
            }, { passive: true });

            calendarGrid.addEventListener('touchmove', (e) => {
                if (!isCalendarSwiping) return;
                e.preventDefault(); // Prevent scrolling during swipe
            }, { passive: false });

            calendarGrid.addEventListener('touchend', (e) => {
                if (!isCalendarSwiping) return;
                touchEndX = e.changedTouches[0].screenX;
                handleCalendarSwipe();
                isCalendarSwiping = false;
            }, { passive: true });

            function handleCalendarSwipe() {
                const swipeThreshold = 50; // Minimum distance for a swipe
                const swipeDistance = touchEndX - touchStartX;
                
                if (Math.abs(swipeDistance) > swipeThreshold) {
                    if (swipeDistance > 0) {
                        // Swipe right - go to previous month
                        currentDate.setMonth(currentDate.getMonth() - 1);
                    } else {
                        // Swipe left - go to next month
                        currentDate.setMonth(currentDate.getMonth() + 1);
                    }
                    renderCalendar(currentDate);
                }
            }

            // Keyboard navigation
            document.addEventListener('keydown', (e) => {
                if (e.target.closest('.calendar-card')) {
                    if (e.key === 'ArrowLeft') {
                        e.preventDefault();
                        currentDate.setMonth(currentDate.getMonth() - 1);
                        renderCalendar(currentDate);
                    } else if (e.key === 'ArrowRight') {
                        e.preventDefault();
                        currentDate.setMonth(currentDate.getMonth() + 1);
                        renderCalendar(currentDate);
                    }
                }
            });

            // Comprehensive translations object
            const translations = {
                'en': {
                    // Header and navigation
                    'searchPlaceholder': 'Search students/data',
                    'welcomeHeading': 'Welcome',
                    'welcomeMessage': 'Manage all aspects of school operations.',
                    'welcomeActionButton': 'My Classes',
                    
                    // Dashboard stats
                    'totalStudentsLabel': 'Total Students',
                    'totalTeachersLabel': 'Total Teachers', 
                    'totalClassesLabel': 'Total Classes',
                    'unreadMessagesLabel': 'Unread Messages',
                    
                    // Exam Analysis
                    'examAnalysisHeading': 'Exam Analysis',
                    'noExamDataMessage': 'No exam analysis data available for your school.',
                    'examDataExplanation': 'Exam data will appear here once exams are conducted and marks are entered.',
                    'classHeader': 'Class',
                    'subjectHeader': 'Subject',
                    'avgScoreHeader': 'Avg. Score',
                    'overallPerformanceHeading': 'Overall Class Performance Graph',
                    
                    // Sidebar menu
                    'dashboardLink': 'Dashboard',
                    'calendarLink': 'Calendar',
                    'usersLink': 'Users',
                    'studentsLink': 'Students',
                    'teachersLink': 'Teachers',
                    'classesLink': 'Classes',
                    'subjectsLink': 'Subjects',
                    'examsLink': 'Exams',
                    'messagesLink': 'Messages',
                    'printoutsLink': 'Printouts',
                    'systemSettingsLink': 'Settings',
                    'logoutLink': 'Logout',
                    
                    // Mobile Footer
                    'footerDashboard': 'Dashboard',
                    'footerUsers': 'Users',
                    'footerStudents': 'Students',
                    'footerMore': 'More',
                    'moreMenuTitle': 'More',
                    'moreTeachers': 'Teachers',
                    'moreClasses': 'Classes',
                    'moreSubjects': 'Subjects',
                    'moreExams': 'Exams',
                    'moreMessages': 'Messages',
                    'morePrintouts': 'Printouts',
                    'moreSettings': 'Settings',
                    'moreLogout': 'Logout'
                },
                'lg': {
                    // Header and navigation
                    'searchPlaceholder': 'Noonya abayizi/obubaka',
                    'welcomeHeading': 'Tukusanyukidde',
                    'welcomeMessage': 'Ddukanya ebintu byonna ebikwata ku ssomero.',
                    'welcomeActionButton': 'Ebibiina Byange',
                    
                    // Dashboard stats
                    'totalStudentsLabel': 'Abayizi Bonna',
                    'totalTeachersLabel': 'Abasomesa Bonna',
                    'totalClassesLabel': 'Ebibiina Byonna',
                    'unreadMessagesLabel': 'Obubaka Obutannasomwa',
                    
                    // Exam Analysis
                    'examAnalysisHeading': 'Okwekenenya Ebibuuzo',
                    'noExamDataMessage': 'Tewali bubaka bwa kwekenenya ebibuuzo ku ssomero lyo.',
                    'examDataExplanation': 'Obubaka bwa bibuuzo bujja kulabika wano ebibuuzo bwe binaakozesebwa n\'obubonero bwe bunaateekebwamu.',
                    'classHeader': 'Ekibiina',
                    'subjectHeader': 'Ekisomo',
                    'avgScoreHeader': 'Obubonero Bwa Wakati',
                    'overallPerformanceHeading': 'Ekyapa ky\'Okukola kw\'Ebibiina Byonna',
                    
                    // Sidebar menu
                    'dashboardLink': 'Omubala',
                    'calendarLink': 'Ekalenda',
                    'usersLink': 'Abakozesa',
                    'studentsLink': 'Abayizi',
                    'teachersLink': 'Abasomesa',
                    'classesLink': 'Ebibiina',
                    'subjectsLink': 'Ebyenjigiriza',
                    'examsLink': 'Ebibuuzo',
                    'messagesLink': 'Obubaka',
                    'printoutsLink': 'Ebifulumizibwa',
                    'systemSettingsLink': 'Enteekateeka',
                    'logoutLink': 'Fuluma',
                    
                    // Mobile Footer
                    'footerDashboard': 'Omubala',
                    'footerUsers': 'Abakozesa',
                    'footerStudents': 'Abayizi',
                    'footerMore': 'Ebirala',
                    'moreMenuTitle': 'Ebirala',
                    'moreTeachers': 'Abasomesa',
                    'moreClasses': 'Ebibiina',
                    'moreSubjects': 'Ebyenjigiriza',
                    'moreExams': 'Ebibuuzo',
                    'moreMessages': 'Obubaka',
                    'morePrintouts': 'Ebifulumizibwa',
                    'moreSettings': 'Enteekateeka',
                    'moreLogout': 'Fuluma'
                },
                'sw': {
                    // Header and navigation
                    'searchPlaceholder': 'Tafuta wanafunzi/data',
                    'welcomeHeading': 'Karibu',
                    'welcomeMessage': 'Simamia mambo yote ya shuleni.',
                    'welcomeActionButton': 'Madarasa Yangu',
                    
                    // Dashboard stats
                    'totalStudentsLabel': 'Wanafunzi Wote',
                    'totalTeachersLabel': 'Walimu Wote',
                    'totalClassesLabel': 'Madarasa Yote',
                    'unreadMessagesLabel': 'Ujumbe Usojimsomi',
                    
                    // Exam Analysis
                    'examAnalysisHeading': 'Uchambuzi wa Mitihani',
                    'noExamDataMessage': 'Hakuna data ya uchambuzi wa mitihani kwa shule yako.',
                    'examDataExplanation': 'Data ya mitihani itaonekana hapa baada ya mitihani kufanywa na alama kuingizwa.',
                    'classHeader': 'Darasa',
                    'subjectHeader': 'Somo',
                    'avgScoreHeader': 'Wastani wa Alama',
                    'overallPerformanceHeading': 'Grafu ya Utendaji wa Madarasa Yote',
                    
                    // Sidebar menu
                    'dashboardLink': 'Dashibodi',
                    'calendarLink': 'Kalenda',
                    'usersLink': 'Watumiaji',
                    'studentsLink': 'Wanafunzi',
                    'teachersLink': 'Walimu',
                    'classesLink': 'Madarasa',
                    'subjectsLink': 'Masomo',
                    'examsLink': 'Mitihani',
                    'messagesLink': 'Ujumbe',
                    'printoutsLink': 'Machapisho',
                    'systemSettingsLink': 'Mipangilio',
                    'logoutLink': 'Ondoka',
                    
                    // Mobile Footer
                    'footerDashboard': 'Dashibodi',
                    'footerUsers': 'Watumiaji',
                    'footerStudents': 'Wanafunzi',
                    'footerMore': 'Zaidi',
                    'moreMenuTitle': 'Zaidi',
                    'moreTeachers': 'Walimu',
                    'moreClasses': 'Madarasa',
                    'moreSubjects': 'Masomo',
                    'moreExams': 'Mitihani',
                    'moreMessages': 'Ujumbe',
                    'morePrintouts': 'Machapisho',
                    'moreSettings': 'Mipangilio',
                    'moreLogout': 'Ondoka'
                }
            };
            
            // Function to update all page text
            function updatePageLanguage(language) {
                const trans = translations[language] || translations['en'];
                
                // Update all elements with translatable IDs
                Object.keys(trans).forEach(key => {
                    const element = document.getElementById(key);
                    if (element) {
                        if (key === 'searchPlaceholder') {
                            element.placeholder = trans[key];
                        } else if (key === 'welcomeHeading') {
                            element.innerHTML = `${trans[key]} <?php echo $username; ?>!`;
                        } else if (key === 'welcomeMessage') {
                            element.innerHTML = `${trans[key]} <?php echo $school_name; ?>`;
                        } else if (element.tagName === 'A') {
                            // For sidebar links, update the text after the icon
                            const icon = element.querySelector('i');
                            if (icon) {
                                element.innerHTML = icon.outerHTML + ' ' + trans[key];
                            } else {
                                element.textContent = trans[key];
                            }
                        } else {
                            element.textContent = trans[key];
                        }
                    }
                });
                
                // Update mobile footer and more menu
                updateMobileFooterLanguage(language);
            }
            
            // Function to update mobile footer language
            function updateMobileFooterLanguage(language) {
                const trans = translations[language] || translations['en'];
                
                // Update mobile footer
                const footerElements = ['footerDashboard', 'footerUsers', 'footerStudents', 'footerMore'];
                footerElements.forEach(id => {
                    const element = document.getElementById(id);
                    if (element && trans[id]) {
                        element.textContent = trans[id];
                    }
                });
                
                // Update more menu
                const moreElements = ['moreMenuTitle', 'moreTeachers', 'moreClasses', 'moreSubjects', 'moreExams', 'moreMessages', 'morePrintouts', 'moreSettings', 'moreLogout'];
                moreElements.forEach(id => {
                    const element = document.getElementById(id);
                    if (element && trans[id]) {
                        element.textContent = trans[id];
                    }
                });
            }

            // Language selection handler
            languageSelect.addEventListener('change', function() {
                const selectedLanguage = this.value;
                currentLocale = localeMap[selectedLanguage] || 'en-US';
                
                // Update day names
                updateDayNames(selectedLanguage);
                
                // Re-render calendar with new locale
                renderCalendar(currentDate);
                
                // Update all page text
                updatePageLanguage(selectedLanguage);
            });

            // Initial setup
            updateDayNames('en');
            renderCalendar(currentDate);
            updatePageLanguage('en');

            // --- 4. Mobile Footer Navigation Logic ---
            const moreMenuButton = document.getElementById('moreMenuButton');
            const moreMenuModal = document.getElementById('more-menu-modal');
            const moreMenuCloseBtn = document.getElementById('more-menu-close-btn');
            const overlay = document.getElementById('overlay');

            function toggleMoreMenu(show) {
                if (show) {
                    moreMenuModal.classList.add('show');
                    overlay.classList.add('show');
                    document.body.style.overflow = 'hidden'; // Prevent scrolling background
                } else {
                    moreMenuModal.classList.remove('show');
                    overlay.classList.remove('show');
                    document.body.style.overflow = ''; // Restore scrolling
                }
            }

            if (moreMenuButton) {
                moreMenuButton.addEventListener('click', (e) => {
                    e.preventDefault();
                    toggleMoreMenu(true);
                });
            }

            if (moreMenuCloseBtn) {
                moreMenuCloseBtn.addEventListener('click', () => {
                    toggleMoreMenu(false);
                });
            }

            if (overlay) {
                overlay.addEventListener('click', () => {
                    toggleMoreMenu(false);
                });
            }

            // --- 3. Chart.js Implementation for Exam Analysis ---
            <?php if (!empty($examAnalysisData)): ?>
                const chartLabels = <?php echo $chartLabels; ?>;
                const chartData = <?php echo $chartData; ?>;
                
                console.log('Chart Labels:', chartLabels);
                console.log('Chart Data:', chartData);
                console.log('Chart.js loaded:', typeof Chart !== 'undefined');

                // Wait for Chart.js to be fully loaded
                function initializeChart() {
                    const chartCanvas = document.getElementById('classPerformanceChart');
                    const chartContainer = document.getElementById('classPerformanceChartContainer');
                    
                    console.log('Chart canvas element:', chartCanvas);
                    console.log('Chart container element:', chartContainer);
                    
                    if (chartCanvas && typeof Chart !== 'undefined') {
                        // Ensure the canvas has proper dimensions
                        chartCanvas.style.display = 'block';
                        chartContainer.style.display = 'block';
                        
                        const ctx = chartCanvas.getContext('2d');
                        const chart = new Chart(ctx, {
                        type: 'bar',
                        data: {
                            labels: chartLabels,
                            datasets: [{
                                label: 'Overall Average Score (%)',
                                data: chartData,
                                backgroundColor: [
                                    'rgba(0, 123, 255, 0.8)', // Blue
                                    'rgba(40, 167, 69, 0.8)',  // Green
                                    'rgba(255, 193, 7, 0.8)',  // Yellow
                                    'rgba(220, 53, 69, 0.8)',  // Red
                                    'rgba(108, 117, 125, 0.8)',// Gray
                                    'rgba(23, 162, 184, 0.8)'  // Cyan
                                ],
                                borderColor: [
                                    'rgba(0, 123, 255, 1)',
                                    'rgba(40, 167, 69, 1)',
                                    'rgba(255, 193, 7, 1)',
                                    'rgba(220, 53, 69, 1)',
                                    'rgba(108, 117, 125, 1)',
                                    'rgba(23, 162, 184, 1)'
                                ],
                                borderWidth: 1
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            interaction: {
                                intersect: false,
                                mode: 'index'
                            },
                            plugins: {
                                legend: {
                                    display: false
                                },
                                title: {
                                    display: true,
                                    text: 'Average Performance by Class',
                                    font: {
                                        size: window.innerWidth < 768 ? 14 : 16
                                    }
                                }
                            },
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    max: 100,
                                    title: {
                                        display: true,
                                        text: 'Average Score (%)',
                                        font: {
                                            size: window.innerWidth < 768 ? 12 : 14
                                        }
                                    },
                                    ticks: {
                                        font: {
                                            size: window.innerWidth < 768 ? 10 : 12
                                        }
                                    }
                                },
                                x: {
                                    grid: {
                                        display: false
                                    },
                                    ticks: {
                                        font: {
                                            size: window.innerWidth < 768 ? 10 : 12
                                        }
                                    }
                                }
                            }
                        }
                        });
                        
                        console.log('Chart initialized successfully');
                    } else {
                        console.error('Chart initialization failed - Canvas element not found or Chart.js not loaded');
                        
                        // Show error message in chart container
                        if (chartContainer) {
                            chartContainer.innerHTML = '<div style="text-align: center; padding: 50px; color: #666;"><i class="fas fa-exclamation-triangle"></i><br>Chart failed to load. Please refresh the page.</div>';
                        }
                    }
                }
                
                // Try to initialize immediately, or wait for Chart.js to load
                if (typeof Chart !== 'undefined') {
                    initializeChart();
                } else {
                    // Wait for Chart.js to load
                    let chartLoadAttempts = 0;
                    const chartLoadInterval = setInterval(() => {
                        chartLoadAttempts++;
                        console.log('Waiting for Chart.js to load, attempt:', chartLoadAttempts);
                        
                        if (typeof Chart !== 'undefined') {
                            clearInterval(chartLoadInterval);
                            initializeChart();
                        } else if (chartLoadAttempts > 10) {
                            clearInterval(chartLoadInterval);
                            console.error('Chart.js failed to load after 10 attempts');
                            const chartContainer = document.getElementById('classPerformanceChartContainer');
                            if (chartContainer) {
                                chartContainer.innerHTML = '<div style="text-align: center; padding: 50px; color: #666;"><i class="fas fa-exclamation-triangle"></i><br>Chart library failed to load. Please check your internet connection and refresh the page.</div>';
                            }
                        }
                    }, 500);
                }
            <?php else: ?>
                console.log('No exam analysis data available for chart');
                // The "no data" message is already displayed in the PHP section above
                // No need to modify the chart container here since PHP handles the display
            <?php endif; ?>
        });

        // Subscription Countdown Timer
        let suspensionTriggered = false;

        function suspendSchool() {
            if (suspensionTriggered) return; // Prevent multiple calls
            suspensionTriggered = true;

            // Send AJAX request to suspend the school
            fetch('suspend_school.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=suspend'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    console.log('School suspended automatically');
                    // Optionally redirect to a suspension notice page
                    setTimeout(() => {
                        window.location.href = 'subscription_suspended.php';
                    }, 3000);
                } else {
                    console.error('Failed to suspend school:', data.message);
                }
            })
            .catch(error => {
                console.error('Error suspending school:', error);
            });
        }

        function updateCountdown() {
            const timerContainer = document.getElementById('subscriptionTimer');
            if (!timerContainer) return;

            const expiryDate = new Date(timerContainer.getAttribute('data-expiry') + ' 23:59:59').getTime();
            const now = new Date().getTime();
            const timeLeft = expiryDate - now;

            if (timeLeft <= 0) {
                // Subscription expired
                timerContainer.classList.add('timer-expired');
                document.querySelector('.subscription-timer-content p').innerHTML = '<strong>⚠️ YOUR SUBSCRIPTION HAS EXPIRED!</strong> Your school has been suspended. Please contact support immediately.';
                document.getElementById('weeks').textContent = '0';
                document.getElementById('days').textContent = '0';
                document.getElementById('hours').textContent = '0';
                document.getElementById('minutes').textContent = '0';
                document.getElementById('seconds').textContent = '0';
                
                // Trigger automatic suspension
                suspendSchool();
                return;
            }

            // Calculate time units
            const seconds = Math.floor((timeLeft / 1000) % 60);
            const minutes = Math.floor((timeLeft / 1000 / 60) % 60);
            const hours = Math.floor((timeLeft / (1000 * 60 * 60)) % 24);
            const totalDays = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
            const weeks = Math.floor(totalDays / 7);
            const days = totalDays % 7;

            // Update display
            document.getElementById('weeks').textContent = weeks;
            document.getElementById('days').textContent = days;
            document.getElementById('hours').textContent = hours.toString().padStart(2, '0');
            document.getElementById('minutes').textContent = minutes.toString().padStart(2, '0');
            document.getElementById('seconds').textContent = seconds.toString().padStart(2, '0');

            // Add critical warning if less than 7 days remaining
            if (totalDays < 7) {
                timerContainer.classList.add('timer-critical');
            }
        }

        // Update countdown every second if timer exists
        if (document.getElementById('subscriptionTimer')) {
            updateCountdown();
            setInterval(updateCountdown, 1000);
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        };

        // Notification Functions
        function showNotification(message, type) {
            const notification = document.getElementById('notificationBox');
            const notificationMessage = document.getElementById('notificationMessage');
            const notificationIcon = document.getElementById('notificationIcon');
            
            notificationMessage.textContent = message;
            
            if (type === 'success') {
                notification.className = 'notification-box notification-success';
                notificationIcon.className = 'fas fa-check-circle';
            } else {
                notification.className = 'notification-box notification-error';
                notificationIcon.className = 'fas fa-exclamation-circle';
            }
            
            notification.style.display = 'flex';
            
            // Auto-hide after 5 seconds
            setTimeout(() => {
                notification.style.opacity = '0';
                setTimeout(() => {
                    notification.style.display = 'none';
                    notification.style.opacity = '1';
                }, 500);
            }, 5000);
        }
        
        function closeNotification() {
            const notification = document.getElementById('notificationBox');
            notification.style.opacity = '0';
            setTimeout(() => {
                notification.style.display = 'none';
                notification.style.opacity = '1';
            }, 500);
        };
    </script>
</body>
</html>