<?php
session_start(); // Start the session to access session variables

require_once 'config.php'; // Include the database configuration file. Ensure this path is correct.

// Define role constants.
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); // Student role is 4
if (!defined('ROLE_PARENT')) define('ROLE_PARENT', 5);
if (!defined('ROLE_STAFF')) define('ROLE_STAFF', 6);

// --- Language Handling and Localization Dictionary ---
$available_languages = ['en', 'lug', 'sw']; // English, Luganda, Kiswahili
$default_language = 'en';

// Check if a language is selected via GET parameter; otherwise, use session or default.
if (isset($_GET['lang']) && in_array($_GET['lang'], $available_languages)) {
    $_SESSION['lang'] = $_GET['lang'];
} elseif (!isset($_SESSION['lang'])) {
    $_SESSION['lang'] = $default_language;
}

$current_lang = $_SESSION['lang'];

/**
 * Loads language-specific strings for the student dashboard.
 * @param string $lang The current language code.
 * @return array An associative array of localized strings.
 */
function load_language_data($lang) {
    $data = [
        'en' => [
            'dashboard_title_prefix' => 'Student Dashboard',
            'sidebar_dashboard' => 'Dashboard',
            'sidebar_profile' => 'Profile',
            'sidebar_reports' => 'Reports',
            'sidebar_assignments' => 'Assignments',
            'sidebar_messages' => 'Messages',
            'sidebar_settings' => 'Settings',
            'sidebar_logout' => 'Logout',
            'school_name_not_found' => 'School Name Not Found',
            'search_placeholder' => 'Search records',
            'welcome_message_prefix' => 'Welcome',
            'welcome_message_suffix' => '!',
            'logged_in_as' => 'Logged in as:',
            'divine_reports' => 'DIVINE REPORTS',
            'manage_records_text' => 'View your academic progress, assignments, and communications for',
            'view_my_reports_button' => 'View My Reports', // New button for students
            'stat_subjects_label' => 'Subjects with Marks', // Updated label
            'stat_upcoming_assignments_label' => 'Upcoming Assignments', // Student specific stat
            'stat_unread_messages_label' => 'Unread Messages', // Student specific stat
            'stat_overall_score_label' => 'Overall Avg. Score', // Student specific stat
            'school_announcements_heading' => 'School Announcements',
            'view_all_button' => 'View All',
            'no_announcements' => 'No new school announcements.',
            'calendar_month_button' => 'Month',
            'calendar_week_button' => 'Week',
            'calendar_day_button' => 'Day',
            'day_mon' => 'Mon', 'day_tue' => 'Tue', 'day_wed' => 'Wed', 'day_thu' => 'Thu',
            'day_fri' => 'Fri', 'day_sat' => 'Sat', 'day_sun' => 'Sun',
        ],
        'lug' => [
            'dashboard_title_prefix' => 'Diisiboodi y\'Omuyizi',
            'sidebar_dashboard' => 'Diisiboodi',
            'sidebar_profile' => 'Purofayiro',
            'sidebar_reports' => 'Lipooti',
            'sidebar_assignments' => 'Ebitongole',
            'sidebar_messages' => 'Obubaka',
            'sidebar_settings' => 'Enteekateeka',
            'sidebar_logout' => 'Log Out',
            'school_name_not_found' => 'Erinnya ly\'Essomero Terinnaba Kulabika',
            'search_placeholder' => 'Noonya ebisaakaate',
            'welcome_message_prefix' => 'Mpulira Olamusiddwa',
            'welcome_message_suffix' => '!',
            'logged_in_as' => 'Oyinze okukakasa nga:',
            'divine_reports' => 'RIPOTA ZA MUNGU',
            'manage_records_text' => 'Laba enkulaakulana yo, ebitongole, n\'ebitongole byo mu',
            'view_my_reports_button' => 'Laba Lipooti Zange',
            'stat_subjects_label' => 'Eby\'okusomesebwa Ebyakolebwa', // Updated label
            'stat_upcoming_assignments_label' => 'Ebitongole Ebirindiridde',
            'stat_unread_messages_label' => 'Obubaka Obutatukirwako',
            'stat_overall_score_label' => 'Akaadi yonna wakati',
            'school_announcements_heading' => 'Amanyisibwa g\'Essomero',
            'view_all_button' => 'Laba Byonna',
            'no_announcements' => 'Tewali manyisibwa mafulu.',
            'calendar_month_button' => 'Omwezi',
            'calendar_week_button' => 'Wiki',
            'calendar_day_button' => 'Olunaku',
            'day_mon' => 'Bal', 'day_tue' => 'Bbi', 'day_wed' => 'Ggo', 'day_thu' => 'Nna',
            'day_fri' => 'Muu', 'day_sat' => 'Lwa', 'day_sun' => 'San',
        ],
        'sw' => [
            'dashboard_title_prefix' => 'Dashibodi ya Mwanafunzi',
            'sidebar_dashboard' => 'Dashibodi',
            'sidebar_profile' => 'Wasifu',
            'sidebar_reports' => 'Ripoti',
            'sidebar_assignments' => 'Kazi',
            'sidebar_messages' => 'Ujumbe',
            'sidebar_settings' => 'Mipangilio',
            'sidebar_logout' => 'Ondoka',
            'school_name_not_found' => 'Jina la Shule Halikupatikana',
            'search_placeholder' => 'Tafuta rekodi',
            'welcome_message_prefix' => 'Karibu',
            'welcome_message_suffix' => '!',
            'logged_in_as' => 'Umeingia kama:',
            'divine_reports' => 'RIPOTI ZA MUNGU',
            'manage_records_text' => 'Tazama maendeleo yako ya masomo, kazi, na mawasiliano kwa',
            'view_my_reports_button' => 'Tazama Ripoti Zangu',
            'stat_subjects_label' => 'Masomo yenye Alama', // Updated label
            'stat_upcoming_assignments_label' => 'Kazi Zijazo',
            'stat_unread_messages_label' => 'Ujumbe Usiomaswa',
            'stat_overall_score_label' => 'Wastani wa Alama',
            'school_announcements_heading' => 'Matangazo ya Shule',
            'view_all_button' => 'Tazama Yote',
            'no_announcements' => 'Hakuna matangazo mapya ya shule.',
            'calendar_month_button' => 'Mwezi',
            'calendar_week_button' => 'Wiki',
            'calendar_day_button' => 'Siku',
            'day_mon' => 'Jt', 'day_tue' => 'Jnn', 'day_wed' => 'Jtatu', 'day_thu' => 'Jne',
            'day_fri' => 'Ij', 'day_sat' => 'Jmo', 'day_sun' => 'Jpili',
        ]
    ];
    return $data[$lang] ?? $data['en']; // Fallback to English if language not found
}

