<?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);
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.
 * @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 settings',
            'welcome_message_prefix' => 'Welcome',
            'welcome_message_suffix' => '!',
            'logged_in_as' => 'Logged in as:',
            'divine_reports' => 'DIVINE REPORTS',
            'settings_heading' => 'Settings',
            'change_password_heading' => 'Change Password',
            'old_password_label' => 'Old Password',
            'new_password_label' => 'New Password',
            'confirm_password_label' => 'Confirm New Password',
            'update_password_button' => 'Update Password',
            'language_settings_heading' => 'Language Settings',
            'select_language_label' => 'Select Language',
            'profile_photo_heading' => 'Profile Photo',
            'current_photo_label' => 'Current Photo',
            'upload_new_photo_label' => 'Upload New Photo',
            'choose_file_button' => 'Choose File',
            'update_photo_button' => 'Update Photo',
            'success_message' => 'Settings updated successfully!',
            'error_message' => 'Error updating settings. Please try again.',
            'password_mismatch_error' => 'New password and confirm password do not match.',
            'old_password_incorrect' => 'Old password is incorrect.',
            'photo_upload_error' => 'Error uploading photo.',
            'invalid_file_type' => 'Invalid file type. Only JPEG, PNG, GIF allowed.'
        ],
        '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 enteekateeka',
            'welcome_message_prefix' => 'Mpulira Olamusiddwa',
            'welcome_message_suffix' => '!',
            'logged_in_as' => 'Oyinze okukakasa nga:',
            'divine_reports' => 'RIPOTA ZA MUNGU',
            'settings_heading' => 'Enteekateeka',
            'change_password_heading' => 'Kyusa Ekikoomo',
            'old_password_label' => 'Ekikoomo Ekikadde',
            'new_password_label' => 'Ekikoomo Ekipya',
            'confirm_password_label' => 'Kakas Ekikoomo Ekipya',
            'update_password_button' => 'Ffula Ekikoomo',
            'language_settings_heading' => 'Enteekateeka z\'Olulimi',
            'select_language_label' => 'Londa Olulimi',
            'profile_photo_heading' => 'Ekifaananyi ky\'Ebimukwatako',
            'current_photo_label' => 'Ekifaananyi Ekisangamu',
            'upload_new_photo_label' => 'Teekawo Ekifaananyi Ekipya',
            'choose_file_button' => 'Londa Fayiro',
            'update_photo_button' => 'Ffula Ekifaananyi',
            'success_message' => 'Enteekateeka zifuliddwa bulungi!',
            'error_message' => 'Waliwo ekifuuse bubi mu kufuna enteekateeka. Gezaako nate.',
            'password_mismatch_error' => 'Ekikoomo ekipya n\'ekikakasa tebikwatagana.',
            'old_password_incorrect' => 'Ekikoomo ekikadde si kituufu.',
            'photo_upload_error' => 'Waliwo ekifuuse bubi mu kuteekawo ekifaananyi.',
            'invalid_file_type' => 'Fayiro si yatuufu. JPEG, PNG, GIF zokka zemukkirizibwa.'
        ],
        '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 mipangilio',
            'welcome_message_prefix' => 'Karibu',
            'welcome_message_suffix' => '!',
            'logged_in_as' => 'Umeingia kama:',
            'divine_reports' => 'RIPOTI ZA MUNGU',
            'settings_heading' => 'Mipangilio',
            'change_password_heading' => 'Badilisha Nenosiri',
            'old_password_label' => 'Nenosiri la Kale',
            'new_password_label' => 'Nenosiri Mpya',
            'confirm_password_label' => 'Thibitisha Nenosiri Mpya',
            'update_password_button' => 'Sasisha Nenosiri',
            'language_settings_heading' => 'Mipangilio ya Lugha',
            'select_language_label' => 'Chagua Lugha',
            'profile_photo_heading' => 'Picha ya Wasifu',
            'current_photo_label' => 'Picha ya Sasa',
            'upload_new_photo_label' => 'Pakia Picha Mpya',
            'choose_file_button' => 'Chagua Faili',
            'update_photo_button' => 'Sasisha Picha',
            'success_message' => 'Mipangilio imesasishwa kwa mafanikio!',
            'error_message' => 'Kuna hitilafu wakati wa kusasisha mipangilio. Tafadhali jaribu tena.',
            'password_mismatch_error' => 'Nenosiri jipya na uthibitisho wa nenosiri hazifanani.',
            'old_password_incorrect' => 'Nenosiri la zamani si sahihi.',
            'photo_upload_error' => 'Kuna hitilafu wakati wa kupakia picha.',
            'invalid_file_type' => 'Aina ya faili si sahihi. Aina za faili zinazoruhusiwa ni JPEG, PNG, GIF pekee.'
        ]
    ];
    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);

