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

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

// Define role constants.
if (!defined('ROLE_SUPER_ADMIN')) define('ROLE_SUPER_ADMIN', 1);
if (!defined('ROLE_ADMIN')) define('ROLE_ADMIN', 2);
if (!defined('ROLE_TEACHER')) define('ROLE_TEACHER', 3);
if (!defined('ROLE_STUDENT')) define('ROLE_STUDENT', 4);
if (!defined('ROLE_PARENT')) define('ROLE_PARENT', 5);
if (!defined('ROLE_STAFF')) define('ROLE_STAFF', 6);

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

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

$current_lang = $_SESSION['lang'];

/**
 * Loads language-specific strings.
 * @param string $lang The current language code.
 * @return array An associative array of localized strings.
 */
function load_language_data($lang) {
    $data = [
        'en' => [
            'dashboard_title_prefix' => 'Student Dashboard',
            'sidebar_dashboard' => 'Dashboard',
            'sidebar_profile' => 'Profile',
            'sidebar_reports' => 'Reports',
            'sidebar_assignments' => 'Assignments',
            'sidebar_messages' => 'Messages',
            'sidebar_settings' => 'Settings',
            'sidebar_logout' => 'Logout',
            'school_name_not_found' => 'School Name Not Found',
            'search_placeholder' => 'Search messages',
            'welcome_message_prefix' => 'Welcome',
            'welcome_message_suffix' => '!',
            'logged_in_as' => 'Logged in as:',
            'divine_reports' => 'DIVINE REPORTS',
            'messages_heading' => 'My Messages',
            'new_message_button' => 'New Message',
            'sender_column' => 'Sender',
            'receiver_column' => 'Receiver',
            'subject_column' => 'Subject',
            'content_column' => 'Content',
            'status_column' => 'Status',
            'date_column' => 'Date',
            'actions_column' => 'Actions',
            'read_message_button' => 'Read Message',
            'no_messages_found' => 'No messages found.',
            'message_details_heading' => 'Message Details',
            'from_label' => 'From:',
            'to_label' => 'To:',
            'message_status_read' => 'Read',
            'message_status_unread' => 'Unread',
            'loading_message' => 'Loading message...',
            'error_loading_message' => 'Error loading message details.'
        ],
        'lug' => [
            'dashboard_title_prefix' => 'Diisiboodi y\'Omuyizi',
            'sidebar_dashboard' => 'Diisiboodi',
            'sidebar_profile' => 'Purofayiro',
            'sidebar_reports' => 'Lipooti',
            'sidebar_assignments' => 'Ebitongole',
            'sidebar_messages' => 'Obubaka',
            'sidebar_settings' => 'Enteekateeka',
            'sidebar_logout' => 'Log Out',
            'school_name_not_found' => 'Erinnya ly\'Essomero Terinnaba Kulabika',
            'search_placeholder' => 'Noonya obubaka',
            'welcome_message_prefix' => 'Mpulira Olamusiddwa',
            'welcome_message_suffix' => '!',
            'logged_in_as' => 'Oyinze okukakasa nga:',
            'divine_reports' => 'RIPOTA ZA MUNGU',
            'messages_heading' => 'Obubaka Bwange',
            'new_message_button' => 'Obubaka Obupya',
            'sender_column' => 'Omuweerezi',
            'receiver_column' => 'Omutandisi',
            'subject_column' => 'Omutwe',
            'content_column' => 'Ebiri mu Bwaka',
            'status_column' => 'Embeera',
            'date_column' => 'Ennaku',
            'actions_column' => 'Ebikolebwa',
            'read_message_button' => 'Soma Obubaka',
            'no_messages_found' => 'Tewali bubaka busangiddwa.',
            'message_details_heading' => 'Ebikwata ku Bwaka',
            'from_label' => 'Okuva:',
            'to_label' => 'Okudda ewa:',
            'message_status_read' => 'Busomeddwa',
            'message_status_unread' => 'Butasomeddwa',
            'loading_message' => 'Nsomesa obubaka...',
            'error_loading_message' => 'Waliwo ekifuuse bubi mu kusoma obubaka.'
        ],
        'sw' => [
            'dashboard_title_prefix' => 'Dashibodi ya Mwanafunzi',
            'sidebar_dashboard' => 'Dashibodi',
            'sidebar_profile' => 'Wasifu',
            'sidebar_reports' => 'Ripoti',
            'sidebar_assignments' => 'Kazi',
            'sidebar_messages' => 'Ujumbe',
            'sidebar_settings' => 'Mipangilio',
            'sidebar_logout' => 'Ondoka',
            'school_name_not_found' => 'Jina la Shule Halikupatikana',
            'search_placeholder' => 'Tafuta ujumbe',
            'welcome_message_prefix' => 'Karibu',
            'welcome_message_suffix' => '!',
            'logged_in_as' => 'Umeingia kama:',
            'divine_reports' => 'RIPOTI ZA MUNGU',
            'messages_heading' => 'Ujumbe Wangu',
            'new_message_button' => 'Ujumbe Mpya',
            'sender_column' => 'Mtumaji',
            'receiver_column' => 'Mpokeaji',
            'subject_column' => 'Mada',
            'content_column' => 'Maudhui',
            'status_column' => 'Hali',
            'date_column' => 'Tarehe',
            'actions_column' => 'Vitendo',
            'read_message_button' => 'Soma Ujumbe',
            'no_messages_found' => 'Hakuna ujumbe uliopatikana.',
            'message_details_heading' => 'Maelezo ya Ujumbe',
            'from_label' => 'Kutoka:',
            'to_label' => 'Kwa:',
            'message_status_read' => 'Umesomwa',
            'message_status_unread' => 'Haujasomwa',
            'loading_message' => 'Inapakia ujumbe...',
            'error_loading_message' => 'Hitilafu wakati wa kupakia maelezo ya ujumbe.'
        ]
    ];
    return $data[$lang] ?? $data['en']; // Fallback to English if language not found
}

