<?php
// Start a new session or resume an existing one.
session_start();

// Include the database configuration file. This file should contain database connection details ($conn).
require_once 'config.php'; // Ensure this path is correct.

// Define role constants if they haven't been defined yet.
if (!defined('ROLE_SUPER_ADMIN')) define('ROLE_SUPER_ADMIN', 1);
if (!defined('ROLE_ADMIN')) define('ROLE_ADMIN', 2);
if (!defined('ROLE_TEACHER')) define('ROLE_TEACHER', 3);
if (!defined('ROLE_STUDENT')) define('ROLE_STUDENT', 4);
if (!defined('ROLE_PARENT')) define('ROLE_PARENT', 5);
if (!defined('ROLE_STAFF')) define('ROLE_STAFF', 6);

// Handle AJAX data requests before any HTML output
if (isset($_GET['fetch_data']) && isset($_SESSION["school_id"]) && $conn instanceof mysqli) {
    header('Content-Type: application/json');
    $current_user_school_id = $_SESSION["school_id"];
    $data = [];

    switch ($_GET['fetch_data']) {
        case 'subjects':
            $sql = "SELECT subject_id, subject_name FROM subjects WHERE school_id = ? ORDER BY subject_name";
            if ($stmt = $conn->prepare($sql)) {
                $stmt->bind_param("i", $current_user_school_id);
                $stmt->execute();
                $result = $stmt->get_result();
                while ($row = $result->fetch_assoc()) {
                    $data[] = $row;
                }
                $result->free_result(); // Free result set
                $stmt->close();
                unset($stmt); // Unset statement variable
            }
            break;
        case 'subject_combinations':
            $sql = "SELECT sc.combination_name, sc.combination_code, sc.combination_description, sc.applicable_levels, GROUP_CONCAT(s.subject_name SEPARATOR ', ') as subjects_list 
                   FROM subject_combinations sc 
                   LEFT JOIN combination_subjects cs ON sc.combination_id = cs.combination_id 
                   LEFT JOIN subjects s ON cs.subject_id = s.subject_id 
                   WHERE sc.school_id = ? 
                   GROUP BY sc.combination_id, sc.combination_name, sc.combination_code, sc.combination_description, sc.applicable_levels 
                   ORDER BY sc.combination_name";
            if ($stmt = $conn->prepare($sql)) {
                $stmt->bind_param("i", $current_user_school_id);
                $stmt->execute();
                $result = $stmt->get_result();
                while ($row = $result->fetch_assoc()) {
                    // IMPORTANT: Use combination_name as the primary identifier for external references (student records, etc.)
                    // This ensures that students store actual combination names like "Physics-Chemistry-Mathematics" 
                    // instead of codes like "PCM" when assigned combinations in senior 5-6
                    $data[] = [
                        'combination_id' => $row['combination_name'], // Store name as ID for frontend compatibility
                        'combination_name' => $row['combination_name'], 
                        'combination_code' => $row['combination_code'],
                        'combination_description' => $row['combination_description'],
                        'applicable_levels' => $row['applicable_levels'],
                        'subjects_list' => $row['subjects_list']
                    ];
                }
                $result->free_result();
                $stmt->close();
                unset($stmt);
            }
            break;
        case 'papers':
            $subject_id = filter_input(INPUT_GET, 'subject_id', FILTER_VALIDATE_INT);
            if ($subject_id) {
                // If a subject_id is provided, fetch papers for that specific subject
                $sql = "SELECT paper_id, paper_name FROM subject_papers WHERE subject_id = ? AND school_id = ? ORDER BY paper_name";
                if ($stmt = $conn->prepare($sql)) {
                    $stmt->bind_param("ii", $subject_id, $current_user_school_id);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    while ($row = $result->fetch_assoc()) {
                        $data[] = $row;
                    }
                    $result->free_result(); // Free result set
                    $stmt->close();
                    unset($stmt); // Unset statement variable
                }
            } else {
                // If no subject_id is provided, fetch all papers for the school (for main 'Add New Paper')
                $sql = "SELECT paper_id, paper_name, subject_id FROM subject_papers WHERE school_id = ? ORDER BY paper_name";
                if ($stmt = $conn->prepare($sql)) {
                    $stmt->bind_param("i", $current_user_school_id);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    while ($row = $result->fetch_assoc()) {
                        $data[] = $row;
                    }
                    $result->free_result(); // Free result set
                    $stmt->close();
                    unset($stmt); // Unset statement variable
                }
            }
            break;
        case 'topics':
            $paper_id = filter_input(INPUT_GET, 'paper_id', FILTER_VALIDATE_INT);
            if ($paper_id) {
                // If a paper_id is provided, fetch topics for that specific paper
                $sql = "SELECT topic_id, topic_name FROM topics WHERE paper_id = ? AND school_id = ? ORDER BY topic_name";
                if ($stmt = $conn->prepare($sql)) {
                    $stmt->bind_param("ii", $paper_id, $current_user_school_id);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    while ($row = $result->fetch_assoc()) {
                        $data[] = $row;
                    }
                    $result->free_result(); // Free result set
                    $stmt->close();
                    unset($stmt); // Unset statement variable
                }
            } else {
                // If no paper_id is provided, fetch all topics for the school (for main 'Add New Topic')
                $sql = "SELECT topic_id, topic_name, paper_id FROM topics WHERE school_id = ? ORDER BY topic_name";
                if ($stmt = $conn->prepare($sql)) {
                    $stmt->bind_param("i", $current_user_school_id);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    while ($row = $result->fetch_assoc()) {
                        $data[] = $row;
                    }
                    $result->free_result(); // Free result set
                    $stmt->close();
                    unset($stmt); // Unset statement variable
                }
            }
            break;
    }
    echo json_encode($data);
    $conn->close(); // Close connection after sending JSON
    exit; // Terminate script execution
}

/**
 * Function to check the current user's role and redirect if unauthorized.
 * This ensures only Admins can access this page.
 *
 * @param int $required_role_code The integer code of the role required to access the page.
 */
function check_role_access($required_role_code) {
    if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || !isset($_SESSION["school_id"])) {
        header("location: login.php");
        exit;
    }

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

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

// Fetch user details from session variables.
$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]); // Sanitize for display.
$user_role_code = $_SESSION["role"];
$current_user_school_id = $_SESSION["school_id"];

// Initialize variables for user and school data.
$phone_number = $photo = $status = "";
$school_name = "School Name Not Found";
$school_name_for_js = "School Name Not Found";
$school_logo_path = "images/default_school_logo.png";

// Initialize message for feedback.
$feedback_message = '';

