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

// --- Language Data Embedded Start ---
$all_languages = array(
    'en' => array(
        // Dashboard
        'dashboard_title' => 'Dashboard',
        'dashboard_header_title' => 'Dashboard',
        'search_placeholder' => 'Search students/data', // Updated for consistency

        // User Management
        'user_management_title' => 'User Management',
        'manage_users_roles' => 'Manage Users & Roles',
        'username_col' => 'User Name',
        'phone_number_col' => 'Phone Number',
        'current_role_col' => 'Current Role',
        'action_col' => 'Action',
        'no_users_found' => 'No users found in your school with Teacher or Admin roles.',
        'grant_admin_btn' => 'Grant Admin',
        'revoke_admin_btn' => 'Revoke Admin',
        'confirm_grant_admin' => 'Are you sure you want to grant admin role to',
        'confirm_revoke_admin' => 'Are you sure you want to revoke admin role from',
        'cannot_revoke_own_role' => 'Error: You cannot revoke your own admin role.',
        'teacher_role' => 'Teacher',
        'admin_role' => 'Admin',
        'student_role' => 'Student',
        'parent_role' => 'Parent',
        'staff_role' => 'Staff',
        'unknown_role' => 'Unknown',
        'logged_in_as' => 'Logged in as', // Added for user profile

        // Generic
        'log_out' => 'Logout', // Updated for consistency
        'profile' => 'Profile',
        'settings' => 'Settings',
        'reports' => 'Reports',
        'exams' => 'Exams',
        'attendance' => 'Attendance',
        'grades' => 'Grades',
        'enrollments' => 'Enrollments',
        'subjects' => 'Subjects',
        'sections' => 'Sections',
        'classes' => 'Classes',
        'courses' => 'Courses',
        'parents' => 'Parents',
        'staff' => 'Staff',
        'teachers' => 'Teachers',
        'students' => 'Students',
        'school_name_not_found' => 'School Name Not Found',
        'teacher_granted_admin_success' => 'Teacher successfully granted Admin role!',
        'error_granting_admin' => 'Error granting admin role:',
        'database_error_prepare_update' => 'Database error (prepare update role):',
        'error_user_not_found_teacher' => 'Error: User not found as a teacher in your school or already an admin.',
        'invalid_teacher_id' => 'Invalid teacher ID provided.',
        'admin_role_revoked_success' => 'Admin role successfully revoked!',
        'error_revoking_admin' => 'Error revoking admin role:',
        'error_user_not_found_admin' => 'Error: User not found as an admin in your school or not an admin.',
        'invalid_user_id_revocation' => 'Invalid user ID provided for revocation.',
        'more_menu' => 'More', // Added for mobile footer
        
        // Confirmation Dialog
        'confirm_title' => 'Confirm Action',
        'confirm_yes' => 'Yes',
        'confirm_no' => 'No',
    ),
    'sw' => array(
        // Dashboard
        'dashboard_title' => 'Dashibodi',
        'dashboard_header_title' => 'Dashibodi',
        'search_placeholder' => 'Tafuta wanafunzi/data', // Updated for consistency

        // User Management
        'user_management_title' => 'Usimamizi wa Watumiaji',
        'manage_users_roles' => 'Simamia Watumiaji & Majukumu',
        'username_col' => 'Jina la Mtumiaji',
        'phone_number_col' => 'Namba ya Simu',
        'current_role_col' => 'Jukumu la Sasa',
        'action_col' => 'Kitendo',
        'no_users_found' => 'Hakuna watumiaji waliopatikana shuleni kwako wenye majukumu ya Mwalimu au Msimamizi.',
        'grant_admin_btn' => 'Mpe Usimamizi',
        'revoke_admin_btn' => 'Ondoa Usimamizi',
        'confirm_grant_admin' => 'Una uhakika unataka kumpa jukumu la msimamizi kwa',
        'confirm_revoke_admin' => 'Una uhakika unataka kumuondolea jukumu la msimamizi',
        'cannot_revoke_own_role' => 'Kosa: Huwezi kujiondolea jukumu lako la msimamizi.',
        'teacher_role' => 'Mwalimu',
        'admin_role' => 'Msimamizi',
        'student_role' => 'Mwanafunzi',
        'parent_role' => 'Mzazi',
        'staff_role' => 'Wafanyakazi',
        'unknown_role' => 'Haijulikani',
        'logged_in_as' => 'Umeingia kama', // Added for user profile

        // Generic
        'log_out' => 'Toka', // Updated for consistency
        'profile' => 'Wasifu',
        'settings' => 'Mipangilio',
        'reports' => 'Ripoti',
        'exams' => 'Mitihani',
        'attendance' => 'Mahudhurio',
        'grades' => 'Alama',
        'enrollments' => 'Uandikishaji',
        'subjects' => 'Masomo',
        'sections' => 'Sehemu',
        'classes' => 'Madarasa',
        'courses' => 'Kozi',
        'parents' => 'Wazazi',
        'staff' => 'Wafanyakazi',
        'teachers' => 'Walimu',
        'students' => 'Wanafunzi',
        'school_name_not_found' => 'Jina la Shule Halikupatikana',
        'teacher_granted_admin_success' => 'Mwalimu amepewa jukumu la Msimamizi kwa mafanikio!',
        'error_granting_admin' => 'Hitilafu wakati wa kumpa jukumu la msimamizi:',
        'database_error_prepare_update' => 'Hitilafu ya hifadhidata (andika upya jukumu):',
        'error_user_not_found_teacher' => 'Kosa: Mtumiaji hakupatikana kama mwalimu shuleni kwako au tayari ni msimamizi.',
        'invalid_teacher_id' => 'Kitambulisho cha mwalimu batili kimetolewa.',
        'admin_role_revoked_success' => 'Jukumu la msimamizi limeondolewa kwa mafanikio!',
        'error_revoking_admin' => 'Hitilafu wakati wa kuondoa jukumu la msimamizi:',
        'error_user_not_found_admin' => 'Kosa: Mtumiaji hakupatikana kama msimamizi shuleni kwako au si msimamizi.',
        'invalid_user_id_revocation' => 'Kitambulisho batili cha mtumiaji kimetolewa kwa kuondoa.',
        'more_menu' => 'Zaidi', // Added for mobile footer
        
        // Confirmation Dialog
        'confirm_title' => 'Thibitisha Kitendo',
        'confirm_yes' => 'Ndiyo',
        'confirm_no' => 'Hapana',
    ),
    'lg' => array(
        // Dashboard
        'dashboard_title' => 'Akatuuti',
        'dashboard_header_title' => 'Akatuuti',
        'search_placeholder' => 'Noonya abayizi/data', // Updated for consistency

        // User Management
        'user_management_title' => 'Okuwaddebeba abakozesa',
        'manage_users_roles' => 'Kuwanika Abakozesa & Ebifo byabwe',
        'username_col' => 'Erinnya ly\'Omukozi',
        'phone_number_col' => 'Namba y\'essimu',
        'current_role_col' => 'Ekifo ekiriko',
        'action_col' => 'Ekikolebwa',
        'no_users_found' => 'Tewali bakozesa basangiddwa mu ssomero lyo abalina ebifo bya Mukuza oba Omuddukanya.',
        'grant_admin_btn' => 'Muwe Obuddukanya',
        'revoke_admin_btn' => 'Muggyako Obuddukanya',
        'confirm_grant_admin' => 'Oli mukakasa nti oyagala okuwa obuddukanya',
        'confirm_revoke_admin' => 'Oli mukakasa nti oyagala okuggyako obuddukanya eri',
        'cannot_revoke_own_role' => 'Ensobi: Tosobola kweggyako kifo kyo eky\'obuddukanya.',
        'teacher_role' => 'Mukuza',
        'admin_role' => 'Omuddukanya',
        'student_role' => 'Omuyizi',
        'parent_role' => 'Mzaddikira',
        'staff_role' => 'Abakozi',
        'unknown_role' => 'Tekimanyiddwa',
        'logged_in_as' => 'Wali oyinze nga', // Added for user profile

        // Generic
        'log_out' => 'Ggalawo', // Updated for consistency
        'profile' => 'Embeera yo',
        'settings' => 'Enteekateeka',
        'reports' => 'Lipooti',
        'exams' => 'Ebizannyo',
        'attendance' => 'Okujjukira',
        'grades' => 'Ebitongole',
        'enrollments' => 'Okuyingira',
        'subjects' => 'Ebisomo',
        'sections' => 'Ebitundu',
        'classes' => 'Amakirasi',
        'courses' => 'Essomo',
        'parents' => 'Abazaddikira',
        'staff' => 'Abakozi',
        'teachers' => 'Abasukira',
        'students' => 'Abayizi',
        'school_name_not_found' => 'Erinnya ly\'essomero terisangiddwa',
        'teacher_granted_admin_success' => 'Omukuza aweereddwa obuddukanya bw\'Omuddukanya!',
        'error_granting_admin' => 'Ensobi mu kuwa obuddukanya:',
        'database_error_prepare_update' => 'Ensobi y\'e database (okuteekateeka obuddukanya obuggya):',
        'error_user_not_found_teacher' => 'Ensobi: Omukozesa tasangiddwa nga mukuza mu ssomero lyo oba alina dda obuddukanya.',
        'invalid_teacher_id' => 'Namba ya mukuza enkyankalanyizibwa.',
        'admin_role_revoked_success' => 'Obuddukanya bw\'omuddukanya buggyiddwawo bulungi!',
        'error_revoking_admin' => 'Ensobi mu kuggyako obuddukanya:',
        'error_user_not_found_admin' => 'Ensobi: Omukozesa tasangiddwa nga muddukanya mu ssomero lyo oba si muddukanya.',
        'invalid_user_id_revocation' => 'Namba y\'omukozi enkyankalanyizibwa eweereddwa okuggyako.',
        'more_menu' => 'Ebirala', // Added for mobile footer
        
        // Confirmation Dialog
        'confirm_title' => 'Kakasa Ekikolebwa',
        'confirm_yes' => 'Ye',
        'confirm_no' => 'Dda',
    )
);
// --- Language Data Embedded End ---

