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

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

// Function to check user role and redirect if unauthorized
function check_role_access($required_role_code) {
    if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || !isset($_SESSION["school_id"])) {
        header("location: login.php");
        exit;
    }

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

// Ensure only Admin can access this page
check_role_access(ROLE_ADMIN);

// Initialize user and school variables
$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]);
$user_role_code = $_SESSION["role"];
$current_user_school_id = $_SESSION["school_id"];
$school_name = "School Name Not Found";
$school_name_for_js = "School Name Not Found"; // For JavaScript usage
$school_logo_path = "images/default_school_logo.png";
$photo = 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD'; // Default user photo

// Array to store teachers data
$teachers = [];
$message = "";
$error = "";

// Fetch school details
if (isset($conn) && $conn instanceof mysqli) {
    $sql_school = "SELECT school_name, logo FROM schools WHERE school_id = ?";
    if ($stmt_school = $conn->prepare($sql_school)) {
        $stmt_school->bind_param("i", $current_user_school_id);
        if ($stmt_school->execute()) {
            $stmt_school->bind_result($school_name_db, $school_logo_db);
            if ($stmt_school->fetch()) {
                $school_name = htmlspecialchars($school_name_db);
                $school_name_for_js = addslashes($school_name_db);
                $school_logo_path = !empty($school_logo_db) ? htmlspecialchars($school_logo_db) : 'images/default_school_logo.png';
            } else {
                error_log("School details not found for school_id: " . $current_user_school_id);
            }
        } else {
            error_log("Execute failed for school data query: " . $stmt_school->error);
        }
        $stmt_school->close();
    } else {
        error_log("Prepare failed for school data query: " . $conn->error);
    }

    // Fetch Admin user photo
    $sql_user_photo = "SELECT photo FROM users WHERE id = ? AND school_id = ?";
    if ($stmt_user_photo = $conn->prepare($sql_user_photo)) {
        $stmt_user_photo->bind_param("ii", $user_id, $current_user_school_id);
        if ($stmt_user_photo->execute()) {
            $stmt_user_photo->bind_result($photo_db);
            if ($stmt_user_photo->fetch() && !empty($photo_db)) {
                $photo = htmlspecialchars($photo_db);
            }
        }
        $stmt_user_photo->close();
    }
}

// --- Teacher Management Operations ---

// Function to upload a photo
function upload_photo($file_key, $upload_dir = "uploads/teachers/") {
    if (!isset($_FILES[$file_key]) || $_FILES[$file_key]['error'] != UPLOAD_ERR_OK) {
        return null; // No file uploaded or an error occurred
    }

    $target_dir = $upload_dir;
    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0777, true); // Create directory if it doesn't exist
    }

    $file_extension = pathinfo($_FILES[$file_key]["name"], PATHINFO_EXTENSION);
    $unique_filename = uniqid('teacher_') . '.' . $file_extension;
    $target_file = $target_dir . $unique_filename;
    $imageFileType = strtolower($file_extension);

    // Check if image file is an actual image or fake image
    $check = getimagesize($_FILES[$file_key]["tmp_name"]);
    if($check === false) {
        return "File is not an image.";
    }

    // Check file size (e.g., 5MB limit)
    if ($_FILES[$file_key]["size"] > 5000000) {
        return "Sorry, your file is too large.";
    }

    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
        return "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    }

    if (move_uploaded_file($_FILES[$file_key]["tmp_name"], $target_file)) {
        return $target_file; // Return path to the uploaded file
    } else {
        error_log("Failed to move uploaded file: " . $_FILES[$file_key]["tmp_name"] . " to " . $target_file);
        return "Sorry, there was an error uploading your file.";
    }
}

