<?php
// Start a new session or resume an existing one.
session_start();

// Include the database configuration file. This file should contain database connection details ($conn).
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',

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

        // Messages
        'messages_title' => 'Messages',
        'inbox' => 'Inbox',
        'sent' => 'Sent',
        'compose_message' => 'Compose Message',
        'received_messages' => 'Received Messages',
        'no_received_messages' => 'No messages in your inbox.',
        'sent_messages' => 'Sent Messages',
        'no_sent_messages' => 'No messages sent yet.',
        'compose_new_message' => 'Compose New Message',
        'to' => 'To:',
        'select_receiver' => 'Select Receiver',
        'all_students' => 'All Students',
        'all_teachers' => 'All Teachers',
        'individual_users' => 'Individual Users',
        'subject' => 'Subject:',
        'message_content' => 'Message:',
        'send_message' => 'Send Message',
        'sender' => 'Sender',
        'receiver' => 'Receiver',
        'message_text' => 'Message',
        'status' => 'Status',
        'date' => 'Date',
        'actions' => 'Actions',
        'view' => 'View',
        'mark_read' => 'Mark Read',
        'from' => 'From:',
        'content' => 'Content:',
        'mark_as_read_modal' => 'Mark as Read',

        // Generic
        'log_out' => 'Logout',
        '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',
        'more_menu' => 'More',
    ),
    'sw' => array(
        // Dashboard
        'dashboard_title' => 'Dashibodi',
        'dashboard_header_title' => 'Dashibodi',
        'search_placeholder' => 'Tafuta wanafunzi/data',

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

        // Messages
        'messages_title' => 'Ujumbe',
        'inbox' => 'Sanduku la Ujumbe',
        'sent' => 'Ujumbe Uliotumwa',
        'compose_message' => 'Andika Ujumbe',
        'received_messages' => 'Ujumbe Uliopokelewa',
        'no_received_messages' => 'Hakuna ujumbe kwenye sanduku lako la ujumbe.',
        'sent_messages' => 'Ujumbe Uliotumwa',
        'no_sent_messages' => 'Hakuna ujumbe uliotumwa bado.',
        'compose_new_message' => 'Andika Ujumbe Mpya',
        'to' => 'Kwa:',
        'select_receiver' => 'Chagua Mpokeaji',
        'all_students' => 'Wanafunzi Wote',
        'all_teachers' => 'Walimu Wote',
        'individual_users' => 'Watumiaji Binafsi',
        'subject' => 'Kichwa:',
        'message_content' => 'Ujumbe:',
        'send_message' => 'Tuma Ujumbe',
        'sender' => 'Mtuma',
        'receiver' => 'Mpokeaji',
        'message_text' => 'Ujumbe',
        'status' => 'Hali',
        'date' => 'Tarehe',
        'actions' => 'Vitendo',
        'view' => 'Angalia',
        'mark_read' => 'Weka Kama Umesoma',
        'from' => 'Kutoka:',
        'content' => 'Yaliyomo:',
        'mark_as_read_modal' => 'Weka Kama Umesoma',

        // Generic
        'log_out' => 'Toka',
        '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',
        'more_menu' => 'Zaidi',
    ),
    'lg' => array(
        // Dashboard
        'dashboard_title' => 'Akatuuti',
        'dashboard_header_title' => 'Akatuuti',
        'search_placeholder' => 'Noonya abayizi/data',

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

        // Messages
        'messages_title' => 'Obubaka',
        'inbox' => 'Obubaka Obukyamu',
        'sent' => 'Obubaka Obuwedde',
        'compose_message' => 'Wandiika Obubaka',
        'received_messages' => 'Obubaka Obukyamu',
        'no_received_messages' => 'Tewali bubaka mu bubaka bwo obukyamu.',
        'sent_messages' => 'Obubaka Obuwedde',
        'no_sent_messages' => 'Tewali bubaka bwawerezeddwa.',
        'compose_new_message' => 'Wandiika Obubaka Obupya',
        'to' => 'Eri:',
        'select_receiver' => 'Londa Omukyamu',
        'all_students' => 'Abayizi Bonna',
        'all_teachers' => 'Abasomesa Bonna',
        'individual_users' => 'Abakozesa Obuntu',
        'subject' => 'Omutwe:',
        'message_content' => 'Obubaka:',
        'send_message' => 'Wereza Obubaka',
        'sender' => 'Omuwereza',
        'receiver' => 'Omukyamu',
        'message_text' => 'Obubaka',
        'status' => 'Embeera',
        'date' => 'Olunaku',
        'actions' => 'Ebikolebwa',
        'view' => 'Laba',
        'mark_read' => 'Marka Okusomwa',
        'from' => 'Okuva:',
        'content' => 'Ebirimu:',
        'mark_as_read_modal' => 'Marka Okusomwa',

        // Generic
        'log_out' => 'Ggalawo',
        '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',
        'more_menu' => 'Ebirala',
    )
);
// --- 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 they haven't been defined yet.
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 the current user's role and redirect if unauthorized.
 * This ensures only Admins can access this page.
 *
 * @param int $required_role_code The integer code of the role required to access the page.
 */
