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

// 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); // Assuming ROLE_PARENT is 5
if (!defined('ROLE_STAFF')) define('ROLE_STAFF', 6);

// Generate CSRF token if not exists
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Debug: Log CSRF token status
error_log("CSRF Token Status: " . (isset($_SESSION['csrf_token']) ? "SET" : "NOT SET"));

// Function to verify CSRF token
function verify_csrf_token() {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        throw new Exception("Invalid CSRF token. Please refresh the page and try again.");
    }
}

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

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

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

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

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

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

$students = []; // Array to store student data
$classes = []; // Array to store class options
$streams = []; // Array to store stream options
$message = "";
$error = "";

// Function to upload a photo (kept from previous iteration)
function upload_photo($file_key, $upload_dir = "uploads/student_photos/") {
    if (!isset($_FILES[$file_key]) || $_FILES[$file_key]['error'] != UPLOAD_ERR_OK) {
        return null;
    }

    $target_dir = $upload_dir;
    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0755, true);
    }

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

    $check = getimagesize($_FILES[$file_key]["tmp_name"]);
    if($check === false) { return "File is not an image."; }
    if ($_FILES[$file_key]["size"] > 5000000) { return "Sorry, your file is too large."; }
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
        return "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    }

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

function upload_bulk_photos($file_key, $upload_dir = "uploads/student_photos/") {
    if (!isset($_FILES[$file_key]) || $_FILES[$file_key]['error'] != UPLOAD_ERR_OK) {
        return null;
    }

    $target_dir = $upload_dir;
    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0755, true);
    }

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

    $check = getimagesize($_FILES[$file_key]["tmp_name"]);
    if($check === false) { return null; }
    if ($_FILES[$file_key]["size"] > 5000000) { return null; }
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
        return null;
    }

    if (move_uploaded_file($_FILES[$file_key]["tmp_name"], $target_file)) {
        return $target_file;
    } else {
        error_log("Failed to move bulk uploaded file: " . $_FILES[$file_key]["tmp_name"] . " to " . $target_file);
        return null;
    }
}

// --- Initial Data Fetch (School, User, Lookup Tables) ---

// IMPORTANT: The combination_id system creates a foreign key relationship between users and subject_combinations tables
// This ensures data integrity by storing only valid combination_id values that exist in the subject_combinations table
// The combination_id is automatically generated as a unique integer by the AUTO_INCREMENT property

// Ensure $conn is available from config.php
// Debug: Log all POST data when any form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    error_log("FORM SUBMITTED - POST data: " . print_r($_POST, true));
    error_log("FILES data: " . print_r($_FILES, true));
}

if (isset($conn) && $conn instanceof mysqli) { // Check if $conn is set and is a mysqli object

    // Fetch additional user details from the database (phone, photo, status) from the 'users' table
    $sql = "SELECT phone_number, photo, status FROM users WHERE id = ? AND school_id = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("ii", $user_id, $current_user_school_id);
        if ($stmt->execute()) {
            $stmt->bind_result($phone_number_db, $photo_db, $status_db);
            $stmt->fetch();
            $phone_number = htmlspecialchars($phone_number_db ?? 'N/A');
            // Default photo for Admin if not set
            $photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD';
            $status = htmlspecialchars($status_db ?? 'N/A');
        } else {
            error_log("Execute failed for user details query for Admin: " . $stmt->error);
        }
        $stmt->close(); // This $stmt is closed here
    } else {
        error_log("Prepare failed for user details query for Admin: " . $conn->error);
    }

    // Fetch School Name and Logo from 'schools' table
    $sql_school = "SELECT school_name, logo FROM schools WHERE school_id = ?";
    if ($stmt_school = $conn->prepare($sql_school)) {
        $stmt_school->bind_param("i", $current_user_school_id);
        if ($stmt_school->execute()) {
            $stmt_school->bind_result($school_name_db, $school_logo_db);
            if ($stmt_school->fetch()) {
                $school_name = htmlspecialchars($school_name_db); // For direct HTML output
                $school_name_for_js = addslashes($school_name_db); // For JavaScript string literal
                $school_logo_path = !empty($school_logo_db) ? htmlspecialchars($school_logo_db) : 'images/default_school_logo.png';
            } else {
                error_log("School details not found for school_id: " . $current_user_school_id);
            }
        } else {
            error_log("Execute failed for school data query: " . $stmt_school->error);
        }
        $stmt_school->close();
    } else {
        error_log("Prepare failed for school data query: " . $conn->error);
    }

    // 2. Fetch Classes
    $sql_classes = "SELECT class_id, class_name FROM classes WHERE school_id = ? ORDER BY class_name ASC";
    if ($stmt_classes = $conn->prepare($sql_classes)) {
        $stmt_classes->bind_param("i", $current_user_school_id);
        if ($stmt_classes->execute()) {
            $result_classes = $stmt_classes->get_result();
            while ($row = $result_classes->fetch_assoc()) {
                $classes[] = $row;
            }
        }
        $stmt_classes->close();
    }

    // 3. Fetch Streams WITH CLASS CONTEXT (FIXED: Now shows class + stream)
    // THIS IS THE KEY FIX - Instead of just stream_name, we show class_name + stream_name
    $sql_streams = "SELECT s.stream_id, s.stream_name, s.class_id, c.class_name 
                    FROM streams s 
                    JOIN classes c ON s.class_id = c.class_id 
                    WHERE s.school_id = ? 
                    ORDER BY c.class_name ASC, s.stream_name ASC";
    if ($stmt_streams = $conn->prepare($sql_streams)) {
        $stmt_streams->bind_param("i", $current_user_school_id);
        if ($stmt_streams->execute()) {
            $result_streams = $stmt_streams->get_result();
            while ($row = $result_streams->fetch_assoc()) {
                // Create display text that shows class context: "Senior 1 - Stream A"
                $row['display_name'] = $row['class_name'] . ' - ' . $row['stream_name'];
                $streams[] = $row;
            }
        }
        $stmt_streams->close();
    }

    // 4. Fetch Subject Combinations for S5/S6 dropdown
    $subject_combinations = [];
    $sql_combinations = "SELECT combination_id, combination_code, combination_name, combination_description 
                        FROM subject_combinations 
                        WHERE school_id = ? 
                        ORDER BY combination_code ASC";
    if ($stmt_combinations = $conn->prepare($sql_combinations)) {
        $stmt_combinations->bind_param("i", $current_user_school_id);
        if ($stmt_combinations->execute()) {
            $result_combinations = $stmt_combinations->get_result();
            while ($row = $result_combinations->fetch_assoc()) {
                $subject_combinations[] = $row;
            }
        }
        $stmt_combinations->close();
    }
}

// Determine role name for display (FIXED: removed non-breaking spaces)
$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;
}

// --- Student Management Operations (Logic remains the same) ---