// Add New Teacher
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["add_teacher"])) {
    $teacher_name = trim($_POST["teacher_name"]);
    $teacher_email = strtolower(trim($_POST["teacher_email"])); // Normalize email to lowercase
    $teacher_phone = trim($_POST["teacher_phone"]);
    $teacher_password = password_hash($_POST["teacher_password"], PASSWORD_DEFAULT); // Hash password

    if (empty($teacher_name) || empty($teacher_email) || empty($teacher_phone) || empty($_POST["teacher_password"])) {
        $error = "All fields are required to add a new teacher.";
    } else if (!filter_var($teacher_email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format.";
    } else {
        // Check for duplicate email within the same school
        $sql_check_duplicate = "SELECT id FROM users WHERE email = ? AND school_id = ?";
        if ($stmt_check = $conn->prepare($sql_check_duplicate)) {
            $stmt_check->bind_param("si", $teacher_email, $current_user_school_id);
            $stmt_check->execute();
            $stmt_check->store_result();
            if ($stmt_check->num_rows > 0) {
                // Updated error message to include the email causing the conflict
                $error = "A user with email '" . htmlspecialchars($teacher_email) . "' already exists in this school.";
                $stmt_check->close();
            } else {
                $stmt_check->close(); // Close statement before starting transaction
                $conn->begin_transaction(); // Start transaction

                try {
                    // First, insert into users table
                    $sql_insert_user = "INSERT INTO users (username, email, password, role, school_id, phone_number, photo, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'active')";
                    if ($stmt_user = $conn->prepare($sql_insert_user)) {
                        $role_teacher_code = ROLE_TEACHER;
                        $photo_path = null; // Default to null, updated if photo uploaded
                        $upload_result = upload_photo("teacher_photo");
                        if (is_string($upload_result) && (strpos($upload_result, 'Sorry') === 0 || strpos($upload_result, 'File') === 0)) {
                            throw new Exception($upload_result); // Propagate upload error
                        } else if ($upload_result !== null) {
                            $photo_path = $upload_result;
                        }

                        $stmt_user->bind_param("sssiiss", $teacher_name, $teacher_email, $teacher_password, $role_teacher_code, $current_user_school_id, $teacher_phone, $photo_path);
                        if (!$stmt_user->execute()) {
                            throw new Exception("Error adding user: " . $stmt_user->error);
                        }
                        $new_user_id = $conn->insert_id;
                        $stmt_user->close();

                        // Then, insert into teachers table
                        $sql_insert_teacher = "INSERT INTO teachers (user_id, school_id) VALUES (?, ?)";
                        if ($stmt_teacher = $conn->prepare($sql_insert_teacher)) {
                            $stmt_teacher->bind_param("ii", $new_user_id, $current_user_school_id);
                            if (!$stmt_teacher->execute()) {
                                throw new Exception("Error adding teacher: " . $stmt_teacher->error);
                            }
                            $stmt_teacher->close();
                            $conn->commit(); // Commit transaction
                            $message = "Teacher added successfully!";
                        } else {
                            throw new Exception("Prepare failed for teacher insert: " . $conn->error);
                        }
                    } else {
                        throw new Exception("Prepare failed for user insert: " . $conn->error);
                    }
                } catch (Exception $e) {
                    $conn->rollback(); // Rollback on error
                    $error = "Failed to add teacher: " . $e->getMessage();
                    error_log("Add Teacher Error: " . $e->getMessage());
                    // If photo was uploaded but transaction failed, try to delete it
                    if ($photo_path && file_exists($photo_path)) {
                        unlink($photo_path);
                    }
                }
            }
        } else {
            $error = "Database prepare error for duplicate check: " . $conn->error;
        }
    }
}

// Edit Teacher
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["edit_teacher"])) {
    $teacher_id_to_edit = $_POST["teacher_id"]; // This is the `teachers.teacher_id`
    $user_id_to_edit = $_POST["user_id"]; // This is the `users.id`
    $teacher_name = trim($_POST["edit_teacher_name"]);
    $teacher_email = strtolower(trim($_POST["edit_teacher_email"])); // Normalize email to lowercase
    $teacher_phone = trim($_POST["edit_teacher_phone"]);
    $current_photo_path = $_POST["current_photo_path"] ?? null; // Get current photo path

    if (empty($teacher_name) || empty($teacher_email) || empty($teacher_phone)) {
        $error = "All fields are required to edit a teacher.";
    } else if (!filter_var($teacher_email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format.";
    } else {
        // Check for duplicate email within the same school, excluding current user
        $sql_check_duplicate = "SELECT id FROM users WHERE email = ? AND school_id = ? AND id != ?";
        if ($stmt_check = $conn->prepare($sql_check_duplicate)) {
            $stmt_check->bind_param("sii", $teacher_email, $current_user_school_id, $user_id_to_edit);
            $stmt_check->execute();
            $stmt_check->store_result();
            if ($stmt_check->num_rows > 0) {
                // Updated error message to include the email causing the conflict
                $error = "A user with email '" . htmlspecialchars($teacher_email) . "' already exists in this school.";
                $stmt_check->close();
            } else {
                $stmt_check->close(); // Close statement before starting transaction
                $conn->begin_transaction();
                try {
                    $photo_path = $current_photo_path; // Start with current path

                    if (isset($_FILES["edit_teacher_photo"]) && $_FILES["edit_teacher_photo"]["error"] == UPLOAD_ERR_OK) {
                        $upload_result = upload_photo("edit_teacher_photo");
                        if (is_string($upload_result) && (strpos($upload_result, 'Sorry') === 0 || strpos($upload_result, 'File') === 0)) {
                            throw new Exception($upload_result);
                        } else {
                            // Delete old photo if it exists and is not default
                            if ($current_photo_path && file_exists($current_photo_path) && $current_photo_path != 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD') {
                                unlink($current_photo_path);
                            }
                            $photo_path = $upload_result;
                        }
                    }

                    // Update users table
                    $sql_update_user = "UPDATE users SET username = ?, email = ?, phone_number = ?, photo = ? WHERE id = ? AND school_id = ?";
                    if ($stmt_user = $conn->prepare($sql_update_user)) {
                        $stmt_user->bind_param("ssssii", $teacher_name, $teacher_email, $teacher_phone, $photo_path, $user_id_to_edit, $current_user_school_id);
                        if (!$stmt_user->execute()) {
                            throw new Exception("Error updating user: " . $stmt_user->error);
                        }
                        $stmt_user->close();
                        $conn->commit();
                        $message = "Teacher updated successfully!";
                    } else {
                        throw new Exception("Prepare failed for user update: " . $conn->error);
                    }
                } catch (Exception $e) {
                    $conn->rollback();
                    $error = "Failed to update teacher: " . $e->getMessage();
                    error_log("Edit Teacher Error: " . $e->getMessage());
                    // If new photo was uploaded but transaction failed, delete it
                    if ($photo_path && $photo_path !== $current_photo_path && file_exists($photo_path)) {
                        unlink($photo_path);
                    }
                }
            }
        } else {
            $error = "Database prepare error for duplicate check: " . $conn->error;
        }
    }
}

// Delete Teacher
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["delete_teacher"])) {
    $user_id_to_delete = $_POST["user_id_to_delete"];
    $teacher_photo_path = $_POST["teacher_photo_path"] ?? null;

    $conn->begin_transaction();
    try {
        // Delete from teachers table first
        $sql_delete_teacher = "DELETE FROM teachers WHERE user_id = ? AND school_id = ?";
        if ($stmt_teacher = $conn->prepare($sql_delete_teacher)) {
            $stmt_teacher->bind_param("ii", $user_id_to_delete, $current_user_school_id);
            if (!$stmt_teacher->execute()) {
                throw new Exception("Error deleting teacher record: " . $stmt_teacher->error);
            }
            $stmt_teacher->close();

            // Then delete from users table
            $sql_delete_user = "DELETE FROM users WHERE id = ? AND school_id = ? AND role = ?";
            if ($stmt_user = $conn->prepare($sql_delete_user)) {
                $role_teacher_code = ROLE_TEACHER;
                $stmt_user->bind_param("iii", $user_id_to_delete, $current_user_school_id, $role_teacher_code);
                if (!$stmt_user->execute()) {
                    throw new Exception("Error deleting user record: " . $stmt_user->error);
                }
                $stmt_user->close();
                $conn->commit();
                $message = "Teacher deleted successfully!";

                // Delete associated photo file
                if ($teacher_photo_path && file_exists($teacher_photo_path) && $teacher_photo_path != 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD') {
                    unlink($teacher_photo_path);
                }
            } else {
                throw new Exception("Prepare failed for user delete: " . $conn->error);
            }
        } else {
            throw new Exception("Prepare failed for teacher delete: " . $conn->error);
        }
    } catch (Exception $e) {
        $conn->rollback();
        $error = "Failed to delete teacher: " . $e->getMessage();
        error_log("Delete Teacher Error: " . $e->getMessage());
    }
}

// Upload CSV
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["upload_csv"])) {
    if (isset($_FILES["csv_file"]) && $_FILES["csv_file"]["error"] == UPLOAD_ERR_OK) {
        $file_tmp_path = $_FILES["csv_file"]["tmp_name"];
        $file_extension = pathinfo($_FILES["csv_file"]["name"], PATHINFO_EXTENSION);

        if (strtolower($file_extension) != 'csv') {
            $error = "Please upload a valid CSV file.";
        } else {
            $row_count = 0;
            $success_count = 0;
            $fail_count = 0;
            $failed_rows = [];

            if (($handle = fopen($file_tmp_path, "r")) !== FALSE) {
                // Read the header row (and skip it)
                fgetcsv($handle);

                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    $row_count++;
                    // Assuming CSV format: Name,Email,Phone,Password
                    if (count($data) >= 4) {
                        $teacher_name = trim($data[0]);
                        $teacher_email = strtolower(trim($data[1])); // Normalize email to lowercase
                        $teacher_phone = trim($data[2]);
                        $teacher_password = password_hash(trim($data[3]), PASSWORD_DEFAULT);

                        if (empty($teacher_name) || empty($teacher_email) || empty($teacher_phone) || empty($data[3])) {
                            $failed_rows[] = "Row $row_count (Missing data)";
                            $fail_count++;
                            continue;
                        }
                        if (!filter_var($teacher_email, FILTER_VALIDATE_EMAIL)) {
                            $failed_rows[] = "Row $row_count (Invalid email)";
                            $fail_count++;
                            continue;
                        }

                        // Check for duplicate email before insertion
                        $sql_check_duplicate_csv = "SELECT id FROM users WHERE email = ? AND school_id = ?";
                        if ($stmt_check_csv = $conn->prepare($sql_check_duplicate_csv)) {
                            $stmt_check_csv->bind_param("si", $teacher_email, $current_user_school_id);
                            $stmt_check_csv->execute();
                            $stmt_check_csv->store_result();
                            if ($stmt_check_csv->num_rows > 0) {
                                // Updated error message for CSV upload to include the email
                                $failed_rows[] = "Row $row_count (Email '" . htmlspecialchars($teacher_email) . "' already exists)";
                                $fail_count++;
                                $stmt_check_csv->close();
                                continue; // Skip to next row
                            }
                            $stmt_check_csv->close();
                        } else {
                            $failed_rows[] = "Row $row_count (Database prepare error for duplicate check)";
                            $fail_count++;
                            continue; // Skip to next row
                        }


                        $conn->begin_transaction();
                        try {
                            // Insert into users table
                            $sql_insert_user = "INSERT INTO users (username, email, password, role, school_id, phone_number, status) VALUES (?, ?, ?, ?, ?, ?, 'active')";
                            if ($stmt_user = $conn->prepare($sql_insert_user)) {
                                $role_teacher_code = ROLE_TEACHER;
                                $stmt_user->bind_param("sssiis", $teacher_name, $teacher_email, $teacher_password, $role_teacher_code, $current_user_school_id, $teacher_phone);
                                if (!$stmt_user->execute()) {
                                    throw new Exception("User insert error: " . $stmt_user->error);
                                }
                                $new_user_id = $conn->insert_id;
                                $stmt_user->close();

                                // Insert into teachers table
                                $sql_insert_teacher = "INSERT INTO teachers (user_id, school_id) VALUES (?, ?)";
                                if ($stmt_teacher = $conn->prepare($sql_insert_teacher)) {
                                    $stmt_teacher->bind_param("ii", $new_user_id, $current_user_school_id);
                                    if (!$stmt_teacher->execute()) {
                                        throw new Exception("Teacher insert error: " . $stmt_teacher->error);
                                    }
                                    $stmt_teacher->close();
                                    $conn->commit();
                                    $success_count++;
                                } else {
                                    throw new Exception("Prepare failed for teacher insert: " . $conn->error);
                                }
                            } else {
                                throw new Exception("Prepare failed for user insert: " . $conn->error);
                            }
                        } catch (Exception $e) {
                            $conn->rollback();
                            $failed_rows[] = "Row $row_count (" . $e->getMessage() . ")";
                            $fail_count++;
                            error_log("CSV Upload Teacher Error: " . $e->getMessage());
                        }
                    } else {
                        $failed_rows[] = "Row $row_count (Incorrect column count)";
                        $fail_count++;
                    }
                }
                fclose($handle);
                $message = "CSV upload complete. Successfully added: $success_count teachers. Failed: $fail_count teachers.";
                if (!empty($failed_rows)) {
                    $message .= " Details of failed rows: " . implode("; ", $failed_rows);
                }
            } else {
                $error = "Could not open CSV file.";
            }
        }
    } else {
        $error = "Error uploading CSV file: " . $_FILES["csv_file"]["error"];
    }
}


