<?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 they are not already defined.
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' => [
            'messages_title_prefix' => 'Messages',
            'sidebar_dashboard' => 'Dashboard',
            'sidebar_my_classes' => 'My Classes',
            'sidebar_my_students' => 'My Students',
            'sidebar_assignments' => 'Assignments',
            'sidebar_grades' => 'Grades',
            'sidebar_messages' => 'Messages',
            'sidebar_calendar' => 'Calendar',
            'sidebar_profile' => 'Profile',
            'sidebar_settings' => 'Settings',
            'sidebar_logout' => 'Logout',
            'school_name_not_found' => 'School Name Not Found',
            'search_placeholder' => 'Search students/data',
            'logged_in_as' => 'Logged in as:',
            'divine_reports' => 'DIVINE REPORTS',
            'compose_message_heading' => 'Compose New Message',
            'sent_messages_heading' => 'Sent Messages',
            'received_messages_heading' => 'Received Messages',
            'tab_compose' => 'Compose',
            'tab_sent' => 'Sent',
            'tab_received' => 'Received',
            'recipient_label' => 'Recipient:',
            'subject_label' => 'Subject:',
            'message_label' => 'Message:',
            'send_button' => 'Send Message',
            'select_recipient_placeholder' => 'Select Recipient',
            'no_sent_messages' => 'You have not sent any messages yet.',
            'no_received_messages' => 'You have not received any messages yet.',
            'from_label' => 'From',
            'to_label' => 'To',
            'date_label' => 'Date',
            'status_label' => 'Status',
            'action_label' => 'Action', // Added for delete button column
            'message_sent_success' => 'Message sent successfully!',
            'message_sent_error' => 'Error sending message. Please try again.',
            'compose_message_info' => 'Compose and send messages to administrators of your school.',
            'no_admin_found' => 'No admin found in your school to send message to.',
            'delete_button' => 'Delete',
            'delete_confirm_title' => 'Confirm Deletion',
            'delete_confirm_message' => 'Are you sure you want to delete this message? This action cannot be undone.',
            'delete_success' => 'Message deleted successfully.',
            'delete_error' => 'Error deleting message. Please try again.',
        ],
        'lug' => [
            'messages_title_prefix' => 'Obubaka',
            'sidebar_dashboard' => 'Diisiboodi',
            'sidebar_my_classes' => 'Ebibiina Byange',
            'sidebar_my_students' => 'Bayizi Bange',
            'sidebar_assignments' => 'Ebitongole',
            'sidebar_grades' => 'Akaadi',
            'sidebar_messages' => 'Obubaka',
            'sidebar_calendar' => 'Kkalenda',
            'sidebar_profile' => 'Purofayiro',
            'sidebar_settings' => 'Enteekateeka',
            'sidebar_logout' => 'Log Out',
            'school_name_not_found' => 'Erinnya ly’Essomero Terinnaba Kulabika',
            'search_placeholder' => 'Noonya abayizi/data',
            'logged_in_as' => 'Oyinze okukakasa nga:',
            'divine_reports' => 'RIPOTA ZA MUNGU',
            'compose_message_heading' => 'Wandiika Obubaka Obupya',
            'sent_messages_heading' => 'Obubaka Obutumiddwa',
            'received_messages_heading' => 'Obubaka Obufuniddwa',
            'tab_compose' => 'Wandiika',
            'tab_sent' => 'Obutumiddwa',
            'tab_received' => 'Obufuniddwa',
            'recipient_label' => 'Omuweereza:',
            'subject_label' => 'Ekitongole:',
            'message_label' => 'Obubaka:',
            'send_button' => 'Tumira Obubaka',
            'select_recipient_placeholder' => 'Londa Omuweereza',
            'no_sent_messages' => 'Tewali bubaka bw’otumidde.',
            'no_received_messages' => 'Tewali bubaka bw’ofunye.',
            'from_label' => 'Okuva',
            'to_label' => 'Ku',
            'date_label' => 'Olunaku',
            'status_label' => 'Embeera',
            'action_label' => 'Ekyakolebwa', // Added for delete button column
            'message_sent_success' => 'Obubaka butumiddwa bulungi!',
            'message_sent_error' => 'Waliwo ensobi mu kutumira obubaka. Gerageza nate.',
            'compose_message_info' => 'Wandiika era otumire obubaka eri abakulembeze b’essomero lyo.',
            'no_admin_found' => 'Tewali mukulembeze mu ssomero lyo gwe tuyinza okutumira obubaka.',
            'delete_button' => 'Gyawo',
            'delete_confirm_title' => 'Kakasa Okugyawo',
            'delete_confirm_message' => 'Olukakasa okugyawo obubaka buno? Ekikolwa kino tekisobola kuddizibwa.',
            'delete_success' => 'Obubaka bugyiddwawo bulungi.',
            'delete_error' => 'Waliwo ensobi mu kugyawo obubaka. Gerageza nate.',
        ],
        'sw' => [
            'messages_title_prefix' => 'Ujumbe',
            'sidebar_dashboard' => 'Dashibodi',
            'sidebar_my_classes' => 'Madarasa Yangu',
            'sidebar_my_students' => 'Wanafunzi Wangu',
            'sidebar_assignments' => 'Kazi',
            'sidebar_grades' => 'Alama',
            'sidebar_messages' => 'Ujumbe',
            'sidebar_calendar' => 'Kalenda',
            'sidebar_profile' => 'Wasifu',
            'sidebar_settings' => 'Mipangilio',
            'sidebar_logout' => 'Ondoka',
            'school_name_not_found' => 'Jina la Shule Halikupatikana',
            'search_placeholder' => 'Tafuta wanafunzi/data',
            'logged_in_as' => 'Umeingia kama:',
            'divine_reports' => 'RIPOTI ZA MUNGU',
            'compose_message_heading' => 'Andika Ujumbe Mpya',
            'sent_messages_heading' => 'Ujumbe Uliotumwa',
            'received_messages_heading' => 'Ujumbe Uliopokelewa',
            'tab_compose' => 'Andika',
            'tab_sent' => 'Uliotumwa',
            'tab_received' => 'Uliopokelewa',
            'recipient_label' => 'Mpokeaji:',
            'subject_label' => 'Mada:',
            'message_label' => 'Ujumbe:',
            'send_button' => 'Tuma Ujumbe',
            'select_recipient_placeholder' => 'Chagua Mpokeaji',
            'no_sent_messages' => 'Haujatuma ujumbe wowote bado.',
            'no_received_messages' => 'Hujapokea ujumbe wowote bado.',
            'from_label' => 'Kutoka',
            'to_label' => 'Kwa',
            'date_label' => 'Tarehe',
            'status_label' => 'Hali',
            'action_label' => 'Kitendo', // Added for delete button column
            'message_sent_success' => 'Ujumbe umetumwa kikamilifu!',
            'message_sent_error' => 'Kuna hitilafu kutuma ujumbe. Tafadhali jaribu tena.',
            'compose_message_info' => 'Andika na utume ujumbe kwa wasimamizi wa shule yako.',
            'no_admin_found' => 'Hakuna msimamizi aliyepatikana katika shule yako wa kutuma ujumbe kwake.',
            'delete_button' => 'Futa',
            'delete_confirm_title' => 'Thibitisha Kufuta',
            'delete_confirm_message' => 'Una uhakika unataka kufuta ujumbe huu? Kitendo hiki hakiwezi kutenduliwa.',
            'delete_success' => 'Ujumbe umefutwa kikamilifu.',
            'delete_error' => 'Kuna hitilafu kufuta ujumbe. Tafadhali jaribu tena.',
        ]
    ];
    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.
 * @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_STUDENT:
                header("location: student_dashboard.php");
                break;
            case ROLE_PARENT:
                header("location: parent_dashboard.php"); // Assuming parent dashboard exists
                break;
            case ROLE_STAFF:
                header("location: staff_dashboard.php"); // Assuming staff dashboard exists
                break;
            default:
                header("location: login.php");
                break;
        }
        exit;
    }
}