// Add New Student
if ($_SERVER["REQUEST_METHOD"] == "POST" && (isset($_POST["add_student"]) || isset($_POST["add_student_submit"]))) {
    try {
        verify_csrf_token();
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    
    if (empty($error)) {
    // Initialize variables to prevent undefined variable warnings
    $student_class_id = 0;
    $student_stream_id = 0;
    $student_combination_id = 0;
    
    $student_name = trim($_POST["student_name"]);
    $student_email = strtolower(trim($_POST["student_email"]));
    $student_phone = trim($_POST["student_phone"]);
    $student_adm = trim($_POST["student_adm"]);
    $student_class_id = (int)($_POST["student_class_id"] ?? 0);
    $student_stream_id = (int)($_POST["student_stream_id"] ?? 0);
    $student_combination_id = (int)($_POST["student_combination_id"] ?? 0);
    $parent_name = trim($_POST["parent_name"]);
    $parent_phone = trim($_POST["parent_phone"]);
    $student_password = password_hash($_POST["student_password"], PASSWORD_DEFAULT);
}


    if (empty($student_name) || empty($student_email) || empty($student_adm) || empty($_POST["student_password"]) || $student_class_id <= 0) {
        $error = "ADD STUDENT ERROR: Name, Email, Admission No, Class, and Password are required.";
    } else if (!filter_var($student_email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format.";
    } else {
        // Validate that the combination_id exists and belongs to this school (if provided)
        // This ensures referential integrity with the subject_combinations table
        if ($student_combination_id > 0) {
            $sql_validate_combination = "SELECT combination_id FROM subject_combinations WHERE combination_id = ? AND school_id = ?";
            if ($stmt_validate = $conn->prepare($sql_validate_combination)) {
                $stmt_validate->bind_param("ii", $student_combination_id, $current_user_school_id);
                $stmt_validate->execute();
                $stmt_validate->store_result();
                if ($stmt_validate->num_rows === 0) {
                    $error = "Invalid subject combination selected. Please choose a valid combination.";
                    $stmt_validate->close();
                } else {
                    $stmt_validate->close();
                }
            } else {
                $error = "Database error validating combination: " . $conn->error;
            }
        }

        if (empty($error)) {
            // Check for duplicate email or admission number within the school
            $sql_check_duplicate = "SELECT id FROM users WHERE (email = ? OR ADM = ?) AND school_id = ?";
        if ($stmt_check = $conn->prepare($sql_check_duplicate)) {
            $stmt_check->bind_param("ssi", $student_email, $student_adm, $current_user_school_id);
            $stmt_check->execute();
            $stmt_check->store_result();
            if ($stmt_check->num_rows > 0) {
                $error = "A user with email '" . htmlspecialchars($student_email) . "' or ADM No. '" . htmlspecialchars($student_adm) . "' already exists in this school.";
                $stmt_check->close();
            } else {
                $stmt_check->close();
                $conn->begin_transaction();

                try {
                    // 1. Upload photo
                    $photo_path = null;
                    $upload_result = upload_photo("student_photo");
                    if (is_string($upload_result) && (strpos($upload_result, 'Sorry') === 0 || strpos($upload_result, 'File') === 0)) {
                        throw new Exception($upload_result);
                    } else if ($upload_result !== null) {
                        $photo_path = $upload_result;
                    } else {
                         // Default photo if none uploaded
                         $photo_path = 'uploads/student_photos/default_student.png';
                    }

                    // 2. Insert into users table (Includes ADM, Parent details, Class/Stream ID, Combination ID)
                    $sql_insert_user = "INSERT INTO users (username, email, password, role, school_id, phone_number, photo, status, ADM, parent_name, parent_phone, class_id, stream_id, combination_id)
                                        VALUES (?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?)";
                    if ($stmt_user = $conn->prepare($sql_insert_user)) {
                        $role_student_code = ROLE_STUDENT;
                        
                        // DEBUG: Log values before binding to prepared statement
                        error_log("=== INSERT DEBUG VALUES ===");
                        error_log("Username: " . $student_name);
                        error_log("Email: " . $student_email);
                        error_log("School ID: " . $current_user_school_id);
                        error_log("Phone: " . $student_phone);
                        error_log("ADM: " . $student_adm);
                        error_log("Parent Name: " . $parent_name);
                        error_log("Parent Phone: " . $parent_phone);
                        error_log("Class ID: " . $student_class_id);
                        error_log("Stream ID: " . $student_stream_id);
                        error_log("COMBINATION ID TO INSERT: " . $student_combination_id);
                        error_log("=== END INSERT DEBUG ===");
                        
                        $stmt_user->bind_param("sssiisssssiii",
                            $student_name,
                            $student_email,
                            $student_password,
                            $role_student_code,
                            $current_user_school_id,
                            $student_phone,
                            $photo_path,
                            $student_adm,
                            $parent_name,
                            $parent_phone,
                            $student_class_id,
                            $student_stream_id,
                            $student_combination_id
                        );
                        if (!$stmt_user->execute()) {
                            throw new Exception("Error adding user: " . $stmt_user->error);
                        }
                        
                        $inserted_user_id = $conn->insert_id;
                        error_log("=== INSERT SUCCESSFUL ===");
                        error_log("Inserted User ID: " . $inserted_user_id);
                        
                        // Immediately verify the combination_id was saved correctly
                        $verify_result = $conn->query("SELECT combination_id FROM users WHERE id = " . $inserted_user_id);
                        if ($verify_result && $verify_row = $verify_result->fetch_assoc()) {
                            error_log("VERIFICATION - combination_id in database: " . ($verify_row['combination_id'] ?? 'NULL'));
                        } else {
                            error_log("ERROR: Could not verify user with ID " . $inserted_user_id);
                        }
                        
                        $stmt_user->close();
                        $conn->commit();
                        $message = "Student added successfully!";
                    } else {
                        throw new Exception("Prepare failed for user insert: " . $conn->error);
                    }

                } catch (Exception $e) {
                    $conn->rollback();
                    error_log("Add Student Error: " . $e->getMessage());
                    $error = "Failed to add student. Please check the fields and try again. Database error: " . $e->getMessage();
                    if ($photo_path && file_exists($photo_path) && strpos($photo_path, 'default') === false) {
                        unlink($photo_path);
                    }
                }
            }
        } else {
            $error = "Database prepare error for duplicate check: " . $conn->error;
        }
        }
    }
    
    if (!empty($error)) {
        $_SESSION['error_message'] = $error;
        header("location: admin_students.php");
        exit;
    }
}

// Edit Student
if ($_SERVER["REQUEST_METHOD"] == "POST" && (isset($_POST["edit_student"]) || isset($_POST["edit_student_submit"]))) {
    try {
        verify_csrf_token();
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    
    if (empty($error)) {
        error_log("EDIT FORM SUBMITTED - POST data: " . print_r($_POST, true));
        $user_id_to_edit = (int)$_POST["user_id"];

    $student_name = trim($_POST["edit_student_name"]);
    $student_email = strtolower(trim($_POST["edit_student_email"]));
    $student_phone = trim($_POST["edit_student_phone"]);
    $student_adm = trim($_POST["edit_student_adm"]);
    $student_class_id = (int)$_POST["edit_student_class_id"];
    $student_stream_id = (int)$_POST["edit_student_stream_id"];
    $student_combination_id = (int)($_POST["edit_student_combination_id"] ?? 0);
    $parent_name = trim($_POST["edit_parent_name"]);
    $parent_phone = trim($_POST["edit_parent_phone"]);
    $student_status = trim($_POST["edit_student_status"]);
    $current_photo_path = $_POST["current_photo_path"] ?? null;
    
    // Debug logging
    error_log("EDIT FORM VALUES: Name='$student_name', Email='$student_email', ADM='$student_adm', Class_ID='$student_class_id', Phone='$student_phone'");
}
    if (empty($student_name) || empty($student_email) || empty($student_adm) || $student_class_id <= 0) {
        $error = "Name, Email, Admission No, and Class are required to edit a student. Details: Name='$student_name', Email='$student_email', ADM='$student_adm', Class_ID='$student_class_id'";
    } else if (!filter_var($student_email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format.";
    } else {
        // Validate that the combination_id exists and belongs to this school (if provided)
        // This ensures referential integrity with the subject_combinations table
        if ($student_combination_id > 0) {
            $sql_validate_combination = "SELECT combination_id FROM subject_combinations WHERE combination_id = ? AND school_id = ?";
            if ($stmt_validate = $conn->prepare($sql_validate_combination)) {
                $stmt_validate->bind_param("ii", $student_combination_id, $current_user_school_id);
                $stmt_validate->execute();
                $stmt_validate->store_result();
                if ($stmt_validate->num_rows === 0) {
                    $error = "Invalid subject combination selected. Please choose a valid combination.";
                    $stmt_validate->close();
                } else {
                    $stmt_validate->close();
                }
            } else {
                $error = "Database error validating combination: " . $conn->error;
            }
        }

        if (empty($error)) {
            // Check for duplicate email OR duplicate ADM (excluding current user)
            $sql_check_duplicate = "SELECT id FROM users WHERE (email = ? OR ADM = ?) AND id != ? AND school_id = ?";
        if ($stmt_check = $conn->prepare($sql_check_duplicate)) {
            $stmt_check->bind_param("ssii", $student_email, $student_adm, $user_id_to_edit, $current_user_school_id);
            $stmt_check->execute();
            $stmt_check->store_result();
            if ($stmt_check->num_rows > 0) {
                $error = "A user with email or ADM No. '" . htmlspecialchars($student_adm) . "' already exists for another user in this school.";
                $stmt_check->close();
            } else {
                $stmt_check->close();
                $conn->begin_transaction();
                try {
                    $photo_path = $current_photo_path;

                    // Handle photo upload
                    if (isset($_FILES["edit_student_photo"]) && $_FILES["edit_student_photo"]["error"] == UPLOAD_ERR_OK) {
                        $upload_result = upload_photo("edit_student_photo");
                        if (is_string($upload_result) && (strpos($upload_result, 'Sorry') === 0 || strpos($upload_result, 'File') === 0)) {
                            throw new Exception($upload_result);
                        } else {
                            if ($current_photo_path && file_exists($current_photo_path) && strpos($current_photo_path, 'default') === false) {
                                unlink($current_photo_path);
                            }
                            $photo_path = $upload_result;
                        }
                    }

                    // Update users table
                    $sql_update_user = "UPDATE users SET
                                            username = ?,
                                            email = ?,
                                            phone_number = ?,
                                            photo = ?,
                                            status = ?,
                                            ADM = ?,
                                            parent_name = ?,
                                            parent_phone = ?,
                                            class_id = ?,
                                            stream_id = ?,
                                            combination_id = ?
                                        WHERE id = ? AND school_id = ? AND role = ?";
                    if ($stmt_user = $conn->prepare($sql_update_user)) {
                        $role_student_code = ROLE_STUDENT;
                        $stmt_user->bind_param("ssssssssiisiii",
                            $student_name,
                            $student_email,
                            $student_phone,
                            $photo_path,
                            $student_status,
                            $student_adm,
                            $parent_name,
                            $parent_phone,
                            $student_class_id,
                            $student_stream_id,
                            $student_combination_id,
                            $user_id_to_edit,
                            $current_user_school_id,
                            $role_student_code
                        );
                        if (!$stmt_user->execute()) {
                            throw new Exception("Error updating user: " . $stmt_user->error);
                        }
                        $stmt_user->close();
                        $conn->commit();
                        $message = "Student updated successfully!";
                    } else {
                        throw new Exception("Prepare failed for user update: " . $conn->error);
                    }
                } catch (Exception $e) {
                    $conn->rollback();
                    error_log("Edit Student Error: " . $e->getMessage());
                    $error = "Failed to update student. Please check the fields and try again. Database error: " . $e->getMessage();
                    if ($photo_path && $photo_path !== $current_photo_path && file_exists($photo_path) && strpos($photo_path, 'default') === false) {
                        unlink($photo_path);
                    }
                }
            }
        } else {
            $error = "Database prepare error for duplicate check: " . $conn->error;
        }
        }
    }
    
    if (!empty($error)) {
        $_SESSION['error_message'] = $error;
        header("location: admin_students.php");
        exit;
    }
}

// Delete Student
if ($_SERVER["REQUEST_METHOD"] == "POST" && (isset($_POST["delete_student"]) || isset($_POST["delete_student_submit"]))) {
    try {
        verify_csrf_token();
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    
    if (empty($error)) {
        $user_id_to_delete = (int)$_POST["user_id_to_delete"];
    $student_photo_path = $_POST["student_photo_path"] ?? null;

    $conn->begin_transaction();
    try {
        // Delete from users table (must be ROLE_STUDENT for safety)
        $sql_delete_user = "DELETE FROM users WHERE id = ? AND school_id = ? AND role = ?";
        if ($stmt_user = $conn->prepare($sql_delete_user)) {
            $role_student_code = ROLE_STUDENT;
            $stmt_user->bind_param("iii", $user_id_to_delete, $current_user_school_id, $role_student_code);
            if (!$stmt_user->execute()) {
                throw new Exception("Error deleting user record: " . $stmt_user->error);
            }
            $stmt_user->close();
            $conn->commit();
            $message = "Student deleted successfully!";

            // Delete associated photo file
            if ($student_photo_path && file_exists($student_photo_path) && strpos($student_photo_path, 'default') === false) {
                unlink($student_photo_path);
            }
        } else {
            throw new Exception("Prepare failed for user delete: " . $conn->error);
        }
    } catch (Exception $e) {
        $conn->rollback();
        error_log("Delete Student Error: " . $e->getMessage());
        $error = "Failed to delete student. A database error occurred.";
    }
    
    if (!empty($error)) {
        $_SESSION['error_message'] = $error;
        header("location: admin_students.php");
        exit;
    }
}

// Upload CSV (Modified: Accept class names and stream names instead of IDs) - FIXED VERSION
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["upload_csv"])) {
    try {
        verify_csrf_token();
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    
    if (empty($error)) {
    if (isset($_FILES["csv_file"]) && $_FILES["csv_file"]["error"] == UPLOAD_ERR_OK) {
        $file_tmp_path = $_FILES["csv_file"]["tmp_name"];
        $file_extension = pathinfo($_FILES["csv_file"]["name"], PATHINFO_EXTENSION);

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

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

                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    $row_count++;
                    // CSV format: 0:Name*, 1:ADM*, 2:ClassName*, 3:StreamName, 4:SubjectCombination, 5:Email, 6:Phone, 7:ParentName, 8:ParentPhone, 9:Password
                    // Name, ADM, ClassName are required (marked with *)
                    
                    // Ensure we have at least the required columns (Name, ADM, ClassName)
                    if (count($data) >= 3) {
                        $student_name = trim($data[0] ?? '');
                        $student_adm = trim($data[1] ?? '');
                        $class_name = trim($data[2] ?? '');
                        $stream_name = trim($data[3] ?? '');
                        $student_subject_combination = trim($data[4] ?? '');
                        $student_email = !empty($data[5]) ? strtolower(trim($data[5])) : '';
                        $student_phone = trim($data[6] ?? '');
                        $parent_name = trim($data[7] ?? '');
                        $parent_phone = trim($data[8] ?? '');
                        $raw_password = trim($data[9] ?? '');
                        
                        // Generate default email if not provided
                        if (empty($student_email)) {
                            $student_email = strtolower(str_replace(' ', '', $student_name)) . '_' . $student_adm . '@school.local';
                        }
                        
                        // Generate default password if not provided
                        if (empty($raw_password)) {
                            $raw_password = 'student' . $student_adm; // Default password format
                        }
                        
                        $student_password = password_hash($raw_password, PASSWORD_DEFAULT);
                        $default_photo = 'uploads/student_photos/default_student.png';

                        // Validate required fields
                        if (empty($student_name) || empty($student_adm) || empty($class_name)) {
                            $failed_rows[] = "Row $row_count (Missing required data: Name, ADM, or Class)";
                            $fail_count++;
                            continue;
                        }
                        
                        // Validate email format if provided
                        if (!empty($student_email) && !filter_var($student_email, FILTER_VALIDATE_EMAIL)) {
                            $failed_rows[] = "Row $row_count (Invalid email format)";
                            $fail_count++;
                            continue;
                        }

                        // Look up class ID from class name
                        $student_class_id = 0;
                        $sql_find_class = "SELECT class_id FROM classes WHERE class_name = ? AND school_id = ?";
                        if ($stmt_find_class = $conn->prepare($sql_find_class)) {
                            $stmt_find_class->bind_param("si", $class_name, $current_user_school_id);
                            $stmt_find_class->execute();
                            $stmt_find_class->bind_result($found_class_id);
                            if ($stmt_find_class->fetch()) {
                                $student_class_id = $found_class_id;
                            }
                            $stmt_find_class->close();
                        }

                        if ($student_class_id <= 0) {
                            $failed_rows[] = "Row $row_count (Class '$class_name' not found)";
                            $fail_count++;
                            continue;
                        }

                        // FIXED: Look up stream ID with CLASS-SPECIFIC matching to avoid wrong streams
                        $student_stream_id = null; // Changed from 0 to NULL
                        if (!empty($stream_name)) {
                            // FIX: Added class_id constraint to find correct stream for this specific class
                            $sql_find_stream = "SELECT stream_id FROM streams WHERE stream_name = ? AND class_id = ? AND school_id = ?";
                            if ($stmt_find_stream = $conn->prepare($sql_find_stream)) {
                                $stmt_find_stream->bind_param("sii", $stream_name, $student_class_id, $current_user_school_id);
                                $stmt_find_stream->execute();
                                $result_stream = $stmt_find_stream->get_result();
                                if ($stream_row = $result_stream->fetch_assoc()) {
                                    $student_stream_id = $stream_row['stream_id'];
                                }
                                $stmt_find_stream->close();
                            }
                        }

                        // Look up combination ID from combination code (if provided)
                        $csv_combination_id = 0;
                        if (!empty($student_subject_combination)) {
                            $sql_find_combination = "SELECT combination_id FROM subject_combinations WHERE combination_code = ? AND school_id = ?";
                            if ($stmt_find_combination = $conn->prepare($sql_find_combination)) {
                                $stmt_find_combination->bind_param("si", $student_subject_combination, $current_user_school_id);
                                $stmt_find_combination->execute();
                                $stmt_find_combination->bind_result($found_combination_id);
                                if ($stmt_find_combination->fetch()) {
                                    $csv_combination_id = $found_combination_id;
                                }
                                $stmt_find_combination->close();
                            }
                        }
                        
                        // Validate that we found a valid combination (if combination code was provided)
                        if (!empty($student_subject_combination) && $csv_combination_id == 0) {
                            $failed_rows[] = "Row $row_count (Invalid combination code: '$student_subject_combination')";
                            $fail_count++;
                            continue;
                        }

                        // Check for duplicate email or ADM
                        $sql_check_duplicate_csv = "SELECT id FROM users WHERE (email = ? OR ADM = ?) AND school_id = ?";
                        if ($stmt_check_csv = $conn->prepare($sql_check_duplicate_csv)) {
                            $stmt_check_csv->bind_param("ssi", $student_email, $student_adm, $current_user_school_id);
                            $stmt_check_csv->execute();
                            $stmt_check_csv->store_result();
                            if ($stmt_check_csv->num_rows > 0) {
                                $failed_rows[] = "Row $row_count (Email/ADM already exists)";
                                $fail_count++;
                                $stmt_check_csv->close();
                                continue;
                            }
                            $stmt_check_csv->close();
                        } else {
                            $failed_rows[] = "Row $row_count (Database prepare error)";
                            $fail_count++;
                            continue;
                        }

                        $conn->begin_transaction();
                        try {
                            // Insert into users table
                            $sql_insert_user = "INSERT INTO users (username, email, password, role, school_id, phone_number, photo, status, ADM, parent_name, parent_phone, class_id, stream_id, combination_id)
                                                VALUES (?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?)";
                            if ($stmt_user = $conn->prepare($sql_insert_user)) {
                                $role_student_code = ROLE_STUDENT;
                                $stmt_user->bind_param("sssiisssssiii",
                                    $student_name,
                                    $student_email,
                                    $student_password,
                                    $role_student_code,
                                    $current_user_school_id,
                                    $student_phone,
                                    $default_photo,
                                    $student_adm,
                                    $parent_name,
                                    $parent_phone,
                                    $student_class_id,
                                    $student_stream_id,  // Now correctly handles NULL
                                    $csv_combination_id
                                );
                                if (!$stmt_user->execute()) {
                                    throw new Exception("User insert error: " . $stmt_user->error);
                                }
                                $stmt_user->close();
                                $conn->commit();
                                $success_count++;
                            } else {
                                throw new Exception("Prepare failed for user insert: " . $conn->error);
                            }
                        } catch (Exception $e) {
                            $conn->rollback();
                            $failed_rows[] = "Row $row_count (DB error)";
                            $fail_count++;
                            error_log("CSV Upload Student Error: " . $e->getMessage());
                        }
                    } else {
                        $failed_rows[] = "Row $row_count (Insufficient columns - minimum 3 required: Name, ADM, ClassName)";
                        $fail_count++;
                    }
                }
                fclose($handle);
                $message = "CSV upload complete. Successfully added: $success_count students. Failed: $fail_count students.";
                if (!empty($failed_rows)) {
                    $message .= " Details of failed rows: " . implode("; ", array_slice($failed_rows, 0, 10)) . (count($failed_rows) > 10 ? "..." : "");
                }
                // Add debug info
                $message .= " (Debug: Processed $row_count total rows)";
            } else {
                $error = "Could not open CSV file.";
            }
        }
    } else {
        $error = "Error uploading CSV file: " . $_FILES["csv_file"]["error"];
    }
    }
    
    if (!empty($error)) {
        $_SESSION['error_message'] = $error;
        header("location: admin_students.php");
        exit;
    }
}

// Bulk Photo Upload Processing
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["upload_bulk_photos"])) {
    try {
        verify_csrf_token();
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    
    if (empty($error)) {
    if (isset($_FILES["bulk_photo_files"]) && !empty($_FILES["bulk_photo_files"]["name"][0])) {
        $uploaded_count = 0;
        $updated_count = 0;
        $failed_count = 0;
        $failed_files = [];
        
        // Create upload directory if it doesn't exist
        $upload_dir = "uploads/student_photos/";
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }

        // Process each uploaded file
        $total_files = count($_FILES["bulk_photo_files"]["name"]);
        
        for ($i = 0; $i < $total_files; $i++) {
            if ($_FILES["bulk_photo_files"]["error"][$i] == UPLOAD_ERR_OK) {
                $original_filename = $_FILES["bulk_photo_files"]["name"][$i];
                $tmp_name = $_FILES["bulk_photo_files"]["tmp_name"][$i];
                
                // Extract admission number from filename (remove extension)
                $adm = pathinfo($original_filename, PATHINFO_FILENAME);
                
                // Validate ADM format (alphanumeric only)
                if (!preg_match('/^[A-Za-z0-9]+$/', $adm)) {
                    $failed_count++;
                    $failed_files[] = "$original_filename (Invalid ADM format)";
                    continue;
                }
                
                // Check if student exists with this ADM
                $sql_check_student = "SELECT id, photo FROM users WHERE ADM = ? AND school_id = ? AND role = ?";
                if ($stmt_check = $conn->prepare($sql_check_student)) {
                    $role_student_code = ROLE_STUDENT;
                    $stmt_check->bind_param("sii", $adm, $current_user_school_id, $role_student_code);
                    if ($stmt_check->execute()) {
                        $result_check = $stmt_check->get_result();
                        if ($student_row = $result_check->fetch_assoc()) {
                            // Student found, proceed with photo upload
                            $uploaded_count++;
                            
                            // Remove old photo if it exists and is not the default
                            if (!empty($student_row['photo']) && 
                                file_exists($student_row['photo']) && 
                                strpos($student_row['photo'], 'default') === false) {
                                unlink($student_row['photo']);
                            }
                            
                            // Upload new photo
                            $upload_result = upload_bulk_photo_single($i, $upload_dir);
                            
                            if ($upload_result && strpos($upload_result, 'error') === false) {
                                // Update student record with new photo
                                $sql_update_photo = "UPDATE users SET photo = ? WHERE id = ?";
                                if ($stmt_update = $conn->prepare($sql_update_photo)) {
                                    $stmt_update->bind_param("si", $upload_result, $student_row['id']);
                                    if ($stmt_update->execute()) {
                                        $updated_count++;
                                    }
                                    $stmt_update->close();
                                }
                            } else {
                                $failed_count++;
                                $failed_files[] = "$original_filename (Upload failed)";
                            }
                        } else {
                            // Student not found
                            $failed_count++;
                            $failed_files[] = "$original_filename (Student not found)";
                        }
                    }
                    $stmt_check->close();
                } else {
                    $failed_count++;
                    $failed_files[] = "$original_filename (Database error)";
                }
            } else {
                $failed_count++;
                $failed_files[] = $_FILES["bulk_photo_files"]["name"][$i] . " (Upload error)";
            }
        }
        
        // Prepare success message
        $message = "Bulk photo upload completed: $uploaded_count files uploaded, $updated_count photos updated";
        if ($failed_count > 0) {
            $message .= ", $failed_count failed";
        }
        if (!empty($failed_files)) {
            $message .= ". Failed files: " . implode("; ", array_slice($failed_files, 0, 5));
            if (count($failed_files) > 5) {
                $message .= "...";
            }
        }
    } else {
        $error = "No photo files selected for upload.";
    }
    
    if (!empty($error)) {
        $_SESSION['error_message'] = $error;
        header("location: admin_students.php");
        exit;
    }
    }
}