$currentPage = 'settings';

$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";
$school_name = $_L['school_name_not_found'];
$school_logo_path = "images/default_school_logo.png";

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

// Handle form submissions for settings
$message = '';
$message_type = ''; // 'success' or 'error'

if (isset($conn) && $conn instanceof mysqli) {
    // Fetch current student data for displaying photo and other info
    $sql_current_user = "SELECT photo, password FROM users WHERE id = ?";
    if ($stmt_current_user = $conn->prepare($sql_current_user)) {
        $stmt_current_user->bind_param("i", $student_user_id);
        $stmt_current_user->execute();
        $stmt_current_user->bind_result($current_photo_db, $hashed_password_db);
        $stmt_current_user->fetch();
        $stmt_current_user->close();
        $student_photo = !empty($current_photo_db) ? htmlspecialchars($current_photo_db) : 'images/default_student_photo.png';
    }


    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (isset($_POST['action']) && $_POST['action'] === 'change_password') {
            $old_password = $_POST['old_password'] ?? '';
            $new_password = $_POST['new_password'] ?? '';
            $confirm_password = $_POST['confirm_password'] ?? '';

            if ($new_password !== $confirm_password) {
                $message = $_L['password_mismatch_error'];
                $message_type = 'error';
            } elseif (!password_verify($old_password, $hashed_password_db)) {
                $message = $_L['old_password_incorrect'];
                $message_type = 'error';
            } else {
                $new_hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                $sql_update_password = "UPDATE users SET password = ? WHERE id = ?";
                if ($stmt_update_password = $conn->prepare($sql_update_password)) {
                    $stmt_update_password->bind_param("si", $new_hashed_password, $student_user_id);
                    if ($stmt_update_password->execute()) {
                        $message = $_L['success_message'];
                        $message_type = 'success';
                    } else {
                        $message = $_L['error_message'] . " (DB Error: " . $stmt_update_password->error . ")";
                        $message_type = 'error';
                    }
                    $stmt_update_password->close();
                }
            }
        } elseif (isset($_POST['action']) && $_POST['action'] === 'upload_photo') {
            if (isset($_FILES['profile_photo']) && $_FILES['profile_photo']['error'] === UPLOAD_ERR_OK) {
                $file_tmp_name = $_FILES['profile_photo']['tmp_name'];
                $file_name = $_FILES['profile_photo']['name'];
                $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                $allowed_ext = ['jpeg', 'jpg', 'png', 'gif'];

                if (in_array($file_ext, $allowed_ext)) {
                    $new_file_name = 'uploads/student_photos/student_' . uniqid() . '.' . $file_ext;
                    if (move_uploaded_file($file_tmp_name, $new_file_name)) {
                        $sql_update_photo = "UPDATE users SET photo = ? WHERE id = ?";
                        if ($stmt_update_photo = $conn->prepare($sql_update_photo)) {
                            $stmt_update_photo->bind_param("si", $new_file_name, $student_user_id);
                            if ($stmt_update_photo->execute()) {
                                $student_photo = htmlspecialchars($new_file_name); // Update displayed photo
                                $message = $_L['success_message'];
                                $message_type = 'success';
                            } else {
                                $message = $_L['error_message'] . " (DB Error: " . $stmt_update_photo->error . ")";
                                $message_type = 'error';
                            }
                            $stmt_update_photo->close();
                        }
                    } else {
                        $message = $_L['photo_upload_error'];
                        $message_type = 'error';
                    }
                } else {
                    $message = $_L['invalid_file_type'];
                    $message_type = 'error';
                }
            } else {
                $message = $_L['photo_upload_error'];
                $message_type = 'error';
            }
        }
    }

    // Fetch school details
    $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();
    }

    $conn->close();
} else {
    error_log("Database connection \$conn not available in student_settings.php");
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $_L['sidebar_settings']; ?> - <?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;
            }
        }

        .settings-card {
            background-color: #ffffff;
            border-radius: 0.75rem;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            padding: 2rem;
            margin-bottom: 2rem;
        }
        .form-group {
            margin-bottom: 1.5rem;
        }
        .form-group label {
            display: block;
            font-size: 0.875rem;
            color: #475569;
            font-weight: 500;
            margin-bottom: 0.5rem;
        }
        .form-group input[type="password"],
        .form-group input[type="file"],
        .form-group select {
            display: block;
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid #cbd5e0;
            border-radius: 0.375rem;
            font-size: 1rem;
            color: #334155;
            background-color: #ffffff;
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
        }
        .form-group input[type="password"]:focus,
        .form-group input[type="file"]:focus,
        .form-group select:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.25);
        }
        .btn-primary {
            background-color: #2563eb;
            color: #ffffff;
            padding: 0.75rem 1.5rem;
            border-radius: 0.5rem;
            font-weight: 600;
            transition: background-color 0.15s ease-in-out;
        }
        .btn-primary:hover {
            background-color: #1d4ed8;
        }
        .alert {
            padding: 1rem;
            border-radius: 0.375rem;
            margin-bottom: 1.5rem;
            font-weight: 500;
        }
        .alert.success {
            background-color: #d1fae5;
            color: #065f46;
            border: 1px solid #34d399;
        }
        .alert.error {
            background-color: #fee2e2;
            color: #991b1b;
            border: 1px solid #ef4444;
        }
        .current-photo {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid #cbd5e0;
            margin-top: 0.5rem;
            margin-bottom: 1rem;
        }
    
        /* 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">
                    <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">3</span>
                    </div>
                    <div class="user-profile">
                        <img src="<?php echo $student_photo; ?>" alt="User Photo">
                        <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="container mx-auto p-6 lg:p-8">
                    <div class="settings-card">
                        <h1 class="text-3xl font-bold text-blue-700 mb-6"><?php echo $_L['settings_heading']; ?></h1>

                        <?php if ($message): ?>
                            <div class="alert <?php echo $message_type; ?>">
                                <?php echo $message; ?>
                            </div>
                        <?php endif; ?>

                        <!-- Change Password Section -->
                        <h2 class="text-xl font-semibold text-gray-800 mb-4"><?php echo $_L['change_password_heading']; ?></h2>
                        <form action="student_settings.php" method="POST" class="space-y-4">
                            <input type="hidden" name="action" value="change_password">
                            <div class="form-group">
                                <label for="old_password"><?php echo $_L['old_password_label']; ?>:</label>
                                <input type="password" id="old_password" name="old_password" required class="w-full">
                            </div>
                            <div class="form-group">
                                <label for="new_password"><?php echo $_L['new_password_label']; ?>:</label>
                                <input type="password" id="new_password" name="new_password" required class="w-full">
                            </div>
                            <div class="form-group">
                                <label for="confirm_password"><?php echo $_L['confirm_password_label']; ?>:</label>
                                <input type="password" id="confirm_password" name="confirm_password" required class="w-full">
                            </div>
                            <button type="submit" class="btn-primary"><?php echo $_L['update_password_button']; ?></button>
                        </form>

                        <hr class="my-8 border-gray-200">

                        <!-- Language Settings Section -->
                        <h2 class="text-xl font-semibold text-gray-800 mb-4"><?php echo $_L['language_settings_heading']; ?></h2>
                        <div class="form-group">
                            <label for="languageSelectorSettings"><?php echo $_L['select_language_label']; ?>:</label>
                            <select id="languageSelectorSettings" onchange="changeLanguage(this.value)" class="w-full">
                                <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>

                        <hr class="my-8 border-gray-200">

                        <!-- Profile Photo Section -->
                        <h2 class="text-xl font-semibold text-gray-800 mb-4"><?php echo $_L['profile_photo_heading']; ?></h2>
                        <div class="flex items-center space-x-4 mb-4">
                            <div>
                                <label class="block text-gray-700 text-sm font-medium mb-1"><?php echo $_L['current_photo_label']; ?>:</label>
                                <img src="<?php echo $student_photo; ?>" alt="Current Photo" class="current-photo" onerror="this.onerror=null;this.src='images/default_student_photo.png';">
                            </div>
                            <form action="student_settings.php" method="POST" enctype="multipart/form-data" class="flex-grow">
                                <input type="hidden" name="action" value="upload_photo">
                                <div class="form-group">
                                    <label for="profile_photo"><?php echo $_L['upload_new_photo_label']; ?>:</label>
                                    <input type="file" id="profile_photo" name="profile_photo" accept="image/jpeg,image/png,image/gif" class="w-full">
                                </div>
                                <button type="submit" class="btn-primary"><?php echo $_L['update_photo_button']; ?></button>
                            </form>
                        </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>