<?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', 1);
if (!defined('ROLE_ADMIN')) define('ROLE_ADMIN', 2);
if (!defined('ROLE_TEACHER')) define('ROLE_TEACHER', 3);
if (!defined('ROLE_STUDENT')) define('ROLE_STUDENT', 4);
if (!defined('ROLE_PARENT')) define('ROLE_PARENT', 5);
if (!defined('ROLE_STAFF')) define('ROLE_STAFF', 6);

// 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;
            case ROLE_PARENT:
                header("location: parent_dashboard.php");
                break;
            case ROLE_STAFF:
                header("location: staff_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);

// 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

// 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) : 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD';
            $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 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);
            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';
            } 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);
    }

    // $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_calendar.php");
    $photo = 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD'; // Fallback photo
}

// Determine role name for display
$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;
    case ROLE_PARENT:      $role_name = "Parent";      break;
    case ROLE_STAFF:       $role_name = "Staff";       break;
}

// 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">
    <title><?php echo $role_name; ?> Calendar - <?php echo $school_name; ?></title>
    <link rel="stylesheet" href="style.css">
    <link rel="icon" href="<?php echo $school_logo_path; ?>" type="image/png">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
    
        /* --- 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: #28a745; /* Green 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: #28a745;
            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;
            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;
        }


        /* Mobile responsiveness - Show footer and modal only on mobile devices */
        @media (max-width: 768px) {
            #mobile-footer-nav {
                display: block;
            }
            /* The modal needs to be visible to receive the 'show' class */
            #more-menu-modal {
                display: block;
            }
            /* Adjust main content padding to account for fixed footer */
            .main-content {
                padding-bottom: 90px;
            }
            /* Hide specific items from sidebar on mobile when footer is active (matching hide-on-mobile class) */
            .sidebar nav ul li.hide-on-mobile {
                display: none;
            }
        }

        /* Calendar Specific Styling */
        .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;
            flex: 1 1 100%;
            max-width: 900px;
            margin: 20px auto;
        }

        /* --- Custom Styles for Calendar Days --- */
        .calendar-grid {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            gap: 5px;
            text-align: center;
        }

        .day-name {
            font-weight: 600;
            color: #666;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
            text-transform: uppercase;
            font-size: 12px;
        }

        .day-cell {
            padding: 10px 5px;
            cursor: pointer;
            border-radius: 8px;
            transition: background-color 0.2s;
            position: relative;
            font-weight: 500;
        }

        .day-cell:hover {
            background-color: #f0f0f0;
        }

        .day-cell.empty {
            cursor: default;
            background-color: transparent;
        }

        .day-cell.has-event {
            /* Example for days with events */
            color: #28a745;
            font-weight: 600;
        }

        .event-dot {
            position: absolute;
            bottom: 3px;
            left: 50%;
            transform: translateX(-50%);
            width: 5px;
            height: 5px;
            background-color: #28a745;
            border-radius: 50%;
        }

        /* --- HIGHLIGHT CURRENT DATE --- */
        .day-cell.today {
            background-color: #28a745; /* Green background */
            color: white !important; /* White text */
            font-weight: 700;
            box-shadow: 0 2px 5px rgba(40, 167, 69, 0.4);
        }

        .day-cell.today:hover {
            background-color: #218838; /* Darker green on hover */
        }
        /* ----------------------------- */

    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <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><a href="admin_dashboard.php" id="dashboardLink"><i class="fas fa-th-large"></i> Dashboard</a></li>
                    <li class="active"><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="messagesLinkSidebar"><i class="fas fa-envelope"></i> Messages</a></li>
                    <li class="hide-on-mobile"><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="logoutLinkSidebar"><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">
                <div class="calendar-card">
                    <h2 id="calendarPageTitle">School Calendar</h2> <div class="calendar-header">
                        <div class="calendar-nav-buttons">
                            <button id="prevMonth"><i class="fas fa-chevron-left"></i></button>
                            <button id="nextMonth"><i class="fas fa-chevron-right"></i></button>
                        </div>
                        <div class="calendar-month-year" id="currentMonthYear"></div>
                        <div class="calendar-view-buttons">
                            <button class="active" id="monthViewButton">Month</button>
                            </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>
                    </div>
                    <div class="events-list">
                        <h4 id="upcomingEventsTitle">Upcoming Events</h4>
                        <ul id="eventsList">
                            <li>No upcoming events.</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div id="mobile-footer-nav">
        <ul>
            <li>
                <a href="admin_dashboard.php" data-section="dashboard">
                    <i class="fas fa-th-large"></i>
                    <span>Dashboard</span>
                </a>
            </li>
            <li>
                <a href="admin_calendar.php" class="active" data-section="calendar">
                    <i class="far fa-calendar-alt"></i>
                    <span>Calendar</span>
                </a>
            </li>
            <li>
                <a href="admin_students.php" data-section="students">
                    <i class="fas fa-user-graduate"></i>
                    <span>Students</span>
                </a>
            </li>
            <li>
                <a href="#" id="moreMenuButton" data-section="more">
                    <i class="fas fa-ellipsis-h"></i>
                    <span>More</span>
                </a>
            </li>
        </ul>
    </div>


    <div id="more-menu-modal">
        <div id="more-menu-modal-header">
            <h3>More Menu</h3>
            <button id="more-menu-close-btn"><i class="fas fa-times"></i></button>
        </div>
        <ul id="more-menu-list">
            <li><a href="admin_classes.php"><i class="fas fa-chalkboard"></i> Classes</a></li>
            <li><a href="admin_subjects.php"><i class="fas fa-book"></i> Subjects</a></li>
            <li><a href="admin_exams.php"><i class="fas fa-file-alt"></i> Exams</a></li>
            <li><a href="admin_messages.php"><i class="fas fa-envelope"></i> Messages</a></li>
            <li><a href="admin_reports_printouts.php"><i class="fas fa-print"></i> Printouts</a></li>
            <li><a href="admin_system_settings.php"><i class="fas fa-cog"></i> Settings</a></li>
            <li class="logout"><a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
        </ul>
    </div>

    <div class="overlay" id="overlay"></div>

    <script>
        const schoolNameForJs = "<?php echo $school_name_for_js; ?>";
        const currentUsername = "<?php echo $username; ?>";

        // --- START: Mobile Footer Modal 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
            }
        }

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

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

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

        // Optional: Close modal on screen resize (when switching from mobile to desktop)
        window.addEventListener('resize', () => {
            if (window.innerWidth > 768) {
                toggleMoreMenu(false);
            }
        });
        // --- END: Mobile Footer Modal Logic ---


        const translations = {
            en: {
                dashboard: "Dashboard",
                calendar: "Calendar",
                users: "Users",
                students: "Students",
                teachers: "Teachers",
                classes: "Classes",
                subjects: "Subjects",
                exams: "Exams",
                messages: "Messages",
                printouts: "Printouts",
                systemSettings: "Settings",
                logout: "Logout",
                searchPlaceholder: "Search students/data",
                welcomePrefix: "Welcome ",
                welcomeSuffix: "!",
                manageSchoolOperations: `Manage all aspects of ${schoolNameForJs} school operations.`,
                totalStudents: "Total Students",
                totalTeachers: "Total Teachers",
                totalClasses: "Total Classes",
                unreadMessages: "Unread Messages",
                examAnalysis: "Exam Analysis",
                classLabel: "Class",
                subjectLabel: "Subject",
                avgScoreLabel: "Avg. Score",
                overallClassPerformance: "Overall Class Performance Graph",
                noExamData: "No exam analysis data available for your school.",
                noChartData: "No data available to generate class performance graph.",
                monthView: "Month",
                mon: "Mon",
                tue: "Tue",
                wed: "Wed",
                thu: "Thu",
                fri: "Fri",
                sat: "Sat",
                sun: "Sun",
                monthNames: ["January", "February", "March", "April", "May", "June",
                              "July", "August", "September", "October", "November", "December"],
                dayNamesShort: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
                chartAvgScoreLabel: "Average Score (%)",
                chartClassLabel: "Class Name",
                chartTitle: "Overall Average Performance Per Class",
                myClasses: "My Classes",
                grades: "Grades",
                profile: "Profile",
                calendarPageTitle: "School Calendar", // New translation for calendar page title
                upcomingEventsTitle: "Upcoming Events", // New translation for upcoming events title
                noUpcomingEvents: "No upcoming events.", // New translation for no events message
                moreMenu: "More Menu" // New translation for More Menu modal
            },
            lg: {
                dashboard: "Akasengejja",
                calendar: "Kkalenda",
                users: "Abakozesa",
                students: "Abayizi",
                teachers: "Abalimu",
                classes: "Ebibiina",
                subjects: "Essomo",
                exams: "Eby'ekigezo",
                messages: "Ebiwandiiko",
                printouts: "Ebiwandiise",
                systemSettings: "Enteekateeka",
                logout: "Ggalawo",
                searchPlaceholder: "Noonya abayizi/ebitabo",
                welcomePrefix: "Mukulike ",
                welcomeSuffix: "!",
                manageSchoolOperations: `Ddukanya ebikolebwa mu ssomero lya ${schoolNameForJs}.`,
                totalStudents: "Abayizi Bonna",
                totalTeachers: "Abalimu Bonna",
                totalClasses: "Ebibiina Byonna",
                unreadMessages: "Ebiwandiiko Ebitasomeddwa",
                examAnalysis: "Okwekenneenya Eby'ekigezo",
                classLabel: "Ekibiina",
                subjectLabel: "Essomo",
                avgScoreLabel: "Avg. Obubonero",
                overallClassPerformance: "Ekiragiro ky'Abayizi mu Bibina Byonna",
                noExamData: "Tewali nteekateeka ya kigezo ekyesomeddwa ku ssomero lyo.",
                noChartData: "Tewali data ya kuyisa ya bibiina ya kulaga.",
                monthView: "Omwezi",
                mon: "Bwe",
                tue: "Bbi",
                wed: "Dda",
                thu: "Nna",
                fri: "Maa",
                sat: "Muka",
                sun: "Ssab",
                monthNames: ["Gatonnya", "Mukutulansanja", "Mugula", "Kafumuula", "Muzigo", "Ssekkukulu",
                              "Kasambula", "Muziziko", "Mutunda", "Mukulukusa", "Museenene", "Mengo"],
                dayNamesShort: ["Bwe", "Bbi", "Dda", "Nna", "Maa", "Muka", "Ssab"],
                chartAvgScoreLabel: "Avg. Obubonero (%)",
                chartClassLabel: "Erinnya ly'Ekibiina",
                chartTitle: "Avg. Obubonero Obulambirira bwa Bibina Byonna",
                myClasses: "Ebibiina Byange",
                grades: "Eby'obubonero",
                profile: "Enkola",
                calendarPageTitle: "Kkalenda y'Essomero",
                upcomingEventsTitle: "Eby'Okuja",
                noUpcomingEvents: "Tewali by'okujja.",
                moreMenu: "Akasengejja Akalala"
            },
            sw: {
                dashboard: "Dashibodi",
                calendar: "Kalenda",
                users: "Watumiaji",
                students: "Wanafunzi",
                teachers: "Walimu",
                classes: "Madarasa",
                subjects: "Masomo",
                exams: "Mitihani",
                messages: "Ujumbe",
                printouts: "Machapisho",
                systemSettings: "Mipangilio",
                logout: "Toka",
                searchPlaceholder: "Tafuta wanafunzi/data",
                welcomePrefix: "Karibu ",
                welcomeSuffix: "!",
                manageSchoolOperations: `Dhibiti masuala yote ya shughuli za shule ya ${schoolNameForJs}.`,
                totalStudents: "Jumla ya Wanafunzi",
                totalTeachers: "Jumla ya Walimu",
                totalClasses: "Jumla ya Madarasa",
                unreadMessages: "Ujumbe Usiosomwa",
                examAnalysis: "Uchambuzi wa Mitihani",
                classLabel: "Darasa",
                subjectLabel: "Somo",
                avgScoreLabel: "Wastani Alama",
                overallClassPerformance: "Grafu ya Utendaji wa Jumla wa Darasa",
                noExamData: "Hakuna data ya uchambuzi wa mitihani inayopatikana kwa shule yako.",
                noChartData: "Hakuna data inayopatikana ya kutengeneza grafu ya utendaji wa darasa.",
                monthView: "Mwezi",
                mon: "Jtatu",
                tue: "Jne",
                wed: "Jtano",
                thu: "Alh",
                fri: "Iju",
                sat: "Jmosi",
                sun: "Jpili",
                monthNames: ["Januari", "Februari", "Machi", "Aprili", "Mei", "Juni",
                              "Julai", "Agosti", "Septemba", "Oktoba", "Novemba", "Desemba"],
                dayNamesShort: ["Jtatu", "Jne", "Jtano", "Alh", "Iju", "Jmosi", "Jpili"],
                chartAvgScoreLabel: "Wastani Alama (%)",
                chartClassLabel: "Jina la Darasa",
                chartTitle: "Wastani wa Utendaji wa Jumla kwa Kila Darasa",
                myClasses: "Madarasa Yangu",
                grades: "Alama",
                profile: "Profaili",
                calendarPageTitle: "Kalenda ya Shule",
                upcomingEventsTitle: "Matukio Yanayokuja",
                noUpcomingEvents: "Hakuna matukio yanayokuja.",
                moreMenu: "Menyu Zaidi"
            }
        };

        // Function to apply translations
        function applyTranslations(lang) {
            const t = translations[lang];

            // Sidebar Navigation
            document.getElementById('dashboardLink').innerHTML = `<i class="fas fa-th-large"></i> ${t.dashboard}`;
            document.getElementById('calendarLink').innerHTML = `<i class="far fa-calendar-alt"></i> ${t.calendar}`;
            document.getElementById('usersLink').innerHTML = `<i class="fas fa-users-cog"></i> ${t.users}`;
            document.getElementById('studentsLink').innerHTML = `<i class="fas fa-user-graduate"></i> ${t.students}`;
            document.getElementById('teachersLink').innerHTML = `<i class="fas fa-chalkboard-teacher"></i> ${t.teachers}`;
            
            // Mobile Modal Menu Links (These need to be targeted on the modal list as well)
            const modalLinks = document.getElementById('more-menu-list').getElementsByTagName('a');
            
            // Function to update links in both sidebar and modal
            function updateLink(id, iconClass, text) {
                const sidebarLink = document.getElementById(id);
                if (sidebarLink) sidebarLink.innerHTML = `<i class="${iconClass}"></i> ${text}`;

                // Find and update the corresponding modal link by matching the href
                for (let link of modalLinks) {
                    if (link.getAttribute('href') === (sidebarLink ? sidebarLink.getAttribute('href') : '')) {
                        link.innerHTML = `<i class="${iconClass}"></i> ${text}`;
                    }
                }
            }

            updateLink('classesLink', 'fas fa-chalkboard', t.classes);
            updateLink('subjectsLink', 'fas fa-book', t.subjects);
            updateLink('examsLink', 'fas fa-file-alt', t.exams);
            updateLink('messagesLinkSidebar', 'fas fa-envelope', t.messages);
            updateLink('printoutsLink', 'fas fa-print', t.printouts);
            updateLink('systemSettingsLink', 'fas fa-cog', t.systemSettings);
            updateLink('logoutLinkSidebar', 'fas fa-sign-out-alt', t.logout);


            // Header
            document.getElementById('searchPlaceholder').placeholder = t.searchPlaceholder;

            // Calendar Page Specific
            document.getElementById('calendarPageTitle').textContent = t.calendarPageTitle;
            document.getElementById('monthViewButton').textContent = t.monthView;
            document.getElementById('upcomingEventsTitle').textContent = t.upcomingEventsTitle;
            document.getElementById('more-menu-modal-header').querySelector('h3').textContent = t.moreMenu;

            // Update the 'no upcoming events' message
            const eventsList = document.getElementById('eventsList');
            if (eventsList && eventsList.children.length === 1 && (eventsList.children[0].textContent.includes("No upcoming events") || eventsList.children[0].textContent.includes("Tewali by'okujja") || eventsList.children[0].textContent.includes("Hakuna matukio yanayokuja"))) {
                 eventsList.innerHTML = `<li>${t.noUpcomingEvents}</li>`;
            }


            // Update day names in calendar grid dynamically
            const dayNames = document.querySelectorAll('.calendar-grid .day-name');
            if (dayNames.length === 7) {
                dayNames[0].textContent = t.dayNamesShort[0]; // Mon
                dayNames[1].textContent = t.dayNamesShort[1]; // Tue
                dayNames[2].textContent = t.dayNamesShort[2]; // Wed
                dayNames[3].textContent = t.dayNamesShort[3]; // Thu
                dayNames[4].textContent = t.dayNamesShort[4]; // Fri
                dayNames[5].textContent = t.dayNamesShort[5]; // Sat
                dayNames[6].textContent = t.dayNamesShort[6]; // Sun
            }

            // Mobile Footer (Update the hardcoded ones - 'More' is updated by button text)
            const footerLinks = document.getElementById('mobile-footer-nav').getElementsByTagName('a');
            for (let link of footerLinks) {
                const section = link.getAttribute('data-section');
                if (section === 'dashboard') link.querySelector('span').textContent = t.dashboard;
                if (section === 'calendar') link.querySelector('span').textContent = t.calendar;
                if (section === 'students') link.querySelector('span').textContent = t.students;
                if (section === 'more') link.querySelector('span').textContent = t.moreMenu;
            }
        } 

        // Language Selector Logic
        const languageSelect = document.getElementById('languageSelect');
        const savedLang = localStorage.getItem('appLang') || 'en'; // Default to English

        // Set the initial selected option
        languageSelect.value = savedLang;
        applyTranslations(savedLang);

        languageSelect.addEventListener('change', function() {
            const newLang = this.value;
            localStorage.setItem('appLang', newLang);
            applyTranslations(newLang);
            // Re-render the calendar when translations change
            renderCalendar(currentDate); 
        });


        // --- START: Calendar Rendering Logic (Placeholder) ---

        const calendarGrid = document.getElementById('calendarGrid');
        const currentMonthYearElement = document.getElementById('currentMonthYear');
        const prevMonthButton = document.getElementById('prevMonth');
        const nextMonthButton = document.getElementById('nextMonth');

        let currentDate = new Date(); // Start with today's date
        const today = new Date(); // Constant for today's date reference

        function renderCalendar(date) {
            const year = date.getFullYear();
            const month = date.getMonth();
            const t = translations[localStorage.getItem('appLang') || 'en']; // Get current translations

            // Update Month/Year display
            currentMonthYearElement.textContent = `${t.monthNames[month]} ${year}`;

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

            // Get the first day of the month (0=Sunday, 1=Monday, ..., 6=Saturday)
            const firstDayOfMonth = new Date(year, month, 1).getDay();
            // Adjust to make Monday (1) the start of the week (Mon=0, Tue=1, ..., Sun=6)
            let startDay = firstDayOfMonth === 0 ? 6 : firstDayOfMonth - 1;

            // Get number of days in the month
            const daysInMonth = new Date(year, month + 1, 0).getDate();

            // Add leading empty cells
            for (let i = 0; i < startDay; i++) {
                const emptyCell = document.createElement('div');
                emptyCell.classList.add('day-cell', 'empty');
                calendarGrid.appendChild(emptyCell);
            }

            // Add day cells
            for (let day = 1; day <= daysInMonth; day++) {
                const dayCell = document.createElement('div');
                dayCell.classList.add('day-cell');
                dayCell.textContent = day;
                
                // ** LOGIC TO HIGHLIGHT CURRENT DATE **
                if (day === today.getDate() && month === today.getMonth() && year === today.getFullYear()) {
                    dayCell.classList.add('today');
                }

                // Add sample events for visual demo
                if (day % 5 === 0) {
                    dayCell.classList.add('has-event');
                    const eventDot = document.createElement('div');
                    eventDot.classList.add('event-dot');
                    dayCell.appendChild(eventDot);
                }

                dayCell.addEventListener('click', () => {
                    alert(`Clicked day ${day}, fetching events...`);
                    // Here you would fetch events for the selected day via AJAX
                });

                calendarGrid.appendChild(dayCell);
            }
        }

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

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

        // Initial render
        renderCalendar(currentDate);

        // --- END: Calendar Rendering Logic (Placeholder) ---


        // --- START: Sidebar/Menu Toggle Logic ---
        const menuToggle = document.getElementById('menuToggle');
        const sidebar = document.getElementById('sidebar');
        const dashboardContainer = document.getElementById('dashboardContainer');

        menuToggle.addEventListener('click', () => {
            sidebar.classList.toggle('collapsed');
            dashboardContainer.classList.toggle('sidebar-collapsed');
        });

        // Close sidebar when clicking outside on mobile
        dashboardContainer.addEventListener('click', (e) => {
            if (window.innerWidth <= 768 && !sidebar.contains(e.target) && !menuToggle.contains(e.target) && !sidebar.classList.contains('collapsed')) {
                sidebar.classList.add('collapsed');
                dashboardContainer.classList.remove('sidebar-collapsed');
            }
        });

        // Initialize sidebar state based on screen size
        if (window.innerWidth <= 768) {
            sidebar.classList.add('collapsed');
        }
        // --- END: Sidebar/Menu Toggle Logic ---

    </script>
</body>
</html>