// Helper function for uploading a single bulk photo
function upload_bulk_photo_single($file_index, $upload_dir = "uploads/student_photos/") {
    if (!isset($_FILES["bulk_photo_files"]) || 
        $_FILES["bulk_photo_files"]["error"][$file_index] != UPLOAD_ERR_OK) {
        return null;
    }

    $file_extension = pathinfo($_FILES["bulk_photo_files"]["name"][$file_index], PATHINFO_EXTENSION);
    $unique_filename = uniqid('student_') . '.' . $file_extension;
    $target_file = $upload_dir . $unique_filename;
    $imageFileType = strtolower($file_extension);

    $check = getimagesize($_FILES["bulk_photo_files"]["tmp_name"][$file_index]);
    if($check === false) { return "error: File is not an image."; }
    if ($_FILES["bulk_photo_files"]["size"][$file_index] > 5000000) { return "error: File too large."; }
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
        return "error: Invalid file type.";
    }

    if (move_uploaded_file($_FILES["bulk_photo_files"]["tmp_name"][$file_index], $target_file)) {
        return $target_file;
    } else {
        error_log("Failed to move bulk uploaded file: " . $_FILES["bulk_photo_files"]["tmp_name"][$file_index] . " to " . $target_file);
        return "error: Move failed.";
    }
}

}

// --- Final Fetch of all Students for Display ---
$sql_fetch_students = "SELECT
                            u.id,
                            u.ADM,
                            u.username,
                            u.email,
                            u.phone_number,
                            u.photo,
                            u.parent_name,
                            u.parent_phone,
                            u.status,
                            u.class_id,
                            u.stream_id,
                            u.combination_id,
                            c.class_name,
                            st.stream_name,
                            sc.combination_code,
                            sc.combination_name
                        FROM
                            users u
                        LEFT JOIN
                            classes c ON u.class_id = c.class_id
                        LEFT JOIN
                            streams st ON u.stream_id = st.stream_id
                        LEFT JOIN
                            subject_combinations sc ON u.combination_id = sc.combination_id
                        WHERE
                            u.school_id = ? AND u.role = ?
                        ORDER BY
                            u.ADM ASC"; // Sorted by Admission Number (ADM)

