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

// Define role constants (ensure these match your config.php or are globally 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);

// 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: // Catch-all for any other unexpected roles
                header("location: login.php");
                break;
        }
        exit;
    }
}

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

// User is authorized, fetch additional details for display
$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]); // Sanitize for display
$user_role_code = $_SESSION["role"]; // Get role code from session
$current_user_school_id = $_SESSION["school_id"]; // Get the school_id for the logged-in user
$phone_number = $photo = $status = ""; // Initialize variables for DB fetch
$success_message = $error_message = null; // Messages for form submissions

// Initialize school variables
$school_name = "School Name Not Found"; // Default value for HTML output
$school_name_for_js = "School Name Not Found"; // Default value for JavaScript output
$school_logo_path = "images/default_school_logo.png"; // Default logo path

// Ensure $conn is available from config.php
if (isset($conn) && $conn instanceof mysqli) {
    // Fetch additional user details from the database (phone, photo, status) from the 'users' table
    // (Assuming 'users' table holds common user info for the logged-in admin)
    $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');
            // Default photo for Admin if not set
            $photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD';
            $status = htmlspecialchars($status_db ?? 'N/A');
        } else {
            error_log("Execute failed for user details query for Admin: " . $stmt->error);
        }
        $stmt->close();
    } else {
        error_log("Prepare failed for user details query for Admin: " . $conn->error);
    }

    // Fetch School Name and Logo from 'schools' table
    $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);
    }

    // Define upload directory for staff photos
    $upload_dir = 'uploads/staff_photos/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    // Handle Add New Staff Form Submission
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_staff'])) {
        // Collect and sanitize input
        $new_staff_username = trim($_POST['new_staff_username']);
        $new_staff_password = $_POST['new_staff_password']; // Will be hashed
        $new_staff_email = trim($_POST['new_staff_email']);
        $new_staff_phone_number = trim($_POST['new_staff_phone_number'] ?? '');
        $new_staff_work = trim($_POST['new_staff_work'] ?? '');
        $new_staff_department = trim($_POST['new_staff_department'] ?? '');

        $new_staff_photo_path = ''; // Default empty photo path

        // Validate input
        if (empty($new_staff_username) || empty($new_staff_password) || empty($new_staff_email)) {
            $error_message = "Please fill all required fields: Username, Password, Email.";
        } elseif (!filter_var($new_staff_email, FILTER_VALIDATE_EMAIL)) {
            $error_message = "Invalid email format.";
        } else {
            // Handle photo upload for new staff
            if (isset($_FILES['new_staff_photo']) && $_FILES['new_staff_photo']['error'] == UPLOAD_ERR_OK) {
                $file_tmp_name = $_FILES['new_staff_photo']['tmp_name'];
                $file_name = basename($_FILES['new_staff_photo']['name']);
                $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                $allowed_ext = ['jpg', 'jpeg', 'png', 'gif'];

                if (in_array($file_ext, $allowed_ext)) {
                    $new_file_name = 'staff_' . uniqid() . '.' . $file_ext;
                    $destination = $upload_dir . $new_file_name;

                    if (move_uploaded_file($file_tmp_name, $destination)) {
                        $new_staff_photo_path = $destination;
                    } else {
                        $error_message = "Failed to upload staff photo.";
                    }
                } else {
                    $error_message = "Invalid file type for photo. Only JPG, JPEG, PNG, GIF are allowed.";
                }
            }

            if ($error_message === null) { // Only proceed if no file upload error
                // Check if username or email already exists in the staff table
                $sql_check_staff = "SELECT staff_id FROM staff WHERE username = ? OR email = ?";
                if ($stmt_check_staff = $conn->prepare($sql_check_staff)) {
                    $stmt_check_staff->bind_param("ss", $new_staff_username, $new_staff_email);
                    $stmt_check_staff->execute();
                    $stmt_check_staff->store_result();
                    if ($stmt_check_staff->num_rows > 0) {
                        $error_message = "Username or Email already exists for another staff member.";
                    }
                    $stmt_check_staff->close();
                } else {
                    error_log("Prepare failed for staff check: " . $conn->error);
                    $error_message = "Database error. Please try again.";
                }
            }

            if ($error_message === null) {
                // Hash password
                $hashed_password = password_hash($new_staff_password, PASSWORD_DEFAULT);
                $new_staff_status = 'active'; // Default status for new staff

                // Insert new staff into the database (staff table serves as authentication for staff)
                $sql_insert_staff = "INSERT INTO staff (school_id, username, password, email, phone_number, photo, work, department, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
                if ($stmt_insert_staff = $conn->prepare($sql_insert_staff)) {
                    $stmt_insert_staff->bind_param("issssssss",
                        $current_user_school_id,
                        $new_staff_username,
                        $hashed_password,
                        $new_staff_email,
                        $new_staff_phone_number,
                        $new_staff_photo_path,
                        $new_staff_work,
                        $new_staff_department,
                        $new_staff_status
                    );

                    if ($stmt_insert_staff->execute()) {
                        $success_message = "New staff member '{$new_staff_username}' added successfully!";
                    } else {
                        error_log("Execute failed for staff insert: " . $stmt_insert_staff->error);
                        $error_message = "Error: Could not add staff member. " . $stmt_insert_staff->error;
                    }
                    $stmt_insert_staff->close();
                } else {
                    error_log("Prepare failed for staff insert: " . $conn->error);
                    $error_message = "Database error. Please try again.";
                }
            }
        }
    }

    // Handle CSV Upload Form Submission
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['upload_csv']) && isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] == UPLOAD_ERR_OK) {
        $csv_file_path = $_FILES['csv_file']['tmp_name'];
        $file_ext = strtolower(pathinfo($_FILES['csv_file']['name'], PATHINFO_EXTENSION));

        if ($file_ext != 'csv') {
            $error_message = "Invalid file type. Please upload a CSV file.";
        } else {
            $handle = fopen($csv_file_path, "r");
            if ($handle === FALSE) {
                $error_message = "Could not open CSV file.";
            } else {
                $row_count = 0;
                $success_count = 0;
                $failed_count = 0;
                $skipped_count = 0; // For existing users
                $headers = fgetcsv($handle, 1000, ","); // Read header row

                if ($headers === FALSE) {
                    $error_message = "CSV file is empty or malformed.";
                } else {
                    // Map CSV headers to expected database columns (case-insensitive for robustness)
                    $header_map = [
                        'username' => array_search('username', array_map('strtolower', $headers)),
                        'password' => array_search('password', array_map('strtolower', $headers)),
                        'email' => array_search('email', array_map('strtolower', $headers)),
                        'phone_number' => array_search('phone_number', array_map('strtolower', $headers)),
                        'photo' => array_search('photo', array_map('strtolower', $headers)),
                        'work' => array_search('work', array_map('strtolower', $headers)),
                        'department' => array_search('department', array_map('strtolower', $headers))
                    ];

                    // Check for mandatory headers
                    if ($header_map['username'] === false || $header_map['password'] === false || $header_map['email'] === false) {
                        $error_message = "CSV must contain 'username', 'password', and 'email' columns.";
                    } else {
                        $stmt_insert_csv = $conn->prepare("INSERT INTO staff (school_id, username, password, email, phone_number, photo, work, department, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                        if ($stmt_insert_csv === FALSE) {
                            error_log("Prepare failed for CSV insert: " . $conn->error);
                            $error_message = "Database error preparing for CSV import.";
                        } else {
                            $conn->autocommit(FALSE); // Disable autocommit for performance

                            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                                $row_count++;
                                // Basic validation and data extraction using header map
                                $csv_username = trim($data[$header_map['username']] ?? '');
                                $csv_password = $data[$header_map['password']] ?? '';
                                $csv_email = trim($data[$header_map['email']] ?? '');
                                $csv_phone_number = trim($data[$header_map['phone_number']] ?? '');
                                $csv_photo = trim($data[$header_map['photo']] ?? '');
                                $csv_work = trim($data[$header_map['work']] ?? '');
                                $csv_department = trim($data[$header_map['department']] ?? '');
                                $csv_status = 'active'; // Always set new staff to active

                                if (empty($csv_username) || empty($csv_password) || empty($csv_email) || !filter_var($csv_email, FILTER_VALIDATE_EMAIL)) {
                                    $failed_count++;
                                    error_log("Skipping CSV row $row_count due to invalid data: " . implode(",", $data));
                                    continue;
                                }

                                // Check if username or email already exists before inserting
                                $sql_check_staff = "SELECT staff_id FROM staff WHERE username = ? OR email = ?";
                                if ($stmt_check_staff = $conn->prepare($sql_check_staff)) {
                                    $stmt_check_staff->bind_param("ss", $csv_username, $csv_email);
                                    $stmt_check_staff->execute();
                                    $stmt_check_staff->store_result();
                                    if ($stmt_check_staff->num_rows > 0) {
                                        $skipped_count++; // Staff already exists
                                        $stmt_check_staff->close();
                                        continue;
                                    }
                                    $stmt_check_staff->close();
                                } else {
                                    error_log("Prepare failed for CSV staff check: " . $conn->error);
                                    $failed_count++;
                                    continue;
                                }

                                $hashed_csv_password = password_hash($csv_password, PASSWORD_DEFAULT);

                                $stmt_insert_csv->bind_param("issssssss", $current_user_school_id, $csv_username, $hashed_csv_password, $csv_email, $csv_phone_number, $csv_photo, $csv_work, $csv_department, $csv_status);

                                if ($stmt_insert_csv->execute()) {
                                    $success_count++;
                                } else {
                                    error_log("Failed to insert CSV row $row_count: " . $stmt_insert_csv->error);
                                    $failed_count++;
                                }
                            }

                            // Commit all changes or rollback on error
                            if ($failed_count == 0 && $error_message === null) {
                                $conn->commit();
                                $success_message = "CSV import complete. Successfully added $success_count staff members, skipped $skipped_count (existing).";
                            } else {
                                $conn->rollback();
                                $error_message = "CSV import completed with errors. Successfully added $success_count staff, skipped $skipped_count (existing), failed $failed_count.";
                            }
                            $stmt_insert_csv->close();
                        }
                        $conn->autocommit(TRUE); // Re-enable autocommit
                    }
                }
                fclose($handle);
            }
        }
    }

    // Fetch all staff members for the current school for display
    $staff_members = [];
    $sql_staff = "SELECT staff_id, username, email, phone_number, photo, work, department, status FROM staff WHERE school_id = ?";
    if ($stmt_staff = $conn->prepare($sql_staff)) {
        $stmt_staff->bind_param("i", $current_user_school_id);
        if ($stmt_staff->execute()) {
            $result_staff = $stmt_staff->get_result();
            while ($row = $result_staff->fetch_assoc()) {
                $staff_members[] = $row;
            }
        } else {
            error_log("Execute failed for staff members query: " . $stmt_staff->error);
        }
        $stmt_staff->close();
    } else {
        error_log("Prepare failed for staff members query: " . $conn->error);
    }

    // Determine role name for display
    $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;
    }

    // Close the connection at the very end
    $conn->close();
} else {
    error_log("Database connection \$conn not available in admin_staff.php");
    $photo = 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD'; // Fallback photo
    $error_message = "Database connection not established.";
}
?>

