<?php
session_start();
require_once 'config.php'; // Include database connection and configuration

// 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: // Added case for parent
                header("location: parent_dashboard.php");
                break;
            case ROLE_STAFF: // Added case for staff
                header("location: staff_dashboard.php");
                break;
            default:
                header("location: login.php");
                break;
        }
        exit;
    }
}

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

$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]);
$school_id = $_SESSION["school_id"];
$user_role_code = $_SESSION["role"]; // Get role code for display

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

// Initialize admin profile photo path (fetch from DB later if it exists)
$admin_profile_photo_path = isset($_SESSION['photo']) && !empty($_SESSION['photo']) ? htmlspecialchars($_SESSION['photo']) : "images/default_avatar.png";


$school_name = "";
$school_logo_path = "images/default_school_logo.png"; // Default logo
$school_motto = "";
$school_email = "";
$school_phone = "";
$school_address = "";
$school_box_number = "";
$school_website = "";
$school_start_date = ""; // School start date (from schools table)
$school_end_date = "";    // School end date (from schools table)
$school_primary_color = "#4C51BF"; // A shade of deep purple/indigo
$school_secondary_color = "#667EEA"; // A lighter, complementary indigo

$message = "";
$message_type = ""; // 'success' or 'error'

// Array to hold academic years and their terms
$academic_years_and_terms = [];

