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

// Define role constants (assuming these are defined in config.php or similar)
// IMPORTANT: If config.php already defines these, REMOVE these lines to avoid 'already defined' errors.
if (!defined('ROLE_SUPER_ADMIN')) define('ROLE_SUPER_ADMIN', 1);
if (!defined('ROLE_ADMIN')) define('ROLE_ADMIN', 2);
if (!defined('ROLE_TEACHER')) define('ROLE_TEACHER', 3);
if (!defined('ROLE_STUDENT')) define('ROLE_STUDENT', 4);

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

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

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

// Initialize classes array
$classes = [];
$search_query = $_GET['search'] ?? ''; // Get search query from GET for initial load

// Initialize teachers and subjects arrays for assignment dropdowns/checkboxes
$all_teachers = [];
$all_subjects = [];
$total_students_count = 0; // Initialize total students count

// Handle form submissions (Add, Edit, Delete, Assign Class Teacher, Assign Class Subjects, Save Subject Teachers, Add Stream)
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Ensure $conn is available for POST operations
    if (!isset($conn) || !$conn instanceof mysqli) {
        require_once 'config.php';
        // Add a check after requiring config.php again
        if ($conn->connect_error) {
            $_SESSION['message'] = "Database connection failed for POST operation: " . $conn->connect_error;
            $_SESSION['message_type'] = "error";
            header("Location: admin_classes.php");
            exit();
        }
    }

    if (isset($_POST['action'])) {
        $action = $_POST['action'];

        if ($action == 'add_class') {
            $new_class_name = trim($_POST['class_name']);

            if (!empty($new_class_name)) {
                // Check if class name already exists for this school
                $check_sql = "SELECT class_id FROM classes WHERE class_name = ? AND school_id = ?";
                if ($check_stmt = $conn->prepare($check_sql)) {
                    $check_stmt->bind_param("si", $new_class_name, $current_user_school_id);
                    $check_stmt->execute();
                    $check_stmt->store_result();
                    if ($check_stmt->num_rows > 0) {
                        $_SESSION['message'] = "Error: Class name already exists in this school.";
                        $_SESSION['message_type'] = "error";
                        $check_stmt->close();
                        header("Location: admin_classes.php");
                        exit();
                    }
                    $check_stmt->close();
                } else {
                    $_SESSION['message'] = "Database error (check class): " . $conn->error;
                    $_SESSION['message_type'] = "error";
                    header("Location: admin_classes.php");
                    exit();
                }

                $insert_sql = "INSERT INTO classes (school_id, class_name) VALUES (?, ?)";
                if ($insert_stmt = $conn->prepare($insert_sql)) {
                    $insert_stmt->bind_param("is", $current_user_school_id, $new_class_name);
                    if ($insert_stmt->execute()) {
                        $_SESSION['message'] = "Class added successfully!";
                        $_SESSION['message_type'] = "success";
                    } else {
                        $_SESSION['message'] = "Error adding class: " . $insert_stmt->error;
                        $_SESSION['message_type'] = "error";
                    }
                    $insert_stmt->close();
                } else {
                    $_SESSION['message'] = "Database error (prepare insert): " . $conn->error;
                    $_SESSION['message_type'] = "error";
                }
            } else {
                $_SESSION['message'] = "Class name is required.";
                $_SESSION['message_type'] = "error";
            }
        } elseif ($action == 'edit_class') {
            $edit_class_id = trim($_POST['edit_class_id']);
            $edit_class_name = trim($_POST['edit_class_name']);

            if (!empty($edit_class_id) && !empty($edit_class_name)) {
                // Check for duplicate class name excluding the current class
                $check_sql = "SELECT class_id FROM classes WHERE class_name = ? AND school_id = ? AND class_id != ?";
                if ($check_stmt = $conn->prepare($check_sql)) {
                    $check_stmt->bind_param("sii", $edit_class_name, $current_user_school_id, $edit_class_id);
                    $check_stmt->execute();
                    $check_stmt->store_result();
                    if ($check_stmt->num_rows > 0) {
                        $_SESSION['message'] = "Error: Class name already exists in this school.";
                        $_SESSION['message_type'] = "error";
                        $check_stmt->close();
                        header("Location: admin_classes.php");
                        exit();
                    }
                    $check_stmt->close();
                } else {
                    $_SESSION['message'] = "Database error (check class update): " . $conn->error;
                    $_SESSION['message_type'] = "error";
                    header("Location: admin_classes.php");
                    exit();
                }

                $update_sql = "UPDATE classes SET class_name = ? WHERE class_id = ? AND school_id = ?";
                if ($update_stmt = $conn->prepare($update_sql)) {
                    $update_stmt->bind_param("sii", $edit_class_name, $edit_class_id, $current_user_school_id);
                    if ($update_stmt->execute()) {
                        $_SESSION['message'] = "Class updated successfully!";
                        $_SESSION['message_type'] = "success";
                    } else {
                        $_SESSION['message'] = "Error updating class: " . $update_stmt->error;
                        $_SESSION['message_type'] = "error";
                    }
                    $update_stmt->close();
                } else {
                    $_SESSION['message'] = "Database error (prepare update): " . $conn->error;
                    $_SESSION['message_type'] = "error";
                }
            } else {
                $_SESSION['message'] = "Class ID and Class name are required for editing.";
                $_SESSION['message_type'] = "error";
            }
        } elseif ($action == 'delete_class') {
            $delete_class_id = trim($_POST['delete_class_id']);

            if (!empty($delete_class_id)) {
                $delete_sql = "DELETE FROM classes WHERE class_id = ? AND school_id = ?";
                if ($delete_stmt = $conn->prepare($delete_sql)) {
                    $delete_stmt->bind_param("ii", $delete_class_id, $current_user_school_id);
                    if ($delete_stmt->execute()) {
                        $_SESSION['message'] = "Class deleted successfully!";
                        $_SESSION['message_type'] = "success";
                    } else {
                        $_SESSION['message'] = "Error deleting class: " . $delete_stmt->error;
                        $_SESSION['message_type'] = "error";
                    }
                    $delete_stmt->close();
                } else {
                    $_SESSION['message'] = "Database error (delete): " . $conn->error;
                    $_SESSION['message_type'] = "error";
                }
            } else {
                $_SESSION['message'] = "No class ID provided for deletion.";
                $_SESSION['message_type'] = "error";
            }
        } elseif ($action == 'assign_class_teacher') {
            // This section is for assigning a 'class teacher' typically
            // to a whole class, not per subject/stream.
            // If you want to replace 'class_teachers' with 'teacher_stream_subject_assignments'
            // for this functionality, you would need a designated 'class teacher' subject
            // and perhaps a generic 'class' stream in your new table schema.
            // For now, this part remains unchanged as per the existing table.
            $class_id = $_POST['class_id'];
            $teacher_user_id = $_POST['teacher_user_id']; // Can be 'none' or a user_id

            if (!empty($class_id)) {
                // Start transaction
                $conn->begin_transaction();
                try {
                    // Delete existing assignment for this class
                    $delete_sql = "DELETE FROM class_teachers WHERE class_id = ?";
                    if ($delete_stmt = $conn->prepare($delete_sql)) {
                        $delete_stmt->bind_param("i", $class_id);
                        $delete_stmt->execute();
                        $delete_stmt->close();
                    } else {
                        throw new Exception("Database error (prepare delete existing class teacher): " . $conn->error);
                    }

                    // Insert new assignment if a teacher was selected
                    if ($teacher_user_id !== 'none') {
                        $insert_sql = "INSERT INTO class_teachers (class_id, teacher_user_id) VALUES (?, ?)";
                        if ($insert_stmt = $conn->prepare($insert_sql)) {
                            $insert_stmt->bind_param("ii", $class_id, $teacher_user_id);
                            $insert_stmt->execute();
                            $insert_stmt->close();
                        } else {
                            throw new Exception("Database error (prepare insert new class teacher): " . $conn->error);
                        }
                    }

                    $conn->commit();
                    $_SESSION['message'] = "Class teacher assigned successfully!";
                    $_SESSION['message_type'] = "success";
                } catch (Exception $e) {
                    $conn->rollback();
                    $_SESSION['message'] = "Error assigning class teacher: " . $e->getMessage();
                    $_SESSION['message_type'] = "error";
                }
            } else {
                $_SESSION['message'] = "No class ID provided for teacher assignment.";
                $_SESSION['message_type'] = "error";
            }
        } elseif ($action == 'assign_class_subjects') {
            // This section manages which subjects are offered in a class,
            // not who teaches them. It uses the 'class_subjects' table.
            // This is distinct from 'teacher_stream_subject_assignments'.
            // For now, this part remains unchanged as per the existing table.
            $class_id = $_POST['class_id'];
            $selected_subjects = isset($_POST['subjects']) ? $_POST['subjects'] : []; // Array of subject_ids

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

                    // 2. Insert new assignments
                    if (!empty($selected_subjects)) {
                        $insert_sql = "INSERT INTO class_subjects (class_id, subject_id) VALUES (?, ?)";
                        if ($insert_stmt = $conn->prepare($insert_sql)) {
                            foreach ($selected_subjects as $subject_id) {
                                $insert_stmt->bind_param("ii", $class_id, $subject_id);
                                $insert_stmt->execute();
                            }
                            $insert_stmt->close();
                        } else {
                            throw new Exception("Database error (prepare insert new class subjects): " . $conn->error);
                        }
                    }

                    $conn->commit();
                    $_SESSION['message'] = "Subjects assigned to class successfully!";
                    $_SESSION['message_type'] = "success";
                } catch (Exception $e) {
                    $conn->rollback();
                    $_SESSION['message'] = "Error assigning subjects to class: " . $e->getMessage();
                    $_SESSION['message_type'] = "error";
                }
            } else {
                $_SESSION['message'] = "No class ID provided for subject assignment.";
                $_SESSION['message_type'] = "error";
            }
    } elseif ($action == 'save_subject_teachers') {
            $class_id = (int)$_POST['class_id']; // Now directly used for the assignment context
            $stream_id = (int)$_POST['selected_stream'];
            $academic_year = trim($_POST['academic_year'] ?? ''); // REQUIRED: Must be sent from frontend
            $term = trim($_POST['term'] ?? ''); // REQUIRED: Must be sent from frontend
            $subject_assignments = json_decode($_POST['subject_assignments'], true); // Decode JSON string

            if (empty($academic_year) || empty($term)) {
                $_SESSION['message'] = "Academic Year and Term are required for subject teacher assignments.";
                $_SESSION['message_type'] = "error";
                header("Location: admin_classes.php"); // Redirect back
                exit();
            }

            // Ensure class_id and stream_id are valid (non-zero for integer types, as 0 might mean "not selected")
            if ($class_id > 0 && $stream_id > 0 && is_array($subject_assignments)) {
                $conn->begin_transaction();
                try {
                    // 1. Delete all existing subject teacher assignments for this specific class, stream, academic year, and term for the current school
                    // This ensures that unselected assignments are removed and current ones are re-added, maintaining data consistency.
                    $delete_all_sql = "DELETE FROM class_subject_teachers
                                         WHERE class_id = ? AND stream_id = ? AND academic_year = ? AND term = ? AND school_id = ?";
                    if ($delete_all_stmt = $conn->prepare($delete_all_sql)) {
                        $delete_all_stmt->bind_param("iisssi", $class_id, $stream_id, $academic_year, $term, $current_user_school_id);
                        $delete_all_stmt->execute();
                        $delete_all_stmt->close();
                    } else {
                        throw new Exception("Database error (prepare delete all existing subject teachers): " . $conn->error);
                    }

                    // 2. Insert new assignments
                    // Each assignment in $subject_assignments represents a subject-teacher pair for the selected class/stream/year/term.
                    // The 'class_subject_teachers' table has: class_id, stream_id, subject_id, teacher_user_id, academic_year, term, school_id
                    $insert_sql = "INSERT INTO class_subject_teachers
                                       (class_id, stream_id, subject_id, teacher_user_id, academic_year, term, school_id)
                                       VALUES (?, ?, ?, ?, ?, ?, ?)";
                    if ($insert_stmt = $conn->prepare($insert_sql)) {
                        foreach ($subject_assignments as $assignment) {
                            $subject_id = $assignment['subject_id'];
                            $teacher_user_id = $assignment['teacher_1_id'] ?? 'none'; // Assuming 'teacher_1_id' for the assigned teacher

                            // Only insert if a valid teacher is selected for the subject
                            if ($teacher_user_id !== 'none' && !empty($teacher_user_id)) {
                                $insert_stmt->bind_param("iiisssi", $class_id, $stream_id, $subject_id, $teacher_user_id, $academic_year, $term, $current_user_school_id);
                                $insert_stmt->execute();
                                if ($insert_stmt->errno) {
                                    // Log the error but don't necessarily roll back the whole transaction for one failed insert
                                    error_log("Error inserting assignment (class_id: {$class_id}, stream_id: {$stream_id}, subject_id: {$subject_id}, teacher_id: {$teacher_user_id}): " . $insert_stmt->error);
                                }
                            }
                        }
                        $insert_stmt->close();
                    } else {
                        throw new Exception("Database error (prepare insert new subject teachers): " . $conn->error);
                    }

                    $conn->commit();
                    $_SESSION['message'] = "Subject teachers assigned successfully for Class ID " . $class_id . ", Stream ID " . $stream_id . " in " . $academic_year . " " . $term . "!";
                    $_SESSION['message_type'] = "success";
                } catch (Exception $e) {
                    $conn->rollback();
                    $_SESSION['message'] = "Error saving subject teachers: " . $e->getMessage();
                    $_SESSION['message_type'] = "error";
                }
            } else {
                $_SESSION['message'] = "Invalid data provided for saving subject teachers. Please ensure Class, Stream, Academic Year, and Term are selected.";
                $_SESSION['message_type'] = "error";
            }
        



        } elseif ($action == 'add_stream') {
            $class_id = trim($_POST['stream_class_id']);
            $new_stream_name = trim($_POST['new_stream_name']);

            if (!empty($class_id) && !empty($new_stream_name)) {
                // Check if stream name already exists for this class in the 'streams' table AND for this school
                $check_sql = "SELECT stream_id FROM streams WHERE class_id = ? AND stream_name = ? AND school_id = ?";
                if ($check_stmt = $conn->prepare($check_sql)) {
                    $check_stmt->bind_param("isi", $class_id, $new_stream_name, $current_user_school_id);
                    $check_stmt->execute();
                    $check_stmt->store_result();
                    if ($check_stmt->num_rows > 0) {
                        $_SESSION['message'] = "Error: Stream name already exists for this class in your school.";
                        $_SESSION['message_type'] = "error";
                        $check_stmt->close();
                        header("Location: admin_classes.php");
                        exit();
                    }
                    $check_stmt->close();
                } else {
                    $_SESSION['message'] = "Database error (check stream): " . $conn->error;
                    $_SESSION['message_type'] = "error";
                    header("Location: admin_classes.php");
                    exit();
                }

                // Insert into the 'streams' table, including school_id
                $insert_sql = "INSERT INTO streams (class_id, stream_name, school_id) VALUES (?, ?, ?)";
                if ($insert_stmt = $conn->prepare($insert_sql)) {
                    $insert_stmt->bind_param("isi", $class_id, $new_stream_name, $current_user_school_id);
                    if ($insert_stmt->execute()) {
                        $_SESSION['message'] = "Stream added successfully!";
                        $_SESSION['message_type'] = "success";
                    } else {
                        $_SESSION['message'] = "Error adding stream: " . $insert_stmt->error;
                        $_SESSION['message_type'] = "error";
                    }
                    $insert_stmt->close();
                } else {
                    $_SESSION['message'] = "Database error (prepare insert stream): " . $conn->error;
                    $_SESSION['message_type'] = "error";
                }
            } else {
                $_SESSION['message'] = "Class and Stream name are required.";
                $_SESSION['message_type'] = "error";
            }
        }
    }
    header("Location: admin_classes.php");
    exit();
}