// --- Language Selection Logic Start ---
// Default language
$current_lang = 'en';

// Check if a language is set in the session
if (isset($_SESSION['lang'])) {
    $current_lang = $_SESSION['lang'];
}

// Check if a language is requested via GET parameter and is supported
if (isset($_GET['lang']) && array_key_exists($_GET['lang'], $all_languages)) {
    $current_lang = $_GET['lang'];
    $_SESSION['lang'] = $current_lang; // Store in session
}

// Set the $lang array to the currently selected language
$lang = $all_languages[$current_lang];
// --- Language Selection Logic End ---


// 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); }

// Function to check user role and redirect if unauthorized
function check_role_access($required_role_code) {
    global $lang; // Make $lang array available inside the function for messages
    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: // Added for consistency
                header("location: parent_dashboard.php");
                break;
            case ROLE_STAFF: // Added for consistency
                header("location: staff_dashboard.php");
                break;
            default:
                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"]);
$user_role_code = $_SESSION["role"];
$current_user_school_id = $_SESSION["school_id"];
$phone_number = $photo = $status = "";

// Initialize school variables
$school_name = $lang['school_name_not_found'];
$school_name_for_js = $lang['school_name_not_found']; // New variable for JS
$school_logo_path = "images/default_school_logo.png"; // Default logo

// Initialize users array
$users_list = [];

// Handle form submissions (Grant Admin Role, Revoke Admin Role)
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (!isset($conn) || !$conn instanceof mysqli) {
        require_once 'config.php';
    }

    if (isset($_POST['action'])) {
        $action = $_POST['action'];

        if ($action == 'grant_admin_role') {
            $teacher_user_id = filter_var($_POST['teacher_user_id'], FILTER_VALIDATE_INT);

            if ($teacher_user_id !== false) {
                $check_teacher_sql = "SELECT id FROM users WHERE id = ? AND school_id = ? AND role = ?";
                if ($check_stmt = $conn->prepare($check_teacher_sql)) {
                    $teacher_role_code = ROLE_TEACHER;
                    $check_stmt->bind_param("iii", $teacher_user_id, $current_user_school_id, $teacher_role_code);
                    $check_stmt->execute();
                    $check_stmt->store_result();

                    if ($check_stmt->num_rows > 0) {
                        $update_sql = "UPDATE users SET role = ? WHERE id = ? AND school_id = ?";
                        if ($update_stmt = $conn->prepare($update_sql)) {
                            $admin_role_code = ROLE_ADMIN;
                            $update_stmt->bind_param("iii", $admin_role_code, $teacher_user_id, $current_user_school_id);
                            if ($update_stmt->execute()) {
                                $_SESSION['message'] = $lang['teacher_granted_admin_success'];
                                $_SESSION['message_type'] = "success";
                            } else {
                                $_SESSION['message'] = $lang['error_granting_admin'] . " " . $update_stmt->error;
                                $_SESSION['message_type'] = "error";
                            }
                            $update_stmt->close();
                        } else {
                            $_SESSION['message'] = "Database error (prepare update role): " . $conn->error;
                            $_SESSION['message_type'] = "error";
                        }
                    } else {
                        $_SESSION['message'] = $lang['error_user_not_found_teacher'];
                        $_SESSION['message_type'] = "error";
                    }
                    $check_stmt->close();
                } else {
                    $_SESSION['message'] = "Database error (prepare check teacher): " . $conn->error;
                    $_SESSION['message_type'] = "error";
                }
            } else {
                $_SESSION['message'] = $lang['invalid_teacher_id'];
                $_SESSION['message_type'] = "error";
            }
        } elseif ($action == 'revoke_admin_role') {
            $admin_user_id = filter_var($_POST['admin_user_id'], FILTER_VALIDATE_INT);

            if ($admin_user_id !== false) {
                $check_admin_sql = "SELECT id FROM users WHERE id = ? AND school_id = ? AND role = ?";
                if ($check_stmt = $conn->prepare($check_admin_sql)) {
                    $admin_role_code = ROLE_ADMIN;
                    $check_stmt->bind_param("iii", $admin_user_id, $current_user_school_id, $admin_role_code);
                    $check_stmt->execute();
                    $check_stmt->store_result();

                    if ($check_stmt->num_rows > 0) {
                        if ($admin_user_id == $user_id) {
                            $_SESSION['message'] = $lang['cannot_revoke_own_role'];
                            $_SESSION['message_type'] = "error";
                        } else {
                            $update_sql = "UPDATE users SET role = ? WHERE id = ? AND school_id = ?";
                            if ($update_stmt = $conn->prepare($update_sql)) {
                                $teacher_role_code = ROLE_TEACHER;
                                $update_stmt->bind_param("iii", $teacher_role_code, $admin_user_id, $current_user_school_id);
                                if ($update_stmt->execute()) {
                                    $_SESSION['message'] = $lang['admin_role_revoked_success'];
                                    $_SESSION['message_type'] = "success";
                                } else {
                                    $_SESSION['message'] = $lang['error_revoking_admin'] . " " . $update_stmt->error;
                                    $_SESSION['message_type'] = "error";
                                }
                                $update_stmt->close();
                            } else {
                                $_SESSION['message'] = "Database error (prepare update role): " . $conn->error;
                                $_SESSION['message_type'] = "error";
                            }
                        }
                    } else {
                        $_SESSION['message'] = $lang['error_user_not_found_admin'];
                        $_SESSION['message_type'] = "error";
                    }
                    $check_stmt->close();
                } else {
                    $_SESSION['message'] = "Database error (prepare check admin): " . $conn->error;
                    $_SESSION['message_type'] = "error";
                }
            } else {
                $_SESSION['message'] = $lang['invalid_user_id_revocation'];
                $_SESSION['message_type'] = "error";
            }
        }
    }
    $redirect_url = "admin_user_management.php";
    if (isset($_GET['lang'])) {
        $redirect_url .= "?lang=" . urlencode($_GET['lang']);
    }
    header("Location: " . $redirect_url);
    exit();
}