if (isset($conn) && $conn instanceof mysqli) {
    if ($stmt_fetch = $conn->prepare($sql_fetch_students)) {
        $role_student_code = ROLE_STUDENT;
        $stmt_fetch->bind_param("ii", $current_user_school_id, $role_student_code);
        if ($stmt_fetch->execute()) {
            $result_fetch = $stmt_fetch->get_result();
            while ($row = $result_fetch->fetch_assoc()) {
                if (empty($row['photo'])) {
                    $row['photo'] = 'uploads/student_photos/default_student.png';
                }
                $students[] = $row;
            }
        } else {
            error_log("Execute failed for fetching students: " . $stmt_fetch->error);
            $error = "Error fetching students data.";
        }
        $stmt_fetch->close();
    } else {
        error_log("Prepare failed for fetching students: " . $conn->error);
        $error = "Error preparing student fetch statement.";
    }
    // Close the connection
    if ($conn->ping()) {
        $conn->close();
    }
} else if (!isset($conn)) {
    $error = "Database connection not available.";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?php echo $role_name; ?> - Students - <?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>
        /* ============================================= */
        /* FIXED HEADER AND LAYOUT STYLES               */
        /* ============================================= */
        
        /* Fixed Header and Sidebar Layout */
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
            height: 100vh;
        }

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

        /* Fixed Sidebar */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            height: 100vh;
            width: 250px;
            overflow-y: auto;
            z-index: 1000;
            transition: transform 0.3s ease;
        }

        .sidebar.collapsed {
            transform: translateX(-250px);
        }

        /* Main Content Area */
        .main-content {
            flex: 1;
            margin-left: 250px;
            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow: hidden;
            transition: margin-left 0.3s ease;
        }

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

        /* Fixed Header */
        .header {
            position: sticky;
            top: 0;
            z-index: 999;
            background: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        /* Header Content Styling */
        .header-right {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        /* Language Selection Styles */
        .language-select {
            position: relative;
        }

        .language-select select {
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 6px;
            padding: 6px 10px;
            font-size: 0.85em;
            color: #333;
            cursor: pointer;
            min-width: 120px;
            appearance: none;
            background-image: url('data:image/svg+xml;charset=US-ASCII,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 5"><path fill="%23666" d="M2 0L0 2h4zm0 5L0 3h4z"/></svg>');
            background-repeat: no-repeat;
            background-position: right 6px center;
            background-size: 10px;
            transition: all 0.2s ease;
        }

        .language-select select:hover {
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
        }

        .language-select select:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
        }

        /* Search Bar Styles */
        .search-bar {
            position: relative;
            display: flex;
            align-items: center;
        }

        .search-bar i {
            position: absolute;
            left: 10px;
            color: #666;
            z-index: 1;
        }

        .search-bar input {
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 6px;
            padding: 8px 10px 8px 35px;
            font-size: 0.85em;
            color: #333;
            min-width: 200px;
            transition: all 0.2s ease;
        }

        .search-bar input:hover {
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
        }

        .search-bar input:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
        }

        /* Notifications Styles */
        .notifications {
            position: relative;
            cursor: pointer;
            padding: 8px;
            border-radius: 6px;
            transition: background-color 0.2s ease;
        }

        .notifications:hover {
            background-color: #f8f9fa;
        }

        .notifications i {
            font-size: 1.2em;
            color: #666;
        }

        .notifications .badge {
            position: absolute;
            top: 2px;
            right: 2px;
            background-color: #e74c3c;
            color: white;
            border-radius: 50%;
            padding: 2px 6px;
            font-size: 0.7em;
            font-weight: 600;
            min-width: 18px;
            height: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        /* User Profile Styles */
        .user-profile {
            display: flex;
            align-items: center;
            gap: 10px;
            cursor: pointer;
            padding: 8px;
            border-radius: 6px;
            transition: background-color 0.2s ease;
        }

        .user-profile:hover {
            background-color: #f8f9fa;
        }

        .user-profile img {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid #e0e0e0;
        }

        .user-profile .user-name {
            font-weight: 600;
            color: #333;
            font-size: 0.9em;
        }

        .user-profile .user-email {
            font-size: 0.75em;
            color: #666;
            margin-top: 2px;
        }

        .user-profile i {
            color: #666;
            font-size: 0.8em;
        }

        /* School Info in Header */
        .school-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .school-info img {
            width: 30px;
            height: 30px;
            border-radius: 4px;
            object-fit: cover;
        }

        .school-info h1 {
            font-size: 1.2em;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        /* Menu Toggle Button */
        .menu-toggle {
            background: none;
            border: none;
            font-size: 1.2em;
            cursor: pointer;
            padding: 8px;
            border-radius: 6px;
            color: #666;
            display: none; /* Hidden by default on desktop */
        }

        .menu-toggle:hover {
            background-color: #f8f9fa;
        }

        /* Scrollable Content Area */
        .dashboard-content {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            padding: 20px;
            background: #f5f5f5;
        }

        /* Scrollbar Styling */
        .dashboard-content::-webkit-scrollbar {
            width: 8px;
        }

        .dashboard-content::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        .dashboard-content::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }

        .dashboard-content::-webkit-scrollbar-thumb:hover {
            background: #555;
        }

        .sidebar::-webkit-scrollbar {
            width: 6px;
        }

        .sidebar::-webkit-scrollbar-track {
            background: transparent;
        }

        .sidebar::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.3);
            border-radius: 3px;
        }

        .sidebar::-webkit-scrollbar-thumb:hover {
            background: rgba(255, 255, 255, 0.5);
        }

        /* Mobile Responsiveness */
        @media (max-width: 768px) {
            .main-content {
                margin-left: 0;
            }
            .dashboard-content {
                padding-bottom: 20px;
            }
            .sidebar {
                transform: translateX(-250px);
            }
            .sidebar.show {
                transform: translateX(0);
            }
            .menu-toggle {
                display: block;
            }
            .header-right {
                gap: 10px;
            }
            .language-select select {
                font-size: 0.8em;
                padding: 5px 8px;
                min-width: 100px;
            }
            .search-bar input {
                min-width: 150px;
            }
        }

        @media (max-width: 480px) {
            .header-right {
                gap: 8px;
            }
            .language-select select {
                font-size: 0.75em;
                padding: 4px 6px;
                min-width: 90px;
            }
            .search-bar input {
                min-width: 120px;
            }
        }

        @media (max-width: 360px) {
            .header-right {
                gap: 5px;
            }
            .language-select select {
                font-size: 0.7em;
                padding: 3px 5px;
                min-width: 80px;
            }
            .search-bar input {
                min-width: 100px;
                font-size: 0.8em;
            }
        }

        /* Base Styles (Assuming a separate style.css handles the main layout, sidebar, and header) */
        
        /* Message and Error Styling with fade animation */
        .php-message, .php-error {
            padding: 12px; 
            border-radius: 8px; 
            margin-bottom: 20px; 
            font-weight: 500; 
            display: flex; 
            align-items: center; 
            gap: 10px;
            transition: opacity 0.5s ease-out, transform 0.5s ease-out;
            opacity: 1;
            transform: translateY(0);
        }
        .php-message { background-color: #e6ffe6; color: #28a745; border: 1px solid #c3e6cb; }
        .php-error { background-color: #ffe6e6; color: #e74c3c; border: 1px solid #e6c3c3; }
        
        /* Fade out classes for automatic hiding */
        .php-message.fade-out, .php-error.fade-out {
            opacity: 0;
            transform: translateY(-20px);
        }

        /* Page Layout */
        .page-header {
            display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; flex-wrap: wrap; gap: 10px;
        }
        .action-buttons {
            display: flex; gap: 10px; flex-wrap: wrap;
        }

        /* Button Styling */
        .btn { 
            padding: 10px 15px; 
            border-radius: 6px; 
            cursor: pointer; 
            font-weight: 500; 
            transition: background-color 0.2s, transform 0.1s; 
            border: none; 
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-size: 0.9em;
        }
        .btn-primary { background-color: #2ecc71; color: white; }
        .btn-primary:hover { background-color: #27ae60; transform: translateY(-1px); }
        .btn-secondary { background-color: #3498db; color: white; }
        .btn-secondary:hover { background-color: #2980b9; transform: translateY(-1px); }
        .btn-danger { background-color: #e74c3c; color: white; }
        .btn-danger:hover { background-color: #c0392b; transform: translateY(-1px); }

        /* Status Badge */
        .status-badge {
            padding: 4px 8px; border-radius: 4px; font-size: 0.8em; font-weight: 600;
        }
        .status-badge.active { background-color: #e6ffe6; color: #28a745; }
        .status-badge.inactive { background-color: #fffae6; color: #ff9800; }
        .status-badge.suspended { background-color: #ffe6e6; color: #e74c3c; }

        /* Table Styling */
        .student-table-container {
            background-color: #ffffff;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
            overflow-x: auto;
        }
        .student-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }
        .student-table th, .student-table td {
            border: 1px solid #e0e0e0;
            padding: 12px 15px;
            text-align: left;
            vertical-align: middle;
            font-size: 0.9em;
        }
        .student-table th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #555;
            white-space: nowrap;
        }
        .student-table tbody tr:nth-child(even) { background-color: #fbfbfb; }
        .student-table tbody tr:hover { background-color: #f0f0f0; }
        .student-table .student-photo {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid #3498db;
        }
        .student-table .actions button {
            background: none; border: none; cursor: pointer; font-size: 1em; margin: 0 3px; transition: color 0.2s ease;
        }
        .student-table .actions button.edit { color: #3498db; }
        .student-table .actions button.delete { color: #e74c3c; }

        /* Modal Styling */
        .modal { 
            display: none; 
            position: fixed; 
            z-index: 1000; 
            left: 0; 
            top: 0; 
            width: 100%; 
            height: 100%; 
            overflow: auto; 
            background-color: rgba(0,0,0,0.4); 
        }
        .modal-content { 
            background-color: #fefefe; 
            margin: 5% auto; 
            padding: 30px; 
            border-radius: 12px; 
            width: 90%; 
            max-width: 600px; 
            box-shadow: 0 5px 15px rgba(0,0,0,0.3); 
            position: relative; 
            max-height: 90vh;
            overflow-y: auto;
        }
        .close-btn { 
            color: #aaa; 
            float: right; 
            font-size: 28px; 
            font-weight: bold; 
        }
        .close-btn:hover, .close-btn:focus { 
            color: #000; 
            text-decoration: none; 
            cursor: pointer; 
        }
        .form-group { 
            margin-bottom: 15px; 
        }
        .form-group label { 
            display: block; 
            margin-bottom: 5px; 
            font-weight: 600; 
            color: #555; 
        }
        .form-group input:not([type="file"]), .form-group select {
            width: 100%; 
            padding: 10px; 
            border: 1px solid #e0e0e0; 
            border-radius: 8px; 
            box-sizing: border-box;
        }
        .modal-content .current-photo-preview {
            width: 80px; 
            height: 80px; 
            border-radius: 50%; 
            object-fit: cover; 
            margin-top: 10px; 
            border: 2px solid #2ecc71;
        }
        .modal-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }

        /* --- MOBILE FOOTER NAVIGATION STYLES --- */
        
        /* Betpawa-Style 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;
        }

        /* Active state for the currently viewed page */
        #mobile-footer-nav a.active {
            color: #007bff; /* Primary dashboard color for active state */
        }

        #mobile-footer-nav a.active i {
            transform: translateY(-2px);
        }

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

        /* Mobile responsiveness - Show only on mobile devices */
        @media (max-width: 768px) {
            #mobile-footer-nav {
                display: block;
            }
            /* Add padding to main content to avoid footer overlap */
            .main-content {
                padding-bottom: 90px;
            }
            /* Hide the standard sidebar on mobile */
            .sidebar {
                display: none;
            }
            .dashboard-container {
                grid-template-columns: 1fr; /* Single column layout */
            }
        }

        /* Very small devices optimization */
        @media (max-width: 360px) {
            #mobile-footer-nav a {
                font-size: 9px;
            }
            
            #mobile-footer-nav a i {
                font-size: 20px;
            }
        }

        /* Safe area support for devices with notches */
        @supports(padding: max(0px)) {
            #mobile-footer-nav {
                padding-left: max(0px, env(safe-area-inset-left));
                padding-right: max(0px, env(safe-area-inset-right));
            }
        }


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

        /* --- MOBILE FOOTER NAVIGATION STYLES --- */


        /* 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;
        }
    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <!-- Sidebar is hidden on mobile via CSS but kept for desktop -->
        <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> Dashboard</a></li>
                    <li><a href="admin_calendar.php" id="calendarLink"><i class="far fa-calendar-alt"></i> Calendar</a></li>
                    <li><a href="admin_user_management.php" id="usersLink"><i class="fas fa-users-cog"></i> Users</a></li>
                    <li class="active"><a href="admin_students.php" id="studentsLink"><i class="fas fa-user-graduate"></i> Students</a></li>
                    <li><a href="admin_teachers.php" id="teachersLink"><i class="fas fa-chalkboard-teacher"></i> Teachers</a></li>
                    <li><a href="admin_classes.php" id="classesLink"><i class="fas fa-chalkboard"></i> Classes</a></li>
                    <li><a href="admin_subjects.php" id="subjectsLink"><i class="fas fa-book"></i> Subjects</a></li>
                    <li><a href="admin_exams.php" id="examsLink"><i class="fas fa-file-alt"></i> Exams</a></li>
                    <li><a href="admin_messages.php" id="messagesLinkSidebar"><i class="fas fa-envelope"></i> Messages</a></li>
                    <li><a href="admin_reports_printouts.php" id="printoutsLink"><i class="fas fa-print"></i> Printouts</a></li>
                    <li><a href="admin_system_settings.php" id="systemSettingsLink"><i class="fas fa-cog"></i> Settings</a></li>
                    <li><a href="logout.php" class="logout-btn" id="logoutLinkSidebar"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
                </ul>
            </nav>
        </aside>

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

            <div class="dashboard-content">
                <!-- The page header title is now handled by the topbar for consistency, 
                     but we'll keep the action buttons section here -->
                <div class="page-header">
                    <h2><i class="fas fa-user-graduate"></i> Student Records</h2>
                    <div class="action-buttons">
                        <button class="btn btn-primary" onclick="openModal('addStudentModal')">
                            <i class="fas fa-plus-circle"></i> Add New Student
                        </button>
                        <button class="btn btn-secondary" onclick="openModal('uploadCsvModal')">
                            <i class="fas fa-upload"></i> Bulk Upload CSV
                        </button>
                        <button class="btn btn-info" onclick="openModal('bulkPhotoUploadModal')">
                            <i class="fas fa-images"></i> Bulk Photo Upload
                        </button>
                        <a href="sample_student_upload.csv" class="btn btn-secondary" download>
                            <i class="fas fa-download"></i> Sample CSV
                        </a>
                    </div>
                </div>

                <!-- PHP Message/Error Display -->
                <?php if (!empty($message)): ?>
                    <div class="php-message" id="php-message"><i class="fas fa-check-circle"></i> <?php echo $message; ?></div>
                <?php endif; ?>
                <?php if (!empty($error)): ?>
                    <div class="php-error" id="php-error"><i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?></div>
                <?php endif; ?>

                <!-- Student Table -->
                <div class="student-table-container">
                    <h3 id="currentStudentsHeading">Current Students (<?php echo count($students); ?>)</h3>
                    <table class="student-table">
                        <thead>
                            <tr>
                                <th id="admHeader">ADM</th>
                                <th id="photoHeader">Photo</th>
                                <th id="nameHeader">Name</th>
                                <th id="emailHeader">Email</th>
                                <th id="classStreamHeader">Class / Stream</th>
                                <th id="subjectCombinationHeader">Subject Combination</th>
                                <th id="parentHeader">Parent (Name / Phone)</th>
                                <th id="statusHeader">Status</th>
                                <th id="actionsHeader">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($students)): ?>
                                <tr><td colspan="9" style="text-align: center;">No student records found for <?php echo $school_name; ?>.</td></tr>
                            <?php endif; ?>

                            <?php foreach ($students as $student): ?>
                                <tr>
                                    <td data-label="ADM No."><?php echo htmlspecialchars($student['ADM']); ?></td>
                                    <td data-label="Photo">
                                        <img src="<?php echo htmlspecialchars($student['photo']); ?>" alt="Photo" class="student-photo" onerror="this.onerror=null; this.src='uploads/student_photos/default_student.png';">
                                    </td>
                                    <td data-label="Name"><?php echo htmlspecialchars($student['username']); ?></td>
                                    <td data-label="Email"><?php echo htmlspecialchars($student['email']); ?></td>
                                    <td data-label="Class / Stream">
                                        <?php echo htmlspecialchars($student['class_name'] ?? 'N/A'); ?><br>
                                        <small><?php echo htmlspecialchars($student['stream_name'] ?? 'N/A'); ?></small>
                                    </td>
                                    <td data-label="Subject Combination">
                                        <?php 
                                        $class_name = $student['class_name'] ?? '';
                                        $is_alevel = (stripos($class_name, 'Senior 5') !== false || stripos($class_name, 'Senior 6') !== false);
                                        if ($is_alevel) {
                                            if (!empty($student['combination_name'])) {
                                                echo htmlspecialchars($student['combination_name'] . ' (' . $student['combination_code'] . ')');
                                            } else {
                                                echo 'Not Set';
                                            }
                                        } else {
                                            echo '-';
                                        }
                                        ?>
                                    </td>
                                    <td data-label="Parent">
                                        <?php echo htmlspecialchars($student['parent_name'] ?? 'N/A'); ?><br>
                                        <small><?php echo htmlspecialchars($student['parent_phone'] ?? 'N/A'); ?></small>
                                    </td>
                                    <td data-label="Status">
                                        <span class="status-badge <?php echo $student['status'] == 'active' ? 'active' : ($student['status'] == 'suspended' ? 'suspended' : 'inactive'); ?>">
                                            <?php echo ucfirst(htmlspecialchars($student['status'])); ?>
                                        </span>
                                    </td>
                                    <td data-label="Actions" class="actions">
                                        <button class="edit" title="Edit"
                                            onclick="openEditModal({
                                                user_id: <?php echo $student['id']; ?>,
                                                username: '<?php echo addslashes(htmlspecialchars($student['username'])); ?>',
                                                adm: '<?php echo addslashes(htmlspecialchars($student['ADM'])); ?>',
                                                email: '<?php echo addslashes(htmlspecialchars($student['email'])); ?>',
                                                phone: '<?php echo addslashes(htmlspecialchars($student['phone_number'])); ?>',
                                                class_id: <?php echo $student['class_id'] ?? 0; ?>,
                                                stream_id: <?php echo $student['stream_id'] ?? 0; ?>,
                                                combination_id: <?php echo $student['combination_id'] ?? 0; ?>,
                                                parent_name: '<?php echo addslashes(htmlspecialchars($student['parent_name'])); ?>',
                                                parent_phone: '<?php echo addslashes(htmlspecialchars($student['parent_phone'])); ?>',
                                                photo: '<?php echo addslashes(htmlspecialchars($student['photo'])); ?>',
                                                status: '<?php echo addslashes(htmlspecialchars($student['status'])); ?>',
                                                class_name: '<?php echo addslashes(htmlspecialchars($student['class_name'])); ?>'
                                            })">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="delete" title="Delete"
                                            onclick="openDeleteModal(
                                                <?php echo $student['id']; ?>,
                                                '<?php echo addslashes(htmlspecialchars($student['username'])); ?>',
                                                '<?php echo addslashes(htmlspecialchars($student['photo'])); ?>'
                                            )">
                                            <i class="fas fa-trash-alt"></i>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    



    <!-- Modal for Adding New Student -->
    <div id="addStudentModal" class="modal">
        <div class="modal-content">
            <span class="close-btn" onclick="closeModal('addStudentModal')">&times;</span>
            <h3 id="addStudentHeading">Add New Student</h3>
            <?php // Available Subject Combinations info box hidden per user request ?>
            <?php // if (!empty($subject_combinations)): ?>
            <!-- <div style="background: #e8f5e8; padding: 10px; border-radius: 5px; margin-bottom: 15px; font-size: 0.9em;">
                <strong>Available Subject Combinations for S5/S6:</strong><br>
                <?php foreach ($subject_combinations as $index => $combination): ?>
                    <span style="display: inline-block; margin: 2px 5px; padding: 2px 6px; background: white; border: 1px solid #ccc; border-radius: 3px;">
                        <?php echo htmlspecialchars($combination['combination_code']); ?>
                    </span>
                <?php endforeach; ?>
                <br><small>Subject combinations will appear when selecting S5 or S6 classes</small>
            </div> -->
            <?php // endif; ?>
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                <div class="form-group">
                    <label for="student_name" id="studentNameLabel">Full Name *</label>
                    <input type="text" id="student_name" name="student_name" required>
                </div>
                <div class="form-group">
                    <label for="student_adm" id="admissionNumberLabel">Admission Number *</label>
                    <input type="text" id="student_adm" name="student_adm" required>
                </div>
                <div class="form-group">
                    <label for="student_email" id="emailAddressLabel">Email Address *</label>
                    <input type="email" id="student_email" name="student_email" required>
                </div>
                <div class="form-group">
                    <label for="student_password" id="passwordLabel">Temporary Password *</label>
                    <input type="password" id="student_password" name="student_password" required>
                </div>
                <div class="form-group">
                    <label for="student_phone" id="phoneNumberLabel">Phone Number</label>
                    <input type="text" id="student_phone" name="student_phone">
                </div>
                <hr>
                <p><strong id="parentDetailsHeading">Parent Details:</strong></p>
                <div class="form-group">
                    <label for="parent_name" id="parentNameLabel">Parent Name</label>
                    <input type="text" id="parent_name" name="parent_name">
                </div>
                <div class="form-group">
                    <label for="parent_phone" id="parentPhoneLabel">Parent Phone</label>
                    <input type="text" id="parent_phone" name="parent_phone">
                </div>
                <hr>
                <div class="form-group">
                    <label for="student_class_id">Class *</label>
                    <select id="student_class_id" name="student_class_id" required>
                        <option value="">-- Select Class --</option>
                        <?php foreach ($classes as $class): ?>
                            <option value="<?php echo $class['class_id']; ?>"><?php echo htmlspecialchars($class['class_name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="student_stream_id" id="addStreamLabel">Stream (Optional)</label>
                    <select id="student_stream_id" name="student_stream_id">
                        <option value="0" id="addSelectStreamOption">-- Select Stream --</option>
                        <?php foreach ($streams as $stream): ?>
                            <option value="<?php echo $stream['stream_id']; ?>"><?php echo htmlspecialchars($stream['display_name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <small style="color: #666; font-size: 0.85em;">
                        <strong>Streams now show class context:</strong> Senior 1 - A, Senior 2 - A, etc.
                    </small>
                </div>
                <div class="form-group" id="add_subject_combination_group" style="display: none;">
                    <label for="student_combination_id" id="subjectCombinationLabel">Subject Combination (A'Level Only)</label>
                    <select id="student_combination_id" name="student_combination_id">
                        <option value="0" id="addSelectCombinationOption">Select Subject Combination</option>
                        <?php foreach ($subject_combinations as $combination): ?>
                            <option value="<?php echo $combination['combination_id']; ?>">
                                <?php echo htmlspecialchars($combination['combination_name'] . ' (' . $combination['combination_code'] . ')'); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <small style="color: #666; font-size: 0.85em;">For Senior 5 and Senior 6 students only</small>
                </div>
                <div class="form-group">
                    <label for="student_photo" id="photoUploadLabel">Student Photo (Max 5MB)</label>
                    <input type="file" id="student_photo" name="student_photo" accept="image/*">
                </div>
                <input type="hidden" name="action" value="add_student">
                <button type="submit" name="add_student_submit" class="btn btn-primary" id="addStudentButton"><i class="fas fa-plus-circle"></i> Add Student</button>
            </form>
        </div>
    </div>

    <!-- Modal for Editing Student -->
    <div id="editStudentModal" class="modal">
        <div class="modal-content">
            <span class="close-btn" onclick="closeModal('editStudentModal')">&times;</span>
            <h3 id="editStudentHeading">Edit Student Details</h3>
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                <input type="hidden" id="edit_user_id" name="user_id">
                <input type="hidden" id="edit_current_photo_path" name="current_photo_path">

                <div class="form-group text-center">
                    <label id="currentPhotoLabel">Current Photo:</label>
                    <img id="edit_current_photo_preview" src="" alt="Current Photo" class="current-photo-preview" onerror="this.onerror=null; this.src='uploads/student_photos/default_student.png';">
                </div>

                <div class="form-group">
                    <label for="edit_student_name" id="editStudentNameLabel">Full Name *</label>
                    <input type="text" id="edit_student_name" name="edit_student_name" required>
                </div>
                <div class="form-group">
                    <label for="edit_student_adm" id="editAdmissionNumberLabel">Admission Number *</label>
                    <input type="text" id="edit_student_adm" name="edit_student_adm" required>
                </div>
                <div class="form-group">
                    <label for="edit_student_email" id="editEmailAddressLabel">Email Address *</label>
                    <input type="email" id="edit_student_email" name="edit_student_email" required>
                </div>
                <div class="form-group">
                    <label for="edit_student_phone" id="editPhoneNumberLabel">Phone Number</label>
                    <input type="text" id="edit_student_phone" name="edit_student_phone">
                </div>
                <hr>
                <p><strong id="editParentDetailsHeading">Parent Details:</strong></p>
                <div class="form-group">
                    <label for="edit_parent_name" id="editParentNameLabel">Parent Name</label>
                    <input type="text" id="edit_parent_name" name="edit_parent_name">
                </div>
                <div class="form-group">
                    <label for="edit_parent_phone" id="editParentPhoneLabel">Parent Phone</label>
                    <input type="text" id="edit_parent_phone" name="edit_parent_phone">
                </div>
                <hr>
                <div class="form-group">
                    <label for="edit_student_class_id" id="classLabel">Class *</label>
                    <select id="edit_student_class_id" name="edit_student_class_id" required>
                        <option value="" id="selectClassOption">-- Select Class --</option>
                        <?php foreach ($classes as $class): ?>
                            <option value="<?php echo $class['class_id']; ?>"><?php echo htmlspecialchars($class['class_name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="edit_student_stream_id" id="streamLabel">Stream (Optional)</label>
                    <select id="edit_student_stream_id" name="edit_student_stream_id">
                        <option value="0" id="selectStreamOption">-- Select Stream --</option>
                        <?php foreach ($streams as $stream): ?>
                            <option value="<?php echo $stream['stream_id']; ?>"><?php echo htmlspecialchars($stream['display_name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <small style="color: #666; font-size: 0.85em;">
                        <strong>Streams now show class context:</strong> Senior 1 - A, Senior 2 - A, etc.
                    </small>
                </div>
                <div class="form-group" id="edit_subject_combination_group" style="display: none;">
                    <label for="edit_student_combination_id" id="editSubjectCombinationLabel">Subject Combination (A'Level Only)</label>
                    <select id="edit_student_combination_id" name="edit_student_combination_id">
                        <option value="0" id="editSelectCombinationOption">Select Subject Combination</option>
                        <?php foreach ($subject_combinations as $combination): ?>
                            <option value="<?php echo $combination['combination_id']; ?>">
                                <?php echo htmlspecialchars($combination['combination_name'] . ' (' . $combination['combination_code'] . ')'); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <small style="color: #666; font-size: 0.85em;">For Senior 5 and Senior 6 students only</small>
                </div>
                <div class="form-group">
                    <label for="edit_student_status" id="statusLabel">Account Status *</label>
                    <select id="edit_student_status" name="edit_student_status" required>
                        <option value="active" id="activeOption">Active</option>
                        <option value="inactive" id="inactiveOption">Inactive</option>
                        <option value="suspended" id="suspendedOption">Suspended</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="edit_student_photo" id="editPhotoLabel">Change Photo (Max 5MB)</label>
                    <input type="file" id="edit_student_photo" name="edit_student_photo" accept="image/*">
                </div>
                <input type="hidden" name="action" value="edit_student">
                <button type="submit" name="edit_student_submit" class="btn btn-primary" id="saveChangesButton"><i class="fas fa-save"></i> Save Changes</button>
            </form>
        </div>
    </div>

    <!-- Modal for CSV Upload -->
    <div id="uploadCsvModal" class="modal">
        <div class="modal-content">
            <span class="close-btn" onclick="closeModal('uploadCsvModal')">&times;</span>
            <h3>Bulk Upload Students via CSV</h3>
            <p>The CSV must have columns in this order (<strong>Required*</strong>):</p>
            <p><strong>Name*, ADM*, ClassName*, StreamName, SubjectCombination, Email, Phone, ParentName, ParentPhone, Password</strong></p>
            <div style="background-color: #e8f5e8; padding: 15px; border-radius: 5px; margin-bottom: 15px; border-left: 4px solid #28a745;">
                <h4><i class="fas fa-shield-alt"></i> Enhanced Stream & Combination Validation</h4>
                <p><strong>IMPORTANT:</strong> The system validates that streams belong to the correct classes and uses proper combination IDs instead of text codes for better data integrity.</p>
            </div>
            <div style="background-color: #f0f8ff; padding: 15px; border-radius: 5px; margin-bottom: 15px; border-left: 4px solid #007bff;">
                <h4><i class="fas fa-database"></i> How Subject Combinations Work</h4>
                <p><strong>Subject combinations are now stored using unique combination IDs</strong> that reference the subject_combinations table. This ensures:</p>
                <ul style="margin: 10px 0; padding-left: 20px;">
                    <li><strong>Data Integrity:</strong> Only valid combinations can be assigned to students</li>
                    <li><strong>Easy Updates:</strong> Combination names can be changed without affecting student records</li>
                    <li><strong>Better Performance:</strong> Integer-based joins are more efficient than text comparisons</li>
                    <li><strong>CSV Compatible:</strong> You still use combination codes in CSV files - they're automatically converted to IDs</li>
                </ul>
            </div>
            <p><small>
                <strong>Required fields:</strong> Name, ADM (Admission Number), ClassName (e.g., "Senior 1")<br>
                <strong>StreamName:</strong> If provided, it must match exactly with existing streams for that class (e.g., "A" for stream A)<br>
                <strong>Optional fields:</strong> SubjectCombination (for A'Level only), Email, Phone, ParentName, ParentPhone, Password<br>
                If Email or Password are not provided, defaults will be generated.<br>
                <strong>ClassName and StreamName should match exactly with your existing classes and streams.</strong><br>
                <strong>SubjectCombination is only relevant for Senior 5 and Senior 6 students.</strong><br>
                <strong>For SubjectCombination, use the exact combination codes from your database (these will be converted to combination IDs):</strong>
                <?php if (!empty($subject_combinations)): ?>
                    <em><?php echo htmlspecialchars(implode(', ', array_column($subject_combinations, 'combination_code'))); ?></em>
                <?php else: ?>
                    <em>No combinations found - create combinations first in Subject Management</em>
                <?php endif; ?>
            </small></p>
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                <div class="form-group">
                    <label for="csv_file">Select CSV File *</label>
                    <input type="file" id="csv_file" name="csv_file" accept=".csv" required>
                </div>
                <button type="submit" name="upload_csv" class="btn btn-primary"><i class="fas fa-upload"></i> Process Upload</button>
            </form>
        </div>
    </div>

    <!-- Modal for Bulk Photo Upload -->
    <div id="bulkPhotoUploadModal" class="modal">
        <div class="modal-content">
            <span class="close-btn" onclick="closeModal('bulkPhotoUploadModal')">&times;</span>
            <h3><i class="fas fa-images"></i> Bulk Photo Upload</h3>
            <p>Upload multiple student photos at once. Photos should be named with the student's <strong>Admission Number (ADM)</strong>.</p>
            <div style="background-color: #f8f9fa; padding: 15px; border-radius: 5px; margin-bottom: 15px;">
                <h4><i class="fas fa-info-circle"></i> Instructions:</h4>
                <ul style="margin: 10px 0; padding-left: 20px;">
                    <li>Name your photo files with the student's exact Admission Number (e.g., <strong>S001.jpg</strong>, <strong>S002.png</strong>)</li>
                    <li>Supported formats: JPG, JPEG, PNG, GIF</li>
                    <li>Maximum file size: 5MB per photo</li>
                    <li>Multiple files can be selected at once</li>
                    <li>Photos will be automatically matched to students by ADM</li>
                </ul>
            </div>
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                <div class="form-group">
                    <label for="bulk_photo_files">Select Photo Files *</label>
                    <input type="file" id="bulk_photo_files" name="bulk_photo_files[]" accept="image/*" multiple required>
                    <small style="color: #666; font-size: 0.85em;">Hold Ctrl/Cmd to select multiple files</small>
                </div>
                <button type="submit" name="upload_bulk_photos" class="btn btn-primary"><i class="fas fa-upload"></i> Upload Photos</button>
            </form>
        </div>
    </div>

    <!-- Modal for Deleting Student -->
    <div id="deleteStudentModal" class="modal">
        <div class="modal-content">
            <span class="close-btn" onclick="closeModal('deleteStudentModal')">&times;</span>
            <h3>Confirm Deletion</h3>
            <p>Are you sure you want to delete the student: <strong id="delete_student_name"></strong>? This action cannot be undone.</p>
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                <input type="hidden" id="delete_user_id_input" name="user_id_to_delete">
                <input type="hidden" id="delete_photo_path_input" name="student_photo_path">
                <div class="modal-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeModal('deleteStudentModal')">Cancel</button>
                    <input type="hidden" name="action" value="delete_student">
                    <button type="submit" name="delete_student_submit" class="btn btn-danger"><i class="fas fa-trash-alt"></i> Delete Student</button>
                </div>
            </form>
        </div>
    </div>



    <!-- 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 id="footerDashboard">Dashboard</span>
                </a>
            </li>
            <li>
                <a href="admin_user_management.php" data-section="user-management">
                    <i class="fas fa-users-cog"></i>
                    <span id="footerUsers">Users</span>
                </a>
            </li>
            <li>
                <a href="admin_students.php" data-section="students">
                    <i class="fas fa-user-graduate"></i>
                    <span id="footerStudents">Students</span>
                </a>
            </li>
            <li>
                <a href="#" id="moreMenuButton" data-section="more">
                    <i class="fas fa-ellipsis-h"></i>
                    <span id="footerMore">More</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 id="moreMenuTitle">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> <span id="moreStudents">Students</span></a></li>
            <li><a href="admin_teachers.php"><i class="fas fa-chalkboard-teacher"></i> <span id="moreTeachers">Teachers</span></a></li>
            <li><a href="admin_staff.php"><i class="fas fa-user-tie"></i> <span id="moreStaff">Staff</span></a></li>
            <li><a href="admin_classes.php"><i class="fas fa-chalkboard"></i> <span id="moreClasses">Classes</span></a></li>
            <li><a href="admin_subjects.php"><i class="fas fa-book"></i> <span id="moreSubjects">Subjects</span></a></li>
            <li><a href="admin_exams.php"><i class="fas fa-file-alt"></i> <span id="moreExams">Exams</span></a></li>
            <li><a href="admin_reports_printouts.php"><i class="fas fa-print"></i> <span id="morePrintouts">Reports</span></a></li>
            <li><a href="admin_system_settings.php"><i class="fas fa-cog"></i> <span id="moreSettings">Settings</span></a></li>
            <li class="logout"><a href="logout.php"><i class="fas fa-sign-out-alt"></i> <span id="moreLogout">Logout</span></a></li>
        </ul>
    </div>

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

    <script>
        // ===================================
        // JAVASCRIPT FOR UI FUNCTIONALITY
        // ===================================

        // --- Mobile More Menu Modal Logic (IMMEDIATE EXECUTION) ---
        console.log('🚀 Initializing mobile footer...');
        
        function initializeMobileFooter() {
            const moreMenuBtn = document.getElementById('moreMenuButton');
            const moreMenuModal = document.getElementById('more-menu-modal');
            const moreMenuCloseBtn = document.getElementById('more-menu-close-btn');
            const overlay = document.getElementById('overlay');

            console.log('📋 Elements found:', {
                moreMenuBtn: !!moreMenuBtn,
                moreMenuModal: !!moreMenuModal,
                moreMenuCloseBtn: !!moreMenuCloseBtn,
                overlay: !!overlay
            });

            function toggleMoreMenu() {
                console.log('🔄 toggleMoreMenu called');
                if (moreMenuModal && overlay) {
                    const wasShowing = moreMenuModal.classList.contains('show');
                    moreMenuModal.classList.toggle('show');
                    overlay.classList.toggle('show');
                    console.log(`📱 Modal ${wasShowing ? 'was' : 'was not'} showing, now ${moreMenuModal.classList.contains('show') ? 'is' : 'is not'} showing`);
                } else {
                    console.error('❌ Modal or overlay not found!');
                }
            }

            if (moreMenuBtn) {
                console.log('✅ Adding click listener to More button');
                moreMenuBtn.addEventListener('click', function(e) {
                    console.log('🖱️ MORE BUTTON CLICKED!');
                    e.preventDefault();
                    e.stopPropagation();
                    toggleMoreMenu();
                });
            } else {
                console.error('❌ More menu button not found!');
            }
            
            if (moreMenuCloseBtn) {
                console.log('✅ Adding click listener to Close button');
                moreMenuCloseBtn.addEventListener('click', function(e) {
                    console.log('🖱️ Close button clicked');
                    e.preventDefault();
                    e.stopPropagation();
                    toggleMoreMenu();
                });
            }
            
            if (overlay) {
                console.log('✅ Adding click listener to Overlay');
                overlay.addEventListener('click', function(e) {
                    console.log('🖱️ Overlay clicked');
                    e.preventDefault();
                    e.stopPropagation();
                    toggleMoreMenu();
                });
            }

            console.log('🎯 Mobile footer initialization complete!');
        }

        // Try to initialize immediately
        if (document.getElementById('moreMenuButton')) {
            initializeMobileFooter();
        } else {
            // Fallback: wait for DOM if elements not ready
            document.addEventListener('DOMContentLoaded', initializeMobileFooter);
        }

        // --- Other UI functionality (WAIT FOR DOM) ---
        document.addEventListener('DOMContentLoaded', function() {
            const sidebar = document.getElementById('sidebar');
            const menuToggle = document.getElementById('menuToggle');
            const dashboardContainer = document.getElementById('dashboardContainer');
            
            // === Handle Subject Combination field visibility for Add Student Form ===
            const addClassSelect = document.getElementById('student_class_id');
            const addSubjectCombGroup = document.getElementById('add_subject_combination_group');
            
            if (addClassSelect && addSubjectCombGroup) {
                addClassSelect.addEventListener('change', function() {
                    const selectedClassId = this.value;
                    const selectedOption = this.options[this.selectedIndex];
                    const className = selectedOption.text;
                    
                    // Check if the selected class is A'Level (Senior 5 or Senior 6) - comprehensive check
                    // This will match various formats: "Senior 5", "SENIOR 5", "S5", "s5", "Senior 5A", "senior 6", "S6", etc.
                    const classNameLower = className.toLowerCase();
                    const classNameUpper = className.toUpperCase();
                    
                    const isALevel = classNameLower.includes('senior 5') || 
                                   classNameUpper.includes('SENIOR 5') ||
                                   classNameLower.includes('s5') || 
                                   classNameUpper.includes('S5') ||
                                   classNameLower.includes('senior 6') || 
                                   classNameUpper.includes('SENIOR 6') ||
                                   classNameLower.includes('s6') || 
                                   classNameUpper.includes('S6') ||
                                   classNameLower.includes('a level') ||
                                   classNameUpper.includes('A LEVEL') ||
                                   classNameLower.includes('a\'level') ||
                                   classNameUpper.includes('A\'LEVEL') ||
                                   classNameLower.includes('advanced') ||
                                   classNameUpper.includes('ADVANCED');
                    
                    addSubjectCombGroup.style.display = isALevel ? 'block' : 'none';
                    
                    // Clear the selection when hiding the dropdown
                    if (!isALevel) {
                        document.getElementById('student_combination_id').value = '0';
                    }
                });
            }
            
            // === Handle Subject Combination field visibility for Edit Student Form ===
            const editClassSelect = document.getElementById('edit_student_class_id');
            const editSubjectCombGroup = document.getElementById('edit_subject_combination_group');
            
            if (editClassSelect && editSubjectCombGroup) {
                editClassSelect.addEventListener('change', function() {
                    const selectedClassId = this.value;
                    const selectedOption = this.options[this.selectedIndex];
                    const className = selectedOption.text;
                    
                    // Check if the selected class is A'Level (Senior 5 or Senior 6) - comprehensive check
                    // This will match various formats: "Senior 5", "SENIOR 5", "S5", "s5", "Senior 5A", "senior 6", "S6", etc.
                    const classNameLower = className.toLowerCase();
                    const classNameUpper = className.toUpperCase();
                    
                    const isALevel = classNameLower.includes('senior 5') || 
                                   classNameUpper.includes('SENIOR 5') ||
                                   classNameLower.includes('s5') || 
                                   classNameUpper.includes('S5') ||
                                   classNameLower.includes('senior 6') || 
                                   classNameUpper.includes('SENIOR 6') ||
                                   classNameLower.includes('s6') || 
                                   classNameUpper.includes('S6') ||
                                   classNameLower.includes('a level') ||
                                   classNameUpper.includes('A LEVEL') ||
                                   classNameLower.includes('a\'level') ||
                                   classNameUpper.includes('A\'LEVEL') ||
                                   classNameLower.includes('advanced') ||
                                   classNameUpper.includes('ADVANCED');
                    
                    editSubjectCombGroup.style.display = isALevel ? 'block' : 'none';
                    
                    // Clear the selection when hiding the dropdown
                    if (!isALevel) {
                        document.getElementById('edit_student_combination_id').value = '0';
                    }
                });
            }
            
            // --- 1. Sidebar Toggle (Primarily for Tablet/Desktop on smaller screens) ---
            if (menuToggle) {
                menuToggle.addEventListener('click', function() {
                    sidebar.classList.toggle('collapsed');
                    dashboardContainer.classList.toggle('sidebar-collapsed');
                });
            }

            // --- 2. Auto-fade messages after 4 seconds ---
            const messageElement = document.getElementById('php-message');
            const errorElement = document.getElementById('php-error');
            
            function fadeOutMessage(element) {
                if (element) {
                    setTimeout(function() {
                        element.classList.add('fade-out');
                        // Remove the element from DOM after animation completes
                        setTimeout(function() {
                            if (element.parentNode) {
                                element.parentNode.removeChild(element);
                            }
                        }, 500); // Wait for CSS transition to complete
                    }, 4000); // 4 seconds delay
                }
            }
            
            // Apply fade-out to success messages
            fadeOutMessage(messageElement);
            
            // Apply fade-out to error messages
            fadeOutMessage(errorElement);
        });

        // Modal functions for edit/delete operations
        function openModal(modalId) {
            document.getElementById(modalId).style.display = 'block';
        }

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

        function openEditModal(studentData) {
            // Populate hidden ID fields
            document.getElementById('edit_user_id').value = studentData.user_id;

            // Populate text fields
            document.getElementById('edit_student_name').value = studentData.username;
            document.getElementById('edit_student_adm').value = studentData.adm;
            document.getElementById('edit_student_email').value = studentData.email;
            document.getElementById('edit_student_phone').value = studentData.phone;
            document.getElementById('edit_parent_name').value = studentData.parent_name;
            document.getElementById('edit_parent_phone').value = studentData.parent_phone;
            document.getElementById('edit_student_status').value = studentData.status;
            document.getElementById('edit_student_combination_id').value = studentData.combination_id || '0';

            // Populate dropdowns (Class and Stream)
            document.getElementById('edit_student_class_id').value = studentData.class_id || 0;
            document.getElementById('edit_student_stream_id').value = studentData.stream_id || 0;

            // Show/hide subject combination based on class
            const className = studentData.class_name || '';
            const isALevel = className.toLowerCase().includes('senior 5') || className.toLowerCase().includes('senior 6');
            const subjectCombGroup = document.getElementById('edit_subject_combination_group');
            if (subjectCombGroup) {
                subjectCombGroup.style.display = isALevel ? 'block' : 'none';
            }
            
            // Clear selection if not A'Level class
            if (!isALevel && subjectCombGroup) {
                document.getElementById('edit_student_combination_id').value = '0';
            }

            // Photo management
            document.getElementById('edit_current_photo_path').value = studentData.photo;
            document.getElementById('edit_current_photo_preview').src = studentData.photo;

            openModal('editStudentModal');
        }

        function openDeleteModal(userId, username, photoPath) {
            document.getElementById('delete_user_id_input').value = userId;
            document.getElementById('delete_photo_path_input').value = photoPath;
            document.getElementById('delete_student_name').textContent = username;
            openModal('deleteStudentModal');
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            if (event.target && event.target.classList && event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        };

        // === Language Selection Functionality ===
        const languageSelect = document.getElementById('languageSelect');
        
        // Language translations
        const translations = {
            'en': {
                'searchPlaceholder': 'Search students/data',
                'addNewStudent': 'Add New Student',
                'editStudent': 'Edit Student',
                'deleteStudent': 'Delete Student',
                'studentName': 'Student Name',
                'admissionNumber': 'Admission Number',
                'emailAddress': 'Email Address',
                'phoneNumber': 'Phone Number',
                'parentName': 'Parent Name',
                'parentPhone': 'Parent Phone',
                'studentStatus': 'Student Status',
                'actions': 'Actions',
                'viewDetails': 'View Details',
                'downloadReport': 'Download Report',
                // Form elements
                'addStudentHeading': 'Add New Student',
                'editStudentHeading': 'Edit Student Details',
                'currentPhotoLabel': 'Current Photo:',
                'studentNameLabel': 'Full Name *',
                'admissionNumberLabel': 'Admission Number *',
                'emailAddressLabel': 'Email Address *',
                'passwordLabel': 'Temporary Password *',
                'phoneNumberLabel': 'Phone Number',
                'parentDetailsHeading': 'Parent Details:',
                'editParentDetailsHeading': 'Parent Details:',
                'parentNameLabel': 'Parent Name',
                'parentPhoneLabel': 'Parent Phone',
                'classLabel': 'Class *',
                'streamLabel': 'Stream (Optional)',
                'subjectCombinationLabel': 'Subject Combination (A\'Level Only)',
                'photoUploadLabel': 'Student Photo (Max 5MB)',
                'editPhotoLabel': 'Change Photo (Max 5MB)',
                'statusLabel': 'Account Status *',
                // Button text
                'addStudentButton': 'Add Student',
                'saveChangesButton': 'Save Changes',
                // Select options
                'selectClassOption': '-- Select Class --',
                'selectStreamOption': '-- Select Stream --',
                'addSelectStreamOption': '-- Select Stream --',
                'selectCombinationOption': 'Select Subject Combination',
                'addSelectCombinationOption': 'Select Subject Combination',
                'editSelectCombinationOption': 'Select Subject Combination',
                'activeOption': 'Active',
                'inactiveOption': 'Inactive',
                'suspendedOption': 'Suspended',
                // Table headers and main text
                'currentStudentsHeading': 'Current Students',
                'admHeader': 'ADM',
                'photoHeader': 'Photo',
                'nameHeader': 'Name',
                'emailHeader': 'Email',
                'classStreamHeader': 'Class / Stream',
                'subjectCombinationHeader': 'Subject Combination',
                'parentHeader': 'Parent (Name / Phone)',
                'statusHeader': 'Status',
                'actionsHeader': 'Actions',
                // Sidebar navigation
                'dashboardLink': 'Dashboard',
                'calendarLink': 'Calendar',
                'usersLink': 'Users',
                'studentsLink': 'Students',
                'teachersLink': 'Teachers',
                'classesLink': 'Classes',
                'subjectsLink': 'Subjects',
                'examsLink': 'Exams',
                'messagesLinkSidebar': 'Messages',
                'printoutsLink': 'Printouts',
                'systemSettingsLink': 'Settings',
                'logoutLinkSidebar': 'Logout',
                'footerDashboard': 'Dashboard',
                'moreStudents': 'Students',
                'moreStaff': 'Staff',
                'footerUsers': 'Users',
                'footerStudents': 'Students',
                'footerMore': 'More',
                'moreMenuTitle': 'More Options',
                'moreTeachers': 'Teachers',
                'moreClasses': 'Classes',
                'moreSubjects': 'Subjects',
                'moreExams': 'Exams',
                'moreMessages': 'Messages',
                'morePrintouts': 'Printouts',
                'moreSettings': 'Settings',
                'moreLogout': 'Logout'
            },
            'lg': {
                'searchPlaceholder': 'Noongoza abafunsi/eddala',
                'addNewStudent': 'Ongeza Omufunsi Omupya',
                'editStudent': 'Ggyako ku Mufunsi',
                'deleteStudent': 'Lekawo Omufunsi',
                'studentName': 'Erinnya lya Mufunsi',
                'admissionNumber': 'Namba y\'Okukyalira',
                'emailAddress': 'Addressi ya Email',
                'phoneNumber': 'Namba ya Telefoni',
                'parentName': 'Erinnya lya Kitaffe/ma',
                'parentPhone': 'Telefoni ya Kitaffe/ma',
                'studentStatus': 'Enkyukakyuka za Mufunsi',
                'actions': 'Ebikolwa',
                'viewDetails': 'Laba detalze',
                'downloadReport': 'Kussa Report',
                // Form elements
                'addStudentHeading': 'Ongeza Omufunsi Omupya',
                'editStudentHeading': 'Ggyako Detalze za Mufunsi',
                'currentPhotoLabel': 'Ekifaananyi ekikyali:',
                'studentNameLabel': 'Erinnya Eyoza *',
                'admissionNumberLabel': 'Namba y\'Okukyalira *',
                'emailAddressLabel': 'Addressi ya Email *',
                'passwordLabel': 'Password ya Mutegekedde *',
                'phoneNumberLabel': 'Namba ya Telefoni',
                'parentDetailsHeading': 'Detalze za Kitaffe/ma:',
                'editParentDetailsHeading': 'Detalze za Kitaffe/ma:',
                'parentNameLabel': 'Erinnya lya Kitaffe/ma',
                'parentPhoneLabel': 'Telefoni ya Kitaffe/ma',
                'classLabel': 'Ekikole *',
                'streamLabel': 'Okuvaamu (Bikyamufunye)',
                'subjectCombinationLabel': 'Okusomya ku A\'Level',
                'photoUploadLabel': 'Ekifaananyi kya Mufunsi (Enene 5MB)',
                'editPhotoLabel': 'Gyako Ekifaananyi (Enene 5MB)',
                'statusLabel': 'Enkyukakyuka za Account *',
                // Button text
                'addStudentButton': 'Ongeza Mufunsi',
                'saveChangesButton': 'Gwamba Enkyukakyuka',
                // Select options
                'selectClassOption': '-- Yegula Ekikole --',
                'selectStreamOption': '-- Yegula Okuvaamu --',
                'addSelectStreamOption': '-- Yegula Okuvaamu --',
                'selectCombinationOption': 'Yegula Okusomya',
                'addSelectCombinationOption': 'Yegula Okusomya',
                'editSelectCombinationOption': 'Yegula Okusomya',
                'activeOption': 'Mu Munda',
                'inactiveOption': 'Tewunze',
                'suspendedOption': 'Wunyiziddwa',
                // Table headers and main text
                'currentStudentsHeading': 'Abafunsi Abakyali',
                'admHeader': 'Namba',
                'photoHeader': 'Ekifaananyi',
                'nameHeader': 'Erinnya',
                'emailHeader': 'Email',
                'classStreamHeader': 'Ekikole / Okuvaamu',
                'subjectCombinationHeader': 'Okusomya',
                'parentHeader': 'Kitaffe/ma (Erinnya / Telefoni)',
                'statusHeader': 'Enkyukakyuka',
                'actionsHeader': 'Ebikolwa',
                // Sidebar navigation
                'dashboardLink': 'Dashboard',
                'calendarLink': 'Kalenda',
                'usersLink': 'Abakozi',
                'studentsLink': 'Abafunsi',
                'teachersLink': 'Abafundisi',
                'classesLink': 'Ebikole',
                'subjectsLink': 'Obuneggero',
                'examsLink': 'Okulaga',
                'messagesLinkSidebar': 'Ebikwatanirizo',
                'printoutsLink': 'Okukoppa',
                'systemSettingsLink': 'Enkyukakyuka',
                'logoutLinkSidebar': 'Okuvaamu',
                'footerDashboard': 'Dashboard',
                'moreStudents': 'Abafunsi',
                'moreStaff': 'Abakozi',
                'footerUsers': 'Abakozi',
                'footerStudents': 'Abafunsi',
                'footerMore': 'Binenjawulo',
                'moreMenuTitle': 'Binenjawulo',
                'moreTeachers': 'Abafundisi',
                'moreClasses': 'Ebikole',
                'moreSubjects': 'Obuneggero',
                'moreExams': 'Okulaga',
                'moreMessages': 'Ebikwatanirizo',
                'morePrintouts': 'Okukoppa',
                'moreSettings': 'Enkyukakyuka',
                'moreLogout': 'Okuvaamu'
            },
            'sw': {
                'searchPlaceholder': 'Tafuta wanafunzi/matendo',
                'addNewStudent': 'Ongeza Mwanafunzi Mpya',
                'editStudent': 'Hariri Mwanafunzi',
                'deleteStudent': 'Futa Mwanafunzi',
                'studentName': 'Jina la Mwanafunzi',
                'admissionNumber': 'Nambari ya Kuingia',
                'emailAddress': 'Barua pepe',
                'phoneNumber': 'Nambari ya Simu',
                'parentName': 'Jina la Mzazi',
                'parentPhone': 'Simu ya Mzazi',
                'studentStatus': 'Hali ya Mwanafunzi',
                'actions': 'Vitendo',
                'viewDetails': 'Angalia Maelezo',
                'downloadReport': 'Pakua Ripoti',
                // Form elements
                'addStudentHeading': 'Ongeza Mwanafunzi Mpya',
                'editStudentHeading': 'Hariri Maelezo ya Mwanafunzi',
                'currentPhotoLabel': 'Picha ya Sasa:',
                'studentNameLabel': 'Jina Kamili *',
                'admissionNumberLabel': 'Nambari ya Kuingia *',
                'emailAddressLabel': 'Barua pepe *',
                'passwordLabel': 'Nenosiri la Muda *',
                'phoneNumberLabel': 'Nambari ya Simu',
                'parentDetailsHeading': 'Maelezo ya Wazazi:',
                'editParentDetailsHeading': 'Maelezo ya Wazazi:',
                'parentNameLabel': 'Jina la Mzazi',
                'parentPhoneLabel': 'Simu ya Mzazi',
                'classLabel': 'Darasa *',
                'streamLabel': 'Kichwa (Si Lazima)',
                'subjectCombinationLabel': 'Mchanganyiko wa Masomo (A\'Level tu)',
                'photoUploadLabel': 'Picha ya Mwanafunzi (Kubwa 5MB)',
                'editPhotoLabel': 'Badilisha Picha (Kubwa 5MB)',
                'statusLabel': 'Hali ya Akaunti *',
                // Button text
                'addStudentButton': 'Ongeza Mwanafunzi',
                'saveChangesButton': 'Hifadhi Mabadiliko',
                // Select options
                'selectClassOption': '-- Chagua Darasa --',
                'selectStreamOption': '-- Chagua Kichwa --',
                'addSelectStreamOption': '-- Chagua Kichwa --',
                'selectCombinationOption': 'Chagua Mchanganyiko wa Masomo',
                'addSelectCombinationOption': 'Chagua Mchanganyiko wa Masomo',
                'editSelectCombinationOption': 'Chagua Mchanganyiko wa Masomo',
                'activeOption': 'Neno',
                'inactiveOption': 'Si Neno',
                'suspendedOption': 'Imesimamishwa',
                // Table headers and main text
                'currentStudentsHeading': 'Wanafunzi wa Sasa',
                'admHeader': 'Nambari',
                'photoHeader': 'Picha',
                'nameHeader': 'Jina',
                'emailHeader': 'Barua pepe',
                'classStreamHeader': 'Darasa / Kichwa',
                'subjectCombinationHeader': 'Mchanganyiko wa Masomo',
                'parentHeader': 'Mzazi (Jina / Simu)',
                'statusHeader': 'Hali',
                'actionsHeader': 'Vitendo',
                // Sidebar navigation
                'dashboardLink': 'Dashibodi',
                'calendarLink': 'Kalenda',
                'usersLink': 'Watumiaji',
                'studentsLink': 'Wanafunzi',
                'teachersLink': 'Walimu',
                'classesLink': 'Madarasa',
                'subjectsLink': 'Masomo',
                'examsLink': 'Mitihani',
                'messagesLinkSidebar': 'Ujumbe',
                'printoutsLink': 'Matokeo',
                'systemSettingsLink': 'Mipangilio',
                'logoutLinkSidebar': 'Toka',
                'footerDashboard': 'Dashibodi',
                'moreStudents': 'Wanafunzi',
                'moreStaff': 'Wafanyakazi',
                'footerUsers': 'Watumiaji',
                'footerStudents': 'Wanafunzi',
                'footerMore': 'Zaidi',
                'moreMenuTitle': 'Chaguo zaidi',
                'moreTeachers': 'Walimu',
                'moreClasses': 'Madarasa',
                'moreSubjects': 'Masomo',
                'moreExams': 'Mitihani',
                'moreMessages': 'Ujumbe',
                'morePrintouts': 'Matokeo',
                'moreSettings': 'Mipangilio',
                'moreLogout': 'Toka'
            }
        };
        
        // Function to update all page text
        function updatePageLanguage(language) {
            const trans = translations[language] || translations['en'];
            
            // Update all elements with translatable IDs
            Object.keys(trans).forEach(key => {
                const element = document.getElementById(key);
                if (element) {
                    if (key === 'searchPlaceholder') {
                        element.placeholder = trans[key];
                    } else if (element.tagName === 'A') {
                        // For sidebar links, update the text after the icon
                        const icon = element.querySelector('i');
                        if (icon) {
                            element.innerHTML = icon.outerHTML + ' ' + trans[key];
                        } else {
                            element.textContent = trans[key];
                        }
                    } else if (element.tagName === 'BUTTON') {
                        // For buttons, preserve the icon and update text
                        const icon = element.querySelector('i');
                        if (icon) {
                            // Extract the text from the button (excluding the icon)
                            const textNode = Array.from(element.childNodes).find(node => 
                                node.nodeType === Node.TEXT_NODE && node.textContent.trim()
                            );
                            if (textNode) {
                                // Preserve the icon and update the text
                                element.innerHTML = icon.outerHTML + ' ' + trans[key];
                            } else {
                                element.textContent = trans[key];
                            }
                        } else {
                            element.textContent = trans[key];
                        }
                    } else if (element.tagName === 'LABEL') {
                        // For labels, check if they contain required asterisk
                        if (element.textContent.includes('*')) {
                            element.textContent = trans[key] + ' *';
                        } else {
                            element.textContent = trans[key];
                        }
                    } else if (element.tagName === 'OPTION') {
                        // For select options
                        element.textContent = trans[key];
                    } else {
                        element.textContent = trans[key];
                    }
                }
            });
            
            // Update mobile footer and more menu
            updateMobileFooterLanguage(language);
        }
        
        // Function to update mobile footer language
        function updateMobileFooterLanguage(language) {
            const trans = translations[language] || translations['en'];
            
            // Update mobile footer
            const footerElements = ['footerDashboard', 'footerUsers', 'footerStudents', 'footerMore'];
            footerElements.forEach(id => {
                const element = document.getElementById(id);
                if (element && trans[id]) {
                    element.textContent = trans[id];
                }
            });
            
            // Update more menu
            const moreElements = ['moreMenuTitle', 'moreStudents', 'moreTeachers', 'moreStaff', 'moreClasses', 'moreSubjects', 'moreExams', 'morePrintouts', 'moreSettings', 'moreLogout'];
            moreElements.forEach(id => {
                const element = document.getElementById(id);
                if (element && trans[id]) {
                    element.textContent = trans[id];
                }
            });
        }
        
        // Language selection event listener
        if (languageSelect) {
            languageSelect.addEventListener('change', function() {
                const selectedLanguage = this.value;
                
                // Update all page text
                updatePageLanguage(selectedLanguage);
                
                // Store language preference in localStorage
                localStorage.setItem('selectedLanguage', selectedLanguage);
            });
            
            // Load saved language preference
            const savedLanguage = localStorage.getItem('selectedLanguage') || 'en';
            languageSelect.value = savedLanguage;
            updatePageLanguage(savedLanguage);
        }

        // Debug: Log form submission
        document.addEventListener('submit', function(e) {
            console.log('FORM SUBMITTED:', e.target);
        });

    </script>

</body>
</html>