// Ensure current active year/term is known for UI
$current_academic_year = '';
$current_term_id = null; // ID of the current term
$current_term_name = ''; // Name of the current term


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

    // Fetch school settings
    $sql_fetch_settings = "SELECT school_name, logo, motto, email, phone, address, box_number, website, start_date, end_date, primary_color, secondary_color FROM schools WHERE school_id = ?";
    if ($stmt_fetch = $conn->prepare($sql_fetch_settings)) {
        $stmt_fetch->bind_param("i", $school_id);
        $stmt_fetch->execute();
        $stmt_fetch->bind_result($name, $logo, $motto, $email, $phone, $address, $box, $website, $start_date, $end_date, $primary_color, $secondary_color);
        if ($stmt_fetch->fetch()) {
            $school_name = htmlspecialchars($name);
            $school_logo_path = !empty($logo) ? htmlspecialchars($logo) : 'images/default_school_logo.png';
            $school_motto = htmlspecialchars($motto);
            $school_email = htmlspecialchars($email);
            $school_phone = htmlspecialchars($phone);
            $school_address = htmlspecialchars($address);
            $school_box_number = htmlspecialchars($box);
            $school_website = htmlspecialchars($website);
            $school_start_date = htmlspecialchars($start_date ?? '');
            $school_end_date = htmlspecialchars($end_date ?? '');
            $school_primary_color = !empty($primary_color) ? htmlspecialchars($primary_color) : "#4C51BF";
            $school_secondary_color = !empty($secondary_color) ? htmlspecialchars($secondary_color) : "#667EEA";
        }
        $stmt_fetch->close();
    } else {
        error_log("Failed to prepare fetch school settings query: " . $conn->error);
        $message = "Error fetching current school settings.";
        $message_type = "error";
    }

    // Fetch current admin's profile photo path
    $sql_fetch_profile_photo = "SELECT photo FROM users WHERE id = ?";
    if ($stmt_fetch_photo = $conn->prepare($sql_fetch_profile_photo)) {
        $stmt_fetch_photo->bind_param("i", $user_id);
        $stmt_fetch_photo->execute();
        $stmt_fetch_photo->bind_result($photo_path);
        if ($stmt_fetch_photo->fetch()) {
            $admin_profile_photo_path = !empty($photo_path) ? htmlspecialchars($photo_path) : 'images/default_avatar.png';
        }
        $stmt_fetch_photo->close();
    } else {
        error_log("Failed to prepare fetch profile photo query: " . $conn->error);
    }


    // Handle form submission for updating general school info and colors
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_general_info'])) {
        $new_school_name = trim($_POST['school_name']);
        $new_school_motto = trim($_POST['school_motto']);
        $new_school_email = trim($_POST['school_email']);
        $new_school_phone = trim($_POST['school_phone']);
        $new_school_address = trim($_POST['school_address']);
        $new_school_box_number = trim($_POST['school_box_number']);
        $new_school_website = trim($_POST['school_website']);
        $new_school_primary_color = trim($_POST['primary_color']);
        $new_school_secondary_color = trim($_POST['secondary_color']);
        $new_school_logo_path = $school_logo_path; // Keep current logo by default

        // Handle logo upload
        if (isset($_FILES['school_logo']) && $_FILES['school_logo']['error'] == UPLOAD_ERR_OK) {
            $target_dir = "uploads/logos/";
            // Create directory if it doesn't exist
            if (!is_dir($target_dir)) {
                mkdir($target_dir, 0777, true);
            }
            $file_extension = pathinfo($_FILES['school_logo']['name'], PATHINFO_EXTENSION);
            $new_file_name = uniqid('logo_') . '.' . $file_extension;
            $target_file = $target_dir . $new_file_name;
            $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

            // Check if image file is a actual image or fake image
            $check = getimagesize($_FILES["school_logo"]["tmp_name"]);
            if($check !== false) {
                // Allow certain file formats
                if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
                    $message = "Sorry, only JPG, JPEG, PNG & GIF files are allowed for logo.";
                    $message_type = "error";
                } else {
                    if (move_uploaded_file($_FILES["school_logo"]["tmp_name"], $target_file)) {
                        $new_school_logo_path = $target_file;
                        // Delete old logo if it's not the default one
                        if ($school_logo_path != 'images/default_school_logo.png' && file_exists($school_logo_path)) {
                            unlink($school_logo_path);
                        }
                    } else {
                        $message = "Sorry, there was an error uploading your logo file.";
                        $message_type = "error";
                    }
                }
            } else {
                $message = "File is not an image.";
                $message_type = "error";
            }
        }

        if (empty($message)) { // Only proceed if no file upload errors
            $sql_update_settings = "UPDATE schools SET school_name = ?, logo = ?, motto = ?, email = ?, phone = ?, address = ?, box_number = ?, website = ?, primary_color = ?, secondary_color = ? WHERE school_id = ?";
            if ($stmt_update = $conn->prepare($sql_update_settings)) {
                $stmt_update->bind_param("ssssssssssi", $new_school_name, $new_school_logo_path, $new_school_motto, $new_school_email, $new_school_phone, $new_school_address, $new_school_box_number, $new_school_website, $new_school_primary_color, $new_school_secondary_color, $school_id);
                if ($stmt_update->execute()) {
                    $message = "School information updated successfully!";
                    $message_type = "success";
                    // Update session and current variables to reflect changes immediately
                    $_SESSION['school_name'] = $new_school_name;
                    $_SESSION['school_logo'] = $new_school_logo_path;
                    $school_name = $new_school_name;
                    $school_logo_path = $new_school_logo_path;
                    $school_motto = $new_school_motto;
                    $school_email = $new_school_email;
                    $school_phone = $new_school_phone;
                    $school_address = $new_school_address;
                    $school_box_number = $new_school_box_number;
                    $school_website = $new_school_website;
                    $school_primary_color = $new_school_primary_color;
                    $school_secondary_color = $new_school_secondary_color;
                } else {
                    $message = "Error updating school information: " . $stmt_update->error;
                    $message_type = "error";
                }
                $stmt_update->close();
            } else {
                error_log("Failed to prepare update school settings query: " . $conn->error);
                $message = "Error preparing update statement for general info.";
                $message_type = "error";
            }
        }
    }

    // Handle form submission for updating school dates (overall school operation dates)
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_dates'])) {
        $new_start_date = trim($_POST['start_date']);
        $new_end_date = trim($_POST['end_date']);

        if (empty($new_start_date) || empty($new_end_date)) {
            $message = "Both start date and end date are required.";
            $message_type = "error";
        } else {
            $sql_update_dates = "UPDATE schools SET start_date = ?, end_date = ? WHERE school_id = ?";
            if ($stmt_dates_update = $conn->prepare($sql_update_dates)) {
                $stmt_dates_update->bind_param("ssi", $new_start_date, $new_end_date, $school_id);
                if ($stmt_dates_update->execute()) {
                    $message = "School dates updated successfully!";
                    $message_type = "success";
                    $school_start_date = $new_start_date;
                    $school_end_date = $new_end_date;
                } else {
                    $message = "Error updating school dates: " . $stmt_dates_update->error;
                    $message_type = "error";
                }
                $stmt_dates_update->close();
            } else {
                error_log("Failed to prepare update school dates query: " . $conn->error);
                $message = "Error preparing update statement for school dates.";
                $message_type = "error";
            }
        }
    }

    // Handle form submission for updating admin profile (username, password, photo)
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_admin_profile'])) {
        $new_username = trim($_POST['new_username']);
        $current_password = trim($_POST['current_password']);
        $new_password = trim($_POST['new_password']);
        $confirm_new_password = trim($_POST['confirm_new_password']);
        $new_profile_photo_path = $admin_profile_photo_path; // Keep current photo by default

        // Fetch current password hash from the database for verification
        $sql_fetch_user_pass = "SELECT password FROM users WHERE id = ? AND school_id = ?";
        $current_password_hash = null;
        if ($stmt_fetch_pass = $conn->prepare($sql_fetch_user_pass)) {
            $stmt_fetch_pass->bind_param("ii", $user_id, $school_id);
            $stmt_fetch_pass->execute();
            $stmt_fetch_pass->bind_result($current_password_hash);
            $stmt_fetch_pass->fetch();
            $stmt_fetch_pass->close();
        } else {
            error_log("Failed to prepare fetch user password query: " . $conn->error);
            $message = "Error checking current password.";
            $message_type = "error";
        }

        if (empty($message)) { // Only proceed if no prior errors
            // Verify current password
            if (!password_verify($current_password, $current_password_hash)) {
                $message = "Current password is incorrect.";
                $message_type = "error";
            } else {
                $hashed_new_password = $current_password_hash; // Default to current hash if no new password

                if (!empty($new_password)) {
                    if ($new_password !== $confirm_new_password) {
                        $message = "New password and confirm password do not match.";
                        $message_type = "error";
                    } else {
                        // Hash the new password
                        $hashed_new_password = password_hash($new_password, PASSWORD_DEFAULT);
                    }
                }

                // Handle profile photo upload
                if (isset($_FILES['profile_photo']) && $_FILES['profile_photo']['error'] == UPLOAD_ERR_OK) {
                    $target_dir_profile = "uploads/avatars/";
                    if (!is_dir($target_dir_profile)) {
                        mkdir($target_dir_profile, 0777, true);
                    }
                    $file_extension_profile = pathinfo($_FILES['profile_photo']['name'], PATHINFO_EXTENSION);
                    $new_file_name_profile = uniqid('profile_') . '.' . $file_extension_profile;
                    $target_file_profile = $target_dir_profile . $new_file_name_profile;
                    $imageFileType_profile = strtolower(pathinfo($target_file_profile, PATHINFO_EXTENSION));

                    $check_profile = getimagesize($_FILES["profile_photo"]["tmp_name"]);
                    if($check_profile !== false) {
                        if($imageFileType_profile != "jpg" && $imageFileType_profile != "png" && $imageFileType_profile != "jpeg" && $imageFileType_profile != "gif" ) {
                            $message = "Sorry, only JPG, JPEG, PNG & GIF files are allowed for profile photo.";
                            $message_type = "error";
                        } else {
                            if (move_uploaded_file($_FILES["profile_photo"]["tmp_name"], $target_file_profile)) {
                                $new_profile_photo_path = $target_file_profile;
                                // Delete old profile photo if it's not the default one
                                if ($admin_profile_photo_path != 'images/default_avatar.png' && file_exists($admin_profile_photo_path)) {
                                    unlink($admin_profile_photo_path);
                                }
                            } else {
                                $message = "Sorry, there was an error uploading your profile photo.";
                                $message_type = "error";
                            }
                        }
                    } else {
                        $message = "Profile photo file is not an image.";
                        $message_type = "error";
                    }
                }

                if (empty($message)) { // Proceed if password and photo conditions are met
                    $sql_update_profile = "UPDATE users SET username = ?, password = ?, photo = ? WHERE id = ? AND school_id = ?";
                    if ($stmt_profile_update = $conn->prepare($sql_update_profile)) {
                        $stmt_profile_update->bind_param("sssii", $new_username, $hashed_new_password, $new_profile_photo_path, $user_id, $school_id);
                        if ($stmt_profile_update->execute()) {
                            $message = "Admin profile updated successfully!";
                            $message_type = "success";
                            $_SESSION['username'] = $new_username; // Update session username
                            $_SESSION['photo'] = $new_profile_photo_path;
                            $username = $new_username; // Update current variable
                            $admin_profile_photo_path = $new_profile_photo_path; // Update current variable
                        } else {
                            $message = "Error updating admin profile: " . $stmt_profile_update->error;
                            $message_type = "error";
                        }
                        $stmt_profile_update->close();
                    } else {
                        error_log("Failed to prepare update admin profile query: " . $conn->error);
                        $message = "Error preparing update statement for admin profile.";
                        $message_type = "error";
                    }
                }
            }
        }
    }

    // --- Academic Year & Term Management Logic ---

    // 1. Handle Adding New Academic Year
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_academic_year'])) {
        $new_academic_year = trim($_POST['academic_year']); // Now expects 'YYYY'

        if (!empty($new_academic_year) && preg_match('/^\d{4}$/', $new_academic_year)) {
            // Check if academic year already exists
            $sql_check_year = "SELECT COUNT(*) FROM academic_years_terms WHERE school_id = ? AND academic_year = ?";
            if ($stmt_check_year = $conn->prepare($sql_check_year)) {
                $stmt_check_year->bind_param("is", $school_id, $new_academic_year);
                $stmt_check_year->execute();
                $stmt_check_year->bind_result($count);
                $stmt_check_year->fetch();
                $stmt_check_year->close();

                if ($count > 0) {
                    $message = "Academic year '{$new_academic_year}' already exists.";
                    $message_type = "error";
                } else {
                    // For a new academic year, we'll insert a placeholder row with default dates.
                    // This row won't represent a 'term', but allows the year to exist for term creation.
                    // You might consider a separate 'academic_years' table if you truly want to separate years from terms.
                    // For now, this structure works by setting term_name to 'Default Term'
                    $sql_insert_year = "INSERT INTO academic_years_terms (school_id, academic_year, term_name, start_date, end_date) VALUES (?, ?, 'Default Term Placeholder', CURDATE(), CURDATE())";
                    if ($stmt_insert_year = $conn->prepare($sql_insert_year)) {
                        $stmt_insert_year->bind_param("is", $school_id, $new_academic_year);
                        if ($stmt_insert_year->execute()) {
                            $message = "Academic Year '{$new_academic_year}' added successfully! You can now add specific terms to it.";
                            $message_type = "success";
                        } else {
                            $message = "Error adding academic year: " . $stmt_insert_year->error;
                            $message_type = "error";
                        }
                        $stmt_insert_year->close();
                    } else {
                        error_log("Failed to prepare insert academic year query: " . $conn->error);
                        $message = "Database error preparing to add academic year.";
                        $message_type = "error";
                    }
                }
            } else {
                error_log("Failed to prepare check academic year query: " . $conn->error);
                $message = "Database error checking academic year existence.";
                $message_type = "error";
            }
        } else {
            $message = "Academic Year must be a 4-digit year (e.g., 2025).";
            $message_type = "error";
        }
    }

    // 2. Handle Adding New Term
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_term'])) {
        $selected_academic_year = trim($_POST['term_academic_year']);
        $new_term_name = trim($_POST['term_name']);
        $term_start_date = trim($_POST['term_start_date']);
        $term_end_date = trim($_POST['term_end_date']);

        if (empty($selected_academic_year) || empty($new_term_name) || empty($term_start_date) || empty($term_end_date)) {
            $message = "All term fields are required.";
            $message_type = "error";
        } else {
            // Check if term already exists for this academic year and school
            $sql_check_term = "SELECT COUNT(*) FROM academic_years_terms WHERE school_id = ? AND academic_year = ? AND term_name = ?";
            if ($stmt_check_term = $conn->prepare($sql_check_term)) {
                $stmt_check_term->bind_param("iss", $school_id, $selected_academic_year, $new_term_name);
                $stmt_check_term->execute();
                $stmt_check_term->bind_result($count);
                $stmt_check_term->fetch();
                $stmt_check_term->close();

                if ($count > 0) {
                    $message = "Term '{$new_term_name}' already exists for academic year '{$selected_academic_year}'.";
                    $message_type = "error";
                } else {
                    $sql_insert_term = "INSERT INTO academic_years_terms (school_id, academic_year, term_name, start_date, end_date) VALUES (?, ?, ?, ?, ?)";
                    if ($stmt_insert_term = $conn->prepare($sql_insert_term)) {
                        $stmt_insert_term->bind_param("issss", $school_id, $selected_academic_year, $new_term_name, $term_start_date, $term_end_date);
                        if ($stmt_insert_term->execute()) {
                            $message = "Term '{$new_term_name}' added successfully to '{$selected_academic_year}'!";
                            $message_type = "success";
                        } else {
                            $message = "Error adding term: " . $stmt_insert_term->error;
                            $message_type = "error";
                        }
                        $stmt_insert_term->close();
                    } else {
                        error_log("Failed to prepare insert term query: " . $conn->error);
                        $message = "Database error preparing to add term.";
                        $message_type = "error";
                    }
                }
            } else {
                error_log("Failed to prepare check term query: " . $conn->error);
                $message = "Database error checking term existence.";
                $message_type = "error";
            }
        }
    }

    // 3. Handle Editing Term
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['edit_term'])) {
        $term_id = filter_var($_POST['term_id'], FILTER_VALIDATE_INT);
        $edited_academic_year = trim($_POST['edited_academic_year']); // Hidden field, should match the original year
        $edited_term_name = trim($_POST['edited_term_name']);
        $edited_start_date = trim($_POST['edited_start_date']);
        $edited_end_date = trim($_POST['edited_end_date']);
        $set_current_term = isset($_POST['set_current_term']) ? 1 : 0;
        $set_current_year = isset($_POST['set_current_year']) ? 1 : 0;

        if (!$term_id || empty($edited_academic_year) || empty($edited_term_name) || empty($edited_start_date) || empty($edited_end_date)) {
            $message = "Invalid term ID or missing fields for editing.";
            $message_type = "error";
        } else {
            $sql_check_duplicate = "SELECT COUNT(*) FROM academic_years_terms WHERE school_id = ? AND academic_year = ? AND term_name = ? AND id != ?";
            if ($stmt_check_duplicate = $conn->prepare($sql_check_duplicate)) {
                $stmt_check_duplicate->bind_param("issi", $school_id, $edited_academic_year, $edited_term_name, $term_id);
                $stmt_check_duplicate->execute();
                $stmt_check_duplicate->bind_result($duplicate_count);
                $stmt_check_duplicate->fetch();
                $stmt_check_duplicate->close();

                if ($duplicate_count > 0) {
                    $message = "Term '{$edited_term_name}' already exists for academic year '{$edited_academic_year}'. Please choose a different name.";
                    $message_type = "error";
                } else {
                    // If setting current term, unset all others first for this school
                    if ($set_current_term) {
                        $sql_unset_current_terms = "UPDATE academic_years_terms SET is_current_term = 0 WHERE school_id = ?";
                        if ($stmt_unset_terms = $conn->prepare($sql_unset_current_terms)) {
                            $stmt_unset_terms->bind_param("i", $school_id);
                            $stmt_unset_terms->execute();
                            $stmt_unset_terms->close();
                        } else {
                            error_log("Failed to prepare unset current terms query: " . $conn->error);
                            $message = "Database error unsetting current terms.";
                            $message_type = "error";
                        }
                    }

                    // If setting current year, unset all others first for this school
                    if ($set_current_year) {
                        $sql_unset_current_years = "UPDATE academic_years_terms SET is_current_year = 0 WHERE school_id = ?";
                        if ($stmt_unset_years = $conn->prepare($sql_unset_current_years)) {
                            $stmt_unset_years->bind_param("i", $school_id);
                            $stmt_unset_years->execute();
                            $stmt_unset_years->close();
                        } else {
                            error_log("Failed to prepare unset current years query: " . $conn->error);
                            $message = "Database error unsetting current years.";
                            $message_type = "error";
                        }
                    }

                    // Update the specific term
                    $sql_update_term = "UPDATE academic_years_terms SET term_name = ?, start_date = ?, end_date = ?, is_current_term = ? WHERE id = ? AND school_id = ?";
                    if ($stmt_update_term = $conn->prepare($sql_update_term)) {
                        $stmt_update_term->bind_param("sssiii", $edited_term_name, $edited_start_date, $edited_end_date, $set_current_term, $term_id, $school_id);
                        if ($stmt_update_term->execute()) {
                            $message = "Term '{$edited_term_name}' updated successfully!";
                            $message_type = "success";

                            // Now, if setting current year, apply it to ALL terms in that academic year
                            if ($set_current_year) {
                                $sql_set_year_current = "UPDATE academic_years_terms SET is_current_year = 1 WHERE school_id = ? AND academic_year = ?";
                                if ($stmt_set_year = $conn->prepare($sql_set_year_current)) {
                                    $stmt_set_year->bind_param("is", $school_id, $edited_academic_year);
                                    if (!$stmt_set_year->execute()) {
                                        error_log("Error setting current academic year after term update: " . $stmt_set_year->error);
                                        $message .= " (Error setting academic year as current)";
                                        $message_type = "error"; // Promote to error if year setting failed
                                    }
                                    $stmt_set_year->close();
                                }
                            }

                        } else {
                            $message = "Error updating term: " . $stmt_update_term->error;
                            $message_type = "error";
                        }
                        $stmt_update_term->close();
                    } else {
                        error_log("Failed to prepare update term query: " . $conn->error);
                        $message = "Database error preparing to update term.";
                        $message_type = "error";
                    }
                }
            } else {
                error_log("Failed to prepare check duplicate term query: " . $conn->error);
                $message = "Database error checking for duplicate term names.";
                $message_type = "error";
            }
        }
    }

    // 4. Handle Deleting Term
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['delete_term'])) {
        $term_id_to_delete = filter_var($_POST['term_id_to_delete'], FILTER_VALIDATE_INT);

        if (!$term_id_to_delete) {
            $message = "Invalid term ID for deletion.";
            $message_type = "error";
        } else {
            // Get academic_year of the term being deleted
            $term_year = '';
            $sql_get_term_year = "SELECT academic_year FROM academic_years_terms WHERE id = ? AND school_id = ?";
            if ($stmt_get_year = $conn->prepare($sql_get_term_year)) {
                $stmt_get_year->bind_param("ii", $term_id_to_delete, $school_id);
                $stmt_get_year->execute();
                $stmt_get_year->bind_result($term_year);
                $stmt_get_year->fetch();
                $stmt_get_year->close();
            } else {
                error_log("Failed to prepare get term year query: " . $conn->error);
            }

            $sql_delete_term = "DELETE FROM academic_years_terms WHERE id = ? AND school_id = ?";
            if ($stmt_delete_term = $conn->prepare($sql_delete_term)) {
                $stmt_delete_term->bind_param("ii", $term_id_to_delete, $school_id);
                if ($stmt_delete_term->execute()) {
                    if ($stmt_delete_term->affected_rows > 0) {
                        $message = "Term deleted successfully!";
                        $message_type = "success";

                        // After deleting a term, check if its academic year now has no terms left.
                        $sql_count_terms_in_year = "SELECT COUNT(*) FROM academic_years_terms WHERE school_id = ? AND academic_year = ? AND term_name != 'Default Term Placeholder'";
                        if ($stmt_count_terms = $conn->prepare($sql_count_terms_in_year)) {
                            $stmt_count_terms->bind_param("is", $school_id, $term_year);
                            $stmt_count_terms->execute();
                            $stmt_count_terms->bind_result($terms_remaining_in_year);
                            $stmt_count_terms->fetch();
                            $stmt_count_terms->close();

                            if ($terms_remaining_in_year == 0) {
                                // If no actual terms are left, reset is_current_year flag for that year
                                $sql_reset_current_year = "UPDATE academic_years_terms SET is_current_year = 0 WHERE school_id = ? AND academic_year = ?";
                                if ($stmt_reset_year = $conn->prepare($sql_reset_current_year)) {
                                    $stmt_reset_year->bind_param("is", $school_id, $term_year);
                                    if (!$stmt_reset_year->execute()) {
                                        error_log("Error resetting current academic year flag after term deletion: " . $stmt_reset_year->error);
                                    }
                                    $stmt_reset_year->close();
                                } else {
                                    error_log("Failed to prepare reset current year query after deletion: " . $conn->error);
                                }
                            }
                        } else {
                            error_log("Failed to prepare count terms in year query after deletion: " . $conn->error);
                        }
                    } else {
                        $message = "No term found with the specified ID in your school.";
                        $message_type = "error";
                    }
                } else {
                    $message = "Error deleting term: " . $stmt_delete_term->error;
                    $message_type = "error";
                }
                $stmt_delete_term->close();
            } else {
                error_log("Failed to prepare delete term query: " . $conn->error);
                $message = "Database error preparing to delete term.";
                $message_type = "error";
            }
        }
    }

    // --- Fetch all Academic Years and Terms for display ---
    $sql_fetch_years_terms = "SELECT id, academic_year, term_name, start_date, end_date, is_current_term, is_current_year FROM academic_years_terms WHERE school_id = ? ORDER BY academic_year DESC, start_date ASC";
    if ($stmt_fetch_years_terms = $conn->prepare($sql_fetch_years_terms)) {
        $stmt_fetch_years_terms->bind_param("i", $school_id);
        $stmt_fetch_years_terms->execute();
        $result = $stmt_fetch_years_terms->get_result();
        while ($row = $result->fetch_assoc()) {
            $year = htmlspecialchars($row['academic_year']);
            $term_name = htmlspecialchars($row['term_name']);

            // Exclude "Default Term Placeholder" from being displayed as an actual term
            if ($term_name === 'Default Term Placeholder') {
                // Only add the year if it doesn't exist yet (handles empty years)
                if (!isset($academic_years_and_terms[$year])) {
                    $academic_years_and_terms[$year] = ['terms' => [], 'is_current_year' => (bool)$row['is_current_year']];
                }
                // Skip adding placeholder as a real term
                continue;
            }

            if (!isset($academic_years_and_terms[$year])) {
                $academic_years_and_terms[$year] = ['terms' => [], 'is_current_year' => (bool)$row['is_current_year']];
            }

            $academic_years_and_terms[$year]['terms'][] = [
                'id' => $row['id'],
                'term_name' => $term_name,
                'start_date' => htmlspecialchars($row['start_date']),
                'end_date' => htmlspecialchars($row['end_date']),
                'is_current_term' => (bool)$row['is_current_term']
            ];

            if ($row['is_current_term']) {
                $current_academic_year = $year;
                $current_term_id = $row['id'];
                $current_term_name = $term_name;
            }
            if ($row['is_current_year']) { // Ensure current_academic_year reflects true current year
                $current_academic_year = $year;
            }
        }
        $stmt_fetch_years_terms->close();
    } else {
        error_log("Failed to prepare fetch academic years and terms query: " . $conn->error);
        $message = "Error fetching academic years and terms.";
        $message_type = "error";
    }

    // Close the connection at the very end
    $conn->close();
} else {
    error_log("Database connection \$conn not available in admin_system_settings.php");
    $message = "Database connection error.";
    $message_type = "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; ?> Settings - <?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 this page if needed, but primarily relying on style.css */
        :root {
            --primary-color: <?php echo $school_primary_color; ?>;
            --secondary-color: <?php echo $school_secondary_color; ?>;
        }
        

        .settings-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .settings-card {
            background-color: var(--card-bg);
            padding: 30px;
            border-radius: 10px;
            box-shadow: var(--shadow-light);
        }

        .settings-card h3 {
            color: var(--text-dark);
            margin-bottom: 20px;
            font-size: 1.5em;
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 10px;
        }

        .settings-card .form-group label {
            font-weight: 600;
            color: #555;
            margin-bottom: 8px;
            display: block;
        }

        .settings-card input[type="text"],
        .settings-card input[type="email"],
        .settings-card input[type="url"],
        .settings-card input[type="tel"],
        .settings-card input[type="password"],
        .settings-card input[type="date"], /* Added date type */
        .settings-card select,
        .settings-card textarea {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-sizing: border-box; /* Ensures padding doesn't affect total width */
        }
        .settings-card input[type="color"] {
            width: 80px; /* Adjust width for color picker */
            height: 40px;
            padding: 0;
            border: 1px solid #ccc;
            border-radius: 5px;
            cursor: pointer;
            vertical-align: middle;
            margin-bottom: 15px;
        }

        .settings-card input[type="file"] {
            padding: 5px 0;
        }

        .settings-card .logo-preview,
        .settings-card .profile-photo-preview {
            max-width: 120px;
            max-height: 120px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 5px;
            margin-bottom: 15px;
            display: block;
            object-fit: contain;
        }
        .settings-card .profile-photo-preview {
            border-radius: 50%; /* Make profile photo round */
            object-fit: cover;
        }

        .settings-card button[type="submit"],
        .settings-card input[type="submit"] {
            background-color: var(--primary-green);
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s ease;
            width: auto; /* Allow button to size based on content */
            margin-top: 10px;
        }

        .settings-card button[type="submit"]:hover,
        .settings-card input[type="submit"]:hover {
            background-color: #251e35; /* Slightly darker green */
        }

        .alert {
            padding: 10px 20px;
            margin-bottom: 20px;
            border-radius: 5px;
            font-weight: 500;
            opacity: 1; /* Initial opacity for fading */
            transition: opacity 0.5s ease-out; /* Smooth fade-out transition */
        }
        .alert.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .alert.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        /* Academic Year & Term Specific Styles */
        .academic-section h4 {
            font-size: 1.2em;
            margin-top: 20px;
            margin-bottom: 10px;
            color: var(--primary-green);
            border-bottom: 1px dashed var(--border-color);
            padding-bottom: 5px;
        }
        .academic-list-item {
            background-color: #f9f9f9;
            border: 1px solid #eee;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            display: flex;
            flex-direction: column;
            gap: 5px;
            position: relative;
        }
        .academic-list-item strong {
            color: var(--text-dark);
            font-size: 1.1em;
        }
        .academic-list-item span {
            font-size: 0.9em;
            color: #666;
        }
        .academic-item-actions {
            display: flex;
            gap: 10px;
            margin-top: 10px;
            justify-content: flex-end;
        }
        .academic-item-actions button {
            padding: 8px 12px;
            border-radius: 5px;
            border: none;
            cursor: pointer;
            font-size: 0.9em;
            transition: background-color 0.2s ease;
        }
        .academic-item-actions .edit-btn {
            background-color: var(--light-blue);
            color: white;
        }
        .academic-item-actions .edit-btn:hover {
            background-color: #4a90e2;
        }
        .academic-item-actions .delete-btn {
            background-color: #e74c3c;
            color: white;
        }
        .academic-item-actions .delete-btn:hover {
            background-color: #c0392b;
        }
        .current-tag {
            background-color: #28a745;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.75em;
            font-weight: 600;
            position: absolute;
            top: 10px;
            right: 10px;
        }
        .checkbox-group {
            display: flex;
            align-items: center;
            margin-top: 10px;
            margin-bottom: 15px;
        }
        .checkbox-group input[type="checkbox"] {
            margin-right: 8px;
            width: auto;
            margin-bottom: 0;
        }
        .checkbox-group label {
            margin-bottom: 0;
            font-weight: normal;
        }
        
        /* Table for Academic Years & Terms List */
        .academic-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        .academic-table th, .academic-table td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: left;
            vertical-align: top; /* Align content to top */
        }
        .academic-table th {
            background-color: #f2f2f2;
            font-weight: 600;
            color: #333;
        }
        .academic-table tbody tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .academic-table tbody tr:hover {
            background-color: #f0f0f0;
        }
        .academic-table .actions-column {
            white-space: nowrap; /* Prevent buttons from wrapping */
            text-align: center;
        }
        .academic-table .status-dot {
            height: 10px;
            width: 10px;
            background-color: #bbb;
            border-radius: 50%;
            display: inline-block;
            margin-right: 5px;
        }
        .academic-table .status-dot.active {
            background-color: #28a745; /* Green for active */
        }

        /* Current Academic Year/Term display */
        .current-academic-display {
            background-color: #eaf6ea; /* Light green background */
            border: 1px solid #c6e7c6;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
        }
        .current-academic-display p {
            margin: 0;
            font-size: 1.1em;
            color: #1a6d1a; /* Darker green text */
        }
        .current-academic-display strong {
            color: var(--dark-green);
        }

        /* Mobile Footer Styling */
        .mobile-footer {
            display: none; /* Hidden by default */
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            background-color: var(--header-bg); /* Use header background color */
            box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
            z-index: 1000;
            padding: 10px 0;
        }

        .mobile-footer nav ul {
            display: flex;
            justify-content: space-around;
            list-style: none;
            margin: 0;
            padding: 0;
        }

        .mobile-footer nav ul li a {
            display: flex;
            flex-direction: column;
            align-items: center;
            color: var(--header-text-color); /* Use header text color */
            text-decoration: none;
            font-size: 0.8em;
            font-weight: 500;
        }

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

        .mobile-footer nav ul li a:hover {
            color: var(--primary-color); /* Highlight on hover */
        }


        /* Responsive adjustments for this page */
        @media (max-width: 768px) {
            .settings-grid {
                grid-template-columns: 1fr; /* Stack settings cards on mobile */
            }
            .settings-card {
                padding: 20px;
            }
            .settings-card h3 {
                font-size: 1.3em;
            }
            .academic-list-item {
                padding: 10px;
            }
            .academic-table th, .academic-table td {
                padding: 8px;
                font-size: 0.9em;
            }
            .academic-table .actions-column button {
                padding: 6px 10px;
                font-size: 0.8em;
            }
            .mobile-footer {
                display: block; /* Show on mobile */
            }
        }

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

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

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

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

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

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

        #mobile-footer-nav a.active::after {
            content: '';
            position: absolute;
            top: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 30px;
            height: 3px;
            background: #4f46e5;
            border-radius: 2px;
        }

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

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

        /* More Menu Modal */
        #more-menu-modal {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            height: auto;
            max-height: 80vh;
            background-color: #fff;
            border-top-left-radius: 20px;
            border-top-right-radius: 20px;
            box-shadow: 0 -4px 15px rgba(0, 0, 0, 0.15);
            z-index: 2000;
            transform: translateY(100%);
            transition: transform 0.3s ease-in-out;
            padding-bottom: env(safe-area-inset-bottom, 20px);
            overflow-y: auto;
            visibility: hidden;
            pointer-events: none;
        }

        #more-menu-modal.show {
            transform: translateY(0) !important;
            visibility: visible !important;
            pointer-events: auto !important;
            z-index: 99999 !important;
            display: block !important;
        }
        
        #more-menu-modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
            position: sticky;
            top: 0;
            background-color: #fff;
        }

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

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

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

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

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

        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1500;
            display: none;
        }
        
        .overlay.show {
            display: block;
        }

        /* Enhanced Modal Styles */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 10000;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
            max-width: 500px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
            position: relative;
        }

        .close-button {
            position: absolute;
            top: 10px;
            right: 15px;
            color: #666;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            transition: color 0.3s;
        }

        .close-button:hover {
            color: #000;
        }

        /* Enhanced Button Styles */
        .edit-term-btn, .delete-term-btn {
            margin: 0 2px;
            padding: 8px 12px !important;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .edit-term-btn {
            background-color: var(--primary-color, #4C51BF) !important;
            color: white !important;
        }

        .edit-term-btn:hover {
            background-color: #3a3f9e !important;
            transform: translateY(-1px);
        }

        .delete-term-btn {
            background-color: #e74c3c !important;
            color: white !important;
        }

        .delete-term-btn:hover {
            background-color: #c0392b !important;
            transform: translateY(-1px);
        }

        .btn-text {
            margin-left: 4px;
        }

        /* Action buttons container */
        .actions-column {
            text-align: center;
            padding: 8px !important;
        }

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

        <div class="main-content">
            <header class="header">
                <button class="menu-toggle" id="menuToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="school-info">
                    <img src="<?php echo $school_logo_path; ?>" alt="<?php echo $school_name; ?> Logo">
                    <h1><?php echo $school_name; ?></h1>
                </div>
                <div class="header-right">
                    <div class="language-select">
                        <select id="languageSelect">
                           <option value="en">🇬🇧 English</option>
                           <option value="lg">🇺🇬 Luganda</option>
                           <option value="sw">🇹🇿 Kiswahili</option>
                        </select>
                    </div>
                    <div class="search-bar">
                        <i class="fas fa-search"></i>
                        <input type="text" placeholder="Search students/data" id="searchPlaceholder">
                    </div>
                    <div class="notifications">
                        <i class="fas fa-bell"></i>
                    </div>
                    <div class="user-profile">
                        <img src="<?php echo $admin_profile_photo_path; ?>" 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 id="settingsPageHeading"><i class="fas fa-cog"></i> System Settings</h2>

                <?php if (!empty($message)): ?>
                    <div class="alert <?php echo $message_type; ?>">
                        <?php echo $message; ?>
                    </div>
                <?php endif; ?>

                <div class="settings-grid">
                    <!-- General School Settings -->
                    <div class="settings-card">
                        <h3 id="generalSettingsHeading">General School Settings</h3>
                        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
                            <div class="form-group">
                                <label for="school_logo" id="logoPreviewLabel">Current Logo Preview:</label>
                                <img src="<?php echo $school_logo_path; ?>" alt="School Logo" class="logo-preview">
                                <label for="school_logo" id="uploadLogoLabel">Upload New Logo:</label>
                                <input type="file" name="school_logo" id="school_logo" accept="image/*">
                            </div>
                            <div class="form-group">
                                <label for="school_name" id="schoolNameLabel">School Name:</label>
                                <input type="text" name="school_name" id="school_name" value="<?php echo $school_name; ?>" required>
                            </div>
                            <div class="form-group">
                                <label for="school_motto" id="schoolMottoLabel">School Motto:</label>
                                <input type="text" name="school_motto" id="school_motto" value="<?php echo $school_motto; ?>">
                            </div>
                            <div class="form-group">
                                <label for="school_email" id="schoolEmailLabel">School Email:</label>
                                <input type="email" name="school_email" id="school_email" value="<?php echo $school_email; ?>">
                            </div>
                            <div class="form-group">
                                <label for="school_phone" id="schoolPhoneLabel">School Phone:</label>
                                <input type="tel" name="school_phone" id="school_phone" value="<?php echo $school_phone; ?>">
                            </div>
                            <div class="form-group">
                                <label for="school_address" id="schoolAddressLabel">School Address:</label>
                                <input type="text" name="school_address" id="school_address" value="<?php echo $school_address; ?>">
                            </div>
                            <div class="form-group">
                                <label for="school_box_number" id="schoolBoxNumberLabel">P.O. Box Number:</label>
                                <input type="text" name="school_box_number" id="school_box_number" value="<?php echo $school_box_number; ?>">
                            </div>
                            <div class="form-group">
                                <label for="school_website" id="schoolWebsiteLabel">School Website (URL):</label>
                                <input type="url" name="school_website" id="school_website" value="<?php echo $school_website; ?>">
                            </div>
                            <div class="form-group">
                                <label for="primary_color" id="primaryColorLabel">Primary Color:</label>
                                <input type="color" name="primary_color" id="primary_color" value="<?php echo $school_primary_color; ?>">
                            </div>
                            <div class="form-group">
                                <label for="secondary_color" id="secondaryColorLabel">Secondary Color:</label>
                                <input type="color" name="secondary_color" id="secondary_color" value="<?php echo $school_secondary_color; ?>">
                            </div>
                            <button type="submit" name="update_general_info" class="btn btn-primary" id="updateInfoBtn">Update Information</button>
                        </form>
                    </div>

                    <!-- School Operating Dates (Academic Year Scope) -->
                    <div class="settings-card">
                        <h3 id="schoolOperatingDatesHeading">School Operating Dates</h3>
                        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                            <div class="form-group">
                                <label for="start_date" id="startDateLabel">School Start Date:</label>
                                <input type="date" name="start_date" id="start_date" value="<?php echo $school_start_date; ?>" required>
                            </div>
                            <div class="form-group">
                                <label for="end_date" id="endDateLabel">School End Date:</label>
                                <input type="date" name="end_date" id="end_date" value="<?php echo $school_end_date; ?>" required>
                            </div>
                            <button type="submit" name="update_dates" class="btn btn-primary" id="updateDatesBtn">Update Dates</button>
                        </form>

                        <h3 class="mt-4" id="adminProfileSettingsHeading">Admin Profile Settings</h3>
                        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
                            <div class="form-group">
                                <label for="profile_photo" id="profilePhotoPreviewLabel">Current Profile Photo:</label>
                                <img src="<?php echo $admin_profile_photo_path; ?>" alt="Profile Photo" class="profile-photo-preview">
                                <label for="profile_photo" id="uploadProfilePhotoLabel">Upload New Profile Photo:</label>
                                <input type="file" name="profile_photo" id="profile_photo" accept="image/*">
                            </div>
                            <div class="form-group">
                                <label for="new_username" id="newUsernameLabel">New Username:</label>
                                <input type="text" name="new_username" id="new_username" value="<?php echo $username; ?>" required>
                            </div>
                            <div class="form-group">
                                <label for="current_password" id="currentPasswordLabel">Current Password (Required):</label>
                                <input type="password" name="current_password" id="current_password" required>
                            </div>
                            <div class="form-group">
                                <label for="new_password" id="newPasswordLabel">New Password (Optional):</label>
                                <input type="password" name="new_password" id="new_password">
                            </div>
                            <div class="form-group">
                                <label for="confirm_new_password" id="confirmNewPasswordLabel">Confirm New Password:</label>
                                <input type="password" name="confirm_new_password" id="confirm_new_password">
                            </div>
                            <button type="submit" name="update_admin_profile" class="btn btn-primary" id="updateProfileBtn">Update Profile</button>
                        </form>
                    </div>
                </div>

                <div class="settings-card mt-4">
                    <h3 id="academicYearTermManagementHeading">Academic Year & Term Management</h3>

                    <div class="current-academic-display">
                        <p>Current Academic Year: <strong><?php echo empty($current_academic_year) ? 'N/A' : $current_academic_year; ?></strong></p>
                        <p>Current Term: <strong><?php echo empty($current_term_name) ? 'N/A' : $current_term_name; ?></strong></p>
                    </div>

                    <h4 id="addAcademicYearHeading">Add New Academic Year</h4>
                    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                        <div class="form-group">
                            <label for="academic_year" id="academicYearLabel">Academic Year (e.g., 2025):</label>
                            <input type="text" name="academic_year" id="academic_year" placeholder="YYYY" pattern="\d{4}" title="Please enter a 4-digit year" required>
                        </div>
                        <button type="submit" name="add_academic_year" class="btn btn-success" id="addYearButton">Add Year</button>
                    </form>

                    <h4 id="addTermHeading">Add New Term</h4>
                    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                        <div class="form-group">
                            <label for="term_academic_year" id="termAcademicYearLabel">Select Academic Year:</label>
                            <select name="term_academic_year" id="termAcademicYear" required>
                                <option value="">Select Year</option>
                                <!-- Options populated by JavaScript -->
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="term_name" id="termNameLabel">Term Name:</label>
                            <input type="text" name="term_name" id="term_name" required>
                        </div>
                        <div class="form-group">
                            <label for="term_start_date" id="termStartDateLabel">Term Start Date:</label>
                            <input type="date" name="term_start_date" id="term_start_date" required>
                        </div>
                        <div class="form-group">
                            <label for="term_end_date" id="termEndDateLabel">Term End Date:</label>
                            <input type="date" name="term_end_date" id="term_end_date" required>
                        </div>
                        <button type="submit" name="add_term" class="btn btn-success" id="addTermButton">Add Term</button>
                    </form>

                    <h4 id="academicYearTermListHeading">Academic Years & Terms List</h4>
                    <table class="academic-table">
                        <thead>
                            <tr>
                                <th id="yearListHeader">Year</th>
                                <th id="termListHeader">Term</th>
                                <th id="startListHeader">Start Date</th>
                                <th id="endListHeader">End Date</th>
                                <th id="currentListHeader">Current?</th>
                                <th id="actionsListHeader" class="actions-column">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($academic_years_and_terms)): ?>
                                <tr><td colspan="6">No academic years or terms configured yet.</td></tr>
                            <?php else: ?>
                                <?php foreach ($academic_years_and_terms as $year => $year_data): ?>
                                    <?php if (empty($year_data['terms'])): // Display year even if it has no terms yet, or only placeholder ?>
                                        <tr>
                                            <td><strong><?php echo $year; ?></strong> <span class="status-dot <?php echo $year_data['is_current_year'] ? 'active' : ''; ?>"></span></td>
                                            <td colspan="5">No terms added for this academic year yet.</td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($year_data['terms'] as $term): ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo $year; ?></strong>
                                                    <?php if ($year_data['is_current_year']): ?>
                                                        <span class="status-dot active"></span>
                                                    <?php endif; ?>
                                                </td>
                                                <td><?php echo $term['term_name']; ?></td>
                                                <td><?php echo $term['start_date']; ?></td>
                                                <td><?php echo $term['end_date']; ?></td>
                                                <td>
                                                    <?php if ($term['is_current_term']): ?>
                                                        <span class="current-tag">Current Term</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="actions-column">
                                                    <button type="button" class="btn edit-term-btn"
                                                            data-id="<?php echo $term['id']; ?>"
                                                            data-year="<?php echo $year; ?>"
                                                            data-name="<?php echo $term['term_name']; ?>"
                                                            data-start-date="<?php echo $term['start_date']; ?>"
                                                            data-end-date="<?php echo $term['end_date']; ?>"
                                                            data-is-current-term="<?php echo $term['is_current_term'] ? '1' : '0'; ?>"
                                                            data-is-current-year="<?php echo $year_data['is_current_year'] ? '1' : '0'; ?>"
                                                            id="editTermBtn_<?php echo $term['id']; ?>">
                                                        <i class="fas fa-edit"></i> <span class="btn-text">Edit</span>
                                                    </button>
                                                    <button type="button" class="btn btn-danger delete-term-btn"
                                                            data-id="<?php echo $term['id']; ?>"
                                                            id="deleteTermBtn_<?php echo $term['id']; ?>">
                                                        <i class="fas fa-trash-alt"></i> <span class="btn-text">Delete</span>
                                                    </button>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </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>

    <!-- Modals for Edit/Delete Term -->
    <div class="modal" id="editTermModal">
        <div class="modal-content">
            <span class="close-button">&times;</span>
            <h3 id="editTermModalHeading">Edit Term</h3>
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                <input type="hidden" name="term_id" id="editTermId">
                <input type="hidden" name="edited_academic_year" id="editedAcademicYearHidden">
                <div class="form-group">
                    <label for="edited_term_name" id="editedTermNameLabel">Term Name:</label>
                    <input type="text" name="edited_term_name" id="editedTermName" required>
                </div>
                <div class="form-group">
                    <label for="edited_start_date" id="editedStartDateLabel">Start Date:</label>
                    <input type="date" name="edited_start_date" id="editedStartDate" required>
                </div>
                <div class="form-group">
                    <label for="edited_end_date" id="editedEndDateLabel">End Date:</label>
                    <input type="date" name="edited_end_date" id="editedEndDate" required>
                </div>
                <div class="checkbox-group">
                    <input type="checkbox" name="set_current_term" id="setCurrentTerm">
                    <label for="setCurrentTerm" id="setCurrentTermLabel">Set as Current Term</label>
                </div>
                <div class="checkbox-group">
                    <input type="checkbox" name="set_current_year" id="setCurrentYear">
                    <label for="setCurrentYear" id="setCurrentYearLabel">Set as Current Academic Year (for this academic year)</label>
                </div>
                <button type="submit" name="edit_term" class="btn btn-primary" id="saveChangesBtn">Save Changes</button>
                <button type="button" class="btn" id="cancelEditBtn">Cancel</button>
            </form>
        </div>
    </div>

    <div class="modal" id="confirmDeleteModal">
        <div class="modal-content">
            <span class="close-button">&times;</span>
            <h3 id="confirmDeleteHeading">Confirm Deletion</h3>
            <p id="confirmDeleteMessage">Are you sure you want to delete this term? This action cannot be undone.</p>
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                <input type="hidden" name="term_id_to_delete" id="termIdToDelete">
                <button type="submit" name="delete_term" class="btn btn-danger" id="deleteConfirmBtn">Delete</button>
                <button type="button" class="btn" id="deleteCancelBtn">Cancel</button>
            </form>
        </div>
    </div>

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

    <script>
        // Existing PHP variable for school name for JS translation
        const schoolNameForJs = "<?php echo addslashes($school_name); ?>"; // For JavaScript string literal

        const translations = {
            en: {
                dashboard: "Dashboard",
                calendar: "Calendar",
                users: "Users",
                students: "Students",
                teachers: "Teachers",
                classes: "Classes",
                subjects: "Subjects",
                grades: "Grades",
                exams: "Exams",
                messages: "Messages",
                printouts: "Printouts",
                systemSettings: "Settings",
                logout: "Logout",
                searchPlaceholder: "Search students/data",
                welcomePrefix: "Welcome ",
                welcomeSuffix: "!",
                totalStudents: "Total Students", 
                totalTeachers: "Total Teachers", 
                totalClasses: "Total Classes",
                unreadMessages: "Unread Messages",
                examAnalysis: "Exam Analysis",
                classLabel: "Class",
                subjectLabel: "Subject",
                avgScoreLabel: "Avg. Score",
                overallClassPerformance: "Overall Class Performance Graph",
                noExamData: "No exam analysis data available for your school.",
                noChartData: "No data available to generate class performance graph.",
                monthView: "Month",
                mon: "Mon",
                tue: "Tue",
                wed: "Wed",
                thu: "Thu",
                fri: "Fri",
                sat: "Sat",
                sun: "Sun",
                monthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
                profile: "Profile", 
                settings: "Settings", 
                logoutFooter: "Logout", 
                // Settings page specific translations
                settingsPageHeading: "System Settings",
                generalSettings: "General School Settings",
                logoPreview: "Current Logo Preview",
                uploadLogo: "Upload New Logo",
                schoolName: "School Name",
                schoolMotto: "School Motto",
                schoolEmail: "School Email",
                schoolPhone: "School Phone",
                schoolAddress: "School Address",
                poBox: "P.O. Box Number",
                schoolWebsite: "School Website (URL)",
                primaryColor: "Primary Color",
                secondaryColor: "Secondary Color",
                updateInfo: "Update Information",
                schoolOperatingDates: "School Operating Dates",
                startDate: "School Start Date",
                endDate: "School End Date",
                updateDates: "Update Dates",
                adminProfileSettings: "Admin Profile Settings",
                profilePhotoPreview: "Current Profile Photo",
                newUsername: "New Username",
                currentPassword: "Current Password (Required)",
                newPassword: "New Password (Optional)",
                confirmNewPassword: "Confirm New Password",
                uploadProfilePhoto: "Upload New Profile Photo",
                updateProfile: "Update Profile",
                academicYearTermManagement: "Academic Year & Term Management",
                currentAcademicYear: "Current Academic Year",
                currentTerm: "Current Term",
                addAcademicYear: "Add New Academic Year",
                yearExample: "Academic Year (e.g., 2025)",
                addYearBtn: "Add Year",
                addTerm: "Add New Term",
                selectAcademicYear: "Select Academic Year",
                termName: "Term Name",
                termStartDate: "Term Start Date",
                termEndDate: "Term End Date",
                addTermBtn: "Add Term",
                academicYearTermList: "Academic Years & Terms List",
                yearHeader: "Year",
                termHeader: "Term",
                startHeader: "Start Date",
                endHeader: "End Date",
                currentHeader: "Current?",
                actionsHeader: "Actions",
                edit: "Edit",
                delete: "Delete",
                setCurrentTerm: "Set as Current Term",
                setCurrentYear: "Set as Current Academic Year (for this academic year)",
                editTerm: "Edit Term",
                confirmDeletion: "Confirm Deletion",
                confirmDeleteTerm: "Are you sure you want to delete this term? This action cannot be undone.",
                saveChanges: "Save Changes",
                cancel: "Cancel",
                noYearsOrTerms: "No academic years or terms configured yet.",
                noTermsForYear: "No terms added for this academic year yet.",
                currentTermTag: "Current Term"
            },
            lg: {
                dashboard: "Deesiboodi",
                calendar: "Kkalenda",
                users: "Abakozesa",
                students: "Abayizi",
                teachers: "Basomesa",
                classes: "Ebibiina",
                subjects: "Ebizibu",
                grades: "Amasomo",
                exams: "Ebigezo",
                messages: "Ebiwandiiko",
                printouts: "Ebiwandiiko",
                systemSettings: "Setingi",
                logout: "Fuluma",
                searchPlaceholder: "Noonya abayizi/data",
                welcomePrefix: "Mukulike ",
                welcomeSuffix: "!",
                totalStudents: "Omugatte gw'Abayizi",
                totalTeachers: "Omugatte gw'Abasomesa",
                totalClasses: "Omugatte gw'Ebibiina",
                unreadMessages: "Ebiwandiiko Ebitasomeddwa",
                examAnalysis: "Okwekenneenya Ebigezo",
                classLabel: "Ekibiina",
                subjectLabel: "Eky'okusoma",
                avgScoreLabel: "Avg. Obubonero",
                overallClassPerformance: "Grafu y'Ebibiina",
                noExamData: "Tewali data ya kugezesa eya ssomero lyo.",
                noChartData: "Tewali data ya grafu.",
                monthView: "Omwezi",
                mon: "Bal",
                tue: "Nk",
                wed: "Ns",
                thu: "Nk",
                fri: "Mg",
                sat: "Lw",
                sun: "Ss",
                monthNames: ["Janwali", "Febwali", "Machi", "Apuli", "Meyi", "Juuni", "Julaayi", "Agusito", "Sebuttemba", "Okitobba", "Novvemba", "Desemba"],
                profile: "Purofayiro",
                settings: "Setingi",
                logoutFooter: "Fuluma",
                settingsPageHeading: "Setingi z'Enkola",
                generalSettings: "Setingi Z'essomero Ennene",
                logoPreview: "Akifaananyi K'obubonero",
                uploadLogo: "Teekawo Obubonero Obupya",
                schoolName: "Erinnya Ly'essomero",
                schoolMotto: "Ekigambo ky'Essomero",
                schoolEmail: "Imeero Y'essomero",
                schoolPhone: "Esimu Y'essomero",
                schoolAddress: "Adidresi Y'essomero",
                poBox: "Ekitongole ky'Ebiwandiiko",
                schoolWebsite: "Wabusaati y'Essomero (URL)",
                primaryColor: "Langgi Enkulu",
                secondaryColor: "Langgi Ey'okubiri",
                updateInfo: "Kyusa Ebikwata",
                schoolOperatingDates: "Ennaku z'Okukola Kw'essomero",
                startDate: "Olunaku Olutandikira",
                endDate: "Olunaku Olukomekkereza",
                updateDates: "Kyusa Ennaku",
                adminProfileSettings: "Setingi za Purofayiro ya Adiminsita",
                profilePhotoPreview: "Akifaananyi ky'ekifananyi",
                newUsername: "Erinnya Ly'omukozesa Eripya",
                currentPassword: "Ekigambo ky'Ekukuta Ekiriwo (Kyetagisa)",
                newPassword: "Ekigambo ky'Ekukuta Eripya (Bw'oba oyagala)",
                confirmNewPassword: "Kakasibwa Ekigambo ky'Ekukuta Eripya",
                uploadProfilePhoto: "Teekawo Akifaananyi ky'ekifananyi Ekipya",
                updateProfile: "Kyusa Purofayiro",
                academicYearTermManagement: "Okufuga Omwaka Gw'okusoma n'Ekisanja",
                currentAcademicYear: "Omwaka Gw'okusoma Oguliwo",
                currentTerm: "Ekisanja Ekiriwo",
                addAcademicYear: "Gattako Omwaka Gw'okusoma Omupya",
                yearExample: "Omwaka Gw'okusoma (e.g., 2025)",
                addYearBtn: "Gattako Omwaka",
                addTerm: "Gattako Ekisanja Ekipya",
                selectAcademicYear: "Londa Omwaka Gw'okusoma",
                termName: "Erinnya Ly'ekisanja",
                termStartDate: "Olunaku Olutandikira Olw'ekisanja",
                termEndDate: "Olunaku Olukomekkereza Olw'ekisanja",
                addTermBtn: "Gattako Ekisanja",
                academicYearTermList: "Emyaaka Gy'okusoma n'Ebisajja",
                yearHeader: "Omwaka",
                termHeader: "Ekisanja",
                startHeader: "Olutandikira",
                endHeader: "Olukomekkereza",
                currentHeader: "Kuliwo?",
                actionsHeader: "Ebikolebwa",
                edit: "Kyusa",
                delete: "Sazaamu",
                setCurrentTerm: "Teeka nga Ekisanja Ekiriwo",
                setCurrentYear: "Teeka nga Omwaka Gw'okusoma Oguliwo (ku mwaka guno ogw'okusoma)",
                editTerm: "Kyusa Ekisanja",
                confirmDeletion: "Kakasibwa Okusazaamu",
                confirmDeleteTerm: "Oli mukakasa okusazaamu ekisanja kino? Ekikolwa kino tekisobola kudibwamu.",
                saveChanges: "Kkwaata Enkyukakyuka",
                cancel: "Lekeraawo",
                noYearsOrTerms: "Tewali myaka gy'okusoma oba bisanja biggyiddwawo.",
                noTermsForYear: "Tewali bisanja biggyiddwawo ku mwaka guno ogw'okusoma.",
                currentTermTag: "Ekisanja Ekiriwo"
            },
            sw: {
                dashboard: "Dashibodi",
                calendar: "Kalenda",
                users: "Watumiaji",
                students: "Wanafunzi",
                teachers: "Walimu",
                classes: "Madarasa",
                subjects: "Masomo",
                grades: "Madaraja",
                exams: "Mitihani",
                messages: "Ujumbe",
                printouts: "Nakala",
                systemSettings: "Mipangilio",
                logout: "Toka",
                searchPlaceholder: "Tafuta wanafunzi/data",
                welcomePrefix: "Karibu ",
                welcomeSuffix: "!",
                totalStudents: "Jumla ya Wanafunzi",
                totalTeachers: "Jumla ya Walimu",
                totalClasses: "Jumla ya Madarasa",
                unreadMessages: "Ujumbe Usiosemwa",
                examAnalysis: "Uchambuzi wa Mitihani",
                classLabel: "Darasa",
                subjectLabel: "Somo",
                avgScoreLabel: "Wastani wa Alama",
                overallClassPerformance: "Grafu ya Utendaji wa Darasa",
                noExamData: "Hakuna data ya uchambuzi wa mitihani inayopatikana kwa shule yako.",
                noChartData: "Hakuna data inayopatikana ya kutengeneza grafu ya utendaji wa darasa.",
                monthView: "Mwezi",
                mon: "Jt",
                tue: "Jn",
                wed: "Jl",
                thu: "Al",
                fri: "Ij",
                sat: "Jm",
                sun: "JP",
                monthNames: ["Januari", "Februari", "Machi", "Aprili", "Mei", "Juni", "Julai", "Agosti", "Septemba", "Oktoba", "Novemba", "Desemba"],
                profile: "Wasifu",
                settings: "Mipangilio",
                logoutFooter: "Toka",
                settingsPageHeading: "Mipangilio ya Mfumo",
                generalSettings: "Mipangilio Mikuu ya Shule",
                logoPreview: "Muhtasari wa Nembo",
                uploadLogo: "Pakia Nembo Mpya",
                schoolName: "Jina la Shule",
                schoolMotto: "Wito wa Shule",
                schoolEmail: "Barua pepe ya Shule",
                schoolPhone: "Namba ya Simu ya Shule",
                schoolAddress: "Anwani ya Shule",
                poBox: "Namba ya Sanduku la Posta",
                schoolWebsite: "Tovuti ya Shule (URL)",
                primaryColor: "Rangi Kuu",
                secondaryColor: "Rangi ya Pili",
                updateInfo: "Sasisha Taarifa",
                schoolOperatingDates: "Tarehe za Uendeshaji Shule",
                startDate: "Tarehe ya Kuanza",
                endDate: "Tarehe ya Kumalizia",
                updateDates: "Sasisha Tarehe",
                adminProfileSettings: "Mipangilio ya Wasifu wa Msimamizi",
                profilePhotoPreview: "Picha ya Sasa ya Wasifu",
                newUsername: "Jina Mpya la Mtumiaji",
                currentPassword: "Nenosiri la Sasa (Lazima)",
                newPassword: "Nenosiri Jipya (Hiari)",
                confirmNewPassword: "Thibitisha Nenosiri Jipya",
                uploadProfilePhoto: "Pakia Picha Mpya ya Wasifu",
                updateProfile: "Sasisha Wasifu",
                academicYearTermManagement: "Usimamizi wa Mwaka wa Masomo na Mihula",
                currentAcademicYear: "Mwaka wa Masomo wa Sasa",
                currentTerm: "Muhula wa Sasa",
                addAcademicYear: "Ongeza Mwaka Mpya wa Masomo",
                yearExample: "Mwaka wa Masomo (mfano, 2025)",
                addYearBtn: "Ongeza Mwaka",
                addTerm: "Ongeza Muhula Mpya",
                selectAcademicYear: "Chagua Mwaka wa Masomo",
                termName: "Jina la Muhula",
                termStartDate: "Tarehe ya Kuanza Muhula",
                termEndDate: "Tarehe ya Kumalizia Muhula",
                addTermBtn: "Ongeza Muhula",
                academicYearTermList: "Orodha ya Miaka ya Masomo na Mihula",
                yearHeader: "Mwaka",
                termHeader: "Muhula",
                startHeader: "Anza",
                endHeader: "Malizia",
                currentHeader: "Ya Sasa?",
                actionsHeader: "Vitendo",
                edit: "Hariri",
                delete: "Futa",
                setCurrentTerm: "Weka kama Muhula wa Sasa",
                setCurrentYear: "Weka kama Mwaka wa Masomo wa Sasa (kwa mwaka huu wa masomo)",
                editTerm: "Hariri Muhula",
                confirmDeletion: "Thibitisha Kufuta",
                confirmDeleteTerm: "Una uhakika unataka kufuta muhula huu? Kitendo hiki hakiwezi kutenduliwa.",
                saveChanges: "Hifadhi Mabadiliko",
                cancel: "Ghairi",
                noYearsOrTerms: "Hakuna miaka ya masomo au mihula iliyosanidiwa bado.",
                noTermsForYear: "Hakuna mihula iliyoongezwa kwa mwaka huu wa masomo bado.",
                currentTermTag: "Muhula wa Sasa"
            }
        };

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

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

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

            // Function to apply translations
            function applyTranslations(lang) {
                const t = translations[lang];

                // Helper function to safely update element text
                function safeUpdateText(elementId, selector, text) {
                    const element = document.getElementById(elementId);
                    if (element) {
                        const target = selector ? element.querySelector(selector) : element;
                        if (target) {
                            target.textContent = text;
                        }
                    }
                }

                // Sidebar links - using safe update functions
                safeUpdateText('dashboardLink', '.nav-text', t.dashboard);
                safeUpdateText('calendarLink', '.nav-text', t.calendar);
                safeUpdateText('usersLink', '.nav-text', t.users);
                safeUpdateText('studentsLink', '.nav-text', t.students);
                safeUpdateText('teachersLink', '.nav-text', t.teachers);
                safeUpdateText('classesLink', '.nav-text', t.classes);
                safeUpdateText('subjectsLink', '.nav-text', t.subjects);
                safeUpdateText('examsLink', '.nav-text', t.exams);
                safeUpdateText('messagesLinkSidebar', '.nav-text', t.messages);
                safeUpdateText('printoutsLink', '.nav-text', t.printouts);
                safeUpdateText('systemSettingsLink', '.nav-text', t.systemSettings);
                safeUpdateText('logoutLinkSidebar', '.nav-text', t.logout);


                // Header elements
                safeUpdateText('searchPlaceholder', null, t.searchPlaceholder);

                // Settings specific elements - using safe updates
                safeUpdateText('settingsPageHeading', null, t.settingsPageHeading);
                safeUpdateText('generalSettingsHeading', null, t.generalSettings);
                safeUpdateText('logoPreviewLabel', null, t.logoPreview);
                safeUpdateText('uploadLogoLabel', null, t.uploadLogo);
                safeUpdateText('schoolNameLabel', null, t.schoolName);
                safeUpdateText('schoolMottoLabel', null, t.schoolMotto);
                safeUpdateText('schoolEmailLabel', null, t.schoolEmail);
                safeUpdateText('schoolPhoneLabel', null, t.schoolPhone);
                safeUpdateText('schoolAddressLabel', null, t.schoolAddress);
                safeUpdateText('schoolBoxNumberLabel', null, t.poBox);
                safeUpdateText('schoolWebsiteLabel', null, t.schoolWebsite);
                safeUpdateText('primaryColorLabel', null, t.primaryColor);
                safeUpdateText('secondaryColorLabel', null, t.secondaryColor);
                safeUpdateText('updateInfoBtn', null, t.updateInfo);

                safeUpdateText('schoolOperatingDatesHeading', null, t.schoolOperatingDates);
                safeUpdateText('startDateLabel', null, t.startDate);
                safeUpdateText('endDateLabel', null, t.endDate);
                safeUpdateText('updateDatesBtn', null, t.updateDates);

                safeUpdateText('adminProfileSettingsHeading', null, t.adminProfileSettings);
                safeUpdateText('profilePhotoPreviewLabel', null, t.profilePhotoPreview);
                safeUpdateText('newUsernameLabel', null, t.newUsername);
                safeUpdateText('currentPasswordLabel', null, t.currentPassword);
                safeUpdateText('newPasswordLabel', null, t.newPassword);
                safeUpdateText('confirmNewPasswordLabel', null, t.confirmNewPassword);
                safeUpdateText('uploadProfilePhotoLabel', null, t.uploadProfilePhoto);
                safeUpdateText('updateProfileBtn', null, t.updateProfile);

                safeUpdateText('academicYearTermManagementHeading', null, t.academicYearTermManagement);
                
                // These need special handling for innerHTML
                const currentAcademicYearElement = document.querySelector('.current-academic-display p:nth-child(1)');
                if (currentAcademicYearElement) {
                    currentAcademicYearElement.innerHTML = `${t.currentAcademicYear}: <strong><?php echo empty($current_academic_year) ? 'N/A' : $current_academic_year; ?></strong>`;
                }
                const currentTermElement = document.querySelector('.current-academic-display p:nth-child(2)');
                if (currentTermElement) {
                    currentTermElement.innerHTML = `${t.currentTerm}: <strong><?php echo empty($current_term_name) ? 'N/A' : $current_term_name; ?></strong>`;
                }

                safeUpdateText('addAcademicYearHeading', null, t.addAcademicYear);
                safeUpdateText('academicYearLabel', null, t.yearExample);
                safeUpdateText('addYearButton', null, t.addYearBtn);

                safeUpdateText('addTermHeading', null, t.addTerm);
                safeUpdateText('termAcademicYearLabel', null, t.selectAcademicYear);
                safeUpdateText('termNameLabel', null, t.termName);
                safeUpdateText('termStartDateLabel', null, t.termStartDate);
                safeUpdateText('termEndDateLabel', null, t.termEndDate);
                safeUpdateText('addTermButton', null, t.addTermBtn);

                safeUpdateText('academicYearTermListHeading', null, t.academicYearTermList);
                safeUpdateText('yearListHeader', null, t.yearHeader);
                safeUpdateText('termListHeader', null, t.termHeader);
                safeUpdateText('startListHeader', null, t.startHeader);
                safeUpdateText('endListHeader', null, t.endHeader);
                safeUpdateText('currentListHeader', null, t.currentHeader);
                safeUpdateText('actionsListHeader', null, t.actionsHeader);

                // Update text for table rows that might be empty
                const noYearsOrTermsRow = document.querySelector('.academic-table tbody tr td[colspan="6"]');
                if (noYearsOrTermsRow) {
                    noYearsOrTermsRow.textContent = t.noYearsOrTerms;
                }
                document.querySelectorAll('.academic-table tbody tr td[colspan="5"]').forEach(element => {
                    element.textContent = t.noTermsForYear;
                });
                document.querySelectorAll('.current-tag').forEach(element => {
                    element.textContent = t.currentTermTag;
                });

                // Update button texts within the table rows
                document.querySelectorAll('.edit-term-btn .btn-text').forEach(btnText => {
                    btnText.textContent = t.edit;
                });
                document.querySelectorAll('.delete-term-btn .btn-text').forEach(btnText => {
                    btnText.textContent = t.delete;
                });

                // Modals - using safe updates
                safeUpdateText('editTermModalHeading', null, t.editTerm);
                safeUpdateText('confirmDeleteHeading', null, t.confirmDeletion);
                safeUpdateText('editedTermNameLabel', null, t.termName);
                safeUpdateText('editedStartDateLabel', null, t.termStartDate);
                safeUpdateText('editedEndDateLabel', null, t.termEndDate);
                safeUpdateText('setCurrentTermLabel', null, t.setCurrentTerm);
                safeUpdateText('setCurrentYearLabel', null, t.setCurrentYear);
                safeUpdateText('saveChangesBtn', null, t.saveChanges);
                safeUpdateText('cancelEditBtn', null, t.cancel);
                safeUpdateText('confirmDeleteMessage', null, t.confirmDeleteTerm);
                safeUpdateText('deleteConfirmBtn', null, t.delete);
                safeUpdateText('deleteCancelBtn', null, t.cancel);

                // Mobile Footer
                safeUpdateText('profileTextFooter', null, t.profile);
                safeUpdateText('settingsTextFooter', null, t.settings);
                safeUpdateText('logoutTextFooter', null, t.logoutFooter);
            }

            // Set initial language based on preference or default
            const savedLang = localStorage.getItem('language') || 'en';
            languageSelect.value = savedLang;
            applyTranslations(savedLang);

            // Language change listener
            languageSelect.addEventListener('change', function() {
                const selectedLang = this.value;
                localStorage.setItem('language', selectedLang);
                applyTranslations(selectedLang);
            });

            // Loop through sidebar links and add 'active' class based on current page
            const sidebarLinks = document.querySelectorAll('.sidebar nav ul li a');
            const currentPage = window.location.pathname.split('/').pop();

            sidebarLinks.forEach(link => {
                // Ensure text nodes are correctly handled for comparison and translation
                const linkHref = link.getAttribute('href');
                if (linkHref && linkHref.includes(currentPage)) {
                    link.closest('li').classList.add('active');
                } else {
                    link.closest('li').classList.remove('active');
                }
            });

            // Dynamically set current academic year in the "Add New Term" dropdown
            const selectAcademicYearAddTerm = document.getElementById('termAcademicYear');
            const academicYearsData = <?php echo json_encode(array_keys($academic_years_and_terms)); ?>;

            // Clear existing options first to prevent duplicates on refresh
            selectAcademicYearAddTerm.innerHTML = '<option value="">Select Year</option>';
            academicYearsData.forEach(year => {
                const option = document.createElement('option');
                option.value = year;
                option.textContent = year;
                selectAcademicYearAddTerm.appendChild(option);
            });

            // Implement edit/delete modals using basic JS
            document.body.addEventListener('click', function(event) {
                // Edit button click
                if (event.target.classList.contains('edit-term-btn') || event.target.closest('.edit-term-btn')) {
                    event.preventDefault();
                    const button = event.target.closest('.edit-term-btn');
                    const termId = button.dataset.id;
                    const academicYear = button.dataset.year;
                    const termName = button.dataset.name;
                    const startDate = button.dataset.startDate;
                    const endDate = button.dataset.endDate;
                    const isCurrentTerm = button.dataset.isCurrentTerm === '1';
                    const isCurrentYear = button.dataset.isCurrentYear === '1';

                    document.getElementById('editTermId').value = termId;
                    document.getElementById('editedAcademicYearHidden').value = academicYear;
                    document.getElementById('editedTermName').value = termName;
                    document.getElementById('editedStartDate').value = startDate;
                    document.getElementById('editedEndDate').value = endDate;
                    document.getElementById('setCurrentTerm').checked = isCurrentTerm;
                    document.getElementById('setCurrentYear').checked = isCurrentYear;

                    document.getElementById('editTermModal').style.display = 'flex';
                    document.getElementById('editTermModal').style.position = 'fixed';
                    document.getElementById('editTermModal').style.top = '50%';
                    document.getElementById('editTermModal').style.left = '50%';
                    document.getElementById('editTermModal').style.transform = 'translate(-50%, -50%)';
                    document.getElementById('editTermModal').style.zIndex = '9999';
                    overlay.classList.add('active');
                    applyTranslations(localStorage.getItem('language') || 'en'); // Reapply translations for modal content
                    console.log('Edit modal opened for term:', termId); // Debug log
                }

                // Delete button click
                if (event.target.classList.contains('delete-term-btn') || event.target.closest('.delete-term-btn')) {
                    event.preventDefault();
                    const button = event.target.closest('.delete-term-btn');
                    const termIdToDelete = button.dataset.id;
                    document.getElementById('termIdToDelete').value = termIdToDelete;
                    document.getElementById('confirmDeleteModal').style.display = 'flex';
                    document.getElementById('confirmDeleteModal').style.position = 'fixed';
                    document.getElementById('confirmDeleteModal').style.top = '50%';
                    document.getElementById('confirmDeleteModal').style.left = '50%';
                    document.getElementById('confirmDeleteModal').style.transform = 'translate(-50%, -50%)';
                    document.getElementById('confirmDeleteModal').style.zIndex = '9999';
                    overlay.classList.add('active');
                    applyTranslations(localStorage.getItem('language') || 'en'); // Reapply translations for modal content
                    console.log('Delete modal opened for term:', termIdToDelete); // Debug log
                }

                // Close modals
                if (event.target.classList.contains('close-button') || event.target.id === 'cancelEditBtn' || event.target.id === 'deleteCancelBtn' || event.target.classList.contains('modal')) {
                    document.getElementById('editTermModal').style.display = 'none';
                    document.getElementById('confirmDeleteModal').style.display = 'none';
                    overlay.classList.remove('active');
                }
            });

            // Add additional direct event listeners for extra reliability
            document.querySelectorAll('.edit-term-btn').forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    console.log('Direct edit button click handler triggered');
                });
            });

            document.querySelectorAll('.delete-term-btn').forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    console.log('Direct delete button click handler triggered');
                });
            });

            // Auto-fade messages
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(alert => {
                setTimeout(() => {
                    alert.style.opacity = '0'; // Start fade out
                    setTimeout(() => {
                        alert.remove(); // Remove from DOM after fade
                    }, 500); // Match CSS transition duration
                }, 3000); // 3 seconds before fading starts
            });
        });
    </script>

    <!-- Mobile Footer Navigation -->
    <div id="mobile-footer-nav">
        <ul>
            <li>
                <a href="admin_dashboard.php" data-section="dashboard">
                    <i class="fas fa-th-large"></i>
                    <span>Dashboard</span>
                </a>
            </li>
            <li>
                <a href="admin_user_management.php" data-section="user-management">
                    <i class="fas fa-users-cog"></i>
                    <span>Users</span>
                </a>
            </li>
            <li>
                <a href="admin_messages.php" data-section="messages">
                    <i class="fas fa-envelope"></i>
                    <span>Messages</span>
                </a>
            </li>
            <li>
                <a href="#" id="moreMenuButton" data-section="more">
                    <i class="fas fa-ellipsis-h"></i>
                    <span>More</span>
                </a>
            </li>
        </ul>
    </div>

    <!-- More Menu Modal -->
    <div id="more-menu-modal">
        <div id="more-menu-modal-header">
            <h3>More</h3>
            <button id="more-menu-close-btn"><i class="fas fa-times"></i></button>
        </div>
        <ul id="more-menu-list">
            <li><a href="admin_students.php"><i class="fas fa-user-graduate"></i> Students</a></li>
            <li><a href="admin_teachers.php"><i class="fas fa-chalkboard-teacher"></i> Teachers</a></li>
            <li><a href="admin_staff.php"><i class="fas fa-user-tie"></i> Staff</a></li>
            <li><a href="admin_classes.php"><i class="fas fa-chalkboard"></i> Classes</a></li>
            <li><a href="admin_subjects.php"><i class="fas fa-book"></i> Subjects</a></li>
            <li><a href="admin_exams.php"><i class="fas fa-file-alt"></i> Exams</a></li>
            <li><a href="admin_reports_printouts.php"><i class="fas fa-print"></i> Reports</a></li>
            <li><a href="admin_system_settings.php"><i class="fas fa-cog"></i> Settings</a></li>
            <li class="logout"><a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
        </ul>
    </div>

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

    <script>
        // Mobile Footer Navigation Logic
        document.addEventListener('DOMContentLoaded', function() {
            const moreMenuButton = document.getElementById('moreMenuButton');
            const moreMenuModal = document.getElementById('more-menu-modal');
            const moreMenuCloseBtn = document.getElementById('more-menu-close-btn');
            const overlay = document.getElementById('overlay');

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

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

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

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

</body>
</html>