$_L = load_language_data($current_lang);

/**
 * Function to check the user's role and redirect if they are unauthorized to access the current page.
 * @param int $required_role_code The role code required to access this page.
 */
function check_role_access($required_role_code) {
    if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || !isset($_SESSION["school_id"])) {
        header("location: login.php");
        exit;
    }

    if ($_SESSION["role"] !== $required_role_code) {
        switch ($_SESSION["role"]) {
            case ROLE_SUPER_ADMIN:
                header("location: super_admin_dashboard.php");
                break;
            case ROLE_ADMIN:
                header("location: admin_dashboard.php");
                break;
            case ROLE_TEACHER:
                header("location: teacher_dashboard.php");
                break;
            default:
                header("location: login.php");
                break;
        }
        exit;
    }
}

check_role_access(ROLE_STUDENT);

$currentPage = 'messages';

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

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

$role_name = "Unknown";
switch ($user_role_code) {
    case ROLE_SUPER_ADMIN: $role_name = "Super Admin"; break;
    case ROLE_ADMIN:        $role_name = "Admin";       break;
    case ROLE_TEACHER:      $role_name = "Teacher";     break;
    case ROLE_STUDENT:      $role_name = "Student";     break;
    case ROLE_PARENT:       $role_name = "Parent";      break;
    case ROLE_STAFF:        $role_name = "Staff";       break;
}