function check_role_access($required_role_code) {
    global $lang;
    if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || !isset($_SESSION["school_id"])) {
        header("location: login.php");
        exit;
    }

    if ($_SESSION["role"] !== $required_role_code) {
        switch ($_SESSION["role"]) {
            case ROLE_SUPER_ADMIN:
                header("location: super_admin_dashboard.php");
                break;
            case ROLE_TEACHER:
                header("location: teacher_dashboard.php");
                break;
            case ROLE_STUDENT:
                header("location: student_dashboard.php");
                break;
            case ROLE_PARENT:
                header("location: parent_dashboard.php");
                break;
            case ROLE_STAFF:
                header("location: staff_dashboard.php");
                break;
            default:
                header("location: login.php");
                break;
        }
        exit;
    }
}

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

// Fetch user details from session variables.
$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]); // Sanitize for display.
$user_role_code = $_SESSION["role"];
$current_user_school_id = $_SESSION["school_id"];

// Initialize variables for user and school data.
$phone_number = $photo = $status = "";
$school_name = $lang['school_name_not_found'];
$school_name_for_js = $lang['school_name_not_found'];
$school_logo_path = "images/default_school_logo.png";

// Initialize message arrays.
$receivedMessages = [];
$sentMessages = [];
$usersList = []; // For the receiver dropdown.
$message = ''; // For success/error messages after sending.

