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

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

// Get current user and school details from session
$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]);
$user_role_code = $_SESSION["role"];
$current_user_school_id = $_SESSION["school_id"];

// Initialize school variables
$school_name = "School Name Not Found";
$school_logo_path = "images/default_school_logo.png";

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

// Initialize user photo
$photo = "images/default_profile.png";

// Fetch school name and logo
if (isset($conn) && $conn instanceof mysqli) {
    $sql_school = "SELECT school_name, logo FROM schools WHERE school_id = ?";
    if ($stmt_school = $conn->prepare($sql_school)) {
        $stmt_school->bind_param("i", $current_user_school_id);
        if ($stmt_school->execute()) {
            $stmt_school->bind_result($school_name_db, $school_logo_db);
            if ($stmt_school->fetch()) {
                $school_name = htmlspecialchars($school_name_db);
                $school_logo_path = !empty($school_logo_db) ? htmlspecialchars($school_logo_db) : 'images/default_school_logo.png';
            }
        } else {
            error_log("Failed to execute school data query: " . $stmt_school->error);
        }
        $stmt_school->close();
    } else {
        error_log("Database connection \$conn not available in admin_classes.php");
    }
} else {
    error_log("Database connection \$conn not available in admin_classes.php");
}

// --- Handle Class Management Actions ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $action = $_POST['action'] ?? '';

    switch ($action) {
        case 'add_class':
            $class_name = trim($_POST['class_name'] ?? '');
            if (!empty($class_name)) {
                $sql = "INSERT INTO classes (school_id, class_name) VALUES (?, ?)";
                if ($stmt = $conn->prepare($sql)) {
                    $stmt->bind_param("is", $current_user_school_id, $class_name);
                    if ($stmt->execute()) {
                        $message = "Class added successfully."; // Modified message
                        $message_type = "success";
                    } else {
                        // Check for duplicate entry error (MySQL error code 1062)
                        if ($conn->errno == 1062) {
                            $message = "Error: A class with the name '{$class_name}' already exists for your school.";
                        } else {
                            $message = "Error adding class: " . $stmt->error;
                        }
                        $message_type = "error";
                    }
                    $stmt->close();
                } else {
                    $message = "Database error: Could not prepare statement for adding class.";
                    $message_type = "error";
                }
            } else {
                $message = "Class name cannot be empty.";
                $message_type = "error";
            }
            break;

        case 'edit_class':
            $class_id = intval($_POST['edit_class_id'] ?? 0);
            $class_name = trim($_POST['edit_class_name'] ?? '');
            if ($class_id > 0 && !empty($class_name)) {
                $sql = "UPDATE classes SET class_name = ? WHERE class_id = ? AND school_id = ?";
                if ($stmt = $conn->prepare($sql)) {
                    $stmt->bind_param("sii", $class_name, $class_id, $current_user_school_id);
                    if ($stmt->execute()) {
                        if ($stmt->affected_rows > 0) {
                            $message = "Class updated successfully.";
                            $message_type = "success";
                        } else {
                            $message = "No changes made or class not found/owned by your school.";
                            $message_type = "error";
                        }
                    } else {
                        if ($conn->errno == 1062) {
                            $message = "Error: A class with the name '{$class_name}' already exists for your school.";
                        } else {
                            $message = "Error updating class: " . $stmt->error;
                        }
                        $message_type = "error";
                    }
                    $stmt->close();
                } else {
                    $message = "Database error: Could not prepare statement for editing class.";
                    $message_type = "error";
                }
            } else {
                $message = "Invalid class ID or class name.";
                $message_type = "error";
            }
            break;

        case 'delete_class':
            $class_id = intval($_POST['delete_class_id'] ?? 0);
            if ($class_id > 0) {
                // The SQL schema has ON DELETE CASCADE for related tables, which simplifies deletion.
                // We just need to delete the class itself.
                $sql = "DELETE FROM classes WHERE class_id = ? AND school_id = ?";
                if ($stmt = $conn->prepare($sql)) {
                    $stmt->bind_param("ii", $class_id, $current_user_school_id);
                    if ($stmt->execute()) {
                        if ($stmt->affected_rows > 0) {
                            $message = "Class deleted successfully.";
                            $message_type = "success";
                        } else {
                            $message = "Class not found or not owned by your school.";
                            $message_type = "error";
                        }
                    } else {
                        $message = "Error deleting class: " . $stmt->error;
                        $message_type = "error";
                    }
                    $stmt->close();
                } else {
                    $message = "Database error: Could not prepare statement for deleting class.";
                    $message_type = "error";
                }
            } else {
                $message = "Invalid class ID for deletion.";
                $message_type = "error";
            }
            break;

        case 'add_stream':
            $class_id = intval($_POST['stream_class_id'] ?? 0);
            $stream_name = trim($_POST['new_stream_name'] ?? '');
            if (!empty($stream_name)) { // Simplified condition, class ID check is done below
                // Check if the class belongs to the current school
                $check_class_sql = "SELECT class_id FROM classes WHERE class_id = ? AND school_id = ?";
                if ($check_stmt = $conn->prepare($check_class_sql)) {
                    $check_stmt->bind_param("ii", $class_id, $current_user_school_id);
                    $check_stmt->execute();
                    $check_stmt->store_result();
                    if ($check_stmt->num_rows === 0) {
                        $message = "Error: Selected class does not exist or is not associated with your school.";
                        $message_type = "error";
                        $check_stmt->close();
                        break;
                    }
                    $check_stmt->close();
                } else {
                    $message = "Database error: Could not prepare class check statement.";
                    $message_type = "error";
                    break;
                }

                $sql = "INSERT INTO streams (school_id, class_id, stream_name) VALUES (?, ?, ?)";
                if ($stmt = $conn->prepare($sql)) {
                    $stmt->bind_param("iis", $current_user_school_id, $class_id, $stream_name);
                    if ($stmt->execute()) {
                        $message = "Stream added successfully."; // Modified message
                        $message_type = "success";
                    } else {
                        if ($conn->errno == 1062) {
                            $message = "Error: Stream '{$stream_name}' already exists for this class.";
                        } else {
                            $message = "Error adding stream: " . $stmt->error;
                        }
                        $message_type = "error";
                    }
                    $stmt->close();
                } else {
                    $message = "Database error: Could not prepare statement for adding stream.";
                    $message_type = "error";
                }
            } else {
                $message = "Invalid class or stream name.";
                $message_type = "error";
            }
            break;

        case 'assign_class_teacher':
            $class_id = intval($_POST['class_id'] ?? 0);
            $teacher_user_id = trim($_POST['teacher_user_id'] ?? 'none'); // 'none' if no teacher selected

            if ($class_id > 0) {
                // Check if the class belongs to the current school
                $check_class_sql = "SELECT class_id FROM classes WHERE class_id = ? AND school_id = ?";
                if ($check_stmt = $conn->prepare($check_class_sql)) {
                    $check_stmt->bind_param("ii", $class_id, $current_user_school_id);
                    $check_stmt->execute();
                    $check_stmt->store_result();
                    if ($check_stmt->num_rows === 0) {
                        $message = "Error: Selected class does not exist or is not associated with your school.";
                        $message_type = "error";
                        $check_stmt->close();
                        break;
                    }
                    $check_stmt->close();
                } else {
                    $message = "Database error: Could not prepare class check statement.";
                    $message_type = "error";
                    break;
                }

                if ($teacher_user_id === 'none') {
                    // Remove existing class teacher assignment
                    $sql = "DELETE FROM class_teachers WHERE class_id = ?";
                    if ($stmt = $conn->prepare($sql)) {
                        $stmt->bind_param("i", $class_id);
                        if ($stmt->execute()) {
                            $message = "Class teacher removed successfully."; // Modified message
                            $message_type = "success";
                        } else {
                            $message = "Error removing class teacher: " . $stmt->error;
                            $message_type = "error";
                        }
                        $stmt->close();
                    } else {
                        $message = "Database error: Could not prepare statement for removing class teacher.";
                        $message_type = "error";
                    }
                } else {
                    $teacher_user_id = intval($teacher_user_id);
                    // Check if teacher exists and belongs to the school (optional but good for integrity)
                    $check_teacher_sql = "SELECT id FROM users WHERE id = ? AND school_id = ? AND role = " . ROLE_TEACHER;
                    if ($check_stmt = $conn->prepare($check_teacher_sql)) {
                        $check_stmt->bind_param("ii", $teacher_user_id, $current_user_school_id);
                        $check_stmt->execute();
                        $check_stmt->store_result();
                        if ($check_stmt->num_rows === 0) {
                            $message = "Error: Selected teacher does not exist or is not associated with your school.";
                            $message_type = "error";
                            $check_stmt->close();
                            break;
                        }
                        $check_stmt->close();
                    } else {
                        $message = "Database error: Could not prepare teacher check statement.";
                        $message_type = "error";
                        break;
                    }

                    // Insert or update class_teachers table
                    $sql = "INSERT INTO class_teachers (class_id, teacher_user_id) VALUES (?, ?)
                            ON DUPLICATE KEY UPDATE teacher_user_id = VALUES(teacher_user_id)";
                    if ($stmt = $conn->prepare($sql)) {
                        $stmt->bind_param("ii", $class_id, $teacher_user_id);
                        if ($stmt->execute()) {
                            $message = "Class teacher assigned successfully."; // Modified message
                            $message_type = "success";
                        } else {
                            $message = "Error assigning class teacher: " . $stmt->error;
                            $message_type = "error";
                        }
                        $stmt->close();
                    } else {
                        $message = "Database error: Could not prepare statement for assigning class teacher.";
                        $message_type = "error";
                    }
                }
            } else {
                $message = "Invalid class ID for teacher assignment.";
                $message_type = "error";
            }
            break;

        case 'assign_class_subjects':
            $class_id = intval($_POST['class_id'] ?? 0);
            $selected_subjects = $_POST['selected_subjects'] ?? []; // Array of subject_ids

            if ($class_id > 0) {
                // Check if the class belongs to the current school
                $check_class_sql = "SELECT class_id FROM classes WHERE class_id = ? AND school_id = ?";
                if ($check_stmt = $conn->prepare($check_class_sql)) {
                    $check_stmt->bind_param("ii", $class_id, $current_user_school_id);
                    $check_stmt->execute();
                    $check_stmt->store_result();
                    if ($check_stmt->num_rows === 0) {
                        $message = "Error: Selected class does not exist or is not associated with your school.";
                        $message_type = "error";
                        $check_stmt->close();
                        break;
                    }
                    $check_stmt->close();
                } else {
                    $message = "Database error: Could not prepare class check statement.";
                    $message_type = "error";
                    break;
                }

                // Start transaction
                $conn->begin_transaction();
                try {
                    // 1. Delete existing subjects for this class
                    $sql_delete = "DELETE FROM class_subjects WHERE class_id = ?";
                    if ($stmt_delete = $conn->prepare($sql_delete)) {
                        $stmt_delete->bind_param("i", $class_id);
                        $stmt_delete->execute();
                        $stmt_delete->close();
                    } else {
                        throw new Exception("Failed to prepare delete statement: " . $conn->error);
                    }

                    // 2. Insert new subject assignments
                    if (!empty($selected_subjects)) {
                        $sql_insert = "INSERT INTO class_subjects (class_id, subject_id) VALUES (?, ?)";
                        if ($stmt_insert = $conn->prepare($sql_insert)) {
                            foreach ($selected_subjects as $subject_id) {
                                $subject_id = intval($subject_id);
                                $stmt_insert->bind_param("ii", $class_id, $subject_id);
                                $stmt_insert->execute();
                            }
                            $stmt_insert->close();
                        } else {
                            throw new Exception("Failed to prepare insert statement: " . $conn->error);
                        }
                    }
                    $conn->commit();
                    $message = "Class subjects updated successfully.";
                    $message_type = "success";
                } catch (Exception $e) {
                    $conn->rollback();
                    $message = "Error updating class subjects: " . $e->getMessage();
                    $message_type = "error";
                }
            } else {
                $message = "Invalid class ID for subject assignment.";
                $message_type = "error";
            }
            break;

        case 'save_subject_teachers':
            $class_id = intval($_POST['class_id'] ?? 0);
            $selected_stream_id = intval($_POST['selected_stream'] ?? 0);
            $subject_assignments_json = $_POST['subject_assignments'] ?? '[]';
            $subject_assignments = json_decode($subject_assignments_json, true);

            if ($class_id > 0 && $selected_stream_id > 0 && is_array($subject_assignments)) {
                // Check if the class and stream belong to the current school
                $check_class_stream_sql = "SELECT s.stream_id FROM streams s JOIN classes c ON s.class_id = c.class_id WHERE s.stream_id = ? AND c.class_id = ? AND c.school_id = ?";
                if ($check_stmt = $conn->prepare($check_class_stream_sql)) {
                    $check_stmt->bind_param("iii", $selected_stream_id, $class_id, $current_user_school_id);
                    $check_stmt->execute();
                    $check_stmt->store_result();
                    if ($check_stmt->num_rows === 0) {
                        $message = "Error: Selected stream or class does not exist or is not associated with your school.";
                        $message_type = "error";
                        $check_stmt->close();
                        break;
                    }
                    $check_stmt->close();
                } else {
                    $message = "Database error: Could not prepare class/stream check statement.";
                    $message_type = "error";
                    break;
                }

                // Get current academic year and term (for class_subject_teachers table)
                // You might need a more robust way to get the current academic year/term
                // For now, let's use a simple approach or default values
                $current_academic_year = date('Y'); // Example: current year
                $current_term = "Term 1"; // Example: default term

                // Fetch current academic year and term from academic_years_terms table
                $sql_academic_term = "SELECT academic_year, term_name FROM academic_years_terms WHERE school_id = ? ORDER BY id DESC LIMIT 1";
                if ($stmt_academic_term = $conn->prepare($sql_academic_term)) {
                    $stmt_academic_term->bind_param("i", $current_user_school_id);
                    $stmt_academic_term->execute();
                    $stmt_academic_term->bind_result($fetched_year, $fetched_term);
                    if ($stmt_academic_term->fetch()) {
                        $current_academic_year = $fetched_year;
                        $current_term = $fetched_term;
                    }
                    $stmt_academic_term->close();
                } else {
                    error_log("Failed to fetch current academic year/term: " . $conn->error);
                }


                $conn->begin_transaction();
                try {
                    // Delete ALL existing subject teacher assignments for this class and stream
                    // This prevents duplicate key errors from old academic year/term records
                    $sql_delete = "DELETE FROM class_subject_teachers WHERE class_id = ? AND stream_id = ? AND school_id = ?";
                    if ($stmt_delete = $conn->prepare($sql_delete)) {
                        $stmt_delete->bind_param("iii", $class_id, $selected_stream_id, $current_user_school_id);
                        $stmt_delete->execute();
                        $stmt_delete->close();
                    } else {
                        throw new Exception("Failed to prepare delete subject teachers statement: " . $conn->error);
                    }

                    // Insert new assignments
                    $sql_insert = "INSERT INTO class_subject_teachers (class_id, subject_id, stream_id, academic_year, term, teacher_user_id, assignment_slot, school_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                    if ($stmt_insert = $conn->prepare($sql_insert)) {
                        foreach ($subject_assignments as $assignment) {
                            $subject_id = intval($assignment['subject_id']);
                            foreach ($assignment['teacher_user_ids'] as $slot => $teacher_user_id) {
                                $teacher_user_id = ($teacher_user_id === 'none') ? NULL : intval($teacher_user_id);
                                $assignment_slot = $slot + 1; // Slot 1, 2, 3

                                // Only insert if a teacher is actually selected
                                if ($teacher_user_id !== NULL) {
                                    $stmt_insert->bind_param("iiissiii", $class_id, $subject_id, $selected_stream_id, $current_academic_year, $current_term, $teacher_user_id, $assignment_slot, $current_user_school_id);
                                    $stmt_insert->execute();
                                }
                            }
                        }
                        $stmt_insert->close();
                    } else {
                        throw new Exception("Failed to prepare insert subject teachers statement: " . $conn->error);
                    }

                    $conn->commit();
                    $message = "Subject teachers assigned successfully for selected stream.";
                    $message_type = "success";
                } catch (Exception $e) {
                    $conn->rollback();
                    $message = "Error saving subject teachers: " . $e->getMessage();
                    $message_type = "error";
                }
            } else {
                $message = "Invalid data for subject teacher assignment.";
                $message_type = "error";
            }
            break;
    }
    
    // Check if this is an AJAX request
    $is_ajax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
    
    // For AJAX requests, return JSON response
    if ($is_ajax || (isset($_POST['ajax']) && $_POST['ajax'] === 'true')) {
        header('Content-Type: application/json');
        echo json_encode([
            'success' => $message_type === 'success',
            'message' => $message
        ]);
        exit();
    }
    
    // For regular form submissions, redirect to self to prevent form resubmission on refresh
    header("Location: admin_classes.php?message=" . urlencode($message) . "&type=" . urlencode($message_type));
    exit();
}