// Fetch additional user details from the database for the logged-in admin
if (isset($conn) && $conn instanceof mysqli) {
    $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');
            $photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD';
            $status = htmlspecialchars($status_db ?? 'N/A');
        }
        $stmt->close();
    } else {
        error_log("Failed to prepare user details query: " . $conn->error);
    }

    // Fetch School Name and Logo
    $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);
                $school_name_for_js = addslashes($school_name_db); // For JavaScript string literal
                // Ensure logo path is correct and exists, otherwise use default
                $school_logo_path = !empty($school_logo_db) ? htmlspecialchars($school_logo_db) : 'images/default_school_logo.png';
                if (!file_exists($school_logo_path) || is_dir($school_logo_path)) {
                    $school_logo_path = 'images/default_school_logo.png';
                }
            }
        }
        $stmt_school->close();
    } else {
        error_log("Failed to prepare school data query: " . $conn->error);
    }

    // Fetch ALL Teachers and Admins for the current school
    $teacher_role_code = ROLE_TEACHER;
    $admin_role_code = ROLE_ADMIN;
    $sql_users = "SELECT u.id, u.username, u.phone_number, u.role
                    FROM users u
                    WHERE u.school_id = ? AND (u.role = ? OR u.role = ?)
                    ORDER BY u.username ASC";
    if ($stmt_users = $conn->prepare($sql_users)) {
        $stmt_users->bind_param("iii", $current_user_school_id, $teacher_role_code, $admin_role_code);
        if ($stmt_users->execute()) {
            $result_users = $stmt_users->get_result();
            while ($row = $result_users->fetch_assoc()) {
                $users_list[] = $row;
            }
        } else {
            error_log("Failed to execute users query: " . $stmt_users->error);
        }
        $stmt_users->close();
    } else {
        error_log("Failed to prepare users query: " . $conn->error);
    }

    $conn->close();
} else {
    error_log("Database connection \$conn not available in admin_user_management.php");
    $photo = 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD';
}