// Ensure $conn is available from config.php.
if (isset($conn) && $conn instanceof mysqli) {
    // Fetch additional user details.
    $sql_user_details = "SELECT phone_number, photo, status FROM users WHERE id = ? AND school_id = ?";
    if ($stmt_user = $conn->prepare($sql_user_details)) {
        $stmt_user->bind_param("ii", $user_id, $current_user_school_id);
        if ($stmt_user->execute()) {
            $stmt_user->bind_result($phone_number_db, $photo_db, $status_db);
            $stmt_user->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');
        } else {
            error_log("Execute failed for user details query in admin_messages.php: " . $stmt_user->error);
        }
        $stmt_user->close();
    } else {
        error_log("Prepare failed for user details query in admin_messages.php: " . $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);
                $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';
                }
            } else {
                error_log("School details not found for school_id: " . $current_user_school_id);
            }
        } else {
            error_log("Execute failed for school data query in admin_messages.php: " . $stmt_school->error);
        }
        $stmt_school->close();
    } else {
        error_log("Prepare failed for school data query in admin_messages.php: " . $conn->error);
    }

    // --- Message Handling Logic ---

    // Handle sending new messages.
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'send_message') {
        $receiver_id = filter_input(INPUT_POST, 'receiver_id', FILTER_SANITIZE_FULL_SPECIAL_CHARS); // Keep as string for "all_students"
        $subject = filter_input(INPUT_POST, 'subject', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        $message_content = filter_input(INPUT_POST, 'message_content', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

        if ($subject && $message_content) {
            $target_receiver_ids = [];

            if ($receiver_id === 'all_students') {
                $sql_get_students = "SELECT id FROM users WHERE school_id = ? AND role = ?";
                if ($stmt_students = $conn->prepare($sql_get_students)) {
                    $student_role = ROLE_STUDENT;
                    $stmt_students->bind_param("ii", $current_user_school_id, $student_role);
                    if ($stmt_students->execute()) {
                        $result_students = $stmt_students->get_result();
                        while ($row = $result_students->fetch_assoc()) {
                            $target_receiver_ids[] = $row['id'];
                        }
                    } else {
                        error_log("Execute failed for get all students query: " . $stmt_students->error);
                    }
                    $stmt_students->close();
                } else {
                    error_log("Prepare failed for get all students query: " . $conn->error);
                }
            } elseif ($receiver_id === 'all_teachers') {
                $sql_get_teachers = "SELECT id FROM users WHERE school_id = ? AND role = ?";
                if ($stmt_teachers = $conn->prepare($sql_get_teachers)) {
                    $teacher_role = ROLE_TEACHER;
                    $stmt_teachers->bind_param("ii", $current_user_school_id, $teacher_role);
                    if ($stmt_teachers->execute()) {
                        $result_teachers = $stmt_teachers->get_result();
                        while ($row = $result_teachers->fetch_assoc()) {
                            $target_receiver_ids[] = $row['id'];
                        }
                    } else {
                        error_log("Execute failed for get all teachers query: " . $stmt_teachers->error);
                    }
                    $stmt_teachers->close();
                } else {
                    error_log("Prepare failed for get all teachers query: " . $conn->error);
                }
            } else {
                // For individual messages, validate as INT.
                $individual_receiver_id = filter_var($receiver_id, FILTER_VALIDATE_INT);
                if ($individual_receiver_id) {
                    $target_receiver_ids[] = $individual_receiver_id;
                }
            }

            if (!empty($target_receiver_ids)) {
                $sql_insert = "INSERT INTO messages (school_id, sender_id, receiver_id, subject, message_content, status) VALUES (?, ?, ?, ?, ?, 'Unread')";
                $all_messages_sent = true;
                foreach ($target_receiver_ids as $target_id) {
                    if ($stmt_insert = $conn->prepare($sql_insert)) {
                        $stmt_insert->bind_param("iiiss", $current_user_school_id, $user_id, $target_id, $subject, $message_content);
                        if (!$stmt_insert->execute()) {
                            $all_messages_sent = false;
                            error_log("Error sending message to receiver_id " . $target_id . ": " . $stmt_insert->error);
                        }
                        $stmt_insert->close();
                    } else {
                        $all_messages_sent = false;
                        error_log("Error preparing message statement for receiver_id " . $target_id . ": " . $conn->error);
                        break; // Stop if prepare fails for one message.
                    }
                }

                if ($all_messages_sent) {
                    $_SESSION['message'] = "Message(s) sent successfully!";
                    $_SESSION['message_type'] = "success";
                } else {
                    $_SESSION['message'] = "Some messages could not be sent. Please check logs.";
                    $_SESSION['message_type'] = "error";
                }
            } else {
                $_SESSION['message'] = "No valid receivers selected or found for the chosen option.";
                $_SESSION['message_type'] = "error";
            }
        } else {
            $_SESSION['message'] = "Please fill all required fields to send a message.";
            $_SESSION['message_type'] = "error";
        }

        $redirect_url = "admin_messages.php";
        if (isset($_GET['lang'])) {
            $redirect_url .= "?lang=" . urlencode($_GET['lang']);
        }
        header("Location: " . $redirect_url);
        exit();
    }

    // Handle marking messages as read.
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'mark_as_read') {
        $message_id = filter_input(INPUT_POST, 'message_id', FILTER_VALIDATE_INT);

        if ($message_id) {
            $sql_update_status = "UPDATE messages SET status = 'Read' WHERE id = ? AND receiver_id = ? AND school_id = ?";
            if ($stmt_update = $conn->prepare($sql_update_status)) {
                $stmt_update->bind_param("iii", $message_id, $user_id, $current_user_school_id);
                if ($stmt_update->execute()) {
                    // Success, no need for a message, just refresh the list.
                } else {
                    error_log("Error marking message as read: " . $stmt_update->error);
                }
                $stmt_update->close();
            } else {
                error_log("Error preparing mark as read statement: " . $conn->error);
            }
        }

        $redirect_url = "admin_messages.php";
        if (isset($_GET['lang'])) {
            $redirect_url .= "?lang=" . urlencode($_GET['lang']);
        }
        header("Location: " . $redirect_url);
        exit();
    }

    // Fetch list of all active users in the same school for the receiver dropdown.
    // Exclude the current user from the list.
    $sql_users = "SELECT id, username, role FROM users WHERE school_id = ? AND status = 'active' AND id != ?";
    if ($stmt_users = $conn->prepare($sql_users)) {
        $stmt_users->bind_param("ii", $current_user_school_id, $user_id);
        if ($stmt_users->execute()) {
            $result_users = $stmt_users->get_result();
            while ($row = $result_users->fetch_assoc()) {
                $usersList[] = $row;
            }
        } else {
            error_log("Execute failed for users list query: " . $stmt_users->error);
        }
        $stmt_users->close();
    } else {
        error_log("Prepare failed for users list query: " . $conn->error);
    }

    // Fetch received messages for the current admin.
    $sql_received = "
        SELECT m.id, m.subject, m.message_content, m.status, m.created_at, u.username AS sender_username, u.role AS sender_role
        FROM messages m
        JOIN users u ON m.sender_id = u.id
        WHERE m.receiver_id = ? AND m.school_id = ?
        ORDER BY m.created_at DESC
    ";
    if ($stmt_received = $conn->prepare($sql_received)) {
        $stmt_received->bind_param("ii", $user_id, $current_user_school_id);
        if ($stmt_received->execute()) {
            $result_received = $stmt_received->get_result();
            while ($row = $result_received->fetch_assoc()) {
                $receivedMessages[] = $row;
            }
        } else {
            error_log("Execute failed for received messages query: " . $stmt_received->error);
        }
        $stmt_received->close();
    } else {
        error_log("Prepare failed for received messages query: " . $conn->error);
    }

    // Fetch sent messages by the current admin.
    $sql_sent = "
        SELECT m.id, m.subject, m.message_content, m.status, m.created_at, u.username AS receiver_username, u.role AS receiver_role
        FROM messages m
        JOIN users u ON m.receiver_id = u.id
        WHERE m.sender_id = ? AND m.school_id = ?
        ORDER BY m.created_at DESC
    ";
    if ($stmt_sent = $conn->prepare($sql_sent)) {
        $stmt_sent->bind_param("ii", $user_id, $current_user_school_id);
        if ($stmt_sent->execute()) {
            $result_sent = $stmt_sent->get_result();
            while ($row = $result_sent->fetch_assoc()) {
                $sentMessages[] = $row;
            }
        } else {
            error_log("Execute failed for sent messages query: " . $stmt_sent->error);
        }
        $stmt_sent->close();
    } else {
        error_log("Prepare failed for sent messages query: " . $conn->error);
    }

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

// Determine role name for display.
$role_name = $lang['unknown_role'];
switch ($user_role_code) {
    case ROLE_SUPER_ADMIN: $role_name = "Super Admin"; break;
    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']);

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

<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $lang['messages_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 {
            padding: 8px 12px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            background-color: #ffffff;
            cursor: pointer;
            font-size: 0.875rem;
            color: #374151;
            appearance: none;
            -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;
        }

        .language-select select:focus {
            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;
        }

        .user-profile div {
            display: flex;
            flex-direction: column;
            text-align: right;
            margin-right: 12px;
        }

        .user-profile .user-name {
            font-weight: 500;
            color: #1f2937;
        }

        .user-profile .user-email {
            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;
        }
        
        .user-profile .fas.fa-chevron-down {
            color: #4b5563;
            font-size: 0.8rem;
        }

        /* Main content area */
        .main-content {
            flex-grow: 1;
            padding: 24px;
            background-color: #f3f4f6;
        }

        /* Message Box */
        .message-box {
            padding: 16px;
            margin-bottom: 16px;
            border-radius: 8px;
            font-weight: 700;
            display: flex;
            justify-content: space-between;
            align-items: center;
            opacity: 1;
            transition: opacity 0.5s ease-out;
        }

        .message-box.success {
            background-color: #d1fae5;
            color: #065f46;
            border: 1px solid #34d399;
        }

        .message-box.error {
            background-color: #fee2e2;
            color: #991b1b;
            border: 1px solid #ef4444;
        }

        .message-box .close-btn {
            background: none;
            border: none;
            font-size: 1rem;
            color: inherit;
            opacity: 0.75;
            cursor: pointer;
        }

        .message-box .close-btn:hover {
            opacity: 1;
        }

        /* Specific styles for messages page */
        .messages-container {
            background-color: #ffffff;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
            margin-top: 20px;
        }

        .tabs {
            display: flex;
            border-bottom: 2px solid #e5e7eb;
            margin-bottom: 25px;
            flex-wrap: wrap;
        }

        .tab-button {
            background-color: #f8f8f8;
            border: 1px solid #e5e7eb;
            border-bottom: none;
            padding: 12px 25px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 500;
            color: #555;
            border-top-left-radius: 8px;
            border-top-right-radius: 8px;
            transition: all 0.2s ease;
            margin-right: 5px;
            margin-bottom: -2px;
            flex-grow: 1;
            text-align: center;
            min-width: 120px;
        }

        .tab-button:hover {
            background-color: #e9ecef;
            color: #1f2937;
        }

        .tab-button.active {
            background-color: #4f46e5;
            color: white;
            border-color: #4f46e5;
            transform: translateY(-2px);
            box-shadow: 0 -3px 8px rgba(0, 0, 0, 0.1);
            z-index: 1;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        /* Compose Message Form */
        .compose-form .form-group {
            margin-bottom: 20px;
        }

        .compose-form label {
            font-weight: 600;
            margin-bottom: 8px;
            display: block;
        }

        .compose-form input[type="text"],
        .compose-form select,
        .compose-form textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.2s ease;
        }

        .compose-form input[type="text"]:focus,
        .compose-form select:focus,
        .compose-form textarea:focus {
            border-color: #4f46e5;
            outline: none;
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }

        .compose-form textarea {
            resize: vertical;
            min-height: 120px;
        }

        .compose-form button {
            background-color: #4f46e5;
            color: white;
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 17px;
            font-weight: 600;
            transition: background-color 0.2s ease, transform 0.2s ease;
        }

        .compose-form button:hover {
            background-color: #3730a3;
            transform: translateY(-2px);
        }

        /* Message Tables */
        .message-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .message-table th, .message-table td {
            border: 1px solid #eee;
            padding: 12px 15px;
            text-align: left;
            vertical-align: top;
        }

        .message-table th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #555;
            position: sticky;
            top: 0;
            z-index: 50;
        }

        .message-table tbody tr:nth-child(even) {
            background-color: #fbfbfb;
        }

        .message-table tbody tr:hover {
            background-color: #e9ecef;
        }

        .message-table .message-subject {
            font-weight: 600;
            color: #4f46e5;
        }
        
        .message-table .message-content {
            font-size: 0.9em;
            color: #666;
            max-width: 400px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .message-table .message-content.expanded {
            white-space: normal;
            overflow: visible;
            text-overflow: clip;
        }

        .message-table .message-status {
            font-weight: 500;
        }
        
        .message-table .message-status.Unread {
            color: #e74c3c;
        }
        
        .message-table .message-status.Read {
            color: #28a745;
        }

        .message-actions button {
            background-color: #4f46e5;
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 0.9em;
            transition: background-color 0.2s ease;
            margin-left: 5px;
        }
        
        .message-actions button:hover {
            background-color: #3730a3;
        }
        
        .message-actions button.mark-read-btn {
            background-color: #28a745;
        }
        
        .message-actions button.mark-read-btn:hover {
            background-color: #218838;
        }

        /* Read Message Modal */
        .modal {
            display: none;
            position: fixed;
            z-index: 2000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.4);
        }

        .modal-content {
            background-color: #fefefe;
            margin: 5% auto;
            padding: 20px;
            border: none;
            border-radius: 12px;
            width: 90%;
            max-width: 600px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }

        .close-button {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close-button:hover,
        .close-button:focus {
            color: black;
            text-decoration: none;
        }

        .modal-content h3 {
            color: #333;
            margin-bottom: 15px;
        }

        .modal-content p {
            margin-bottom: 10px;
            line-height: 1.6;
        }

        .modal-label {
            font-weight: 600;
            color: #333;
            margin-right: 5px;
        }

        .modal-actions {
            margin-top: 20px;
            text-align: right;
        }

        .modal-actions button {
            background-color: #28a745;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
        }

        .modal-actions button:hover {
            background-color: #218838;
        }

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

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

        /* Hide specific items from sidebar on mobile when footer is active */
        .hide-on-mobile {
            display: list-item;
        }

        /* 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 */
            .main-content {
                padding-bottom: 90px;
            }
            
            /* Hide specific items from sidebar on mobile when footer is active */
            .sidebar nav ul li.hide-on-mobile {
                display: none;
            }

            .messages-container {
                padding: 15px;
            }
            
            .tab-button {
                padding: 10px 15px;
                font-size: 14px;
                flex-grow: 1;
                min-width: unset;
            }
            
            .message-table, .message-table tbody, .message-table tr, .message-table td, .message-table th {
                display: block;
            }
            
            .message-table thead {
                display: none;
            }
            
            .message-table tr {
                margin-bottom: 15px;
                border: 1px solid #eee;
                border-radius: 8px;
                display: block;
                padding: 10px;
            }
            
            .message-table td {
                position: relative;
                padding-left: 100px;
                padding-bottom: 10px;
                border: none;
            }
            
            .message-table td::before {
                content: attr(data-label);
                position: absolute;
                left: 10px;
                width: 85px;
                padding-right: 10px;
                white-space: nowrap;
                text-align: left;
                font-weight: 600;
                color: #555;
            }
            
            .message-table .message-content, .message-table .message-content.expanded {
                white-space: normal;
                max-width: unset;
                overflow: visible;
                text-overflow: clip;
            }
            
            .message-actions {
                text-align: center;
                margin-top: 10px;
                padding-left: 10px;
            }
            
            .message-actions button {
                margin: 5px;
            }
        }

        @media (max-width: 480px) {
            .tabs {
                flex-direction: column;
                align-items: stretch;
            }
            
            .tab-button {
                margin-right: 0;
                margin-bottom: 5px;
                border-radius: 8px;
                border-bottom: 1px solid #e5e7eb;
            }
            
            .tab-button.active {
                transform: none;
                box-shadow: none;
            }
        }

        /* Apply this to your button's class or element selector (e.g., .my-button) */
        @media (max-width: 600px) {
          .button-selector {
            white-space: normal;
            word-wrap: break-word;
            padding: 12px 10px;
            min-height: 44px;
            font-size: 0.9em;
            line-height: 1.2;
            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_user_management.php"><i class="fas fa-users-cog"></i> Users</a></li>
                    <li><a href="admin_students.php" id="studentsLink"><i class="fas fa-user-graduate"></i> <?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="active"><a href="admin_messages.php" id="messagesLinkSidebar"><i class="fas fa-envelope"></i> <?php echo $lang['messages_title']; ?></a></li> 
                    <li class="hide-on-mobile"><a href="admin_staff.php" id="staffLink"><i class="fas fa-user-tie"></i> <?php echo $lang['staff']; ?></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="hide-on-mobile"><a href="admin_reports_printouts.php" id="reportsLink"><i class="fas fa-print"></i> <?php echo $lang['reports']; ?></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" onclick="document.getElementById('messageBox').style.display='none';">&times;</button>
                    </div>
                <?php endif; ?>

                <h2><i class="fas fa-envelope"></i> <?php echo $lang['messages_title']; ?></h2>

                <div class="messages-container">
                    <div class="tabs">
                        <button class="tab-button active" data-tab="inbox" id="inboxTabButton"><?php echo $lang['inbox']; ?></button>
                        <button class="tab-button" data-tab="sent" id="sentTabButton"><?php echo $lang['sent']; ?></button>
                        <button class="tab-button" data-tab="compose" id="composeTabButton"><?php echo $lang['compose_message']; ?></button>
                    </div>

                    <div id="inbox" class="tab-content active">
                        <h3><?php echo $lang['received_messages']; ?></h3>
                        <?php if (empty($receivedMessages)): ?>
                            <p id="noReceivedMessages"><?php echo $lang['no_received_messages']; ?></p>
                        <?php else: ?>
                            <div style="overflow-x:auto;">
                                <table class="message-table">
                                    <thead>
                                        <tr>
                                            <th><?php echo $lang['sender']; ?></th>
                                            <th><?php echo $lang['subject']; ?></th>
                                            <th><?php echo $lang['message_text']; ?></th>
                                            <th><?php echo $lang['status']; ?></th>
                                            <th><?php echo $lang['date']; ?></th>
                                            <th><?php echo $lang['actions']; ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($receivedMessages as $msg): ?>
                                            <tr class="<?php echo ($msg['status'] === 'Unread') ? 'unread-message' : ''; ?>">
                                                <td data-label="<?php echo $lang['sender']; ?>:"><?php echo htmlspecialchars($msg['sender_username']) . " (" . htmlspecialchars($msg['sender_role']) . ")"; ?></td>
                                                <td data-label="<?php echo $lang['subject']; ?>:"><span class="message-subject"><?php echo htmlspecialchars($msg['subject']); ?></span></td>
                                                <td data-label="<?php echo $lang['message_text']; ?>:">
                                                    <span class="message-content" data-full-content="<?php echo htmlspecialchars($msg['message_content']); ?>">
                                                        <?php echo htmlspecialchars(substr($msg['message_content'], 0, 100)) . (strlen($msg['message_content']) > 100 ? '...' : ''); ?>
                                                    </span>
                                                </td>
                                                <td data-label="<?php echo $lang['status']; ?>:"><span class="message-status <?php echo htmlspecialchars($msg['status']); ?>"><?php echo htmlspecialchars($msg['status']); ?></span></td>
                                                <td data-label="<?php echo $lang['date']; ?>:"><?php echo date('Y-m-d H:i', strtotime($msg['created_at'])); ?></td>
                                                <td data-label="<?php echo $lang['actions']; ?>:" class="message-actions">
                                                    <button class="view-message-btn" 
                                                        data-message-id="<?php echo $msg['id']; ?>" 
                                                        data-sender="<?php echo htmlspecialchars($msg['sender_username']); ?>" 
                                                        data-subject="<?php echo htmlspecialchars($msg['subject']); ?>" 
                                                        data-content="<?php echo htmlspecialchars($msg['message_content']); ?>" 
                                                        data-status="<?php echo htmlspecialchars($msg['status']); ?>"><?php echo $lang['view']; ?></button>
                                                    <?php if ($msg['status'] === 'Unread'): ?>
                                                        <button class="mark-read-btn" data-message-id="<?php echo $msg['id']; ?>"><?php echo $lang['mark_read']; ?></button>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div id="sent" class="tab-content">
                        <h3><?php echo $lang['sent_messages']; ?></h3>
                        <?php if (empty($sentMessages)): ?>
                            <p id="noSentMessages"><?php echo $lang['no_sent_messages']; ?></p>
                        <?php else: ?>
                            <div style="overflow-x:auto;">
                                <table class="message-table">
                                    <thead>
                                        <tr>
                                            <th><?php echo $lang['receiver']; ?></th>
                                            <th><?php echo $lang['subject']; ?></th>
                                            <th><?php echo $lang['message_text']; ?></th>
                                            <th><?php echo $lang['status']; ?></th>
                                            <th><?php echo $lang['date']; ?></th>
                                            <th><?php echo $lang['actions']; ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($sentMessages as $msg): ?>
                                            <tr>
                                                <td data-label="<?php echo $lang['receiver']; ?>:"><?php echo htmlspecialchars($msg['receiver_username']) . " (" . htmlspecialchars($msg['receiver_role']) . ")"; ?></td>
                                                <td data-label="<?php echo $lang['subject']; ?>:"><span class="message-subject"><?php echo htmlspecialchars($msg['subject']); ?></span></td>
                                                <td data-label="<?php echo $lang['message_text']; ?>:">
                                                    <span class="message-content" data-full-content="<?php echo htmlspecialchars($msg['message_content']); ?>">
                                                        <?php echo htmlspecialchars(substr($msg['message_content'], 0, 100)) . (strlen($msg['message_content']) > 100 ? '...' : ''); ?>
                                                    </span>
                                                </td>
                                                <td data-label="<?php echo $lang['status']; ?>:"><span class="message-status <?php echo htmlspecialchars($msg['status']); ?>"><?php echo htmlspecialchars($msg['status']); ?></span></td>
                                                <td data-label="<?php echo $lang['date']; ?>:"><?php echo date('Y-m-d H:i', strtotime($msg['created_at'])); ?></td>
                                                <td data-label="<?php echo $lang['actions']; ?>:" class="message-actions">
                                                    <button class="view-message-btn" 
                                                        data-message-id="<?php echo $msg['id']; ?>" 
                                                        data-sender="<?php echo htmlspecialchars($msg['receiver_username']); ?>" 
                                                        data-subject="<?php echo htmlspecialchars($msg['subject']); ?>" 
                                                        data-content="<?php echo htmlspecialchars($msg['message_content']); ?>" 
                                                        data-status="<?php echo htmlspecialchars($msg['status']); ?>"><?php echo $lang['view']; ?></button>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div id="compose" class="tab-content">
                        <h3><?php echo $lang['compose_new_message']; ?></h3>
                        <form action="admin_messages.php<?php echo isset($_GET['lang']) ? '?lang=' . urlencode($_GET['lang']) : ''; ?>" method="POST" class="compose-form">
                            <input type="hidden" name="action" value="send_message">
                            <div class="form-group">
                                <label for="receiver_id"><?php echo $lang['to']; ?></label>
                                <select id="receiver_id" name="receiver_id" required>
                                    <option value=""><?php echo $lang['select_receiver']; ?></option>
                                    <option value="all_students"><?php echo $lang['all_students']; ?></option>
                                    <option value="all_teachers"><?php echo $lang['all_teachers']; ?></option>
                                    <optgroup label="<?php echo $lang['individual_users']; ?>">
                                        <?php foreach ($usersList as $user): ?>
                                            <option value="<?php echo htmlspecialchars($user['id']); ?>">
                                                <?php echo htmlspecialchars($user['username']) . " (" . htmlspecialchars($user['role']) . ")"; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="subject"><?php echo $lang['subject']; ?></label>
                                <input type="text" id="subject" name="subject" maxlength="255" required>
                            </div>
                            <div class="form-group">
                                <label for="message_content"><?php echo $lang['message_content']; ?></label>
                                <textarea id="message_content" name="message_content" required></textarea>
                            </div>
                            <button type="submit"><?php echo $lang['send_message']; ?></button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Mobile Footer Navigation -->
    <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" 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_messages.php" class="active" data-section="messages">
                    <i class="fas fa-envelope"></i>
                    <span><?php echo $lang['messages_title']; ?></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>

    <!-- More Menu Modal -->
    <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_students.php"><i class="fas fa-user-graduate"></i> <?php echo $lang['students']; ?></a></li>
            <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>

    <!-- Read Message Modal Structure -->
    <div id="readMessageModal" class="modal">
        <div class="modal-content">
            <span class="close-button">&times;</span>
            <h3 id="modalMessageSubject"></h3>
            <p><span class="modal-label" id="modalLabelFrom"><?php echo $lang['from']; ?></span> <span id="modalMessageSender"></span></p>
            <p><span class="modal-label" id="modalLabelStatus"><?php echo $lang['status']; ?>:</span> <span id="modalMessageStatus"></span></p>
            <p><span class="modal-label" id="modalLabelContent"><?php echo $lang['content']; ?></span></p>
            <div id="modalMessageContent" style="white-space: pre-wrap; word-wrap: break-word;"></div>
            <div class="modal-actions">
                <form method="POST" action="admin_messages.php<?php echo isset($_GET['lang']) ? '?lang=' . urlencode($_GET['lang']) : ''; ?>" style="display: inline;">
                    <input type="hidden" name="action" value="mark_as_read">
                    <input type="hidden" name="message_id" id="modalMarkReadMessageId">
                    <button type="submit" id="modalMarkReadBtn"><?php echo $lang['mark_as_read_modal']; ?></button>
                </form>
            </div>
        </div>
    </div>

    <script>
        // Your existing PHP variable for school name for JS translation
        const schoolNameForJs = "<?php echo $school_name_for_js; ?>";
        const currentUsername = "<?php echo $username; ?>";
        const currentLang = "<?php echo $current_lang; ?>";

        // --- START: Language & Translation Logic ---
        const all_languages_js = <?php echo json_encode($all_languages); ?>;

        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('messagesLinkSidebar').innerHTML = `<i class="fas fa-envelope"></i> ${t.messages_title}`;
            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;
            
            // Messages Page
            document.querySelector('.dashboard-content h2').innerHTML = `<i class="fas fa-envelope"></i> ${t.messages_title}`;
            document.getElementById('inboxTabButton').textContent = t.inbox;
            document.getElementById('sentTabButton').textContent = t.sent;
            document.getElementById('composeTabButton').textContent = t.compose_message;

            // 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 === 'messages') link.querySelector('span').textContent = t.messages_title;
                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;
            document.querySelector('#more-menu-list a[href="admin_students.php"]').innerHTML = `<i class="fas fa-user-graduate"></i> ${t.students}`;
            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}`;
        } 
        // --- END: Language & Translation Logic ---

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

        // Set the initial selected option
        languageSelect.value = savedLang;
        
        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';
            } 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);
                // Also close read message modal if open
                const readMessageModal = document.getElementById('readMessageModal');
                if (readMessageModal.style.display === 'block') {
                    readMessageModal.style.display = 'none';
                }
            });
        }
        // --- 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 ---

        // Tab functionality
        const tabButtons = document.querySelectorAll('.tab-button');
        const tabContents = document.querySelectorAll('.tab-content');

        tabButtons.forEach(button => {
            button.addEventListener('click', () => {
                // Deactivate all tabs and hide all content
                tabButtons.forEach(btn => btn.classList.remove('active'));
                tabContents.forEach(content => content.classList.remove('active'));

                // Activate clicked tab and show corresponding content
                button.classList.add('active');
                const targetTabId = button.dataset.tab;
                document.getElementById(targetTabId).classList.add('active');
            });
        });

        // Read Message Modal Logic
        const readMessageModal = document.getElementById('readMessageModal');
        const closeModalButton = readMessageModal.querySelector('.close-button');
        const modalMessageSubject = document.getElementById('modalMessageSubject');
        const modalMessageSender = document.getElementById('modalMessageSender');
        const modalMessageStatus = document.getElementById('modalMessageStatus');
        const modalMessageContent = document.getElementById('modalMessageContent');
        const modalMarkReadBtn = document.getElementById('modalMarkReadBtn');
        const modalMarkReadMessageId = document.getElementById('modalMarkReadMessageId');

        document.addEventListener('click', (event) => {
            if (event.target.classList.contains('view-message-btn')) {
                const button = event.target;
                const messageId = button.dataset.messageId;
                const sender = button.dataset.sender;
                const subject = button.dataset.subject;
                const content = button.dataset.content;
                const status = button.dataset.status;

                modalMessageSubject.textContent = subject;
                modalMessageSender.textContent = sender;
                modalMessageStatus.textContent = status;
                modalMessageContent.textContent = content;
                modalMarkReadMessageId.value = messageId;

                // Hide Mark as Read button if already read
                if (status === 'Read') {
                    modalMarkReadBtn.style.display = 'none';
                } else {
                    modalMarkReadBtn.style.display = 'inline-block';
                }

                readMessageModal.style.display = 'block';
                overlay.classList.add('show');
            }
        });

        closeModalButton.addEventListener('click', () => {
            readMessageModal.style.display = 'none';
            overlay.classList.remove('show');
        });

        // Direct Mark as Read buttons (for the table rows themselves)
        document.querySelectorAll('.mark-read-btn').forEach(button => {
            button.addEventListener('click', (event) => {
                const messageId = event.target.dataset.messageId;
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = window.location.href;
                
                const actionInput = document.createElement('input');
                actionInput.type = 'hidden';
                actionInput.name = 'action';
                actionInput.value = 'mark_as_read';
                
                const messageIdInput = document.createElement('input');
                messageIdInput.type = 'hidden';
                messageIdInput.name = 'message_id';
                messageIdInput.value = messageId;
                
                form.appendChild(actionInput);
                form.appendChild(messageIdInput);
                document.body.appendChild(form);
                form.submit();
            });
        });

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