// Handle messages from redirection
if (isset($_GET['message']) && isset($_GET['type'])) {
    $message = htmlspecialchars($_GET['message']);
    $message_type = htmlspecialchars($_GET['type']);
}


// --- Fetch Data for Display ---
$allClassesData = [];
$allTeachersData = [];
$allSubjectsData = [];
$totalStudentsCount = 0;

if (isset($conn) && $conn instanceof mysqli) {
    // Fetch all classes with their assigned class teacher and student count
    // Modified to count from users table where role = 3 (students)
    $sql_classes = "
        SELECT
            c.class_id,
            c.class_name,
            COALESCE(u.username, 'N/A') AS class_teacher_name,
            ct.teacher_user_id AS class_teacher_id,
            (SELECT COUNT(usr.id) FROM users usr WHERE usr.role = 3 AND usr.class_id = c.class_id AND usr.school_id = c.school_id) AS student_count
        FROM
            classes c
        LEFT JOIN
            class_teachers ct ON c.class_id = ct.class_id
        LEFT JOIN
            users u ON ct.teacher_user_id = u.id
        WHERE
            c.school_id = ?
        ORDER BY
            c.class_name ASC";

    if ($stmt_classes = $conn->prepare($sql_classes)) {
        $stmt_classes->bind_param("i", $current_user_school_id);
        $stmt_classes->execute();
        $result_classes = $stmt_classes->get_result();
        while ($row = $result_classes->fetch_assoc()) {
            $allClassesData[] = $row;
            $totalStudentsCount += $row['student_count'];
        }
        $stmt_classes->close();
    } else {
        error_log("Failed to prepare classes query: " . $conn->error);
    }

    // Fetch all teachers for dropdowns (users with ROLE_TEACHER)
    $sql_teachers = "SELECT u.id, u.username FROM users u JOIN teachers t ON u.id = t.user_id WHERE u.school_id = ? AND u.role = " . ROLE_TEACHER . " ORDER BY u.username ASC";
    if ($stmt_teachers = $conn->prepare($sql_teachers)) {
        $stmt_teachers->bind_param("i", $current_user_school_id);
        $stmt_teachers->execute();
        $result_teachers = $stmt_teachers->get_result();
        while ($row = $result_teachers->fetch_assoc()) {
            $allTeachersData[] = $row;
        }
        $stmt_teachers->close();
    } else {
        error_log("Failed to prepare teachers query: " . $conn->error);
    }

    // Fetch all subjects for dropdowns
    $sql_subjects = "SELECT subject_id, subject_name FROM subjects WHERE school_id = ? ORDER BY subject_name ASC";
    if ($stmt_subjects = $conn->prepare($sql_subjects)) {
        $stmt_subjects->bind_param("i", $current_user_school_id);
        $stmt_subjects->execute();
        $result_subjects = $stmt_subjects->get_result();
        while ($row = $result_subjects->fetch_assoc()) {
            $allSubjectsData[] = $row;
        }
        $stmt_subjects->close();
    } else {
        error_log("Failed to prepare subjects query: " . $conn->error);
    }

    $conn->close();
}

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Classes - <?php echo $school_name; ?></title>
    <link rel="icon" href="<?php echo $school_logo_path; ?>" type="image/png">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="stylesheet" href="style.css">
    <style>
        :root {
            --primary-color: #2b2c2eff;
            --secondary-color: #6c757d;
            --success-color: #28a745;
            --warning-color: #ffc107;
            --danger-color: #dc3545;
            --light-color: #f8f9fa;
            --dark-color: #343a40;
            --sidebar-width: 280px;
            --header-height: 70px;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            color: #333;
            overflow-x: hidden;
        }

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

       
       
        .main-content {
            flex: 1;
            margin-left: 0;
            transition: margin-left 0.3s ease-in-out;
        }

        .header {
            background: white;
            height: var(--header-height);
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: fixed;
            top: 0;
            left: 5;
            right: 0;
            z-index: 999;
            transition: opacity 0.3s ease, visibility 0.3s ease;
        }

        .header.hide-header {
            opacity: 0;
            visibility: hidden;
        }

        .header .menu-toggle {
            background: none;
            border: none;
            font-size: 1.5rem;
            color: #333;
            cursor: pointer;
            padding: 0.5rem;
            border-radius: 5px;
            transition: background 0.3s ease;
        }

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

        .header .school-info {
            display: flex;
            align-items: center;
            gap: 38rem;
        }

        .header .school-info img {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            
        }

        .header .school-info h1 {
            font-size: 1.2rem;
            font-weight: 600;
            color: #333;
        }

        .header .header-right {
            display: flex;
            align-items: center;
            gap: 1.5rem;
        }

        .header .language-select select {
            padding: 0.5rem;
            border: 1px solid #ddd;
            border-radius: 5px;
            background: white;
            font-size: 0.9rem;
        }

        .header .search-bar {
            position: relative;
            display: flex;
            align-items: center;
        }

        .header .search-bar i {
            position: absolute;
            left: 1rem;
            color: #666;
        }

        .header .search-bar input {
            padding: 0.75rem 1rem 0.75rem 3rem;
            border: 1px solid #ddd;
            border-radius: 25px;
            width: 300px;
            font-size: 0.9rem;
            transition: border-color 0.3s ease;
        }

        .header .search-bar input:focus {
            outline: none;
            border-color: var(--primary-color);
        }

        .header .notifications {
            position: relative;
            cursor: pointer;
        }

        .header .notifications .badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background: var(--danger-color);
            color: white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            font-size: 0.75rem;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .header .user-profile {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            cursor: pointer;
            padding: 0.5rem;
            border-radius: 8px;
            transition: background 0.3s ease;
        }

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

        .header .user-profile img {
            width: 35px;
            height: 35px;
            border-radius: 50%;
        }

        .header .user-profile .user-name {
            font-weight: 500;
            color: #333;
        }

        .header .user-profile .user-email {
            font-size: 0.8rem;
            color: #666;
        }

        .dashboard-content {
            margin-top: var(--header-height);
            padding: 2rem;
            min-height: calc(100vh - var(--header-height));
            display: flex;
            flex-direction: column;
            align-items: center;
            max-width: 1400px;
            margin-left: auto;
            margin-right: auto;
            width: 100%;
        }

        /* Mobile Footer Navigation */
        .mobile-footer {
            display: none;
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            background: var(--primary-color);
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
            z-index: 1000;
            padding: 10px 0;
        }

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

        .mobile-footer nav li {
            text-align: center;
        }

        .mobile-footer nav a {
            display: flex;
            flex-direction: column;
            align-items: center;
            color: white;
            text-decoration: none;
            font-size: 0.8rem;
            padding: 5px;
            transition: opacity 0.3s ease;
        }

        .mobile-footer nav a:hover {
            opacity: 0.7;
        }

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

        /* Mobile "More" Modal */
        .more-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 2000;
            justify-content: center;
            align-items: center;
        }

        .more-modal-content {
            background: white;
            border-radius: 15px;
            padding: 2rem;
            width: 90%;
            max-width: 400px;
            max-height: 80vh;
            overflow-y: auto;
        }

        .more-modal h3 {
            margin-bottom: 1.5rem;
            text-align: center;
            color: #333;
        }

        .more-modal ul {
            list-style: none;
        }

        .more-modal li {
            margin-bottom: 1rem;
        }

        .more-modal a {
            display: flex;
            align-items: center;
            padding: 1rem;
            color: #333;
            text-decoration: none;
            border-radius: 8px;
            transition: background 0.3s ease;
        }

        .more-modal a:hover {
            background: #f8f9fa;
        }

        .more-modal a i {
            margin-right: 1rem;
            width: 20px;
            text-align: center;
            color: var(--primary-color);
        }

        .close-more-modal {
            background: var(--danger-color);
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            cursor: pointer;
            width: 100%;
            margin-top: 1rem;
            font-weight: 500;
        }

        /* Responsive Design */
        @media (min-width: 769px) {
            .sidebar {
                position: fixed;
                transform: translateX(0);
                left: 0;
                top: 0;
            }

            .main-content {
                margin-left: var(--sidebar-width);
            }

            .header .menu-toggle {
                display: none;
            }
        }

        @media (max-width: 768px) {
            .mobile-footer {
                display: block;
            }

            .dashboard-content {
                padding-bottom: 80px;
            }

            .header .search-bar input {
                width: 200px;
            }

            .modal-content {
                width: 98%;
                padding: 1.5rem;
            }

            #manageClassDetailsModal .modal-content,
            #manageStudentsModal .modal-content {
                width: 98%;
                max-width: 98%;
            }
        }

        @media (max-width: 480px) {
            .header {
                padding: 0 1rem;
            }

            .header .search-bar {
                display: none;
            }

            .dashboard-content {
                padding: 1rem;
            }

            .card {
                padding: 1rem;
            }
        }

        /* Custom styles for modals */
        .modal {
            position: fixed;
            z-index: 1001;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.4);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 1rem;
        }

        .modal.hidden {
            display: none;
        }

        .modal-content {
            background-color: #fff;
            margin: auto;
            padding: 2rem;
            border-radius: 12px;
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            position: relative;
            width: 95%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
            animation: fadeIn 0.3s ease-out;
            border-bottom: 4px solid #4f46e5;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }

        #assignClassSubjectsModal .modal-content {
            max-width: 700px;
        }

        #manageClassDetailsModal .modal-content,
        #manageStudentsModal .modal-content {
            max-width: 1400px;
            width: 98%;
            max-height: 90vh;
        }

        .close-button {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            position: sticky;
            top: 0;
            z-index: 10;
            background: white;
            padding: 0.5rem;
            margin: -0.5rem -0.5rem 0 0;
            border-radius: 0 12px 0 0;
        }

        .close-button:hover,
        .close-button:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* Message styling */
        .message {
            padding: 0.75rem;
            margin-bottom: 1rem;
            border-radius: 6px;
            font-weight: 500;
            opacity: 1;
            transition: opacity 0.5s ease-out;
            width: 100%;
            position: relative;
            z-index: 9999;
            font-size: 0.875rem;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
        }
        .message.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #68d391;
        }
        .message.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f6ad55;
        }

        /* Table responsiveness */
        .table-responsive-wrapper {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }
        .data-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            min-width: 800px;
        }
        .data-table th, .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #e2e8f0;
        }
        .data-table thead th {
            background-color: #f8fafc;
            font-weight: 600;
            color: #4a5568;
            text-transform: uppercase;
            font-size: 0.75rem;
            letter-spacing: 0.05em;
        }
        .data-table tbody tr:last-child td {
            border-bottom: none;
        }
        .data-table tbody tr:hover {
            background-color: #f0f4f8;
        }
        .data-table tbody td {
            color: #2d3748;
        }
        .data-table tfoot td {
            font-weight: 600;
            background-color: #f0f4f8;
            border-top: 2px solid #cbd5e0;
        }

        /* Form group spacing */
        .form-group {
            margin-bottom: 1rem;
        }
        .form-group label {
            display: block;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 0.5rem;
        }
        .form-group input[type="text"],
        .form-group select {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #cbd5e0;
            border-radius: 8px;
            box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.05);
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
            background-color: #fdfdfd;
            color: #1a202c;
            transition: all 0.2s ease-in-out;
        }
        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #6366f1;
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.25);
        }

        /* For subject checkboxes in modal */
        .subject-checkbox-group {
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #e2e8f0;
            padding: 10px;
            border-radius: 8px;
            background-color: #f8fafc;
        }
        .subject-checkbox-group label {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            cursor: pointer;
            font-weight: normal;
        }
        .subject-checkbox-group input[type="checkbox"] {
            margin-right: 8px;
            width: auto;
            padding: 0;
            border-radius: 4px;
        }

        /* Enhanced button styling */
        .btn-primary {
            background-color: #4f46e5;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: bold;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: all 0.2s ease-in-out;
            border: none;
            cursor: pointer;
        }
        .btn-primary:hover {
            background-color: #4338ca;
            box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
        }
        .btn-primary:focus {
            outline: none;
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.5);
        }

        .btn-danger {
            background-color: #ef4444;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: bold;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: all 0.2s ease-in-out;
            border: none;
            cursor: pointer;
        }
        .btn-danger:hover {
            background-color: #dc2626;
            box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
        }
        .btn-danger:focus {
            outline: none;
            box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.5);
        }

        .btn-secondary {
            background-color: #d1d5db;
            color: #374151;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: bold;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            transition: all 0.2s ease-in-out;
            border: none;
            cursor: pointer;
        }
        .btn-secondary:hover {
            background-color: #9ca3af;
            box-shadow: 0 6px 8px rgba(0, 0, 0, 0.1);
        }
        .btn-secondary:focus {
            outline: none;
            box-shadow: 0 0 0 3px rgba(209, 213, 219, 0.5);
        }

        /* Card styling */
        .card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            padding: 2rem;
            margin-bottom: 2rem;
            width: 100%;
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
        }

        .card-title {
            font-size: 1.5rem;
            font-weight: 600;
            color: #1f2937;
        }

        /* Specific adjustments for select elements in the manage modal for better alignment */
        #manageClassSubjectsTableBody select {
            padding: 0.5rem 0.75rem;
            border: 1px solid #cbd5e0;
            border-radius: 6px;
        }

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

        .overlay.active {
            display: block;
        }

        /* Action buttons in table */
        .action-btn {
            display: inline-flex;
            align-items: center;
            padding: 0.5rem 0.75rem;
            margin: 0;
            border-radius: 6px;
            text-decoration: none;
            font-size: 0.875rem;
            font-weight: 500;
            transition: all 0.2s ease;
            border: none;
            cursor: pointer;
            white-space: nowrap;
            flex-shrink: 0;
        }

        .action-btn i {
            margin-right: 0.5rem;
        }

        .action-btn.edit {
            background-color: #3b82f6;
            color: white;
        }

        .action-btn.edit:hover {
            background-color: #2563eb;
        }

        .action-btn.delete {
            background-color: #ef4444;
            color: white;
        }

        .action-btn.delete:hover {
            background-color: #dc2626;
        }

        .action-btn.assign {
            background-color: #10b981;
            color: white;
        }

        .action-btn.assign:hover {
            background-color: #059669;
        }

        .action-btn.subjects {
            background-color: #8b5cf6;
            color: white;
        }

        .action-btn.subjects:hover {
            background-color: #7c3aed;
        }

        .action-btn.manage {
            background-color: #6366f1;
            color: white;
        }

        .action-btn.manage:hover {
            background-color: #4f46e5;
        }

        .action-btn.stream {
            background-color: #14b8a6;
            color: white;
        }

        .action-btn.stream:hover {
            background-color: #0d9488;
        }
    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <!-- Sidebar -->
        <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"><i class="fas fa-th-large"></i> Dashboard</a></li>
                    <li><a href="admin_calendar.php"><i class="far fa-calendar-alt"></i> Calendar</a></li>
                    <li><a href="admin_user_management.php"><i class="fas fa-users-cog"></i> Users</a></li>
                    <li><a href="admin_students.php"><i class="fas fa-user-graduate"></i> Students</a></li>
                    <li><a href="admin_teachers.php"><i class="fas fa-chalkboard-teacher"></i> Teachers</a></li>
                    <li class="active"><a href="admin_classes.php"><i class="fas fa-chalkboard"></i> Classes</a></li>
                    <li><a href="admin_subjects.php"><i class="fas fa-book"></i> Subjects</a></li>
                    <li><a href="admin_exams.php"><i class="fas fa-file-alt"></i> Exams</a></li>
                    <li><a href="admin_messages.php"><i class="fas fa-envelope"></i> Messages</a></li>
                    <li><a href="admin_reports_printouts.php"><i class="fas fa-print"></i> Printouts</a></li>
                    <li><a href="admin_system_settings.php"><i class="fas fa-cog"></i> Settings</a></li>
                    <li><a href="logout.php" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
                </ul>
            </nav>
        </aside>

        <!-- Main Content -->
        <div class="main-content">
            <!-- Header -->
            <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>

            <!-- Main Dashboard Content -->
            <div class="dashboard-content">
                <!-- Message Display -->
                <?php if (!empty($message)): ?>
                    <div id="messageBox" class="message <?php echo $message_type; ?>">
                        <?php echo $message; ?>
                    </div>
                <?php endif; ?>
                
                <div class="card">
                    <div class="card-header">
                        <h2 class="card-title">Classes Management - <?php echo $school_name; ?></h2>
                        <div style="display: flex; gap: 1rem;">
                            <button onclick="openAddModal()" class="btn-primary">
                                <i class="fas fa-plus"></i> Add New Class
                            </button>
                            <button onclick="openAddStreamModal()" class="action-btn stream">
                                <i class="fas fa-stream"></i> Add Stream
                            </button>
                        </div>
                    </div>

                    <!-- Search Control (client-side) -->
                    <div style="margin-bottom: 1.5rem; background: #f8fafc; padding: 1rem; border-radius: 8px;">
                        <div class="form-group">
                            <label for="search">Search Classes</label>
                            <input type="text" id="search" placeholder="Search by class name or teacher..." style="padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 8px; width: 100%;">
                        </div>
                        <div style="display: flex; justify-content: flex-end; margin-top: 1rem;">
                            <a href="admin_classes.php" class="btn-secondary">Reset Search</a>
                        </div>
                    </div>

                    <div class="table-responsive-wrapper">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Class Name</th>
                                    <th>Class Teacher</th>
                                    <th>Students Count</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="classTableBody">
                                <!-- Data will be populated by JavaScript -->
                            </tbody>
                            <tfoot id="classTableFooter">
                                <!-- Total students count will be populated here by JavaScript -->
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Mobile Footer Navigation -->
    <div class="mobile-footer">
        <nav>
            <ul>
                <li><a href="admin_dashboard.php"><i class="fas fa-th-large"></i><span>Dashboard</span></a></li>
                <li><a href="admin_calendar.php"><i class="far fa-calendar-alt"></i><span>Calendar</span></a></li>
                <li><a href="admin_students.php"><i class="fas fa-user-graduate"></i><span>Students</span></a></li>
                <li><a href="admin_teachers.php"><i class="fas fa-chalkboard-teacher"></i><span>Teachers</span></a></li>
                <li><a href="#" onclick="openMoreModal()"><i class="fas fa-ellipsis-h"></i><span>More</span></a></li>
            </ul>
        </nav>
    </div>

    <!-- Mobile "More" Modal -->
    <div class="more-modal" id="moreModal">
        <div class="more-modal-content">
            <h3>More Options</h3>
            <ul>
                <li><a href="admin_classes.php"><i class="fas fa-chalkboard"></i> Classes</a></li>
                <li><a href="admin_subjects.php"><i class="fas fa-book"></i> Subjects</a></li>
                <li><a href="admin_exams.php"><i class="fas fa-file-alt"></i> Exams</a></li>
                <li><a href="admin_messages.php"><i class="fas fa-envelope"></i> Messages</a></li>
                <li><a href="admin_reports_printouts.php"><i class="fas fa-print"></i> Printouts</a></li>
                <li><a href="admin_system_settings.php"><i class="fas fa-cog"></i> Settings</a></li>
                <li><a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
            </ul>
            <button class="close-more-modal" onclick="closeMoreModal()">Close</button>
        </div>
    </div>

    <!-- Add Class Modal -->
    <div id="addClassModal" class="modal hidden">
        <div class="modal-content">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 style="font-size: 1.25rem; font-weight: 600; margin-bottom: 1rem;">Add New Class</h3>
            <form id="addClassForm" action="admin_classes.php" method="POST">
                <input type="hidden" name="action" value="add_class">
                <div class="form-group">
                    <label for="class_name">Class Name</label>
                    <input type="text" id="class_name" name="class_name" required>
                    <span id="classNameError" style="color: #dc2626; font-size: 0.875rem; display: none; margin-top: 0.25rem;"></span>
                </div>
                <div style="display: flex; justify-content: flex-end; margin-top: 1.5rem;">
                    <button type="submit" class="btn-primary">Add Class</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Add Stream Modal -->
    <div id="addStreamModal" class="modal hidden">
        <div class="modal-content">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 style="font-size: 1.25rem; font-weight: 600; margin-bottom: 1rem;">Add New Stream</h3>
            <form id="addStreamForm" action="admin_classes.php" method="POST">
                <input type="hidden" name="action" value="add_stream">
                <div class="form-group">
                    <label for="stream_class_id">Select Class</label>
                    <select id="stream_class_id" name="stream_class_id" required>
                        <option value="">-- Select a Class --</option>
                        <!-- Options populated by JavaScript -->
                    </select>
                </div>
                <div class="form-group">
                    <label for="new_stream_name">Stream Name</label>
                    <input type="text" id="new_stream_name" name="new_stream_name" required>
                    <span id="streamNameError" style="color: #dc2626; font-size: 0.875rem; display: none; margin-top: 0.25rem;"></span>
                </div>
                <div style="display: flex; justify-content: flex-end; margin-top: 1.5rem;">
                    <button type="submit" class="action-btn stream">Add Stream</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Class Modal -->
    <div id="editClassModal" class="modal hidden">
        <div class="modal-content">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 style="font-size: 1.25rem; font-weight: 600; margin-bottom: 1rem;">Edit Class</h3>
            <form action="admin_classes.php" method="POST">
                <input type="hidden" name="action" value="edit_class">
                <input type="hidden" name="edit_class_id" id="edit_class_id">
                <div class="form-group">
                    <label for="edit_class_name">Class Name</label>
                    <input type="text" id="edit_class_name" name="edit_class_name" required>
                </div>
                <div style="display: flex; justify-content: flex-end; margin-top: 1.5rem;">
                    <button type="submit" class="btn-primary">Update Class</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Delete Class Modal -->
    <div id="deleteClassModal" class="modal hidden">
        <div class="modal-content" style="max-width: 400px;">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 style="font-size: 1.25rem; font-weight: 600; margin-bottom: 1rem; color: #dc2626;">Confirm Deletion</h3>
            <p style="margin-bottom: 1.5rem;">Are you sure you want to delete class "<strong id="delete_class_name_display"></strong>"? This action cannot be undone.</p>
            <form action="admin_classes.php" method="POST">
                <input type="hidden" name="action" value="delete_class">
                <input type="hidden" name="delete_class_id" id="delete_class_id">
                <div style="display: flex; justify-content: flex-end; gap: 1rem;">
                    <button type="button" onclick="closeModals()" class="btn-secondary">Cancel</button>
                    <button type="submit" class="btn-danger">Delete</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Assign Class Teacher Modal -->
    <div id="assignClassTeacherModal" class="modal hidden">
        <div class="modal-content" style="max-width: 500px;">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 style="font-size: 1.25rem; font-weight: 600; margin-bottom: 1rem;">Assign Teacher to <span id="assign_teacher_class_name_display" style="color: #6366f1;"></span></h3>
            <form action="admin_classes.php" method="POST">
                <input type="hidden" name="action" value="assign_class_teacher">
                <input type="hidden" name="class_id" id="assign_teacher_class_id">

                <div class="form-group">
                    <label for="teacher_user_id">Select Class Teacher:</label>
                    <select id="teacher_user_id" name="teacher_user_id">
                        <option value="none">-- No Class Teacher --</option>
                        <!-- Teachers will be populated by JavaScript -->
                    </select>
                </div>

                <div style="display: flex; justify-content: flex-end; margin-top: 1.5rem;">
                    <button type="submit" class="btn-primary">Save Assignment</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Assign Class Subjects Modal -->
    <div id="assignClassSubjectsModal" class="modal hidden">
        <div class="modal-content" style="max-width: 500px;">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 style="font-size: 1.25rem; font-weight: 600; margin-bottom: 1rem;">Assign Subjects to <span id="assign_subjects_class_name_display" style="color: #6366f1;"></span></h3>
            <form action="admin_classes.php" method="POST">
                <input type="hidden" name="action" value="assign_class_subjects">
                <input type="hidden" name="class_id" id="assign_subjects_class_id">
                <input type="hidden" name="selected_subjects" id="selected_subjects_json">

                <div class="form-group">
                    <label style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Select Subjects:</label>
                    <div id="classSubjectsCheckboxContainer" class="subject-checkbox-group">
                        <!-- Subjects will be populated here by JavaScript -->
                    </div>
                </div>

                <div style="display: flex; justify-content: flex-end; margin-top: 1.5rem;">
                    <button type="submit" class="btn-primary">Save Assignments</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Manage Class Details Modal -->
    <div id="manageClassDetailsModal" class="modal hidden">
        <div class="modal-content">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 style="font-size: 1.25rem; font-weight: 600; margin-bottom: 1rem;">Manage Subjects for <span id="manage_class_name_display" style="color: #6366f1;"></span></h3>
            
            <div class="form-group" style="margin-bottom: 1rem;">
                <label for="stream_select" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Select Stream:</label>
                <select id="stream_select" style="padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 8px; width: 100%; font-size: 0.875rem;">
                    <!-- Options will be populated by JavaScript -->
                </select>
            </div>

            <form id="manageClassSubjectsForm" action="" method="POST">
                <input type="hidden" name="action" value="save_subject_teachers">
                <input type="hidden" name="class_id" id="manage_class_id_form">
                <input type="hidden" name="selected_stream" id="selected_stream_form">
                <input type="hidden" name="subject_assignments" id="subject_assignments_json">

                <div class="table-responsive-wrapper" style="margin-bottom: 1rem;">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Subject</th>
                                <th>Students</th>
                                <th>Subject Teacher (1)</th>
                                <th>Subject Teacher (2)</th>
                                <th>Subject Teacher (3)</th>
                            </tr>
                        </thead>
                        <tbody id="manageClassSubjectsTableBody">
                            <tr><td colspan="5" style="text-align: center; padding: 1rem; color: #6b7280;">Please select a stream.</td></tr>
                        </tbody>
                    </table>
                </div>
                <div style="display: flex; justify-content: flex-end; margin-top: 1.5rem;">
                    <button type="button" id="saveSubjectTeachersBtn" class="btn-primary">Save Subject Teachers</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Manage Students Modal -->
    <div id="manageStudentsModal" class="modal hidden">
        <div class="modal-content">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 style="font-size: 1.25rem; font-weight: 600; margin-bottom: 1rem;">Manage Students for <span id="manage_students_class_name_display" style="color: #6366f1;"></span></h3>
            
            <div class="form-group" style="margin-bottom: 1.5rem;">
                <label for="students_stream_select" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Select Stream:</label>
                <select id="students_stream_select" style="padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 8px; width: 100%; font-size: 0.9rem;">
                    <option value="">-- Select a Stream --</option>
                </select>
            </div>

            <div id="studentsListContainer" style="display: none;">
                <div style="background: #f0f9ff; border: 1px solid #bae6fd; padding: 1rem; border-radius: 8px; margin-bottom: 1rem;">
                    <p style="margin: 0; color: #0c4a6e; font-size: 0.9rem;">
                        <strong>Note:</strong> Students can select a maximum of <strong>2 optional subjects</strong>. 
                        Compulsory subjects are automatically assigned to all students.
                    </p>
                </div>

                <div style="margin-bottom: 1rem; background: #f8fafc; padding: 1rem; border-radius: 8px;">
                    <input type="text" id="studentSearchInput" placeholder="Search students by name or ADM..." style="padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 8px; width: 100%;">
                </div>

                <div class="table-responsive-wrapper">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>ADM</th>
                                <th>Student Name</th>
                                <th>Gender</th>
                                <th>Optional Subjects Selected</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="studentsTableBody">
                            <tr><td colspan="6" style="text-align: center; padding: 1rem; color: #6b7280;">Please select a stream.</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Subject to Student Modal -->
    <div id="addSubjectToStudentModal" class="modal hidden">
        <div class="modal-content" style="max-width: 500px;">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 style="font-size: 1.25rem; font-weight: 600; margin-bottom: 1rem;">Add Optional Subject for <span id="add_subject_student_name_display" style="color: #6366f1;"></span></h3>
            
            <input type="hidden" id="add_subject_student_adm">
            <input type="hidden" id="add_subject_class_id">
            <input type="hidden" id="add_subject_stream_id">

            <div class="form-group">
                <label for="optional_subject_select" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Select Optional Subject:</label>
                <select id="optional_subject_select" style="padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 8px; width: 100%; font-size: 0.9rem;">
                    <option value="">-- Select Subject --</option>
                </select>
            </div>

            <div style="display: flex; justify-content: flex-end; gap: 1rem; margin-top: 1.5rem;">
                <button type="button" onclick="closeModals()" class="btn-secondary">Cancel</button>
                <button type="button" onclick="saveStudentSubjectChoice()" class="btn-primary">Add Subject</button>
            </div>
        </div>
    </div>

    <!-- Custom Confirmation Modal -->
    <div id="customConfirmModal" class="modal hidden">
        <div class="modal-content" style="max-width: 450px;">
            <span class="close-button" onclick="closeConfirmModal()">&times;</span>
            <h3 id="confirmModalTitle" style="font-size: 1.25rem; font-weight: 600; margin-bottom: 1rem; color: #dc2626;">Confirm Action</h3>
            <p id="confirmModalMessage" style="margin-bottom: 1.5rem; color: #4b5563;"></p>
            <div style="display: flex; justify-content: flex-end; gap: 1rem;">
                <button type="button" onclick="closeConfirmModal()" class="btn-secondary">Cancel</button>
                <button type="button" id="confirmModalButton" class="btn-danger">Confirm</button>
            </div>
        </div>
    </div>

    <div class="overlay" id="overlay" onclick="closeModals()"></div>

    <script>
        // Global variables to store data fetched from PHP
        let allClassesData = <?php echo json_encode($allClassesData); ?>;
        let allTeachersData = <?php echo json_encode($allTeachersData); ?>;
        let allSubjectsData = <?php echo json_encode($allSubjectsData); ?>;
        let totalStudentsCount = <?php echo json_encode($totalStudentsCount); ?>;

        // Get references to filter elements and table body
        const searchInput = document.getElementById('search');
        const classTableBody = document.getElementById('classTableBody');
        const classTableFooter = document.getElementById('classTableFooter');
        const overlay = document.getElementById('overlay');
        const sidebar = document.getElementById('sidebar');
        const dashboardContainer = document.getElementById('dashboardContainer');
        const messageBox = document.getElementById('messageBox');

        // Sidebar and mobile navigation
        const menuToggle = document.getElementById('menuToggle');
        const moreModal = document.getElementById('moreModal');

        // Function to show message and hide after a delay
        function showMessage(message, type) {
            if (messageBox) {
                messageBox.textContent = message;
                messageBox.className = `message ${type}`;
                messageBox.style.display = 'block';
                messageBox.style.opacity = '1';
                messageBox.style.zIndex = '9999'; // Ensure it's above everything
                
                // Scroll to top so user can see the message
                window.scrollTo({ top: 0, behavior: 'smooth' });

                setTimeout(() => {
                    messageBox.style.opacity = '0';
                    setTimeout(() => {
                        messageBox.style.display = 'none';
                    }, 500);
                }, 3000); // 3 seconds display time
            }
        }

        // Custom confirmation modal functions
        let confirmCallback = null;
        let confirmButtonHandler = null;

        function showConfirmModal(title, message, onConfirm) {
            const confirmModal = document.getElementById('customConfirmModal');
            const confirmTitle = document.getElementById('confirmModalTitle');
            const confirmMessage = document.getElementById('confirmModalMessage');
            const confirmButton = document.getElementById('confirmModalButton');
            
            confirmTitle.textContent = title;
            confirmMessage.textContent = message;
            confirmCallback = onConfirm;
            
            confirmModal.classList.remove('hidden');
            overlay.classList.add('active');
            document.querySelector('.header').classList.add('hide-header');
            
            // Remove previous event listener if exists
            if (confirmButtonHandler) {
                confirmButton.removeEventListener('click', confirmButtonHandler);
            }
            
            // Create new event handler
            confirmButtonHandler = function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                console.log('Confirm button clicked');
                
                // Save the callback before closing the modal
                const callbackToExecute = confirmCallback;
                
                // Close the modal first
                closeConfirmModal();
                
                // Then execute the saved callback
                if (callbackToExecute) {
                    console.log('Executing callback');
                    callbackToExecute();
                } else {
                    console.log('No callback found');
                }
            };
            
            // Attach new event listener
            confirmButton.addEventListener('click', confirmButtonHandler);
        }

        function closeConfirmModal() {
            const confirmModal = document.getElementById('customConfirmModal');
            confirmModal.classList.add('hidden');
            overlay.classList.remove('active');
            document.querySelector('.header').classList.remove('hide-header');
            
            // Clean up the event listener
            const confirmButton = document.getElementById('confirmModalButton');
            if (confirmButtonHandler) {
                confirmButton.removeEventListener('click', confirmButtonHandler);
                confirmButtonHandler = null;
            }
            
            confirmCallback = null;
        }

        // Display initial message if present from PHP
        <?php if (!empty($message)): ?>
            showMessage("<?php echo $message; ?>", "<?php echo $message_type; ?>");
        <?php endif; ?>

        // Function to render the class table based on filtered data
        function renderClassesTable(classesToRender) {
            classTableBody.innerHTML = '';
            classTableFooter.innerHTML = '';

            if (classesToRender.length === 0) {
                const noRecordsRow = document.createElement('tr');
                noRecordsRow.innerHTML = '<td colspan="4" style="text-align: center; padding: 1rem; color: #6b7280;">No classes found.</td>';
                classTableBody.appendChild(noRecordsRow);
                return;
            }

            let currentTotalStudentsDisplayed = 0;

            classesToRender.forEach(classItem => {
                const row = document.createElement('tr');
                row.setAttribute('data-id', classItem.class_id);
                row.setAttribute('data-name', classItem.class_name);
                row.setAttribute('data-teacher-id', classItem.class_teacher_id || 'none');
                row.setAttribute('data-teacher-name', classItem.class_teacher_name || 'N/A');
                row.setAttribute('data-student-count', classItem.student_count || 0);

                currentTotalStudentsDisplayed += parseInt(classItem.student_count || 0);

                row.innerHTML = `
                    <td>${classItem.class_name}</td>
                    <td>${classItem.class_teacher_name || 'N/A'}</td>
                    <td>${classItem.student_count || 0}</td>
                    <td>
                        <div style="display: flex; flex-wrap: nowrap; gap: 0.5rem; overflow-x: auto; padding: 0.25rem 0;">
                            <button onclick="openEditModal(this)" class="action-btn edit">
                                <i class="fas fa-edit"></i> Edit Class
                            </button>
                            <button onclick="openDeleteModal(this)" class="action-btn delete">
                                <i class="fas fa-trash-alt"></i> Delete Class
                            </button>
                            <button onclick="openAssignClassTeacherModal(this)" class="action-btn assign">
                                <i class="fas fa-user-tie"></i> Assign Teacher
                            </button>
                            <button onclick="openAssignClassSubjectsModal(this)" class="action-btn subjects">
                                <i class="fas fa-book-reader"></i> Assign Subjects
                            </button>
                            <button onclick="openManageClassDetailsModal(this)" class="action-btn manage">
                                <i class="fas fa-cogs"></i> Manage
                            </button>
                            <button onclick="openManageStudentsModal(this)" class="action-btn" style="background-color: #f59e0b; color: white;">
                                <i class="fas fa-user-plus"></i> Manage Students
                            </button>
                        </div>
                    </td>
                `;
                classTableBody.appendChild(row);
            });

            // Update footer with total students count
            const footerRow = document.createElement('tr');
            footerRow.innerHTML = `
                <td colspan="2" style="text-align: right; font-weight: 600;">Total Students:</td>
                <td style="font-weight: 600;">${currentTotalStudentsDisplayed}</td>
                <td></td>
            `;
            classTableFooter.appendChild(footerRow);
        }

        // Initial render of the table
        document.addEventListener('DOMContentLoaded', () => {
            renderClassesTable(allClassesData);
            
            // Add Class form validation
            const addClassForm = document.getElementById('addClassForm');
            if (addClassForm) {
                addClassForm.addEventListener('submit', function(e) {
                    const classNameInput = document.getElementById('class_name');
                    const classNameError = document.getElementById('classNameError');
                    const className = classNameInput.value.trim();
                    
                    if (!validateClassName(className)) {
                        e.preventDefault();
                        classNameError.textContent = `Class "${className}" already exists. Please use a different name.`;
                        classNameError.style.display = 'block';
                        classNameInput.style.borderColor = '#dc2626';
                        classNameInput.focus();
                        return false;
                    }
                    
                    // Clear any previous errors
                    classNameError.style.display = 'none';
                    classNameInput.style.borderColor = '#cbd5e0';
                });
                
                // Clear error on input
                document.getElementById('class_name').addEventListener('input', function() {
                    document.getElementById('classNameError').style.display = 'none';
                    this.style.borderColor = '#cbd5e0';
                });
            }
            
            // Add Stream form validation
            const addStreamForm = document.getElementById('addStreamForm');
            if (addStreamForm) {
                addStreamForm.addEventListener('submit', async function(e) {
                    e.preventDefault();
                    
                    const classIdSelect = document.getElementById('stream_class_id');
                    const streamNameInput = document.getElementById('new_stream_name');
                    const streamNameError = document.getElementById('streamNameError');
                    const classId = classIdSelect.value;
                    const streamName = streamNameInput.value.trim();
                    
                    if (!classId) {
                        showMessage('Please select a class', 'error');
                        return false;
                    }
                    
                    // Check for duplicate stream name
                    const isValid = await validateStreamName(classId, streamName);
                    
                    if (!isValid) {
                        streamNameError.textContent = `Stream "${streamName}" already exists in this class. Please use a different name.`;
                        streamNameError.style.display = 'block';
                        streamNameInput.style.borderColor = '#dc2626';
                        streamNameInput.focus();
                        return false;
                    }
                    
                    // Clear any previous errors and submit
                    streamNameError.style.display = 'none';
                    streamNameInput.style.borderColor = '#cbd5e0';
                    
                    // Submit the form
                    this.submit();
                });
                
                // Clear error on input
                document.getElementById('new_stream_name').addEventListener('input', function() {
                    document.getElementById('streamNameError').style.display = 'none';
                    this.style.borderColor = '#cbd5e0';
                });
            }
        });

        // Search functionality
        searchInput.addEventListener('keyup', (event) => {
            const searchTerm = event.target.value.toLowerCase();
            const filteredClasses = allClassesData.filter(classItem => {
                const className = classItem.class_name.toLowerCase();
                const classTeacherName = (classItem.class_teacher_name || '').toLowerCase();
                return className.includes(searchTerm) || classTeacherName.includes(searchTerm);
            });
            renderClassesTable(filteredClasses);
        });

        // --- Modal Functions ---
        function openModal(modalId) {
            document.getElementById(modalId).classList.remove('hidden');
            overlay.classList.add('active');
            // Hide the page header when any modal opens
            const header = document.querySelector('.header');
            if (header) {
                header.classList.add('hide-header');
            }
        }

        function closeModals() {
            document.querySelectorAll('.modal').forEach(modal => {
                modal.classList.add('hidden');
            });
            overlay.classList.remove('active');
            // Show the page header when all modals are closed
            const header = document.querySelector('.header');
            if (header) {
                header.classList.remove('hide-header');
            }
        }

        // Duplicate validation functions
        function validateClassName(className) {
            const trimmedName = className.trim();
            const duplicate = allClassesData.find(classItem => 
                classItem.class_name.toLowerCase() === trimmedName.toLowerCase()
            );
            return duplicate ? false : true;
        }

        async function validateStreamName(classId, streamName) {
            if (!classId || !streamName) return true;
            
            const trimmedName = streamName.trim();
            
            try {
                const response = await fetch(`admin_classes_api.php?action=get_class_streams&class_id=${classId}`);
                const data = await response.json();
                
                if (data.success) {
                    const duplicate = data.streams.find(stream => 
                        stream.stream_name.toLowerCase() === trimmedName.toLowerCase()
                    );
                    return duplicate ? false : true;
                }
                return true;
            } catch (error) {
                console.error('Error checking stream name:', error);
                return true; // Allow submission if check fails
            }
        }

        function openAddModal() {
            openModal('addClassModal');
        }

        function openAddStreamModal() {
            const streamClassSelect = document.getElementById('stream_class_id');
            streamClassSelect.innerHTML = '<option value="">-- Select a Class --</option>';
            allClassesData.forEach(classItem => {
                const option = document.createElement('option');
                option.value = classItem.class_id;
                option.textContent = classItem.class_name;
                streamClassSelect.appendChild(option);
            });
            openModal('addStreamModal');
        }

        function openEditModal(button) {
            const row = button.closest('tr');
            const classId = row.getAttribute('data-id');
            const className = row.getAttribute('data-name');

            document.getElementById('edit_class_id').value = classId;
            document.getElementById('edit_class_name').value = className;
            openModal('editClassModal');
        }

        function openDeleteModal(button) {
            const row = button.closest('tr');
            const classId = row.getAttribute('data-id');
            const className = row.getAttribute('data-name');

            document.getElementById('delete_class_id').value = classId;
            document.getElementById('delete_class_name_display').textContent = className;
            openModal('deleteClassModal');
        }

        function openAssignClassTeacherModal(button) {
            const row = button.closest('tr');
            const classId = row.getAttribute('data-id');
            const className = row.getAttribute('data-name');
            const currentTeacherId = row.getAttribute('data-teacher-id');

            document.getElementById('assign_teacher_class_id').value = classId;
            document.getElementById('assign_teacher_class_name_display').textContent = className;

            const teacherSelect = document.getElementById('teacher_user_id');
            teacherSelect.innerHTML = '<option value="none">-- No Class Teacher --</option>';

            allTeachersData.forEach(teacher => {
                const option = document.createElement('option');
                option.value = teacher.id;
                option.textContent = teacher.username;
                if (teacher.id == currentTeacherId) {
                    option.selected = true;
                }
                teacherSelect.appendChild(option);
            });
            openModal('assignClassTeacherModal');
        }

        async function openAssignClassSubjectsModal(button) {
            const row = button.closest('tr');
            const classId = row.getAttribute('data-id');
            const className = row.getAttribute('data-name');

            document.getElementById('assign_subjects_class_id').value = classId;
            document.getElementById('assign_subjects_class_name_display').textContent = className;

            const checkboxContainer = document.getElementById('classSubjectsCheckboxContainer');
            checkboxContainer.innerHTML = '';

            // Fetch currently assigned subjects for this class
            let assignedSubjects = [];
            try {
                const response = await fetch(`admin_classes_api.php?action=get_class_subjects&class_id=${classId}`);
                const data = await response.json();
                if (data.success) {
                    assignedSubjects = data.subjects.map(s => s.subject_id);
                } else {
                    showMessage(`Error fetching assigned subjects: ${data.message}`, 'error');
                }
            } catch (error) {
                showMessage(`Network error fetching assigned subjects: ${error.message}`, 'error');
            }

            allSubjectsData.forEach(subject => {
                const label = document.createElement('label');
                label.className = 'flex items-center mb-2 cursor-pointer';
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.name = 'selected_subjects[]';
                checkbox.value = subject.subject_id;
                checkbox.className = 'mr-2 form-checkbox h-4 w-4 text-indigo-600 transition duration-150 ease-in-out rounded focus:ring-indigo-500';

                if (assignedSubjects.includes(subject.subject_id)) {
                    checkbox.checked = true;
                }

                label.appendChild(checkbox);
                label.appendChild(document.createTextNode(subject.subject_name));
                checkboxContainer.appendChild(label);
            });

            // Add event listener to the form to capture selected subjects before submission
            const assignSubjectsForm = document.querySelector('#assignClassSubjectsModal form');
            assignSubjectsForm.onsubmit = function() {
                const selectedSubjects = Array.from(checkboxContainer.querySelectorAll('input[type="checkbox"]:checked'))
                                            .map(cb => cb.value);
                document.getElementById('selected_subjects_json').value = JSON.stringify(selectedSubjects);
                return true;
            };

            openModal('assignClassSubjectsModal');
        }

        async function openManageClassDetailsModal(button) {
            const row = button.closest('tr');
            const classId = row.getAttribute('data-id');
            const className = row.getAttribute('data-name');

            document.getElementById('manage_class_id_form').value = classId;
            document.getElementById('manage_class_name_display').textContent = className;

            const streamSelect = document.getElementById('stream_select');
            streamSelect.innerHTML = '<option value="">-- Select a Stream --</option>';
            document.getElementById('manageClassSubjectsTableBody').innerHTML = '<tr><td colspan="5" style="text-align: center; padding: 1rem; color: #6b7280;">Please select a stream.</td></tr>';
            document.getElementById('selected_stream_form').value = '';

            // Fetch streams for the selected class
            try {
                const response = await fetch(`admin_classes_api.php?action=get_class_streams&class_id=${classId}`);
                const data = await response.json();
                if (data.success) {
                    if (data.streams.length === 0) {
                        streamSelect.innerHTML = '<option value="">-- No Streams Found --</option>';
                        showMessage('No streams found for this class. Please add streams first.', 'error');
                    } else {
                        data.streams.forEach(stream => {
                            const option = document.createElement('option');
                            option.value = stream.stream_id;
                            option.textContent = stream.stream_name;
                            streamSelect.appendChild(option);
                        });
                    }
                } else {
                    showMessage(`Error fetching streams: ${data.message}`, 'error');
                }
            } catch (error) {
                showMessage(`Network error fetching streams: ${error.message}`, 'error');
            }

            // Event listener for stream selection change
            streamSelect.onchange = () => {
                const selectedStreamId = streamSelect.value;
                document.getElementById('selected_stream_form').value = selectedStreamId;
                if (selectedStreamId) {
                    populateSubjectTeacherTable(classId, selectedStreamId);
                } else {
                    document.getElementById('manageClassSubjectsTableBody').innerHTML = '<tr><td colspan="5" style="text-align: center; padding: 1rem; color: #6b7280;">Please select a stream.</td></tr>';
                }
            };

            // Add event listener to the form to capture subject assignments before submission
            const manageSubjectsForm = document.getElementById('manageClassSubjectsForm');
            
            if (!manageSubjectsForm) {
                console.error('Form element not found: manageClassSubjectsForm');
                return;
            }
            
            // Get the save button and add click event listener
            const saveBtn = document.getElementById('saveSubjectTeachersBtn');
            
            // Remove any existing click handlers by cloning the button
            if (saveBtn) {
                const newBtn = saveBtn.cloneNode(true);
                saveBtn.parentNode.replaceChild(newBtn, saveBtn);
                
                // Add click event to the new button
                const freshBtn = document.getElementById('saveSubjectTeachersBtn');
                freshBtn.addEventListener('click', async function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    console.log('Button clicked - save triggered');
                    
                    const classId = document.getElementById('manage_class_id_form').value;
                    const selectedStreamId = document.getElementById('selected_stream_form').value;
                    
                    console.log('Class ID:', classId, 'Stream ID:', selectedStreamId);
                    
                    if (!selectedStreamId) {
                        showMessage('Please select a stream before saving', 'error');
                        return false;
                    }
                    
                    const assignments = [];
                    const rows = document.querySelectorAll('#manageClassSubjectsTableBody tr');
                    let hasAssignments = false;
                    
                    console.log('Found rows:', rows.length);
                    
                    rows.forEach(row => {
                        const subjectId = row.getAttribute('data-subject-id');
                        if (subjectId) {
                            const teacherSelects = row.querySelectorAll('select[name^="teacher_user_id_"]');
                            const teacherUserIds = Array.from(teacherSelects).map(select => select.value);
                            
                            console.log('Subject ID:', subjectId, 'Teachers:', teacherUserIds);
                            
                            // Check if any teacher is actually assigned
                            if (teacherUserIds.some(id => id !== 'none')) {
                                hasAssignments = true;
                            }
                            
                            assignments.push({
                                subject_id: subjectId,
                                teacher_user_ids: teacherUserIds
                            });
                        }
                    });
                    
                    console.log('Has assignments:', hasAssignments);
                    console.log('Assignments:', assignments);
                    
                    if (!hasAssignments) {
                        showMessage('Please assign at least one teacher before saving', 'error');
                        return false;
                    }
                    
                    // Submit via AJAX to preserve modal state
                    try {
                        console.log('Submitting form via AJAX...');
                        
                        const formData = new FormData();
                        formData.append('action', 'save_subject_teachers');
                        formData.append('class_id', classId);
                        formData.append('selected_stream', selectedStreamId);
                        formData.append('subject_assignments', JSON.stringify(assignments));
                        formData.append('ajax', 'true'); // Flag to indicate AJAX request
                        
                        const response = await fetch('admin_classes.php', {
                            method: 'POST',
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest' // Standard AJAX header
                            },
                            body: formData
                        });
                        
                        console.log('Response status:', response.status);
                        console.log('Response ok:', response.ok);
                        
                        const data = await response.json();
                        console.log('Response data:', data);
                        
                        if (data.success) {
                            showMessage(data.message || 'Subject teachers assigned successfully', 'success');
                            // Reload the table to show updated data
                            await populateSubjectTeacherTable(classId, selectedStreamId);
                        } else {
                            showMessage(data.message || 'Error saving subject teachers', 'error');
                        }
                    } catch (error) {
                        console.error('Error details:', error);
                        showMessage(`Network error: ${error.message}`, 'error');
                    }
            });
            }

            openModal('manageClassDetailsModal');
        }

        async function populateSubjectTeacherTable(classId, streamId) {
            const tableBody = document.getElementById('manageClassSubjectsTableBody');
            tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center; padding: 1rem; color: #6b7280;">Loading subjects...</td></tr>';

            // Fetch subjects assigned to this class
            let classSubjects = [];
            try {
                const response = await fetch(`admin_classes_api.php?action=get_class_subjects&class_id=${classId}`);
                const data = await response.json();
                if (data.success) {
                    classSubjects = data.subjects;
                } else {
                    showMessage(`Error fetching class subjects: ${data.message}`, 'error');
                    tableBody.innerHTML = `<tr><td colspan="5" style="text-align: center; padding: 1rem; color: #6b7280;">Error: ${data.message}</td></tr>`;
                    return;
                }
            } catch (error) {
                showMessage(`Network error fetching class subjects: ${error.message}`, 'error');
                tableBody.innerHTML = `<tr><td colspan="5" style="text-align: center; padding: 1rem; color: #6b7280;">Network error: ${error.message}</td></tr>`;
                return;
            }

            if (classSubjects.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center; padding: 1rem; color: #6b7280;">No subjects assigned to this class. Please assign subjects first.</td></tr>';
                return;
            }

            // Fetch current subject teacher assignments for this stream and class
            let currentAssignments = {};
            try {
                const response = await fetch(`admin_classes_api.php?action=get_subject_teachers&class_id=${classId}&stream_id=${streamId}`);
                const data = await response.json();
                if (data.success) {
                    data.assignments.forEach(assignment => {
                        if (!currentAssignments[assignment.subject_id]) {
                            currentAssignments[assignment.subject_id] = {};
                        }
                        currentAssignments[assignment.subject_id][assignment.assignment_slot] = assignment.teacher_user_id;
                    });
                } else {
                    showMessage(`Error fetching subject teachers: ${data.message}`, 'error');
                }
            } catch (error) {
                showMessage(`Network error fetching subject teachers: ${error.message}`, 'error');
            }

            tableBody.innerHTML = '';

            for (const subject of classSubjects) {
                const row = document.createElement('tr');
                row.setAttribute('data-subject-id', subject.subject_id);

                let studentsInSubjectCount = 0;
                try {
                    const studentCountResponse = await fetch(`admin_classes_api.php?action=get_stream_subject_student_count&class_id=${classId}&stream_id=${streamId}&subject_id=${subject.subject_id}`);
                    const studentCountData = await studentCountResponse.json();
                    if (studentCountData.success) {
                        studentsInSubjectCount = studentCountData.count;
                    }
                } catch (error) {
                    console.error("Network error fetching student count for subject:", error);
                }

                let teacherSelectsHtml = '';
                for (let i = 1; i <= 3; i++) {
                    teacherSelectsHtml += `
                        <td>
                            <select name="teacher_user_id_${subject.subject_id}_${i}" style="padding: 0.5rem 0.75rem; border: 1px solid #d1d5db; border-radius: 6px; width: 100%; font-size: 0.875rem;">
                                <option value="none">-- Select Teacher --</option>
                                ${allTeachersData.map(teacher => `
                                    <option value="${teacher.id}" ${currentAssignments[subject.subject_id] && currentAssignments[subject.subject_id][i] == teacher.id ? 'selected' : ''}>
                                        ${teacher.username}
                                    </option>
                                `).join('')}
                            </select>
                        </td>
                    `;
                }

                row.innerHTML = `
                    <td>${subject.subject_name}</td>
                    <td>${studentsInSubjectCount}</td>
                    ${teacherSelectsHtml}
                `;
                tableBody.appendChild(row);
            }
        }

        // Mobile navigation functions
        function openMoreModal() {
            moreModal.style.display = 'flex';
        }

        function closeMoreModal() {
            moreModal.style.display = 'none';
        }

        // Sidebar toggle functionality
        menuToggle.addEventListener('click', function() {
            sidebar.classList.toggle('active');
            overlay.classList.toggle('active');
        });

        overlay.addEventListener('click', function() {
            sidebar.classList.remove('active');
            closeModals();
            closeMoreModal();
        });

        // ==================== STUDENT MANAGEMENT FUNCTIONS ====================
        
        let currentManageStudentsClassId = 0;
        let currentManageStudentsStreamId = 0;
        let allStudentsInStream = [];
        let optionalSubjectsForClass = [];

        async function openManageStudentsModal(button) {
            const row = button.closest('tr');
            const classId = row.getAttribute('data-id');
            const className = row.getAttribute('data-name');

            currentManageStudentsClassId = classId;
            document.getElementById('manage_students_class_name_display').textContent = className;

            const studentsStreamSelect = document.getElementById('students_stream_select');
            studentsStreamSelect.innerHTML = '<option value="">-- Select a Stream --</option>';
            document.getElementById('studentsListContainer').style.display = 'none';
            document.getElementById('studentsTableBody').innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 1rem; color: #6b7280;">Please select a stream.</td></tr>';

            // Fetch streams for the selected class
            try {
                const response = await fetch(`admin_classes_api.php?action=get_class_streams&class_id=${classId}`);
                const data = await response.json();
                if (data.success) {
                    if (data.streams.length === 0) {
                        studentsStreamSelect.innerHTML = '<option value="">-- No Streams Found --</option>';
                        showMessage('No streams found for this class. Please add streams first.', 'error');
                    } else {
                        data.streams.forEach(stream => {
                            const option = document.createElement('option');
                            option.value = stream.stream_id;
                            option.textContent = stream.stream_name;
                            studentsStreamSelect.appendChild(option);
                        });
                    }
                } else {
                    showMessage(`Error fetching streams: ${data.message}`, 'error');
                }
            } catch (error) {
                showMessage(`Network error fetching streams: ${error.message}`, 'error');
            }

            // Fetch optional subjects for this class
            try {
                const response = await fetch(`admin_classes_api.php?action=get_class_subjects&class_id=${classId}`);
                const data = await response.json();
                if (data.success) {
                    optionalSubjectsForClass = data.subjects.filter(s => s.subject_category === 'Optional' || s.subject_category === 'Elective');
                } else {
                    showMessage(`Error fetching subjects: ${data.message}`, 'error');
                }
            } catch (error) {
                showMessage(`Network error fetching subjects: ${error.message}`, 'error');
            }

            // Event listener for stream selection change
            studentsStreamSelect.onchange = () => {
                const selectedStreamId = studentsStreamSelect.value;
                if (selectedStreamId) {
                    currentManageStudentsStreamId = selectedStreamId;
                    loadStudentsForStream(classId, selectedStreamId);
                } else {
                    document.getElementById('studentsListContainer').style.display = 'none';
                    document.getElementById('studentsTableBody').innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 1rem; color: #6b7280;">Please select a stream.</td></tr>';
                }
            };

            openModal('manageStudentsModal');
        }

        async function loadStudentsForStream(classId, streamId) {
            const tableBody = document.getElementById('studentsTableBody');
            tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 1rem; color: #6b7280;">Loading students...</td></tr>';

            // Fetch students in this stream
            try {
                const response = await fetch(`admin_classes_api.php?action=get_stream_students&class_id=${classId}&stream_id=${streamId}`);
                const data = await response.json();
                if (data.success) {
                    allStudentsInStream = data.students;
                    if (allStudentsInStream.length === 0) {
                        tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 1rem; color: #6b7280;">No students found in this stream.</td></tr>';
                        document.getElementById('studentsListContainer').style.display = 'block';
                    } else {
                        await renderStudentsTable(allStudentsInStream);
                        document.getElementById('studentsListContainer').style.display = 'block';
                    }
                } else {
                    showMessage(`Error fetching students: ${data.message}`, 'error');
                    tableBody.innerHTML = `<tr><td colspan="6" style="text-align: center; padding: 1rem; color: #6b7280;">Error: ${data.message}</td></tr>`;
                }
            } catch (error) {
                showMessage(`Network error fetching students: ${error.message}`, 'error');
                tableBody.innerHTML = `<tr><td colspan="6" style="text-align: center; padding: 1rem; color: #6b7280;">Network error: ${error.message}</td></tr>`;
            }
        }

        async function renderStudentsTable(students) {
            const tableBody = document.getElementById('studentsTableBody');
            tableBody.innerHTML = '';

            for (const student of students) {
                // Fetch student's subject choices
                let subjectChoices = [];
                try {
                    const response = await fetch(`admin_classes_api.php?action=get_student_subject_choices&student_adm=${student.ADM}`);
                    const data = await response.json();
                    if (data.success) {
                        subjectChoices = data.choices;
                    }
                } catch (error) {
                    console.error('Error fetching subject choices:', error);
                }

                const row = document.createElement('tr');
                const studentFullName = `${student.surname} ${student.other_names}`;
                const choicesCount = subjectChoices.length;
                const maxChoices = 2;

                // Create subject badges
                let subjectBadgesHtml = '';
                if (subjectChoices.length === 0) {
                    subjectBadgesHtml = '<span style="color: #9ca3af; font-style: italic;">None</span>';
                } else {
                    subjectChoices.forEach(choice => {
                        subjectBadgesHtml += `
                            <span style="display: inline-flex; align-items: center; background: #dbeafe; color: #1e40af; padding: 0.25rem 0.75rem; border-radius: 12px; margin: 0.25rem; font-size: 0.85rem;">
                                ${choice.subject_name}
                                <button onclick="removeStudentSubject('${student.ADM}', ${choice.subject_id})" style="background: none; border: none; color: #dc2626; margin-left: 0.5rem; cursor: pointer; font-weight: bold;" title="Remove subject">
                                    &times;
                                </button>
                            </span>
                        `;
                    });
                }

                // Determine status
                let statusHtml = '';
                if (choicesCount === maxChoices) {
                    statusHtml = '<span style="background: #d1fae5; color: #065f46; padding: 0.25rem 0.75rem; border-radius: 12px; font-size: 0.85rem; font-weight: 500;">✓ Complete (2/2)</span>';
                } else {
                    statusHtml = `<span style="background: #fef3c7; color: #92400e; padding: 0.25rem 0.75rem; border-radius: 12px; font-size: 0.85rem; font-weight: 500;">⚠ Incomplete (${choicesCount}/2)</span>`;
                }

                // Actions
                let actionsHtml = '';
                if (choicesCount < maxChoices) {
                    actionsHtml = `<button onclick="openAddSubjectModal('${student.ADM}', '${studentFullName}')" class="action-btn" style="background-color: #10b981; color: white; padding: 0.4rem 0.6rem; font-size: 0.85rem;"><i class="fas fa-plus"></i> Add Subject</button>`;
                } else {
                    actionsHtml = '<span style="color: #9ca3af; font-size: 0.85rem;">Max reached</span>';
                }

                row.innerHTML = `
                    <td>${student.ADM}</td>
                    <td>${studentFullName}</td>
                    <td>${student.gender}</td>
                    <td>${subjectBadgesHtml}</td>
                    <td>${statusHtml}</td>
                    <td>${actionsHtml}</td>
                `;
                tableBody.appendChild(row);
            }
        }

        // Student search functionality
        document.addEventListener('DOMContentLoaded', () => {
            const studentSearchInput = document.getElementById('studentSearchInput');
            if (studentSearchInput) {
                studentSearchInput.addEventListener('keyup', (event) => {
                    const searchTerm = event.target.value.toLowerCase();
                    const filteredStudents = allStudentsInStream.filter(student => {
                        const fullName = `${student.surname} ${student.other_names}`.toLowerCase();
                        const adm = student.ADM.toLowerCase();
                        return fullName.includes(searchTerm) || adm.includes(searchTerm);
                    });
                    renderStudentsTable(filteredStudents);
                });
            }
        });

        function openAddSubjectModal(studentAdm, studentName) {
            document.getElementById('add_subject_student_adm').value = studentAdm;
            document.getElementById('add_subject_student_name_display').textContent = studentName;
            document.getElementById('add_subject_class_id').value = currentManageStudentsClassId;
            document.getElementById('add_subject_stream_id').value = currentManageStudentsStreamId;

            // Populate optional subjects dropdown
            const subjectSelect = document.getElementById('optional_subject_select');
            subjectSelect.innerHTML = '<option value="">-- Select Subject --</option>';

            optionalSubjectsForClass.forEach(subject => {
                const option = document.createElement('option');
                option.value = subject.subject_id;
                option.textContent = subject.subject_name;
                subjectSelect.appendChild(option);
            });

            // Close manage students modal temporarily
            document.getElementById('manageStudentsModal').classList.add('hidden');
            openModal('addSubjectToStudentModal');
        }

        async function saveStudentSubjectChoice() {
            const studentAdm = document.getElementById('add_subject_student_adm').value;
            const subjectId = document.getElementById('optional_subject_select').value;
            const classId = document.getElementById('add_subject_class_id').value;
            const streamId = document.getElementById('add_subject_stream_id').value;

            if (!subjectId) {
                showMessage('Please select a subject', 'error');
                return;
            }

            try {
                const response = await fetch('admin_classes_api.php?action=save_student_subject_choice', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        student_adm: studentAdm,
                        subject_id: parseInt(subjectId),
                        class_id: parseInt(classId),
                        stream_id: parseInt(streamId)
                    })
                });

                const data = await response.json();
                if (data.success) {
                    showMessage(data.message, 'success');
                    closeModals();
                    // Reopen manage students modal and reload the students list
                    document.getElementById('manageStudentsModal').classList.remove('hidden');
                    overlay.classList.add('active');
                    await loadStudentsForStream(classId, streamId);
                } else {
                    showMessage(data.message, 'error');
                }
            } catch (error) {
                showMessage(`Network error: ${error.message}`, 'error');
            }
        }

        async function removeStudentSubject(studentAdm, subjectId) {
            showConfirmModal(
                'Remove Subject',
                'Are you sure you want to remove this subject from the student?',
                async function() {
                    try {
                        const response = await fetch('admin_classes_api.php?action=remove_student_subject_choice', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                student_adm: studentAdm,
                                subject_id: parseInt(subjectId)
                            })
                        });

                        const data = await response.json();
                        if (data.success) {
                            showMessage(data.message, 'success');
                            // Reload the students list
                            await loadStudentsForStream(currentManageStudentsClassId, currentManageStudentsStreamId);
                        } else {
                            showMessage(data.message, 'error');
                        }
                    } catch (error) {
                        showMessage(`Network error: ${error.message}`, 'error');
                    }
                }
            );
        }

        // ==================== END STUDENT MANAGEMENT FUNCTIONS ====================
    </script>
</body>
</html>