// Handle AJAX requests for messages
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action'])) {
    header('Content-Type: application/json');
    ini_set('display_errors', 0);
    error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);

    if (!isset($conn) || !$conn instanceof mysqli) {
        require 'config.php';
        if (!isset($conn) || !$conn instanceof mysqli) {
            echo json_encode(['success' => false, 'message' => 'Database connection error.']);
            exit;
        }
    }

    if ($_POST['action'] == 'fetch_message_details') {
        $message_id = filter_input(INPUT_POST, 'message_id', FILTER_VALIDATE_INT);
        if ($message_id) {
            $sql_message_details = "
                SELECT
                    m.id,
                    COALESCE(s.username, 'System') AS sender_name,
                    COALESCE(r.username, 'System') AS receiver_name,
                    m.subject,
                    m.message_content,
                    m.status,
                    m.created_at
                FROM
                    messages m
                LEFT JOIN
                    users s ON m.sender_id = s.id
                LEFT JOIN
                    users r ON m.receiver_id = r.id
                WHERE
                    m.id = ? AND (m.sender_id = ? OR m.receiver_id = ?) AND m.school_id = ?;
            ";
            if ($stmt_details = $conn->prepare($sql_message_details)) {
                $stmt_details->bind_param("iiii", $message_id, $student_user_id, $student_user_id, $school_id);
                if ($stmt_details->execute()) {
                    $result_details = $stmt_details->get_result();
                    if ($message = $result_details->fetch_assoc()) {
                        // If the message was received by the current student and is 'Unread', mark it as 'Read'
                        if ($message['receiver_name'] == $username && $message['status'] == 'Unread') {
                            $sql_mark_read = "UPDATE messages SET status = 'Read' WHERE id = ?";
                            if ($stmt_mark_read = $conn->prepare($sql_mark_read)) {
                                $stmt_mark_read->bind_param("i", $message_id);
                                $stmt_mark_read->execute();
                                $stmt_mark_read->close();
                                $message['status'] = 'Read'; // Update status for immediate response
                            }
                        }
                        echo json_encode(['success' => true, 'message_data' => $message]);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'Message not found.']);
                    }
                } else {
                    error_log("Execute failed for message details query: " . $stmt_details->error);
                    echo json_encode(['success' => false, 'message' => 'Error executing query.']);
                }
                $stmt_details->close();
            } else {
                error_log("Prepare failed for message details query: " . $conn->error);
                echo json_encode(['success' => false, 'message' => 'Error preparing query.']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Invalid message ID.']);
        }
    }
    $conn->close();
    exit;
}

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

    $sql_school_details = "SELECT school_name, logo FROM schools WHERE school_id = ?";
    if ($stmt_school = $conn->prepare($sql_school_details)) {
        $stmt_school->bind_param("i", $school_id);
        if ($stmt_school->execute()) {
            $stmt_school->bind_result($school_name_db, $school_logo_db);
            if ($stmt_school->fetch()) {
                $school_name = htmlspecialchars($school_name_db);
                $school_logo_path = !empty($school_logo_db) ? htmlspecialchars($school_logo_db) : 'images/default_school_logo.png';
            }
        }
        $stmt_school->close();
    }

    $studentMessages = [];
    $sql_messages = "
        SELECT
            m.id,
            COALESCE(s.username, 'System') AS sender_name,
            COALESCE(r.username, 'System') AS receiver_name,
            m.subject,
            m.message_content,
            m.status,
            m.created_at
        FROM
            messages m
        LEFT JOIN
            users s ON m.sender_id = s.id
        LEFT JOIN
            users r ON m.receiver_id = r.id
        WHERE
            (m.sender_id = ? OR m.receiver_id = ?) AND m.school_id = ?
        ORDER BY
            m.created_at DESC;
    ";
    if ($stmt_messages = $conn->prepare($sql_messages)) {
        $stmt_messages->bind_param("iii", $student_user_id, $student_user_id, $school_id);
        if ($stmt_messages->execute()) {
            $result_messages = $stmt_messages->get_result();
            while ($row = $result_messages->fetch_assoc()) {
                $studentMessages[] = $row;
            }
        } else {
            error_log("Execute failed for messages query: " . $stmt_messages->error);
        }
        $stmt_messages->close();
    } else {
        error_log("Prepare failed for messages query: " . $conn->error);
    }

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $_L['sidebar_messages']; ?> - <?php echo $school_name; ?></title>
    <link rel="stylesheet" href="style.css">
    <link rel="icon" href="<?php echo $school_logo_path; ?>" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        /* Fixed Header and Sidebar Styles */
        .dashboard-container {
            display: flex;
            height: 100vh;
            overflow: hidden;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

            .header {
                left: 0;
            }
        }

        .modern-table-container {
            border-collapse: separate;
            border-spacing: 0;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            border-radius: 0.75rem;
        }
        .modern-table-container th,
        .modern-table-container td {
            padding: 1rem 1.5rem;
            text-align: left;
            border-bottom: 1px solid #e2e8f0;
        }
        .modern-table-container thead th {
            background-color: #f8fafc;
            color: #475569;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            font-size: 0.875rem;
        }
        .modern-table-container tbody tr:last-child td {
            border-bottom: none;
        }
        .modern-table-container tbody tr:hover {
            background-color: #f0f8ff;
            transition: background-color 0.2s ease-in-out;
        }
        .modern-table-container tbody td {
            color: #334155;
            font-size: 0.95rem;
        }
        .modern-table-container tbody tr td[colspan] {
            font-style: italic;
            color: #64748b;
            text-align: center;
            padding: 1.5rem;
        }
        .overflow-x-auto {
            width: 100%;
        }

        /* Modal Specific Styles */
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.3s ease-in-out, visibility 0.3s ease-in-out;
        }
        .modal.show {
            opacity: 1;
            visibility: visible;
        }
        .modal-content {
            background-color: #ffffff;
            padding: 2rem;
            border-radius: 0.75rem;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
            width: 90%;
            max-width: 600px;
            transform: translateY(-20px);
            transition: transform 0.3s ease-in-out;
        }
        .modal.show .modal-content {
            transform: translateY(0);
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            padding-bottom: 1rem;
        }
        .modal-header h2 {
            font-size: 1.75rem;
            font-weight: bold;
            color: #1e293b;
        }
        .modal-close-button {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #64748b;
        }
        .message-detail-item {
            margin-bottom: 1rem;
        }
        .message-detail-item label {
            font-weight: 600;
            color: #475569;
            margin-right: 0.5rem;
        }
        .message-content-box {
            background-color: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 0.5rem;
            padding: 1rem;
            min-height: 100px;
            overflow-y: auto;
            color: #334155;
            line-height: 1.6;
        }
        .status-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        .status-badge.unread {
            background-color: #fee2e2;
            color: #dc2626;
        }
        .status-badge.read {
            background-color: #d1fae5;
            color: #065f46;
        }
    
        /* Hide specific items from sidebar on mobile when footer is active */
        .hide-on-mobile {
            display: list-item;
        }

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

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

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

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

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

        #mobile-footer-nav a.active {
            color: #4f46e5;
        }

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

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

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

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

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

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

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

        /* Overlay for mobile sidebar and modal */
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1500;
            display: none;
        }
        
        .overlay.show {
            display: block;
        }

        /* Responsive adjustments */
        @media (max-width: 768px) {
            #mobile-footer-nav {
                display: block;
            }
            
            #more-menu-modal {
                display: block;
            }
            
            /* Adjust main content padding to account for fixed footer */
            .content-wrapper {
                padding-bottom: 90px;
            }
            
            /* Hide specific items from sidebar on mobile when footer is active */
            .sidebar nav ul li.hide-on-mobile {
                display: none;
            }
        }

    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <aside class="sidebar" id="sidebar">
            <div class="logo">
                <img src="images/logo.png" alt="divine Logo">
                <?php echo $_L['divine_reports']; ?>
            </div>
            <nav>
                <ul>
                    <li class="<?php echo ($currentPage == 'dashboard' ? 'active' : ''); ?>"><a href="student_dashboard.php"><i class="fas fa-th-large"></i> <?php echo $_L['sidebar_dashboard']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'profile' ? 'active' : ''); ?>"><a href="student_profile.php"><i class="fas fa-user-circle"></i> <?php echo $_L['sidebar_profile']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'reports' ? 'active' : ''); ?>"><a href="student_reports.php"><i class="fas fa-file-invoice"></i> <?php echo $_L['sidebar_reports']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'assignments' ? 'active' : ''); ?>"><a href="student_assignments.php"><i class="fas fa-file-alt"></i> <?php echo $_L['sidebar_assignments']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'messages' ? 'active' : ''); ?>"><a href="student_messages.php"><i class="fas fa-envelope"></i> <?php echo $_L['sidebar_messages']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'settings' ? 'active' : ''); ?>"><a href="student_settings.php"><i class="fas fa-cog"></i> <?php echo $_L['sidebar_settings']; ?></a></li>
                    <li><a href="logout.php"><i class="fas fa-sign-out-alt"></i> <?php echo $_L['sidebar_logout']; ?></a></li>
                </ul>
            </nav>
        </aside>

        <div class="main-content">
            <header class="header">
                <button class="menu-toggle" id="menuToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="school-info">
                    <img src="<?php echo $school_logo_path; ?>" alt="<?php echo $school_name; ?> Logo">
                    <h1><?php echo $school_name; ?></h1>
                </div>
                <div class="header-right">
                    <div class="language-select">
                        <select id="languageSelector" onchange="changeLanguage(this.value)">
                           <option value="en" <?php if ($current_lang === 'en') echo 'selected'; ?>>🇬🇧 English</option>
                           <option value="lug" <?php if ($current_lang === 'lug') echo 'selected'; ?>>🇺🇬 Luganda</option>
                           <option value="sw" <?php if ($current_lang === 'sw') echo 'selected'; ?>>🇹🇿 Kiswahili</option>
                        </select>
                    </div>
                    <div class="search-bar">
                        <i class="fas fa-search"></i>
                        <input type="text" placeholder="<?php echo $_L['search_placeholder']; ?>">
                    </div>
                    <div class="notifications">
                        <i class="fas fa-bell"></i>
                        <span class="badge">3</span>
                    </div>
                    <div class="user-profile">
                        <img src="<?php echo $student_photo; ?>" alt="User Photo">
                        <div>
                            <div class="user-name"><?php echo $username; ?></div>
                            <div class="user-email"><?php echo $_L['logged_in_as']; ?> <?php echo $role_name; ?></div>
                        </div>
                        <i class="fas fa-chevron-down"></i>
                    </div>
                </div>
            </header>

            <div class="content-wrapper">
                <div class="container mx-auto p-6 lg:p-8">
                    <div class="bg-white rounded-lg shadow-md p-6">
                        <div class="flex justify-between items-center mb-6">
                            <h1 class="text-3xl font-bold text-blue-700"><?php echo $_L['messages_heading']; ?></h1>
                            <button class="bg-green-600 hover:bg-green-700 text-white font-bold py-2.5 px-5 rounded-lg transition duration-150 ease-in-out shadow-md">
                                <?php echo $_L['new_message_button']; ?>
                            </button>
                        </div>

                        <!-- Messages Table -->
                        <div class="overflow-x-auto modern-table-container">
                            <table class="min-w-full bg-white">
                                <thead>
                                    <tr>
                                        <th><?php echo $_L['sender_column']; ?></th>
                                        <th><?php echo $_L['receiver_column']; ?></th>
                                        <th><?php echo $_L['subject_column']; ?></th>
                                        <th><?php echo $_L['content_column']; ?></th>
                                        <th><?php echo $_L['status_column']; ?></th>
                                        <th><?php echo $_L['date_column']; ?></th>
                                        <th><?php echo $_L['actions_column']; ?></th>
                                    </tr>
                                </thead>
                                <tbody id="messagesTableBody">
                                    <?php if (!empty($studentMessages)): ?>
                                        <?php foreach ($studentMessages as $message): ?>
                                            <tr data-message-id="<?php echo htmlspecialchars($message['id']); ?>">
                                                <td><?php echo htmlspecialchars($message['sender_name']); ?></td>
                                                <td><?php echo htmlspecialchars($message['receiver_name']); ?></td>
                                                <td><?php echo htmlspecialchars($message['subject']); ?></td>
                                                <td><?php echo htmlspecialchars(substr($message['message_content'], 0, 50)) . (strlen($message['message_content']) > 50 ? '...' : ''); ?></td>
                                                <td>
                                                    <span class="status-badge <?php echo ($message['status'] === 'Read' ? 'read' : 'unread'); ?>">
                                                        <?php echo htmlspecialchars(ucfirst($message['status'])); ?>
                                                    </span>
                                                </td>
                                                <td><?php echo htmlspecialchars(date('Y-m-d H:i', strtotime($message['created_at']))); ?></td>
                                                <td>
                                                    <button class="bg-blue-500 hover:bg-blue-600 text-white font-semibold py-1.5 px-3 rounded-md text-xs read-message-btn" data-message-id="<?php echo htmlspecialchars($message['id']); ?>">
                                                        <i class="fas fa-eye mr-1"></i> <?php echo $_L['read_message_button']; ?>
                                                    </button>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="7" class="text-center text-gray-500 py-4">
                                                <?php echo $_L['no_messages_found']; ?>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Message Details Modal -->
    <div id="messageDetailsModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modalMessageSubject"></h2>
                <button class="modal-close-button" id="closeMessageModalBtn">&times;</button>
            </div>
            <div class="modal-body">
                <div class="message-detail-item">
                    <label><?php echo $_L['from_label']; ?></label>
                    <span id="modalMessageSender"></span>
                </div>
                <div class="message-detail-item">
                    <label><?php echo $_L['to_label']; ?></label>
                    <span id="modalMessageReceiver"></span>
                </div>
                <div class="message-detail-item">
                    <label><?php echo $_L['date_column']; ?>:</label>
                    <span id="modalMessageDate"></span>
                </div>
                <div class="message-detail-item">
                    <label><?php echo $_L['status_column']; ?>:</label>
                    <span id="modalMessageStatus" class="status-badge"></span>
                </div>
                <hr class="my-4 border-gray-200">
                <p id="modalMessageContent" class="message-content-box"></p>
            </div>
        </div>
    </div>

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

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

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

                dashboardContainer.addEventListener('click', function(event) {
                    if (sidebar.classList.contains('active') && !sidebar.contains(event.target) && !menuToggle.contains(event.target)) {
                        sidebar.classList.remove('active');
                        dashboardContainer.classList.remove('sidebar-open');
                    }
                });
            } else {
                console.error("Menu toggle, sidebar, or dashboard container elements for responsive behavior not found.");
            }

            // --- Message Details Modal Logic ---
            const messageDetailsModal = document.getElementById('messageDetailsModal');
            const closeMessageModalBtn = document.getElementById('closeMessageModalBtn');
            const messagesTableBody = document.getElementById('messagesTableBody');

            const modalMessageSubject = document.getElementById('modalMessageSubject');
            const modalMessageSender = document.getElementById('modalMessageSender');
            const modalMessageReceiver = document.getElementById('modalMessageReceiver');
            const modalMessageDate = document.getElementById('modalMessageDate');
            const modalMessageStatus = document.getElementById('modalMessageStatus');
            const modalMessageContent = document.getElementById('modalMessageContent');

            // Event delegation for "Read Message" buttons
            messagesTableBody.addEventListener('click', function(event) {
                if (event.target.classList.contains('read-message-btn')) {
                    const messageId = event.target.dataset.messageId;
                    fetchMessageDetails(messageId, event.target);
                }
            });

            closeMessageModalBtn.addEventListener('click', () => {
                messageDetailsModal.classList.remove('show');
            });

            window.addEventListener('click', (event) => {
                if (event.target === messageDetailsModal) {
                    messageDetailsModal.classList.remove('show');
                }
            });

            function fetchMessageDetails(messageId, buttonElement) {
                // Clear previous content and show loading state
                modalMessageSubject.textContent = "<?php echo $_L['loading_message']; ?>";
                modalMessageSender.textContent = '';
                modalMessageReceiver.textContent = '';
                modalMessageDate.textContent = '';
                modalMessageStatus.textContent = '';
                modalMessageStatus.className = 'status-badge';
                modalMessageContent.textContent = '';
                messageDetailsModal.classList.add('show');

                const formData = new URLSearchParams();
                formData.append('action', 'fetch_message_details');
                formData.append('message_id', messageId);

                fetch('student_messages.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: formData
                })
                .then(response => {
                    const contentType = response.headers.get("content-type");
                    if (contentType && contentType.indexOf("application/json") !== -1) {
                        return response.json();
                    } else {
                        return response.text().then(text => {
                            console.error("Non-JSON response:", text);
                            throw new Error("Server did not return JSON. Full response: " + text);
                        });
                    }
                })
                .then(data => {
                    if (data.success && data.message_data) {
                        const message = data.message_data;
                        modalMessageSubject.textContent = message.subject;
                        modalMessageSender.textContent = message.sender_name;
                        modalMessageReceiver.textContent = message.receiver_name;
                        modalMessageDate.textContent = new Date(message.created_at).toLocaleString();
                        modalMessageContent.textContent = message.message_content;

                        // Update status badge
                        modalMessageStatus.textContent = message.status === 'Read' ? "<?php echo $_L['message_status_read']; ?>" : "<?php echo $_L['message_status_unread']; ?>";
                        modalMessageStatus.classList.add(message.status === 'Read' ? 'read' : 'unread');

                        // Update the table row status if it was unread and is now read
                        const row = buttonElement.closest('tr');
                        if (row && message.status === 'Read') {
                            const statusSpanInTable = row.querySelector('.status-badge');
                            if (statusSpanInTable && statusSpanInTable.textContent.trim() === "<?php echo $_L['message_status_unread']; ?>") {
                                statusSpanInTable.textContent = "<?php echo $_L['message_status_read']; ?>";
                                statusSpanInTable.classList.remove('unread');
                                statusSpanInTable.classList.add('read');
                            }
                        }
                    } else {
                        modalMessageSubject.textContent = "<?php echo $_L['error_loading_message']; ?>";
                        modalMessageContent.textContent = data.message || 'Details unavailable.';
                    }
                })
                .catch(error => {
                    console.error('Error fetching message details:', error);
                    modalMessageSubject.textContent = "<?php echo $_L['error_loading_message']; ?>";
                    modalMessageContent.textContent = 'Please check console for more details.';
                });
            }
        });
    
        // --- START: Mobile Footer Modal Logic ---
        document.addEventListener('DOMContentLoaded', function() {
            const moreMenuButton = document.getElementById('moreMenuButton');
            const moreMenuModal = document.getElementById('more-menu-modal');
            const moreMenuCloseBtn = document.getElementById('more-menu-close-btn');
            const overlay = document.getElementById('overlay');

            function toggleMoreMenu(show) {
                if (show) {
                    moreMenuModal.classList.add('show');
                    overlay.classList.add('show');
                    document.body.style.overflow = 'hidden';
                } else {
                    moreMenuModal.classList.remove('show');
                    overlay.classList.remove('show');
                    document.body.style.overflow = '';
                }
            }

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

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

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

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

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

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

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


</body>
</html>