// Ensure $conn is available from config.php.
if (isset($conn) && $conn instanceof mysqli) {
    // Fetch additional user details.
    $sql_user_details = "SELECT phone_number, photo, status FROM users WHERE id = ? AND school_id = ?";
    if ($stmt_user = $conn->prepare($sql_user_details)) {
        $stmt_user->bind_param("ii", $user_id, $current_user_school_id);
        if ($stmt_user->execute()) {
            $result_user = $stmt_user->get_result(); // Use get_result()
            if ($row = $result_user->fetch_assoc()) { // Fetch data
                $phone_number = $row['phone_number'];
                $photo = $row['photo'];
                $status = $row['status'];
            }
            $result_user->free_result(); // Free result set
        } else {
            error_log("Execute failed for user details query in admin_subjects.php: " . $stmt_user->error);
        }
        $stmt_user->close();
        unset($stmt_user); // Unset statement variable
    } else {
        error_log("Prepare failed for user details query in admin_subjects.php: " . $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()) {
            $result_school = $stmt_school->get_result(); // Use get_result()
            if ($row = $result_school->fetch_assoc()) { // Fetch data
                $school_name = htmlspecialchars($row['school_name']);
                $school_name_for_js = addslashes($row['school_name']);
                $school_logo_path = !empty($row['logo']) ? htmlspecialchars($row['logo']) : 'images/default_school_logo.png';
            } else {
                error_log("School details not found for school_id: " . $current_user_school_id);
            }
            $result_school->free_result(); // Free result set
        } else {
            error_log("Execute failed for school data query in admin_subjects.php: " . $stmt_school->error);
        }
        $stmt_school->close();
        unset($stmt_school); // Unset statement variable
    } else {
        error_log("Prepare failed for school data query in admin_subjects.php: " . $conn->error);
    }

    // --- CRUD Operations for Subjects, Papers, Topics, Competencies ---
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (isset($_POST['action'])) {
            $action = $_POST['action'];

            // Handle Subject Operations
            if ($action == 'add_subject') {
                $subject_name = filter_input(INPUT_POST, 'subject_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $subject_category = filter_input(INPUT_POST, 'subject_category', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $applicable_levels = isset($_POST['applicable_levels']) && is_array($_POST['applicable_levels']) ? implode(',', $_POST['applicable_levels']) : '';
                $min_students = filter_input(INPUT_POST, 'min_students', FILTER_VALIDATE_INT);
                $max_students = filter_input(INPUT_POST, 'max_students', FILTER_VALIDATE_INT);
                $subject_description = filter_input(INPUT_POST, 'subject_description', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                
                if (!empty($subject_name)) {
                    // Check if subject already exists for this school
                    $check_sql = "SELECT COUNT(*) FROM subjects WHERE school_id = ? AND subject_name = ?";
                    if ($check_stmt = $conn->prepare($check_sql)) {
                        $check_stmt->bind_param("is", $current_user_school_id, $subject_name);
                        $check_stmt->execute();
                        $check_result = $check_stmt->get_result(); // Use get_result()
                        $row = $check_result->fetch_assoc(); // Fetch the single row
                        $count = $row['COUNT(*)']; // Get the count
                        $check_result->free_result(); // Free result set
                        $check_stmt->close();
                        unset($check_stmt);

                        if ($count > 0) {
                            $feedback_message = "<div class='error'>Error: A subject with this name already exists for your school.</div>";
                        } else {
                            // Generate unique subject code
                            $subject_code = '';
                            $base_code = '';
                            
                            // Extract letters from subject name (remove special characters and numbers)
                            $clean_name = preg_replace('/[^A-Za-z ]/', '', strtoupper($subject_name));
                            $words = explode(' ', trim($clean_name));
                            
                            // Strategy: Use first letter of each word, or first 3 letters if single word
                            if (count($words) > 1) {
                                // Multiple words: use first letter of each word
                                foreach ($words as $word) {
                                    if (!empty($word)) {
                                        $base_code .= substr($word, 0, 1);
                                    }
                                }
                            } else {
                                // Single word: use first 1-3 letters
                                $base_code = substr($clean_name, 0, min(3, strlen($clean_name)));
                            }
                            
                            // Ensure we have at least one character
                            if (empty($base_code)) {
                                $base_code = substr($subject_name, 0, 1);
                            }
                            
                            $subject_code = $base_code;
                            $counter = 1;
                            
                            // Check if code is unique, if not, append numbers
                            while (true) {
                                $check_code_sql = "SELECT COUNT(*) FROM subjects WHERE school_id = ? AND subject_code = ?";
                                if ($check_code_stmt = $conn->prepare($check_code_sql)) {
                                    $check_code_stmt->bind_param("is", $current_user_school_id, $subject_code);
                                    $check_code_stmt->execute();
                                    $check_code_result = $check_code_stmt->get_result();
                                    $code_row = $check_code_result->fetch_assoc();
                                    $code_count = $code_row['COUNT(*)'];
                                    $check_code_result->free_result();
                                    $check_code_stmt->close();
                                    unset($check_code_stmt);
                                    
                                    if ($code_count == 0) {
                                        // Code is unique, break the loop
                                        break;
                                    } else {
                                        // Code exists, try with counter
                                        $subject_code = $base_code . $counter;
                                        $counter++;
                                    }
                                } else {
                                    break; // Error in preparation, exit loop
                                }
                            }
                            
                            $sql = "INSERT INTO subjects (school_id, subject_name, subject_code, subject_category, applicable_levels, min_students, max_students, subject_description) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                            if ($stmt = $conn->prepare($sql)) {
                                $stmt->bind_param("issssiis", $current_user_school_id, $subject_name, $subject_code, $subject_category, $applicable_levels, $min_students, $max_students, $subject_description);
                                if ($stmt->execute()) {
                                    $feedback_message = "<div class='success'>Subject added successfully with code: " . htmlspecialchars($subject_code) . " (" . htmlspecialchars($subject_category) . ")</div>";
                                } else {
                                    $feedback_message = "<div class='error'>Error adding subject: " . $stmt->error . "</div>";
                                }
                                $stmt->close();
                                unset($stmt); // Unset statement variable
                            }
                        }
                    } else {
                        $feedback_message = "<div class='error'>Database error during subject existence check: " . $conn->error . "</div>";
                    }
                } else {
                    $feedback_message = "<div class='error'>Subject name cannot be empty.</div>";
                }
            } elseif ($action == 'edit_subject') {
                $subject_id = filter_input(INPUT_POST, 'subject_id', FILTER_VALIDATE_INT);
                $subject_name = filter_input(INPUT_POST, 'subject_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $subject_category = filter_input(INPUT_POST, 'subject_category', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $applicable_levels = isset($_POST['applicable_levels']) && is_array($_POST['applicable_levels']) ? implode(',', $_POST['applicable_levels']) : '';
                $min_students = filter_input(INPUT_POST, 'min_students', FILTER_VALIDATE_INT);
                $max_students = filter_input(INPUT_POST, 'max_students', FILTER_VALIDATE_INT);
                $subject_description = filter_input(INPUT_POST, 'subject_description', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                
                if ($subject_id && !empty($subject_name)) {
                    $sql = "UPDATE subjects SET subject_name = ?, subject_category = ?, applicable_levels = ?, min_students = ?, max_students = ?, subject_description = ? WHERE subject_id = ? AND school_id = ?";
                    if ($stmt = $conn->prepare($sql)) {
                        $stmt->bind_param("sssiisii", $subject_name, $subject_category, $applicable_levels, $min_students, $max_students, $subject_description, $subject_id, $current_user_school_id);
                        if ($stmt->execute()) {
                            $feedback_message = "<div class='success'>Subject updated successfully.</div>";
                        } else {
                            $feedback_message = "<div class='error'>Error updating subject: " . $stmt->error . "</div>";
                        }
                        $stmt->close();
                        unset($stmt); // Unset statement variable
                    }
                } else {
                    $feedback_message = "<div class='error'>Invalid subject data for editing.</div>";
                }
            } elseif ($action == 'delete_subject') {
                $subject_id = filter_input(INPUT_POST, 'subject_id', FILTER_VALIDATE_INT);
                if ($subject_id) {
                    // Start transaction for cascaded delete
                    $conn->begin_transaction();
                    try {
                        // Delete competencies associated with topics related to papers related to this subject
                        $sql = "DELETE c FROM competencies c JOIN topics t ON c.topic_id = t.topic_id JOIN subject_papers p ON t.paper_id = p.paper_id WHERE p.subject_id = ? AND p.subject_id IN (SELECT subject_id FROM subjects WHERE school_id = ?)";
                        if ($stmt = $conn->prepare($sql)) {
                            $stmt->bind_param("ii", $subject_id, $current_user_school_id);
                            $stmt->execute();
                            $stmt->close();
                            unset($stmt); // Unset statement variable
                        } else { throw new Exception($conn->error); }

                        // Delete topics associated with papers related to this subject
                        $sql = "DELETE t FROM topics t JOIN subject_papers p ON t.paper_id = p.paper_id WHERE p.subject_id = ? AND p.subject_id IN (SELECT subject_id FROM subjects WHERE school_id = ?)";
                        if ($stmt = $conn->prepare($sql)) {
                            $stmt->bind_param("ii", $subject_id, $current_user_school_id);
                            $stmt->execute();
                            $stmt->close();
                            unset($stmt); // Unset statement variable
                        } else { throw new Exception($conn->error); }

                        // Delete papers associated with this subject
                        $sql = "DELETE FROM subject_papers WHERE subject_id = ? AND subject_id IN (SELECT subject_id FROM subjects WHERE school_id = ?)";
                        if ($stmt = $conn->prepare($sql)) {
                            $stmt->bind_param("ii", $subject_id, $current_user_school_id);
                            $stmt->execute();
                            $stmt->close();
                            unset($stmt); // Unset statement variable
                        } else { throw new Exception($conn->error); }

                        // Finally, delete the subject itself
                        $sql = "DELETE FROM subjects WHERE subject_id = ? AND school_id = ?";
                        if ($stmt = $conn->prepare($sql)) {
                            $stmt->bind_param("ii", $subject_id, $current_user_school_id);
                            if ($stmt->execute()) {
                                $feedback_message = "<div class='success'>Subject and all related data deleted successfully.</div>";
                                $conn->commit(); // Commit transaction
                            } else {
                                throw new Exception($stmt->error);
                            }
                            $stmt->close();
                            unset($stmt); // Unset statement variable
                        } else { throw new Exception($conn->error); }
                    } catch (Exception $e) {
                        $conn->rollback(); // Rollback on error
                        $feedback_message = "<div class='error'>Error deleting subject: " . $e->getMessage() . "</div>";
                        error_log("Error deleting subject with ID $subject_id: " . $e->getMessage());
                    }
                } else {
                    $feedback_message = "<div class='error'>Invalid subject ID for deletion.</div>";
                }
            }

            // Handle Paper Operations
            elseif ($action == 'add_paper') {
                $subject_id = filter_input(INPUT_POST, 'parent_subject_id', FILTER_VALIDATE_INT);
                $paper_name = filter_input(INPUT_POST, 'paper_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                
                if ($subject_id && !empty($paper_name)) {
                    // Check if paper already exists for this subject and school
                    $check_sql = "SELECT COUNT(*) FROM subject_papers WHERE subject_id = ? AND school_id = ? AND paper_name = ?";
                    if ($check_stmt = $conn->prepare($check_sql)) {
                        $check_stmt->bind_param("iis", $subject_id, $current_user_school_id, $paper_name);
                        $check_stmt->execute();
                        $check_result = $check_stmt->get_result(); // Use get_result()
                        $row = $check_result->fetch_assoc();
                        $count = $row['COUNT(*)'];
                        $check_result->free_result(); // Free result set
                        $check_stmt->close();
                        unset($check_stmt);

                        if ($count > 0) {
                            $feedback_message = "<div class='error'>Error: A paper with this name already exists for the selected subject.</div>";
                        } else {
                            $sql = "INSERT INTO subject_papers (subject_id, school_id, paper_name) VALUES (?, ?, ?)";
                            if ($stmt = $conn->prepare($sql)) {
                                $stmt->bind_param("iis", $subject_id, $current_user_school_id, $paper_name);
                                if ($stmt->execute()) {
                                    $feedback_message = "<div class='success'>Paper added successfully.</div>";
                                } else {
                                    $feedback_message = "<div class='error'>Error adding paper: " . $stmt->error . "</div>";
                                }
                                $stmt->close();
                                unset($stmt); // Unset statement variable
                            }
                        }
                    } else {
                        $feedback_message = "<div class='error'>Database error during paper existence check: " . $conn->error . "</div>";
                    }
                } else {
                    $feedback_message = "<div class='error'>Paper name and parent subject are required.</div>";
                }
            } elseif ($action == 'edit_paper') {
                $paper_id = filter_input(INPUT_POST, 'paper_id', FILTER_VALIDATE_INT);
                $paper_name = filter_input(INPUT_POST, 'paper_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                if ($paper_id && !empty($paper_name)) {
                    // Ensure the paper belongs to the current school's subject
                    $sql = "UPDATE subject_papers p JOIN subjects s ON p.subject_id = s.subject_id SET p.paper_name = ? WHERE p.paper_id = ? AND s.school_id = ?";
                    if ($stmt = $conn->prepare($sql)) {
                        $stmt->bind_param("sii", $paper_name, $paper_id, $current_user_school_id);
                        if ($stmt->execute()) {
                            $feedback_message = "<div class='success'>Paper updated successfully.</div>";
                        } else {
                            $feedback_message = "<div class='error'>Error updating paper: " . $stmt->error . "</div>";
                        }
                        $stmt->close();
                        unset($stmt); // Unset statement variable
                    }
                } else {
                    $feedback_message = "<div class='error'>Invalid paper data for editing.</div>";
                }
            } elseif ($action == 'delete_paper') {
                $paper_id = filter_input(INPUT_POST, 'paper_id', FILTER_VALIDATE_INT);
                if ($paper_id) {
                    $conn->begin_transaction();
                    try {
                        // Delete competencies related to topics of this paper
                        $sql = "DELETE c FROM competencies c JOIN topics t ON c.topic_id = t.topic_id WHERE t.paper_id = ? AND t.paper_id IN (SELECT paper_id FROM subject_papers WHERE subject_id IN (SELECT subject_id FROM subjects WHERE school_id = ?))";
                        if ($stmt = $conn->prepare($sql)) {
                            $stmt->bind_param("ii", $paper_id, $current_user_school_id);
                            $stmt->execute();
                            $stmt->close();
                            unset($stmt); // Unset statement variable
                        } else { throw new Exception($conn->error); }

                        // Delete topics related to this paper
                        $sql = "DELETE FROM topics WHERE paper_id = ? AND paper_id IN (SELECT paper_id FROM subject_papers WHERE subject_id IN (SELECT subject_id FROM subjects WHERE school_id = ?))";
                        if ($stmt = $conn->prepare($sql)) {
                            $stmt->bind_param("ii", $paper_id, $current_user_school_id);
                            $stmt->execute();
                            $stmt->close();
                            unset($stmt); // Unset statement variable
                        } else { throw new Exception($conn->error); }

                        // Delete the paper itself
                        $sql = "DELETE FROM subject_papers WHERE paper_id = ? AND subject_id IN (SELECT subject_id FROM subjects WHERE school_id = ?)";
                        if ($stmt = $conn->prepare($sql)) {
                            $stmt->bind_param("ii", $paper_id, $current_user_school_id);
                            if ($stmt->execute()) {
                                $feedback_message = "<div class='success'>Paper and all related data deleted successfully.</div>";
                                $conn->commit();
                            } else {
                                throw new Exception($stmt->error);
                            }
                            $stmt->close();
                            unset($stmt); // Unset statement variable
                        } else { throw new Exception($conn->error); }
                    } catch (Exception $e) {
                        $conn->rollback();
                        $feedback_message = "<div class='error'>Error deleting paper: " . $e->getMessage() . "</div>";
                        error_log("Error deleting paper with ID $paper_id: " . $e->getMessage());
                    }
                } else {
                    $feedback_message = "<div class='error'>Invalid paper ID for deletion.</div>";
                }
            }

            // Handle Topic Operations
            elseif ($action == 'add_topic') {
                $paper_id = filter_input(INPUT_POST, 'parent_paper_id', FILTER_VALIDATE_INT);
                $topic_name = filter_input(INPUT_POST, 'topic_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                if ($paper_id && !empty($topic_name)) {
                    // Fetch school_id from subject_papers for the given paper_id
                    $school_id_for_topic = null;
                    $sql_get_school_id = "SELECT school_id FROM subject_papers WHERE paper_id = ?";
                    if ($stmt_get_school = $conn->prepare($sql_get_school_id)) {
                        $stmt_get_school->bind_param("i", $paper_id);
                        if ($stmt_get_school->execute()) {
                            $result_get_school = $stmt_get_school->get_result(); // Use get_result()
                            if ($row = $result_get_school->fetch_assoc()) {
                                $school_id_for_topic = $row['school_id'];
                            }
                            $result_get_school->free_result(); // Free result set
                        }
                        $stmt_get_school->close();
                        unset($stmt_get_school); // Unset statement variable
                    }

                    if ($school_id_for_topic !== null) {
                        $sql = "INSERT INTO topics (paper_id, school_id, topic_name) VALUES (?, ?, ?)";
                        if ($stmt = $conn->prepare($sql)) {
                            $stmt->bind_param("iis", $paper_id, $school_id_for_topic, $topic_name);
                            if ($stmt->execute()) {
                                $feedback_message = "<div class='success'>Topic added successfully.</div>";
                            } else {
                                $feedback_message = "<div class='error'>Error adding topic: " . $stmt->error . "</div>";
                            }
                            $stmt->close();
                            unset($stmt); // Unset statement variable
                        }
                    } else {
                        $feedback_message = "<div class='error'>Could not find school ID for the selected paper.</div>";
                    }
                } else {
                    $feedback_message = "<div class='error'>Topic name and parent paper are required.</div>";
                }
            } elseif ($action == 'edit_topic') {
                $topic_id = filter_input(INPUT_POST, 'topic_id', FILTER_VALIDATE_INT);
                $topic_name = filter_input(INPUT_POST, 'topic_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                if ($topic_id && !empty($topic_name)) {
                    $sql = "UPDATE topics t JOIN subject_papers p ON t.paper_id = p.paper_id JOIN subjects s ON p.subject_id = s.subject_id SET t.topic_name = ? WHERE t.topic_id = ? AND s.school_id = ?";
                    if ($stmt = $conn->prepare($sql)) {
                        $stmt->bind_param("sii", $topic_name, $topic_id, $current_user_school_id);
                        if ($stmt->execute()) {
                            $feedback_message = "<div class='success'>Topic updated successfully.</div>";
                        } else {
                            $feedback_message = "<div class='error'>Error updating topic: " . $stmt->error . "</div>";
                        }
                        $stmt->close();
                        unset($stmt); // Unset statement variable
                    }
                } else {
                    $feedback_message = "<div class='error'>Invalid topic data for editing.</div>";
                }
            } elseif ($action == 'delete_topic') {
                $topic_id = filter_input(INPUT_POST, 'topic_id', FILTER_VALIDATE_INT);
                if ($topic_id) {
                    $conn->begin_transaction();
                    try {
                        // Delete competencies related to this topic
                        $sql = "DELETE FROM competencies WHERE topic_id = ? AND topic_id IN (SELECT topic_id FROM topics WHERE paper_id IN (SELECT paper_id FROM subject_papers WHERE subject_id IN (SELECT subject_id FROM subjects WHERE school_id = ?)))";
                        if ($stmt = $conn->prepare($sql)) {
                            $stmt->bind_param("ii", $topic_id, $current_user_school_id);
                            $stmt->execute();
                            $stmt->close();
                            unset($stmt); // Unset statement variable
                        } else { throw new Exception($conn->error); }

                        // Delete the topic itself
                        $sql = "DELETE FROM topics WHERE topic_id = ? AND paper_id IN (SELECT paper_id FROM subject_papers WHERE subject_id IN (SELECT subject_id FROM subjects WHERE school_id = ?))";
                        if ($stmt = $conn->prepare($sql)) {
                            $stmt->bind_param("ii", $topic_id, $current_user_school_id);
                            if ($stmt->execute()) {
                                $feedback_message = "<div class='success'>Topic and all related competencies deleted successfully.</div>";
                                $conn->commit();
                            } else {
                                throw new Exception($stmt->error);
                            }
                            $stmt->close();
                            unset($stmt); // Unset statement variable
                        } else { throw new Exception($conn->error); }
                    } catch (Exception $e) {
                        $conn->rollback();
                        $feedback_message = "<div class='error'>Error deleting topic: " . $e->getMessage() . "</div>";
                        error_log("Error deleting topic with ID $topic_id: " . $e->getMessage());
                    }
                } else {
                    $feedback_message = "<div class='error'>Invalid topic ID for deletion.</div>";
                }
            }

            // Handle Competency Operations
            elseif ($action == 'add_competency') {
                $topic_id = filter_input(INPUT_POST, 'parent_topic_id', FILTER_VALIDATE_INT);
                $competency_description = filter_input(INPUT_POST, 'competency_description', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                if ($topic_id && !empty($competency_description)) {
                    // Fetch school_id from topics for the given topic_id
                    $school_id_for_competency = null;
                    $sql_get_school_id = "SELECT school_id FROM topics WHERE topic_id = ?";
                    if ($stmt_get_school = $conn->prepare($sql_get_school_id)) {
                        $stmt_get_school->bind_param("i", $topic_id);
                        if ($stmt_get_school->execute()) {
                            $result_get_school = $stmt_get_school->get_result(); // Use get_result()
                            if ($row = $result_get_school->fetch_assoc()) {
                                $school_id_for_competency = $row['school_id'];
                            }
                            $result_get_school->free_result(); // Free result set
                        }
                        $stmt_get_school->close();
                        unset($stmt_get_school); // Unset statement variable
                    }

                    if ($school_id_for_competency !== null) {
                        $sql = "INSERT INTO competencies (topic_id, school_id, competency_name) VALUES (?, ?, ?)"; // Changed competency_description to competency_name
                        if ($stmt = $conn->prepare($sql)) {
                            $stmt->bind_param("iis", $topic_id, $school_id_for_competency, $competency_description);
                            if ($stmt->execute()) {
                                $feedback_message = "<div class='success'>Competency added successfully.</div>";
                            } else {
                                $feedback_message = "<div class='error'>Error adding competency: " . $stmt->error . "</div>";
                            }
                            $stmt->close();
                            unset($stmt); // Unset statement variable
                        }
                    } else {
                        $feedback_message = "<div class='error'>Could not find school ID for the selected topic.</div>";
                    }
                } else {
                    $feedback_message = "<div class='error'>Competency description and parent topic are required.</div>";
                }
            } elseif ($action == 'edit_competency') {
                $competency_id = filter_input(INPUT_POST, 'competency_id', FILTER_VALIDATE_INT);
                $competency_description = filter_input(INPUT_POST, 'competency_description', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                if ($competency_id && !empty($competency_description)) {
                    $sql = "UPDATE competencies c JOIN topics t ON c.topic_id = t.topic_id JOIN subject_papers p ON t.paper_id = p.paper_id JOIN subjects s ON p.subject_id = s.subject_id SET c.competency_name = ? WHERE c.competency_id = ? AND s.school_id = ?"; // Changed competency_description to competency_name
                    if ($stmt = $conn->prepare($sql)) {
                        $stmt->bind_param("sii", $competency_description, $competency_id, $current_user_school_id);
                        if ($stmt->execute()) {
                            $feedback_message = "<div class='success'>Competency updated successfully.</div>";
                        } else {
                            $feedback_message = "<div class='error'>Error updating competency: " . $stmt->error . "</div>";
                        }
                        $stmt->close();
                        unset($stmt); // Unset statement variable
                    }
                } else {
                    $feedback_message = "<div class='error'>Invalid competency data for editing.</div>";
                }
            } elseif ($action == 'delete_competency') {
                $competency_id = filter_input(INPUT_POST, 'competency_id', FILTER_VALIDATE_INT);
                if ($competency_id) {
                    // Ensure the competency belongs to the current school's subject hierarchy
                    $sql = "DELETE FROM competencies WHERE competency_id = ? AND topic_id IN (SELECT topic_id FROM topics WHERE paper_id IN (SELECT paper_id FROM subject_papers WHERE subject_id IN (SELECT subject_id FROM subjects WHERE school_id = ?)))";
                    if ($stmt = $conn->prepare($sql)) {
                        $stmt->bind_param("ii", $competency_id, $current_user_school_id);
                        if ($stmt->execute()) {
                            $feedback_message = "<div class='success'>Competency deleted successfully.</div>";
                        } else {
                            $feedback_message = "<div class='error'>Error deleting competency: " . $stmt->error . "</div>";
                        }
                        $stmt->close();
                        unset($stmt); // Unset statement variable
                    }
                } else {
                    $feedback_message = "<div class='error'>Invalid competency ID for deletion.</div>";
                }
            }

            // Handle Subject Combination Operations
            elseif ($action == 'add_subject_combination') {
                $combination_name = filter_input(INPUT_POST, 'combination_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $combination_code = filter_input(INPUT_POST, 'combination_code', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $combination_description = filter_input(INPUT_POST, 'combination_description', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $applicable_levels = isset($_POST['applicable_levels']) && is_array($_POST['applicable_levels']) ? implode(',', $_POST['applicable_levels']) : '';
                $selected_subjects = isset($_POST['selected_subjects']) && is_array($_POST['selected_subjects']) ? $_POST['selected_subjects'] : [];
                
                if (!empty($combination_name) && !empty($combination_code) && !empty($selected_subjects) && !empty($applicable_levels)) {
                    // Check if combination name already exists
                    $check_sql = "SELECT COUNT(*) FROM subject_combinations WHERE school_id = ? AND combination_name = ?";
                    if ($check_stmt = $conn->prepare($check_sql)) {
                        $check_stmt->bind_param("is", $current_user_school_id, $combination_name);
                        $check_stmt->execute();
                        $check_result = $check_stmt->get_result();
                        $row = $check_result->fetch_assoc();
                        $count = $row['COUNT(*)'];
                        $check_result->free_result();
                        $check_stmt->close();
                        unset($check_stmt);

                        // Check if combination code already exists
                        $check_code_sql = "SELECT COUNT(*) FROM subject_combinations WHERE school_id = ? AND combination_code = ?";
                        if ($check_code_stmt = $conn->prepare($check_code_sql)) {
                            $check_code_stmt->bind_param("is", $current_user_school_id, $combination_code);
                            $check_code_stmt->execute();
                            $check_code_result = $check_code_stmt->get_result();
                            $code_row = $check_code_result->fetch_assoc();
                            $code_count = $code_row['COUNT(*)'];
                            $check_code_result->free_result();
                            $check_code_stmt->close();
                            unset($check_code_stmt);

                            if ($count > 0) {
                                $feedback_message = "<div class='error'>Error: A combination with this name already exists for your school.</div>";
                            } elseif ($code_count > 0) {
                                $feedback_message = "<div class='error'>Error: A combination with this code already exists for your school.</div>";
                            } else {
                                // Check if this is for S5-S6 and auto-include General Paper
                                $final_selected_subjects = $selected_subjects;
                                $is_senior_level = (strpos($applicable_levels, 'S5') !== false || strpos($applicable_levels, 'S6') !== false);
                                
                                if ($is_senior_level) {
                                    // Find General Paper subject
                                    $general_paper_sql = "SELECT subject_id FROM subjects WHERE school_id = ? AND (LOWER(subject_name) LIKE '%general paper%' OR LOWER(subject_name) LIKE '%general%') LIMIT 1";
                                    if ($general_paper_stmt = $conn->prepare($general_paper_sql)) {
                                        $general_paper_stmt->bind_param("i", $current_user_school_id);
                                        $general_paper_stmt->execute();
                                        $general_paper_result = $general_paper_stmt->get_result();
                                        if ($general_paper_row = $general_paper_result->fetch_assoc()) {
                                            $general_paper_id = $general_paper_row['subject_id'];
                                            // Add General Paper if not already included
                                            if (!in_array($general_paper_id, $selected_subjects)) {
                                                $final_selected_subjects[] = $general_paper_id;
                                            }
                                        }
                                        $general_paper_result->free_result();
                                        $general_paper_stmt->close();
                                        unset($general_paper_stmt);
                                    }
                                }
                                
                                // Insert the combination with the manually entered code
                                $sql = "INSERT INTO subject_combinations (school_id, combination_code, combination_name, combination_description, applicable_levels) VALUES (?, ?, ?, ?, ?)";
                                if ($stmt = $conn->prepare($sql)) {
                                    $stmt->bind_param("issss", $current_user_school_id, $combination_code, $combination_name, $combination_description, $applicable_levels);
                                    if ($stmt->execute()) {
                                        $combination_id = $conn->insert_id;
                                        
                                        // Insert subject combinations in the order they were selected
                                        foreach ($final_selected_subjects as $subject_id) {
                                            $insert_cs_sql = "INSERT INTO combination_subjects (combination_id, subject_id) VALUES (?, ?)";
                                            if ($insert_cs_stmt = $conn->prepare($insert_cs_sql)) {
                                                $insert_cs_stmt->bind_param("ii", $combination_id, $subject_id);
                                                $insert_cs_stmt->execute();
                                                $insert_cs_stmt->close();
                                                unset($insert_cs_stmt);
                                            }
                                        }
                                        
                                        $auto_added_message = $is_senior_level ? " (General Paper automatically added for S5-S6)" : "";
                                        $feedback_message = "<div class='success'>Subject combination '" . htmlspecialchars($combination_name) . "' added successfully" . $auto_added_message . ".</div>";
                                    } else {
                                        $feedback_message = "<div class='error'>Error adding subject combination: " . $stmt->error . "</div>";
                                    }
                                    $stmt->close();
                                    unset($stmt);
                                }
                            }
                        }
                    } else {
                        $feedback_message = "<div class='error'>Database error during combination existence check: " . $conn->error . "</div>";
                    }
                } else {
                    $feedback_message = "<div class='error'>Combination name, code, applicable levels, and at least one subject are required.</div>";
                }
            } elseif ($action == 'edit_subject_combination') {
                $combination_id = filter_input(INPUT_POST, 'combination_id', FILTER_VALIDATE_INT);
                $combination_name = filter_input(INPUT_POST, 'combination_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $combination_code = filter_input(INPUT_POST, 'combination_code', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $combination_description = filter_input(INPUT_POST, 'combination_description', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $applicable_levels = isset($_POST['applicable_levels']) && is_array($_POST['applicable_levels']) ? implode(',', $_POST['applicable_levels']) : '';
                $selected_subjects = isset($_POST['selected_subjects']) && is_array($_POST['selected_subjects']) ? $_POST['selected_subjects'] : [];
                
                if ($combination_id && !empty($combination_name) && !empty($combination_code) && !empty($selected_subjects) && !empty($applicable_levels)) {
                    // Check if combination name already exists (excluding current combination)
                    $check_sql = "SELECT COUNT(*) FROM subject_combinations WHERE school_id = ? AND combination_name = ? AND combination_id != ?";
                    if ($check_stmt = $conn->prepare($check_sql)) {
                        $check_stmt->bind_param("isi", $current_user_school_id, $combination_name, $combination_id);
                        $check_stmt->execute();
                        $check_result = $check_stmt->get_result();
                        $row = $check_result->fetch_assoc();
                        $count = $row['COUNT(*)'];
                        $check_result->free_result();
                        $check_stmt->close();
                        unset($check_stmt);

                        // Check if combination code already exists (excluding current combination)
                        $check_code_sql = "SELECT COUNT(*) FROM subject_combinations WHERE school_id = ? AND combination_code = ? AND combination_id != ?";
                        if ($check_code_stmt = $conn->prepare($check_code_sql)) {
                            $check_code_stmt->bind_param("isi", $current_user_school_id, $combination_code, $combination_id);
                            $check_code_stmt->execute();
                            $check_code_result = $check_code_stmt->get_result();
                            $code_row = $check_code_result->fetch_assoc();
                            $code_count = $code_row['COUNT(*)'];
                            $check_code_result->free_result();
                            $check_code_stmt->close();
                            unset($check_code_stmt);

                            if ($count > 0) {
                                $feedback_message = "<div class='error'>Error: A combination with this name already exists for your school.</div>";
                            } elseif ($code_count > 0) {
                                $feedback_message = "<div class='error'>Error: A combination with this code already exists for your school.</div>";
                            } else {
                                // Check if this is for S5-S6 and auto-include General Paper
                                $final_selected_subjects = $selected_subjects;
                                $is_senior_level = (strpos($applicable_levels, 'S5') !== false || strpos($applicable_levels, 'S6') !== false);
                                
                                if ($is_senior_level) {
                                    // Find General Paper subject
                                    $general_paper_sql = "SELECT subject_id FROM subjects WHERE school_id = ? AND (LOWER(subject_name) LIKE '%general paper%' OR LOWER(subject_name) LIKE '%general%') LIMIT 1";
                                    if ($general_paper_stmt = $conn->prepare($general_paper_sql)) {
                                        $general_paper_stmt->bind_param("i", $current_user_school_id);
                                        $general_paper_stmt->execute();
                                        $general_paper_result = $general_paper_stmt->get_result();
                                        if ($general_paper_row = $general_paper_result->fetch_assoc()) {
                                            $general_paper_id = $general_paper_row['subject_id'];
                                            // Add General Paper if not already included
                                            if (!in_array($general_paper_id, $selected_subjects)) {
                                                $final_selected_subjects[] = $general_paper_id;
                                            }
                                        }
                                        $general_paper_result->free_result();
                                        $general_paper_stmt->close();
                                        unset($general_paper_stmt);
                                    }
                                }
                                
                                // Update the combination including the code and applicable levels
                                $sql = "UPDATE subject_combinations SET combination_name = ?, combination_code = ?, combination_description = ?, applicable_levels = ? WHERE combination_id = ? AND school_id = ?";
                                if ($stmt = $conn->prepare($sql)) {
                                    $stmt->bind_param("ssssii", $combination_name, $combination_code, $combination_description, $applicable_levels, $combination_id, $current_user_school_id);
                                    if ($stmt->execute()) {
                                        // Delete existing combination subjects
                                        $delete_cs_sql = "DELETE FROM combination_subjects WHERE combination_id = ?";
                                        if ($delete_cs_stmt = $conn->prepare($delete_cs_sql)) {
                                            $delete_cs_stmt->bind_param("i", $combination_id);
                                            $delete_cs_stmt->execute();
                                            $delete_cs_stmt->close();
                                            unset($delete_cs_stmt);
                                        }
                                        
                                        // Insert new combination subjects in the order they were selected
                                        foreach ($final_selected_subjects as $subject_id) {
                                            $insert_cs_sql = "INSERT INTO combination_subjects (combination_id, subject_id) VALUES (?, ?)";
                                            if ($insert_cs_stmt = $conn->prepare($insert_cs_sql)) {
                                                $insert_cs_stmt->bind_param("ii", $combination_id, $subject_id);
                                                $insert_cs_stmt->execute();
                                                $insert_cs_stmt->close();
                                                unset($insert_cs_stmt);
                                            }
                                        }
                                        
                                        $auto_added_message = $is_senior_level ? " (General Paper automatically maintained for S5-S6)" : "";
                                        $feedback_message = "<div class='success'>Subject combination updated successfully" . $auto_added_message . ".</div>";
                                    } else {
                                        $feedback_message = "<div class='error'>Error updating subject combination: " . $stmt->error . "</div>";
                                    }
                                    $stmt->close();
                                    unset($stmt);
                                }
                            }
                        }
                    } else {
                        $feedback_message = "<div class='error'>Database error during combination update: " . $conn->error . "</div>";
                    }
                } else {
                    $feedback_message = "<div class='error'>Invalid combination data for editing.</div>";
                }
            } elseif ($action == 'delete_subject_combination') {
                $combination_id = filter_input(INPUT_POST, 'combination_id', FILTER_VALIDATE_INT);
                if ($combination_id && !empty($combination_id)) {
                    // Get combination details for logging
                    $sql_get_name = "SELECT combination_name FROM subject_combinations WHERE school_id = ? AND combination_id = ?";
                    if ($stmt_get_name = $conn->prepare($sql_get_name)) {
                        $stmt_get_name->bind_param("ii", $current_user_school_id, $combination_id);
                        $stmt_get_name->execute();
                        $result_get_name = $stmt_get_name->get_result();
                        $row_get_name = $result_get_name->fetch_assoc();
                        $combination_name = $row_get_name ? $row_get_name['combination_name'] : 'Unknown';
                        $stmt_get_name->close();
                        unset($stmt_get_name);

                        if ($combination_id) {
                            $conn->begin_transaction();
                            try {
                                // Delete combination subjects
                                $sql = "DELETE FROM combination_subjects WHERE combination_id = ?";
                                if ($stmt = $conn->prepare($sql)) {
                                    $stmt->bind_param("i", $combination_id);
                                    $stmt->execute();
                                    $stmt->close();
                                    unset($stmt);
                                } else { throw new Exception($conn->error); }

                                // Delete the combination itself
                                $sql = "DELETE FROM subject_combinations WHERE combination_id = ? AND school_id = ?";
                                if ($stmt = $conn->prepare($sql)) {
                                    $stmt->bind_param("ii", $combination_id, $current_user_school_id);
                                    if ($stmt->execute()) {
                                        $feedback_message = "<div class='success'>Subject combination '" . htmlspecialchars($combination_name) . "' deleted successfully.</div>";
                                        $conn->commit();
                                    } else {
                                        throw new Exception($stmt->error);
                                    }
                                    $stmt->close();
                                    unset($stmt);
                                } else { throw new Exception($conn->error); }
                            } catch (Exception $e) {
                                $conn->rollback();
                                $feedback_message = "<div class='error'>Error deleting subject combination: " . $e->getMessage() . "</div>";
                                error_log("Error deleting subject combination '" . $combination_name . "': " . $e->getMessage());
                            }
                        } else {
                            $feedback_message = "<div class='error'>Subject combination not found.</div>";
                        }
                    } else {
                        $feedback_message = "<div class='error'>Database error during combination lookup: " . $conn->error . "</div>";
                    }
                } else {
                    $feedback_message = "<div class='error'>Invalid combination name for deletion.</div>";
                }
            }
        }
    }

    // Clear any potentially lingering results from previous commands before fetching data for display.
    // This addresses "Commands out of sync" errors by ensuring the connection is ready for new queries.
    while ($conn->next_result()) {
        if ($result = $conn->store_result()) {
            $result->free();
        }
    }

    // --- Fetching Data for Display ---
    $subjects = [];
    $sql_subjects = "SELECT subject_id, subject_name, subject_code, subject_category, applicable_levels, min_students, max_students FROM subjects WHERE school_id = ? ORDER BY subject_category, subject_name";
    if ($stmt_subjects = $conn->prepare($sql_subjects)) {
        $stmt_subjects->bind_param("i", $current_user_school_id);
        if ($stmt_subjects->execute()) {
            $result_subjects = $stmt_subjects->get_result();
            while ($row = $result_subjects->fetch_assoc()) {
                $subjects[] = $row;
            }
            $result_subjects->free_result(); // IMPORTANT: Free the result set
        }
        $stmt_subjects->close();
        unset($stmt_subjects); // Unset statement variable
    }

    $papers = [];
    $selected_subject_id = filter_input(INPUT_GET, 'subject_id', FILTER_VALIDATE_INT);
    $selected_subject_name = '';
    if ($selected_subject_id) {
        $sql_papers = "SELECT paper_id, paper_name FROM subject_papers WHERE subject_id = ? AND school_id = ? ORDER BY paper_name"; // Added school_id
        if ($stmt_papers = $conn->prepare($sql_papers)) {
            $stmt_papers->bind_param("ii", $selected_subject_id, $current_user_school_id); // Bound school_id
            if ($stmt_papers->execute()) {
                $result_papers = $stmt_papers->get_result();
                while ($row = $result_papers->fetch_assoc()) {
                    $papers[] = $row;
                }
                $result_papers->free_result(); // IMPORTANT: Free the result set
            }
            $stmt_papers->close();
            unset($stmt_papers); // Unset statement variable
        }
        // Fetch selected subject name for breadcrumb/heading
        $sql_selected_subject_name = "SELECT subject_name FROM subjects WHERE subject_id = ? AND school_id = ?";
        if ($stmt = $conn->prepare($sql_selected_subject_name)) {
            $stmt->bind_param("ii", $selected_subject_id, $current_user_school_id);
            if ($stmt->execute()) {
                $result_selected_subject_name = $stmt->get_result(); // Use get_result()
                if ($row = $result_selected_subject_name->fetch_assoc()) {
                    $selected_subject_name = htmlspecialchars($row['subject_name']);
                }
                $result_selected_subject_name->free_result(); // Free result set
            }
            $stmt->close();
            unset($stmt); // Unset statement variable
        }
    }

    $topics = [];
    $selected_paper_id = filter_input(INPUT_GET, 'paper_id', FILTER_VALIDATE_INT);
    $selected_paper_name = '';
    if ($selected_paper_id) {
        $sql_topics = "SELECT topic_id, topic_name FROM topics WHERE paper_id = ? AND school_id = ? ORDER BY topic_name"; // Added school_id
        if ($stmt_topics = $conn->prepare($sql_topics)) {
            $stmt_topics->bind_param("ii", $selected_paper_id, $current_user_school_id); // Bound school_id
            if ($stmt_topics->execute()) {
                $result_topics = $stmt_topics->get_result();
                while ($row = $result_topics->fetch_assoc()) {
                    $topics[] = $row;
                }
                $result_topics->free_result(); // IMPORTANT: Free the result set
            }
            $stmt_topics->close();
            unset($stmt_topics); // Unset statement variable
        }
        // Fetch selected paper name for breadcrumb/heading
        $sql_selected_paper_name = "SELECT paper_name, subject_id FROM subject_papers WHERE paper_id = ? AND school_id = ?"; // Added school_id
        if ($stmt = $conn->prepare($sql_selected_paper_name)) {
            $stmt->bind_param("ii", $selected_paper_id, $current_user_school_id); // Bound school_id
            if ($stmt->execute()) {
                $result_selected_paper_name = $stmt->get_result(); // Use get_result()
                if ($row = $result_selected_paper_name->fetch_assoc()) {
                    $selected_paper_name = htmlspecialchars($row['paper_name']);
                    $selected_subject_id = $row['subject_id']; // Update for breadcrumb
                    // Fetch subject name for breadcrumb
                    $sql_subj_name_for_breadcrumb = "SELECT subject_name FROM subjects WHERE subject_id = ? AND school_id = ?";
                    if ($stmt_subj_crumb = $conn->prepare($sql_subj_name_for_breadcrumb)) {
                        $stmt_subj_crumb->bind_param("ii", $selected_subject_id, $current_user_school_id);
                        if ($stmt_subj_crumb->execute()) {
                            $result_subj_crumb = $stmt_subj_crumb->get_result(); // Use get_result()
                            if ($row_subj_crumb = $result_subj_crumb->fetch_assoc()) {
                                $selected_subject_name = htmlspecialchars($row_subj_crumb['subject_name']);
                            }
                            $result_subj_crumb->free_result(); // Free result set
                        }
                        $stmt_subj_crumb->close();
                        unset($stmt_subj_crumb); // Unset statement variable
                    }
                }
                $result_selected_paper_name->free_result(); // Free result set
            }
            $stmt->close();
            unset($stmt); // Unset statement variable
        }
    }

    $competencies = [];
    $selected_topic_id = filter_input(INPUT_GET, 'topic_id', FILTER_VALIDATE_INT);
    $selected_topic_name = '';
    if ($selected_topic_id) {
        $sql_competencies = "SELECT competency_id, competency_name FROM competencies WHERE topic_id = ? AND school_id = ? ORDER BY competency_id"; // Changed to competency_name, added school_id
        if ($stmt_competencies = $conn->prepare($sql_competencies)) {
            $stmt_competencies->bind_param("ii", $selected_topic_id, $current_user_school_id); // Bound school_id
            if ($stmt_competencies->execute()) {
                $result_competencies = $stmt_competencies->get_result();
                while ($row = $result_competencies->fetch_assoc()) {
                    $competencies[] = $row;
                }
                $result_competencies->free_result(); // IMPORTANT: Free the result set
            }
            $stmt_competencies->close();
            unset($stmt_competencies); // Unset statement variable
        }
        // Fetch selected topic name for breadcrumb/heading
        $sql_selected_topic_name = "SELECT topic_name, paper_id FROM topics WHERE topic_id = ? AND school_id = ?"; // Added school_id
        if ($stmt = $conn->prepare($sql_selected_topic_name)) {
            $stmt->bind_param("ii", $selected_topic_id, $current_user_school_id); // Bound school_id
            if ($stmt->execute()) {
                $result_selected_topic_name = $stmt->get_result(); // Use get_result()
                if ($row = $result_selected_topic_name->fetch_assoc()) {
                    $selected_topic_name = htmlspecialchars($row['topic_name']);
                    $selected_paper_id = $row['paper_id']; // Update for breadcrumb
                    // Fetch paper name for breadcrumb
                    $sql_pap_name_for_breadcrumb = "SELECT paper_name, subject_id FROM subject_papers WHERE paper_id = ? AND school_id = ?"; // Added school_id
                    if ($stmt_pap_crumb = $conn->prepare($sql_pap_name_for_breadcrumb)) {
                        $stmt_pap_crumb->bind_param("ii", $selected_paper_id, $current_user_school_id); // Bound school_id
                        if ($stmt_pap_crumb->execute()) {
                            $result_pap_crumb = $stmt_pap_crumb->get_result(); // Use get_result()
                            if ($row_pap_crumb = $result_pap_crumb->fetch_assoc()) {
                                $selected_paper_name = htmlspecialchars($row_pap_crumb['paper_name']);
                                $selected_subject_id = $row_pap_crumb['subject_id']; // Update for breadcrumb
                                // Fetch subject name for breadcrumb
                                $sql_subj_name_for_breadcrumb_2 = "SELECT subject_name FROM subjects WHERE subject_id = ? AND school_id = ?";
                                if ($stmt_subj_crumb_2 = $conn->prepare($sql_subj_name_for_breadcrumb_2)) {
                                    $stmt_subj_crumb_2->bind_param("ii", $selected_subject_id, $current_user_school_id);
                                    if ($stmt_subj_crumb_2->execute()) {
                                        $result_subj_crumb_2 = $stmt_subj_crumb_2->get_result(); // Use get_result()
                                        if ($row_subj_crumb_2 = $result_subj_crumb_2->fetch_assoc()) {
                                            $selected_subject_name = htmlspecialchars($row_subj_crumb_2['subject_name']);
                                        }
                                        $result_subj_crumb_2->free_result(); // Free result set
                                    }
                                    $stmt_subj_crumb_2->close();
                                    unset($stmt_subj_crumb_2); // Unset statement variable
                                }
                            }
                        }
                        $stmt_pap_crumb->close();
                        unset($stmt_pap_crumb); // Unset statement variable
                    }
                }
                $result_selected_topic_name->free_result(); // Free result set
            }
            $stmt->close();
            unset($stmt); // Unset statement variable
        }
    }

    // Fetch Subject Combinations for Display
    $subject_combinations = [];
    $selected_combination_id = filter_input(INPUT_GET, 'combination_id', FILTER_VALIDATE_INT);
    $selected_combination_name = '';
    if ($selected_combination_id) {
        $sql_combination = "SELECT sc.combination_id, sc.combination_code, sc.combination_name, sc.combination_description, GROUP_CONCAT(s.subject_name ORDER BY s.subject_name SEPARATOR ', ') as subjects_list 
                           FROM subject_combinations sc 
                           LEFT JOIN combination_subjects cs ON sc.combination_id = cs.combination_id 
                           LEFT JOIN subjects s ON cs.subject_id = s.subject_id 
                           WHERE sc.combination_id = ? AND sc.school_id = ? 
                           GROUP BY sc.combination_id, sc.combination_code, sc.combination_name, sc.combination_description";
        if ($stmt_combination = $conn->prepare($sql_combination)) {
            $stmt_combination->bind_param("ii", $selected_combination_id, $current_user_school_id);
            if ($stmt_combination->execute()) {
                $result_combination = $stmt_combination->get_result();
                if ($row = $result_combination->fetch_assoc()) {
                    $selected_combination_name = htmlspecialchars($row['combination_name']);
                    $subject_combinations[] = $row;
                }
                $result_combination->free_result();
            }
            $stmt_combination->close();
            unset($stmt_combination);
        }
    } else {
        // Fetch all combinations if no specific combination selected
        $sql_combinations = "SELECT sc.combination_id, sc.combination_code, sc.combination_name, sc.combination_description, GROUP_CONCAT(s.subject_name ORDER BY s.subject_name SEPARATOR ', ') as subjects_list 
                            FROM subject_combinations sc 
                            LEFT JOIN combination_subjects cs ON sc.combination_id = cs.combination_id 
                            LEFT JOIN subjects s ON cs.subject_id = s.subject_id 
                            WHERE sc.school_id = ? 
                            GROUP BY sc.combination_id, sc.combination_code, sc.combination_name, sc.combination_description 
                            ORDER BY sc.combination_name";
        if ($stmt_combinations = $conn->prepare($sql_combinations)) {
            $stmt_combinations->bind_param("i", $current_user_school_id);
            if ($stmt_combinations->execute()) {
                $result_combinations = $stmt_combinations->get_result();
                while ($row = $result_combinations->fetch_assoc()) {
                    $subject_combinations[] = $row;
                }
                $result_combinations->free_result();
            }
            $stmt_combinations->close();
            unset($stmt_combinations);
        }
    }

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

// Determine role name for display.
$role_name = "Unknown";
switch ($user_role_code) {
    case ROLE_SUPER_ADMIN: $role_name = "Super Admin"; break;
    case ROLE_ADMIN:        $role_name = "Admin";       break;
    case ROLE_TEACHER:      $role_name = "Teacher";     break;
    case ROLE_STUDENT:      $role_name = "Student";     break;
    case ROLE_PARENT:       $role_name = "Parent";      break;
    case ROLE_STAFF:        $role_name = "Staff";       break;
}

// Close the connection at the very end if it's still open.
if (isset($conn) && $conn instanceof mysqli && $conn->ping()) {
    $conn->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $role_name; ?> Subject Management - <?php echo $school_name; ?></title>
    <link rel="stylesheet" href="style.css">
    <link rel="icon" href="<?php echo $school_logo_path; ?>" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* Mobile Footer Styles (Re-used/Modified) */
.mobile-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 60px;
    background-color: #ffffff;
    border-top: 1px solid #e0e0e0;
    box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
    z-index: 1000;
}

.mobile-footer nav {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 100%;
}

.footer-item {
    /* Style both 'a' and 'button' for consistency */
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    flex-grow: 1;
    color: #888888;
    text-decoration: none;
    font-size: 0.7em;
    padding: 5px 0;
    transition: color 0.3s ease;
    
    /* Styles specific for the button to look like a link */
    background: none;
    border: none;
    cursor: pointer;
    font-family: inherit;
}

.footer-item i {
    font-size: 1.2em;
    margin-bottom: 3px;
}

/* Active and Hover States */
.footer-item.active,
.footer-item:hover {
    color: #007bff; /* Primary color */
}

/* --- Drawer Styles --- */
.drawer-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 1001;
    visibility: hidden;
    opacity: 0;
    transition: opacity 0.3s, visibility 0.3s;
}

.drawer-overlay.visible {
    visibility: visible;
    opacity: 1;
}

.more-drawer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%; /* Full width for drawer */
    max-height: 50%; /* Limit drawer height */
    background-color: #ffffff;
    z-index: 1002; /* Above the overlay */
    transform: translateY(100%); /* Start off-screen */
    transition: transform 0.3s ease-out;
    box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.15);
    border-radius: 12px 12px 0 0; /* Rounded top corners */
    overflow-y: auto;
}

.more-drawer.open {
    transform: translateY(0); /* Slide up into view */
}

.drawer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
}

.drawer-header h4 {
    margin: 0;
    font-size: 1.1em;
    color: #333;
}

.close-drawer {
    background: none;
    border: none;
    font-size: 1.8em;
    font-weight: 300;
    cursor: pointer;
    color: #888;
    padding: 0 10px;
}

.drawer-link {
    display: block;
    padding: 15px;
    text-decoration: none;
    color: #333;
    font-size: 1em;
    border-bottom: 1px solid #f9f9f9;
    transition: background-color 0.2s;
}

.drawer-link:hover {
    background-color: #f5f5f5;
}

.drawer-link i {
    margin-right: 10px;
    color: #007bff;
}

.logout-link {
    color: #dc3545; /* Red color for logout */
}

/* Compensate for the fixed footer */
body {
    padding-bottom: 70px; 
}

/* Optional: Hide the mobile specific elements on larger screens */
@media (min-width: 768px) {
    .mobile-footer, .more-drawer, .drawer-overlay {
        display: none;
    }
    body {
        padding-bottom: 0;
    }
}
        /* Specific styles for subject management page */
        .management-container {
            background-color: var(--card-bg);
            padding: 30px;
            border-radius: 12px;
            box-shadow: var(--shadow-medium);
            margin-top: 20px;
        }

        .action-buttons {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        .action-buttons .btn {
            padding: 10px 18px;
            font-size: 15px;
        }

        .breadcrumb {
            margin-bottom: 20px;
            font-size: 1em;
            color: #666;
        }
        .breadcrumb a {
            color: var(--light-blue);
            text-decoration: none;
            font-weight: 500;
        }
        .breadcrumb a:hover {
            text-decoration: underline;
        }
        .breadcrumb span {
            margin: 0 5px;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .data-table th, .data-table td {
            border: 1px solid #eee;
            padding: 12px 15px;
            text-align: left;
            vertical-align: top;
        }

        .data-table th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #555;
            position: sticky;
            top: 0;
            z-index: 50;
        }

        .data-table tbody tr:nth-child(even) {
            background-color: #fbfbfb;
        }

        .data-table tbody tr:hover {
            background-color: #e9ecef;
        }

        .data-actions {
            display: flex;
            gap: 5px;
            flex-wrap: wrap;
        }
        .data-actions .btn {
            padding: 6px 10px;
            font-size: 0.85em;
        }

        /* Form styling for Add/Edit Modals */
        .modal .form-group {
            margin-bottom: 15px;
        }
        .modal label {
            font-weight: 600;
            margin-bottom: 5px;
            display: block;
        }
        .modal input[type="text"],
        .modal textarea,
        .modal select { /* Added select here */
            width: calc(100% - 24px); /* Account for padding */
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 8ox;
            font-size: 1em;
            transition: border-color 0.2s ease;
        }
        .modal input[type="text"]:focus,
        .modal textarea:focus,
        .modal select:focus { /* Added select here */
            border-color: var(--primary-green);
            outline: none;
            box-shadow: 0 0 0 3px rgba(44, 37, 63, 0.1);
        }
        .modal textarea {
            min-height: 80px;
            resize: vertical;
        }
        .modal .modal-actions {
            text-align: right;
            margin-top: 20px;
        }
        .modal .modal-actions .btn {
            margin-left: 10px;
        }

        /* Responsive table behavior */
        @media (max-width: 768px) {
            .management-container {
                padding: 15px;
            }
            .data-table, .data-table tbody, .data-table tr, .data-table td, .data-table th {
                display: block;
            }
            .data-table thead {
                display: none;
            }
            .data-table tr {
                margin-bottom: 15px;
                border: 1px solid #eee;
                border-radius: 8px;
                padding: 10px;
                box-shadow: var(--shadow-light);
            }
            .data-table td {
                border: none;
                position: relative;
                padding-left: 100px;
                text-align: right;
            }
            .data-table td::before {
                content: attr(data-label);
                position: absolute;
                left: 10px;
                width: 85px;
                padding-right: 10px;
                white-space: nowrap;
                text-align: left;
                font-weight: 600;
                color: #555;
            }
            .data-actions {
                justify-content: center;
                margin-top: 10px;
            }
            .data-actions .btn {
                flex-grow: 1;
            }
        }

        @media (max-width: 480px) {
            .action-buttons .btn {
                flex-grow: 1;
            }
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1500;
            display: none;
        }
        
        .overlay.show {
            display: block;
        }
        
        .overlay.active {
            display: block;
        }
        
        /* Modal Styles - Ensure modals appear above overlay */
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.6);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 2000; /* Higher than overlay */
        }
        
        .modal-content {
            background-color: #ffffff;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
            max-width: 500px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
            position: relative;
            z-index: 2001; /* Even higher to ensure content is clickable */
        }
        
        /* Feedback message auto-fade styles */
        .success, .error {
            padding: 15px 20px;
            margin-bottom: 20px;
            border-radius: 8px;
            font-weight: 500;
            animation: slideInDown 0.3s ease-out;
            transition: opacity 0.5s ease-out, transform 0.5s ease-out;
        }
        
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .success.fade-out, .error.fade-out {
            opacity: 0;
            transform: translateY(-20px);
        }
        
        @keyframes slideInDown {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        /* Badge styles for subject categories */
        .badge {
            display: inline-block;
            padding: 4px 10px;
            font-size: 0.85em;
            font-weight: 600;
            border-radius: 12px;
            text-transform: capitalize;
        }
        
        .badge-compulsory {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .badge-optional {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .badge-elective {
            background-color: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        
        /* Form enhancements */
        .required {
            color: #dc3545;
            font-weight: bold;
        }
        
        .form-row {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
        }
        
        .checkbox-group {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
            gap: 10px;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #e0e0e0;
        }
        
        .checkbox-label {
            display: flex;
            align-items: center;
            font-weight: normal !important;
            cursor: pointer;
            padding: 5px;
            transition: background-color 0.2s;
        }
        
        .checkbox-label:hover {
            background-color: #e9ecef;
            border-radius: 4px;
        }
        
        .checkbox-label input[type="checkbox"] {
            margin-right: 8px;
            width: 18px;
            height: 18px;
            cursor: pointer;
        }
        
        .modal .form-group small {
            display: block;
            margin-top: 5px;
            color: #6c757d;
            font-size: 0.85em;
        }
        
        .close-button {
            position: absolute;
            top: 15px;
            right: 20px;
            font-size: 28px;
            font-weight: bold;
            color: #aaa;
            cursor: pointer;
            background: none;
            border: none;
            padding: 0;
            line-height: 1;
        }
        
        .close-button:hover,
        .close-button:focus {
            color: #000;
        }

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

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

                <div class="dashboard-content">
                    <h2><i class="fas fa-book"></i> Subject Management</h2>

                    <div class="management-container">
                        <?php echo $feedback_message; // Display success/error messages ?>

                        <div class="breadcrumb">
                            <a href="admin_subjects.php">Subjects</a>
                            <?php if ($selected_subject_id && $selected_subject_name): ?>
                                <span>&gt;</span> <a href="admin_subjects.php?subject_id=<?php echo $selected_subject_id; ?>"><?php echo $selected_subject_name; ?></a>
                            <?php endif; ?>
                            <?php if ($selected_paper_id && $selected_paper_name): ?>
                                <span>&gt;</span> <a href="admin_subjects.php?paper_id=<?php echo $selected_paper_id; ?>"><?php echo $selected_paper_name; ?></a>
                            <?php endif; ?>
                            <?php if ($selected_topic_id && $selected_topic_name): ?>
                                <span>&gt;</span> <span><?php echo $selected_topic_name; ?></span>
                            <?php endif; ?>
                        </div>

                        <?php if (!$selected_subject_id): // Display Subjects List ?>
                            <h3 id="subjectsListTitle">All Subjects</h3>
                            <div class="action-buttons">
                                <button class="btn btn-primary" id="addSubjectBtn">Add New Subject</button>
                                <!-- New buttons for direct access to add forms -->
                                <button class="btn btn-primary" id="addPaperFromMainBtn">Add New Paper</button>
                                <button class="btn btn-primary" id="addTopicFromMainBtn">Add New Topic</button>
                                <button class="btn btn-primary" id="addCompetencyFromMainBtn">Add New Competency</button>
                                <button class="btn btn-success" id="addSubjectCombinationBtn">Create Subject Combination</button>
                            </div>
                            <?php if (empty($subjects)): ?>
                                <p id="noSubjectsMessage">No subjects found for your school. Click "Add New Subject" to get started.</p>
                            <?php else: ?>
                                <div style="overflow-x:auto;">
                                    <table class="data-table">
                                        <thead>
                                            <tr>
                                                <th>Subject Name</th>
                                                <th>Code</th>
                                                <th>Category</th>
                                                <th>Levels</th>
                                                <th>Min/Max Students</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($subjects as $subject): ?>
                                                <tr>
                                                    <td data-label="Subject Name:"><?php echo htmlspecialchars($subject['subject_name']); ?></td>
                                                    <td data-label="Code:"><?php echo htmlspecialchars($subject['subject_code'] ?? 'N/A'); ?></td>
                                                    <td data-label="Category:">
                                                        <span class="badge badge-<?php echo strtolower($subject['subject_category'] ?? 'optional'); ?>">
                                                            <?php echo htmlspecialchars($subject['subject_category'] ?? 'Optional'); ?>
                                                        </span>
                                                    </td>
                                                    <td data-label="Levels:"><?php echo htmlspecialchars($subject['applicable_levels'] ?? 'All'); ?></td>
                                                    <td data-label="Capacity:">
                                                        <?php 
                                                        $min = $subject['min_students'] ?? '-';
                                                        $max = $subject['max_students'] ?? '-';
                                                        echo $min . ' / ' . $max;
                                                        ?>
                                                    </td>
                                                    <td data-label="Actions:" class="data-actions">
                                                        <a href="admin_subjects.php?subject_id=<?php echo $subject['subject_id']; ?>" class="btn btn-primary">View Papers</a>
                                                        <button class="btn btn-warning edit-subject-btn"
                                                                data-id="<?php echo $subject['subject_id']; ?>"
                                                                data-name="<?php echo htmlspecialchars($subject['subject_name']); ?>"
                                                                data-category="<?php echo htmlspecialchars($subject['subject_category'] ?? 'Optional'); ?>"
                                                                data-levels="<?php echo htmlspecialchars($subject['applicable_levels'] ?? ''); ?>"
                                                                data-min="<?php echo $subject['min_students'] ?? ''; ?>"
                                                                data-max="<?php echo $subject['max_students'] ?? ''; ?>">Edit</button>
                                                        <button class="btn btn-danger delete-subject-btn" data-id="<?php echo $subject['subject_id']; ?>">Delete</button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>

                            <!-- Subject Combinations Section -->
                            <h3 id="subjectCombinationsTitle">Subject Combinations</h3>
                            <?php if (empty($subject_combinations)): ?>
                                <p id="noCombinationsMessage">No subject combinations created yet. Click "Create Subject Combination" to combine subjects with unique codes.</p>
                            <?php else: ?>
                                <div style="overflow-x:auto;">
                                    <table class="data-table">
                                        <thead>
                                            <tr>
                                                <th>Combination Code</th>
                                                <th>Combination Name</th>
                                                <th>Subjects</th>
                                                <th>Description</th>
                                                <th>Levels</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($subject_combinations as $combination): ?>
                                                <tr>
                                                    <td data-label="Code:">
                                                        <strong><?php echo htmlspecialchars($combination['combination_code']); ?></strong>
                                                    </td>
                                                    <td data-label="Name:"><?php echo htmlspecialchars($combination['combination_name']); ?></td>
                                                    <td data-label="Subjects:">
                                                        <small><?php echo htmlspecialchars($combination['subjects_list']); ?></small>
                                                    </td>
                                                    <td data-label="Description:">
                                                        <small><?php echo htmlspecialchars($combination['combination_description'] ?? 'N/A'); ?></small>
                                                    </td>
                                                    <td data-label="Levels:">
                                                        <small><?php echo htmlspecialchars($combination['applicable_levels'] ?? 'All'); ?></small>
                                                    </td>
                                                    <td data-label="Actions:" class="data-actions">
                                                        <button class="btn btn-warning edit-combination-btn"
                                                                data-id="<?php echo $combination['combination_id']; ?>"
                                                                data-name="<?php echo htmlspecialchars($combination['combination_name']); ?>"
                                                                data-code="<?php echo htmlspecialchars($combination['combination_code']); ?>"
                                                                data-description="<?php echo htmlspecialchars($combination['combination_description'] ?? ''); ?>"
                                                                data-levels="<?php echo htmlspecialchars($combination['applicable_levels'] ?? ''); ?>"
                                                                data-subjects="<?php echo htmlspecialchars($combination['subjects_list']); ?>">Edit</button>
                                                        <button class="btn btn-danger delete-combination-btn" data-id="<?php echo $combination['combination_id']; ?>">Delete</button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>

                        <?php elseif ($selected_subject_id && !$selected_paper_id): // Display Papers for Selected Subject ?>
                            <h3>Papers for <?php echo $selected_subject_name; ?></h3>
                            <div class="action-buttons">
                                <button class="btn btn-primary" id="addPaperBtn" data-subject-id="<?php echo $selected_subject_id; ?>">Add New Paper</button>
                            </div>
                            <?php if (empty($papers)): ?>
                                <p>No papers found for this subject. Click "Add New Paper" to add one.</p>
                            <?php else: ?>
                                <div style="overflow-x:auto;">
                                    <table class="data-table">
                                        <thead>
                                            <tr>
                                                <th>Paper Name</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($papers as $paper): ?>
                                                <tr>
                                                    <td data-label="Paper Name:"><?php echo htmlspecialchars($paper['paper_name']); ?></td>
                                                    <td data-label="Actions:" class="data-actions">
                                                        <a href="admin_subjects.php?paper_id=<?php echo $paper['paper_id']; ?>" class="btn btn-primary">View Topics</a>
                                                        <button class="btn btn-warning edit-paper-btn"
                                                                data-id="<?php echo $paper['paper_id']; ?>"
                                                                data-name="<?php echo htmlspecialchars($paper['paper_name']); ?>">Edit</button>
                                                        <button class="btn btn-danger delete-paper-btn" data-id="<?php echo $paper['paper_id']; ?>">Delete</button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>

                        <?php elseif ($selected_paper_id && !$selected_topic_id): // Display Topics for Selected Paper ?>
                            <h3>Topics for <?php echo $selected_paper_name; ?></h3>
                            <div class="action-buttons">
                                <button class="btn btn-primary" id="addTopicBtn" data-paper-id="<?php echo $selected_paper_id; ?>">Add New Topic</button>
                            </div>
                            <?php if (empty($topics)): ?>
                                <p>No topics found for this paper. Click "Add New Topic" to add one.</p>
                            <?php else: ?>
                                <div style="overflow-x:auto;">
                                    <table class="data-table">
                                        <thead>
                                            <tr>
                                                <th>Topic Name</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($topics as $topic): ?>
                                                <tr>
                                                    <td data-label="Topic Name:"><?php echo htmlspecialchars($topic['topic_name']); ?></td>
                                                    <td data-label="Actions:" class="data-actions">
                                                        <a href="admin_subjects.php?topic_id=<?php echo $topic['topic_id']; ?>" class="btn btn-primary">View Competencies</a>
                                                        <button class="btn btn-warning edit-topic-btn"
                                                                data-id="<?php echo $topic['topic_id']; ?>"
                                                                data-name="<?php echo htmlspecialchars($topic['topic_name']); ?>">Edit</button>
                                                        <button class="btn btn-danger delete-topic-btn" data-id="<?php echo $topic['topic_id']; ?>">Delete</button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>

                        <?php elseif ($selected_topic_id): // Display Competencies for Selected Topic ?>
                            <h3>Competencies for <?php echo $selected_topic_name; ?></h3>
                            <div class="action-buttons">
                                <button class="btn btn-primary" id="addCompetencyBtn" data-topic-id="<?php echo $selected_topic_id; ?>">Add New Competency</button>
                            </div>
                            <?php if (empty($competencies)): ?>
                                <p>No competencies found for this topic. Click "Add New Competency" to add one.</p>
                            <?php else: ?>
                                <div style="overflow-x:auto;">
                                    <table class="data-table">
                                        <thead>
                                            <tr>
                                                <th>Competency Description</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($competencies as $competency): ?>
                                                <tr>
                                                    <td data-label="Competency Description:"><?php echo htmlspecialchars($competency['competency_name']); ?></td>
                                                    <td data-label="Actions:" class="data-actions">
                                                        <button class="btn btn-warning edit-competency-btn"
                                                                data-id="<?php echo $competency['competency_id']; ?>"
                                                                data-description="<?php echo htmlspecialchars($competency['competency_name']); ?>">Edit</button>
                                                        <button class="btn btn-danger delete-competency-btn" data-id="<?php echo $competency['competency_id']; ?>">Delete</button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>

                        <?php endif; ?>
                    </div>
                </div>
            </div>

           
        </div>
    </div>

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

    <!-- Modals for Add/Edit operations -->

    <!-- Add/Edit Subject Modal -->
    <div id="subjectModal" class="modal">
        <div class="modal-content">
            <span class="close-button">&times;</span>
            <h3 id="subjectModalTitle">Add Subject</h3>
            <form id="subjectForm" method="POST" action="admin_subjects.php">
                <input type="hidden" name="action" id="subjectAction">
                <input type="hidden" name="subject_id" id="subjectId">
                
                <div class="form-group">
                    <label for="subject_name">Subject Name: <span class="required">*</span></label>
                    <input type="text" id="subject_name" name="subject_name" required>
                </div>
                
                <div class="form-group">
                    <label for="subject_category">Subject Category: <span class="required">*</span></label>
                    <select id="subject_category" name="subject_category" required>
                        <option value="Compulsory">Compulsory (Must take)</option>
                        <option value="Optional" selected>Optional (Can choose)</option>
                        <option value="Elective">Elective (Additional)</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Applicable Levels:</label>
                    <div class="checkbox-group">
                        <label class="checkbox-label">
                            <input type="checkbox" name="applicable_levels[]" value="S1" checked> Senior 1
                        </label>
                        <label class="checkbox-label">
                            <input type="checkbox" name="applicable_levels[]" value="S2" checked> Senior 2
                        </label>
                        <label class="checkbox-label">
                            <input type="checkbox" name="applicable_levels[]" value="S3" checked> Senior 3
                        </label>
                        <label class="checkbox-label">
                            <input type="checkbox" name="applicable_levels[]" value="S4" checked> Senior 4
                        </label>
                        <label class="checkbox-label">
                            <input type="checkbox" name="applicable_levels[]" value="S5"> Senior 5
                        </label>
                        <label class="checkbox-label">
                            <input type="checkbox" name="applicable_levels[]" value="S6"> Senior 6
                        </label>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group" style="flex: 1;">
                        <label for="min_students">Min. Students:</label>
                        <input type="number" id="min_students" name="min_students" min="0" placeholder="Optional">
                        <small>Minimum students to run this subject</small>
                    </div>
                    <div class="form-group" style="flex: 1;">
                        <label for="max_students">Max. Students:</label>
                        <input type="number" id="max_students" name="max_students" min="0" placeholder="Optional">
                        <small>Maximum capacity for this subject</small>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="subject_description">Description:</label>
                    <textarea id="subject_description" name="subject_description" rows="3" placeholder="Brief description of the subject (optional)"></textarea>
                </div>
                
                <div class="modal-actions">
                    <button type="submit" class="btn btn-success">Save Subject</button>
                    <button type="button" class="btn btn-secondary close-button">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Add/Edit Paper Modal -->
    <div id="paperModal" class="modal">
        <div class="modal-content">
            <span class="close-button">&times;</span>
            <h3 id="paperModalTitle">Add Paper</h3>
            <form id="paperForm" method="POST" action="admin_subjects.php">
                <input type="hidden" name="action" id="paperAction">
                <input type="hidden" name="paper_id" id="paperId">
                <div class="form-group">
                    <label for="paperSubjectSelect">Parent Subject:</label>
                    <select id="paperSubjectSelect" name="parent_subject_id" required>
                        <!-- Options will be populated by JavaScript -->
                    </select>
                </div>
                <div class="form-group">
                    <label for="paper_name">Paper Name:</label>
                    <input type="text" id="paper_name" name="paper_name" required>
                </div>
                <div class="modal-actions">
                    <button type="submit" class="btn btn-success">Save Paper</button>
                    <button type="button" class="btn btn-secondary close-button">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Add/Edit Topic Modal -->
    <div id="topicModal" class="modal">
        <div class="modal-content">
            <span class="close-button">&times;</span>
            <h3 id="topicModalTitle">Add Topic</h3>
            <form id="topicForm" method="POST" action="admin_subjects.php">
                <input type="hidden" name="action" id="topicAction">
                <input type="hidden" name="topic_id" id="topicId">
                <div class="form-group">
                    <label for="topicPaperSelect">Parent Paper:</label>
                    <select id="topicPaperSelect" name="parent_paper_id" required>
                        <!-- Options will be populated by JavaScript -->
                    </select>
                </div>
                <div class="form-group">
                    <label for="topic_name">Topic Name:</label>
                    <input type="text" id="topic_name" name="topic_name" required>
                </div>
                <div class="modal-actions">
                    <button type="submit" class="btn btn-success">Save Topic</button>
                    <button type="button" class="btn btn-secondary close-button">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Add/Edit Competency Modal -->
    <div id="competencyModal" class="modal">
        <div class="modal-content">
            <span class="close-button">&times;</span>
            <h3 id="competencyModalTitle">Add Competency</h3>
            <form id="competencyForm" method="POST" action="admin_subjects.php">
                <input type="hidden" name="action" id="competencyAction">
                <input type="hidden" name="competency_id" id="competencyId">
                <div class="form-group">
                    <label for="competencyTopicSelect">Parent Topic:</label>
                    <select id="competencyTopicSelect" name="parent_topic_id" required>
                        <!-- Options will be populated by JavaScript -->
                    </select>
                </div>
                <div class="form-group">
                    <label for="competency_description">Competency Description:</label>
                    <textarea id="competency_description" name="competency_description" required></textarea>
                </div>
                <div class="modal-actions">
                    <button type="submit" class="btn btn-success">Save Competency</button>
                    <button type="button" class="btn btn-secondary close-button">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Add/Edit Subject Combination Modal -->
    <div id="combinationModal" class="modal">
        <div class="modal-content">
            <span class="close-button">&times;</span>
            <h3 id="combinationModalTitle">Create Subject Combination</h3>
            <form id="combinationForm" method="POST" action="admin_subjects.php">
                <input type="hidden" name="action" id="combinationAction">
                <input type="hidden" name="combination_id" id="combinationId">
                
                <div class="form-group">
                    <label for="combination_name">Combination Name: <span class="required">*</span></label>
                    <input type="text" id="combination_name" name="combination_name" required>
                    <small>A descriptive name for this combination (e.g., "Physics-Economics-Mathematics")</small>
                </div>
                
                <div class="form-group">
                    <label for="combination_description">Description:</label>
                    <textarea id="combination_description" name="combination_description" rows="3" placeholder="Brief description of this combination (optional)"></textarea>
                </div>
                
                <div class="form-group">
                    <label>Applicable Levels: <span class="required">*</span></label>
                    <div class="checkbox-group">
                        <label class="checkbox-label">
                            <input type="checkbox" name="applicable_levels[]" value="S1"> Senior 1
                        </label>
                        <label class="checkbox-label">
                            <input type="checkbox" name="applicable_levels[]" value="S2"> Senior 2
                        </label>
                        <label class="checkbox-label">
                            <input type="checkbox" name="applicable_levels[]" value="S3"> Senior 3
                        </label>
                        <label class="checkbox-label">
                            <input type="checkbox" name="applicable_levels[]" value="S4"> Senior 4
                        </label>
                        <label class="checkbox-label">
                            <input type="checkbox" name="applicable_levels[]" value="S5"> Senior 5
                        </label>
                        <label class="checkbox-label">
                            <input type="checkbox" name="applicable_levels[]" value="S6"> Senior 6
                        </label>
                    </div>
                    <small>Select the levels this combination applies to. For S5-S6, General Paper will be automatically included.</small>
                </div>
                
                <div class="form-group">
                    <label>Select Subjects: <span class="required">*</span></label>
                    <div class="checkbox-group" id="subjectsChecklist">
                        <!-- Subject checkboxes will be populated by JavaScript -->
                    </div>
                    <small>Select the subjects to include in this combination in the desired order. The code will be generated based on the order of selection. General Paper will be automatically included for S5-S6 combinations.</small>
                </div>
                
                <div class="form-group">
                    <label for="combination_code">Combination Code: <span class="required">*</span></label>
                    <div style="display: flex; gap: 10px; align-items: center;">
                        <input type="text" id="combination_code" name="combination_code" required placeholder="Enter combination code" style="flex: 1;">
                        <button type="button" id="generateCodeBtn" class="btn btn-secondary" style="white-space: nowrap;">Generate from Subjects</button>
                    </div>
                    <div style="margin-top: 5px;">
                        <small><strong>Suggested Code:</strong> <span id="generatedCode" style="color: #007bff;">Select subjects to see suggestions</span></small>
                    </div>
                    <small>Enter a unique code for this combination (e.g., PEM/ICT). You can either type it manually or use the "Generate from Subjects" button.</small>
                </div>
                
                <div class="modal-actions">
                    <button type="submit" class="btn btn-success">Save Combination</button>
                    <button type="button" class="btn btn-secondary close-button">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Confirmation Modal for Deletion -->
    <div id="confirmModal" class="modal">
        <div class="modal-content">
            <span class="close-button">&times;</span>
            <h3>Confirm Deletion</h3>
            <p id="confirmMessage">Are you sure you want to delete this item? This action cannot be undone.</p>
            <form id="deleteForm" method="POST" action="admin_subjects.php">
                <input type="hidden" name="action" id="deleteAction">
                <input type="hidden" name="subject_id" id="deleteSubjectId">
                <input type="hidden" name="paper_id" id="deletePaperId">
                <input type="hidden" name="topic_id" id="deleteTopicId">
                <input type="hidden" name="competency_id" id="deleteCompetencyId">
                <input type="hidden" name="combination_id" id="deleteCombinationId">
                <div class="modal-actions">
                    <button type="submit" class="btn btn-danger">Delete</button>
                    <button type="button" class="btn btn-secondary close-button">Cancel</button>
                </div>
            </form>
        </div>
    </div>


    <script>
        // Your existing PHP variable for school name for JS translation
        const schoolNameForJs = "<?php echo $school_name_for_js; ?>";
        const currentUserId = "<?php echo $user_id; ?>"; // Get current user ID for potential use

        const translations = {
            en: {
                dashboard: "Dashboard",
                calendar: "Calendar",
                users: "Users",
                students: "Students",
                teachers: "Teachers",
                classes: "Classes",
                subjects: "Subjects",
                exams: "Exams",
                messages: "Messages",
                printouts: "Printouts",
                systemSettings: "Settings",
                logout: "Logout",
                searchPlaceholder: "Search students/data",
                welcomePrefix: "Welcome ",
                welcomeSuffix: "!",
                manageSchoolOperations: `Manage all aspects of ${schoolNameForJs} school operations.`,
                totalStudents: "Total Students",
                totalTeachers: "Total Teachers",
                totalClasses: "Total Classes",
                unreadMessages: "Unread Messages",
                examAnalysis: "Exam Analysis",
                classLabel: "Class",
                subjectLabel: "Subject",
                avgScoreLabel: "Avg. Score",
                overallClassPerformance: "Overall Class Performance Graph",
                noExamData: "No exam analysis data available for your school.",
                noChartData: "No data available to generate class performance graph.",
                monthView: "Month",
                mon: "Mon",
                tue: "Tue",
                wed: "Wed",
                thu: "Thu",
                fri: "Fri",
                sat: "Sat",
                sun: "Sun",
                monthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
                profileTextFooter: "Profile",
                settingsTextFooter: "Settings",
                logoutTextFooter: "Logout",
                // New translations for admin_subjects.php
                subjectManagement: "Subject Management",
                allSubjects: "All Subjects",
                addNewSubject: "Add New Subject",
                subjectName: "Subject Name",
                actions: "Actions",
                viewPapers: "View Papers",
                edit: "Edit",
                delete: "Delete",
                noSubjectsFound: "No subjects found for your school. Click \"Add New Subject\" to get started.",
                addSubject: "Add Subject",
                saveSubject: "Save Subject",
                editSubject: "Edit Subject",
                papersFor: "Papers for",
                addNewPaper: "Add New Paper",
                paperName: "Paper Name",
                viewTopics: "View Topics",
                noPapersFound: "No papers found for this subject. Click \"Add New Paper\" to add one.",
                addPaper: "Add Paper",
                savePaper: "Save Paper",
                editPaper: "Edit Paper",
                topicsFor: "Topics for",
                addNewTopic: "Add New Topic",
                topicName: "Topic Name",
                viewCompetencies: "View Competencies",
                noTopicsFound: "No topics found for this paper. Click \"Add New Topic\" to add one.",
                addNewCompetency: "Add New Competency",
                competencyDescription: "Competency Description",
                noCompetenciesFound: "No competencies found for this topic. Click \"Add New Competency\" to add one.",
                addCompetency: "Add Competency",
                saveCompetency: "Save Competency",
                editCompetency: "Edit Competency",
                confirmDeletion: "Confirm Deletion",
                confirmDeleteMessage: "Are you sure you want to delete this item? This action cannot be undone.",
                cancel: "Cancel",
                home: "Home", // For breadcrumb if needed
                // New translations for advanced subject system
                subjectCode: "Code",
                category: "Category",
                levels: "Levels",
                minMaxStudents: "Min/Max Students",
                capacity: "Capacity",
                compulsory: "Compulsory",
                optional: "Optional",
                elective: "Elective",
                applicableLevels: "Applicable Levels",
                minStudents: "Min. Students",
                maxStudents: "Max. Students",
                description: "Description",
                senior1: "Senior 1",
                senior2: "Senior 2",
                senior3: "Senior 3",
                senior4: "Senior 4",
                senior5: "Senior 5",
                senior6: "Senior 6",
                // New translations for subject combinations
                subjectCombinations: "Subject Combinations",
                createSubjectCombination: "Create Subject Combination",
                combinationCode: "Combination Code",
                combinationName: "Combination Name",
                subjects: "Subjects",
                description: "Description",
                selectSubjects: "Select Subjects",
                generatedCode: "Generated Code",
                selectSubjectsToSeeCode: "Select subjects to see suggestions",
                saveCombination: "Save Combination",
                editSubjectCombination: "Edit Subject Combination",
                editCombination: "Edit",
                deleteCombination: "Delete Combination",
                noCombinationsMessage: "No subject combinations created yet. Click \"Create Subject Combination\" to combine subjects with unique codes.",
                combinationCreatedSuccessfully: "Subject combination created successfully",
                combinationUpdatedSuccessfully: "Subject combination updated successfully",
                combinationDeletedSuccessfully: "Subject combination deleted successfully",
                errorLoadingSubjects: "Error loading subjects. Please try again.",
                selectSubjectsPlaceholder: "Select subjects to see suggestions",
                generalPaperAutoAdded: "General Paper automatically added for S5-S6"
            },
            lg: { // Luganda translations
                dashboard: "Akawungeezi",
                calendar: "Kalenda",
                users: "Abakozesa",
                students: "Abayizi",
                teachers: "Basomesa",
                classes: "Ebyana",
                subjects: "Ebizibu",
                exams: "Ebyokugezesa",
                messages: "Obubaka",
                printouts: "Ebiwandiiko",
                systemSettings: "Enteekateeka",
                logout: "Vaamu",
                searchPlaceholder: "Noonya abayizi/ebitabo",
                welcomePrefix: "Tukwaniriza ",
                welcomeSuffix: "!",
                manageSchoolOperations: `Fuga eby'ettutumu byonna eby'essomero lya ${schoolNameForJs}.`,
                totalStudents: "Omugatte gw'Abayizi",
                totalTeachers: "Omugatte gw'Abasomesa",
                totalClasses: "Omugatte gw'Ebyana",
                unreadMessages: "Obubaka obutatambuddwa",
                examAnalysis: "Okunoonyereza ku ebyokugezesa",
                classLabel: "Ekibiina",
                subjectLabel: "Ekitabo",
                avgScoreLabel: "Avg. Obubonero",
                overallClassPerformance: "Ekiragiro ky'obubonero bw'ebibiina",
                noExamData: "Tewali data ya kunoonyereza ku byokugezesa eyateekebwawo.",
                noChartData: "Tewali data ya kutandika kiragiro ky'obubonero bw'ebibiina.",
                monthView: "Omwezi",
                mon: "Bal",
                tue: "Bab",
                wed: "Kus",
                thu: "Kut",
                fri: "Kut",
                sat: "Nga",
                sun: "Saw",
                monthNames: ["Gatonnya", "Mugula", "Muganga", "Kafumu", "Muzigo", "Ogusooka", "Ogwokubiri", "Ogusatu", "Ogukkumi", "Ogwomunaana", "Ogwomwenda", "Ogwekkumi"],
                profileTextFooter: "Enkola",
                settingsTextFooter: "Enteekateeka",
                logoutTextFooter: "Vaamu",
                // New translations for admin_subjects.php
                subjectManagement: "Okuddukanya Ebisuubizo",
                allSubjects: "Ebisuubizo Byonna",
                addNewSubject: "Yongeramu Ekisuubizo Kipya",
                subjectName: "Erinnya ly'Ekisuubizo",
                actions: "Ebikolebwa",
                viewPapers: "Laba Empapula",
                edit: "Wandika",
                delete: "Sazaamu",
                noSubjectsFound: "Tewali bisuubizo byasangibwa ku ssomero lyo. Nyiga \"Yongeramu Ekisuubizo Kipya\" okutandika.",
                addSubject: "Yongeramu Ekisuubizo",
                saveSubject: "Kuuma Ekisuubizo",
                editSubject: "Wandika Ekisuubizo",
                papersFor: "Empapula z'ekisuubizo",
                addNewPaper: "Yongeramu Olupapula Olupya",
                paperName: "Erinnya ly'Olupapula",
                viewTopics: "Laba Emitwe",
                noPapersFound: "Tewali mpapula zaasangibwa ku kisuubizo kino. Nyiga \"Yongeramu Olupapula Olupya\" okuyongeramu.",
                addPaper: "Yongeramu Olupapula",
                savePaper: "Kuuma Olupapula",
                editPaper: "Wandika Olupapula",
                topicsFor: "Emitwe gy'olupapula",
                addNewTopic: "Yongeramu Omutwe Omupya",
                topicName: "Erinnya ly'Omutwe",
                viewCompetencies: "Laba Obukugu",
                noTopicsFound: "Tewali mitwe gyaasangibwa ku lupapula luno. Nyiga \"Yongeramu Omutwe Omupya\" okuyongeramu.",
                addNewCompetency: "Yongeramu Obukugu Obupya",
                competencyDescription: "Ekyokulaga Obukugu",
                noCompetenciesFound: "Tewali bukugu bwasangibwa ku mutwe guno. Nyiga \"Yongeramu Obukugu Obupya\" okuyongeramu.",
                addCompetency: "Yongeramu Obukugu",
                saveCompetency: "Kuuma Obukugu",
                editCompetency: "Wandika Obukugu",
                confirmDeletion: "Kakasa Okusazaawo",
                confirmDeleteMessage: "Oli mukakasa okusazaamu kino? Ekikolwa kino tekisobola kuddizibwa.",
                cancel: "Ghairi",
                home: "Awaka",
                // New translations for advanced subject system
                subjectCode: "Koodi",
                category: "Ekibiina",
                levels: "Amawanika",
                minMaxStudents: "Min/Max Abayizi",
                capacity: "Omugatte",
                compulsory: "Ekisaanidde",
                optional: "Ekyerobozibwa",
                elective: "Ekyongerwako",
                applicableLevels: "Amawanika Agakwata",
                minStudents: "Abayizi Abatono",
                maxStudents: "Abayizi Abasinga",
                description: "Ennyonnyola",
                senior1: "Seniya 1",
                senior2: "Seniya 2",
                senior3: "Seniya 3",
                senior4: "Seniya 4",
                senior5: "Seniya 5",
                senior6: "Seniya 6",
                // New translations for subject combinations
                subjectCombinations: "Ebisuubizo Ebyonesebwa",
                createSubjectCombination: "Yongeramu Ekisuubizo Ekigatte",
                combinationCode: "Koodi y'Ekisuubizo",
                combinationName: "Erinnya ly'Ekisuubizo",
                subjects: "Ebisuubizo",
                description: "Ennyonnyola",
                selectSubjects: "Yonnyola Ebisuubizo",
                generatedCode: "Koodi Eyogerwa",
                selectSubjectsToSeeCode: "Yonnyola ebisuubizo olabe koodi",
                saveCombination: "Kuuma Ekigatte",
                editSubjectCombination: "Wandika Ekisubizo Ekigatte",
                editCombination: "Wandika",
                deleteCombination: "Sazaamu Ekigatte",
                noCombinationsMessage: "Tewali bisuubizo byonesebwa. Nyiga \"Yongeramu Ekisubizo Ekigatte\" okugatta ebisuubizo n'akoodi kapya.",
                combinationCreatedSuccessfully: "Ekisuubizo ekigatte kikolebwa bulungi",
                combinationUpdatedSuccessfully: "Ekisubizo ekigatte kiwandikiddwa bulungi",
                combinationDeletedSuccessfully: "Ekisubizo ekigatte kisasiziddwa bulungi",
                errorLoadingSubjects: "Kyasudde okuwaanya ebisuubizo. Muweeko ettaka.",
                selectSubjectsPlaceholder: "Yonnyola ebisuubizo olabe koodi"
            },
            sw: { // Kiswahili translations
                dashboard: "Dashibodi",
                calendar: "Kalenda",
                users: "Watumiaji",
                students: "Wanafunzi",
                teachers: "Walimu",
                classes: "Madarasa",
                subjects: "Masomo",
                exams: "Mitihani",
                messages: "Ujumbe",
                printouts: "Machapisho",
                systemSettings: "Mipangilio",
                logout: "Toka",
                searchPlaceholder: "Tafuta wanafunzi/data",
                welcomePrefix: "Karibu ",
                welcomeSuffix: "!",
                manageSchoolOperations: `Dhibiti masuala yote ya uendeshaji wa shule ya ${schoolNameForJs}.`,
                totalStudents: "Jumla ya Wanafunzi",
                totalTeachers: "Jumla ya Walimu",
                totalClasses: "Jumla ya Madarasa",
                unreadMessages: "Ujumbe Usiosomwa",
                examAnalysis: "Uchambuzi wa Mitihani",
                classLabel: "Darasa",
                subjectLabel: "Somo",
                avgScoreLabel: "Wastani wa Alama",
                overallClassPerformance: "Grafu ya Utendaji wa Jumla wa Darasa",
                noExamData: "Hakuna data ya uchambuzi wa mitihani inayopatikana kwa shule yako.",
                noChartData: "Hakuna data inayopatikana ili kuzalisha grafu ya utendaji wa darasa.",
                monthView: "Mwezi",
                mon: "Jt",
                tue: "Jnn",
                wed: "Jt",
                thu: "Alh",
                fri: "Ij",
                sat: "Jmn",
                sun: "Jp",
                monthNames: ["Januari", "Februari", "Machi", "Aprili", "Mei", "Juni", "Julai", "Agosti", "Septemba", "Oktoba", "Novemba", "Desemba"],
                profileTextFooter: "Wasifu",
                settingsTextFooter: "Mipangilio",
                logoutTextFooter: "Toka",
                // New translations for admin_subjects.php
                subjectManagement: "Usimamizi wa Masomo",
                allSubjects: "Masomo Yote",
                addNewSubject: "Ongeza Somo Jipya",
                subjectName: "Jina la Somo",
                actions: "Vitendo",
                viewPapers: "Angalia Karatasi",
                edit: "Hariri",
                delete: "Futa",
                noSubjectsFound: "Hakuna masomo yaliyopatikana kwa shule yako. Bofya \"Ongeza Somo Jipya\" ili kuanza.",
                addSubject: "Ongeza Somo",
                saveSubject: "Hifadhi Somo",
                editSubject: "Hariri Somo",
                papersFor: "Karatasi za",
                addNewPaper: "Ongeza Karatasi Mpya",
                paperName: "Jina la Karatasi",
                viewTopics: "Angalia Mada",
                noPapersFound: "Hakuna karatasi zilizopatikana kwa somo hili. Bofya \"Ongeza Karatasi Mpya\" ili kuongeza.",
                addPaper: "Ongeza Karatasi",
                savePaper: "Hifadhi Karatasi",
                editPaper: "Hariri Karatasi",
                topicsFor: "Mada za",
                addNewTopic: "Ongeza Mada Mpya",
                topicName: "Jina la Mada",
                viewCompetencies: "Angalia Umahiri",
                noTopicsFound: "Hakuna mada zilizopatikana kwa karatasi hii. Bofya \"Ongeza Mada Mpya\" ili kuongeza.",
                addNewCompetency: "Ongeza Umahiri Mpya",
                competencyDescription: "Maelezo ya Umahiri",
                noCompetenciesFound: "Hakuna umahiri uliyopatikana kwa mada hii. Bofya \"Ongeza Umahiri Mpya\" ili kuongeza.",
                addCompetency: "Ongeza Umahiri",
                saveCompetency: "Hifadhi Umahiri",
                editCompetency: "Hariri Umahiri",
                confirmDeletion: "Thibitisha Kufuta",
                confirmDeleteMessage: "Una uhakika unataka kufuta kipengee hiki? Kitendo hiki hakiwezi kutenduliwa.",
                cancel: "Ghairi",
                home: "Nyumbani",
                // New translations for advanced subject system
                subjectCode: "Msimbo",
                category: "Aina",
                levels: "Madaraja",
                minMaxStudents: "Idadi ya Wanafunzi",
                capacity: "Uwezo",
                compulsory: "Lazima",
                optional: "Hiari",
                elective: "Za Ziada",
                applicableLevels: "Madaraja Yanayohusika",
                minStudents: "Wanafunzi Wachache",
                maxStudents: "Wanafunzi Wengi",
                description: "Maelezo",
                senior1: "Kidato cha 1",
                senior2: "Kidato cha 2",
                senior3: "Kidato cha 3",
                senior4: "Kidato cha 4",
                senior5: "Kidato cha 5",
                senior6: "Kidato cha 6",
                // New translations for subject combinations
                subjectCombinations: "M集合 ya Masomo",
                createSubjectCombination: "Unda Muungano wa Somo",
                combinationCode: "Namba ya Muungano",
                combinationName: "Jina la Muungano",
                subjects: "Masomo",
                description: "Maelezo",
                selectSubjects: "Chagua Masomo",
                generatedCode: "Namba Iliyoundwa",
                selectSubjectsToSeeCode: "Chagua masomo kuona mapendekezo",
                saveCombination: "Hifadhi Muungano",
                editSubjectCombination: "Hariri Muungano wa Somo",
                editCombination: "Hariri",
                deleteCombination: "Futa Muungano",
                noCombinationsMessage: "Hakuna mungano wa somo ulioundwa. Bofya \"Unda Muungano wa Somo\" kuunganisha masomo kwa msimbo wa kipekee.",
                combinationCreatedSuccessfully: "Muungano wa somo umeundwa kwa mafanikio",
                combinationUpdatedSuccessfully: "Muungano wa somo umefanyiwa mabadiliko kwa mafanikio",
                combinationDeletedSuccessfully: "Muungano wa somo umefutwa kwa mafanikio",
                errorLoadingSubjects: "Kuna tatizo kupakia masomo. Jaribu tena.",
                selectSubjectsPlaceholder: "Chagua masomo kuona mapendekezo",
                generalPaperAutoAdded: "General Paper imeongezwa kiotomatiki kwa S5-S6"
            }
        };

        // Function to apply translations based on the selected language
        function applyTranslations(lang) {
            const t = translations[lang];

            // Sidebar links - THESE ARE ALWAYS PRESENT
            const dashboardLinkElem = document.getElementById('dashboardLink');
            if (dashboardLinkElem) {
                const span = dashboardLinkElem.querySelector('i + span');
                if (span) span.textContent = t.dashboard;
            }
            const calendarLinkElem = document.getElementById('calendarLink');
            if (calendarLinkElem) {
                const span = calendarLinkElem.querySelector('i + span');
                if (span) span.textContent = t.calendar;
            }
            const usersLinkElem = document.getElementById('usersLink');
            if (usersLinkElem) {
                const span = usersLinkElem.querySelector('i + span');
                if (span) span.textContent = t.users;
            }
            const studentsLinkElem = document.getElementById('studentsLink');
            if (studentsLinkElem) {
                const span = studentsLinkElem.querySelector('i + span');
                if (span) span.textContent = t.students;
            }
            const teachersLinkElem = document.getElementById('teachersLink');
            if (teachersLinkElem) {
                const span = teachersLinkElem.querySelector('i + span');
                if (span) span.textContent = t.teachers;
            }
            const classesLinkElem = document.getElementById('classesLink');
            if (classesLinkElem) { // This can be hidden by CSS but should exist in DOM
                const span = classesLinkElem.querySelector('i + span');
                if (span) span.textContent = t.classes;
            }
            const subjectsLinkElem = document.getElementById('subjectsLink');
            if (subjectsLinkElem) {
                const span = subjectsLinkElem.querySelector('i + span');
                if (span) span.textContent = t.subjects;
            }
            const gradesLinkElem = document.getElementById('gradesLink');
            if (gradesLinkElem) {
                const span = gradesLinkElem.querySelector('i + span');
                if (span) span.textContent = "Grades"; // Hardcoded as per comment
            }
            const examsLinkElem = document.getElementById('examsLink');
            if (examsLinkElem) { // Can be hidden by CSS
                const span = examsLinkElem.querySelector('i + span');
                if (span) span.textContent = t.exams;
            }
            const messagesLinkSidebarElem = document.getElementById('messagesLinkSidebar');
            if (messagesLinkSidebarElem) {
                const span = messagesLinkSidebarElem.querySelector('i + span');
                if (span) span.textContent = t.messages;
            }
            const printoutsLinkElem = document.getElementById('printoutsLink');
            if (printoutsLinkElem) { // Can be hidden by CSS
                const span = printoutsLinkElem.querySelector('i + span');
                if (span) span.textContent = t.printouts;
            }
            const systemSettingsLinkElem = document.getElementById('systemSettingsLink');
            if (systemSettingsLinkElem) { // Can be hidden by CSS
                const span = systemSettingsLinkElem.querySelector('i + span');
                if (span) span.textContent = t.systemSettings;
            }
            const logoutLinkSidebarElem = document.getElementById('logoutLinkSidebar');
            if (logoutLinkSidebarElem) { // Can be hidden by CSS
                const span = logoutLinkSidebarElem.querySelector('i + span');
                if (span) span.textContent = t.logout;
            }

            // Header elements - THESE ARE ALWAYS PRESENT
            const searchPlaceholderElem = document.getElementById('searchPlaceholder');
            if (searchPlaceholderElem) searchPlaceholderElem.placeholder = t.searchPlaceholder;

            // Mobile Footer - THESE ARE ALWAYS PRESENT
            const profileTextFooterElem = document.getElementById('profileLinkFooter')?.querySelector('span'); // Corrected
            if (profileTextFooterElem) profileTextFooterElem.textContent = t.profileTextFooter;
            const settingsTextFooterElem = document.getElementById('settingsLinkFooter')?.querySelector('span'); // Corrected
            if (settingsTextFooterElem) settingsTextFooterElem.textContent = t.settingsTextFooter;
            const logoutTextFooterElem = document.getElementById('logoutLinkFooter')?.querySelector('span'); // Corrected
            if (logoutTextFooterElem) logoutTextFooterElem.textContent = t.logoutTextFooter;

            // Subject Management Page Main Title (always present)
            const dashboardContentH2 = document.querySelector('.dashboard-content h2');
            if (dashboardContentH2) dashboardContentH2.innerHTML = `<i class="fas fa-book"></i> ${t.subjectManagement}`;

            // Subject Combinations elements
            const subjectCombinationsTitle = document.getElementById('subjectCombinationsTitle');
            if (subjectCombinationsTitle) subjectCombinationsTitle.textContent = t.subjectCombinations;
            
            const addCombinationBtn = document.getElementById('addSubjectCombinationBtn');
            if (addCombinationBtn) addCombinationBtn.textContent = t.createSubjectCombination;
            
            const noCombinationsMessage = document.getElementById('noCombinationsMessage');
            if (noCombinationsMessage) {
                noCombinationsMessage.textContent = t.noCombinationsMessage;
            }

            // Table headers for combinations
            const combinationTableHeaders = document.querySelectorAll('.data-table th');
            combinationTableHeaders.forEach(th => {
                const text = th.textContent.trim();
                if (text === "Combination Code") th.textContent = t.combinationCode;
                else if (text === "Combination Name") th.textContent = t.combinationName;
                else if (text === "Subjects") th.textContent = t.subjects;
                else if (text === "Description") th.textContent = t.description;
                else if (text === "Levels") th.textContent = t.levels;
            });

            // Combination action buttons
            document.querySelectorAll('.edit-combination-btn').forEach(btn => btn.textContent = t.editCombination);
            document.querySelectorAll('.delete-combination-btn').forEach(btn => btn.textContent = t.deleteCombination);

            // Combination modal
            const combinationModalTitle = document.getElementById('combinationModalTitle');
            if (combinationModalTitle) {
                if (combinationModalTitle.textContent.includes('Create Subject Combination')) {
                    combinationModalTitle.textContent = t.createSubjectCombination;
                } else if (combinationModalTitle.textContent.includes('Edit Subject Combination')) {
                    combinationModalTitle.textContent = t.editSubjectCombination;
                }
            }

            // Form labels for combinations
            const combinationNameLabel = document.querySelector('label[for="combination_name"]');
            if (combinationNameLabel) combinationNameLabel.textContent = t.combinationName + ":";
            
            const combinationDescriptionLabel = document.querySelector('label[for="combination_description"]');
            if (combinationDescriptionLabel) combinationDescriptionLabel.textContent = t.description + ":";
            
            // Find labels by their text content
            const combinationModalLabels = document.querySelectorAll('#combinationModal label');
            combinationModalLabels.forEach(label => {
                const text = label.textContent.trim();
                if (text.startsWith('Select Subjects:')) {
                    label.textContent = t.selectSubjects + ":";
                } else if (text.startsWith('Generated Code:')) {
                    label.textContent = t.generatedCode + ":";
                }
            });
            
            const combinationFormSaveBtn = document.querySelector('#combinationForm .btn-success');
            if (combinationFormSaveBtn) combinationFormSaveBtn.textContent = t.saveCombination;

            // Breadcrumb (always present)
            const breadcrumbLinks = document.querySelectorAll('.breadcrumb a');
            if (breadcrumbLinks[0]) breadcrumbLinks[0].textContent = t.subjects;
            // The rest of the breadcrumbs are dynamically generated, their text content will be from PHP variables.

            // Conditional translation for specific page views
            // Check if we are on the 'All Subjects' view (i.e., no subject_id, paper_id, or topic_id in URL)
            const urlParams = new URLSearchParams(window.location.search);
            const isAllSubjectsView = !urlParams.has('subject_id') && !urlParams.has('paper_id') && !urlParams.has('topic_id');

            if (isAllSubjectsView) {
                const subjectsListTitle = document.getElementById('subjectsListTitle');
                if (subjectsListTitle) subjectsListTitle.textContent = t.allSubjects;

                // Buttons for the main view
                const addSubjectBtn = document.getElementById('addSubjectBtn');
                if (addSubjectBtn) addSubjectBtn.textContent = t.addNewSubject;
                const addPaperFromMainBtn = document.getElementById('addPaperFromMainBtn');
                if (addPaperFromMainBtn) addPaperFromMainBtn.textContent = t.addNewPaper;
                const addTopicFromMainBtn = document.getElementById('addTopicFromMainBtn');
                if (addTopicFromMainBtn) addTopicFromMainBtn.textContent = t.addNewTopic;
                const addCompetencyFromMainBtn = document.getElementById('addCompetencyFromMainBtn');
                if (addCompetencyFromMainBtn) addCompetencyFromMainBtn.textContent = t.addNewCompetency;
                
                const noSubjectsMessage = document.getElementById('noSubjectsMessage');
                if (noSubjectsMessage) {
                    noSubjectsMessage.textContent = t.noSubjectsFound;
                }
            }


            // Tables headers (These loops will gracefully do nothing if no such elements exist)
            document.querySelectorAll('.data-table th').forEach(th => {
                const text = th.textContent.trim();
                if (text === "Subject Name") th.textContent = t.subjectName;
                else if (text === "Paper Name") th.textContent = t.paperName;
                else if (text === "Topic Name") th.textContent = t.topicName;
                else if (text === "Competency Description") th.textContent = t.competencyDescription;
                else if (text === "Actions") th.textContent = t.actions;
            });

            // Table action buttons
            document.querySelectorAll('.btn-primary').forEach(btn => {
                // Check if the button is specifically for navigation, not just a primary button
                if (btn.textContent.includes("View Papers")) btn.textContent = t.viewPapers;
                if (btn.textContent.includes("View Topics")) btn.textContent = t.viewTopics;
                if (btn.textContent.includes("View Competencies")) btn.textContent = t.viewCompetencies;
            });
            document.querySelectorAll('.btn-warning').forEach(btn => btn.textContent = t.edit);
            document.querySelectorAll('.btn-danger').forEach(btn => btn.textContent = t.delete);

            // Add/Edit Modals (These exist in the DOM but are hidden, so direct manipulation is fine if they exist)
            const subjectModalTitle = document.getElementById('subjectModalTitle');
            if (subjectModalTitle) {
                // Use .includes to allow for cases where PHP might inject a default title like "Add Subject"
                if (subjectModalTitle.textContent.includes('Add Subject')) subjectModalTitle.textContent = t.addSubject;
                else if (subjectModalTitle.textContent.includes('Edit Subject')) subjectModalTitle.textContent = t.editSubject;
            }
            const subjectFormLabel = document.querySelector('#subjectForm label[for="subject_name"]');
            if (subjectFormLabel) subjectFormLabel.textContent = t.subjectName + ":";
            const subjectFormSaveBtn = document.querySelector('#subjectForm .btn-success');
            if (subjectFormSaveBtn) subjectFormSaveBtn.textContent = t.saveSubject;


            const paperModalTitle = document.getElementById('paperModalTitle');
            if (paperModalTitle) {
                if (paperModalTitle.textContent.includes('Add Paper')) paperModalTitle.textContent = t.addPaper;
                else if (paperModalTitle.textContent.includes('Edit Paper')) paperModalTitle.textContent = t.editPaper;
            }
            const paperFormLabel = document.querySelector('#paperForm label[for="paper_name"]');
            if (paperFormLabel) paperFormLabel.textContent = t.paperName + ":";
            const paperFormSaveBtn = document.querySelector('#paperForm .btn-success');
            if (paperFormSaveBtn) paperFormSaveBtn.textContent = t.savePaper;
            const paperSubjectSelectLabel = document.querySelector('#paperForm label[for="paperSubjectSelect"]');
            if (paperSubjectSelectLabel) paperSubjectSelectLabel.textContent = t.subjectLabel + ":";


            const topicModalTitle = document.getElementById('topicModalTitle');
            if (topicModalTitle) {
                if (topicModalTitle.textContent.includes('Add Topic')) topicModalTitle.textContent = t.addTopic;
                else if (topicModalTitle.textContent.includes('Edit Topic')) topicModalTitle.textContent = t.editTopic;
            }
            const topicFormLabel = document.querySelector('#topicForm label[for="topic_name"]');
            if (topicFormLabel) topicFormLabel.textContent = t.topicName + ":";
            const topicFormSaveBtn = document.querySelector('#topicForm .btn-success');
            if (topicFormSaveBtn) topicFormSaveBtn.textContent = t.saveTopic;
            const topicPaperSelectLabel = document.querySelector('#topicForm label[for="topicPaperSelect"]');
            if (topicPaperSelectLabel) topicPaperSelectLabel.textContent = t.paperName + ":"; // Should be paper, not subject


            const competencyModalTitle = document.getElementById('competencyModalTitle');
            if (competencyModalTitle) {
                if (competencyModalTitle.textContent.includes('Add Competency')) competencyModalTitle.textContent = t.addCompetency;
                else if (competencyModalTitle.textContent.includes('Edit Competency')) competencyModalTitle.textContent = t.editCompetency;
            }
            const competencyFormLabel = document.querySelector('#competencyForm label[for="competency_description"]');
            if (competencyFormLabel) competencyFormLabel.textContent = t.competencyDescription + ":";
            const competencyFormSaveBtn = document.querySelector('#competencyForm .btn-success');
            if (competencyFormSaveBtn) competencyFormSaveBtn.textContent = t.saveCompetency;
            const competencyTopicSelectLabel = document.querySelector('#competencyForm label[for="competencyTopicSelect"]');
            if (competencyTopicSelectLabel) competencyTopicSelectLabel.textContent = t.topicName + ":";


            // Confirmation Modal (This exists in the DOM but is hidden)
            const confirmModalHeading = document.querySelector('#confirmModal h3');
            if (confirmModalHeading) confirmModalHeading.textContent = t.confirmDeletion;
            
            const confirmMessageElement = document.getElementById('confirmMessage');
            if (confirmMessageElement) confirmMessageElement.textContent = t.confirmDeleteMessage;
            
            const confirmModalDeleteBtn = document.querySelector('#confirmModal .btn-danger');
            if (confirmModalDeleteBtn) confirmModalDeleteBtn.textContent = t.delete;
            
            // Explicitly target the Cancel button within each modal if they have unique IDs or if it's the only one
            // Or ensure generic close buttons are not text-translated if they are just 'x'
            document.querySelectorAll('.modal .btn-secondary.close-button').forEach(btn => {
                 btn.textContent = t.cancel;
            });

        }

        // Language selection event listener
        document.getElementById('languageSelect').addEventListener('change', function() {
            applyTranslations(this.value);
            // Store selected language in localStorage
            localStorage.setItem('selectedLanguage', this.value);
        });

        // Apply initial translation on page load
        const storedLanguage = localStorage.getItem('selectedLanguage');
        if (storedLanguage && translations[storedLanguage]) {
            document.getElementById('languageSelect').value = storedLanguage;
            applyTranslations(storedLanguage);
        } else {
            applyTranslations('en'); // Default to English if no stored preference
        }
        
        // Auto-fade feedback messages after 5 seconds
        document.addEventListener('DOMContentLoaded', function() {
            const feedbackMessages = document.querySelectorAll('.success, .error');
            
            feedbackMessages.forEach(function(message) {
                // Start fade-out after 5 seconds
                setTimeout(function() {
                    message.classList.add('fade-out');
                    
                    // Remove from DOM after animation completes (0.5s)
                    setTimeout(function() {
                        message.remove();
                    }, 500);
                }, 5000);
            });
        });


        // Sidebar Toggle
        const menuToggle = document.getElementById('menuToggle');
        const sidebar = document.getElementById('sidebar');
        const dashboardContainer = document.getElementById('dashboardContainer');
        const overlay = document.getElementById('overlay');

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

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

        // Helper function to populate dropdowns via AJAX
        async function populateDropdown(selectElementId, dataUrl, defaultOptionText, selectedId = null, filterParentId = null, filterParentKey = null) {
            const selectElement = document.getElementById(selectElementId);
            if (!selectElement) return;

            // Clear existing options
            selectElement.innerHTML = `<option value="">${defaultOptionText}</option>`; 

            try {
                let url = dataUrl;
                if (filterParentId && filterParentKey) {
                    url += `&${filterParentKey}=${filterParentId}`;
                }
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status} from ${url}`);
                }
                const data = await response.json();

                data.forEach(item => {
                    const option = document.createElement('option');
                    let idKey, nameKey;

                    // Determine the ID and Name keys dynamically based on the type of data being fetched
                    if (selectElementId === 'paperSubjectSelect') {
                        idKey = 'subject_id';
                        nameKey = 'subject_name';
                    } else if (selectElementId === 'topicPaperSelect') {
                        idKey = 'paper_id';
                        nameKey = 'paper_name';
                    } else if (selectElementId === 'competencyTopicSelect') {
                        idKey = 'topic_id';
                        nameKey = 'topic_name';
                    } else {
                        // Fallback for unexpected cases, though ideally these should be explicit
                        idKey = Object.keys(item)[0];
                        nameKey = Object.keys(item)[1];
                    }

                    option.value = item[idKey];
                    option.textContent = item[nameKey];
                    if (selectedId && item[idKey] == selectedId) {
                        option.selected = true;
                    }
                    selectElement.appendChild(option);
                });
            } catch (error) {
                console.error(`Error populating ${selectElementId}:`, error);
                // Optionally add an error option or message to the dropdown
                const errorOption = document.createElement('option');
                errorOption.value = "";
                errorOption.textContent = "Error loading data.";
                selectElement.appendChild(errorOption);
            }
        }


        // Universal modal handling
        function openModal(modalId, title, action, itemId = null, itemName = null, parentId = null, parentType = null) {
            const modal = document.getElementById(modalId);
            const form = modal.querySelector('form');
            const modalTitle = modal.querySelector('h3');

            modalTitle.textContent = title;
            form.reset(); // Clear form fields

            // Set hidden action and ID fields for form submission
            form.querySelector('input[name="action"]').value = action;
            const idInput = form.querySelector('input[name$="_id"]'); // e.g., subject_id, paper_id, topic_id, competency_id
            if (idInput) idInput.value = itemId || '';


            // Populate specific fields and dropdowns based on modal type
            if (modalId === 'subjectModal') {
                const subjectNameInput = document.getElementById('subject_name');
                if (subjectNameInput) subjectNameInput.value = itemName || '';
                
                // Reset category to default when adding new
                if (action === 'add_subject') {
                    document.getElementById('subject_category').value = 'Optional';
                    // Check S1-S4 by default for new subjects
                    document.querySelectorAll('input[name="applicable_levels[]"]').forEach(checkbox => {
                        checkbox.checked = ['S1', 'S2', 'S3', 'S4'].includes(checkbox.value);
                    });
                    document.getElementById('min_students').value = '';
                    document.getElementById('max_students').value = '';
                    document.getElementById('subject_description').value = '';
                }
            } else if (modalId === 'paperModal') {
                const paperNameInput = document.getElementById('paper_name');
                if (paperNameInput) paperNameInput.value = itemName || '';
                
                // Always populate subject dropdown when opening paper modal
                populateDropdown('paperSubjectSelect', 'admin_subjects.php?fetch_data=subjects', 'Select Parent Subject', parentId);

            } else if (modalId === 'topicModal') {
                const topicNameInput = document.getElementById('topic_name');
                if (topicNameInput) topicNameInput.value = itemName || '';

                // Always populate paper dropdown when opening topic modal
                populateDropdown('topicPaperSelect', 'admin_subjects.php?fetch_data=papers', 'Select Parent Paper', parentId);

                // Add event listener for cascading topic papers if a subject is first selected
                // (Not explicitly implemented in this general case, as it loads all papers, but ready for future)

            } else if (modalId === 'competencyModal') {
                const competencyDescriptionInput = document.getElementById('competency_description');
                if (competencyDescriptionInput) competencyDescriptionInput.value = itemName || '';

                // Always populate topic dropdown when opening competency modal
                populateDropdown('competencyTopicSelect', 'admin_subjects.php?fetch_data=topics', 'Select Parent Topic', parentId);

                // Add event listener for cascading competencies if a paper/subject is first selected
                // (Not explicitly implemented in this general case)
            }

            modal.style.display = 'flex';
            // DO NOT activate overlay - modal has its own background
            // overlay.classList.add('active');
        }

        function closeModals() {
            document.querySelectorAll('.modal').forEach(modal => {
                modal.style.display = 'none';
            });
            // DO NOT remove overlay active class - we're not using it for modals
            // overlay.classList.remove('active');
        }

        // Attach event listeners for opening modals
        document.getElementById('addSubjectBtn')?.addEventListener('click', () => {
            openModal('subjectModal', translations[localStorage.getItem('selectedLanguage') || 'en'].addSubject, 'add_subject');
        });
        document.querySelectorAll('.edit-subject-btn').forEach(button => {
            button.addEventListener('click', () => {
                const id = button.dataset.id;
                const name = button.dataset.name;
                const category = button.dataset.category || 'Optional';
                const levels = button.dataset.levels ? button.dataset.levels.split(',') : [];
                const minStudents = button.dataset.min || '';
                const maxStudents = button.dataset.max || '';
                
                // Open modal and set basic fields
                openModal('subjectModal', translations[localStorage.getItem('selectedLanguage') || 'en'].editSubject, 'edit_subject', id, name);
                
                // Set category
                document.getElementById('subject_category').value = category;
                
                // Set checkboxes for applicable levels
                document.querySelectorAll('input[name="applicable_levels[]"]').forEach(checkbox => {
                    checkbox.checked = levels.includes(checkbox.value);
                });
                
                // Set min/max students
                document.getElementById('min_students').value = minStudents;
                document.getElementById('max_students').value = maxStudents;
            });
        });

        // Event listener for "Add New Paper" from Main View
        document.getElementById('addPaperFromMainBtn')?.addEventListener('click', () => {
            openModal('paperModal', translations[localStorage.getItem('selectedLanguage') || 'en'].addPaper, 'add_paper');
        });
        // Existing "Add New Paper" button from Subject-specific view
        document.getElementById('addPaperBtn')?.addEventListener('click', (event) => {
            const subjectId = event.target.dataset.subjectId;
            openModal('paperModal', translations[localStorage.getItem('selectedLanguage') || 'en'].addPaper, 'add_paper', null, null, subjectId, 'subject');
        });
        document.querySelectorAll('.edit-paper-btn').forEach(button => {
            button.addEventListener('click', () => {
                const id = button.dataset.id;
                const name = button.dataset.name;
                // Pass the current subject ID from PHP context if editing from within a subject view
                openModal('paperModal', translations[localStorage.getItem('selectedLanguage') || 'en'].editPaper, 'edit_paper', id, name, <?php echo $selected_subject_id ?: 'null'; ?>, 'subject');
            });
        });

        // Event listener for "Add New Topic" from Main View
        document.getElementById('addTopicFromMainBtn')?.addEventListener('click', () => {
            openModal('topicModal', translations[localStorage.getItem('selectedLanguage') || 'en'].addTopic, 'add_topic');
        });
        // Existing "Add New Topic" button from Paper-specific view
        document.getElementById('addTopicBtn')?.addEventListener('click', (event) => {
            const paperId = event.target.dataset.paperId;
            openModal('topicModal', translations[localStorage.getItem('selectedLanguage') || 'en'].addTopic, 'add_topic', null, null, paperId, 'paper');
        });
        document.querySelectorAll('.edit-topic-btn').forEach(button => {
            button.addEventListener('click', () => {
                const id = button.dataset.id;
                const name = button.dataset.name;
                // Pass the current paper ID from PHP context if editing from within a paper view
                openModal('topicModal', translations[localStorage.getItem('selectedLanguage') || 'en'].editTopic, 'edit_topic', id, name, <?php echo $selected_paper_id ?: 'null'; ?>, 'paper');
            });
        });

        // Event listener for "Add New Competency" from Main View
        document.getElementById('addCompetencyFromMainBtn')?.addEventListener('click', () => {
            openModal('competencyModal', translations[localStorage.getItem('selectedLanguage') || 'en'].addCompetency, 'add_competency');
        });
        // Existing "Add New Competency" button from Topic-specific view
        document.getElementById('addCompetencyBtn')?.addEventListener('click', (event) => {
            const topicId = event.target.dataset.topicId;
            openModal('competencyModal', translations[localStorage.getItem('selectedLanguage') || 'en'].addCompetency, 'add_competency', null, null, topicId, 'topic');
        });
        document.querySelectorAll('.edit-competency-btn').forEach(button => {
            button.addEventListener('click', () => {
                const id = button.dataset.id;
                const description = button.dataset.description;
                // Pass the current topic ID from PHP context if editing from within a topic view
                openModal('competencyModal', translations[localStorage.getItem('selectedLanguage') || 'en'].editCompetency, 'edit_competency', id, description, <?php echo $selected_topic_id ?: 'null'; ?>, 'topic');
            });
        });


        // Attach event listeners for closing modals
        document.querySelectorAll('.modal .close-button').forEach(button => {
            button.addEventListener('click', closeModals);
        });
        document.querySelectorAll('.modal .btn-secondary.close-button').forEach(button => {
            button.addEventListener('click', closeModals);
        });
        
        // Close modal when clicking outside the modal-content (on the modal background)
        document.querySelectorAll('.modal').forEach(modal => {
            modal.addEventListener('click', (e) => {
                if (e.target === modal) { // Only if clicking the modal itself, not its children
                    closeModals();
                }
            });
        });

        // Handle deletion confirmation
        document.querySelectorAll('.delete-subject-btn, .delete-paper-btn, .delete-topic-btn, .delete-competency-btn, .delete-combination-btn').forEach(button => {
            button.addEventListener('click', (event) => {
                const itemId = event.target.dataset.id;
                let actionType = '';
                let fieldName = ''; // Dynamic field name
                let confirmMsg = translations[localStorage.getItem('selectedLanguage') || 'en'].confirmDeleteMessage;

                if (event.target.classList.contains('delete-subject-btn')) {
                    actionType = 'delete_subject';
                    fieldName = 'subject_id';
                    confirmMsg = "Are you sure you want to delete this subject and ALL its associated papers, topics, and competencies? This action cannot be undone.";
                } else if (event.target.classList.contains('delete-paper-btn')) {
                    actionType = 'delete_paper';
                    fieldName = 'paper_id';
                    confirmMsg = "Are you sure you want to delete this paper and ALL its associated topics and competencies? This action cannot be undone.";
                } else if (event.target.classList.contains('delete-topic-btn')) {
                    actionType = 'delete_topic';
                    fieldName = 'topic_id';
                    confirmMsg = "Are you sure you want to delete this topic and ALL its associated competencies? This action cannot be undone.";
                } else if (event.target.classList.contains('delete-competency-btn')) {
                    actionType = 'delete_competency';
                    fieldName = 'competency_id';
                    confirmMsg = translations[localStorage.getItem('selectedLanguage') || 'en'].confirmDeleteMessage;
                } else if (event.target.classList.contains('delete-combination-btn')) {
                    actionType = 'delete_subject_combination';
                    fieldName = 'combination_id';
                    confirmMsg = "Are you sure you want to delete this subject combination? This action cannot be undone.";
                }

                document.getElementById('confirmMessage').textContent = confirmMsg;
                document.getElementById('deleteAction').value = actionType;
                
                // Clear all delete ID fields first
                document.getElementById('deleteSubjectId').value = '';
                document.getElementById('deletePaperId').value = '';
                document.getElementById('deleteTopicId').value = '';
                document.getElementById('deleteCompetencyId').value = '';
                document.getElementById('deleteCombinationId').value = '';
                
                // Set the appropriate field based on the type
                if (fieldName === 'subject_id') {
                    document.getElementById('deleteSubjectId').value = itemId;
                } else if (fieldName === 'paper_id') {
                    document.getElementById('deletePaperId').value = itemId;
                } else if (fieldName === 'topic_id') {
                    document.getElementById('deleteTopicId').value = itemId;
                } else if (fieldName === 'competency_id') {
                    document.getElementById('deleteCompetencyId').value = itemId;
                } else if (fieldName === 'combination_id') {
                    document.getElementById('deleteCombinationId').value = itemId;
                }

                document.getElementById('confirmModal').style.display = 'flex';
                // DO NOT activate overlay - modal has its own background
                // overlay.classList.add('active');
            });
        });

        // Subject Combinations Functionality
        async function populateSubjectsChecklist() {
            const checklist = document.getElementById('subjectsChecklist');
            if (!checklist) return;

            try {
                const response = await fetch('admin_subjects.php?fetch_data=subjects');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const subjects = await response.json();

                checklist.innerHTML = ''; // Clear existing content

                subjects.forEach(subject => {
                    const label = document.createElement('label');
                    label.className = 'checkbox-label';
                    
                    const checkbox = document.createElement('input');
                    checkbox.type = 'checkbox';
                    checkbox.name = 'selected_subjects[]';
                    checkbox.value = subject.subject_id;
                    checkbox.dataset.subjectName = subject.subject_name;
                    
                    // Track selection order
                    checkbox.addEventListener('change', function(e) {
                        const subjectId = this.value;
                        const subjectName = this.dataset.subjectName;
                        
                        if (this.checked) {
                            // Add to order tracking
                            selectedSubjectsOrder.push({id: subjectId, name: subjectName});
                        } else {
                            // Remove from order tracking
                            selectedSubjectsOrder = selectedSubjectsOrder.filter(item => item.id !== subjectId);
                        }
                        
                        updateGeneratedCode();
                    });
                    
                    const text = document.createElement('span');
                    text.textContent = subject.subject_name;
                    
                    label.appendChild(checkbox);
                    label.appendChild(text);
                    checklist.appendChild(label);
                });
            } catch (error) {
                console.error('Error loading subjects for checklist:', error);
                checklist.innerHTML = '<p style="color: red;">Error loading subjects. Please try again.</p>';
            }
        }

        // Track the order of subject selection
        let selectedSubjectsOrder = [];

        function updateGeneratedCode() {
            let code = '';
            
            // Use the order tracking array to maintain selection order
            selectedSubjectsOrder.forEach(item => {
                const subjectName = item.name;
                
                // Extract subject code from name or generate from first letters
                let subjectCode = '';
                
                // Common subject mappings
                const subjectMappings = {
                    'Physics': 'P',
                    'Mathematics': 'M',
                    'Chemistry': 'C',
                    'Biology': 'B',
                    'English': 'E',
                    'History': 'H',
                    'Geography': 'G',
                    'Economics': 'EC',
                    'Business': 'BU',
                    'Computer': 'ICT',
                    'ICT': 'ICT',
                    'Art': 'A',
                    'Music': 'MU',
                    'Literature': 'L',
                    'French': 'FR',
                    'German': 'GE',
                    'Spanish': 'SP',
                    'Latin': 'LA',
                    'Religious': 'R',
                    'Christian': 'CR'
                };
                
                // Try to match exact subject name
                for (const [key, value] of Object.entries(subjectMappings)) {
                    if (subjectName.toLowerCase().includes(key.toLowerCase())) {
                        subjectCode = value;
                        break;
                    }
                }
                
                // If no match found, generate from first letters
                if (!subjectCode) {
                    const words = subjectName.split(' ');
                    subjectCode = words.map(word => word.charAt(0)).join('');
                }
                
                code += subjectCode;
            });
            
            // Update both the display and the editable field
            const generatedCodeElement = document.getElementById('generatedCode');
            const combinationCodeInput = document.getElementById('combination_code');
            
            if (generatedCodeElement) {
                generatedCodeElement.textContent = code || 'Select subjects to see suggestions';
            }
            
            // Only auto-populate if the field is empty (first time) or if user clicked "Generate from Subjects"
            if (combinationCodeInput && (!combinationCodeInput.value || combinationCodeInput.dataset.autofill === 'true')) {
                combinationCodeInput.value = code;
                combinationCodeInput.dataset.autofill = 'false';
            }
        }

        // Event listener for creating subject combinations
        document.getElementById('addSubjectCombinationBtn')?.addEventListener('click', () => {
            openCombinationModal('Create Subject Combination', 'add_subject_combination');
        });

        // Event listener for Generate from Subjects button
        document.addEventListener('click', (e) => {
            if (e.target.id === 'generateCodeBtn') {
                const combinationCodeInput = document.getElementById('combination_code');
                if (combinationCodeInput) {
                    combinationCodeInput.dataset.autofill = 'true';
                    updateGeneratedCode();
                }
            }
        });

        // Event listeners for applicable levels to auto-add General Paper
        document.addEventListener('change', (e) => {
            if (e.target.name === 'applicable_levels[]') {
                handleApplicableLevelsChange(e.target);
            }
        });

        function handleApplicableLevelsChange(changedCheckbox) {
            const applicableLevelCheckboxes = document.querySelectorAll('input[name="applicable_levels[]"]');
            const isSeniorLevel = Array.from(applicableLevelCheckboxes).some(cb => 
                (cb.value === 'S5' || cb.value === 'S6') && cb.checked
            );
            
            if (isSeniorLevel) {
                // S5 or S6 is selected, auto-add General Paper
                autoAddGeneralPaper();
            } else {
                // Remove General Paper if not senior level
                removeGeneralPaper();
            }
        }

        function autoAddGeneralPaper() {
            const checklist = document.getElementById('subjectsChecklist');
            if (!checklist) return;

            // Find General Paper checkbox
            const generalPaperCheckboxes = checklist.querySelectorAll('input[name="selected_subjects[]"]');
            let generalPaperCheckbox = null;
            
            generalPaperCheckboxes.forEach(checkbox => {
                const subjectName = checkbox.dataset.subjectName || '';
                if (subjectName.toLowerCase().includes('general paper') || 
                    (subjectName.toLowerCase().includes('general') && !subjectName.toLowerCase().includes('mathematics'))) {
                    generalPaperCheckbox = checkbox;
                }
            });

            if (generalPaperCheckbox && !generalPaperCheckbox.checked) {
                generalPaperCheckbox.checked = true;
                
                // Add to order tracking
                const subjectId = generalPaperCheckbox.value;
                const subjectName = generalPaperCheckbox.dataset.subjectName;
                
                // Add to the beginning of the array (General Paper should be first)
                selectedSubjectsOrder.unshift({id: subjectId, name: subjectName});
                
                updateGeneratedCode();
                
                // Show a subtle notification
                showAutoAddNotification();
            }
        }

        function removeGeneralPaper() {
            const checklist = document.getElementById('subjectsChecklist');
            if (!checklist) return;

            // Find General Paper checkbox
            const generalPaperCheckboxes = checklist.querySelectorAll('input[name="selected_subjects[]"]');
            
            generalPaperCheckboxes.forEach(checkbox => {
                const subjectName = checkbox.dataset.subjectName || '';
                if (subjectName.toLowerCase().includes('general paper') || 
                    (subjectName.toLowerCase().includes('general') && !subjectName.toLowerCase().includes('mathematics'))) {
                    checkbox.checked = false;
                    
                    // Remove from order tracking
                    selectedSubjectsOrder = selectedSubjectsOrder.filter(item => item.id !== checkbox.value);
                }
            });
            
            updateGeneratedCode();
        }

        function showAutoAddNotification(message) {
            // Get the translated message
            const storedLanguage = localStorage.getItem('selectedLanguage') || 'en';
            const translations = {
                en: "General Paper automatically added for S5-S6",
                sw: "General Paper imeongezwa kiotomatiki kwa S5-S6"
            };
            
            const translatedMessage = translations[storedLanguage] || translations.en;
            
            // Create a temporary notification
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: #28a745;
                color: white;
                padding: 10px 15px;
                border-radius: 5px;
                z-index: 9999;
                font-size: 14px;
                box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            `;
            notification.textContent = translatedMessage;
            
            document.body.appendChild(notification);
            
            // Remove after 3 seconds
            setTimeout(() => {
                notification.remove();
            }, 3000);
        }

        function openCombinationModal(title, action, combinationId = null, combinationName = '', combinationDescription = '', selectedSubjects = [], combinationCode = '', applicableLevels = '') {
            const modal = document.getElementById('combinationModal');
            const form = modal.querySelector('form');
            const modalTitle = document.getElementById('combinationModalTitle');

            modalTitle.textContent = title;
            form.reset();

            // Clear order tracking when opening modal
            selectedSubjectsOrder = [];

            // Set hidden action and ID fields
            document.getElementById('combinationAction').value = action;
            document.getElementById('combinationId').value = combinationId || '';

            // Set form fields
            document.getElementById('combination_name').value = combinationName || '';
            document.getElementById('combination_description').value = combinationDescription || '';
            document.getElementById('combination_code').value = combinationCode || '';

            // Set applicable levels checkboxes
            if (applicableLevels) {
                const levels = applicableLevels.split(',');
                const applicableLevelCheckboxes = document.querySelectorAll('input[name="applicable_levels[]"]');
                applicableLevelCheckboxes.forEach(checkbox => {
                    checkbox.checked = levels.includes(checkbox.value);
                });
            }

            // Populate subjects checklist
            populateSubjectsChecklist().then(() => {
                // After populating, check the selected subjects
                if (selectedSubjects.length > 0) {
                    selectedSubjects.forEach(subjectId => {
                        const checkbox = document.querySelector(`input[name="selected_subjects[]"][value="${subjectId}"]`);
                        if (checkbox) {
                            checkbox.checked = true;
                            // Add to order tracking
                            selectedSubjectsOrder.push({
                                id: subjectId, 
                                name: checkbox.dataset.subjectName
                            });
                        }
                    });
                }
                updateGeneratedCode();
            });

            modal.style.display = 'flex';
        }

        // Event listeners for editing combinations
        document.querySelectorAll('.edit-combination-btn').forEach(button => {
            button.addEventListener('click', async () => {
                const combinationName = button.dataset.name; // Use name as identifier
                const description = button.dataset.description;
                const combinationCode = button.dataset.code;
                const applicableLevels = button.dataset.levels || '';
                
                // Get the selected subjects for this combination
                try {
                    const response = await fetch('admin_subjects.php?fetch_data=subjects');
                    const subjects = await response.json();
                    
                    // Get the subjects list from the button's data-subjects attribute
                    const subjectsList = button.dataset.subjects.split(', ');
                    
                    // Find subject IDs for the selected subjects
                    const selectedSubjectIds = [];
                    subjects.forEach(subject => {
                        if (subjectsList.includes(subject.subject_name)) {
                            selectedSubjectIds.push(subject.subject_id);
                        }
                    });
                    
                    // Get the combination data by fetching combinations and finding by name
                    const comboResponse = await fetch('admin_subjects.php?fetch_data=subject_combinations');
                    const combinations = await comboResponse.json();
                    const combinationData = combinations.find(combo => combo.combination_name === combinationName);
                    const combinationId = combinationData ? combinationData.combination_id : combinationName;
                    
                    openCombinationModal('Edit Subject Combination', 'edit_subject_combination', combinationId, combinationName, description, selectedSubjectIds, combinationCode, applicableLevels);
                } catch (error) {
                    console.error('Error loading combination data:', error);
                }
            });
        });

    </script>
    <footer class="mobile-footer" id="mobileFooter">
    <nav>
        <a href="admin_dashboard.php" class="footer-item">
            <i class="fas fa-home"></i>
            <span>Home</span>
        </a>
        <a href="#subjects-section" class="footer-item active">
            <i class="fas fa-book"></i>
            <span>Subjects</span>
        </a>
        <a href="#papers-section" class="footer-item">
            <i class="fas fa-copy"></i>
            <span>Papers</span>
        </a>
        <a href="#topics-section" class="footer-item">
            <i class="fas fa-list-alt"></i>
            <span>Topics</span>
        </a>
        <button class="footer-item" id="moreButton">
            <i class="fas fa-ellipsis-h"></i>
            <span>More</span>
        </button>
    </nav>
</footer>

<div class="more-drawer" id="moreDrawer">
    <div class="drawer-header">
        <h4>Admin Menu</h4>
        <button class="close-drawer" id="closeDrawer">&times;</button>
    </div>
    <a href="admin_users.php" class="drawer-link"><i class="fas fa-users"></i> Manage Users</a>
    <a href="admin_settings.php" class="drawer-link"><i class="fas fa-cog"></i> Settings</a>
    <a href="logout.php" class="drawer-link logout-link"><i class="fas fa-sign-out-alt"></i> Logout</a>
    
</div>

<div class="drawer-overlay" id="drawerOverlay"></div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        const moreButton = document.getElementById('moreButton');
        const closeDrawer = document.getElementById('closeDrawer');
        const moreDrawer = document.getElementById('moreDrawer');
        const drawerOverlay = document.getElementById('drawerOverlay');
        const footerItems = document.querySelectorAll('.mobile-footer .footer-item');
        
        const toggleDrawer = () => {
            moreDrawer.classList.toggle('open');
            drawerOverlay.classList.toggle('visible');
        };

        moreButton.addEventListener('click', toggleDrawer);
        closeDrawer.addEventListener('click', toggleDrawer);
        drawerOverlay.addEventListener('click', toggleDrawer); // Close when clicking outside

        // Handle active state for main nav items and smooth scroll
        footerItems.forEach(item => {
            item.addEventListener('click', function(e) {
                // Ignore the 'More' button click
                if (this.id === 'moreButton') return;
                
                // Remove active class from all main items
                document.querySelectorAll('.mobile-footer .footer-item').forEach(i => i.classList.remove('active'));
                // Add active class to the clicked one
                this.classList.add('active');
                
                // Handle smooth scroll for section links
                const href = this.getAttribute('href');
                if (href && href.startsWith('#')) {
                    e.preventDefault(); 
                    const targetElement = document.querySelector(href);
                    if (targetElement) {
                        targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    }
                }
            });
        });

        // Set initial active state
        document.querySelector('a[href="#subjects-section"]').classList.add('active');
    });
</script>

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

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

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

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

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

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

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

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

</body>
</html>