// !! CRITICAL: Call the check for Teacher role !!
check_role_access(ROLE_TEACHER);

// This variable is used by includes/sidebar.php (or similar) to highlight the active link in the navigation.
$currentPage = 'messages';

// User is authorized, now fetch additional details for display.
$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]);
$user_role_code = $_SESSION["role"];
$current_user_school_id = $_SESSION["school_id"];

// Initialize variables
$phone_number = $photo = $status = "";
$school_name = $_L['school_name_not_found'];
$school_logo_path = "images/default_school_logo.png";
$message = ''; // For displaying success/error messages

// Arrays to hold messages
$sent_messages = [];
$received_messages = [];
$admin_users = []; // To store admins for recipient dropdown

// Determine the human-readable role name for display purposes.
$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;
}


if (isset($conn) && $conn instanceof mysqli) {

    // --- Handle Mark Message as Read (AJAX request) ---
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['mark_read']) && $_POST['mark_read'] === 'true') {
        $message_id_to_mark_read = filter_var($_POST['message_id'], FILTER_VALIDATE_INT);

        if ($message_id_to_mark_read) {
            // Ensure the message belongs to the current user (receiver_id) and school_id
            $sql_mark_read = "UPDATE messages SET status = 'Read' WHERE id = ? AND receiver_id = ? AND school_id = ?";
            if ($stmt_mark_read = $conn->prepare($sql_mark_read)) {
                $stmt_mark_read->bind_param("iii", $message_id_to_mark_read, $user_id, $current_user_school_id);
                if ($stmt_mark_read->execute()) {
                    echo json_encode(['success' => true]);
                } else {
                    echo json_encode(['success' => false, 'error' => $stmt_mark_read->error]);
                    error_log("Execute failed for marking message as read: " . $stmt_mark_read->error);
                }
                $stmt_mark_read->close();
            } else {
                echo json_encode(['success' => false, 'error' => $conn->error]);
                error_log("Prepare failed for marking message as read: " . $conn->error);
            }
        } else {
            echo json_encode(['success' => false, 'error' => 'Invalid message ID.']);
        }
        exit; // Important: Exit after handling AJAX request
    }

    // --- Handle Message Deletion (AJAX request) ---
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['delete_message']) && $_POST['delete_message'] === 'true') {
        $message_id_to_delete = filter_var($_POST['message_id'], FILTER_VALIDATE_INT);
        $message_type_to_delete = $_POST['message_type']; // 'sent' or 'received'

        if ($message_id_to_delete && ($message_type_to_delete == 'sent' || $message_type_to_delete == 'received')) {
            $sql_delete = "";
            if ($message_type_to_delete == 'sent') {
                // User is the sender
                $sql_delete = "DELETE FROM messages WHERE id = ? AND sender_id = ? AND school_id = ?";
            } elseif ($message_type_to_delete == 'received') {
                // User is the receiver
                $sql_delete = "DELETE FROM messages WHERE id = ? AND receiver_id = ? AND school_id = ?";
            }

            if (!empty($sql_delete)) {
                if ($stmt_delete = $conn->prepare($sql_delete)) {
                    $stmt_delete->bind_param("iii", $message_id_to_delete, $user_id, $current_user_school_id);
                    if ($stmt_delete->execute()) {
                        if ($stmt_delete->affected_rows > 0) {
                            echo json_encode(['success' => true, 'message' => $_L['delete_success']]);
                        } else {
                            // No row was deleted, likely because it didn't match user_id/school_id
                            echo json_encode(['success' => false, 'error' => 'Message not found or unauthorized to delete.']);
                        }
                    } else {
                        echo json_encode(['success' => false, 'error' => $stmt_delete->error]);
                        error_log("Execute failed for deleting message: " . $stmt_delete->error);
                    }
                    $stmt_delete->close();
                } else {
                    echo json_encode(['success' => false, 'error' => $conn->error]);
                    error_log("Prepare failed for deleting message: " . $conn->error);
                }
            } else {
                 echo json_encode(['success' => false, 'error' => 'Invalid message type for deletion.']);
            }
        } else {
            echo json_encode(['success' => false, 'error' => 'Invalid message ID or type for deletion.']);
        }
        exit; // Important: Exit after handling AJAX request
    }


    // Fetch user details
    $sql = "SELECT phone_number, photo, status FROM users WHERE id = ? AND school_id = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("ii", $user_id, $current_user_school_id);
        if ($stmt->execute()) {
            $stmt->bind_result($phone_number_db, $photo_db, $status_db);
            $stmt->fetch();
            $phone_number = htmlspecialchars($phone_number_db ?? 'N/A');
            $photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'https://via.placeholder.com/80/cccccc/FFFFFF?text=TR';
            $status = htmlspecialchars($status_db ?? 'N/A');
        } else {
            error_log("Execute failed for user details query in teacher_messages: " . $stmt->error);
        }
        $stmt->close();
    } else {
        error_log("Prepare failed for user details query in teacher_messages: " . $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_logo_path = !empty($school_logo_db) ? htmlspecialchars($school_logo_db) : '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 teacher_messages: " . $stmt_school->error);
        }
        $stmt_school->close();
    } else {
        error_log("Prepare failed for school data query: " . $conn->error);
    }

    // Fetch Admin Users for 'Compose' dropdown
    $sql_admins = "SELECT id, username FROM users WHERE role = ? AND school_id = ? AND status = 'active'";
    if ($stmt_admins = $conn->prepare($sql_admins)) {
        $admin_role_code = ROLE_ADMIN; // Assuming ROLE_ADMIN is defined
        $stmt_admins->bind_param("ii", $admin_role_code, $current_user_school_id);
        if ($stmt_admins->execute()) {
            $result_admins = $stmt_admins->get_result();
            while ($row = $result_admins->fetch_assoc()) {
                $admin_users[] = $row;
            }
        } else {
            error_log("Execute failed for fetching admin users: " . $stmt_admins->error);
        }
        $stmt_admins->close();
    } else {
        error_log("Prepare failed for fetching admin users: " . $conn->error);
    }


    // --- Handle Sending Message ---
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['send_message'])) {
        $recipient_id = filter_var($_POST['recipient_id'], FILTER_VALIDATE_INT);
        $subject = trim($_POST['subject']);
        $message_content = trim($_POST['message_content']);
        $current_datetime = date('Y-m-d H:i:s'); // Current timestamp

        // Basic validation
        if ($recipient_id && !empty($subject) && !empty($message_content)) {
            // Check if recipient_id is a valid admin within the same school
            $isValidRecipient = false;
            foreach ($admin_users as $admin) {
                if ($admin['id'] == $recipient_id) {
                    $isValidRecipient = true;
                    break;
                }
            }

            if ($isValidRecipient) {
                $sql_insert_message = "INSERT INTO messages (sender_id, receiver_id, subject, message_content, status, school_id, created_at) VALUES (?, ?, ?, ?, 'Unread', ?, ?)";
                if ($stmt_insert = $conn->prepare($sql_insert_message)) {
                    $stmt_insert->bind_param("iissss", $user_id, $recipient_id, $subject, $message_content, $current_user_school_id, $current_datetime);
                    if ($stmt_insert->execute()) {
                        $message = '<div class="success">' . $_L['message_sent_success'] . '</div>';
                    } else {
                        $message = '<div class="error">' . $_L['message_sent_error'] . '</div>';
                        error_log("Execute failed for inserting message: " . $stmt_insert->error);
                    }
                    $stmt_insert->close();
                } else {
                    $message = '<div class="error">' . $_L['message_sent_error'] . '</div>';
                    error_log("Prepare failed for inserting message: " . $conn->error);
                }
            } else {
                $message = '<div class="error">Invalid recipient.</div>';
            }
        } else {
            $message = '<div class="error">Please fill in all fields.</div>';
        }
    }


    // --- Fetch Sent Messages ---
    // Join with users table to get recipient's username
    $sql_sent_messages = "
        SELECT m.id, u.username AS receiver_username, m.subject, m.message_content, m.created_at, m.status
        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_messages)) {
        $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()) {
                $sent_messages[] = $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);
    }

    // --- Fetch Received Messages ---
    // Join with users table to get sender's username
    $sql_received_messages = "
        SELECT m.id, u.username AS sender_username, m.subject, m.message_content, m.created_at, m.status
        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_messages)) {
        $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()) {
                $received_messages[] = $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);
    }

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

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

        .dashboard-container {
            display: flex;
            height: 100vh;
            overflow: hidden;
        }

        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            height: 100vh;
            overflow-y: auto;
            z-index: 1000;
            width: 250px;
        }

        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            height: 100vh;
            margin-left: 250px;
            overflow: hidden;
        }

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

        /* Scrollable content area */
        .main-content > div:not(.header) {
            margin-top: 80px;
            overflow-y: auto;
            flex: 1;
            padding-bottom: 20px;
        }

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

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

            .main-content {
                margin-left: 0;
            }

            .header {
                left: 0;
            }

            .main-content > div:not(.header) {
                padding-bottom: 110px !important;
            }
        }

        
        /* Specific styles for messages page */
        .message-tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 2px solid var(--border-color);
        }
        .message-tab {
            padding: 12px 20px;
            cursor: pointer;
            font-weight: 500;
            color: #777;
            border-bottom: 2px solid transparent;
            transition: all 0.3s ease;
        }
        .message-tab.active {
            color: var(--primary-green);
            border-bottom: 2px solid var(--primary-green);
        }
        .message-tab:hover {
            color: var(--dark-green);
        }
        .tab-content {
            display: none;
            background-color: var(--card-bg);
            padding: 25px;
            border-radius: 10px;
            box-shadow: var(--shadow-light);
        }
        .tab-content.active {
            display: block;
        }

        .message-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        .message-table th, .message-table td {
            border: 1px solid var(--border-color);
            padding: 12px;
            text-align: left;
        }
        .message-table th {
            background-color: #f8f8f8;
            font-weight: 600;
            color: var(--text-dark);
        }
        .message-table tbody tr:nth-child(even) {
            background-color: #fcfcfc;
        }
        .message-table tbody tr:hover {
            background-color: #f0f0f0;
        }
        .message-table .status-badge {
            padding: 4px 8px;
            border-radius: 5px;
            font-size: 0.85em;
            font-weight: 600;
            color: white;
        }
        .status-badge.Unread { background-color: #e74c3c; } /* Red for unread */
        .status-badge.Read { background-color: #28a745; } /* Green for read */
        .status-badge.Sent { background-color: #0275d8; } /* Blue for sent (from sender's perspective) */

        /* Delete Button specific styles */
        .btn-delete-message {
            background-color: #e74c3c; /* Red for delete */
            color: white;
            border: none;
            padding: 6px 10px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 0.8em;
            transition: background-color 0.3s ease;
        }
        .btn-delete-message:hover {
            background-color: #c0392b;
        }

        .message-detail-modal {
            display: none;
            position: fixed;
            z-index: 1002;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.5);
            justify-content: center;
            align-items: center;
        }

        .message-detail-content {
            background-color: var(--card-bg);
            padding: 30px;
            border-radius: 10px;
            width: 90%;
            max-width: 600px;
            box-shadow: var(--shadow-medium);
            position: relative;
            animation: fadeIn 0.3s ease-out;
        }

        .message-detail-content h4 {
            margin-top: 0;
            margin-bottom: 15px;
            font-size: 1.4em;
            color: var(--primary-green);
        }

        .message-detail-content p {
            margin-bottom: 10px;
            line-height: 1.6;
        }
        .message-detail-content strong {
            color: var(--text-dark);
        }
        .message-detail-content .close-button {
            top: 15px;
            right: 20px;
            font-size: 28px;
        }

        /* Confirmation Modal */
        .confirmation-modal {
            display: none; /* Hidden by default */
            position: fixed;
            z-index: 1003; /* Higher than message detail modal */
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.6);
            justify-content: center;
            align-items: center;
        }

        .confirmation-content {
            background-color: var(--card-bg);
            padding: 30px;
            border-radius: 10px;
            width: 90%;
            max-width: 400px;
            box-shadow: var(--shadow-medium);
            text-align: center;
            animation: fadeIn 0.3s ease-out;
        }

        .confirmation-content h4 {
            margin-top: 0;
            margin-bottom: 20px;
            color: var(--text-dark);
        }

        .confirmation-content .button-group {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-top: 25px;
        }

        @media (max-width: 768px) {
            .message-table, .message-table thead, .message-table tbody, .message-table th, .message-table td, .message-table tr {
                display: block;
            }
            .message-table thead tr {
                position: absolute;
                top: -9999px;
                left: -9999px;
            }
            .message-table tr {
                border: 1px solid var(--border-color);
                margin-bottom: 15px;
                border-radius: 8px;
                overflow: hidden;
            }
            .message-table td {
                border: none;
                border-bottom: 1px solid var(--border-color);
                position: relative;
                padding-left: 50%;
                text-align: right;
            }
            .message-table td:before {
                position: absolute;
                top: 0;
                left: 6px;
                width: 45%;
                padding-right: 10px;
                white-space: nowrap;
                text-align: left;
                font-weight: 600;
                color: #555;
            }
            /* Updated nth-of-type for new column */
            .message-table td:nth-of-type(1):before { content: "<?php echo $_L['from_label']; ?>/<?php echo $_L['to_label']; ?>"; }
            .message-table td:nth-of-type(2):before { content: "<?php echo $_L['subject_label']; ?>"; }
            .message-table td:nth-of-type(3):before { content: "<?php echo $_L['date_label']; ?>"; }
            .message-table td:nth-of-type(4):before { content: "<?php echo $_L['status_label']; ?>"; }
            .message-table td:nth-of-type(5):before { content: "<?php echo $_L['action_label']; ?>"; } /* New for action */


            .message-detail-content {
                padding: 20px;
                max-width: 95%;
            }
        }
    </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="teacher_dashboard.php"><i class="fas fa-th-large"></i> <?php echo $_L['sidebar_dashboard']; ?></a></li>
                    <li><a href="teacher_my_classes.php"><i class="fas fa-chalkboard"></i> <?php echo $_L['sidebar_my_classes']; ?></a></li>
                    <li><a href="teacher_my_students.php"><i class="fas fa-user-graduate"></i> <?php echo $_L['sidebar_my_students']; ?></a></li>
                    <li><a href="create_assignment.php"><i class="fas fa-file-alt"></i> <?php echo $_L['sidebar_assignments']; ?></a></li>
                    <li><a href="teacher_grades.php"><i class="fas fa-award"></i> <?php echo $_L['sidebar_grades']; ?></a></li>
                    <li class="active"><a href="teacher_messages.php"><i class="fas fa-envelope"></i> <?php echo $_L['sidebar_messages']; ?></a></li>
                    <li><a href="teacher_calendar.php"><i class="far fa-calendar-alt"></i> <?php echo $_L['sidebar_calendar']; ?></a></li>
                    <li><a href="teacher_profile.php"><i class="fas fa-user-circle"></i> <?php echo $_L['sidebar_profile']; ?></a></li>
                    <li><a href="teacher_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 $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="dashboard-content">
                <h2><i class="fas fa-envelope-open-text"></i> <?php echo $_L['messages_title_prefix']; ?></h2>

                <?php echo $message; // Display success/error messages ?>

                <div class="message-tabs">
                    <div class="message-tab active" data-tab="compose"><?php echo $_L['tab_compose']; ?></div>
                    <div class="message-tab" data-tab="sent"><?php echo $_L['tab_sent']; ?></div>
                    <div class="message-tab" data-tab="received"><?php echo $_L['tab_received']; ?></div>
                </div>

                <div id="compose" class="tab-content active">
                    <h3><?php echo $_L['compose_message_heading']; ?></h3>
                    <p><?php echo $_L['compose_message_info']; ?></p>
                    <?php if (empty($admin_users)): ?>
                        <div class="error"><?php echo $_L['no_admin_found']; ?></div>
                    <?php else: ?>
                        <form action="teacher_messages.php" method="post">
                            <div class="form-group">
                                <label for="recipient_id"><?php echo $_L['recipient_label']; ?></label>
                                <select id="recipient_id" name="recipient_id" required>
                                    <option value=""><?php echo $_L['select_recipient_placeholder']; ?></option>
                                    <?php foreach ($admin_users as $admin): ?>
                                        <option value="<?php echo htmlspecialchars($admin['id']); ?>">
                                            <?php echo htmlspecialchars($admin['username']); ?> (Admin)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="subject"><?php echo $_L['subject_label']; ?></label>
                                <input type="text" id="subject" name="subject" required placeholder="Enter message subject">
                            </div>
                            <div class="form-group">
                                <label for="message_content"><?php echo $_L['message_label']; ?></label>
                                <textarea id="message_content" name="message_content" rows="8" required placeholder="Type your message here..."></textarea>
                            </div>
                            <input type="submit" name="send_message" value="<?php echo $_L['send_button']; ?>" class="btn-primary">
                        </form>
                    <?php endif; ?>
                </div>

                <div id="sent" class="tab-content">
                    <h3><?php echo $_L['sent_messages_heading']; ?></h3>
                    <?php if (empty($sent_messages)): ?>
                        <p><?php echo $_L['no_sent_messages']; ?></p>
                    <?php else: ?>
                        <table class="message-table">
                            <thead>
                                <tr>
                                    <th><?php echo $_L['to_label']; ?></th>
                                    <th><?php echo $_L['subject_label']; ?></th>
                                    <th><?php echo $_L['date_label']; ?></th>
                                    <th><?php echo $_L['status_label']; ?></th>
                                    <th><?php echo $_L['action_label']; ?></th> <!-- New column for action -->
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($sent_messages as $msg): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($msg['receiver_username']); ?></td>
                                    <td><a href="#" class="view-message-link" data-message-id="<?php echo $msg['id']; ?>" data-message-type="sent"><?php echo htmlspecialchars($msg['subject']); ?></a></td>
                                    <td><?php echo date('M j, Y H:i', strtotime($msg['created_at'])); ?></td>
                                    <td><span class="status-badge <?php echo htmlspecialchars($msg['status']); ?>"><?php echo htmlspecialchars($msg['status']); ?></span></td>
                                    <td>
                                        <button class="btn-delete-message" data-message-id="<?php echo $msg['id']; ?>" data-message-type="sent"><?php echo $_L['delete_button']; ?></button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>

                <div id="received" class="tab-content">
                    <h3><?php echo $_L['received_messages_heading']; ?></h3>
                    <?php if (empty($received_messages)): ?>
                        <p><?php echo $_L['no_received_messages']; ?></p>
                    <?php else: ?>
                        <table class="message-table">
                            <thead>
                                <tr>
                                    <th><?php echo $_L['from_label']; ?></th>
                                    <th><?php echo $_L['subject_label']; ?></th>
                                    <th><?php echo $_L['date_label']; ?></th>
                                    <th><?php echo $_L['status_label']; ?></th>
                                    <th><?php echo $_L['action_label']; ?></th> <!-- New column for action -->
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($received_messages as $msg): ?>
                                <tr class="<?php echo ($msg['status'] === 'Unread') ? 'unread-row' : ''; ?>">
                                    <td><?php echo htmlspecialchars($msg['sender_username']); ?></td>
                                    <td><a href="#" class="view-message-link" data-message-id="<?php echo $msg['id']; ?>" data-message-type="received"><?php echo htmlspecialchars($msg['subject']); ?></a></td>
                                    <td><?php echo date('M j, Y H:i', strtotime($msg['created_at'])); ?></td>
                                    <td><span class="status-badge <?php echo htmlspecialchars($msg['status']); ?>"><?php echo htmlspecialchars($msg['status']); ?></span></td>
                                    <td>
                                        <button class="btn-delete-message" data-message-id="<?php echo $msg['id']; ?>" data-message-type="received"><?php echo $_L['delete_button']; ?></button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Message Detail Modal -->
    <div id="messageDetailModal" class="message-detail-modal modal">
        <div class="message-detail-content modal-content">
            <span class="close-button">&times;</span>
            <h4>Message Details</h4>
            <p><strong><?php echo $_L['from_label']; ?>:</strong> <span id="modalSender"></span></p>
            <p><strong><?php echo $_L['to_label']; ?>:</strong> <span id="modalRecipient"></span></p>
            <p><strong><?php echo $_L['subject_label']; ?>:</strong> <span id="modalSubject"></span></p>
            <p><strong><?php echo $_L['date_label']; ?>:</strong> <span id="modalDate"></span></p>
            <p><strong><?php echo $_L['status_label']; ?>:</strong> <span id="modalStatus" class="status-badge"></span></p>
            <hr>
            <p><strong><?php echo $_L['message_label']; ?>:</strong></p>
            <p id="modalMessageContent"></p>
        </div>
    </div>

    <!-- Custom Confirmation Modal -->
    <div id="confirmationModal" class="confirmation-modal modal">
        <div class="confirmation-content">
            <span class="close-button" id="confirmCloseButton">&times;</span>
            <h4 id="confirmTitle"><?php echo $_L['delete_confirm_title']; ?></h4>
            <p id="confirmMessage"><?php echo $_L['delete_confirm_message']; ?></p>
            <div class="button-group">
                <button class="btn btn-danger" id="confirmDeleteBtn"><?php echo $_L['delete_button']; ?></button>
                <button class="btn btn-primary" id="cancelDeleteBtn">Cancel</button>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Sidebar Toggle Logic
            const menuToggle = document.getElementById('menuToggle');
            const sidebar = document.getElementById('sidebar');
            const dashboardContainer = document.getElementById('dashboardContainer');
            // const mainContent = document.querySelector('.main-content'); // No direct use for overlay

            menuToggle.addEventListener('click', function() {
                sidebar.classList.toggle('active');
                dashboardContainer.classList.toggle('sidebar-open'); // Add class to body for main content push
            });

            // Close sidebar when clicking outside (on desktop sizes, if applicable, or just for responsiveness)
            document.addEventListener('click', function(event) {
                if (window.innerWidth <= 768) { // Only for mobile/tablet views
                    if (!sidebar.contains(event.target) && !menuToggle.contains(event.target) && sidebar.classList.contains('active')) {
                        sidebar.classList.remove('active');
                        dashboardContainer.classList.remove('sidebar-open');
                    }
                }
            });


            // Language Selector Logic
            window.changeLanguage = function(lang) {
                window.location.href = `teacher_messages.php?lang=${lang}`;
            };

            // Tab Switching Logic
            const messageTabs = document.querySelectorAll('.message-tab');
            const tabContents = document.querySelectorAll('.tab-content');

            messageTabs.forEach(tab => {
                tab.addEventListener('click', function() {
                    // Deactivate all tabs and hide all tab contents
                    messageTabs.forEach(item => item.classList.remove('active'));
                    tabContents.forEach(content => content.classList.remove('active'));

                    // Activate clicked tab and show corresponding content
                    this.classList.add('active');
                    const targetTab = this.getAttribute('data-tab');
                    document.getElementById(targetTab).classList.add('active');
                });
            });

            // Message Detail Modal Logic
            const messageDetailModal = document.getElementById('messageDetailModal');
            const closeButton = messageDetailModal.querySelector('.close-button');

            document.querySelectorAll('.view-message-link').forEach(link => {
                link.addEventListener('click', async function(event) {
                    event.preventDefault(); // Prevent default link behavior
                    const messageId = this.getAttribute('data-message-id');
                    const messageType = this.getAttribute('data-message-type'); // 'sent' or 'received'

                    // Determine which message array to search
                    let messagesData = [];
                    if (messageType === 'sent') {
                        messagesData = <?php echo json_encode($sent_messages); ?>;
                        const msg = messagesData.find(m => m.id == messageId);

                        document.getElementById('modalSender').textContent = "<?php echo $username; ?>"; // Current user is sender
                        document.getElementById('modalRecipient').textContent = msg ? msg.receiver_username : 'N/A';
                        document.getElementById('modalSubject').textContent = msg ? msg.subject : 'N/A';
                        document.getElementById('modalDate').textContent = msg ? new Date(msg.created_at).toLocaleString() : 'N/A';
                        document.getElementById('modalStatus').textContent = msg ? msg.status : 'N/A';
                        document.getElementById('modalStatus').className = 'status-badge ' + (msg ? msg.status : '');
                        document.getElementById('modalMessageContent').textContent = msg ? msg.message_content : 'N/A';

                    } else if (messageType === 'received') {
                        messagesData = <?php echo json_encode($received_messages); ?>;
                        const msg = messagesData.find(m => m.id == messageId);

                        document.getElementById('modalSender').textContent = msg ? msg.sender_username : 'N/A';
                        document.getElementById('modalRecipient').textContent = "<?php echo $username; ?>"; // Current user is recipient
                        document.getElementById('modalSubject').textContent = msg ? msg.subject : 'N/A';
                        document.getElementById('modalDate').textContent = msg ? new Date(msg.created_at).toLocaleString() : 'N/A';
                        document.getElementById('modalStatus').textContent = msg ? msg.status : 'N/A';
                        document.getElementById('modalStatus').className = 'status-badge ' + (msg ? msg.status : '');
                        document.getElementById('modalMessageContent').textContent = msg ? msg.message_content : 'N/A';

                        // Mark message as read if it's received and unread
                        if (msg && msg.status === 'Unread') {
                            const formData = new FormData();
                            formData.append('mark_read', 'true');
                            formData.append('message_id', messageId);

                            fetch('teacher_messages.php', {
                                method: 'POST',
                                body: formData
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    const statusSpan = link.closest('tr').querySelector('.status-badge');
                                    if (statusSpan) {
                                        statusSpan.textContent = 'Read';
                                        statusSpan.classList.remove('Unread');
                                        statusSpan.classList.add('Read');
                                    }
                                    link.closest('tr').classList.remove('unread-row'); // Remove highlight
                                } else {
                                    console.error('Failed to mark message as read:', data.error);
                                }
                            })
                            .catch(error => console.error('Error marking message as read:', error));
                        }
                    }

                    messageDetailModal.style.display = 'flex';
                });
            });

            closeButton.addEventListener('click', function() {
                messageDetailModal.style.display = 'none';
            });

            window.addEventListener('click', function(event) {
                if (event.target == messageDetailModal) {
                    messageDetailModal.style.display = 'none';
                }
            });

            // --- Delete Message Logic (New) ---
            const confirmationModal = document.getElementById('confirmationModal');
            const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
            const cancelDeleteBtn = document.getElementById('cancelDeleteBtn');
            const confirmCloseButton = document.getElementById('confirmCloseButton');

            let messageToDeleteId = null;
            let messageToDeleteType = null;
            let messageToDeleteRow = null;

            document.querySelectorAll('.btn-delete-message').forEach(button => {
                button.addEventListener('click', function() {
                    messageToDeleteId = this.getAttribute('data-message-id');
                    messageToDeleteType = this.getAttribute('data-message-type');
                    messageToDeleteRow = this.closest('tr'); // Store the table row to remove it later

                    // Show the custom confirmation modal
                    confirmationModal.style.display = 'flex';
                });
            });

            confirmDeleteBtn.addEventListener('click', function() {
                if (messageToDeleteId && messageToDeleteType) {
                    const formData = new FormData();
                    formData.append('delete_message', 'true');
                    formData.append('message_id', messageToDeleteId);
                    formData.append('message_type', messageToDeleteType);

                    fetch('teacher_messages.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            messageToDeleteRow.remove(); // Remove the row from the table
                            // Optionally display a success message to the user
                            console.log(data.message); // For debugging: "Message deleted successfully."
                            // alert(data.message); // Not using alert as per instructions, but for quick testing
                        } else {
                            console.error('Deletion failed:', data.error);
                            // alert('Error: ' + data.error); // For quick testing
                        }
                        confirmationModal.style.display = 'none'; // Hide modal
                        messageToDeleteId = null; // Reset stored values
                        messageToDeleteType = null;
                        messageToDeleteRow = null;
                    })
                    .catch(error => {
                        console.error('Error during deletion AJAX call:', error);
                        // alert('Network error during deletion.'); // For quick testing
                        confirmationModal.style.display = 'none'; // Hide modal
                        messageToDeleteId = null;
                        messageToDeleteType = null;
                        messageToDeleteRow = null;
                    });
                }
            });

            cancelDeleteBtn.addEventListener('click', function() {
                confirmationModal.style.display = 'none'; // Hide modal
                messageToDeleteId = null; // Reset stored values
                messageToDeleteType = null;
                messageToDeleteRow = null;
            });

            confirmCloseButton.addEventListener('click', function() {
                confirmationModal.style.display = 'none';
                messageToDeleteId = null;
                messageToDeleteType = null;
                messageToDeleteRow = null;
            });

            // Close confirmation modal if clicked outside
            window.addEventListener('click', function(event) {
                if (event.target == confirmationModal) {
                    confirmationModal.style.display = 'none';
                    messageToDeleteId = null;
                    messageToDeleteType = null;
                    messageToDeleteRow = null;
                }
            });
        });
    </script>

    <!-- Mobile Footer (visible only on mobile screens) -->
    <footer class="mobile-footer">
        <div class="footer-nav">
            <a href="teacher_dashboard.php" class="footer-item">
                <i class="fas fa-th-large"></i>
                <span>Dashboard</span>
            </a>
            <a href="teacher_my_classes.php" class="footer-item">
                <i class="fas fa-chalkboard"></i>
                <span>Classes</span>
            </a>
            <a href="teacher_my_students.php" class="footer-item">
                <i class="fas fa-user-graduate"></i>
                <span>Students</span>
            </a>
            <button class="footer-item" id="moreButton">
                <i class="fas fa-ellipsis-h"></i>
                <span>More</span>
            </button>
        </div>
    </footer>

    <!-- More Menu Modal -->
    <div id="more-menu-modal" class="more-menu-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>More Options</h3>
                <button class="close-modal" id="closeModal">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-nav">
                <a href="create_assignment.php" class="modal-nav-item">
                    <i class="fas fa-file-alt"></i>
                    <span>Assignments</span>
                </a>
                <a href="teacher_exams.php" class="modal-nav-item">
                    <i class="fas fa-award"></i>
                    <span>Grades</span>
                </a>
                <a href="teacher_messages.php" class="modal-nav-item active">
                    <i class="fas fa-envelope"></i>
                    <span>Messages</span>
                </a>
                <a href="teacher_calendar.php" class="modal-nav-item">
                    <i class="far fa-calendar-alt"></i>
                    <span>Calendar</span>
                </a>
                <a href="teacher_profile.php" class="modal-nav-item">
                    <i class="fas fa-user-circle"></i>
                    <span>Profile</span>
                </a>
                <a href="teacher_settings.php" class="modal-nav-item">
                    <i class="fas fa-cog"></i>
                    <span>Settings</span>
                </a>
                <a href="logout.php" class="modal-nav-item logout">
                    <i class="fas fa-sign-out-alt"></i>
                    <span>Logout</span>
                </a>
            </div>
        </div>
    </div>

    <style>
        /* Mobile Footer Styles */
        .mobile-footer {
            display: none;
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            border-top: 1px solid #e2e8f0;
            z-index: 1000;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
        }

        .footer-nav {
            display: flex;
            justify-content: space-around;
            align-items: center;
            padding: 8px 0;
        }

        .footer-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            text-decoration: none;
            color: #6b7280;
            font-size: 12px;
            padding: 8px 12px;
            border-radius: 8px;
            transition: all 0.2s;
            background: none;
            border: none;
            cursor: pointer;
            min-width: 60px;
        }

        .footer-item i {
            font-size: 18px;
            margin-bottom: 4px;
        }

        .footer-item.active {
            color: #3b82f6;
            background-color: #eff6ff;
        }

        .footer-item:hover {
            color: #3b82f6;
            background-color: #f3f4f6;
        }

        /* More Menu Modal Styles */
        #more-menu-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 9999;
            transform: translateY(100%);
            transition: transform 0.3s ease;
            visibility: hidden;
            pointer-events: none;
        }

        #more-menu-modal.show {
            transform: translateY(0) !important;
            visibility: visible !important;
            pointer-events: auto !important;
            z-index: 99999 !important;
            display: block !important;
        }

        .modal-content {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            border-radius: 20px 20px 0 0;
            max-height: 80vh;
            overflow-y: auto;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 20px 10px;
            border-bottom: 1px solid #e2e8f0;
        }

        .modal-header h3 {
            margin: 0;
            color: #1f2937;
            font-size: 18px;
            font-weight: 600;
        }

        .close-modal {
            background: none;
            border: none;
            font-size: 20px;
            color: #6b7280;
            cursor: pointer;
            padding: 5px;
            border-radius: 50%;
            transition: background-color 0.2s;
        }

        .close-modal:hover {
            background-color: #f3f4f6;
        }

        .modal-nav {
            padding: 10px 0 30px;
        }

        .modal-nav-item {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            text-decoration: none;
            color: #374151;
            transition: background-color 0.2s;
        }

        .modal-nav-item:hover {
            background-color: #f9fafb;
        }

        .modal-nav-item.active {
            background-color: #eff6ff;
            color: #3b82f6;
        }

        .modal-nav-item i {
            width: 24px;
            font-size: 18px;
            margin-right: 15px;
            color: #6b7280;
        }

        .modal-nav-item.active i {
            color: #3b82f6;
        }

        .modal-nav-item span {
            font-size: 16px;
            font-weight: 500;
        }

        .modal-nav-item.logout {
            color: #dc2626;
        }

        .modal-nav-item.logout i {
            color: #dc2626;
        }

        /* Show mobile footer only on mobile screens */
        @media (max-width: 768px) {
            .mobile-footer {
                display: block;
            }
            
            /* Add bottom padding to main content to account for fixed footer */
            .main-content {
                padding-bottom: 80px;
            }
        }
    </style>

    <script>
        // Mobile footer modal functionality
        document.addEventListener('DOMContentLoaded', function() {
            const moreButton = document.getElementById('moreButton');
            const moreModal = document.getElementById('more-menu-modal');
            const closeModal = document.getElementById('closeModal');

            if (moreButton && moreModal) {
                moreButton.addEventListener('click', function() {
                    moreModal.classList.add('show');
                });
            }

            if (closeModal && moreModal) {
                closeModal.addEventListener('click', function() {
                    moreModal.classList.remove('show');
                });
            }

            // Close modal when clicking outside
            if (moreModal) {
                moreModal.addEventListener('click', function(e) {
                    if (e.target === moreModal) {
                        moreModal.classList.remove('show');
                    }
                });
            }
        });
    </script>
</body>
</html>al) {
                    confirmationModal.style.display = 'none';
                    messageToDeleteId = null;
                    messageToDeleteType = null;
                    messageToDeleteRow = null;
                }
            });
        });
    </script>
</body>
</html>