// Determine role name for display (using $lang array)
$role_name = $lang['unknown_role'];
switch ($user_role_code) {
    case ROLE_SUPER_ADMIN: $role_name = "Super Admin"; break; // Assuming Super Admin role name is always English
    case ROLE_ADMIN:         $role_name = $lang['admin_role'];         break;
    case ROLE_TEACHER:       $role_name = $lang['teacher_role'];       break;
    case ROLE_STUDENT:       $role_name = $lang['student_role'];       break;
    case ROLE_PARENT:        $role_name = $lang['parent_role'];        break;
    case ROLE_STAFF:         $role_name = $lang['staff_role'];         break;
}

// Check for and display messages
$message = $_SESSION['message'] ?? '';
$message_type = $_SESSION['message_type'] ?? '';
unset($_SESSION['message']);
unset($_SESSION['message_type']);

?>

<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $lang['user_management_title']; ?> - <?php echo $school_name; ?></title>
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="icon" href="<?php echo $school_logo_path; ?>" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"> <style>
        
        .language-select select { /* Renamed from .language-selector, now targeting the select inside .language-select for consistency */
            padding: 8px 12px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            background-color: #ffffff;
            cursor: pointer;
            font-size: 0.875rem;
            color: #374151;
            appearance: none; /* Remove default dropdown arrow */
            -webkit-appearance: none;
            -moz-appearance: none;
            background-image: url('data:image/svg+xml;charset=US-ASCII,%3Csvg xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22 viewBox%3D%220 0 4 5%22%3E%3Cpath fill%3D%22%23343a40%22 d%3D%22M2 0L0 2h4zm0 5L0 3h4z%22%2F%3E%3C%2Fsvg%3E');
            background-repeat: no-repeat;
            background-position: right 0.75rem center;
            background-size: 8px 10px;
            padding-right: 2.25rem; /* Make space for the custom arrow */
        }

        .language-select select:focus { /* Renamed from .language-selector:focus for consistency */
            outline: none;
            border-color: #4f46e5;
            box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.25);
        }

        .user-profile {
            display: flex;
            align-items: center;
            cursor: pointer; /* Indicate it's clickable */
        }

        .user-profile div { /* General div for user info, removed .user-profile-info class for consistency */
            display: flex;
            flex-direction: column;
            text-align: right;
            margin-right: 12px;
        }

        .user-profile .user-name { /* Renamed from .username for consistency */
            font-weight: 500;
            color: #1f2937;
        }

        .user-profile .user-email { /* Renamed from .role for consistency */
            font-size: 0.875rem;
            color: #4b5563;
        }

        .user-profile img {
            height: 40px;
            width: 40px;
            border-radius: 9999px;
            border: 2px solid #d1d5db;
            object-fit: cover;
            margin-right: 8px; /* Space before dropdown arrow */
        }
        .user-profile .fas.fa-chevron-down { /* Targeted directly, removed .profile-dropdown-arrow class for consistency */
            color: #4b5563;
            font-size: 0.8rem;
        }


        /* Main content area */
        .main-content {
            flex-grow: 1; /* Equivalent to flex-1 */
            padding: 24px; /* Equivalent to p-6 */
            background-color: #f3f4f6; /* Equivalent to bg-gray-100 */
        }

        /* Message Box */
        .message-box {
            padding: 16px; /* Equivalent to p-4 */
            margin-bottom: 16px; /* Equivalent to mb-4 */
            border-radius: 8px; /* Equivalent to rounded-lg */
            font-weight: 700; /* Equivalent to font-bold */
            display: flex;
            justify-content: space-between;
            align-items: center;
            opacity: 1;
            transition: opacity 0.5s ease-out;
            animation: slideIn 0.3s ease-out;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .message-box.fade-out {
            opacity: 0;
            animation: slideOut 0.5s ease-out forwards;
        }

        @keyframes slideOut {
            from {
                opacity: 1;
                transform: translateY(0);
            }
            to {
                opacity: 0;
                transform: translateY(-20px);
            }
        }

        .message-box.success {
            background-color: #d1fae5; /* Equivalent to bg-green-100 */
            color: #065f46; /* Equivalent to text-green-800 */
            border: 1px solid #34d399; /* Equivalent to border border-green-400 */
        }

        .message-box.error {
            background-color: #fee2e2; /* Equivalent to bg-red-100 */
            color: #991b1b; /* Equivalent to text-red-800 */
            border: 1px solid #ef4444; /* Equivalent to border border-red-400 */
        }

        .message-box .close-btn {
            background: none;
            border: none;
            font-size: 1rem;
            color: inherit;
            opacity: 0.75;
            cursor: pointer;
            padding: 0;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .message-box .close-btn:hover {
            opacity: 1;
            background-color: rgba(0, 0, 0, 0.1);
            border-radius: 3px;
        }

        /* Content Card */
        .content-card {
            background-color: #ffffff; /* Equivalent to bg-white */
            padding: 24px; /* Equivalent to p-6 */
            border-radius: 8px; /* Equivalent to rounded-lg */
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08); /* Equivalent to shadow-md */
        }

        .content-card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e5e7eb; /* Light gray border */
        }

        .content-card-header h2 {
            font-size: 1.5rem;
            font-weight: 600;
            color: #1f2937;
            margin: 0;
        }

        /* Table Styles */
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .data-table th, .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #e5e7eb;
        }

        .data-table th {
            background-color: #f9fafb; /* Light background for headers */
            font-weight: 600;
            color: #4b5563;
            text-transform: uppercase;
            font-size: 0.85rem;
        }

        .data-table tbody tr:hover {
            background-color: #f3f4f6; /* Hover effect for rows */
        }

        .data-table .action-buttons button {
            background-color: #4f46e5; /* Indigo */
            color: white;
            padding: 8px 12px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 0.875rem;
            transition: background-color 0.2s ease;
            margin-right: 5px; /* Space between buttons */
        }

        .data-table .action-buttons button.revoke {
            background-color: #ef4444; /* Red */
        }

        .data-table .action-buttons button:hover {
            opacity: 0.9;
        }

        /* Responsive Table */
        @media (max-width: 768px) {
            .data-table thead {
                display: none; /* Hide table headers on small screens */
            }

            .data-table, .data-table tbody, .data-table tr, .data-table td {
                display: block; /* Make table elements behave like block elements */
                width: 100%;
            }

            .data-table tr {
                margin-bottom: 15px;
                border: 1px solid #e5e7eb;
                border-radius: 8px;
                overflow: hidden;
            }

            .data-table td {
                text-align: right;
                padding-left: 50%;
                position: relative;
            }

            .data-table td::before {
                content: attr(data-label); /* Use data-label for pseudo-elements */
                position: absolute;
                left: 15px;
                width: calc(50% - 30px);
                text-align: left;
                font-weight: 600;
                color: #4b5563;
            }

            .data-table .action-buttons {
                text-align: left;
                padding-left: 15px; /* Adjust for pseudo-element */
            }
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        /* --- Confirmation Modal Styles --- */
        #confirm-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 3000;
            display: none;
            align-items: center;
            justify-content: center;
        }

        #confirm-modal.show {
            display: flex;
        }

        #confirm-modal .modal-content {
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            max-width: 400px;
            width: 90%;
            text-align: center;
        }

        #confirm-modal .modal-content h3 {
            margin-top: 0;
            color: #333;
            font-size: 1.25rem;
            margin-bottom: 15px;
        }

        #confirm-modal .modal-content p {
            margin-bottom: 25px;
            color: #666;
            line-height: 1.5;
        }

        #confirm-modal .button-group {
            display: flex;
            gap: 10px;
            justify-content: center;
        }

        #confirm-modal .button-group button {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 0.9rem;
            font-weight: 500;
            transition: background-color 0.2s ease;
        }

        #confirm-modal .button-group .confirm-yes {
            background-color: #4f46e5;
            color: white;
        }

        #confirm-modal .button-group .confirm-yes:hover {
            background-color: #4338ca;
        }

        #confirm-modal .button-group .confirm-no {
            background-color: #6b7280;
            color: white;
        }

        #confirm-modal .button-group .confirm-no:hover {
            background-color: #4b5563;
        }


        @media (max-width: 768px) {
            #mobile-footer-nav {
                display: block;
            }
            #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;
            }
        }
        /* Apply this to your button's class or element selector (e.g., .my-button) */
