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

// Define role constants
if (!defined('ROLE_ADMIN')) define('ROLE_ADMIN', 2);

// Only allow access if logged in as an Admin
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== ROLE_ADMIN || !isset($_SESSION["school_id"])) {
    header("location: login.php");
    exit;
}

$current_user_school_id = $_SESSION["school_id"];
$staff_id = $_GET['id'] ?? null; // Get staff_id from URL

$staff = null; // Initialize staff data
$success_message = $error_message = null;

// Ensure $conn is available from config.php
if (isset($conn) && $conn instanceof mysqli) {
    // Fetch School Name and Logo (for header display)
    $school_name = "School Name Not Found";
    $school_logo_path = "images/default_school_logo.png";
    $sql_school = "SELECT school_name, logo FROM schools WHERE school_id = ?";
    if ($stmt_school = $conn->prepare($sql_school)) {
        $stmt_school->bind_param("i", $current_user_school_id);
        if ($stmt_school->execute()) {
            $stmt_school->bind_result($school_name_db, $school_logo_db);
            if ($stmt_school->fetch()) {
                $school_name = htmlspecialchars($school_name_db);
                $school_logo_path = !empty($school_logo_db) ? htmlspecialchars($school_logo_db) : 'images/default_school_logo.png';
            }
        }
        $stmt_school->close();
    }

    // --- Handle GET request: Fetch staff data for pre-filling the form ---
    if ($staff_id !== null) {
        $sql = "SELECT staff_id, username, email, phone_number, photo, work, department, status FROM staff WHERE staff_id = ? AND school_id = ?";
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("ii", $staff_id, $current_user_school_id);
            if ($stmt->execute()) {
                $result = $stmt->get_result();
                if ($result->num_rows == 1) {
                    $staff = $result->fetch_assoc();
                } else {
                    $error_message = "Staff member not found or you don't have permission to edit them.";
                    $staff_id = null; // Invalidate staff_id if not found
                }
            } else {
                error_log("Execute failed for staff fetch: " . $stmt->error);
                $error_message = "Database error fetching staff details.";
            }
            $stmt->close();
        } else {
            error_log("Prepare failed for staff fetch: " . $conn->error);
            $error_message = "Database error. Please try again.";
        }
    } else {
        $error_message = "No staff ID provided for editing.";
    }

    // --- Handle POST request: Update staff data ---
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_staff_id'])) {
        $staff_id_to_update = $_POST['update_staff_id'];
        $updated_username = trim($_POST['username']);
        $updated_email = trim($_POST['email']);
        $updated_phone_number = trim($_POST['phone_number'] ?? '');
        $updated_work = trim($_POST['work'] ?? '');
        $updated_department = trim($_POST['department'] ?? '');
        $updated_status = trim($_POST['status'] ?? 'active');
        $new_password = $_POST['password'] ?? ''; // Only update if provided

        $upload_dir = 'uploads/staff_photos/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        $photo_path = $_POST['existing_photo'] ?? ''; // Keep existing photo by default

        // Validate basic inputs
        if (empty($updated_username) || empty($updated_email)) {
            $error_message = "Username and Email are required.";
        } elseif (!filter_var($updated_email, FILTER_VALIDATE_EMAIL)) {
            $error_message = "Invalid email format.";
        } else {
            // Check for duplicate username/email (excluding current staff member)
            $sql_check_duplicate = "SELECT staff_id FROM staff WHERE (username = ? OR email = ?) AND staff_id != ? AND school_id = ?";
            if ($stmt_check = $conn->prepare($sql_check_duplicate)) {
                $stmt_check->bind_param("ssii", $updated_username, $updated_email, $staff_id_to_update, $current_user_school_id);
                $stmt_check->execute();
                $stmt_check->store_result();
                if ($stmt_check->num_rows > 0) {
                    $error_message = "Username or Email already exists for another staff member.";
                }
                $stmt_check->close();
            } else {
                error_log("Prepare failed for duplicate check: " . $conn->error);
                $error_message = "Database error. Please try again.";
            }

            if ($error_message === null) {
                // Handle photo upload
                if (isset($_FILES['photo']) && $_FILES['photo']['error'] == UPLOAD_ERR_OK) {
                    $file_tmp_name = $_FILES['photo']['tmp_name'];
                    $file_name = basename($_FILES['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)) {
                            $photo_path = $destination;
                            // Optionally, delete old photo if it's not default
                            if (!empty($_POST['existing_photo']) && file_exists($_POST['existing_photo']) && $_POST['existing_photo'] !== 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD') {
                                unlink($_POST['existing_photo']);
                            }
                        } else {
                            $error_message = "Failed to upload new photo.";
                        }
                    } else {
                        $error_message = "Invalid file type for photo. Only JPG, JPEG, PNG, GIF are allowed.";
                    }
                }
            }

            if ($error_message === null) {
                // Prepare update statement
                $sql_update = "UPDATE staff SET username = ?, email = ?, phone_number = ?, photo = ?, work = ?, department = ?, status = ?";
                $params = [$updated_username, $updated_email, $updated_phone_number, $photo_path, $updated_work, $updated_department, $updated_status];
                $types = "sssssss";

                if (!empty($new_password)) {
                    $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                    $sql_update .= ", password = ?";
                    $params[] = $hashed_password;
                    $types .= "s";
                }
                $sql_update .= " WHERE staff_id = ? AND school_id = ?";
                $params[] = $staff_id_to_update;
                $params[] = $current_user_school_id;
                $types .= "ii";

                if ($stmt_update = $conn->prepare($sql_update)) {
                    $stmt_update->bind_param($types, ...$params);
                    if ($stmt_update->execute()) {
                        $success_message = "Staff member '{$updated_username}' updated successfully!";
                        // Re-fetch updated data to reflect changes on the form
                        $sql_re_fetch = "SELECT staff_id, username, email, phone_number, photo, work, department, status FROM staff WHERE staff_id = ? AND school_id = ?";
                        if ($stmt_re_fetch = $conn->prepare($sql_re_fetch)) {
                            $stmt_re_fetch->bind_param("ii", $staff_id_to_update, $current_user_school_id);
                            $stmt_re_fetch->execute();
                            $result_re_fetch = $stmt_re_fetch->get_result();
                            $staff = $result_re_fetch->fetch_assoc();
                            $stmt_re_fetch->close();
                        }
                    } else {
                        error_log("Execute failed for staff update: " . $stmt_update->error);
                        $error_message = "Error: Could not update staff member. " . $stmt_update->error;
                    }
                    $stmt_update->close();
                } else {
                    error_log("Prepare failed for staff update: " . $conn->error);
                    $error_message = "Database error. Please try again.";
                }
            }
        }
    }

    // Determine role name for display
    $user_role_code = $_SESSION["role"];
    $role_name = "Unknown";
    switch ($user_role_code) {
        case 1: $role_name = "Super Admin"; break;
        case 2: $role_name = "Admin";       break;
        case 3: $role_name = "Teacher";     break;
        case 4: $role_name = "Student";     break;
        case 5: $role_name = "Parent";      break;
        case 6: $role_name = "Staff";       break;
    }

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