<!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; ?> Staff 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">
    <style>
        /* Existing styles from style.css should cover most of this */
        /* Additional styles specific to admin_staff.php if needed */
        .staff-management-container {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .staff-action-buttons-container {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            flex-wrap: wrap; /* Allow wrapping on small screens */
            justify-content: center; /* Center the buttons */
        }
        .staff-action-buttons-container .btn {
            flex-grow: 1; /* Allow buttons to expand */
            text-align: center;
            padding: 10px 15px; /* Slightly smaller padding for these main action buttons */
            font-size: 0.95em; /* Slightly smaller font size */
            min-width: unset; /* Override previous min-width */
        }

        /* New container for the print/export buttons, placed within a card */
        .staff-print-export-options {
            display: flex;
            gap: 10px; /* Reduced gap between print/export buttons */
            flex-wrap: wrap;
            justify-content: center; /* Center these buttons too */
            margin-top: 15px; /* Space from the heading */
        }

        .staff-print-export-options .btn {
            padding: 8px 15px; /* Smaller padding for print/export buttons */
            font-size: 0.9em; /* Smaller font size for print/export buttons */
            flex-grow: 0; /* Prevent stretching, let them size content */
            min-width: unset;
        }


        .staff-section-card {
            background-color: var(--card-bg);
            padding: 25px;
            border-radius: 10px;
            box-shadow: var(--shadow-light);
            margin-bottom: 20px;
        }

        .hidden-section {
            display: none;
        }

        .staff-section-card h3 {
            font-size: 22px;
            margin-bottom: 20px;
            color: var(--primary-green);
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        /* Adjust icon size within card headers */
        .staff-section-card h3 .fas,
        .staff-section-card h3 .far {
            font-size: 1.1em; /* Make icons slightly smaller in card headers */
        }


        .staff-section-card form {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .staff-section-card .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 20px;
        }

        .staff-section-card .form-group {
            margin-bottom: 0; /* Override default form-group margin */
        }

        .staff-section-card label {
            font-weight: 600;
            color: #555;
            margin-bottom: 5px;
        }

        .staff-section-card input[type="text"],
        .staff-section-card input[type="password"],
        .staff-section-card input[type="email"],
        .staff-section-card input[type="tel"],
        .staff-section-card input[type="file"],
        .staff-section-card select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        .staff-section-card input[type="file"] {
            padding: 5px; /* Adjust padding for file input */
        }

        .staff-section-card input[type="text"]:focus,
        .staff-section-card input[type="password"]:focus,
        .staff-section-card input[type="email"]:focus,
        .staff-section-card input[type="tel"]:focus,
        .staff-section-card select:focus {
            border-color: var(--light-blue);
            outline: none;
        }

        .staff-section-card .btn-submit {
            background-color: var(--dark-green);
            color: white;
            padding: 12px 25px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 18px;
            font-weight: 500;
            transition: background-color 0.3s ease, transform 0.2s ease;
            margin-top: 10px;
            align-self: flex-start; /* Align button to start in flex column */
        }

        .staff-section-card .btn-submit:hover {
            background-color: #218838;
            transform: translateY(-2px);
        }

        .staff-table-container {
            overflow-x: auto; /* Enable horizontal scrolling for tables on small screens */
        }

        .staff-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .staff-table th, .staff-table td {
            border: 1px solid var(--border-color);
            padding: 12px 15px;
            text-align: left;
            vertical-align: middle;
        }

        .staff-table th {
            background-color: #f8f8f8;
            font-weight: 600;
            color: #555;
        }

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

        .staff-table tbody tr:hover {
            background-color: #f0f0f0;
        }

        .staff-table .staff-photo {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid var(--light-blue);
        }

        .staff-table .actions {
            display: flex;
            gap: 5px;
            flex-wrap: wrap;
        }

        .staff-table .actions .action-btn {
            padding: 8px 12px;
            font-size: 14px;
            border-radius: 5px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        .staff-table .actions .edit-btn { background-color: var(--light-blue); color: white; }
        .staff-table .actions .delete-btn { background-color: #e74c3c; color: white; }
        .staff-table .actions .edit-btn:hover { background-color: #4a90e2; }
        .staff-table .actions .delete-btn:hover { background-color: #c0392b; }

        .print-options { /* This class is now largely redundant with staff-print-export-options */
            display: flex;
            gap: 15px;
            margin-top: 20px;
            flex-wrap: wrap;
        }
        .print-options .btn {
            padding: 10px 20px;
            font-size: 16px;
            min-width: 150px;
            text-align: center;
        }

        /* Message styling */
        .message-container {
            margin-bottom: 20px;
            padding: 15px;
            border-radius: 8px;
            font-weight: 500;
        }

        .message-container.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .message-container.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        /* Fixed Header Styles */
        .header {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1001;
            background: var(--header-bg, #ffffff);
            border-bottom: 1px solid var(--border-color, #e0e0e0);
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        /* Mobile Footer Navigation Styles */
        #mobile-footer-nav {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: var(--header-bg, #ffffff);
            border-top: 1px solid var(--border-color, #e0e0e0);
            display: flex;
            justify-content: space-around;
            padding: 8px 0;
            z-index: 1000;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
        }

        #mobile-footer-nav .nav-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            text-decoration: none;
            color: var(--text-color, #333);
            padding: 8px 12px;
            border-radius: 8px;
            transition: all 0.3s ease;
            min-width: 60px;
        }

        #mobile-footer-nav .nav-item:hover,
        #mobile-footer-nav .nav-item.active {
            background-color: var(--primary-green, #28a745);
            color: white;
        }

        #mobile-footer-nav .nav-item i {
            font-size: 20px;
            margin-bottom: 4px;
        }

        #mobile-footer-nav .nav-item span {
            font-size: 11px;
            font-weight: 500;
        }

        /* Ensure more button is properly styled */
        #mobile-footer-nav .more-btn {
            background: none;
            border: none;
            cursor: pointer;
        }

        #mobile-footer-nav .more-btn:focus {
            outline: none;
        }

        /* More Menu Modal Styles */
        .more-menu-modal {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: var(--card-bg, #ffffff);
            transform: translateY(100%);
            transition: transform 0.3s ease;
            z-index: 1002;
            max-height: 70vh;
            border-radius: 20px 20px 0 0;
            box-shadow: 0 -5px 20px rgba(0,0,0,0.2);
            overflow-y: auto;
            visibility: hidden;
            pointer-events: none;
        }

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

        .more-menu-content {
            padding: 20px;
        }

        .more-menu-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid var(--border-color, #e0e0e0);
        }

        .more-menu-header h3 {
            margin: 0;
            color: var(--primary-green, #28a745);
            font-size: 20px;
        }

        .close-more-menu {
            background: none;
            border: none;
            font-size: 30px;
            color: var(--text-color, #333);
            cursor: pointer;
            padding: 0;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: background-color 0.3s ease;
        }

        .close-more-menu:hover {
            background-color: var(--border-color, #e0e0e0);
        }

        .more-menu-items {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 15px;
        }

        .more-menu-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            text-decoration: none;
            color: var(--text-color, #333);
            padding: 15px 10px;
            border-radius: 12px;
            transition: all 0.3s ease;
            background: var(--background-color, #f8f9fa);
            border: 1px solid var(--border-color, #e0e0e0);
        }

        .more-menu-item:hover,
        .more-menu-item.active {
            background-color: var(--primary-green, #28a745);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
        }

        .more-menu-item.logout-item:hover {
            background-color: #dc3545;
            box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3);
        }

        .more-menu-item i {
            font-size: 24px;
            margin-bottom: 8px;
        }

        .more-menu-item span {
            font-size: 12px;
            font-weight: 500;
            text-align: center;
        }

        /* Overlay for modal */
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 999;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.3s ease, visibility 0.3s ease;
        }

        .overlay.active {
            opacity: 1;
            visibility: visible;
            z-index: 999;
        }

        .overlay.modal-active {
            opacity: 1;
            visibility: visible;
            z-index: 1001;
            background: rgba(0, 0, 0, 0.4);
        }

        /* Main content adjustments for fixed header */
        .main-content {
            padding-top: 80px; /* Account for fixed header */
        }

        .dashboard-content {
            padding: 20px;
        }

        /* Responsive adjustments */
        @media (max-width: 768px) {
            .staff-action-buttons-container,
            .staff-print-export-options {
                flex-direction: column;
                align-items: stretch; /* Stretch buttons to full width */
            }
            .staff-action-buttons-container .btn,
            .staff-print-export-options .btn {
                width: 100%; /* Ensure full width */
                flex-grow: 1;
            }
            .staff-section-card .form-grid {
                grid-template-columns: 1fr; /* Stack form inputs on small screens */
            }
            .staff-table th, .staff-table td {
                padding: 10px; /* Smaller padding for table cells */
                font-size: 14px;
            }
            .staff-table .staff-photo {
                width: 40px;
                height: 40px;
            }
            .staff-table .actions .action-btn {
                padding: 6px 10px;
                font-size: 12px;
            }
            .print-options { /* Still used for the content of the printout card */
                flex-direction: column;
            }
            .print-options .btn {
                width: 100%;
            }

            /* Add top and bottom padding to main content for fixed header and footer */
            .main-content {
                padding-top: 70px; /* Account for fixed header on mobile */
                padding-bottom: 80px; /* Account for fixed footer on mobile */
            }

            .header {
                padding: 10px 15px; /* Reduce header padding on mobile */
            }
        }

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

            .more-menu-modal {
                display: none;
            }

            /* Reset main content padding for desktop */
            .main-content {
                padding-bottom: 20px;
            }
        }

        /* Additional mobile optimizations */
        @media (max-width: 768px) {
            /* Ensure sidebar doesn't interfere with fixed positioning */
            .sidebar.active {
                z-index: 998;
            }

            /* Improve touch targets for mobile */
            #mobile-footer-nav .nav-item {
                min-height: 44px;
                justify-content: center;
            }

            .more-menu-item {
                min-height: 60px;
                touch-action: manipulation;
            }

            /* Prevent zoom on form inputs */
            input[type="text"], 
            input[type="email"], 
            input[type="password"], 
            input[type="tel"], 
            select {
                font-size: 16px;
            }
        }
    </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">
               <H8> DIVINE REPORTS</H8>
            </div>
            <nav>
                <ul>
                    <li><a href="admin_dashboard.php" id="dashboardLink"><i class="fas fa-th-large"></i> Dashboard</a></li>
                    <li><a href="admin_calendar.php" id="calendarLink"><i class="far fa-calendar-alt"></i> Calendar</a></li>
                    <li><a href="admin_user_management.php" id="usersLink"><i class="fas fa-users-cog"></i> Users</a></li>
                    <li><a href="admin_students.php" id="studentsLink"><i class="fas fa-user-graduate"></i> Students</a></li>
                    <li><a href="admin_teachers.php" id="teachersLink"><i class="fas fa-chalkboard-teacher"></i> Teachers</a></li>
                    <li class="active"><a href="admin_staff.php" id="staffLink"><i class="fas fa-users"></i> Staff</a></li>
                    <li class="hidden md:block"><a href="admin_classes.php" id="classesLink"><i class="fas fa-chalkboard"></i> Classes</a></li>
                    <li class="hidden md:block"><a href="admin_subjects.php" id="subjectsLink"><i class="fas fa-book"></i> Subjects</a></li>
                    <li><a href="admin_grades.php" id="gradesLink"><i class="fas fa-star"></i> Grades</a></li>
                    <li class="hidden md:block"><a href="admin_exams.php" id="examsLink"><i class="fas fa-file-alt"></i> Exams</a></li>
                    <li class="hidden md:block"><a href="admin_messages.php" id="messagesLinkSidebar"><i class="fas fa-envelope"></i> Messages</a></li>
                    <li class="hidden md:block"><a href="admin_reports_printouts.php" id="printoutsLink"><i class="fas fa-print"></i> Printouts</a></li>
                    <li class="hidden md:block"><a href="admin_system_settings.php" id="systemSettingsLink"><i class="fas fa-cog"></i> Settings</a></li>
                    <li class="hidden md:block"><a href="logout.php" class="logout-btn" id="logoutLinkSidebar"><i class="fas fa-sign-out-alt"></i> 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="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 staff/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: <?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-users"></i> Staff Management</h2>

                <?php if ($success_message): ?>
                    <div class="message-container success">
                        <?php echo $success_message; ?>
                    </div>
                <?php endif; ?>
                <?php if ($error_message): ?>
                    <div class="message-container error">
                        <?php echo $error_message; ?>
                    </div>
                <?php endif; ?>

                <div class="staff-management-container">
                    <div class="staff-action-buttons-container">
                        <button id="showAddStaffBtn" class="btn btn-primary"><i class="fas fa-user-plus"></i> Add New Staff</button>
                        <button id="showImportCsvBtn" class="btn btn-primary"><i class="fas fa-file-import"></i> Import Staff from CSV</button>
                        <!-- Print and Export buttons moved here, directly visible -->
                        <button class="btn btn-primary" onclick="window.print()" id="printStaffListBtn"><i class="fas fa-print"></i> Print Staff List</button>
                        <a href="export_staff_csv.php" class="btn btn-success" id="exportStaffCsvBtn"><i class="fas fa-file-csv"></i> Export to CSV</a>
                    </div>

                    <!-- Add New Staff Section -->
                    <div class="staff-section-card hidden-section" id="addStaffCard">
                        <h3><i class="fas fa-user-plus"></i> Add New Staff</h3>
                        <form action="admin_staff.php" method="POST" enctype="multipart/form-data">
                            <div class="form-grid">
                                <div class="form-group">
                                    <label for="new_staff_username">Username <span style="color: red;">*</span></label>
                                    <input type="text" id="new_staff_username" name="new_staff_username" required>
                                </div>
                                <div class="form-group">
                                    <label for="new_staff_password">Password <span style="color: red;">*</span></label>
                                    <input type="password" id="new_staff_password" name="new_staff_password" required>
                                </div>
                                <div class="form-group">
                                    <label for="new_staff_email">Email <span style="color: red;">*</span></label>
                                    <input type="email" id="new_staff_email" name="new_staff_email" required>
                                </div>
                                <div class="form-group">
                                    <label for="new_staff_phone_number">Phone Number</label>
                                    <input type="tel" id="new_staff_phone_number" name="new_staff_phone_number">
                                </div>
                                <div class="form-group">
                                    <label for="new_staff_work">Work/Job Title</label>
                                    <input type="text" id="new_staff_work" name="new_staff_work">
                                </div>
                                <div class="form-group">
                                    <label for="new_staff_department">Department</label>
                                    <input type="text" id="new_staff_department" name="new_staff_department">
                                </div>
                                <div class="form-group">
                                    <label for="new_staff_photo">Staff Photo</label>
                                    <input type="file" id="new_staff_photo" name="new_staff_photo" accept="image/*">
                                </div>
                            </div>
                            <button type="submit" name="add_staff" class="btn-submit">Add Staff</button>
                        </form>
                    </div>

                    <!-- Import Staff from CSV Section -->
                    <div class="staff-section-card hidden-section" id="importCsvCard">
                        <h3><i class="fas fa-file-import"></i> Import Staff from CSV</h3>
                        <p>Upload a CSV file with columns: <code>username, password, email, phone_number, photo, work, department</code>.
                           <code>username</code>, <code>password</code>, and <code>email</code> are required. Photos specified in CSV must exist in the server's file system already, relative to your site root.</p>
                        <form action="admin_staff.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-submit">Upload CSV</button>
                        </form>
                    </div>

                    <!-- Current Staff List -->
                    <div class="staff-section-card">
                        <h3><i class="fas fa-users-line"></i> Current Staff Members</h3>
                        <div class="staff-table-container">
                            <?php if (empty($staff_members)): ?>
                                <p id="noStaffFoundMessage">No staff members found for your school.</p>
                            <?php else: ?>
                                <table class="staff-table">
                                    <thead>
                                        <tr>
                                            <th><span>ID</span></th>
                                            <th><span>Photo</span></th>
                                            <th><span>Username</span></th>
                                            <th><span>Email</span></th>
                                            <th><span>Phone</span></th>
                                            <th><span>Work</span></th>
                                            <th><span>Department</span></th>
                                            <th><span>Status</span></th>
                                            <th><span>Actions</span></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($staff_members as $staff): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($staff['staff_id']); ?></td>
                                                <td>
                                                    <img src="<?php echo !empty($staff['photo']) ? htmlspecialchars($staff['photo']) : 'https://via.placeholder.com/50/dddddd/FFFFFF?text=NA'; ?>"
                                                         alt="Staff Photo" class="staff-photo"
                                                         onerror="this.onerror=null;this.src='https://via.placeholder.com/50/dddddd/FFFFFF?text=NA';">
                                                </td>
                                                <td><?php echo htmlspecialchars($staff['username']); ?></td>
                                                <td><?php echo htmlspecialchars($staff['email']); ?></td>
                                                <td><?php echo htmlspecialchars($staff['phone_number']); ?></td>
                                                <td><?php echo htmlspecialchars($staff['work']); ?></td>
                                                <td><?php echo htmlspecialchars($staff['department']); ?></td>
                                                <td><?php echo htmlspecialchars($staff['status']); ?></td>
                                                <td class="actions">
                                                    <a href="edit_staff.php?id=<?php echo $staff['staff_id']; ?>" class="action-btn edit-btn" title="Edit Staff"><i class="fas fa-edit"></i> Edit</a>
                                                    <a href="delete_staff.php?id=<?php echo $staff['staff_id']; ?>" class="action-btn delete-btn" title="Delete Staff" onclick="return confirm('Are you sure you want to delete this staff member?');"><i class="fas fa-trash-alt"></i> Delete</a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Mobile Footer Navigation (visible only on small screens) -->
            <nav id="mobile-footer-nav" class="md:hidden">
                <a href="admin_dashboard.php" class="nav-item" id="mobileDashboardLink">
                    <i class="fas fa-th-large"></i>
                    <span id="mobileDashboardText">Dashboard</span>
                </a>
                <a href="admin_user_management.php" class="nav-item" id="mobileUsersLink">
                    <i class="fas fa-users-cog"></i>
                    <span id="mobileUsersText">Users</span>
                </a>
                <a href="admin_students.php" class="nav-item" id="mobileStudentsLink">
                    <i class="fas fa-user-graduate"></i>
                    <span id="mobileStudentsText">Students</span>
                </a>
                <a href="admin_messages.php" class="nav-item" id="mobileMessagesLink">
                    <i class="fas fa-envelope"></i>
                    <span id="mobileMessagesText">Messages</span>
                </a>
                <button class="nav-item more-btn" id="moreMenuButton">
                    <i class="fas fa-ellipsis-h"></i>
                    <span id="mobileMoreText">More</span>
                </button>
            </nav>
        </div>
    </div>

    <!-- More Menu Modal (slide up from bottom on mobile) -->
    <div id="more-menu-modal" class="more-menu-modal">
        <div class="more-menu-content">
            <div class="more-menu-header">
                <h3 id="moreMenuTitle">More Options</h3>
                <button class="close-more-menu" id="closeMoreMenu">&times;</button>
            </div>
            <div class="more-menu-items">
                <a href="admin_teachers.php" class="more-menu-item" id="moreTeachersLink">
                    <i class="fas fa-chalkboard-teacher"></i>
                    <span id="moreTeachersText">Teachers</span>
                </a>
                <a href="admin_staff.php" class="more-menu-item active" id="moreStaffLink">
                    <i class="fas fa-users"></i>
                    <span id="moreStaffText">Staff</span>
                </a>
                <a href="admin_classes.php" class="more-menu-item" id="moreClassesLink">
                    <i class="fas fa-chalkboard"></i>
                    <span id="moreClassesText">Classes</span>
                </a>
                <a href="admin_subjects.php" class="more-menu-item" id="moreSubjectsLink">
                    <i class="fas fa-book"></i>
                    <span id="moreSubjectsText">Subjects</span>
                </a>
                <a href="admin_grades.php" class="more-menu-item" id="moreGradesLink">
                    <i class="fas fa-star"></i>
                    <span id="moreGradesText">Grades</span>
                </a>
                <a href="admin_exams.php" class="more-menu-item" id="moreExamsLink">
                    <i class="fas fa-file-alt"></i>
                    <span id="moreExamsText">Exams</span>
                </a>
                <a href="admin_reports_printouts.php" class="more-menu-item" id="morePrintoutsLink">
                    <i class="fas fa-print"></i>
                    <span id="morePrintoutsText">Printouts</span>
                </a>
                <a href="admin_system_settings.php" class="more-menu-item" id="moreSystemSettingsLink">
                    <i class="fas fa-cog"></i>
                    <span id="moreSystemSettingsText">Settings</span>
                </a>
                <a href="logout.php" class="more-menu-item logout-item" id="moreLogoutLink">
                    <i class="fas fa-sign-out-alt"></i>
                    <span id="moreLogoutText">Logout</span>
                </a>
            </div>
        </div>
    </div>

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

    <script>
        const schoolNameForJs = "<?php echo $school_name_for_js; ?>";

        const translations = {
            en: {
                dashboard: "Dashboard",
                calendar: "Calendar",
                users: "Users",
                students: "Students",
                teachers: "Teachers",
                staff: "Staff", // New translation for staff link
                classes: "Classes",
                subjects: "Subjects",
                exams: "Exams",
                grades: "Grades",
                messages: "Messages",
                printouts: "Printouts",
                systemSettings: "Settings",
                logout: "Logout",
                searchPlaceholder: "Search staff/data",
                welcomePrefix: "Welcome ",
                welcomeSuffix: "!",
                manageSchoolOperations: `Manage all aspects of ${schoolNameForJs} school operations.`,
                profileText: "Profile",
                settingsText: "Settings",
                logoutText: "Logout",
                staffManagement: "Staff Management",
                addNewStaff: "Add New Staff",
                importStaffCSV: "Import Staff from CSV",
                currentStaffMembers: "Current Staff Members",
                printExportStaff: "Print / Export Staff List", // This might be unused now
                username: "Username",
                password: "Password",
                email: "Email",
                phoneNumber: "Phone Number",
                workTitle: "Work/Job Title",
                department: "Department",
                staffPhoto: "Staff Photo",
                addStaff: "Add Staff",
                selectCSVFile: "Select CSV File",
                uploadCSV: "Upload CSV",
                id: "ID",
                photo: "Photo",
                phone: "Phone",
                work: "Work",
                status: "Status",
                actions: "Actions",
                edit: "Edit",
                delete: "Delete",
                printStaffList: "Print Staff List",
                exportToCSV: "Export to CSV",
                noStaffFound: "No staff members found for your school.",
                csvHeadersHint: "Upload a CSV file with columns: username, password, email, phone_number, photo, work, department. username, password, and email are required. Photos specified in CSV must exist in the server's file system already, relative to your site root.",
                addNewStaffBtn: "Add New Staff",
                hideAddNewStaffBtn: "Hide Add New Staff",
                importCsvBtn: "Import Staff from CSV",
                hideImportCsvBtn: "Hide Import Staff from CSV",
                staffActionsAndPrintouts: "Staff Actions & Printouts", // New translation for card title
                moreOptions: "More Options",
                more: "More"
            },
            lg: {
                dashboard: "Akawungeezi",
                calendar: "Kkalenda",
                users: "Abakozesa",
                students: "Abayizi",
                teachers: "Basomesa",
                staff: "Abakozi", // New translation
                classes: "Ebibiina",
                subjects: "Ebyenjigiriza",
                exams: "Ebigezo",
                grades: "Amanota",
                messages: "Obubaka",
                printouts: "Ebyafulumizibwa",
                systemSettings: "Enteekateeka z'Enkola",
                logout: "Ggalawo",
                searchPlaceholder: "Noonya abakozi/data",
                welcomePrefix: "Tukwanirizza ",
                welcomeSuffix: "!",
                manageSchoolOperations: `Fuga ebya ${schoolNameForJs} byonna eby'omuddozi gwa somero.`,
                profileText: "Purofayiro",
                settingsText: "Enteekateeka",
                logoutText: "Ggalawo",
                staffManagement: "Okufuga abakozi",
                addNewStaff: "Yongeramu omukozi omupya",
                importStaffCSV: "Yingiza abakozi okuva mu CSV",
                currentStaffMembers: "Abakozi abaliwo kati",
                printExportStaff: "Printa / Fuula CSV y'abakozi",
                username: "Erinnya ly'omukozi",
                password: "Ekigambo ky'ekyama",
                email: "Email",
                phoneNumber: "Esimu",
                workTitle: "Omulimu/Ekifo",
                department: "Ekitongole",
                staffPhoto: "Ekifaananyi ky'omukozi",
                addStaff: "Yongeramu omukozi",
                selectCSVFile: "Londa fayiro ya CSV",
                uploadCSV: "Teeka fayiro ya CSV",
                id: "NN",
                photo: "Ekifaananyi",
                phone: "Esimu",
                work: "Omulimu",
                status: "Ebyo ebikwata",
                actions: "Ebikolebwa",
                edit: "Kyusa",
                delete: "Ggyawo",
                printStaffList: "Printa olukalala lw'abakozi",
                exportToCSV: "Fuula CSV",
                noStaffFound: "Tewali bakozi abazuliddwa ku ssomero lyo.",
                csvHeadersHint: "Teeka fayiro ya CSV nga erimu emitwe: username, password, email, phone_number, photo, work, department. username, password, ne email byetaagisa. Ebifaananyi ebiragiddwa mu CSV birina okuba nga bibaawo mu fayiro za server, okuva ku mukono gwa sayiti yo.",
                addNewStaffBtn: "Yongeramu omukozi omupya",
                hideAddNewStaffBtn: "Kweka omukozi omupya",
                importCsvBtn: "Yingiza abakozi okuva mu CSV",
                hideImportCsvBtn: "Kweka abakozi okuva mu CSV",
                staffActionsAndPrintouts: "Ebikolebwa ku bakozi & Ebyafulumizibwa",
                moreOptions: "Obulondozzi Obulala",
                more: "Endala"
            },
            sw: {
                dashboard: "Dashibodi",
                calendar: "Kalenda",
                users: "Watumiaji",
                students: "Wanafunzi",
                teachers: "Walimu",
                staff: "Wafanyakazi", // New translation
                classes: "Madarasa",
                subjects: "Masomo",
                exams: "Mitihani",
                grades: "Alama",
                messages: "Ujumbe",
                printouts: "Machapisho",
                systemSettings: "Mipangilio ya Mfumo",
                logout: "Ondoka",
                searchPlaceholder: "Tafuta wafanyakazi/data",
                welcomePrefix: "Karibu ",
                welcomeSuffix: "!",
                manageSchoolOperations: `Dhibiti masuala yote ya shule ya ${schoolNameForJs}.`,
                profileText: "Wasifu",
                settingsText: "Mipangilio",
                logoutText: "Ondoka",
                staffManagement: "Usimamizi wa Wafanyakazi",
                addNewStaff: "Ongeza Mfanyakazi Mpya",
                importStaffCSV: "Ingiza Wafanyakazi kutoka CSV",
                currentStaffMembers: "Wafanyakazi wa Sasa",
                printExportStaff: "Chapisha / Hamisha Orodha ya Wafanyakazi",
                username: "Jina la mtumiaji",
                password: "Nenosiri",
                email: "Barua pepe",
                phoneNumber: "Namba ya Simu",
                workTitle: "Kazi/Kichwa cha Kazi",
                department: "Idara",
                staffPhoto: "Picha ya Mfanyakazi",
                addStaff: "Ongeza Mfanyakazi",
                selectCSVFile: "Chagua Faili ya CSV",
                uploadCSV: "Pakia CSV",
                id: "Kitambulisho",
                photo: "Picha",
                phone: "Simu",
                work: "Kazi",
                status: "Hali",
                actions: "Vitendo",
                edit: "Hariri",
                delete: "Futa",
                printStaffList: "Chapisha Orodha ya Wafanyakazi",
                exportToCSV: "Hamisha kwa CSV",
                noStaffFound: "Hakuna wafanyakazi waliopatikana kwa shule yako.",
                csvHeadersHint: "Pakia faili ya CSV yenye safu wima: username, password, email, phone_number, photo, work, department. username, password, na email zinahitajika. Picha zilizobainishwa kwenye CSV lazima ziwe tayari zipo kwenye mfumo wa faili wa seva, kulingana na saraka kuu ya tovuti yako.",
                addNewStaffBtn: "Ongeza Mfanyakazi Mpya",
                hideAddNewStaffBtn: "Ficha Mfanyakazi Mpya",
                importCsvBtn: "Ingiza Wafanyakazi kutoka CSV",
                hideImportCsvBtn: "Ficha Wafanyakazi kutoka CSV",
                staffActionsAndPrintouts: "Vitendo vya Wafanyakazi & Machapisho",
                moreOptions: "Chaguo Zaidi",
                more: "Zaidi"
            }
        };

        let currentLanguage = localStorage.getItem('language') || 'en';
        const menuToggle = document.getElementById('menuToggle');
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('overlay');
        const languageSelect = document.getElementById('languageSelect');
        const moreMenuModal = document.getElementById('more-menu-modal');
        const moreMenuButton = document.getElementById('moreMenuButton');
        const closeMoreMenu = document.getElementById('closeMoreMenu');

        function updateTranslations() {
            const t = translations[currentLanguage];

            // Update sidebar links
            document.getElementById('dashboardLink').querySelector('i').nextSibling.textContent = " " + t.dashboard;
            document.getElementById('calendarLink').querySelector('i').nextSibling.textContent = " " + t.calendar;
            document.getElementById('usersLink').querySelector('i').nextSibling.textContent = " " + t.users;
            document.getElementById('studentsLink').querySelector('i').nextSibling.textContent = " " + t.students;
            document.getElementById('teachersLink').querySelector('i').nextSibling.textContent = " " + t.teachers;
            document.getElementById('staffLink').querySelector('i').nextSibling.textContent = " " + t.staff; // New staff link
            if (document.getElementById('classesLink')) document.getElementById('classesLink').querySelector('i').nextSibling.textContent = " " + t.classes;
            if (document.getElementById('subjectsLink')) document.getElementById('subjectsLink').querySelector('i').nextSibling.textContent = " " + t.subjects;
            if (document.getElementById('gradesLink')) document.getElementById('gradesLink').querySelector('i').nextSibling.textContent = " " + t.grades;
            if (document.getElementById('examsLink')) document.getElementById('examsLink').querySelector('i').nextSibling.textContent = " " + t.exams;
            if (document.getElementById('messagesLinkSidebar')) document.getElementById('messagesLinkSidebar').querySelector('i').nextSibling.textContent = " " + t.messages;
            if (document.getElementById('printoutsLink')) document.getElementById('printoutsLink').querySelector('i').nextSibling.textContent = " " + t.printouts;
            if (document.getElementById('systemSettingsLink')) document.getElementById('systemSettingsLink').querySelector('i').nextSibling.textContent = " " + t.systemSettings;
            if (document.getElementById('logoutLinkSidebar')) document.getElementById('logoutLinkSidebar').querySelector('i').nextSibling.textContent = " " + t.logout;

            // Update mobile footer navigation
            document.getElementById('mobileDashboardText').textContent = t.dashboard;
            document.getElementById('mobileUsersText').textContent = t.users;
            document.getElementById('mobileStudentsText').textContent = t.students;
            document.getElementById('mobileMessagesText').textContent = t.messages;
            document.getElementById('mobileMoreText').textContent = t.more;

            // Update more menu items
            document.getElementById('moreMenuTitle').textContent = t.moreOptions;
            document.getElementById('moreTeachersText').textContent = t.teachers;
            document.getElementById('moreStaffText').textContent = t.staff;
            document.getElementById('moreClassesText').textContent = t.classes;
            document.getElementById('moreSubjectsText').textContent = t.subjects;
            document.getElementById('moreGradesText').textContent = t.grades;
            document.getElementById('moreExamsText').textContent = t.exams;
            document.getElementById('morePrintoutsText').textContent = t.printouts;
            document.getElementById('moreSystemSettingsText').textContent = t.systemSettings;
            document.getElementById('moreLogoutText').textContent = t.logout;

            // Update header elements
            document.getElementById('searchPlaceholder').placeholder = t.searchPlaceholder;
            const staffManagementHeading = document.querySelector('.dashboard-content h2');
            if (staffManagementHeading) {
                staffManagementHeading.innerHTML = `<i class="fas fa-users"></i> ${t.staffManagement}`;
            }

            // Update Add New Staff form labels
            const newStaffUsernameLabel = document.querySelector('label[for="new_staff_username"]');
            if (newStaffUsernameLabel) newStaffUsernameLabel.innerHTML = `${t.username} <span style="color: red;">*</span>`;
            const newStaffPasswordLabel = document.querySelector('label[for="new_staff_password"]');
            if (newStaffPasswordLabel) newStaffPasswordLabel.innerHTML = `${t.password} <span style="color: red;">*</span>`;
            const newStaffEmailLabel = document.querySelector('label[for="new_staff_email"]');
            if (newStaffEmailLabel) newStaffEmailLabel.innerHTML = `${t.email} <span style="color: red;">*</span>`;
            const newStaffPhoneNumberLabel = document.querySelector('label[for="new_staff_phone_number"]');
            if (newStaffPhoneNumberLabel) newStaffPhoneNumberLabel.textContent = t.phoneNumber;
            const newStaffWorkLabel = document.querySelector('label[for="new_staff_work"]');
            if (newStaffWorkLabel) newStaffWorkLabel.textContent = t.workTitle;
            const newStaffDepartmentLabel = document.querySelector('label[for="new_staff_department"]');
            if (newStaffDepartmentLabel) newStaffDepartmentLabel.textContent = t.department;
            const newStaffPhotoLabel = document.querySelector('label[for="new_staff_photo"]');
            if (newStaffPhotoLabel) newStaffPhotoLabel.textContent = t.staffPhoto;
            const addStaffButton = document.querySelector('button[name="add_staff"]');
            if (addStaffButton) addStaffButton.textContent = t.addStaff;

            // Update Import CSV section
            const importCsvCardP = document.querySelector('#importCsvCard p');
            if (importCsvCardP) importCsvCardP.innerHTML = t.csvHeadersHint;
            const csvFileLabel = document.querySelector('label[for="csv_file"]');
            if (csvFileLabel) csvFileLabel.textContent = t.selectCSVFile;
            const uploadCsvButton = document.querySelector('button[name="upload_csv"]');
            if (uploadCsvButton) uploadCsvButton.textContent = t.uploadCSV;

            // Update Staff List table headers
            const thElements = document.querySelectorAll('.staff-table th span'); // Using span for consistency
            if (thElements.length > 0) {
                thElements[0].textContent = t.id;
                thElements[1].textContent = t.photo;
                thElements[2].textContent = t.username;
                thElements[3].textContent = t.email;
                thElements[4].textContent = t.phone;
                thElements[5].textContent = t.work;
                thElements[6].textContent = t.department;
                thElements[7].textContent = t.status;
                thElements[8].textContent = t.actions;
            }

            // Update "No staff members found" message
            const noStaffMessage = document.getElementById('noStaffFoundMessage');
            if (noStaffMessage) {
                noStaffMessage.textContent = t.noStaffFound;
            }

            // Update Action buttons (Edit/Delete)
            document.querySelectorAll('.action-btn.edit-btn').forEach(btn => {
                const icon = btn.querySelector('i');
                btn.innerHTML = '';
                if (icon) btn.appendChild(icon);
                btn.appendChild(document.createTextNode(` ${t.edit}`));
            });
            document.querySelectorAll('.action-btn.delete-btn').forEach(btn => {
                const icon = btn.querySelector('i');
                btn.innerHTML = '';
                if (icon) btn.appendChild(icon);
                btn.appendChild(document.createTextNode(` ${t.delete}`));
            });

            // Update print/export buttons - these are now in staff-action-buttons-container
            const printStaffListBtn = document.getElementById('printStaffListBtn');
            if (printStaffListBtn) printStaffListBtn.innerHTML = `<i class="fas fa-print"></i> ${t.printStaffList}`;
            const exportStaffCsvBtn = document.getElementById('exportStaffCsvBtn');
            if (exportStaffCsvBtn) exportStaffCsvBtn.innerHTML = `<i class="fas fa-file-csv"></i> ${t.exportToCSV}`;

            // Update toggle button texts based on current state
            const addStaffCard = document.getElementById('addStaffCard');
            const showAddStaffBtn = document.getElementById('showAddStaffBtn');
            if (showAddStaffBtn) {
                showAddStaffBtn.innerHTML = `<i class="fas fa-user-plus"></i> ${addStaffCard.classList.contains('hidden-section') ? t.addNewStaffBtn : t.hideAddNewStaffBtn}`;
            }

            const importCsvCard = document.getElementById('importCsvCard');
            const showImportCsvBtn = document.getElementById('showImportCsvBtn');
            if (showImportCsvBtn) {
                showImportCsvBtn.innerHTML = `<i class="fas fa-file-import"></i> ${importCsvCard.classList.contains('hidden-section') ? t.importCsvBtn : t.hideImportCsvBtn}`;
            }

            // Update card titles for dynamic sections
            const addNewStaffCardTitle = document.querySelector('#addStaffCard h3');
            if (addNewStaffCardTitle) addNewStaffCardTitle.innerHTML = `<i class="fas fa-user-plus"></i> ${t.addNewStaff}`;

            const importCsvCardTitle = document.querySelector('#importCsvCard h3');
            if (importCsvCardTitle) importCsvCardTitle.innerHTML = `<i class="fas fa-file-import"></i> ${t.importStaffCSV}`;
        }

        function openMoreMenu() {
            moreMenuModal.classList.add('active');
            overlay.classList.add('modal-active');
            // Prevent body scroll when modal is open
            document.body.style.overflow = 'hidden';
        }

        function closeMoreMenuModal() {
            moreMenuModal.classList.remove('active');
            overlay.classList.remove('modal-active');
            // Restore body scroll
            document.body.style.overflow = '';
        }

        document.addEventListener('DOMContentLoaded', () => {
            // Set language selector to current language
            languageSelect.value = currentLanguage;
            updateTranslations();

            const showAddStaffBtn = document.getElementById('showAddStaffBtn');
            const showImportCsvBtn = document.getElementById('showImportCsvBtn');
            const addStaffCard = document.getElementById('addStaffCard');
            const importCsvCard = document.getElementById('importCsvCard');

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

            overlay.addEventListener('click', () => {
                if (overlay.classList.contains('modal-active')) {
                    closeMoreMenuModal();
                } else {
                    sidebar.classList.remove('active');
                    overlay.classList.remove('active');
                    document.getElementById('dashboardContainer').classList.remove('sidebar-open');
                }
            });

            languageSelect.addEventListener('change', (event) => {
                currentLanguage = event.target.value;
                localStorage.setItem('language', currentLanguage);
                updateTranslations();
            });

            // More menu functionality
            if (moreMenuButton) {
                moreMenuButton.addEventListener('click', (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    openMoreMenu();
                });
            }

            if (closeMoreMenu) {
                closeMoreMenu.addEventListener('click', (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    closeMoreMenuModal();
                });
            }

            // Close modal when clicking outside content area
            if (moreMenuModal) {
                moreMenuModal.addEventListener('click', (e) => {
                    if (e.target === moreMenuModal) {
                        closeMoreMenuModal();
                    }
                });
            }

            // Prevent modal content clicks from closing the modal
            const moreMenuContent = document.querySelector('.more-menu-content');
            if (moreMenuContent) {
                moreMenuContent.addEventListener('click', (e) => {
                    e.stopPropagation();
                });
            }

            // Event listeners for new toggle buttons
            showAddStaffBtn.addEventListener('click', () => {
                addStaffCard.classList.toggle('hidden-section');
                if (!addStaffCard.classList.contains('hidden-section')) {
                    // If showing Add Staff, ensure Import CSV is hidden
                    importCsvCard.classList.add('hidden-section');
                }
                updateTranslations(); // Update button text and possibly other elements
            });

            showImportCsvBtn.addEventListener('click', () => {
                importCsvCard.classList.toggle('hidden-section');
                if (!importCsvCard.classList.contains('hidden-section')) {
                    // If showing Import CSV, ensure Add Staff is hidden
                    addStaffCard.classList.add('hidden-section');
                }
                updateTranslations(); // Update button text and possibly other elements
            });
        });
    </script>
</body>
</html>