@media (max-width: 600px) { /* Only apply on smaller screens */
  .button-selector {
    white-space: normal; /* Allow text to wrap */
    word-wrap: break-word;
    padding: 12px 10px; /* Increase padding for wrapped text */
    min-height: 44px; /* Ensure a minimum touch target size */
    font-size: 0.9em; /* Slightly reduce text size */
    line-height: 1.2; /* Ensure lines are close */
    justify-content: flex-end;
  }
}
    </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> <?php echo $lang['dashboard_title']; ?></a></li>
                    <li><a href="admin_calendar.php" id="calendarLink"><i class="far fa-calendar-alt"></i> Calendar</a></li>
                    <li><a href="admin_user_management.php" id="usersLink"><i class="fas fa-users-cog"></i> <span class="nav-text">Users</span></a></li>
                    <li><a href="admin_students.php" id="studentsLink"><i class="fas fa-user-graduate"></i> <?php echo $lang['students']; ?></a></li>
                    <li><a href="admin_teachers.php" id="teachersLink"><i class="fas fa-chalkboard-teacher"></i> <?php echo $lang['teachers']; ?></a></li>
                    <li class="hide-on-mobile"><a href="admin_classes.php" id="classesLink"><i class="fas fa-chalkboard"></i> <?php echo $lang['classes']; ?></a></li>
                    <li class="hide-on-mobile"><a href="admin_subjects.php" id="subjectsLink"><i class="fas fa-book"></i> <?php echo $lang['subjects']; ?></a></li>
                    <li class="hide-on-mobile"><a href="admin_exams.php" id="examsLink"><i class="fas fa-file-alt"></i> <?php echo $lang['exams']; ?></a></li>
                     <li class="hidden md:block"><a href="admin_messages.php" id="messagesLinkSidebar"><i class="fas fa-envelope"></i> <span class="nav-text">Messages</span></a></li>
                    <li><a href="admin_reports_printouts.php" id="printoutsLink"><i class="fas fa-print"></i> Printouts</a></li>
                    <li class="hide-on-mobile"><a href="admin_system_settings.php" id="systemSettingsLink"><i class="fas fa-cog"></i> <?php echo $lang['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> <?php echo $lang['log_out']; ?></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" <?php echo ($current_lang == 'en' ? 'selected' : ''); ?>>🇬🇧 English</option>
                           <option value="lg" <?php echo ($current_lang == 'lg' ? 'selected' : ''); ?>>🇺🇬 Luganda</option>
                           <option value="sw" <?php echo ($current_lang == 'sw' ? 'selected' : ''); ?>>🇹🇿 Kiswahili</option>
                        </select>
                    </div>
                    <div class="search-bar">
                        <i class="fas fa-search"></i>
                        <input type="text" placeholder="<?php echo $lang['search_placeholder']; ?>" 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"><?php echo $lang['logged_in_as']; ?>: <?php echo $role_name; ?></div>
                        </div>
                        <i class="fas fa-chevron-down"></i>
                    </div>
                </div>
            </header>

            <div class="dashboard-content">
                <?php if ($message) : ?>
                    <div class="message-box <?php echo $message_type; ?>" id="messageBox">
                        <span><?php echo $message; ?></span>
                        <button class="close-btn" id="closeMessageBtn">&times;</button>
                    </div>
                <?php endif; ?>

                <div class="content-card">
                    <div class="content-card-header">
                        <h2><?php echo $lang['manage_users_roles']; ?></h2>
                    </div>
                    
                    <?php if (count($users_list) > 0) : ?>
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th><?php echo $lang['username_col']; ?></th>
                                    <th><?php echo $lang['phone_number_col']; ?></th>
                                    <th><?php echo $lang['current_role_col']; ?></th>
                                    <th><?php echo $lang['action_col']; ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($users_list as $user) : 
                                    $user_role = $lang['unknown_role'];
                                    switch ($user['role']) {
                                        case ROLE_ADMIN: $user_role = $lang['admin_role']; break;
                                        case ROLE_TEACHER: $user_role = $lang['teacher_role']; break;
                                    }
                                ?>
                                    <tr>
                                        <td data-label="<?php echo $lang['username_col']; ?>"><?php echo htmlspecialchars($user['username'] ?? ''); ?></td>
                                        <td data-label="<?php echo $lang['phone_number_col']; ?>"><?php echo htmlspecialchars($user['phone_number'] ?? ''); ?></td>
                                        <td data-label="<?php echo $lang['current_role_col']; ?>"><?php echo $user_role; ?></td>
                                        <td data-label="<?php echo $lang['action_col']; ?>" class="action-buttons">
                                            <?php if ($user['role'] == ROLE_TEACHER) : ?>
                                                <form method="POST" action="admin_user_management.php<?php echo isset($_GET['lang']) ? '?lang=' . urlencode($_GET['lang']) : ''; ?>" style="display:inline;" id="grant-form-<?php echo $user['id']; ?>">
                                                    <input type="hidden" name="action" value="grant_admin_role">
                                                    <input type="hidden" name="teacher_user_id" value="<?php echo $user['id']; ?>">
                                                    <button type="button" class="grant confirm-btn" data-action="grant" data-username="<?php echo addslashes(htmlspecialchars($user['username'])); ?>" data-confirm-message="<?php echo addslashes($lang['confirm_grant_admin'] . ' ' . htmlspecialchars($user['username']) . '?'); ?>" data-form-id="grant-form-<?php echo $user['id']; ?>"><?php echo $lang['grant_admin_btn']; ?></button>
                                                </form>
                                            <?php elseif ($user['role'] == ROLE_ADMIN) : ?>
                                                <form method="POST" action="admin_user_management.php<?php echo isset($_GET['lang']) ? '?lang=' . urlencode($_GET['lang']) : ''; ?>" style="display:inline;" id="revoke-form-<?php echo $user['id']; ?>">
                                                    <input type="hidden" name="action" value="revoke_admin_role">
                                                    <input type="hidden" name="admin_user_id" value="<?php echo $user['id']; ?>">
                                                    <button type="button" class="revoke confirm-btn" data-action="revoke" data-username="<?php echo addslashes(htmlspecialchars($user['username'])); ?>" data-confirm-message="<?php echo addslashes($lang['confirm_revoke_admin'] . ' ' . htmlspecialchars($user['username']) . '?'); ?>" data-form-id="revoke-form-<?php echo $user['id']; ?>" <?php echo ($user['id'] == $user_id) ? 'disabled title="' . $lang['cannot_revoke_own_role'] . '"' : ''; ?>><?php echo $lang['revoke_admin_btn']; ?></button>
                                                </form>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php else : ?>
                        <p><?php echo $lang['no_users_found']; ?></p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Confirmation Modal -->
    <div id="confirm-modal">
        <div class="modal-content">
            <h3 id="confirm-title"><?php echo $lang['confirm_title']; ?></h3>
            <p id="confirm-message"></p>
            <div class="button-group">
                <button type="button" class="confirm-yes" id="confirm-yes-btn"><?php echo $lang['confirm_yes']; ?></button>
                <button type="button" class="confirm-no" id="confirm-no-btn"><?php echo $lang['confirm_no']; ?></button>
            </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><?php echo $lang['dashboard_title']; ?></span>
                </a>
            </li>
            <li>
                <a href="admin_user_management.php" class="active" data-section="user-management">
                    <i class="fas fa-users-cog"></i>
                    <span><?php echo $lang['user_management_title']; ?></span>
                </a>
            </li>
            <li>
                <a href="admin_students.php" data-section="students">
                    <i class="fas fa-user-graduate"></i>
                    <span><?php echo $lang['students']; ?></span>
                </a>
            </li>
            <li>
                <a href="#" id="moreMenuButton" data-section="more">
                    <i class="fas fa-ellipsis-h"></i>
                    <span><?php echo $lang['more_menu']; ?></span>
                </a>
            </li>
        </ul>
    </div>
    <div id="more-menu-modal">
        <div id="more-menu-modal-header">
            <h3><?php echo $lang['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_teachers.php"><i class="fas fa-chalkboard-teacher"></i> <?php echo $lang['teachers']; ?></a></li>
            <li><a href="admin_staff.php"><i class="fas fa-user-tie"></i> <?php echo $lang['staff']; ?></a></li>
            <li><a href="admin_classes.php"><i class="fas fa-chalkboard"></i> <?php echo $lang['classes']; ?></a></li>
            <li><a href="admin_subjects.php"><i class="fas fa-book"></i> <?php echo $lang['subjects']; ?></a></li>
            <li><a href="admin_exams.php"><i class="fas fa-file-alt"></i> <?php echo $lang['exams']; ?></a></li>
            <li><a href="admin_reports_printouts.php"><i class="fas fa-print"></i> <?php echo $lang['reports']; ?></a></li>
            <li><a href="admin_system_settings.php"><i class="fas fa-cog"></i> <?php echo $lang['settings']; ?></a></li>
            <li class="logout"><a href="logout.php"><i class="fas fa-sign-out-alt"></i> <?php echo $lang['log_out']; ?></a></li>
        </ul>
    </div>
    <div class="overlay" id="overlay"></div>

    <script>
        const schoolNameForJs = "<?php echo $school_name_for_js; ?>";
        const currentUsername = "<?php echo $username; ?>";
        const currentLang = "<?php echo $current_lang; ?>";
        const all_languages_js = <?php echo json_encode($all_languages); ?>;

        // --- Auto-fade Message Logic ---
        function autoFadeMessage() {
            const messageBox = document.getElementById('messageBox');
            if (messageBox) {
                // Set a 3-second timer for auto-fade
                setTimeout(() => {
                    messageBox.classList.add('fade-out');
                    // Remove the message after fade animation completes (0.5s fade + 0.1s buffer)
                    setTimeout(() => {
                        messageBox.remove();
                    }, 600);
                }, 3000); // 3 seconds

                // Add close button functionality
                const closeBtn = document.getElementById('closeMessageBtn');
                if (closeBtn) {
                    closeBtn.addEventListener('click', () => {
                        messageBox.classList.add('fade-out');
                        setTimeout(() => {
                            messageBox.remove();
                        }, 600);
                    });
                }
            }
        }

        // Initialize auto-fade when DOM is loaded
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', autoFadeMessage);
        } else {
            autoFadeMessage();
        }

        // --- Confirmation Modal Logic ---
        const confirmModal = document.getElementById('confirm-modal');
        const confirmMessage = document.getElementById('confirm-message');
        const confirmYesBtn = document.getElementById('confirm-yes-btn');
        const confirmNoBtn = document.getElementById('confirm-no-btn');
        let currentForm = null;

        function showConfirmModal(message, formId) {
            confirmMessage.textContent = message;
            confirmModal.classList.add('show');
            currentForm = document.getElementById(formId);
        }

        function hideConfirmModal() {
            confirmModal.classList.remove('show');
            currentForm = null;
        }

        // Add click event listeners to all confirm buttons
        document.querySelectorAll('.confirm-btn').forEach(button => {
            button.addEventListener('click', function() {
                const message = this.getAttribute('data-confirm-message');
                const formId = this.getAttribute('data-form-id');
                showConfirmModal(message, formId);
            });
        });

        // Handle confirm button clicks
        confirmYesBtn.addEventListener('click', function() {
            if (currentForm) {
                currentForm.submit();
            }
            hideConfirmModal();
        });

        confirmNoBtn.addEventListener('click', function() {
            hideConfirmModal();
        });

        // Close modal when clicking outside
        confirmModal.addEventListener('click', function(e) {
            if (e.target === confirmModal) {
                hideConfirmModal();
            }
        });

        function getTranslation(key) {
            return all_languages_js[localStorage.getItem('appLang') || 'en'][key] || key;
        }

        function applyTranslations(lang) {
            const t = all_languages_js[lang];

            // Sidebar & General
            document.getElementById('dashboardLink').innerHTML = `<i class="fas fa-th-large"></i> ${t.dashboard_title}`;
            document.getElementById('userManagementLink').innerHTML = `<i class="fas fa-users-cog"></i> ${t.user_management_title}`;
            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}`;
            document.getElementById('staffLink').innerHTML = `<i class="fas fa-user-tie"></i> ${t.staff}`;
            document.getElementById('classesLink').innerHTML = `<i class="fas fa-chalkboard"></i> ${t.classes}`;
            document.getElementById('subjectsLink').innerHTML = `<i class="fas fa-book"></i> ${t.subjects}`;
            document.getElementById('examsLink').innerHTML = `<i class="fas fa-file-alt"></i> ${t.exams}`;
            document.getElementById('reportsLink').innerHTML = `<i class="fas fa-print"></i> ${t.reports}`;
            document.getElementById('systemSettingsLink').innerHTML = `<i class="fas fa-cog"></i> ${t.settings}`;
            document.getElementById('logoutLinkSidebar').innerHTML = `<i class="fas fa-sign-out-alt"></i> ${t.log_out}`;
            
            // Header
            document.getElementById('searchPlaceholder').placeholder = t.search_placeholder;
            
            // Confirmation Modal
            document.getElementById('confirm-title').textContent = t.confirm_title;
            document.getElementById('confirm-yes-btn').textContent = t.confirm_yes;
            document.getElementById('confirm-no-btn').textContent = t.confirm_no;
            
            // Table Headers (Need to check if they exist before updating)
            const thMap = {
                '<?php echo $lang['username_col']; ?>': t.username_col,
                '<?php echo $lang['phone_number_col']; ?>': t.phone_number_col,
                '<?php echo $lang['current_role_col']; ?>': t.current_role_col,
                '<?php echo $lang['action_col']; ?>': t.action_col
            };
            const tableHeaders = document.querySelectorAll('.data-table th');
            tableHeaders.forEach(th => {
                if (th.textContent.trim() in thMap) {
                    th.textContent = thMap[th.textContent.trim()];
                }
            });
            
            // Table Data Labels (for mobile view)
            const tableCells = document.querySelectorAll('.data-table td');
            tableCells.forEach(td => {
                 const currentLabel = td.getAttribute('data-label');
                 if (currentLabel && currentLabel in thMap) {
                     td.setAttribute('data-label', thMap[currentLabel]);
                 }
            });

            // Mobile Footer
            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_title;
                if (section === 'user-management') link.querySelector('span').textContent = t.user_management_title;
                if (section === 'students') link.querySelector('span').textContent = t.students;
                if (section === 'more') link.querySelector('span').textContent = t.more_menu;
            }

            // More Menu Modal
            document.getElementById('more-menu-modal-header').querySelector('h3').textContent = t.more_menu;
            // Update modal links
            document.querySelector('#more-menu-list a[href="admin_teachers.php"]').innerHTML = `<i class="fas fa-chalkboard-teacher"></i> ${t.teachers}`;
            document.querySelector('#more-menu-list a[href="admin_staff.php"]').innerHTML = `<i class="fas fa-user-tie"></i> ${t.staff}`;
            document.querySelector('#more-menu-list a[href="admin_classes.php"]').innerHTML = `<i class="fas fa-chalkboard"></i> ${t.classes}`;
            document.querySelector('#more-menu-list a[href="admin_subjects.php"]').innerHTML = `<i class="fas fa-book"></i> ${t.subjects}`;
            document.querySelector('#more-menu-list a[href="admin_exams.php"]').innerHTML = `<i class="fas fa-file-alt"></i> ${t.exams}`;
            document.querySelector('#more-menu-list a[href="admin_reports_printouts.php"]').innerHTML = `<i class="fas fa-print"></i> ${t.reports}`;
            document.querySelector('#more-menu-list a[href="admin_system_settings.php"]').innerHTML = `<i class="fas fa-cog"></i> ${t.settings}`;
            document.querySelector('#more-menu-list a[href="logout.php"]').innerHTML = `<i class="fas fa-sign-out-alt"></i> ${t.log_out}`;
        } 

        // Language Selector Logic
        const languageSelect = document.getElementById('languageSelect');
        const savedLang = localStorage.getItem('appLang') || currentLang; 

        // Set the initial selected option
        languageSelect.value = savedLang;
        // applyTranslations(savedLang); // Already executed by PHP on page load for initial text, but good for dynamic elements
        
        languageSelect.addEventListener('change', function() {
            const newLang = this.value;
            localStorage.setItem('appLang', newLang);
            
            // Redirect to the same page with the new language parameter to update PHP translations
            let url = window.location.pathname;
            let params = new URLSearchParams(window.location.search);
            params.set('lang', newLang);
            window.location.href = url + '?' + params.toString();
        });


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

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

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

        if (overlay) {
            overlay.addEventListener('click', () => {
                toggleMoreMenu(false);
            });
        }
        // --- END: Mobile Footer Modal Logic ---


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

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

        // Close sidebar when clicking outside on mobile
        if (dashboardContainer) {
            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) {
            sidebar.classList.add('collapsed');
        }
        // --- END: Sidebar/Menu Toggle Logic ---

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