$_L = load_language_data($current_lang);

/**
 * Function to check the user's role and redirect if they are unauthorized to access the current page.
 * @param int $required_role_code The role code required to access this page.
 */
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_ADMIN:
                header("location: admin_dashboard.php");
                break;
            case ROLE_TEACHER:
                header("location: teacher_dashboard.php");
                break;
            default:
                header("location: login.php");
                break;
        }
        exit;
    }
}

check_role_access(ROLE_STUDENT); // Ensure only students can access this page

$currentPage = 'dashboard';

$student_user_id = $_SESSION["id"];
$school_id = $_SESSION["school_id"];
$username = htmlspecialchars($_SESSION["username"]);
$user_role_code = $_SESSION["role"];

$student_photo = "images/default_student_photo.png"; // Default path
$school_name = $_L['school_name_not_found'];
$school_logo_path = "images/default_school_logo.png"; // Default path

$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;
}

// Initialize student-specific dashboard statistics
$totalSubjectsWithMarks = 0; // Updated variable name
$upcomingAssignments = 0;
$unreadMessages = 0;
$overallAverageScore = 0;
$announcements = []; // Array to store fetched school-specific announcements.

// Ensure $conn (database connection) is available
if (isset($conn) && $conn instanceof mysqli) {
    // Fetch student photo and school details for header and welcome banner
    $sql_student_details = "SELECT photo FROM users WHERE id = ?";
    if ($stmt_student = $conn->prepare($sql_student_details)) {
        $stmt_student->bind_param("i", $student_user_id);
        if ($stmt_student->execute()) {
            $stmt_student->bind_result($photo_db);
            if ($stmt_student->fetch()) {
                $student_photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'images/default_student_photo.png';
            }
        }
        $stmt_student->close();
    }

    $sql_school_details = "SELECT school_name, logo FROM schools WHERE school_id = ?";
    if ($stmt_school = $conn->prepare($sql_school_details)) {
        $stmt_school->bind_param("i", $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);
                $school_logo_path = !empty($school_logo_db) ? htmlspecialchars($school_logo_db) : 'images/default_school_logo.png';
            }
        }
        $stmt_school->close();
    }

    // --- Student Specific Dashboard Statistics ---

    // 1. Total Subjects with Marks for the student (replaces total subjects via enrollments)
    // Counts distinct subjects for which the student has recorded marks.
    $sql_total_subjects_with_marks = "
        SELECT COUNT(DISTINCT subject_id)
        FROM marks
        WHERE student_id = ? AND school_id = ?
    ";
    if ($stmt_subjects = $conn->prepare($sql_total_subjects_with_marks)) {
        $stmt_subjects->bind_param("ii", $student_user_id, $school_id);
        if ($stmt_subjects->execute()) {
            $stmt_subjects->bind_result($count);
            $stmt_subjects->fetch();
            $totalSubjectsWithMarks = $count;
        } else {
            error_log("Execute failed for total subjects with marks query: " . $stmt_subjects->error);
        }
        $stmt_subjects->close();
    } else {
        error_log("Prepare failed for total subjects with marks query: " . $conn->error);
    }

    // --- START: Upcoming Assignments for the student ---
    // This section now correctly queries the 'assignments' table by joining with 'students' and 'streams' tables.
    $student_current_class_id = null;
    $student_stream_name = null;
    $student_stream_id = null;

    // 1. Get the student's current_class_id and stream_id from the 'users' table
    $sql_student_class_stream = "SELECT class_id, stream_id FROM users WHERE id = ? AND school_id = ?";
    if ($stmt_student_cs = $conn->prepare($sql_student_class_stream)) {
        $stmt_student_cs->bind_param("ii", $student_user_id, $school_id);
        if ($stmt_student_cs->execute()) {
            $stmt_student_cs->bind_result($class_id_db, $stream_id_db);
            if ($stmt_student_cs->fetch()) {
                $student_current_class_id = $class_id_db;
                $student_stream_id = $stream_id_db;
            }
        }
        $stmt_student_cs->close();
    } else {
        error_log("Prepare failed for student class and stream query: " . $conn->error);
    }

    if ($student_current_class_id !== null && $student_stream_id !== null) {
        // 2. Get the stream name from the 'streams' table using stream_id
        $sql_get_stream_name = "SELECT stream_name FROM streams WHERE stream_id = ? AND school_id = ?";
        if ($stmt_stream_name = $conn->prepare($sql_get_stream_name)) {
            $stmt_stream_name->bind_param("ii", $student_stream_id, $school_id);
            if ($stmt_stream_name->execute()) {
                $stmt_stream_name->bind_result($stream_name_db);
                if ($stmt_stream_name->fetch()) {
                    $student_stream_name = $stream_name_db;
                }
            }
            $stmt_stream_name->close();
        } else {
            error_log("Prepare failed for getting stream_name: " . $conn->error);
        }
    } else {
        error_log("Student class_id or stream_id not found for user_id: " . $student_user_id . ". Cannot proceed with assignments query.");
    }


    if ($student_stream_id !== null) {
        // 3. Query the 'assignments' table using the fetched stream_id
        $sql_upcoming_assignments = "
            SELECT COUNT(assignment_id)
            FROM assignments
            WHERE stream_id = ? AND school_id = ? AND due_date >= CURDATE();
        ";
        if ($stmt_assignments = $conn->prepare($sql_upcoming_assignments)) {
            $stmt_assignments->bind_param("ii", $student_stream_id, $school_id);
            if ($stmt_assignments->execute()) {
                $stmt_assignments->bind_result($count);
                $stmt_assignments->fetch();
                $upcomingAssignments = $count;
            } else {
                error_log("Execute failed for upcoming assignments query: " . $stmt_assignments->error);
            }
            $stmt_assignments->close();
        } else {
            error_log("Prepare failed for upcoming assignments query: " . $conn->error);
        }
    } else {
        error_log("Could not determine student's stream information for user_id: " . $student_user_id . ". Upcoming assignments count defaulted to 0.");
    }
    // --- END: Upcoming Assignments for the student ---


    // 3. Count Unread Messages for the student
    $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", $student_user_id, $school_id);
        if ($stmt_messages->execute()) {
            $stmt_messages->bind_result($count);
            $stmt_messages->fetch();
            $unreadMessages = $count;
        } else {
            error_log("Execute failed for unread messages query: " . $stmt_messages->error);
        }
        $stmt_messages->close();
    } else {
        error_log("Prepare failed for unread messages query: " . $conn->error);
    }

    // 4. Calculate Overall Average Score
    // This aggregates marks from the 'marks' table for the student.
    $sql_overall_average_score = "
        SELECT AVG(mark)
        FROM marks
        WHERE student_id = ? AND school_id = ?
    ";
    if ($stmt_avg_score = $conn->prepare($sql_overall_average_score)) {
        $stmt_avg_score->bind_param("ii", $student_user_id, $school_id);
        if ($stmt_avg_score->execute()) {
            $stmt_avg_score->bind_result($avg_score_db);
            $stmt_avg_score->fetch();
            $overallAverageScore = round($avg_score_db ?? 0, 2); // Round to 2 decimal places, default to 0
        } else {
            error_log("Execute failed for overall average score query: " . $stmt_avg_score->error);
        }
        $stmt_avg_score->close();
    } else {
        error_log("Prepare failed for overall average score query: " . $conn->error);
    }

    // Fetch School-Specific Announcements.
    $sql_announcements = "SELECT title, content, created_at FROM announcements WHERE school_id = ? ORDER BY created_at DESC LIMIT 5";
    if ($stmt_announcements = $conn->prepare($sql_announcements)) {
        $stmt_announcements->bind_param("i", $school_id);
        if ($stmt_announcements->execute()) {
            $result_announcements = $stmt_announcements->get_result();
            while ($row = $result_announcements->fetch_assoc()) {
                $announcements[] = $row;
            }
        } else {
            error_log("Execute failed for announcements query for Student: " . $stmt_announcements->error);
        }
        $stmt_announcements->close();
    } else {
        error_log("Prepare failed for announcements query for Student: " . $conn->error);
    }


    $conn->close(); // Close the database connection after all data has been fetched.
} else {
    error_log("Database connection \$conn not available in student_dashboard.php");
    $student_photo = 'images/default_student_photo.png'; // Set default photo if no DB connection.
}