<!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; ?> Edit Staff - <?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>
        /* Specific styles for edit_staff.php */
        .edit-staff-container {
            max-width: 800px;
            margin: 20px auto;
            background-color: var(--card-bg);
            padding: 30px;
            border-radius: 10px;
            box-shadow: var(--shadow-light);
        }

        .edit-staff-container h2 {
            font-size: 2em;
            color: var(--primary-green);
            margin-bottom: 25px;
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

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

        .edit-staff-container .form-group {
            margin-bottom: 0;
        }

        .edit-staff-container label {
            font-weight: 600;
            color: #555;
            margin-bottom: 8px;
            display: block;
        }

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

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

        .edit-staff-container input[type="file"] {
            padding: 5px; /* Adjust padding for file input */
            width: 100%;
            border: 1px solid #ccc; /* Add border for consistency */
            border-radius: 5px;
        }

        .edit-staff-container .current-photo-preview {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-top: 10px;
        }

        .edit-staff-container .current-photo-preview img {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
            border: 3px solid var(--light-blue);
        }

        .edit-staff-container .button-group {
            display: flex;
            gap: 15px;
            justify-content: flex-start;
            margin-top: 20px;
        }

        .edit-staff-container .btn {
            padding: 12px 25px;
            font-size: 1.05em;
            font-weight: 500;
            border-radius: 8px; /* Slightly more rounded */
            box-shadow: 0 4px 6px rgba(0,0,0,0.1); /* Subtle shadow */
            transition: all 0.3s ease;
        }

        .edit-staff-container .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0,0,0,0.15); /* Stronger shadow on hover */
        }

        .edit-staff-container .btn-primary {
            background-color: var(--primary-green);
        }
        .edit-staff-container .btn-primary:hover {
            background-color: #241d34; /* Slightly darker */
        }

        .edit-staff-container .btn-cancel {
            background-color: #dc3545; /* Bootstrap danger red */
        }
        .edit-staff-container .btn-cancel:hover {
            background-color: #c82333;
        }


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

        /* Responsive adjustments */
        @media (max-width: 768px) {
            .edit-staff-container {
                padding: 20px;
                margin: 15px;
            }
            .edit-staff-container h2 {
                font-size: 1.6em;
            }
            .edit-staff-container .form-grid {
                grid-template-columns: 1fr;
            }
            .edit-staff-container .button-group {
                flex-direction: column;
                gap: 10px;
            }
            .edit-staff-container .btn {
                width: 100%;
            }
        }
    </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 $_SESSION['photo'] ?? 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD'; ?>" alt="User Photo">
                        <div>
                            <div class="user-name"><?php echo htmlspecialchars($_SESSION['username'] ?? 'Admin'); ?></div>
                            <div class="user-email">Logged in as: Admin</div>
                        </div>
                        <i class="fas fa-chevron-down"></i>
                    </div>
                </header>

            <div class="dashboard-content">
                <div class="edit-staff-container">
                    <h2><i class="fas fa-user-edit"></i> Edit Staff: <?php echo htmlspecialchars($staff['username'] ?? 'N/A'); ?></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; ?>

                    <?php if ($staff): ?>
                    <form action="edit_staff.php?id=<?php echo htmlspecialchars($staff['staff_id']); ?>" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="update_staff_id" value="<?php echo htmlspecialchars($staff['staff_id']); ?>">
                        <input type="hidden" name="existing_photo" value="<?php echo htmlspecialchars($staff['photo']); ?>">

                        <div class="form-grid">
                            <div class="form-group">
                                <label for="username">Username</label>
                                <input type="text" id="username" name="username" value="<?php echo htmlspecialchars($staff['username']); ?>" required>
                            </div>
                            <div class="form-group">
                                <label for="email">Email</label>
                                <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($staff['email']); ?>" required>
                            </div>
                            <div class="form-group">
                                <label for="phone_number">Phone Number</label>
                                <input type="tel" id="phone_number" name="phone_number" value="<?php echo htmlspecialchars($staff['phone_number']); ?>">
                            </div>
                            <div class="form-group">
                                <label for="work">Work/Job Title</label>
                                <input type="text" id="work" name="work" value="<?php echo htmlspecialchars($staff['work']); ?>">
                            </div>
                            <div class="form-group">
                                <label for="department">Department</label>
                                <input type="text" id="department" name="department" value="<?php echo htmlspecialchars($staff['department']); ?>">
                            </div>
                            <div class="form-group">
                                <label for="status">Status</label>
                                <select id="status" name="status">
                                    <option value="active" <?php if ($staff['status'] == 'active') echo 'selected'; ?>>Active</option>
                                    <option value="inactive" <?php if ($staff['status'] == 'inactive') echo 'selected'; ?>>Inactive</option>
                                    <option value="leave" <?php if ($staff['status'] == 'leave') echo 'selected'; ?>>On Leave</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="photo">Staff Photo</label>
                                <input type="file" id="photo" name="photo" accept="image/*">
                                <div class="current-photo-preview">
                                    <img src="<?php echo !empty($staff['photo']) ? htmlspecialchars($staff['photo']) : 'https://via.placeholder.com/80/cccccc/FFFFFF?text=NA'; ?>"
                                         alt="Current Staff Photo"
                                         onerror="this.onerror=null;this.src='https://via.placeholder.com/80/cccccc/FFFFFF?text=NA';">
                                    <span>Current Photo</span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="password">New Password (leave blank to keep current)</label>
                                <input type="password" id="password" name="password">
                                <small>Enter a new password only if you wish to change it.</small>
                            </div>
                        </div>

                        <div class="button-group">
                            <button type="submit" class="btn btn-primary">Update Staff</button>
                            <a href="admin_staff.php" class="btn btn-cancel">Cancel</a>
                        </div>
                    </form>
                    <?php else: ?>
                        <p>No staff member details available. Please go back to the <a href="admin_staff.php">Staff Management</a> page.</p>
                    <?php endif; ?>
                </div>
            </div>

            <footer class="mobile-footer">
                <nav>
                    <ul>
                        <li><a href="admin_profile.php" id="profileLinkFooter"><i class="fas fa-user-circle"></i> <span id="profileTextFooter">Profile</span></a></li>
                        <li><a href="admin_settings.php" id="settingsLinkFooter"><i class="fas fa-cog"></i> <span id="settingsTextFooter">Settings</span></a></li>
                        <li><a href="logout.php" id="logoutLinkFooter"><i class="fas fa-sign-out-alt"></i> <span id="logoutTextFooter">Logout</span></a></li>
                    </ul>
                </nav>
            </footer>
        </div>
    </div>

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

    <script>
        // Note: Translations and menu toggle logic are similar to admin_staff.php
        // You might consider centralizing common JS for all admin pages.
        const schoolNameForJs = "<?php echo addslashes($school_name); ?>"; // Ensure this matches php variable

        const translations = {
            en: {
                dashboard: "Dashboard",
                calendar: "Calendar",
                users: "Users",
                students: "Students",
                teachers: "Teachers",
                staff: "Staff",
                classes: "Classes",
                subjects: "Subjects",
                exams: "Exams",
                grades: "Grades",
                messages: "Messages",
                printouts: "Printouts",
                systemSettings: "Settings",
                logout: "Logout",
                searchPlaceholder: "Search staff/data",
                profileText: "Profile",
                settingsText: "Settings",
                logoutText: "Logout",
                editStaff: "Edit Staff:",
                username: "Username",
                password: "New Password (leave blank to keep current)",
                email: "Email",
                phoneNumber: "Phone Number",
                workTitle: "Work/Job Title",
                department: "Department",
                staffPhoto: "Staff Photo",
                status: "Status",
                currentPhoto: "Current Photo",
                updateStaff: "Update Staff",
                cancel: "Cancel",
                newPasswordHint: "Enter a new password only if you wish to change it.",
                staffNotFound: "No staff member details available. Please go back to the Staff Management page."
            },
            lg: {
                dashboard: "Akawungeezi",
                calendar: "Kkalenda",
                users: "Abakozesa",
                students: "Abayizi",
                teachers: "Basomesa",
                staff: "Abakozi",
                classes: "Ebibiina",
                subjects: "Ebyenjigiriza",
                exams: "Ebigezo",
                grades: "Amanota",
                messages: "Obubaka",
                printouts: "Ebyafulumizibwa",
                systemSettings: "Enteekateeka z'Enkola",
                logout: "Ggalawo",
                searchPlaceholder: "Noonya abakozi/data",
                profileText: "Purofayiro",
                settingsText: "Enteekateeka",
                logoutText: "Ggalawo",
                editStaff: "Kyusa Omukozi:",
                username: "Erinnya ly'omukozi",
                password: "Ekigambo ky'ekyama ekipya (lekerawo ekikaddiye bwe tokyusa)",
                email: "Email",
                phoneNumber: "Esimu",
                workTitle: "Omulimu/Ekifo",
                department: "Ekitongole",
                staffPhoto: "Ekifaananyi ky'omukozi",
                status: "Ebyo ebikwata",
                currentPhoto: "Ekifaananyi ekiriwo kati",
                updateStaff: "Kyusa Omukozi",
                cancel: "Sazaamu",
                newPasswordHint: "Yingiza ekigambo ky'ekyama ekipya bwe wabaawo ky'oyagala okukyusa.",
                staffNotFound: "Tewali mukazi aguliddwa. Ddamu ku lupapula olufuga Abakozi."
            },
            sw: {
                dashboard: "Dashibodi",
                calendar: "Kalenda",
                users: "Watumiaji",
                students: "Wanafunzi",
                teachers: "Walimu",
                staff: "Wafanyakazi",
                classes: "Madarasa",
                subjects: "Masomo",
                exams: "Mitihani",
                grades: "Alama",
                messages: "Ujumbe",
                printouts: "Machapisho",
                systemSettings: "Mipangilio ya Mfumo",
                logout: "Ondoka",
                searchPlaceholder: "Tafuta wafanyakazi/data",
                profileText: "Wasifu",
                settingsText: "Mipangilio",
                logoutText: "Ondoka",
                editStaff: "Hariri Mfanyakazi:",
                username: "Jina la mtumiaji",
                password: "Nenosiri Jipya (acha wazi ili kubaki la sasa)",
                email: "Barua pepe",
                phoneNumber: "Namba ya Simu",
                workTitle: "Kazi/Kichwa cha Kazi",
                department: "Idara",
                staffPhoto: "Picha ya Mfanyakazi",
                status: "Hali",
                currentPhoto: "Picha ya Sasa",
                updateStaff: "Sasisha Mfanyakazi",
                cancel: "Ghairi",
                newPasswordHint: "Weka nenosiri jipya tu ikiwa unataka kulibadilisha.",
                staffNotFound: "Hakuna maelezo ya mfanyakazi yaliyopatikana. Tafadhali rudi kwenye ukurasa wa Usimamizi wa Wafanyakazi."
            }
        };

        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');

        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;
            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 header elements
            document.getElementById('searchPlaceholder').placeholder = t.searchPlaceholder;
            document.querySelector('.user-email').textContent = `Logged in as: Admin`; // Assuming admin_staff.php
            // document.querySelector('.welcome-banner .welcome-text h3').textContent = `${t.welcomePrefix}${username}!`; // Assuming username is dynamic
            // document.querySelector('.welcome-banner .welcome-text p').textContent = t.manageSchoolOperations;

            // Update edit form elements
            const editStaffHeading = document.querySelector('.edit-staff-container h2');
            if (editStaffHeading) {
                const staffUsername = editStaffHeading.textContent.split(': ')[1] || 'N/A'; // Extract current username
                editStaffHeading.innerHTML = `<i class="fas fa-user-edit"></i> ${t.editStaff} ${staffUsername}`;
            }

            document.querySelector('label[for="username"]').textContent = t.username;
            document.querySelector('label[for="email"]').textContent = t.email;
            document.querySelector('label[for="phone_number"]').textContent = t.phoneNumber;
            document.querySelector('label[for="work"]').textContent = t.workTitle;
            document.querySelector('label[for="department"]').textContent = t.department;
            document.querySelector('label[for="status"]').textContent = t.status;
            document.querySelector('label[for="photo"]').textContent = t.staffPhoto;
            document.querySelector('.current-photo-preview span').textContent = t.currentPhoto;
            document.querySelector('label[for="password"]').textContent = t.password;
            document.querySelector('small').textContent = t.newPasswordHint;
            document.querySelector('.btn-primary').textContent = t.updateStaff;
            document.querySelector('.btn-cancel').textContent = t.cancel;
            const staffNotFoundMessage = document.querySelector('.edit-staff-container > p');
            if (staffNotFoundMessage) {
                staffNotFoundMessage.innerHTML = t.staffNotFound.replace('Staff Management', `<a href="admin_staff.php">${t.staffManagement}</a>`);
            }

            // Update mobile footer
            document.getElementById('profileLinkFooter').querySelector('span').textContent = t.profileText;
            document.getElementById('settingsLinkFooter').querySelector('span').textContent = t.settingsText;
            document.getElementById('logoutLinkFooter').querySelector('span').textContent = t.logoutText;
        }


        document.addEventListener('DOMContentLoaded', () => {
            languageSelect.value = currentLanguage;
            updateTranslations();

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

            overlay.addEventListener('click', () => {
                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();
            });
        });
    </script>
</body>
</html>