// Fetch additional user details from the database for the logged-in admin
if (isset($conn) && $conn instanceof mysqli) {
    $sql = "SELECT phone_number, photo, status FROM users WHERE id = ? AND school_id = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("ii", $user_id, $current_user_school_id);
        if ($stmt->execute()) {
            $stmt->bind_result($phone_number_db, $photo_db, $status_db);
            $stmt->fetch();
            $phone_number = htmlspecialchars($phone_number_db ?? 'N/A');
            $photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD';
            $status = htmlspecialchars($status_db ?? 'N/A');
        }
        $stmt->close();
    } else {
        error_log("Failed to prepare user details query: " . $conn->error);
    }

    // Fetch School Name and Logo
    $sql_school = "SELECT school_name, logo FROM schools WHERE school_id = ?";
    if ($stmt_school = $conn->prepare($sql_school)) {
        $stmt_school->bind_param("i", $current_user_school_id);
        if ($stmt_school->execute()) {
            $stmt_school->bind_result($school_name_db, $school_logo_db);
            if ($stmt_school->fetch()) {
                $school_name = htmlspecialchars($school_name_db);
                $school_logo_path = !empty($school_logo_db) ? htmlspecialchars($school_logo_db) : 'images/default_school_logo.png';
            }
        }
        $stmt_school->close();
    } else {
        error_log("Failed to prepare school data query: " . $conn->error);
    }

    // Fetch ALL Classes for the current school, including assigned teacher username AND student count
    $all_classes_data = [];
    $sql_all_classes = "SELECT c.class_id, c.class_name,
                                u.username AS class_teacher_name, u.id AS class_teacher_id,
                                (SELECT COUNT(s.user_id) FROM students s WHERE s.class = c.class_name AND s.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 = ?
                         GROUP BY c.class_id, c.class_name, u.username, u.id
                         ORDER BY c.class_name ASC";

    if ($stmt_all_classes = $conn->prepare($sql_all_classes)) {
        $stmt_all_classes->bind_param("i", $current_user_school_id);
        if ($stmt_all_classes->execute()) {
            $result_all_classes = $stmt_all_classes->get_result();
            while ($row = $result_all_classes->fetch_assoc()) {
                $all_classes_data[] = $row;
            }
        } else {
            error_log("Failed to execute all classes data query: " . $stmt_all_classes->error);
        }
        $stmt_all_classes->close();
    } else {
        error_log("Failed to prepare all classes data query: " . $conn->error);
    }

    // Fetch TOTAL Students Count for the current school
    $sql_total_students = "SELECT COUNT(u.id) AS total_students
                            FROM users u
                            JOIN students s ON u.id = s.user_id
                            WHERE u.school_id = ? AND u.role = ?";
    if ($stmt_total_students = $conn->prepare($sql_total_students)) {
        $student_role_code_var = ROLE_STUDENT; // Assign to a variable for bind_param
        $stmt_total_students->bind_param("ii", $current_user_school_id, $student_role_code_var);
        if ($stmt_total_students->execute()) {
            $stmt_total_students->bind_result($total_students_count_db);
            $stmt_total_students->fetch();
            $total_students_count = $total_students_count_db;
        } else {
            error_log("Failed to execute total students query: " . $stmt_total_students->error);
        }
        $stmt_total_students->close();
    } else {
        error_log("Failed to prepare total students query: " . $conn->error);
    }


    // Fetch ALL Teachers for the current school (for assignment dropdown)
    $teacher_role_code = ROLE_TEACHER;
    $sql_all_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 = ? ORDER BY u.username ASC";
    if ($stmt_all_teachers = $conn->prepare($sql_all_teachers)) {
        $teacher_role_code_var = $teacher_role_code; // Assign to a variable for bind_param
        $stmt_all_teachers->bind_param("ii", $current_user_school_id, $teacher_role_code_var);
        if ($stmt_all_teachers->execute()) {
            $result_all_teachers = $stmt_all_teachers->get_result();
            while ($row = $result_all_teachers->fetch_assoc()) {
                $all_teachers[] = $row;
            }
        } else {
            error_log("Failed to execute all teachers query: " . $stmt_all_teachers->error);
        }
        $stmt_all_teachers->close();
    } else {
        error_log("Failed to prepare all teachers query: " . $conn->error);
    }

    // Fetch ALL Subjects for the current school (for assignment checkboxes and manage modal)
    $sql_all_subjects = "SELECT subject_id, subject_name FROM subjects WHERE school_id = ? ORDER BY subject_name ASC";
    if ($stmt_all_subjects = $conn->prepare($sql_all_subjects)) {
        $stmt_all_subjects->bind_param("i", $current_user_school_id);
        if ($stmt_all_subjects->execute()) {
            $result_all_subjects = $stmt_all_subjects->get_result();
            while ($row = $result_all_subjects->fetch_assoc()) {
                $all_subjects[] = $row;
            }
        }
        $stmt_all_subjects->close();
    } else {
        error_log("Failed to prepare all subjects query: " . $conn->error);
    }


    $conn->close();
} else {
    error_log("Database connection \$conn not available in admin_classes.php");
    $photo = 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD';
}

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