// Fetch all teachers for the current school
if (isset($conn) && $conn instanceof mysqli) {
    $sql_fetch_teachers = "SELECT
                                t.teacher_id,
                                u.id AS user_id,
                                u.username,
                                u.email,
                                u.phone_number,
                                u.photo,
                                u.status
                           FROM
                                teachers t
                           JOIN
                                users u ON t.user_id = u.id
                           WHERE
                                t.school_id = ?
                           ORDER BY
                                u.username ASC";

    if ($stmt_fetch = $conn->prepare($sql_fetch_teachers)) {
        $stmt_fetch->bind_param("i", $current_user_school_id);
        if ($stmt_fetch->execute()) {
            $result_fetch = $stmt_fetch->get_result();
            while ($row = $result_fetch->fetch_assoc()) {
                // Ensure photo path is not empty, otherwise use default
                if (empty($row['photo'])) {
                    $row['photo'] = 'https://via.placeholder.com/80/cccccc/FFFFFF?text=TC'; // Teacher default placeholder
                }
                $teachers[] = $row;
            }
        } else {
            error_log("Execute failed for fetching teachers: " . $stmt_fetch->error);
            $error = "Error fetching teachers data.";
        }
        $stmt_fetch->close();
    } else {
        error_log("Prepare failed for fetching teachers: " . $conn->error);
        $error = "Error preparing teacher fetch statement.";
    }
    // No need to close connection here, it might be used later in the page for other components.
} else {
    $error = "Database connection not available.";
}

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Teacher Management - <?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/6.0.0-beta3/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        /* Add specific styles for this page, if needed, or rely on style.css */
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 10px;
        }
        .page-header h2 {
            margin: 0;
        }
        .action-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        .teacher-table-container {
            background-color: var(--card-bg);
            padding: 25px;
            border-radius: 10px;
            box-shadow: var(--shadow-light);
            overflow-x: auto; /* Make table scrollable on small screens */
        }
        .teacher-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }
        .teacher-table th, .teacher-table td {
            border: 1px solid var(--border-color);
            padding: 12px 15px;
            text-align: left;
            vertical-align: middle;
        }
        .teacher-table th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #555;
            white-space: nowrap; /* Prevent header text from wrapping */
        }
        .teacher-table tbody tr:nth-child(even) {
            background-color: #fbfbfb;
        }
        .teacher-table tbody tr:hover {
            background-color: #f0f0f0;
        }
        .teacher-table .teacher-photo {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid var(--light-blue);
        }
        .teacher-table .actions button {
            background: none;
            border: none;
            cursor: pointer;
            font-size: 1.1em;
            margin: 0 5px;
            transition: color 0.2s ease;
        }
        .teacher-table .actions button.edit {
            color: var(--light-blue);
        }
        .teacher-table .actions button.edit:hover {
            color: #4a90e2;
        }
        .teacher-table .actions button.delete {
            color: #e74c3c;
        }
        .teacher-table .actions button.delete:hover {
            color: #c0392b;
        }

        /* Modal specific styles (override if necessary) */
        .modal-content .form-group label {
            font-weight: 600;
            color: var(--text-dark);
            margin-bottom: 5px;
        }
        .modal-content .form-group input[type="file"] {
            padding: 10px;
            border: 1px solid var(--border-color);
            border-radius: 5px;
            width: 100%;
            background-color: #f9f9f9;
        }
        .modal-content .current-photo-preview {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
            margin-top: 10px;
            border: 2px solid var(--primary-green);
        }

        /* Message and Error Styling */
        .php-message, .php-error {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 10px;
            transition: opacity 0.5s ease-out; /* For fading effect */
        }
        .php-message {
            background-color: #e6ffe6; /* Light green */
            color: #28a745; /* Dark green text */
            border: 1px solid #c3e6cb;
        }
        .php-error {
            background-color: #ffe6e6; /* Light red */
            color: #e74c3c; /* Dark red text */
            border: 1px solid #e6c3c3;
        }
        .php-message i, .php-error i {
            font-size: 1.2em;
        }

        /* Responsive adjustments for tables */
        @media (max-width: 768px) {
            .teacher-table thead {
                display: none; /* Hide table headers on small screens */
            }
            .teacher-table, .teacher-table tbody, .teacher-table tr, .teacher-table td {
                display: block;
                width: 100%;
            }
            .teacher-table tr {
                margin-bottom: 15px;
                border: 1px solid var(--border-color);
                border-radius: 8px;
                box-shadow: var(--shadow-light);
            }
            .teacher-table td {
                text-align: right;
                padding-left: 50%;
                position: relative;
                border: none;
            }
            .teacher-table td::before {
                content: attr(data-label);
                position: absolute;
                left: 15px;
                width: calc(50% - 30px);
                text-align: left;
                font-weight: 600;
                color: #333;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
            .teacher-table .actions {
                text-align: center;
                padding-top: 10px;
                border-top: 1px solid #eee;
                margin-top: 10px;
            }

/* --- MOBILE FOOTER & OVERLAY STYLES --- */
@media (max-width: 768px) {
    /* ... (keep your existing mobile table styles here) ... */

    /* 1. Mobile Footer (Primary Navigation) */
    .mobile-footer {
        display: flex; /* Use flexbox for button alignment */
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 60px; /* Standard footer height */
        background-color: var(--sidebar-bg, #343a40); /* Use your sidebar background */
        color: var(--text-light, #ffffff);
        box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.2);
        z-index: 1000;
        padding: 0;
        margin: 0;
    }

    .mobile-footer nav {
        width: 100%;
    }

    .mobile-footer nav ul {
        display: flex;
        justify-content: space-around;
        align-items: center;
        height: 100%;
        padding: 0;
        margin: 0;
        list-style: none;
    }

    .mobile-footer nav ul li a {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        text-decoration: none;
        color: rgba(255, 255, 255, 0.7); /* Lighter default color */
        font-size: 0.75em;
        font-weight: 500;
        padding: 5px;
        transition: color 0.2s ease;
        min-width: 60px; /* Ensure a large enough tap target */
        height: 50px;
    }

    .mobile-footer nav ul li a i {
        font-size: 1.4em;
        margin-bottom: 2px;
    }

    .mobile-footer nav ul li a.active,
    .mobile-footer nav ul li a:hover {
        color: var(--light-blue, #5dade2); /* Use your primary accent color */
    }

    /* 2. Content Padding */
    .dashboard-content {
        padding-bottom: 75px; /* Must be slightly larger than footer height (60px) */
    }

    /* 3. The "More Menu" Overlay (Bottom Sheet) */
    .more-menu-overlay {
        position: fixed;
        bottom: 60px; /* Position right above the fixed footer */
        left: 0;
        width: 100%;
        max-height: calc(100vh - 80px); /* Limit max height */
        background-color: var(--card-bg, white);
        box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.15);
        z-index: 999; /* Below the footer but above content */
        transform: translateY(100%); /* Initially hidden off-screen */
        transition: transform 0.3s ease-out;
        overflow-y: auto; /* Scroll content if too long */
        border-top-left-radius: 15px;
        border-top-right-radius: 15px;
        padding: 20px 15px;
        box-sizing: border-box;
    }

    .more-menu-overlay.open {
        transform: translateY(0); /* Slide up into view */
    }

    .more-menu-overlay h3 {
        color: var(--primary-green);
        border-bottom: 1px solid var(--border-color);
        padding-bottom: 10px;
        margin-bottom: 15px;
    }

    .more-menu-overlay ul {
        list-style: none;
        padding: 0;
        margin: 0;
    }

    .more-menu-overlay ul li a {
        display: block;
        padding: 12px 0;
        color: var(--text-dark);
        text-decoration: none;
        border-bottom: 1px solid #eee;
        transition: background-color 0.2s;
    }

    .more-menu-overlay ul li a:hover {
        background-color: #f8f8f8;
    }
}

/* Hide mobile footer on larger screens */
@media (min-width: 769px) {
    .mobile-footer, .more-menu-overlay {
        display: none !important;
    }
}

            /* Add padding to the main content to prevent it from being hidden by the fixed footer */
            .dashboard-content {
                padding-bottom: 80px; /* Adjust based on actual footer height */
            }
        }

        /* Hide mobile footer on larger screens (desktop/tablet) */
        @media (min-width: 769px) {
            .mobile-footer {
                display: none;
            }
        }

        /* --- MOBILE FOOTER NAVIGATION STYLES --- */
        
        /* 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; /* Hidden by default on desktop */
        }

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

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

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

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

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

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

        @media (max-width: 768px) {
            #mobile-footer-nav {
                display: block;
            }
            
            .main-content {
                padding-bottom: 90px;
            }
            
            .sidebar nav ul li.hide-on-mobile {
                display: none;
            }
        }

        @media (max-width: 360px) {
            #mobile-footer-nav a {
                font-size: 9px;
            }
            
            #mobile-footer-nav a i {
                font-size: 20px;
            }
        }

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

        @media (max-width: 768px) {
        }
    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <aside class="sidebar" id="sidebar">
            <div class="logo">
                <img src="images/logo.png" alt="divine Logo">
                <br><H8> DIVINE REPORTS</H8></br>
            </div>
            <nav>
                <ul>
                    <li><a href="admin_dashboard.php" id="dashboardLink"><i class="fas fa-th-large"></i> <span class="nav-text">Dashboard</span></a></li>
                    <li><a href="admin_calendar.php" id="calendarLink"><i class="far fa-calendar-alt"></i> <span class="nav-text">Calendar</span></a></li>
                    <li><a href="admin_user_management.php" id="usersLink"><i class="fas fa-users-cog"></i> <span class="nav-text">Users</span></a></li>
                    <li><a href="admin_students.php" id="studentsLink"><i class="fas fa-user-graduate"></i> <span class="nav-text">Students</span></a></li>
                    <li class="active"><a href="admin_teachers.php" id="teachersLink"><i class="fas fa-chalkboard-teacher"></i> <span class="nav-text">Teachers</span></a></li>
                    <li class="hidden md:block"><a href="admin_classes.php" id="classesLink"><i class="fas fa-chalkboard"></i> <span class="nav-text">Classes</span></a></li>
                    <li class="hidden md:block"><a href="admin_subjects.php" id="subjectsLink"><i class="fas fa-book"></i> <span class="nav-text">Subjects</span></a></li>
                    <li class="hidden md:block"><a href="admin_exams.php" id="examsLink"><i class="fas fa-file-alt"></i> <span class="nav-text">Exams</span></a></li>
                    <li class="hidden md:block"><a href="admin_messages.php" id="messagesLinkSidebar"><i class="fas fa-envelope"></i> <span class="nav-text">Messages</span></a></li>
                    <li class="hidden md:block"><a href="admin_reports_printouts.php" id="printoutsLink"><i class="fas fa-print"></i> <span class="nav-text">Printouts</span></a></li>
                    <li class="hidden md:block"><a href="admin_system_settings.php" id="systemSettingsLink"><i class="fas fa-cog"></i> <span class="nav-text">Settings</span></a></li>
                    <li class="hidden md:block"><a href="logout.php" class="logout-btn" id="logoutLinkSidebar"><i class="fas fa-sign-out-alt"></i> <span class="nav-text">Logout</span></a></li>
                </ul>
            </nav>
        </aside>

        <div class="main-content">
            <header class="header">
                <button class="menu-toggle" id="menuToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="school-info">
                    <img src="<?php echo $school_logo_path; ?>" alt="<?php echo $school_name; ?> Logo">
                    <h1><?php echo $school_name; ?></h1>
                </div>
                <div class="header-right">
                    <div class="language-select">
                        <select id="languageSelect">
                            <option value="en">🇬🇧 English</option>
                            <option value="lg">🇺🇬 Luganda</option>
                            <option value="sw">🇹🇿 Kiswahili</option>
                        </select>
                    </div>
                    <div class="search-bar">
                        <i class="fas fa-search"></i>
                        <input type="text" placeholder="Search students/data" id="searchPlaceholder">
                    </div>
                    <div class="notifications">
                        <i class="fas fa-bell"></i>
                        <span class="badge">3</span>
                    </div>
                    <div class="user-profile">
                        <img src="<?php echo $photo; ?>" alt="User Photo">
                        <div>
                            <div class="user-name"><?php echo $username; ?></div>
                            <div class="user-email">Logged in as: Admin</div>
                        </div>
                        <i class="fas fa-chevron-down"></i>
                    </div>
                </div>
            </header>

            <div class="dashboard-content">
                <div class="page-header">
                    <h2><i class="fas fa-chalkboard-teacher"></i> Teacher Management</h2>
                    <div class="action-buttons">
                        <button class="btn btn-primary" id="addTeacherBtn"><i class="fas fa-plus"></i> Add New Teacher</button>
                        <button class="btn btn-success" id="uploadCsvBtn"><i class="fas fa-file-csv"></i> Upload Teachers CSV</button>
                    </div>
                </div>

                <?php if (!empty($message)): ?>
                    <div class="php-message" id="phpMessage"><i class="fas fa-check-circle"></i> <?php echo $message; ?></div>
                <?php endif; ?>
                <?php if (!empty($error)): ?>
                    <div class="php-error" id="phpError"><i class="fas fa-times-circle"></i> <?php echo $error; ?></div>
                <?php endif; ?>

                <div class="teacher-table-container">
                    <h3>Teacher List</h3>
                    <?php if (empty($teachers)): ?>
                        <p>No teachers found for your school.</p>
                    <?php else: ?>
                        <table class="teacher-table">
                            <thead>
                                <tr>
                                    <th>Photo</th>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Phone</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($teachers as $teacher): ?>
                                    <tr>
                                        <td data-label="Photo">
                                            <img src="<?php echo htmlspecialchars($teacher['photo']); ?>" alt="Teacher Photo" class="teacher-photo">
                                        </td>
                                        <td data-label="Name"><?php echo htmlspecialchars($teacher['username']); ?></td>
                                        <td data-label="Email"><?php echo htmlspecialchars($teacher['email']); ?></td>
                                        <td data-label="Phone"><?php echo htmlspecialchars($teacher['phone_number']); ?></td>
                                        <td data-label="Status"><?php echo htmlspecialchars(ucfirst($teacher['status'] ?: 'N/A')); ?></td>
                                        <td data-label="Actions" class="actions">
                                            <button class="edit" title="Edit Teacher"
                                                    data-user-id="<?php echo htmlspecialchars($teacher['user_id']); ?>"
                                                    data-teacher-id="<?php echo htmlspecialchars($teacher['teacher_id']); ?>"
                                                    data-username="<?php echo htmlspecialchars($teacher['username']); ?>"
                                                    data-email="<?php echo htmlspecialchars($teacher['email']); ?>"
                                                    data-phone="<?php echo htmlspecialchars($teacher['phone_number']); ?>"
                                                    data-photo="<?php echo htmlspecialchars($teacher['photo']); ?>">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button class="delete" title="Delete Teacher"
                                                    data-user-id="<?php echo htmlspecialchars($teacher['user_id']); ?>"
                                                    data-username="<?php echo htmlspecialchars($teacher['username']); ?>"
                                                    data-photo-path="<?php echo htmlspecialchars($teacher['photo']); ?>">
                                                <i class="fas fa-trash-alt"></i>
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>
            </div>

           <div class="dashboard-content">
        </div>
    
        </div>
    </div>

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

    <!-- Add Teacher Modal -->
    <div id="addTeacherModal" class="modal">
        <div class="modal-content">
            <span class="close-button">&times;</span>
            <h3>Add New Teacher</h3>
            <form action="admin_teachers.php" method="post" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="teacher_name">Full Name:</label>
                    <input type="text" id="teacher_name" name="teacher_name" required>
                </div>
                <div class="form-group">
                    <label for="teacher_email">Email:</label>
                    <input type="email" id="teacher_email" name="teacher_email" required>
                </div>
                <div class="form-group">
                    <label for="teacher_phone">Phone Number:</label>
                    <input type="text" id="teacher_phone" name="teacher_phone">
                </div>
                <div class="form-group">
                    <label for="teacher_password">Password:</label>
                    <input type="password" id="teacher_password" name="teacher_password" required>
                </div>
                <div class="form-group">
                    <label for="teacher_photo">Photo:</label>
                    <input type="file" id="teacher_photo" name="teacher_photo" accept="image/*">
                </div>
                <button type="submit" name="add_teacher" class="btn btn-primary">Add Teacher</button>
            </form>
        </div>
    </div>

    <!-- Edit Teacher Modal -->
    <div id="editTeacherModal" class="modal">
        <div class="modal-content">
            <span class="close-button">&times;</span>
            <h3>Edit Teacher Details</h3>
            <form action="admin_teachers.php" method="post" enctype="multipart/form-data">
                <input type="hidden" id="edit_teacher_id" name="teacher_id">
                <input type="hidden" id="edit_user_id" name="user_id">
                <input type="hidden" id="current_photo_path" name="current_photo_path">
                <div class="form-group">
                    <label for="edit_teacher_name">Full Name:</label>
                    <input type="text" id="edit_teacher_name" name="edit_teacher_name" required>
                </div>
                <div class="form-group">
                    <label for="edit_teacher_email">Email:</label>
                    <input type="email" id="edit_teacher_email" name="edit_teacher_email" required>
                </div>
                <div class="form-group">
                    <label for="edit_teacher_phone">Phone Number:</label>
                    <input type="text" id="edit_teacher_phone" name="edit_teacher_phone">
                </div>
                <div class="form-group">
                    <label>Current Photo:</label>
                    <img id="edit_current_photo_preview" src="" alt="Current Photo" class="current-photo-preview">
                </div>
                <div class="form-group">
                    <label for="edit_teacher_photo">Change Photo (optional):</label>
                    <input type="file" id="edit_teacher_photo" name="edit_teacher_photo" accept="image/*">
                </div>
                <button type="submit" name="edit_teacher" class="btn btn-primary">Update Teacher</button>
            </form>
        </div>
    </div>

    <!-- Upload CSV Modal -->
    <div id="uploadCsvModal" class="modal">
        <div class="modal-content">
            <span class="close-button">&times;</span>
            <h3>Upload Teachers CSV</h3>
            <p>CSV format: <code>Name,Email,Phone,Password</code> (No header row expected)</p>
            <form action="admin_teachers.php" method="post" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="csv_file">Select CSV File:</label>
                    <input type="file" id="csv_file" name="csv_file" accept=".csv" required>
                </div>
                <button type="submit" name="upload_csv" class="btn btn-success">Upload CSV</button>
            </form>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div id="deleteConfirmationModal" class="modal">
        <div class="modal-content">
            <span class="close-button">&times;</span>
            <h3>Confirm Deletion</h3>
            <p>Are you sure you want to delete teacher: <strong id="teacherNameToDelete"></strong>?</p>
            <p>This action cannot be undone.</p>
            <form action="admin_teachers.php" method="post">
                <input type="hidden" id="delete_user_id" name="user_id_to_delete">
                <input type="hidden" id="delete_teacher_photo_path" name="teacher_photo_path">
                <button type="submit" name="delete_teacher" class="btn btn-danger">Delete</button>
                <button type="button" class="btn" id="cancelDeleteBtn">Cancel</button>
            </form>
        </div>
    </div>


    <script>
        // --- Sidebar and Header Toggle Logic (from admin_dashboard.php) ---
        const menuToggle = document.getElementById('menuToggle');
        const sidebar = document.getElementById('sidebar');
        const dashboardContainer = document.getElementById('dashboardContainer');
        const overlay = document.getElementById('overlay');

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

        if (overlay) {
            overlay.addEventListener('click', () => {
                sidebar.classList.remove('active');
                dashboardContainer.classList.remove('sidebar-open');
                overlay.classList.remove('active');
            });
        }


        // --- Modal Logic ---
        function openModal(modalId) {
            document.getElementById(modalId).style.display = 'flex';
        }

        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        document.querySelectorAll('.close-button').forEach(button => {
            button.addEventListener('click', (e) => {
                const modal = e.target.closest('.modal');
                if (modal) {
                    closeModal(modal.id);
                }
            });
        });

        window.addEventListener('click', (event) => {
            document.querySelectorAll('.modal').forEach(modal => {
                if (event.target == modal) {
                    closeModal(modal.id);
                }
            });
        });

        // Add Teacher Modal
        const addTeacherBtn = document.getElementById('addTeacherBtn');
        if (addTeacherBtn) {
            addTeacherBtn.addEventListener('click', () => openModal('addTeacherModal'));
        }

        // Upload CSV Modal
        const uploadCsvBtn = document.getElementById('uploadCsvBtn');
        if (uploadCsvBtn) {
            uploadCsvBtn.addEventListener('click', () => openModal('uploadCsvModal'));
        }

        // Edit Teacher Modal
        document.querySelectorAll('.teacher-table .actions button.edit').forEach(button => {
            button.addEventListener('click', function() {
                const userId = this.dataset.userId;
                const teacherId = this.dataset.teacherId;
                const username = this.dataset.username;
                const email = this.dataset.email;
                const phone = this.dataset.phone;
                const photo = this.dataset.photo;

                document.getElementById('edit_user_id').value = userId;
                document.getElementById('edit_teacher_id').value = teacherId;
                document.getElementById('edit_teacher_name').value = username;
                document.getElementById('edit_teacher_email').value = email;
                document.getElementById('edit_teacher_phone').value = phone;
                document.getElementById('current_photo_path').value = photo;
                document.getElementById('edit_current_photo_preview').src = photo;

                openModal('editTeacherModal');
            });
        });

        // Delete Confirmation Modal
        document.querySelectorAll('.teacher-table .actions button.delete').forEach(button => {
            button.addEventListener('click', function() {
                const userId = this.dataset.userId;
                const username = this.dataset.username;
                const photoPath = this.dataset.photoPath;

                document.getElementById('delete_user_id').value = userId;
                document.getElementById('delete_teacher_photo_path').value = photoPath;
                document.getElementById('teacherNameToDelete').textContent = username;
                openModal('deleteConfirmationModal');
            });
        });

        const cancelDeleteBtn = document.getElementById('cancelDeleteBtn');
        if (cancelDeleteBtn) {
            cancelDeleteBtn.addEventListener('click', () => closeModal('deleteConfirmationModal'));
        }

        // --- Message Fade Out Logic ---
        document.addEventListener('DOMContentLoaded', () => {
            const phpMessage = document.getElementById('phpMessage');
            const phpError = document.getElementById('phpError');

            if (phpMessage) {
                setTimeout(() => {
                    phpMessage.style.opacity = '0';
                    setTimeout(() => phpMessage.style.display = 'none', 500); // Wait for fade out transition
                }, 3000); // 3 seconds
            }

            if (phpError) {
                setTimeout(() => {
                    phpError.style.opacity = '0';
                    setTimeout(() => phpError.style.display = 'none', 500); // Wait for fade out transition
                }, 3000); // 3 seconds
            }
        });


        // --- Language Translation (from admin_dashboard.php, adapted) ---
        const schoolNameForJs = "<?php echo $school_name_for_js; ?>"; // PHP variable passed to JS

        const translations = {
            en: {
                // Sidebar
                dashboard: "Dashboard",
                calendar: "Calendar",
                users: "Users",
                students: "Students",
                teachers: "Teachers",
                classes: "Classes",
                subjects: "Subjects",
                grades: "Grades",
                exams: "Exams",
                messages: "Messages",
                printouts: "Printouts",
                systemSettings: "Settings",
                logout: "Logout",
                // Header
                searchPlaceholder: "Search students/data",
                // Page Specific
                pageTitle: "Teacher Management",
                addTeacherBtn: "Add New Teacher",
                uploadCsvBtn: "Upload Teachers CSV",
                teacherList: "Teacher List",
                noTeachersFound: "No teachers found for your school.",
                tablePhoto: "Photo",
                tableName: "Name",
                tableEmail: "Email",
                tablePhone: "Phone",
                tableStatus: "Status",
                tableActions: "Actions",
                editTeacherTitle: "Edit Teacher",
                deleteTeacherTitle: "Delete Teacher",
                // Modals
                addTeacherModalTitle: "Add New Teacher",
                fullNameLabel: "Full Name:",
                emailLabel: "Email:",
                phoneNumberLabel: "Phone Number:",
                passwordLabel: "Password:",
                photoLabel: "Photo:",
                addTeacherSubmit: "Add Teacher",
                editTeacherModalTitle: "Edit Teacher Details",
                currentPhotoLabel: "Current Photo:",
                changePhotoLabel: "Change Photo (optional):",
                updateTeacherSubmit: "Update Teacher",
                uploadCsvModalTitle: "Upload Teachers CSV",
                csvFormatHint: "CSV format: Name,Email,Phone,Password (No header row expected)",
                selectCsvFileLabel: "Select CSV File:",
                uploadCsvSubmit: "Upload CSV",
                confirmDeleteTitle: "Confirm Deletion",
                confirmDeleteMessage: "Are you sure you want to delete teacher: ",
                cannotBeUndone: "This action cannot be undone.",
                deleteBtn: "Delete",
                cancelBtn: "Cancel",
                // Footer
                profileText: "Profile",
                settingsText: "Settings",
                logoutText: "Logout"
            },
            lg: {
                // Sidebar
                dashboard: "Akawungeezi",
                calendar: "Kalenje",
                users: "Abakozesa",
                students: "Abayizi",
                teachers: "Abaasomesa",
                classes: "Ebibiina",
                subjects: "Ebizibu",
                grades: "Amasomero",
                exams: "Ebigezo",
                messages: "Ebiwandiiko",
                printouts: "Ebipimoo",
                systemSettings: "Enkola",
                logout: "Fuluma",
                // Header
                searchPlaceholder: "Noonya abayizi/ebitundu",
                // Page Specific
                pageTitle: "Okuteekateeka Abaasomesa",
                addTeacherBtn: "Yongeramu Omusomesa Omujja",
                uploadCsvBtn: "Teeka Abaasomesa mu CSV",
                teacherList: "Olukalala lw'Abaasomesa",
                noTeachersFound: "Tewali baasomesa basangiddwa mu ssomero lyo.",
                tablePhoto: "Ekifaananyi",
                tableName: "Erinnya",
                tableEmail: "E-mail",
                tablePhone: "Essimu",
                tableStatus: "Ekifo",
                tableActions: "Ebikolebwa",
                editTeacherTitle: "Eddita Omusomesa",
                deleteTeacherTitle: "Ggyawo Omusomesa",
                // Modals
                addTeacherModalTitle: "Yongeramu Omusomesa Omujja",
                fullNameLabel: "Erinnya Eddirira:",
                emailLabel: "E-mail:",
                phoneNumberLabel: "Essimu:",
                passwordLabel: "Ekyama:",
                photoLabel: "Ekifaananyi:",
                addTeacherSubmit: "Yongeramu Omusomesa",
                editTeacherModalTitle: "Eddita Abaasomesa",
                currentPhotoLabel: "Ekifaananyi ekiriwo kati:",
                changePhotoLabel: "Kyusa Ekifaananyi (Kyawulira):",
                updateTeacherSubmit: "Ddaabiriza Omusomesa",
                uploadCsvModalTitle: "Teeka Abaasomesa mu CSV",
                csvFormatHint: "Mu CSV: Erinnya,E-mail,Essimu,Ekyama (Tewali mukulu gw'olinya gw'osuubirwa)",
                selectCsvFileLabel: "Londa Fayiro ya CSV:",
                uploadCsvSubmit: "Teeka CSV",
                confirmDeleteTitle: "Kakasibwa Okuggyawo",
                confirmDeleteMessage: "Oli mukakafu oyagala okuggyawo omusomesa: ",
                cannotBeUndone: "Ekikolwa kino tekisobola kuddizibwa.",
                deleteBtn: "Ggyawo",
                cancelBtn: "Kirangirira",
                // Footer
                profileText: "Profayiro",
                settingsText: "Enkola",
                logoutText: "Fuluma"
            },
            sw: {
                // Sidebar
                dashboard: "Dashibodi",
                calendar: "Kalenda",
                users: "Watumiaji",
                students: "Wanafunzi",
                teachers: "Walimu",
                classes: "Madarasa",
                subjects: "Masomo",
                grades: "Alama",
                exams: "Mitihani",
                messages: "Ujumbe",
                printouts: "Machapisho",
                systemSettings: "Mipangilio",
                logout: "Toka",
                // Header
                searchPlaceholder: "Tafuta wanafunzi/data",
                // Page Specific
                pageTitle: "Usimamizi wa Walimu",
                addTeacherBtn: "Ongeza Mwalimu Mpya",
                uploadCsvBtn: "Pakia Walimu CSV",
                teacherList: "Orodha ya Walimu",
                noTeachersFound: "Hakuna walimu waliopatikana kwa shule yako.",
                tablePhoto: "Picha",
                tableName: "Jina",
                tableEmail: "Barua pepe",
                tablePhone: "Simu",
                tableStatus: "Hali",
                tableActions: "Vitendo",
                editTeacherTitle: "Hariri Mwalimu",
                deleteTeacherTitle: "Futa Mwalimu",
                // Modals
                addTeacherModalTitle: "Ongeza Mwalimu Mpya",
                fullNameLabel: "Jina Kamili:",
                emailLabel: "Barua pepe:",
                phoneNumberLabel: "Namba ya Simu:",
                passwordLabel: "Neno Siri:",
                photoLabel: "Picha:",
                addTeacherSubmit: "Ongeza Mwalimu",
                editTeacherModalTitle: "Hariri Maelezo ya Mwalimu",
                currentPhotoLabel: "Picha ya Sasa:",
                changePhotoLabel: "Badilisha Picha (si lazima):",
                updateTeacherSubmit: "Sasisha Mwalimu",
                uploadCsvModalTitle: "Pakia Walimu CSV",
                csvFormatHint: "Umbizo la CSV: Jina,Barua pepe,Simu,Neno Siri (Hakuna kichwa cha safu kinachotarajiwa)",
                selectCsvFileLabel: "Chagua Faili ya CSV:",
                uploadCsvSubmit: "Pakia CSV",
                confirmDeleteTitle: "Thibitisha Kufuta",
                confirmDeleteMessage: "Una uhakika unataka kumfuta mwalimu: ",
                cannotBeUndone: "Kitendo hiki hakiwezi kutenduliwa.",
                deleteBtn: "Futa",
                cancelBtn: "Ghairi",
                // Footer
                profileText: "Profaili",
                settingsText: "Mipangilio",
                logoutText: "Toka"
            }
        };

        const languageSelect = document.getElementById('languageSelect');
        const currentLanguage = localStorage.getItem('selectedLanguage') || 'en';
        languageSelect.value = currentLanguage;
        applyTranslations(currentLanguage);

        languageSelect.addEventListener('change', (event) => {
            const newLanguage = event.target.value;
            localStorage.setItem('selectedLanguage', newLanguage);
            applyTranslations(newLanguage);
        });

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

            // Sidebar
            // For each sidebar link, find the .nav-text span and update its textContent
            const sidebarLinks = [
                { id: 'dashboardLink', text: t.dashboard },
                { id: 'calendarLink', text: t.calendar },
                { id: 'usersLink', text: t.users },
                { id: 'studentsLink', text: t.students },
                { id: 'teachersLink', text: t.teachers },
                { id: 'classesLink', text: t.classes },
                { id: 'subjectsLink', text: t.subjects },
                { id: 'gradesLink', text: t.grades },
                { id: 'examsLink', text: t.exams },
                { id: 'messagesLinkSidebar', text: t.messages },
                { id: 'printoutsLink', text: t.printouts },
                { id: 'systemSettingsLink', text: t.systemSettings },
                { id: 'logoutLinkSidebar', text: t.logout }
            ];

            sidebarLinks.forEach(linkInfo => {
                const linkElement = document.getElementById(linkInfo.id);
                if (linkElement) {
                    const navTextSpan = linkElement.querySelector('.nav-text');
                    if (navTextSpan) {
                        navTextSpan.textContent = linkInfo.text;
                    }
                }
            });


            // Header
            document.getElementById('searchPlaceholder').placeholder = t.searchPlaceholder;

            // Page Specific Elements
            // Ensure childNodes[1] exists before attempting to set textContent
            const pageHeaderH2 = document.querySelector('.page-header h2');
            if (pageHeaderH2 && pageHeaderH2.childNodes[1]) {
                pageHeaderH2.childNodes[1].textContent = ' ' + t.pageTitle;
            }
            document.getElementById('addTeacherBtn').innerHTML = `<i class="fas fa-plus"></i> ${t.addTeacherBtn}`;
            document.getElementById('uploadCsvBtn').innerHTML = `<i class="fas fa-file-csv"></i> ${t.uploadCsvBtn}`;
            document.querySelector('.teacher-table-container h3').textContent = t.teacherList;

            // Table headers
            // More robust selection for table headers
            const tableHeaders = {
                'Photo': 'tablePhoto',
                'Name': 'tableName',
                'Email': 'tableEmail',
                'Phone': 'tablePhone',
                'Status': 'tableStatus',
                'Actions': 'tableActions'
            };

            document.querySelectorAll('.teacher-table th').forEach(th => {
                const headerText = th.textContent.trim();
                if (tableHeaders[headerText]) {
                    th.textContent = t[tableHeaders[headerText]];
                }
            });

            // For responsive table headers (data-label attributes)
            document.querySelectorAll('.teacher-table td[data-label]').forEach(td => {
                const label = td.getAttribute('data-label');
                // Re-map the data-label to the English key for lookup, then set translated value
                let originalLabelKey = '';
                for (const key in tableHeaders) {
                    if (t[tableHeaders[key]] === label) { // Find the key that matches the translated label
                        originalLabelKey = key;
                        break;
                    }
                }
                if (originalLabelKey && t[tableHeaders[originalLabelKey]]) {
                    td.setAttribute('data-label', t[tableHeaders[originalLabelKey]]);
                }
            });


            // Modals
            if (document.getElementById('addTeacherModal')) {
                document.getElementById('addTeacherModal').querySelector('h3').textContent = t.addTeacherModalTitle;
                document.querySelector('#addTeacherModal label[for="teacher_name"]').textContent = t.fullNameLabel;
                document.querySelector('#addTeacherModal label[for="teacher_email"]').textContent = t.emailLabel;
                document.querySelector('#addTeacherModal label[for="teacher_phone"]').textContent = t.phoneNumberLabel;
                document.querySelector('#addTeacherModal label[for="teacher_password"]').textContent = t.passwordLabel;
                document.querySelector('#addTeacherModal label[for="teacher_photo"]').textContent = t.photoLabel;
                document.querySelector('#addTeacherModal button[type="submit"]').textContent = t.addTeacherSubmit;
            }

            if (document.getElementById('editTeacherModal')) {
                document.getElementById('editTeacherModal').querySelector('h3').textContent = t.editTeacherModalTitle;
                document.querySelector('#editTeacherModal label[for="edit_teacher_name"]').textContent = t.fullNameLabel;
                document.querySelector('#editTeacherModal label[for="edit_teacher_email"]').textContent = t.emailLabel;
                document.querySelector('#editTeacherModal label[for="edit_teacher_phone"]').textContent = t.phoneNumberLabel;
                // Assuming this label targets a text next to current photo, otherwise adjust selector
                const currentPhotoLabelElement = document.querySelector('#editTeacherModal label:not([for])'); // Target label without a 'for' attribute
                if (currentPhotoLabelElement) {
                    currentPhotoLabelElement.textContent = t.currentPhotoLabel;
                }
                document.querySelector('#editTeacherModal label[for="edit_teacher_photo"]').textContent = t.changePhotoLabel;
                document.querySelector('#editTeacherModal button[type="submit"]').textContent = t.updateTeacherSubmit;
            }

            if (document.getElementById('uploadCsvModal')) {
                document.getElementById('uploadCsvModal').querySelector('h3').textContent = t.uploadCsvModalTitle;
                document.querySelector('#uploadCsvModal p').textContent = t.csvFormatHint;
                document.querySelector('#uploadCsvModal label[for="csv_file"]').textContent = t.selectCsvFileLabel;
                document.querySelector('#uploadCsvModal button[type="submit"]').textContent = t.uploadCsvSubmit;
            }

            if (document.getElementById('deleteConfirmationModal')) {
                document.getElementById('deleteConfirmationModal').querySelector('h3').textContent = t.confirmDeleteTitle;
                // Update the text content of the first paragraph, keeping the strong tag intact
                const confirmMessageP = document.querySelector('#deleteConfirmationModal p:nth-of-type(1)');
                if (confirmMessageP) {
                    // Temporarily store the strong element, clear the P, add new text, then re-append strong
                    const teacherNameStrong = confirmMessageP.querySelector('strong');
                    confirmMessageP.textContent = t.confirmDeleteMessage;
                    if (teacherNameStrong) {
                        confirmMessageP.appendChild(teacherNameStrong);
                    }
                }
                document.querySelector('#deleteConfirmationModal p:nth-of-type(2)').textContent = t.cannotBeUndone;
                document.querySelector('#deleteConfirmationModal button[type="submit"]').textContent = t.deleteBtn;
                document.getElementById('cancelDeleteBtn').textContent = t.cancelBtn;
            }

            // Fallback for "No teachers found"
            const noTeachersElement = document.querySelector('.teacher-table-container p');
            if (noTeachersElement && noTeachersElement.textContent.includes('No teachers found')) { // Check if it's the specific message
                noTeachersElement.textContent = t.noTeachersFound;
            }

            // Footer
            if (document.getElementById('profileTextFooter')) document.getElementById('profileTextFooter').textContent = t.profileText;
            if (document.getElementById('settingsTextFooter')) document.getElementById('settingsTextFooter').textContent = t.settingsText;
            if (document.getElementById('logoutTextFooter')) document.getElementById('logoutTextFooter').textContent = t.logoutText;

            // Clear any old message/error if present after translation (they will fade out anyway)
            // No need to actively remove them here as the fade-out logic handles visibility.
        }
    </script>
    
    <div class="mobile-footer" id="mobile-footer">
        <nav>
            <ul>
                <li>
                    <a href="admin_dashboard.php" class="<?php echo (basename($_SERVER['PHP_SELF']) == 'admin_dashboard.php' ? 'active' : ''); ?>">
                        <i class="fas fa-home"></i>
                        <span>Home</span>
                    </a>
                </li>
                <li>
                    <a href="teacher_management.php" class="<?php echo (basename($_SERVER['PHP_SELF']) == 'teacher_management.php' ? 'active' : ''); ?>">
                        <i class="fas fa-chalkboard-teacher"></i>
                        <span>Teachers</span>
                    </a>
                </li>
                <li>
                    <a href="student_management.php" class="<?php echo (basename($_SERVER['PHP_SELF']) == 'student_management.php' ? 'active' : ''); ?>">
                        <i class="fas fa-user-graduate"></i>
                        <span>Students</span>
                    </a>
                </li>
                <li>
                    <a href="javascript:void(0);" onclick="toggleMoreMenu(this);" id="more-button">
                        <i class="fas fa-bars"></i>
                        <span id="more-label">More</span>
                    </a>
                </li>
            </ul>
        </nav>
    </div>

    <div class="more-menu-overlay" id="more-menu-overlay">
        
        <h3><i class="fas fa-user-circle"></i> Account</h3>
        <ul>
            <li><a href="admin_classes.php"><i class="fas fa-cog"></i> classes</a></li>
            <li><a href="admin_user_management.php"><i class="fas fa-users-cog"></i> Users</a></li>
        </ul>
        <ul>
            <li><a href="admin_subjects.php"><i class="fas fa-book"></i> subjects</a></li>
            <li><a href="admin_exams.php"><i class="fas fa-file-alt"></i> Exams</a></li>
            <li><a href="admin_reports_printouts.php"><i class="fas fa-print"></i> printouts</a></li>
        </ul>
        <ul>
            <li><a href="admin_messages.php"><i class="fas fa-envelope"></i> messages</a></li>
            <li><a href="logout.php" style="color: #e74c3c;"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
        </ul>
    </div>
    
   
    <script>
        // Function to toggle the "More Menu" overlay
        function toggleMoreMenu(button) {
            const overlay = document.getElementById('more-menu-overlay');
            const icon = button.querySelector('i');
            const label = document.getElementById('more-label');

            // Toggle the 'open' class
            const isOpen = overlay.classList.toggle('open');

            // Change icon and label based on state
            if (isOpen) {
                icon.classList.remove('fa-bars');
                icon.classList.add('fa-times'); // Use 'X' icon when open
                label.textContent = 'Close';
            } else {
                icon.classList.remove('fa-times');
                icon.classList.add('fa-bars'); // Use 'Bars' icon when closed
                label.textContent = 'More';
            }
        }

        // Close the menu if the user taps outside the overlay
        document.addEventListener('click', function(event) {
            const overlay = document.getElementById('more-menu-overlay');
            const button = document.getElementById('more-button');

            // Check if the menu is open and the click is outside the menu AND not on the More button
            if (overlay.classList.contains('open') && !overlay.contains(event.target) && !button.contains(event.target)) {
                // Manually close the menu
                toggleMoreMenu(button);
            }
        });
        
        // This is a placeholder for your existing JavaScript code (Chart.js, modals, etc.)
        // You should ensure your existing script tag content is preserved.
        // For example, if you had a script for showing alerts:
        <?php if ($message || $error): ?>
        // Logic to fade out the message/error boxes after a few seconds
        setTimeout(function() {
            const msg = document.querySelector('.php-message');
            const err = document.querySelector('.php-error');
            if (msg) msg.style.opacity = '0';
            if (err) err.style.opacity = '0';
        }, 5000);
        <?php endif; ?>

    </script>

    <!-- Mobile Footer Navigation -->
    <div id="mobile-footer-nav">
        <ul>
            <li>
                <a href="admin_dashboard.php" data-section="dashboard">
                    <i class="fas fa-th-large"></i>
                    <span>Dashboard</span>
                </a>
            </li>
            <li>
                <a href="admin_user_management.php" data-section="user-management">
                    <i class="fas fa-users-cog"></i>
                    <span>Users</span>
                </a>
            </li>
            <li>
                <a href="admin_messages.php" data-section="messages">
                    <i class="fas fa-envelope"></i>
                    <span>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="admin_students.php"><i class="fas fa-user-graduate"></i> Students</a></li>
            <li><a href="admin_teachers.php"><i class="fas fa-chalkboard-teacher"></i> Teachers</a></li>
            <li><a href="admin_staff.php"><i class="fas fa-user-tie"></i> Staff</a></li>
            <li><a href="admin_classes.php"><i class="fas fa-chalkboard"></i> Classes</a></li>
            <li><a href="admin_subjects.php"><i class="fas fa-book"></i> Subjects</a></li>
            <li><a href="admin_exams.php"><i class="fas fa-file-alt"></i> Exams</a></li>
            <li><a href="admin_reports_printouts.php"><i class="fas fa-print"></i> Reports</a></li>
            <li><a href="admin_system_settings.php"><i class="fas fa-cog"></i> Settings</a></li>
            <li class="logout"><a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
        </ul>
    </div>

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

    <script>
        // Mobile Footer Navigation 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);
                });
            }
        });
    </script>

</body>
</html>