// --- PHP for Dynamic Calendar Generation (Same as Teacher Dashboard) ---
$current_day = date('d');
$current_month_num = date('m');
$current_year = date('Y');
$num_days_in_month = cal_days_in_month(CAL_GREGORIAN, $current_month_num, $current_year);
$first_day_of_month_timestamp = mktime(0, 0, 0, $current_month_num, 1, $current_year);
$first_day_of_week = date('N', $first_day_of_month_timestamp);
$current_month_name = date('F', $first_day_of_month_timestamp);

?>

<!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; ?> <?php echo $_L['dashboard_title_prefix']; ?> - <?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/5.15.4/css/all.min.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        /* Fixed Header and Sidebar Styles */
        .dashboard-container {
            display: flex;
            height: 100vh;
            overflow: hidden;
        }

        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            height: 100vh;
            width: 250px;
            overflow-y: auto;
            z-index: 1000;
            box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
        }

        .main-content {
            margin-left: 250px;
            width: calc(100% - 250px);
            height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .header {
            position: fixed;
            top: 0;
            left: 250px;
            right: 0;
            z-index: 999;
            background-color: #ffffff;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        /* Scrollable content area with fade effect */
        .content-wrapper {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            margin-top: 80px;
            position: relative;
        }

        /* Fade overlay at the top */
        .content-wrapper::before {
            content: '';
            position: sticky;
            top: 0;
            left: 0;
            right: 0;
            height: 40px;
            background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0) 100%);
            pointer-events: none;
            z-index: 10;
        }

        /* Smooth scrolling */
        .content-wrapper {
            scroll-behavior: smooth;
        }

        /* Custom scrollbar */
        .content-wrapper::-webkit-scrollbar {
            width: 8px;
        }

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

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

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

        /* Responsive adjustments */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
                transition: transform 0.3s ease-in-out;
            }

            .sidebar.active {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
                width: 100%;
            }

            .header {
                left: 0;
            }
        }

        /* Dashboard Specific Styles */
        .welcome-banner {
            background-image: url('https://via.placeholder.com/1200x200/F5F5F5/888888?text=Your+Banner+Image+Here');
            background-size: cover;
            background-position: center;
            border-radius: 10px;
            padding: 40px;
            color: #333;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            position: relative;
        }

        .welcome-banner::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(255, 255, 255, 0.8);
            border-radius: 10px;
        }

        .welcome-banner * {
            position: relative;
            z-index: 1;
        }

        .welcome-banner .user-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 20px;
            border: 3px solid #2c253f;
        }

        .welcome-banner .welcome-text h3 {
            font-size: 24px;
            margin-bottom: 5px;
            color: #2c253f;
        }

        .welcome-banner .welcome-text p {
            font-size: 16px;
            color: #555;
        }

        .welcome-banner .action-button {
            background-color: #28a745;
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            text-decoration: none;
            font-weight: 500;
            transition: background-color 0.3s ease;
        }

        .welcome-banner .action-button:hover {
            background-color: #218838;
        }

        .dashboard-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .stat-card {
            background-color: #fff;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            position: relative;
            overflow: hidden;
            transition: transform 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
        }

        .stat-card .icon {
            font-size: 45px;
            color: #71b7e6;
            margin-bottom: 15px;
        }

        .stat-card.subjects-marks .icon { color: #5bc0de; }
        .stat-card.assignments .icon { color: #5cb85c; }
        .stat-card.messages .icon { color: #f0ad4e; }
        .stat-card.score .icon { color: #0275d8; }

        .stat-card .count {
            font-size: 32px;
            font-weight: 700;
            color: #333;
            margin-bottom: 5px;
        }

        .stat-card .label {
            font-size: 16px;
            color: #777;
            margin-bottom: 15px;
        }

        .stat-card .arrow {
            position: absolute;
            bottom: 15px;
            right: 20px;
            font-size: 20px;
            color: #aaa;
            transition: color 0.3s ease;
        }
        .stat-card:hover .arrow {
            color: #2c253f;
        }

        .dashboard-sections {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 20px;
        }

        .upcoming-events-card, .calendar-card {
            background-color: #fff;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .upcoming-events-card h3, .calendar-card h3 {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .upcoming-events-card .add-event-btn {
            background-color: #71b7e6;
            color: white;
            padding: 8px 15px;
            border-radius: 5px;
            text-decoration: none;
            font-size: 14px;
            transition: background-color 0.3s ease;
        }

        .upcoming-events-card .add-event-btn:hover {
            background-color: #4a90e2;
        }

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

        .calendar-nav-buttons button {
            background: none;
            border: 1px solid #eee;
            padding: 5px 10px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            color: #777;
            transition: background-color 0.3s ease;
        }

        .calendar-nav-buttons button:hover {
            background-color: #f0f0f0;
        }

        .calendar-month-year {
            font-size: 18px;
            font-weight: 600;
        }

        .calendar-view-buttons button {
            background-color: #eee;
            border: none;
            padding: 5px 12px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            margin-left: 5px;
            color: #555;
            transition: background-color 0.3s ease;
        }

        .calendar-view-buttons button.active,
        .calendar-view-buttons button:hover {
            background-color: #2c253f;
            color: white;
        }

        .calendar-grid {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            gap: 5px;
            font-size: 14px;
            text-align: center;
        }

        .calendar-grid .day-name {
            font-weight: 600;
            padding: 8px 0;
            color: #555;
        }

        .calendar-grid .day-number {
            padding: 10px 0;
            border-radius: 5px;
            background-color: #fdfdfd;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }

        .calendar-grid .day-number:hover {
            background-color: #e0e0e0;
        }

        .calendar-grid .day-number.today {
            background-color: #71b7e6;
            color: white;
            font-weight: 600;
        }

        .calendar-grid .day-number.selected {
            background-color: #2c253f;
            color: white;
            font-weight: 600;
        }

        @media (max-width: 992px) {
            .dashboard-sections {
                grid-template-columns: 1fr;
            }
        }
    
        /* Hide specific items from sidebar on mobile when footer is active */
        .hide-on-mobile {
            display: list-item;
        }

        /* --- Mobile Footer Navigation --- */
        #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;
        }

        #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;
        }

        #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;
            transform: translateY(100%);
            transition: transform 0.3s ease-in-out;
            padding-bottom: env(safe-area-inset-bottom, 20px);
            overflow-y: auto;
            display: none;
        }

        #more-menu-modal.show {
            transform: translateY(0);
        }
        
        #more-menu-modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
            position: sticky;
            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;
            display: none;
        }
        
        .overlay.show {
            display: block;
        }

        /* Responsive adjustments */
        @media (max-width: 768px) {
            #mobile-footer-nav {
                display: block;
            }
            
            #more-menu-modal {
                display: block;
            }
            
            /* Adjust main content padding to account for fixed footer */
            .content-wrapper {
                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">
        <aside class="sidebar" id="sidebar">
            <div class="logo">
                <img src="images/logo.png" alt="divine Logo">
                <?php echo $_L['divine_reports']; ?>
            </div>
            <nav>
                <ul>
                    <li class="<?php echo ($currentPage == 'dashboard' ? 'active' : ''); ?>"><a href="student_dashboard.php"><i class="fas fa-th-large"></i> <?php echo $_L['sidebar_dashboard']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'profile' ? 'active' : ''); ?>"><a href="student_profile.php"><i class="fas fa-user-circle"></i> <?php echo $_L['sidebar_profile']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'reports' ? 'active' : ''); ?>"><a href="student_reports.php"><i class="fas fa-file-invoice"></i> <?php echo $_L['sidebar_reports']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'assignments' ? 'active' : ''); ?>"><a href="student_assignments.php"><i class="fas fa-file-alt"></i> <?php echo $_L['sidebar_assignments']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'messages' ? 'active' : ''); ?>"><a href="student_messages.php"><i class="fas fa-envelope"></i> <?php echo $_L['sidebar_messages']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'settings' ? 'active' : ''); ?>"><a href="student_settings.php"><i class="fas fa-cog"></i> <?php echo $_L['sidebar_settings']; ?></a></li>
                    <li><a href="logout.php"><i class="fas fa-sign-out-alt"></i> <?php echo $_L['sidebar_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" onerror="this.onerror=null;this.src='images/default_school_logo.png';">
                    <h1><?php echo $school_name; ?></h1>
                </div>
                <div class="header-right">
                    <div class="language-select">
                        <select id="languageSelector" onchange="changeLanguage(this.value)">
                           <option value="en" <?php if ($current_lang === 'en') echo 'selected'; ?>>🇬🇧 English</option>
                           <option value="lug" <?php if ($current_lang === 'lug') echo 'selected'; ?>>🇺🇬 Luganda</option>
                           <option value="sw" <?php if ($current_lang === 'sw') echo 'selected'; ?>>🇹🇿 Kiswahili</option>
                        </select>
                    </div>
                    <div class="search-bar">
                        <i class="fas fa-search"></i>
                        <input type="text" placeholder="<?php echo $_L['search_placeholder']; ?>">
                    </div>
                    <div class="notifications">
                        <i class="fas fa-bell"></i>
                        <span class="badge"><?php echo $unreadMessages; ?></span>
                    </div>
                    <div class="user-profile">
                        <img src="<?php echo $student_photo; ?>" alt="User Photo" onerror="this.onerror=null;this.src='images/default_student_photo.png';">
                        <div>
                            <div class="user-name"><?php echo $username; ?></div>
                            <div class="user-email"><?php echo $_L['logged_in_as']; ?> <?php echo $role_name; ?></div>
                        </div>
                        <i class="fas fa-chevron-down"></i>
                    </div>
                </div>
            </header>

            <div class="content-wrapper">
                <div class="dashboard-content" style="padding: 20px;">
                    <div class="welcome-banner">
                        <img src="<?php echo $student_photo; ?>" alt="User Avatar" class="user-avatar" onerror="this.onerror=null;this.src='images/default_student_photo.png';">
                        <div class="welcome-text">
                            <h3><?php echo $_L['welcome_message_prefix']; ?> <?php echo $username; ?><?php echo $_L['welcome_message_suffix']; ?></h3>
                            <p><?php echo $_L['manage_records_text']; ?> <?php echo $school_name; ?>.</p>
                        </div>
                        <a href="student_reports.php" class="action-button"><?php echo $_L['view_my_reports_button']; ?></a>
                    </div>

                    <div class="dashboard-stats">
                        <div class="stat-card subjects-marks">
                            <i class="fas fa-book-open icon"></i>
                            <div class="count"><?php echo $totalSubjectsWithMarks; ?></div>
                            <div class="label"><?php echo $_L['stat_subjects_label']; ?></div>
                            <a href="student_reports.php" class="arrow"><i class="fas fa-arrow-right"></i></a>
                        </div>
                        <div class="stat-card assignments">
                            <i class="fas fa-clipboard-list icon"></i>
                            <div class="count"><?php echo $upcomingAssignments; ?></div>
                            <div class="label"><?php echo $_L['stat_upcoming_assignments_label']; ?></div>
                            <a href="student_assignments.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"><?php echo $_L['stat_unread_messages_label']; ?></div>
                            <a href="student_messages.php" class="arrow"><i class="fas fa-arrow-right"></i></a>
                        </div>
                        <div class="stat-card score">
                            <i class="fas fa-chart-line icon"></i>
                            <div class="count"><?php echo $overallAverageScore; ?>%</div>
                            <div class="label"><?php echo $_L['stat_overall_score_label']; ?></div>
                            <a href="student_reports.php" class="arrow"><i class="fas fa-arrow-right"></i></a>
                        </div>
                    </div>

                    <div class="dashboard-sections">
                        <div class="upcoming-events-card">
                            <h3><?php echo $_L['school_announcements_heading']; ?> <a href="#" class="add-event-btn"><i class="fas fa-info-circle"></i> <?php echo $_L['view_all_button']; ?></a></h3>
                            <?php if (empty($announcements)): ?>
                                <p><?php echo $_L['no_announcements']; ?></p>
                            <?php else: ?>
                                <?php foreach ($announcements as $announcement): ?>
                                    <div class="announcement-item" style="margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #eee;">
                                        <h4 style="font-size: 16px; font-weight: 600; margin-bottom: 8px; color: #333;"><?php echo htmlspecialchars($announcement['title']); ?></h4>
                                        <p style="color: #666; line-height: 1.6; margin-bottom: 8px;"><?php echo nl2br(htmlspecialchars($announcement['content'])); ?></p>
                                        <span class="announcement-date" style="font-size: 12px; color: #999;"><?php echo date('F j, Y', strtotime($announcement['created_at'])); ?></span>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                        <div class="calendar-card">
                            <div class="calendar-header">
                                <div class="calendar-nav-buttons">
                                    <button><i class="fas fa-chevron-left"></i></button>
                                    <button><i class="fas fa-chevron-right"></i></button>
                                </div>
                                <div class="calendar-month-year"><?php echo $current_month_name . ' ' . $current_year; ?></div>
                                <div class="calendar-view-buttons">
                                    <button class="active"><?php echo $_L['calendar_month_button']; ?></button>
                                    <button><?php echo $_L['calendar_week_button']; ?></button>
                                    <button><?php echo $_L['calendar_day_button']; ?></button>
                                </div>
                            </div>
                            <div class="calendar-grid">
                                <div class="day-name"><?php echo $_L['day_mon']; ?></div>
                                <div class="day-name"><?php echo $_L['day_tue']; ?></div>
                                <div class="day-name"><?php echo $_L['day_wed']; ?></div>
                                <div class="day-name"><?php echo $_L['day_thu']; ?></div>
                                <div class="day-name"><?php echo $_L['day_fri']; ?></div>
                                <div class="day-name"><?php echo $_L['day_sat']; ?></div>
                                <div class="day-name"><?php echo $_L['day_sun']; ?></div>

                                <?php
                                // Loop to create empty day cells for days before the 1st of the month
                                for ($i = 1; $i < $first_day_of_week; $i++) {
                                    echo '<div class="day-number"></div>';
                                }
                                // Loop to create day cells for each day of the month
                                for ($day = 1; $day <= $num_days_in_month; $day++) {
                                    // Add 'today' class if it's the current day, month, and year
                                    $class = ($day == $current_day && $current_month_num == date('m') && $current_year == date('Y')) ? 'today' : '';
                                    echo '<div class="day-number ' . $class . '">' . $day . '</div>';
                                }
                                ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        function changeLanguage(lang) {
            window.location.href = `?lang=${lang}`;
        }

        document.addEventListener('DOMContentLoaded', function() {
            const menuToggle = document.getElementById('menuToggle');
            const sidebar = document.getElementById('sidebar');
            const dashboardContainer = document.getElementById('dashboardContainer');

            if (menuToggle && sidebar && dashboardContainer) {
                menuToggle.addEventListener('click', function() {
                    sidebar.classList.toggle('active');
                    dashboardContainer.classList.toggle('sidebar-open');
                });

                dashboardContainer.addEventListener('click', function(event) {
                    if (sidebar.classList.contains('active') && !sidebar.contains(event.target) && !menuToggle.contains(event.target)) {
                        sidebar.classList.remove('active');
                        dashboardContainer.classList.remove('sidebar-open');
                    }
                });
            } else {
                console.error("Menu toggle, sidebar, or dashboard container elements for responsive behavior not found.");
            }
        });
    
        // --- START: Mobile Footer Modal Logic ---
        document.addEventListener('DOMContentLoaded', function() {
            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';
                } else {
                    moreMenuModal.classList.remove('show');
                    overlay.classList.remove('show');
                    document.body.style.overflow = '';
                }
            }

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

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

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

            // Set active state for mobile footer based on current page
            const currentPage = '<?php echo $currentPage; ?>';
            const mobileNavLinks = document.querySelectorAll('#mobile-footer-nav a[data-section]');
            mobileNavLinks.forEach(link => {
                const section = link.getAttribute('data-section');
                if (section === currentPage) {
                    link.classList.add('active');
                }
            });
        });
        // --- END: Mobile Footer Modal Logic ---

    </script>    <!-- Mobile Footer Navigation -->
    <div id="mobile-footer-nav">
        <ul>
            <li>
                <a href="student_dashboard.php" data-section="dashboard" id="mobileNavDashboard">
                    <i class="fas fa-th-large"></i>
                    <span><?php echo $_L['sidebar_dashboard']; ?></span>
                </a>
            </li>
            <li>
                <a href="student_profile.php" data-section="profile" id="mobileNavProfile">
                    <i class="fas fa-user"></i>
                    <span><?php echo $_L['sidebar_profile']; ?></span>
                </a>
            </li>
            <li>
                <a href="student_messages.php" data-section="messages" id="mobileNavMessages">
                    <i class="fas fa-envelope"></i>
                    <span><?php echo $_L['sidebar_messages']; ?></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>

    <!-- More Menu Modal -->
    <div id="more-menu-modal">
        <div id="more-menu-modal-header">
            <h3>More</h3>
            <button id="more-menu-close-btn"><i class="fas fa-times"></i></button>
        </div>
        <ul id="more-menu-list">
            <li><a href="student_reports.php"><i class="fas fa-file-alt"></i> <?php echo $_L['sidebar_reports']; ?></a></li>
            <li><a href="student_assignments.php"><i class="fas fa-tasks"></i> <?php echo $_L['sidebar_assignments']; ?></a></li>
            <li><a href="student_settings.php"><i class="fas fa-cog"></i> <?php echo $_L['sidebar_settings']; ?></a></li>
            <li class="logout"><a href="logout.php"><i class="fas fa-sign-out-alt"></i> <?php echo $_L['sidebar_logout']; ?></a></li>
        </ul>
    </div>

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


</body>
</html>