// Check for and display messages
$message = $_SESSION['message'] ?? '';
$message_type = $_SESSION['message_type'] ?? '';
// Unset messages after displaying (optional, but good for one-time messages)
unset($_SESSION['message']);
unset($_SESSION['message_type']);

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Class Management - <?php echo $school_name; ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="icon" href="<?php echo $school_logo_path; ?>" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        /* Custom styles for the sidebar and overlay to integrate with Tailwind */
        .dashboard-container {
            display: flex;
            min-height: 100vh;
            font-family: "Inter", sans-serif; /* Apply Inter font */
        }
        .sidebar {
            width: 280px;
            flex-shrink: 0;
            transition: all 0.3s ease-in-out;
            transform: translateX(0);
            z-index: 50; /* Tailwind z-index-50 */
        }
        .sidebar.active {
            transform: translateX(-100%);
        }
        .main-content {
            flex-grow: 1;
            transition: margin-left 0.3s ease-in-out;
        }
        .dashboard-container.sidebar-open .main-content {
            margin-left: 0; /* Adjust for mobile when sidebar is hidden */
        }
        .overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 40; /* Tailwind z-index-40 */
        }
        .overlay.active {
            display: block;
        }

        /* Custom styles for modals */
        .modal {
            position: fixed; /* Stay in place */
            z-index: 100; /* Sit on top */
            left: 0;
            top: 0;
            width: 100%; /* Full width */
            height: 100%;
            overflow: auto; /* Enable scroll if needed */
            background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
            display: flex; /* Use flexbox for centering */
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background-color: #fefefe;
            margin: auto; /* Centered */
            padding: 20px;
            border-radius: 0.75rem; /* rounded-xl */
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05); /* shadow-xl */
            position: relative;
            width: 90%; /* Responsive width */
            max-width: 500px; /* Max width for class forms */
            animation: fadeIn 0.3s ease-out;
            /* Added styles for attractiveness */
            border-bottom: 4px solid #4f46e5; /* indigo-600 */
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); /* shadow-2xl */
        }
        /* Adjust max-width for subject assignment modal if needed */
        #assignSubjectsModal .modal-content,
        #manageClassDetailsModal .modal-content {
            max-width: 800px; /* Wider for subject teacher assignments */
        }

        .close-button {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

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

        /* Animation for modal */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* Message styling */
        .message {
            padding: 1rem;
            margin-bottom: 1rem;
            border-radius: 0.5rem; /* rounded-lg */
            font-weight: 500; /* font-medium */
            opacity: 1;
            transition: opacity 0.5s ease-out;
            /* Enhanced message styling */
            font-weight: bold;
        }
        .message.success {
            background-color: #d4edda; /* green-100 */
            color: #155724; /* green-800 */
            border: 1px solid #68d391; /* green-400 */
        }
        .message.error {
            background-color: #f8d7da; /* red-100 */
            color: #721c24; /* red-800 */
            border: 1px solid #f6ad55; /* red-400 */
        }

        /* Table responsiveness */
        .table-responsive-wrapper {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch; /* For smoother scrolling on iOS */
        }
        .data-table {
            width: 100%;
            border-collapse: separate; /* Allows border-radius on cells */
            border-spacing: 0;
            min-width: 800px; /* Adjusted min-width for new columns */
        }
        .data-table th, .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #e2e8f0; /* border-b border-gray-200 */
        }
        .data-table thead th {
            background-color: #f8fafc; /* gray-50 */
            font-weight: 600; /* font-semibold */
            color: #4a5568; /* gray-700 */
            text-transform: uppercase;
            font-size: 0.75rem; /* text-xs */
            letter-spacing: 0.05em; /* tracking-wider */
        }
        .data-table tbody tr:last-child td {
            border-bottom: none;
        }
        .data-table tbody tr:hover {
            background-color: #f0f4f8; /* gray-100 */
        }
        .data-table tbody td {
            color: #2d3748; /* gray-800 */
        }
        .data-table tfoot td {
            font-weight: 600;
            background-color: #f0f4f8;
            border-top: 2px solid #cbd5e0;
        }


        /* Form group spacing */
        .form-group {
            margin-bottom: 1rem; /* mb-4 */
        }
        .form-group label {
            display: block;
            /* Enhanced label styling */
            font-weight: 600; /* font-semibold */
            color: #2d3748; /* gray-800 */
            margin-bottom: 0.5rem; /* mb-2 */
        }
        .form-group input[type="text"],
        .form-group select {
            width: 100%;
            padding: 0.75rem; /* p-3 */
            border: 1px solid #cbd5e0; /* border-gray-300 */
            border-radius: 0.5rem; /* rounded-lg */
            box-shadow: inset 0 1px 2px /* ... */
    </style>
</head>
<body>
    </body>
</html>