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

// --- Language Data Embedded Start ---
$all_languages = array(
    'en' => array(
        // Dashboard
        'dashboard_title' => 'Dashboard',
        'dashboard_header_title' => 'Dashboard',
        'search_placeholder' => 'Search students/data',

        // User Management
        'user_management_title' => 'User Management',
        'manage_users_roles' => 'Manage Users & Roles',
        'username_col' => 'User Name',
        'phone_number_col' => 'Phone Number',
        'current_role_col' => 'Current Role',
        'action_col' => 'Action',
        'no_users_found' => 'No users found in your school with Teacher or Admin roles.',
        'grant_admin_btn' => 'Grant Admin',
        'revoke_admin_btn' => 'Revoke Admin',
        'confirm_grant_admin' => 'Are you sure you want to grant admin role to',
        'confirm_revoke_admin' => 'Are you sure you want to revoke admin role from',
        'cannot_revoke_own_role' => 'Error: You cannot revoke your own admin role.',
        'teacher_role' => 'Teacher',
        'admin_role' => 'Admin',
        'student_role' => 'Student',
        'parent_role' => 'Parent',
        'staff_role' => 'Staff',
        'unknown_role' => 'Unknown',
        'logged_in_as' => 'Logged in as',

        // Exams specific
        'exams_title' => 'Exam Management',
        'create_new_exam' => 'Create New Exam',
        'grading_system' => 'Grading System',
        'view_grading_scales' => 'View Grading Scales',
        'exam_name' => 'Exam Name',
        'term' => 'Term',
        'year' => 'Year',
        'classes_affected' => 'Classes Affected',
        'status' => 'Status',
        'last_updated_by' => 'Last Updated By',
        'actions' => 'Actions',
        'edit' => 'Edit',
        'delete' => 'Delete',
        'view' => 'View',
        'publish' => 'Publish',
        'unpublish' => 'Unpublish',
        'exam_type' => 'Exam Type',
        'normal_exam' => 'Normal Exam',
        'consolidated_exam' => 'Consolidated Exam',
        'term_summary_exam' => 'Term Summary Exam',
        'select_exam_type' => 'Select Exam Type',
        'exam_type_description_normal' => 'Standard single exam with regular scoring',
        'exam_type_description_consolidated' => 'Combines two exams and calculates their average',
        'exam_type_description_term_summary' => 'Combines integration activities (20 marks) with normal exam (80 marks)',
        'continue' => 'Continue',
        'back' => 'Back',
        'select_first_exam' => 'Select First Exam',
        'select_second_exam' => 'Select Second Exam',
        'select_integration_activities' => 'Select Integration Activities',
        'select_normal_exam_for_summary' => 'Select Normal Exam',
        'integration_weight' => 'Integration Activities Weight (out of 20)',
        'normal_exam_weight' => 'Normal Exam Weight (out of 80)',
        'average_assessment' => 'Average Assessment',
        'average_assessment_description' => 'Combines all integration activities across subjects with entered marks',
        'publish_assessment' => 'Publish Assessment',
        'view_streams' => 'View Streams',
        'stream_name' => 'Stream Name',
        'subject_teacher' => 'Subject Teacher',
        'students_with_marks' => 'Students with Marks',
        'total_students' => 'Total Students',
        'marks_status' => 'Marks Status',
        'no_streams_found' => 'No streams found for this class',
        'subjects_marks_summary' => 'Subjects & Marks Summary',

        // Generic
        'log_out' => 'Logout',
        'profile' => 'Profile',
        'settings' => 'Settings',
        'reports' => 'Reports',
        'exams' => 'Exams',
        'attendance' => 'Attendance',
        'grades' => 'Grades',
        'enrollments' => 'Enrollments',
        'subjects' => 'Subjects',
        'sections' => 'Sections',
        'classes' => 'Classes',
        'courses' => 'Courses',
        'parents' => 'Parents',
        'staff' => 'Staff',
        'teachers' => 'Teachers',
        'students' => 'Students',
        'school_name_not_found' => 'School Name Not Found',
        'more_menu' => 'More',
    ),
    'sw' => array(
        // Dashboard
        'dashboard_title' => 'Dashibodi',
        'dashboard_header_title' => 'Dashibodi',
        'search_placeholder' => 'Tafuta wanafunzi/data',

        // User Management
        'user_management_title' => 'Usimamizi wa Watumiaji',
        'manage_users_roles' => 'Simamia Watumiaji & Majukumu',
        'username_col' => 'Jina la Mtumiaji',
        'phone_number_col' => 'Namba ya Simu',
        'current_role_col' => 'Jukumu la Sasa',
        'action_col' => 'Kitendo',
        'no_users_found' => 'Hakuna watumiaji waliopatikana shuleni kwako wenye majukumu ya Mwalimu au Msimamizi.',
        'grant_admin_btn' => 'Mpe Usimamizi',
        'revoke_admin_btn' => 'Ondoa Usimamizi',
        'confirm_grant_admin' => 'Una uhakika unataka kumpa jukumu la msimamizi kwa',
        'confirm_revoke_admin' => 'Una uhakika unataka kumuondolea jukumu la msimamizi',
        'cannot_revoke_own_role' => 'Kosa: Huwezi kujiondolea jukumu lako la msimamizi.',
        'teacher_role' => 'Mwalimu',
        'admin_role' => 'Msimamizi',
        'student_role' => 'Mwanafunzi',
        'parent_role' => 'Mzazi',
        'staff_role' => 'Wafanyakazi',
        'unknown_role' => 'Haijulikani',
        'logged_in_as' => 'Umeingia kama',

        // Exams specific
        'exams_title' => 'Usimamizi wa Mitihani',
        'create_new_exam' => 'Unda Mtihani Mpya',
        'grading_system' => 'Mfumo wa Alama',
        'view_grading_scales' => 'Ona Vipimo vya Alama',
        'exam_name' => 'Jina la Mtihani',
        'term' => 'Muhula',
        'year' => 'Mwaka',
        'classes_affected' => 'Madarasa Yaliyoathiriwa',
        'status' => 'Hali',
        'last_updated_by' => 'Ilibadilishwa Mwisho na',
        'actions' => 'Vitendo',
        'edit' => 'Hariri',
        'delete' => 'Futa',
        'view' => 'Ona',
        'publish' => 'Chapisha',
        'unpublish' => 'Ondoa Uchapishaji',
        'exam_type' => 'Aina ya Mtihani',
        'normal_exam' => 'Mtihani wa Kawaida',
        'consolidated_exam' => 'Mtihani wa Pamoja',
        'term_summary_exam' => 'Muhtasari wa Muhula',
        'select_exam_type' => 'Chagua Aina ya Mtihani',
        'exam_type_description_normal' => 'Mtihani wa kawaida wenye alama za kawaida',
        'exam_type_description_consolidated' => 'Unachanganya mitihani miwili na kuhesabu wastani wao',
        'exam_type_description_term_summary' => 'Unachanganya shughuli za ujumuishaji (alama 20) na mtihani wa kawaida (alama 80)',
        'continue' => 'Endelea',
        'back' => 'Rudi',
        'select_first_exam' => 'Chagua Mtihani wa Kwanza',
        'select_second_exam' => 'Chagua Mtihani wa Pili',
        'select_integration_activities' => 'Chagua Shughuli za Ujumuishaji',
        'select_normal_exam_for_summary' => 'Chagua Mtihani wa Kawaida',
        'integration_weight' => 'Uzito wa Shughuli za Ujumuishaji (kati ya 20)',
        'normal_exam_weight' => 'Uzito wa Mtihani wa Kawaida (kati ya 80)',
        'average_assessment' => 'Tathmini ya Wastani',
        'average_assessment_description' => 'Unachanganya shughuli zote za ujumuishaji katika masomo yenye alama zilizoingizwa',
        'publish_assessment' => 'Chapisha Tathmini',
        'view_streams' => 'Ona Mikondo',
        'stream_name' => 'Jina la Mkondo',
        'subject_teacher' => 'Mwalimu wa Somo',
        'students_with_marks' => 'Wanafunzi wenye Alama',
        'total_students' => 'Jumla ya Wanafunzi',
        'marks_status' => 'Hali ya Alama',
        'no_streams_found' => 'Hakuna mikondo iliyopatikana kwa darasa hili',
        'subjects_marks_summary' => 'Muhtasari wa Masomo na Alama',

        // Generic
        'log_out' => 'Toka',
        'profile' => 'Wasifu',
        'settings' => 'Mipangilio',
        'reports' => 'Ripoti',
        'exams' => 'Mitihani',
        'attendance' => 'Mahudhurio',
        'grades' => 'Alama',
        'enrollments' => 'Uandikishaji',
        'subjects' => 'Masomo',
        'sections' => 'Sehemu',
        'classes' => 'Madarasa',
        'courses' => 'Kozi',
        'parents' => 'Wazazi',
        'staff' => 'Wafanyakazi',
        'teachers' => 'Walimu',
        'students' => 'Wanafunzi',
        'school_name_not_found' => 'Jina la Shule Halikupatikana',
        'more_menu' => 'Zaidi',
    ),
    'lg' => array(
        // Dashboard
        'dashboard_title' => 'Akatuuti',
        'dashboard_header_title' => 'Akatuuti',
        'search_placeholder' => 'Noonya abayizi/data',

        // User Management
        'user_management_title' => 'Okuwaddebeba abakozesa',
        'manage_users_roles' => 'Kuwanika Abakozesa & Ebifo byabwe',
        'username_col' => 'Erinnya ly\'Omukozi',
        'phone_number_col' => 'Namba y\'essimu',
        'current_role_col' => 'Ekifo ekiriko',
        'action_col' => 'Ekikolebwa',
        'no_users_found' => 'Tewali bakozesa basangiddwa mu ssomero lyo abalina ebifo bya Mukuza oba Omuddukanya.',
        'grant_admin_btn' => 'Muwe Obuddukanya',
        'revoke_admin_btn' => 'Muggyako Obuddukanya',
        'confirm_grant_admin' => 'Oli mukakasa nti oyagala okuwa obuddukanya',
        'confirm_revoke_admin' => 'Oli mukakasa nti oyagala okuggyako obuddukanya eri',
        'cannot_revoke_own_role' => 'Ensobi: Tosobola kweggyako kifo kyo eky\'obuddukanya.',
        'teacher_role' => 'Mukuza',
        'admin_role' => 'Omuddukanya',
        'student_role' => 'Omuyizi',
        'parent_role' => 'Mzaddikira',
        'staff_role' => 'Abakozi',
        'unknown_role' => 'Tekimanyiddwa',
        'logged_in_as' => 'Wali oyinze nga',

        // Exams specific
        'exams_title' => 'Okudukanya Ebizannyo',
        'create_new_exam' => 'Tondawo Ekizannyo Ekipya',
        'grading_system' => 'Enkola y\'Ebitongole',
        'view_grading_scales' => 'Laba Emipimo gy\'Ebitongole',
        'exam_name' => 'Erinnya ly\'Ekizannyo',
        'term' => 'Ekiseera',
        'year' => 'Omwaka',
        'classes_affected' => 'Amakirasi Agakoseddwa',
        'status' => 'Embeera',
        'last_updated_by' => 'Yakyusibwa mu nkomerero',
        'actions' => 'Ebikolwa',
        'edit' => 'Kyusa',
        'delete' => 'Sazaamu',
        'view' => 'Laba',
        'publish' => 'Sindika',
        'unpublish' => 'Koma okusindika',
        'exam_type' => 'Ekika ky\'Ekizannyo',
        'normal_exam' => 'Ekizannyo Ekya Bulijjo',
        'consolidated_exam' => 'Ekizannyo Ekigatiddwa',
        'term_summary_exam' => 'Okutikkira kw\'Ekiseera',
        'select_exam_type' => 'Londa Ekika ky\'Ekizannyo',
        'exam_type_description_normal' => 'Ekizannyo ekya bulijjo ekirina ebitongole ebya bulijjo',
        'exam_type_description_consolidated' => 'Kigatta ebizannyo bibiri ne kikozesa wastani waabyo',
        'exam_type_description_term_summary' => 'Kigatta ebikolwa by\'okugatta (obutongole 20) n\'ekizannyo ekya bulijjo (obutongole 80)',
        'continue' => 'Genda mu maaso',
        'back' => 'Ddayo',
        'select_first_exam' => 'Londa Ekizannyo Eky\'okubanza',
        'select_second_exam' => 'Londa Ekizannyo Eky\'okubiri',
        'select_integration_activities' => 'Londa Ebikolwa by\'Okugatta',
        'select_normal_exam_for_summary' => 'Londa Ekizannyo Ekya Bulijjo',
        'integration_weight' => 'Obuzito bw\'Ebikolwa by\'Okugatta (ku 20)',
        'normal_exam_weight' => 'Obuzito bw\'Ekizannyo Ekya Bulijjo (ku 80)',
        'average_assessment' => 'Okukebera kw\'Omutindo',
        'average_assessment_description' => 'Kugatta ebikolwa byonna by\'okugatta mu masomo agalina ebitongole ebyayingiziddwa',
        'publish_assessment' => 'Sindika Okukebera',
        'view_streams' => 'Laba Emigga',
        'stream_name' => 'Erinnya ly\'Omugga',
        'subject_teacher' => 'Mukuza w\'Essomo',
        'students_with_marks' => 'Abayizi abalina Ebitongole',
        'total_students' => 'Obuwumbi bw\'Abayizi',
        'marks_status' => 'Embeera y\'Ebitongole',
        'no_streams_found' => 'Tewali migga egisangiddwa mu kikirasa kino',
        'subjects_marks_summary' => 'Okutondawo kw\'Amasomo n\'Ebitongole',

        // Generic
        'log_out' => 'Ggalawo',
        'profile' => 'Embeera yo',
        'settings' => 'Enteekateeka',
        'reports' => 'Lipooti',
        'exams' => 'Ebizannyo',
        'attendance' => 'Okujjukira',
        'grades' => 'Ebitongole',
        'enrollments' => 'Okuyingira',
        'subjects' => 'Ebisomo',
        'sections' => 'Ebitundu',
        'classes' => 'Amakirasi',
        'courses' => 'Essomo',
        'parents' => 'Abazaddikira',
        'staff' => 'Abakozi',
        'teachers' => 'Abasukira',
        'students' => 'Abayizi',
        'school_name_not_found' => 'Erinnya ly\'essomero terisangiddwa',
        'more_menu' => 'Ebirala',
    )
);
// --- Language Data Embedded End ---

// --- Language Selection Logic Start ---
// Default language
$current_lang = 'en';

// Check if a language is set in the session
if (isset($_SESSION['lang'])) {
    $current_lang = $_SESSION['lang'];
}

// Check if a language is requested via GET parameter and is supported
if (isset($_GET['lang']) && array_key_exists($_GET['lang'], $all_languages)) {
    $current_lang = $_GET['lang'];
    $_SESSION['lang'] = $current_lang; // Store in session
}

// Set the $lang array to the currently selected language
$lang = $all_languages[$current_lang];
// --- Language Selection Logic End ---

// Define role constants
if (!defined('ROLE_SUPER_ADMIN')) { define('ROLE_SUPER_ADMIN', 1); }
if (!defined('ROLE_ADMIN')) { define('ROLE_ADMIN', 2); }
if (!defined('ROLE_TEACHER')) { define('ROLE_TEACHER', 3); }
if (!defined('ROLE_STUDENT')) { define('ROLE_STUDENT', 4); }
if (!defined('ROLE_PARENT')) { define('ROLE_PARENT', 5); }
if (!defined('ROLE_STAFF')) { define('ROLE_STAFF', 6); }

// Function to check user role and redirect if unauthorized
function check_role_access($required_role_code) {
    global $lang;
    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);

// User is authorized, fetch additional details for display
$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]);
$user_role_code = $_SESSION["role"];
$current_user_school_id = $_SESSION["school_id"];
$phone_number = $photo = $status = "";

// Initialize school variables
$school_name = $lang['school_name_not_found'];
$school_name_for_js = $lang['school_name_not_found'];
$school_logo_path = "images/default_school_logo.png";

// Initialize message variables
$message = '';
$message_type = '';

// Database connection (assuming $conn is established via config.php)
if (!isset($conn)) {
    die("Database connection not established. Check config.php.");
}

// Ensure school_id is available
if (!$current_user_school_id) {
    die("School ID not found in session. Please log in again.");
}

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

    // Fetch School Name and Logo
    $sql_school = "SELECT school_name, logo FROM schools WHERE school_id = ?";
    if ($stmt_school = $conn->prepare($sql_school)) {
        $stmt_school->bind_param("i", $current_user_school_id);
        if ($stmt_school->execute()) {
            $stmt_school->bind_result($school_name_db, $school_logo_db);
            if ($stmt_school->fetch()) {
                // Decode the school name if it's URL encoded
                $decoded_school_name = urldecode($school_name_db);
                // Also try decoding HTML entities if present
                $decoded_school_name = html_entity_decode($decoded_school_name, ENT_QUOTES, 'UTF-8');
                
                // Store the clean decoded name (don't re-encode here)
                $school_name = $decoded_school_name;
                $school_name_for_js = addslashes($decoded_school_name);
                $school_logo_path = !empty($school_logo_db) ? htmlspecialchars($school_logo_db) : 'images/default_school_logo.png';
                if (!file_exists($school_logo_path) || is_dir($school_logo_path)) {
                    $school_logo_path = 'images/default_school_logo.png';
                }
            }
        }
        $stmt_school->close();
    }
}

// --- Fetch Master Data (Academic Years, Terms, Classes, and Subjects) ---

// Fetch Academic Years (distinct from academic_years_terms table)
$academic_years_from_db = [];
$stmt = $conn->prepare("SELECT DISTINCT academic_year FROM academic_years_terms WHERE school_id = ? ORDER BY academic_year DESC");
$stmt->bind_param("i", $current_user_school_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $academic_years_from_db[] = $row['academic_year'];
}
$stmt->close();

// Fetch Terms (distinct from academic_years_terms table)
$terms_from_db = [];
$stmt = $conn->prepare("SELECT DISTINCT term_name FROM academic_years_terms WHERE school_id = ? ORDER BY term_name ASC");
$stmt->bind_param("i", $current_user_school_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $terms_from_db[] = $row['term_name'];
}
$stmt->close();

// Fetch all Classes for the current school
$all_classes = [];
$stmt = $conn->prepare("SELECT class_id, class_name FROM classes WHERE school_id = ? ORDER BY class_name ASC");
$stmt->bind_param("i", $current_user_school_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $all_classes[] = $row;
}
$stmt->close();

// Fetch all Subjects for the current school
$all_subjects = [];
$stmt = $conn->prepare("SELECT subject_id, subject_name FROM subjects WHERE school_id = ? ORDER BY subject_name ASC");
$stmt->bind_param("i", $current_user_school_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $all_subjects[] = $row;
}
$stmt->close();

// Fetch all Streams for the current school (needed for "View" modal)
$all_streams = [];
$stmt = $conn->prepare("SELECT stream_id, stream_name, class_id FROM streams WHERE school_id = ? ORDER BY stream_name ASC");
$stmt->bind_param("i", $current_user_school_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $all_streams[] = $row;
}
$stmt->close();

// --- Handle API GET requests (for grading scales data) ---
if (isset($_GET['action']) && $_GET['action'] === 'get_grading_scales_data') {
    $filter_grade_academic_year = $_GET['academic_year'] ?? '';
    $filter_grade_term = $_GET['term'] ?? '';
    $filter_grade_class_id = intval($_GET['class_id'] ?? 0);
    $filter_grade_subject_id = intval($_GET['subject_id'] ?? 0);

    $grading_scales_data = [];
    $sql_grading_scales = "
        SELECT gs.*, u.username AS created_by_username, u2.username AS updated_by_username,
               c.class_name, s.subject_name
        FROM grading_scales gs
        LEFT JOIN users u ON gs.created_by = u.id
        LEFT JOIN users u2 ON gs.updated_by = u2.id
        LEFT JOIN classes c ON gs.class_id = c.class_id
        LEFT JOIN subjects s ON gs.subject_id = s.subject_id
        WHERE gs.school_id = ?
    ";
    $params_grading_scales = [$current_user_school_id];
    $types_grading_scales = 'i';

    // Academic Year Filter
    if (!empty($filter_grade_academic_year)) {
        $sql_grading_scales .= " AND gs.academic_year = ?";
        $params_grading_scales[] = $filter_grade_academic_year;
        $types_grading_scales .= 's';
    } else {
        $sql_grading_scales .= " AND (gs.academic_year IS NULL OR gs.academic_year IS NOT NULL)";
    }

    // Term Filter
    if (!empty($filter_grade_term)) {
        $sql_grading_scales .= " AND gs.term_name = ?";
        $params_grading_scales[] = $filter_grade_term;
        $types_grading_scales .= 's';
    } else {
        $sql_grading_scales .= " AND (gs.term_name IS NULL OR gs.term_name IS NOT NULL)";
    }

    // Class ID Filter
    if ($filter_grade_class_id > 0) {
        $sql_grading_scales .= " AND gs.class_id = ?";
        $params_grading_scales[] = $filter_grade_class_id;
        $types_grading_scales .= 'i';
    } else {
        $sql_grading_scales .= " AND (gs.class_id = 0 OR gs.class_id > 0)";
    }

    // Subject ID Filter
    if ($filter_grade_subject_id > 0) {
        $sql_grading_scales .= " AND gs.subject_id = ?";
        $params_grading_scales[] = $filter_grade_subject_id;
        $types_grading_scales .= 'i';
    } else {
        $sql_grading_scales .= " AND (gs.subject_id = 0 OR gs.subject_id > 0)";
    }

    $sql_grading_scales .= " ORDER BY gs.academic_year DESC, gs.term_name ASC, gs.grade_name ASC, gs.min_score DESC";

    $stmt_grading_scales = $conn->prepare($sql_grading_scales);
    if ($stmt_grading_scales === false) {
        echo json_encode(['success' => false, 'message' => 'Database error preparing grading scales statement: ' . $conn->error]);
        exit();
    }

    if (!empty($params_grading_scales)) {
        $bind_params_args = array($types_grading_scales);
        for ($i = 0; $i < count($params_grading_scales); $i++) {
            $bind_params_args[] = &$params_grading_scales[$i];
        }
        call_user_func_array([$stmt_grading_scales, 'bind_param'], $bind_params_args);
    }

    $stmt_grading_scales->execute();
    $result_grading_scales = $stmt_grading_scales->get_result();
    while ($row = $result_grading_scales->fetch_assoc()) {
        $grading_scales_data[] = $row;
    }
    $stmt_grading_scales->close();

    echo json_encode(['success' => true, 'data' => $grading_scales_data]);
    exit();
}

// --- Handle API GET requests (for single grading scale) ---
if (isset($_GET['action']) && $_GET['action'] === 'get_grading_scale') {
    $grading_scale_id = intval($_GET['id'] ?? 0);
    
    if ($grading_scale_id === 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid grading scale ID']);
        exit();
    }

    $sql_grading_scale = "
        SELECT gs.*, u.username AS created_by_username, u2.username AS updated_by_username,
               c.class_name, s.subject_name
        FROM grading_scales gs
        LEFT JOIN users u ON gs.created_by = u.id
        LEFT JOIN users u2 ON gs.updated_by = u2.id
        LEFT JOIN classes c ON gs.class_id = c.class_id
        LEFT JOIN subjects s ON gs.subject_id = s.subject_id
        WHERE gs.id = ? AND gs.school_id = ?
    ";
    
    $stmt = $conn->prepare($sql_grading_scale);
    if ($stmt === false) {
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
        exit();
    }
    
    $stmt->bind_param("ii", $grading_scale_id, $current_user_school_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        echo json_encode(['success' => true, 'data' => $row]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Grading scale not found']);
    }
    
    $stmt->close();
    exit();
}

// --- Handle API GET requests (for stream assessment details) ---
if (isset($_GET['action']) && $_GET['action'] === 'get_stream_assessment_details') {
    $stream_id = intval($_GET['stream_id'] ?? 0);
    $class_id = intval($_GET['class_id'] ?? 0);
    $exam_id = intval($_GET['exam_id'] ?? 0);

    if ($stream_id === 0 || $class_id === 0 || $exam_id === 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
        exit();
    }

    try {
        // Get subjects for this exam
        $subjects_data = [];
        $sql_subjects = "
            SELECT DISTINCT 
                s.subject_id,
                s.subject_name,
                c.class_name,
                u.username AS teacher_name,
                (SELECT COUNT(DISTINCT iam.student_id) 
                 FROM integration_activity_marks iam 
                 INNER JOIN assignments a ON iam.activity_id = a.assignment_id 
                 WHERE iam.subject_id = s.subject_id 
                   AND iam.stream_id = ? 
                   AND iam.school_id = ?
                ) AS students_with_marks,
                (SELECT COUNT(DISTINCT se.user_id) 
                 FROM student_enrollment se 
                 WHERE se.class_id = ? 
                   AND se.stream_id = ?
                ) AS total_students
            FROM exam_subjects es
            INNER JOIN subjects s ON es.subject_id = s.subject_id
            INNER JOIN classes c ON c.class_id = ?
            LEFT JOIN class_subject_teachers cst ON cst.subject_id = s.subject_id 
                AND cst.class_id = ? 
                AND cst.stream_id = ? 
                AND cst.school_id = ?
            LEFT JOIN users u ON cst.teacher_user_id = u.id
            WHERE es.exam_id = ? 
              AND s.school_id = ?
            ORDER BY s.subject_name ASC
        ";
        
        $stmt_subjects = $conn->prepare($sql_subjects);
        if ($stmt_subjects === false) {
            echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
            exit();
        }
        
        $stmt_subjects->bind_param("iiiiiiiiii", 
            $stream_id, $current_user_school_id, 
            $class_id, $stream_id, 
            $class_id, $class_id, $stream_id, $current_user_school_id,
            $exam_id, $current_user_school_id
        );
        
        $stmt_subjects->execute();
        $result_subjects = $stmt_subjects->get_result();
        
        while ($row = $result_subjects->fetch_assoc()) {
            $subjects_data[] = [
                'subject_id' => $row['subject_id'],
                'subject_name' => $row['subject_name'],
                'class_name' => $row['class_name'],
                'teacher_name' => $row['teacher_name'],
                'students_with_marks' => intval($row['students_with_marks']),
                'total_students' => intval($row['total_students'])
            ];
        }
        
        $stmt_subjects->close();
        
        echo json_encode(['success' => true, 'subjects' => $subjects_data]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
    
    exit();
}

// --- Exam Management Logic ---

// Handle form submissions for creating, editing, deleting exams, etc.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    switch ($action) {
        case 'create_normal_exam':
            $exam_name = trim($_POST['exam_name']);
            $term = $_POST['term'];
            $year = $_POST['year'];
            $selected_classes = $_POST['classes'] ?? [];
            $selected_subjects = $_POST['subjects'] ?? [];
            $exam_type = 'Normal';

            if (empty($exam_name) || empty($term) || empty($year) || empty($selected_classes) || empty($selected_subjects)) {
                $message = "Please fill all required fields and select at least one class and one subject.";
                $message_type = "error";
            } else {
                $conn->begin_transaction();
                try {
                    $stmt = $conn->prepare("INSERT INTO exams (school_id, exam_name, term, year, exam_type, status, updated_by, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                    $exam_status = 'Draft';
                    $stmt->bind_param("isssisii", $current_user_school_id, $exam_name, $term, $year, $exam_type, $exam_status, $user_id, $user_id);
                    $stmt->execute();
                    $exam_id = $conn->insert_id;
                    $stmt->close();

                    $stmt_classes = $conn->prepare("INSERT INTO exam_classes (exam_id, class_id) VALUES (?, ?)");
                    foreach ($selected_classes as $class_id) {
                        $stmt_classes->bind_param("ii", $exam_id, $class_id);
                        $stmt_classes->execute();
                    }
                    $stmt_classes->close();

                    $stmt_subjects = $conn->prepare("INSERT INTO exam_subjects (exam_id, subject_id) VALUES (?, ?)");
                    foreach ($selected_subjects as $subject_id) {
                        $stmt_subjects->bind_param("ii", $exam_id, $subject_id);
                        $stmt_subjects->execute();
                    }
                    $stmt_subjects->close();

                    // AUTO-ADD COMBINATION SUBJECTS for Senior 5/6 students
                    // This ensures all subjects required by student combinations are available in the exam
                    $stmt_combo_subjects = $conn->prepare("
                        INSERT IGNORE INTO exam_subjects (exam_id, subject_id, status) 
                        SELECT ?, cs.subject_id, 'Draft'
                        FROM combination_subjects cs
                        INNER JOIN subject_combinations sc ON cs.combination_id = sc.combination_id
                        WHERE sc.school_id = ?
                    ");
                    $stmt_combo_subjects->bind_param("ii", $exam_id, $current_user_school_id);
                    $stmt_combo_subjects->execute();
                    $stmt_combo_subjects->close();

                    $conn->commit();
                    $message = "Exam '{$exam_name}' created successfully!";
                    $message_type = "success";
                    
                    // Redirect to refresh the page and show the new exam
                    header("Location: admin_exams.php?message=" . urlencode($message) . "&message_type=" . $message_type);
                    exit();
                } catch (mysqli_sql_exception $e) {
                    $conn->rollback();
                    if ($e->getCode() == 1062) {
                        $message = "Error creating exam: An exam with this name already exists for this term/year or a class/subject link already exists.";
                    } else {
                        $message = "Error creating exam: " . $e->getMessage();
                    }
                    $message_type = "error";
                }
            }
            break;

        case 'create_consolidated_exam':
            $exam_name = trim($_POST['exam_name']);
            $term = $_POST['term'];
            $year = $_POST['year'];
            $first_exam_id = intval($_POST['first_exam_id']);
            $second_exam_id = intval($_POST['second_exam_id']);
            $exam_type = 'Consolidated';

            if (empty($exam_name) || empty($term) || empty($year) || $first_exam_id === 0 || $second_exam_id === 0) {
                $message = "Please fill all required fields and select both exams for consolidation.";
                $message_type = "error";
            } elseif ($first_exam_id === $second_exam_id) {
                $message = "Please select two different exams for consolidation.";
                $message_type = "error";
            } else {
                $conn->begin_transaction();
                try {
                    // Create the consolidated exam
                    $stmt = $conn->prepare("INSERT INTO exams (school_id, exam_name, term, year, exam_type, status, updated_by, created_by, first_exam_id, second_exam_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $exam_status = 'Draft';
                    $stmt->bind_param("isssisiiii", $current_user_school_id, $exam_name, $term, $year, $exam_type, $exam_status, $user_id, $user_id, $first_exam_id, $second_exam_id);
                    $stmt->execute();
                    $exam_id = $conn->insert_id;
                    $stmt->close();

                    // Copy classes and subjects from the first exam
                    $stmt_copy_classes = $conn->prepare("INSERT INTO exam_classes (exam_id, class_id) SELECT ?, class_id FROM exam_classes WHERE exam_id = ?");
                    $stmt_copy_classes->bind_param("ii", $exam_id, $first_exam_id);
                    $stmt_copy_classes->execute();
                    $stmt_copy_classes->close();

                    $stmt_copy_subjects = $conn->prepare("INSERT INTO exam_subjects (exam_id, subject_id) SELECT ?, subject_id FROM exam_subjects WHERE exam_id = ?");
                    $stmt_copy_subjects->bind_param("ii", $exam_id, $first_exam_id);
                    $stmt_copy_subjects->execute();
                    $stmt_copy_subjects->close();

                    // AUTO-ADD COMBINATION SUBJECTS for Senior 5/6 students
                    $stmt_combo_subjects = $conn->prepare("
                        INSERT IGNORE INTO exam_subjects (exam_id, subject_id, status) 
                        SELECT ?, cs.subject_id, 'Draft'
                        FROM combination_subjects cs
                        INNER JOIN subject_combinations sc ON cs.combination_id = sc.combination_id
                        WHERE sc.school_id = ?
                    ");
                    $stmt_combo_subjects->bind_param("ii", $exam_id, $current_user_school_id);
                    $stmt_combo_subjects->execute();
                    $stmt_combo_subjects->close();

                    $conn->commit();
                    $message = "Consolidated exam '{$exam_name}' created successfully!";
                    $message_type = "success";
                } catch (mysqli_sql_exception $e) {
                    $conn->rollback();
                    $message = "Error creating consolidated exam: " . $e->getMessage();
                    $message_type = "error";
                }
            }
            break;

        case 'create_term_summary_exam':
            $exam_name = trim($_POST['exam_name']);
            $term = $_POST['term'];
            $year = $_POST['year'];
            $integration_exam_id = intval($_POST['integration_exam_id']);
            $normal_exam_id = intval($_POST['normal_exam_id']);
            $integration_weight = floatval($_POST['integration_weight'] ?? 20);
            $normal_weight = floatval($_POST['normal_weight'] ?? 80);
            $exam_type = 'Term Summary';

            if (empty($exam_name) || empty($term) || empty($year) || $integration_exam_id === 0 || $normal_exam_id === 0) {
                $message = "Please fill all required fields and select both integration activities and normal exam.";
                $message_type = "error";
            } elseif ($integration_exam_id === $normal_exam_id) {
                $message = "Please select different exams for integration activities and normal exam.";
                $message_type = "error";
            } else {
                $conn->begin_transaction();
                try {
                    // Create the term summary exam
                    $stmt = $conn->prepare("INSERT INTO exams (school_id, exam_name, term, year, exam_type, status, updated_by, created_by, integration_exam_id, normal_exam_id, integration_weight, normal_weight) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $exam_status = 'Draft';
                    $stmt->bind_param("isssisiiiidd", $current_user_school_id, $exam_name, $term, $year, $exam_type, $exam_status, $user_id, $user_id, $integration_exam_id, $normal_exam_id, $integration_weight, $normal_weight);
                    $stmt->execute();
                    $exam_id = $conn->insert_id;
                    $stmt->close();

                    // Copy classes and subjects from the normal exam
                    $stmt_copy_classes = $conn->prepare("INSERT INTO exam_classes (exam_id, class_id) SELECT ?, class_id FROM exam_classes WHERE exam_id = ?");
                    $stmt_copy_classes->bind_param("ii", $exam_id, $normal_exam_id);
                    $stmt_copy_classes->execute();
                    $stmt_copy_classes->close();

                    $stmt_copy_subjects = $conn->prepare("INSERT INTO exam_subjects (exam_id, subject_id) SELECT ?, subject_id FROM exam_subjects WHERE exam_id = ?");
                    $stmt_copy_subjects->bind_param("ii", $exam_id, $normal_exam_id);
                    $stmt_copy_subjects->execute();
                    $stmt_copy_subjects->close();

                    // AUTO-ADD COMBINATION SUBJECTS for Senior 5/6 students
                    $stmt_combo_subjects = $conn->prepare("
                        INSERT IGNORE INTO exam_subjects (exam_id, subject_id, status) 
                        SELECT ?, cs.subject_id, 'Draft'
                        FROM combination_subjects cs
                        INNER JOIN subject_combinations sc ON cs.combination_id = sc.combination_id
                        WHERE sc.school_id = ?
                    ");
                    $stmt_combo_subjects->bind_param("ii", $exam_id, $current_user_school_id);
                    $stmt_combo_subjects->execute();
                    $stmt_combo_subjects->close();

                    $conn->commit();
                    $message = "Term summary exam '{$exam_name}' created successfully!";
                    $message_type = "success";
                } catch (mysqli_sql_exception $e) {
                    $conn->rollback();
                    $message = "Error creating term summary exam: " . $e->getMessage();
                    $message_type = "error";
                }
            }
            break;

        case 'create_average_assessment':
            $exam_name = trim($_POST['exam_name']);
            $term = $_POST['term'];
            $year = $_POST['year'];
            $selected_classes = $_POST['classes'] ?? [];
            $exam_type = 'Average Assessment';

            if (empty($exam_name) || empty($term) || empty($year) || empty($selected_classes)) {
                $message = "Please fill all required fields and select at least one class.";
                $message_type = "error";
            } else {
                $conn->begin_transaction();
                try {
                    $stmt = $conn->prepare("INSERT INTO exams (school_id, exam_name, term, year, exam_type, status, updated_by, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                    $exam_status = 'Draft';
                    $stmt->bind_param("isssisii", $current_user_school_id, $exam_name, $term, $year, $exam_type, $exam_status, $user_id, $user_id);
                    $stmt->execute();
                    $exam_id = $conn->insert_id;
                    $stmt->close();

                    $stmt_classes = $conn->prepare("INSERT INTO exam_classes (exam_id, class_id) VALUES (?, ?)");
                    foreach ($selected_classes as $class_id) {
                        $stmt_classes->bind_param("ii", $exam_id, $class_id);
                        $stmt_classes->execute();
                    }
                    $stmt_classes->close();

                    // For average assessment, we need to copy all subjects that have integration activities
                    $stmt_subjects = $conn->prepare("
                        INSERT INTO exam_subjects (exam_id, subject_id) 
                        SELECT DISTINCT ?, iam.subject_id 
                        FROM integration_activity_marks iam 
                        INNER JOIN assignments a ON iam.activity_id = a.assignment_id 
                        WHERE iam.school_id = ? AND iam.academic_year = ? AND iam.term = ?
                    ");
                    $stmt_subjects->bind_param("iiss", $exam_id, $current_user_school_id, $year, $term);
                    $stmt_subjects->execute();
                    $stmt_subjects->close();

                    // AUTO-ADD COMBINATION SUBJECTS for Senior 5/6 students
                    $stmt_combo_subjects = $conn->prepare("
                        INSERT IGNORE INTO exam_subjects (exam_id, subject_id, status) 
                        SELECT ?, cs.subject_id, 'Draft'
                        FROM combination_subjects cs
                        INNER JOIN subject_combinations sc ON cs.combination_id = sc.combination_id
                        WHERE sc.school_id = ?
                    ");
                    $stmt_combo_subjects->bind_param("ii", $exam_id, $current_user_school_id);
                    $stmt_combo_subjects->execute();
                    $stmt_combo_subjects->close();

                    $conn->commit();
                    $message = "Average Assessment '{$exam_name}' created successfully!";
                    $message_type = "success";
                } catch (mysqli_sql_exception $e) {
                    $conn->rollback();
                    $message = "Error creating average assessment: " . $e->getMessage();
                    $message_type = "error";
                }
            }
            break;

        case 'edit_exam':
            $exam_id = $_POST['exam_id'];
            $exam_name = trim($_POST['exam_name']);
            $term = $_POST['term'];
            $year = $_POST['year'];
            $selected_classes = $_POST['classes'] ?? [];
            $selected_subjects = $_POST['subjects'] ?? [];

            if (empty($exam_name) || empty($term) || empty($year) || empty($selected_classes) || empty($selected_subjects)) {
                $message = "Please fill all required fields and select at least one class and one subject.";
                $message_type = "error";
            } else {
                $conn->begin_transaction();
                try {
                    $stmt = $conn->prepare("UPDATE exams SET exam_name = ?, term = ?, year = ?, updated_by = ?, updated_at = NOW() WHERE exam_id = ? AND school_id = ?");
                    $stmt->bind_param("sssiii", $exam_name, $term, $year, $user_id, $exam_id, $current_user_school_id);
                    $stmt->execute();
                    $stmt->close();

                    $stmt_delete_classes = $conn->prepare("DELETE FROM exam_classes WHERE exam_id = ?");
                    $stmt_delete_classes->bind_param("i", $exam_id);
                    $stmt_delete_classes->execute();
                    $stmt_delete_classes->close();

                    $stmt_insert_classes = $conn->prepare("INSERT INTO exam_classes (exam_id, class_id) VALUES (?, ?)");
                    foreach ($selected_classes as $class_id) {
                        $stmt_insert_classes->bind_param("ii", $exam_id, $class_id);
                        $stmt_insert_classes->execute();
                    }
                    $stmt_insert_classes->close();

                    $stmt_delete_subjects = $conn->prepare("DELETE FROM exam_subjects WHERE exam_id = ?");
                    $stmt_delete_subjects->bind_param("i", $exam_id);
                    $stmt_delete_subjects->execute();
                    $stmt_delete_subjects->close();

                    $stmt_insert_subjects = $conn->prepare("INSERT INTO exam_subjects (exam_id, subject_id) VALUES (?, ?)");
                    foreach ($selected_subjects as $subject_id) {
                        $stmt_insert_subjects->bind_param("ii", $exam_id, $subject_id);
                        $stmt_insert_subjects->execute();
                    }
                    $stmt_insert_subjects->close();

                    // AUTO-ADD COMBINATION SUBJECTS for Senior 5/6 students
                    $stmt_combo_subjects = $conn->prepare("
                        INSERT IGNORE INTO exam_subjects (exam_id, subject_id, status) 
                        SELECT ?, cs.subject_id, 'Draft'
                        FROM combination_subjects cs
                        INNER JOIN subject_combinations sc ON cs.combination_id = sc.combination_id
                        WHERE sc.school_id = ?
                    ");
                    $stmt_combo_subjects->bind_param("ii", $exam_id, $current_user_school_id);
                    $stmt_combo_subjects->execute();
                    $stmt_combo_subjects->close();

                    $conn->commit();
                    $message = "Exam '{$exam_name}' updated successfully!";
                    $message_type = "success";
                    
                    // Redirect to refresh the page and show updated exam
                    header("Location: admin_exams.php?message=" . urlencode($message) . "&message_type=" . $message_type);
                    exit();
                } catch (mysqli_sql_exception $e) {
                    $conn->rollback();
                    if ($e->getCode() == 1062) {
                        $message = "Error updating exam: A class/subject link already exists, or the exam name conflicts.";
                    } else {
                        $message = "Error updating exam: " . $e->getMessage();
                    }
                    $message_type = "error";
                }
            }
            break;

        case 'delete_exam':
            $exam_id = $_POST['exam_id'];
            $conn->begin_transaction();
            try {
                $stmt_delete_classes = $conn->prepare("DELETE FROM exam_classes WHERE exam_id = ?");
                $stmt_delete_classes->bind_param("i", $exam_id);
                $stmt_delete_classes->execute();
                $stmt_delete_classes->close();

                $stmt_delete_subjects = $conn->prepare("DELETE FROM exam_subjects WHERE exam_id = ?");
                $stmt_delete_subjects->bind_param("i", $exam_id);
                $stmt_delete_subjects->execute();
                $stmt_delete_subjects->close();
                
                $stmt = $conn->prepare("DELETE FROM exams WHERE exam_id = ? AND school_id = ?");
                $stmt->bind_param("ii", $exam_id, $current_user_school_id);
                $stmt->execute();
                $stmt->close();
                $conn->commit();
                $message = "Exam deleted successfully!";
                $message_type = "success";
                
                // Redirect to refresh the page and remove the deleted exam from the table
                header("Location: admin_exams.php?message=" . urlencode($message) . "&message_type=" . $message_type);
                exit();
            } catch (mysqli_sql_exception $e) {
                $conn->rollback();
                $message = "Error deleting exam: " . $e->getMessage();
                $message_type = "error";
            }
            break;

        case 'manage_class_publishing':
            // Handle AJAX requests for class-level publishing management
            header('Content-Type: application/json');
            
            // Start output buffering to catch any unexpected output
            ob_start();
            
            try {
                // Check if database connection is still valid
                if (!$conn || $conn->connect_error) {
                    throw new Exception('Database connection error: ' . ($conn->connect_error ?? 'Unknown error'));
                }
                
                $action = $_POST['class_action'] ?? '';
            
            if ($action === 'get_classes') {
                $exam_id = intval($_POST['exam_id'] ?? 0);
                
                if ($exam_id === 0) {
                    echo json_encode(['success' => false, 'message' => 'Invalid exam ID']);
                    exit();
                }
                
                // Get exam info
                $stmt_exam = $conn->prepare("SELECT exam_name FROM exams WHERE exam_id = ? AND school_id = ?");
                $stmt_exam->bind_param("ii", $exam_id, $current_user_school_id);
                $stmt_exam->execute();
                $result_exam = $stmt_exam->get_result();
                $exam_info = $result_exam->fetch_assoc();
                $stmt_exam->close();
                
                if (!$exam_info) {
                    echo json_encode(['success' => false, 'message' => 'Exam not found']);
                    exit();
                }
                
                // Get all classes for this exam with their publishing status
                $stmt_classes = $conn->prepare("
                    SELECT 
                        c.class_id, 
                        c.class_name, 
                        NULL as stream_id,
                        'All Streams' as stream_name,
                        COALESCE(ecs.status, 'Draft') as class_status,
                        ecs.published_at,
                        ecs.published_by,
                        u.username as published_by_username
                    FROM exam_classes ec
                    INNER JOIN classes c ON ec.class_id = c.class_id
                    LEFT JOIN exam_class_status ecs ON ec.exam_id = ecs.exam_id 
                        AND ec.class_id = ecs.class_id 
                        AND (ecs.stream_id IS NULL OR ecs.stream_id = 0)
                    LEFT JOIN users u ON ecs.published_by = u.id
                    WHERE ec.exam_id = ?
                    ORDER BY c.class_name
                ");
                $stmt_classes->bind_param("i", $exam_id);
                $stmt_classes->execute();
                $result_classes = $stmt_classes->get_result();
                
                $classes = [];
                while ($row = $result_classes->fetch_assoc()) {
                    $classes[] = [
                        'class_id' => $row['class_id'],
                        'class_name' => $row['class_name'],
                        'stream_id' => $row['stream_id'],
                        'stream_name' => $row['stream_name'],
                        'status' => $row['class_status'],
                        'published_at' => $row['published_at'],
                        'published_by' => $row['published_by'],
                        'published_by_username' => $row['published_by_username']
                    ];
                }
                $stmt_classes->close();
                
                echo json_encode([
                    'success' => true, 
                    'exam_name' => $exam_info['exam_name'],
                    'classes' => $classes
                ]);
                exit();
            }
            
            // Handle publish/unpublish class requests
            if ($action === 'publish_class' || $action === 'unpublish_class') {
                $exam_id = intval($_POST['exam_id'] ?? 0);
                $class_id = intval($_POST['class_id'] ?? 0);
                $stream_id = intval($_POST['stream_id'] ?? 0);
                
                if ($exam_id === 0 || $class_id === 0) {
                    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
                    exit();
                }
                
                // Validate user_id
                if (empty($user_id) || !is_numeric($user_id)) {
                    echo json_encode(['success' => false, 'message' => 'Invalid user session']);
                    exit();
                }
                
                $conn->begin_transaction();
                try {
                    // Debug logging
                    error_log("Publishing class - Exam ID: $exam_id, Class ID: $class_id, Stream ID: $stream_id, User ID: $user_id");
                    
                    if ($action === 'publish_class') {
                        // First try to update existing record
                        $update_stmt = $conn->prepare("
                            UPDATE exam_class_status 
                            SET status = 'Published',
                                published_by = ?,
                                published_at = NOW(),
                                updated_at = NOW()
                            WHERE exam_id = ? AND class_id = ? AND (stream_id = ? OR stream_id IS NULL OR stream_id = 0)
                        ");
                        $update_stmt->bind_param("iiii", $user_id, $exam_id, $class_id, $stream_id);
                        $update_stmt->execute();
                        $rows_affected = $update_stmt->affected_rows;
                        $update_stmt->close();
                        
                        // If no rows were updated, insert new record
                        if ($rows_affected == 0) {
                            $insert_stmt = $conn->prepare("
                                INSERT INTO exam_class_status (exam_id, class_id, stream_id, status, published_by, published_at, created_at, updated_at)
                                VALUES (?, ?, ?, 'Published', ?, NOW(), NOW(), NOW())
                            ");
                            $insert_stmt->bind_param("iiii", $exam_id, $class_id, $stream_id, $user_id);
                            $insert_stmt->execute();
                            $insert_stmt->close();
                        }
                    } else {
                        // Update class status to Draft
                        $unpublish_stmt = $conn->prepare("
                            UPDATE exam_class_status 
                            SET status = 'Draft', 
                                published_by = NULL,
                                published_at = NULL, 
                                updated_at = NOW()
                            WHERE exam_id = ? AND class_id = ? AND (stream_id = ? OR stream_id IS NULL)
                        ");
                        $unpublish_stmt->bind_param("iii", $exam_id, $class_id, $stream_id);
                        $unpublish_stmt->execute();
                        $unpublish_stmt->close();
                    }
                    
                    $conn->commit();
                    
                    // Debug logging
                    error_log("Successfully published/unpublished class - Exam ID: $exam_id, Class ID: $class_id");
                    
                    $action_text = ($action === 'publish_class') ? 'published' : 'unpublished';
                    echo json_encode([
                        'success' => true, 
                        'message' => "Class $action_text successfully!"
                    ]);
                } catch (Exception $e) {
                    $conn->rollback();
                    echo json_encode([
                        'success' => false, 
                        'message' => 'Error: ' . $e->getMessage()
                    ]);
                }
                exit();
            }
            
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            exit();
            
            } catch (Exception $e) {
                // Clear any output that might have been generated
                ob_clean();
                
                echo json_encode([
                    'success' => false, 
                    'message' => 'Error processing request: ' . $e->getMessage()
                ]);
                exit();
            }
            break;

        // REMOVED: Whole-exam publish/unpublish functionality
        // This has been replaced with class-by-class publishing via manage_class_publishing case above
        
        case 'add_grading_system':
            $grade_name = trim($_POST['grade_name'] ?? '');
            $academic_year = trim($_POST['grading_academic_year'] ?? '');
            $term_name = trim($_POST['grading_term'] ?? '');
            $class_id_for_grading = intval($_POST['grading_class_id'] ?? 0);
            $subject_id_for_grading = intval($_POST['grading_subject_id'] ?? 0);
            $grade_ranges_json = $_POST['grade_ranges_json'] ?? '[]';
            $grade_ranges = json_decode($grade_ranges_json, true);

            if (empty($grade_name) || !is_array($grade_ranges) || empty($grade_ranges)) {
                $message = "Grading system name and at least one grade range must be provided.";
                $message_type = "error";
                break;
            }

            $insert_academic_year = empty($academic_year) ? NULL : $academic_year;
            $insert_term_name = empty($term_name) ? NULL : $term_name;

            $conn->begin_transaction();
            try {
                $sql_insert_grade = "INSERT INTO grading_scales (school_id, grade_name, min_score, max_score, grade_letter, grade, remarks, academic_year, term_name, class_id, subject_id, created_by, updated_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                $stmt_insert_grade = $conn->prepare($sql_insert_grade);

                foreach ($grade_ranges as $range) {
                    $current_min_score = floatval($range['min_score']);
                    $current_max_score = floatval($range['max_score']);
                    $current_grade_letter = trim($range['grade_letter']);
                    $current_grade = isset($range['grade']) ? trim($range['grade']) : NULL;
                    $current_remarks = trim($range['remarks']);

                    if ($current_min_score < 0 || $current_max_score <= 0 || empty($current_grade_letter)) {
                        throw new mysqli_sql_exception("Invalid score range or grade letter in one of the entries.");
                    }

                    $stmt_insert_grade->bind_param("isddssssisiii",
                        $current_user_school_id,
                        $grade_name,
                        $current_min_score,
                        $current_max_score,
                        $current_grade_letter,
                        $current_grade,
                        $current_remarks,
                        $insert_academic_year,
                        $insert_term_name,
                        $class_id_for_grading,
                        $subject_id_for_grading,
                        $user_id,
                        $user_id
                    );
                    $stmt_insert_grade->execute();
                }
                $stmt_insert_grade->close();
                $conn->commit();
                $message = "Grading system '{$grade_name}' and its ranges added successfully.";
                $message_type = "success";
            } catch (mysqli_sql_exception $e) {
                $conn->rollback();
                $message = "Error adding grading system: " . $e->getMessage();
                $message_type = "error";
            }
            break;

        case 'update_grading_scale':
            $grading_scale_id = intval($_POST['edit_grading_scale_id'] ?? 0);
            $min_score = floatval($_POST['edit_min_score'] ?? 0);
            $max_score = floatval($_POST['edit_max_score'] ?? 0);
            $grade_letter = trim($_POST['edit_grade_letter'] ?? '');
            $grade = trim($_POST['edit_grade'] ?? '');
            $remarks = trim($_POST['edit_remarks'] ?? '');

            if ($grading_scale_id === 0 || empty($grade_letter)) {
                $message = "Invalid grading scale ID or grade letter.";
                $message_type = "error";
                break;
            }

            if ($min_score < 0 || $max_score <= 0) {
                $message = "Invalid score range.";
                $message_type = "error";
                break;
            }

            try {
                $stmt = $conn->prepare("UPDATE grading_scales SET min_score = ?, max_score = ?, grade_letter = ?, grade = ?, remarks = ?, updated_by = ? WHERE id = ? AND school_id = ?");
                $grade_value = empty($grade) ? NULL : $grade;
                $stmt->bind_param("ddsssiis", $min_score, $max_score, $grade_letter, $grade_value, $remarks, $user_id, $grading_scale_id, $current_user_school_id);
                $stmt->execute();
                $stmt->close();
                $message = "Grading scale updated successfully!";
                $message_type = "success";
            } catch (mysqli_sql_exception $e) {
                $message = "Error updating grading scale: " . $e->getMessage();
                $message_type = "error";
            }
            break;

        case 'delete_grading_scale':
            $grading_scale_id = intval($_POST['grading_scale_id'] ?? 0);
            if ($grading_scale_id === 0) {
                $message = "Invalid grading scale ID for deletion.";
                $message_type = "error";
                break;
            }
            try {
                $stmt = $conn->prepare("DELETE FROM grading_scales WHERE id = ? AND school_id = ?");
                $stmt->bind_param("ii", $grading_scale_id, $current_user_school_id);
                $stmt->execute();
                $stmt->close();
                $message = "Grading scale deleted successfully!";
                $message_type = "success";
            } catch (mysqli_sql_exception $e) {
                $message = "Error deleting grading scale: " . $e->getMessage();
                $message_type = "error";
            }
            break;
    }

    // Redirect to prevent form re-submission on refresh
    $redirect_url = "admin_exams.php";
    if (isset($_GET['lang'])) {
        $redirect_url .= "?lang=" . urlencode($_GET['lang']);
    }
    header("Location: " . $redirect_url);
    exit();
}

// --- Filtering and Displaying Exams ---
$selected_academic_year = $_GET['academic_year'] ?? '';
$selected_term = $_GET['term'] ?? '';

$exams_list = [];
$sql = "SELECT DISTINCT 
                e.exam_id, e.exam_name, e.term, e.year, e.status, e.exam_type,
                e.first_exam_id, e.second_exam_id, e.integration_exam_id, e.normal_exam_id,
                e.integration_weight, e.normal_weight,
                u.username AS updated_by_username,
                c.class_name AS class_affected,
                c.class_id AS class_id_affected,
                COALESCE(ecs.status, 'Draft') AS class_status,
                GROUP_CONCAT(DISTINCT s.subject_name ORDER BY s.subject_name SEPARATOR ', ') AS subjects_affected,
                GROUP_CONCAT(DISTINCT s.subject_id ORDER BY s.subject_name SEPARATOR ',') AS subject_ids_affected,
                e1.exam_name AS first_exam_name, e2.exam_name AS second_exam_name,
                e3.exam_name AS integration_exam_name, e4.exam_name AS normal_exam_name
        FROM exams e
        LEFT JOIN users u ON e.updated_by = u.id
        LEFT JOIN exam_classes ec ON e.exam_id = ec.exam_id
        LEFT JOIN classes c ON ec.class_id = c.class_id
        LEFT JOIN exam_class_status ecs ON e.exam_id = ecs.exam_id 
            AND c.class_id = ecs.class_id 
            AND (ecs.stream_id IS NULL OR ecs.stream_id = 0)
        LEFT JOIN exam_subjects es ON e.exam_id = es.exam_id
        LEFT JOIN subjects s ON es.subject_id = s.subject_id
        LEFT JOIN exams e1 ON e.first_exam_id = e1.exam_id
        LEFT JOIN exams e2 ON e.second_exam_id = e2.exam_id
        LEFT JOIN exams e3 ON e.integration_exam_id = e3.exam_id
        LEFT JOIN exams e4 ON e.normal_exam_id = e4.exam_id
        WHERE e.school_id = ?
        GROUP BY e.exam_id, e.exam_name, e.term, e.year, e.status, e.exam_type,
                 e.first_exam_id, e.second_exam_id, e.integration_exam_id, e.normal_exam_id,
                 e.integration_weight, e.normal_weight, u.username, c.class_name, c.class_id, ecs.status,
                 e1.exam_name, e2.exam_name, e3.exam_name, e4.exam_name";
        
$params = [$current_user_school_id];
$types = 'i';

if (!empty($selected_academic_year)) {
    $sql .= " AND e.year = ?";
    $params[] = $selected_academic_year;
    $types .= 's';
}
if (!empty($selected_term)) {
    $sql .= " AND e.term = ?";
    $params[] = $selected_term;
    $types .= 's';
}

$sql .= " ORDER BY e.year DESC, e.term DESC, e.exam_name ASC, c.class_name ASC";

$stmt_exams = $conn->prepare($sql);

if ($stmt_exams === false) {
    die("Error preparing statement: " . $conn->error);
}

if (!empty($params)) {
    $bind_params_args = array($types);
    for ($i = 0; $i < count($params); $i++) {
        $bind_params_args[] = &$params[$i];
    }
    call_user_func_array([$stmt_exams, 'bind_param'], $bind_params_args);
}

$stmt_exams->execute();
$result_exams = $stmt_exams->get_result();
while ($row = $result_exams->fetch_assoc()) {
    $exams_list[] = $row;
}
$stmt_exams->close();

// Group exams by year for better display organization
$exams_by_year = [];
foreach ($exams_list as $exam) {
    $year = $exam['year'];
    if (!isset($exams_by_year[$year])) {
        $exams_by_year[$year] = [];
    }
    $exams_by_year[$year][] = $exam;
}

// Group exams by exam_id for rowspan calculation
$exams_by_exam_id = [];
foreach ($exams_list as $exam) {
    $exam_id = $exam['exam_id'];
    if (!isset($exams_by_exam_id[$exam_id])) {
        $exams_by_exam_id[$exam_id] = [];
    }
    $exams_by_exam_id[$exam_id][] = $exam;
}

// Sort years in descending order (most recent first)
krsort($exams_by_year);

// Handle messages passed via GET after redirect
if (isset($_GET['message']) && isset($_GET['message_type'])) {
    $message = urldecode($_GET['message']);
    $message_type = urldecode($_GET['message_type']);
}

// Determine role name for display
$role_name = $lang['unknown_role'];
switch ($user_role_code) {
    case ROLE_SUPER_ADMIN: $role_name = "Super Admin"; break;
    case ROLE_ADMIN:         $role_name = $lang['admin_role'];         break;
    case ROLE_TEACHER:       $role_name = $lang['teacher_role'];       break;
    case ROLE_STUDENT:       $role_name = $lang['student_role'];       break;
    case ROLE_PARENT:        $role_name = $lang['parent_role'];        break;
    case ROLE_STAFF:         $role_name = $lang['staff_role'];         break;
}


?>

<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $lang['exams_title']; ?> - <?php echo htmlspecialchars($school_name, ENT_QUOTES, 'UTF-8'); ?></title>
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <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>
        
        .language-select select {
            padding: 8px 12px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            background: white;
            min-width: 120px;
        }

        /* Year-based table organization styles */
        .year-section {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            transition: all 0.3s ease;
        }

        .year-section:hover {
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        }

        .year-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            margin-bottom: 0;
        }

        .year-header h3 {
            margin: 0;
            font-weight: 600;
        }

        .year-table {
            margin-bottom: 0;
            border-radius: 0;
        }

        .year-table thead th {
            background-color: #f8fafc;
            border-bottom: 2px solid #e2e8f0;
            font-weight: 600;
            color: #4a5568;
            font-size: 0.875rem;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }

        .year-table tbody tr:hover {
            background-color: #f7fafc;
        }

        /* Custom blue color variations for exam differentiation */
        .bg-blue-50 {
            background-color: #eff6ff !important;
        }

        .bg-blue-25 {
            background-color: #f0f9ff !important;
        }

        .bg-blue-75 {
            background-color: #dbeafe !important;
        }

        .bg-blue-100 {
            background-color: #bfdbfe !important;
        }

        .bg-blue-150 {
            background-color: #93c5fd !important;
        }

        /* Ensure color variations work well with hover */
        .bg-blue-50:hover,
        .bg-blue-25:hover,
        .bg-blue-75:hover,
        .bg-blue-100:hover,
        .bg-blue-150:hover {
            background-color: #f7fafc !important;
        }

        /* Enhanced button styling for better visibility */
        .btn-view {
            background-color: #3182ce;
            color: white;
            border: 1px solid #3182ce;
        }

        .btn-view:hover {
            background-color: #2c5282;
            border-color: #2c5282;
            transform: translateY(-1px);
        }

        /* Ensure action buttons are properly visible */
        .action-buttons-cell {
            min-width: 250px;
        }

        .action-buttons-cell .btn {
            margin: 2px;
            font-size: 0.75rem;
            padding: 6px 10px;
        }
            background-color: #ffffff;
            cursor: pointer;
            font-size: 0.875rem;
            color: #374151;
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            background-image: url('data:image/svg+xml;charset=US-ASCII,%3Csvg xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22 viewBox%3D%220 0 4 5%22%3E%3Cpath fill%3D%22%23343a40%22 d%3D%22M2 0L0 2h4zm0 5L0 3h4z%22%2F%3E%3C%2Fsvg%3E');
            background-repeat: no-repeat;
            background-position: right 0.75rem center;
            background-size: 8px 10px;
            padding-right: 2.25rem;
        }

        .language-select select:focus {
            outline: none;
            border-color: #4f46e5;
            box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.25);
        }

        .user-profile {
            display: flex;
            align-items: center;
            cursor: pointer;
        }

        .user-profile div {
            display: flex;
            flex-direction: column;
            text-align: right;
            margin-right: 12px;
        }

        .user-profile .user-name {
            font-weight: 500;
            color: #1f2937;
        }

        .user-profile .user-email {
            font-size: 0.875rem;
            color: #4b5563;
        }

        .user-profile img {
            height: 40px;
            width: 40px;
            border-radius: 9999px;
            border: 2px solid #d1d5db;
            object-fit: cover;
            margin-right: 8px;
        }
        .user-profile .fas.fa-chevron-down {
            color: #4b5563;
            font-size: 0.8rem;
        }

        .main-content {
            flex-grow: 1;
            padding: 24px;
            background-color: #f3f4f6;
        }

        .message-box {
            padding: 16px;
            margin-bottom: 16px;
            border-radius: 8px;
            font-weight: 700;
            display: flex;
            justify-content: space-between;
            align-items: center;
            opacity: 1;
            transition: opacity 0.5s ease-out;
        }

        .message-box.success {
            background-color: #d1fae5;
            color: #065f46;
            border: 1px solid #34d399;
        }

        .message-box.error {
            background-color: #fee2e2;
            color: #991b1b;
            border: 1px solid #ef4444;
        }

        .message-box .close-btn {
            background: none;
            border: none;
            font-size: 1rem;
            color: inherit;
            opacity: 0.75;
            cursor: pointer;
        }

        .message-box .close-btn:hover {
            opacity: 1;
        }

        .content-card {
            background-color: #ffffff;
            padding: 24px;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
        }

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

        .content-card-header h2 {
            font-size: 1.5rem;
            font-weight: 600;
            color: #1f2937;
            margin: 0;
        }

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

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

        .data-table th {
            background-color: #f9fafb;
            font-weight: 600;
            color: #4b5563;
            text-transform: uppercase;
            font-size: 0.85rem;
        }

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

        .action-buttons-cell {
            display: flex;
            flex-wrap: wrap;
            gap: 0.5rem;
        }
        .action-buttons-cell .btn {
            padding: 0.4rem 0.8rem;
            font-size: 0.875rem;
            border-radius: 0.375rem;
            transition: background-color 0.2s ease-in-out;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
        }
        .action-buttons-cell .btn-edit {
            background-color: #3b82f6;
            color: white;
        }
        .action-buttons-cell .btn-edit:hover {
            background-color: #2563eb;
        }
        .action-buttons-cell .btn-delete {
            background-color: #ef4444;
            color: white;
        }
        .action-buttons-cell .btn-delete:hover {
            background-color: #dc2626;
        }
        .action-buttons-cell .btn-publish {
            background-color: #10b981;
            color: white;
        }
        .action-buttons-cell .btn-publish:hover {
            background-color: #059669;
        }
        .action-buttons-cell .btn-unpublish {
            background-color: #f59e0b;
            color: white;
        }
        .action-buttons-cell .btn-unpublish:hover {
            background-color: #d97706;
        }
        .action-buttons-cell .btn-view {
            background-color: #6366f1;
            color: white;
        }
        .action-buttons-cell .btn-view:hover {
            background-color: #4f46e5;
        }

        @media (max-width: 768px) {
            .data-table thead {
                display: none;
            }

            .data-table, .data-table tbody, .data-table tr, .data-table td {
                display: block;
                width: 100%;
            }

            .data-table tr {
                margin-bottom: 15px;
                border: 1px solid #e5e7eb;
                border-radius: 8px;
                overflow: hidden;
            }

            .data-table td {
                text-align: right;
                padding-left: 50%;
                position: relative;
            }

            .data-table td::before {
                content: attr(data-label);
                position: absolute;
                left: 15px;
                width: calc(50% - 30px);
                text-align: left;
                font-weight: 600;
                color: #4b5563;
            }

            .data-table .action-buttons-cell {
                text-align: left;
                padding-left: 15px;
            }
        }

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

        .modal-content {
            background-color: #ffffff;
            margin: auto;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
            position: relative;
            width: 90%;
            max-width: 500px;
            animation: fadeIn 0.3s ease-out;
            font-family: 'Inter', 'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif;
            color: #333333;
        }

        .close-button {
            position: absolute;
            right: 20px;
            top: 20px;
            color: #9ca3af;
            font-size: 24px;
            font-weight: normal;
            cursor: pointer;
            transition: color 0.2s ease;
        }

        .close-button:hover {
            color: #6b7280;
        }

        /* Success Modal Styles */
        .success-modal .modal-content {
            text-align: center;
            max-width: 380px;
        }

        .success-icon-wrapper {
            background-color: #28a745;
            border-radius: 50%;
            width: 60px;
            height: 60px;
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0 auto 20px auto;
        }

        .success-icon {
            width: 30px;
            height: 30px;
            fill: none;
            stroke: white;
            stroke-width: 4px;
            stroke-linecap: round;
            stroke-linejoin: round;
        }

        .success-title {
            font-size: 1.8em;
            font-weight: 700;
            color: #333333;
            margin-bottom: 10px;
        }

        .success-message {
            font-size: 1em;
            color: #6c757d;
            line-height: 1.5;
            margin-bottom: 25px;
        }

        /* Error Modal Styles */
        .error-modal .modal-content {
            text-align: center;
            max-width: 380px;
        }

        .error-icon-wrapper {
            background-color: #dc3545;
            border-radius: 50%;
            width: 60px;
            height: 60px;
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0 auto 20px auto;
        }

        .error-icon {
            width: 30px;
            height: 30px;
            fill: none;
            stroke: white;
            stroke-width: 4px;
            stroke-linecap: round;
            stroke-linejoin: round;
        }

        .error-title {
            font-size: 1.8em;
            font-weight: 700;
            color: #333333;
            margin-bottom: 10px;
        }

        .error-message {
            font-size: 1em;
            color: #6c757d;
            line-height: 1.5;
            margin-bottom: 25px;
        }

        /* Warning Modal Styles */
        .warning-modal .modal-content {
            text-align: center;
            max-width: 380px;
        }

        .warning-icon-wrapper {
            background-color: #ffc107;
            border-radius: 50%;
            width: 60px;
            height: 60px;
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0 auto 20px auto;
        }

        .warning-icon {
            width: 30px;
            height: 30px;
            fill: none;
            stroke: white;
            stroke-width: 4px;
            stroke-linecap: round;
            stroke-linejoin: round;
        }

        .warning-title {
            font-size: 1.8em;
            font-weight: 700;
            color: #333333;
            margin-bottom: 10px;
        }

        .warning-message {
            font-size: 1em;
            color: #6c757d;
            line-height: 1.5;
            margin-bottom: 25px;
        }

        /* Modern Button Styles */
        .btn-modal {
            display: inline-block;
            padding: 12px 28px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1em;
            font-weight: 600;
            text-decoration: none;
            transition: background-color 0.2s ease-in-out;
            text-align: center;
        }

        .btn-modal-primary {
            background-color: #007bff;
            color: #ffffff;
        }

        .btn-modal-primary:hover {
            background-color: #0056b3;
        }

        .btn-modal-success {
            background-color: #28a745;
            color: #ffffff;
        }

        .btn-modal-success:hover {
            background-color: #1e7e34;
        }

        .btn-modal-danger {
            background-color: #dc3545;
            color: #ffffff;
        }

        .btn-modal-danger:hover {
            background-color: #c82333;
        }

        .btn-modal-warning {
            background-color: #ffc107;
            color: #212529;
        }

        .btn-modal-warning:hover {
            background-color: #e0a800;
        }

        .btn-modal-secondary {
            background-color: #6c757d;
            color: #ffffff;
        }

        .btn-modal-secondary:hover {
            background-color: #5a6268;
        }

        .modal-footer {
            text-align: center;
            margin-top: 20px;
        }

        .modal-footer .btn-modal {
            min-width: 100px;
        }

        #createNormalExamModal .modal-content,
        #createConsolidatedExamModal .modal-content,
        #createTermSummaryExamModal .modal-content,
        #createAverageAssessmentModal .modal-content,
        #editExamModal .modal-content {
            max-width: 700px;
        }
        #addGradingSystemModal .modal-content {
            max-width: 800px;
        }
        #viewResultsStatusModal .modal-content,
        #viewGradingScalesModal .modal-content,
        #publishAssessmentModal .modal-content,
        #streamAssessmentDetailsModal .modal-content {
            max-width: 900px;
        }

        .exam-type-option {
            transition: all 0.2s ease-in-out;
        }
        .exam-type-option:hover {
            border-color: #d1d5db !important;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

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

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

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

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

        .checkbox-group {
            max-height: 150px;
            overflow-y: auto;
            border: 1px solid #e2e8f0;
            padding: 10px;
            border-radius: 0.5rem;
            background-color: #f8fafc;
        }
        .checkbox-group label {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            cursor: pointer;
            font-weight: normal;
        }
        .checkbox-group input[type="checkbox"] {
            margin-right: 8px;
            width: auto;
            padding: 0;
            border-radius: 0.25rem;
        }

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

        .btn-secondary {
            background-color: #6b7280;
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 0.375rem;
            border: none;
            cursor: pointer;
            transition: background-color 0.2s ease-in-out;
        }
        .btn-secondary:hover {
            background-color: #4b5563;
        }

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

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

        #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;
        }
        
        #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;
            display: none;
        }

        #more-menu-modal.show {
            transform: translateY(0);
        }
        
        #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;
        }

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

        .table-responsive-wrapper {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }

        .filter-controls {
            background-color: #f8fafc;
            padding: 1rem;
            border-radius: 0.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid #e2e8f0;
        }

        .grid {
            display: grid;
        }
        .grid-cols-1 { grid-template-columns: repeat(1, minmax(0, 1fr)); }
        .grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
        .grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
        .grid-cols-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); }
        .grid-cols-5 { grid-template-columns: repeat(5, minmax(0, 1fr)); }
        .gap-2 { gap: 0.5rem; }
        .gap-3 { gap: 0.75rem; }
        .gap-4 { gap: 1rem; }

        @media (min-width: 768px) {
            .md\:grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
            .md\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
            .md\:col-span-2 { grid-column: span 2 / span 2; }
        }

        @media (min-width: 1024px) {
            .lg\:grid-cols-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); }
            .lg\:col-span-4 { grid-column: span 4 / span 4; }
        }

        .hidden { display: none; }
        .flex { display: flex; }
        .items-center { align-items: center; }
        .justify-between { justify-content: space-between; }
        .justify-end { justify-content: flex-end; }
        .space-x-3 > :not([hidden]) ~ :not([hidden]) { margin-left: 0.75rem; }
        .mb-4 { margin-bottom: 1rem; }
        .mb-6 { margin-bottom: 1.5rem; }
        .mt-6 { margin-top: 1.5rem; }
        .text-center { text-align: center; }
        .text-sm { font-size: 0.875rem; }
        .text-xl { font-size: 1.25rem; }
        .font-semibold { font-weight: 600; }
        .px-2 { padding-left: 0.5rem; padding-right: 0.5rem; }
        .px-4 { padding-left: 1rem; padding-right: 1rem; }
        .py-2 { padding-top: 0.5rem; padding-bottom: 0.5rem; }
        .py-4 { padding-top: 1rem; padding-bottom: 1rem; }
        .w-full { width: 100%; }
        .max-w-sm { max-width: 24rem; }
        .border { border-width: 1px; }
        .border-gray-200 { border-color: #e5e7eb; }
        .rounded-md { border-radius: 0.375rem; }
        .rounded-lg { border-radius: 0.5rem; }
        .shadow-md { box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); }
        .transition { transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter; }
        .duration-200 { transition-duration: 200ms; }
        .bg-white { background-color: #ffffff; }
        .bg-gray-100 { background-color: #f3f4f6; }
        .bg-gray-50 { background-color: #f9fafb; }
        .bg-gray-500 { background-color: #6b7280; }
        .bg-purple-600 { background-color: #9333ea; }
        .bg-blue-600 { background-color: #2563eb; }
        .bg-red-600 { background-color: #dc2626; }
        .hover\:bg-gray-700:hover { background-color: #374151; }
        .hover\:bg-purple-700:hover { background-color: #7c2d12; }
        .hover\:bg-blue-700:hover { background-color: #1d4ed8; }
        .hover\:bg-red-700:hover { background-color: #b91c1c; }
        .text-white { color: #ffffff; }
        .text-gray-500 { color: #6b7280; }
        .text-gray-600 { color: #4b5563; }
        .text-gray-700 { color: #374151; }
        .text-gray-800 { color: #1f2937; }
        .text-green-600 { color: #16a34a; }
        .text-orange-600 { color: #ea580c; }
        .text-red-500 { color: #ef4444; }
        .text-red-700 { color: #b91c1c; }
        .text-green-700 { color: #15803d; }
        .text-orange-700 { color: #c2410c; }
        .text-indigo-700 { color: #4338ca; }
        .col-span-1 { grid-column: span 1 / span 1; }
        .items-end { align-items: flex-end; }
        .ml-2 { margin-left: 0.5rem; }
        .mr-1 { margin-right: 0.25rem; }
        .mr-2 { margin-right: 0.5rem; }
        .font-medium { font-weight: 500; }
        .capitalize { text-transform: capitalize; }
        .space-y-4 > :not([hidden]) ~ :not([hidden]) { margin-top: 1rem; }
    </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> <?php echo $lang['dashboard_title']; ?></a></li>
                     <li><a href="admin_user_management.php" id="usersLink"><i class="fas fa-users-cog"></i> <span class="nav-text">Users</span></a></li>
                    <li><a href="admin_students.php" id="studentsLink"><i class="fas fa-user-graduate"></i> <?php echo $lang['students']; ?></a></li>
                    <li><a href="admin_teachers.php" id="teachersLink"><i class="fas fa-chalkboard-teacher"></i> <?php echo $lang['teachers']; ?></a></li>
                    
                    <li class="hide-on-mobile"><a href="admin_staff.php" id="staffLink"><i class="fas fa-user-tie"></i> <?php echo $lang['staff']; ?></a></li>
                    <li class="hide-on-mobile"><a href="admin_classes.php" id="classesLink"><i class="fas fa-chalkboard"></i> <?php echo $lang['classes']; ?></a></li>
                    <li class="hide-on-mobile"><a href="admin_subjects.php" id="subjectsLink"><i class="fas fa-book"></i> <?php echo $lang['subjects']; ?></a></li>
                    <li class="active"><a href="admin_exams.php" id="examsLink"><i class="fas fa-file-alt"></i> <?php echo $lang['exams']; ?></a></li>
                    <li class="hide-on-mobile"><a href="admin_reports_printouts.php" id="reportsLink"><i class="fas fa-print"></i> <?php echo $lang['reports']; ?></a></li>
                    <li class="hide-on-mobile"><a href="admin_system_settings.php" id="systemSettingsLink"><i class="fas fa-cog"></i> <?php echo $lang['settings']; ?></a></li>
                    <li class="hide-on-mobile"><a href="logout.php" class="logout-btn" id="logoutLinkSidebar"><i class="fas fa-sign-out-alt"></i> <?php echo $lang['log_out']; ?></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 htmlspecialchars($school_name, ENT_QUOTES, 'UTF-8'); ?> Logo">
                    <h1><?php echo htmlspecialchars($school_name, ENT_QUOTES, 'UTF-8'); ?></h1>
                </div>
                <div class="header-right">
                    <div class="language-select">
                        <select id="languageSelect">
                           <option value="en" <?php echo ($current_lang == 'en' ? 'selected' : ''); ?>>🇬🇧 English</option>
                           <option value="lg" <?php echo ($current_lang == 'lg' ? 'selected' : ''); ?>>🇺🇬 Luganda</option>
                           <option value="sw" <?php echo ($current_lang == 'sw' ? 'selected' : ''); ?>>🇹🇿 Kiswahili</option>
                        </select>
                    </div>
                    <div class="search-bar">
                        <i class="fas fa-search"></i>
                        <input type="text" placeholder="<?php echo $lang['search_placeholder']; ?>" 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"><?php echo $lang['logged_in_as']; ?>: <?php echo $role_name; ?></div>
                        </div>
                        <i class="fas fa-chevron-down"></i>
                    </div>
                </div>
            </header>

            <div class="dashboard-content">
                <?php if ($message) : ?>
                    <div class="message-box <?php echo $message_type; ?>" id="messageBox">
                        <span><?php echo $message; ?></span>
                        <button class="close-btn" onclick="document.getElementById('messageBox').style.display='none';">&times;</button>
                    </div>
                <?php endif; ?>

                <div class="content-card">
                    <div class="content-card-header">
                        <h2><?php echo $lang['exams_title']; ?> (<?php echo htmlspecialchars($school_name, ENT_QUOTES, 'UTF-8'); ?>)</h2>
                        <div class="flex gap-3 flex-wrap">
                            <button onclick="openCreateExamModal()" class="btn-primary flex items-center">
                                <i class="fas fa-plus mr-2"></i> <?php echo $lang['create_new_exam']; ?>
                            </button>
                            <button onclick="openAddGradingSystemModal()" class="bg-purple-600 text-white px-4 py-2 rounded-lg shadow-md hover:bg-purple-700 transition duration-200 flex items-center">
                                <i class="fas fa-percentage mr-2"></i> <?php echo $lang['grading_system']; ?>
                            </button>
                            <button onclick="openViewGradingScalesModal()" class="bg-blue-600 text-white px-4 py-2 rounded-lg shadow-md hover:bg-blue-700 transition duration-200 flex items-center">
                                <i class="fas fa-eye mr-2"></i> <?php echo $lang['view_grading_scales']; ?>
                            </button>
                            
                            <!-- Pending Reviews Toggle -->
                            <button onclick="togglePendingReviews()" id="pendingReviewsToggle" class="bg-orange-600 text-white px-4 py-2 rounded-lg shadow-md hover:bg-orange-700 transition duration-200 flex items-center">
                                <i class="fas fa-clock mr-2"></i> Pending Reviews <span id="pendingReviewsCount" class="ml-2 bg-orange-800 text-white text-xs px-2 py-1 rounded-full">0</span>
                            </button>
                        </div>
                    </div>

                    <!-- Filter Controls -->
                    <div class="filter-controls grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div class="form-group">
                            <label for="filter_academic_year" class="text-sm">Filter by Academic Year</label>
                            <select id="filter_academic_year" class="p-2 border rounded-md w-full">
                                <option value="">All Years</option>
                                <?php foreach ($academic_years_from_db as $year): ?>
                                    <option value="<?php echo htmlspecialchars($year); ?>" <?php echo ($selected_academic_year === $year) ? 'selected' : ''; ?>><?php echo htmlspecialchars($year); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="filter_term" class="text-sm">Filter by Term</label>
                            <select id="filter_term" class="p-2 border rounded-md w-full">
                                <option value="">All Terms</option>
                                <?php foreach ($terms_from_db as $term): ?>
                                    <option value="<?php echo htmlspecialchars($term); ?>" <?php echo ($selected_term === $term) ? 'selected' : ''; ?>><?php echo htmlspecialchars($term); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="flex items-end justify-end md:col-span-1">
                        <button onclick="applyFilters()" class="btn-secondary px-4 py-2">Apply Filters</button>
                        <button onclick="resetFilters()" class="btn-secondary ml-2 px-4 py-2">Reset Filters</button>
                    </div>
                </div>

                <div class="table-responsive-wrapper">
                    <?php if (empty($exams_list)): ?>
                        <div class="bg-white rounded-lg shadow-sm p-8 text-center">
                            <i class="fas fa-file-alt text-gray-400 text-6xl mb-4"></i>
                            <p class="text-gray-500 text-lg">No exams found.</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($exams_by_year as $year => $year_exams): ?>
                            <div class="year-section mb-8">
                                <div class="year-header bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-t-lg px-6 py-4">
                                    <h3 class="text-xl font-semibold flex items-center">
                                        <i class="fas fa-calendar-alt mr-3"></i>
                                        Academic Year <?php echo htmlspecialchars($year); ?>
                                        <span class="ml-auto bg-white bg-opacity-20 px-3 py-1 rounded-full text-sm">
                                            <?php echo count($year_exams); ?> exam<?php echo count($year_exams) !== 1 ? 's' : ''; ?>
                                        </span>
                                    </h3>
                                </div>
                                
                                <table class="data-table year-table">
                                    <thead>
                                        <tr>
                                            <th><?php echo $lang['exam_name']; ?></th>
                                            <th><?php echo $lang['term']; ?></th>
                                            <th><?php echo $lang['classes_affected']; ?></th>
                                            <th><?php echo $lang['status']; ?></th>
                                            <th><?php echo $lang['last_updated_by']; ?></th>
                                            <th><?php echo $lang['actions']; ?></th>
                                        </tr>
                                    </thead>
                                    <tbody class="examTableBody">
                                        <?php 
                                        $displayed_exams = [];
                                        $exam_color_classes = [];
                                        $color_class_index = 0;
                                        
                                        // Define a set of light blue color classes for visual differentiation
                                        $blue_color_classes = [
                                            'bg-blue-50',     // Very light blue
                                            'bg-blue-25',     // Lighter blue  
                                            'bg-blue-75',     // Light blue
                                            'bg-blue-100',    // Medium light blue
                                            'bg-blue-150'     // Custom light blue
                                        ];
                                        
                                        foreach ($year_exams as $index => $exam): 
                                            $exam_id = $exam['exam_id'];
                                            $is_first_occurrence = !isset($displayed_exams[$exam_id]);
                                            $displayed_exams[$exam_id] = true;
                                            
                                            // Calculate rowspan for this exam (how many classes it has)
                                            $rowspan = isset($exams_by_exam_id[$exam_id]) ? count($exams_by_exam_id[$exam_id]) : 1;
                                            
                                            // Assign color class only on first occurrence
                                            if ($is_first_occurrence) {
                                                $color_class = $blue_color_classes[$color_class_index % count($blue_color_classes)];
                                                $exam_color_classes[$exam_id] = $color_class;
                                                $color_class_index++;
                                            }
                                            $current_color_class = $exam_color_classes[$exam_id];
                                        ?>
                                            <tr class="<?php echo $current_color_class; ?>" data-exam-id="<?php echo htmlspecialchars($exam['exam_id']); ?>"
                                                data-exam-name="<?php echo htmlspecialchars($exam['exam_name']); ?>"
                                                data-term="<?php echo htmlspecialchars($exam['term']); ?>"
                                                data-year="<?php echo htmlspecialchars($exam['year']); ?>"
                                                data-exam-type="<?php echo htmlspecialchars($exam['exam_type']); ?>"
                                                data-status="<?php echo htmlspecialchars($exam['status']); ?>"
                                                data-class-affected="<?php echo htmlspecialchars($exam['class_affected']); ?>"
                                                data-class-id-affected="<?php echo htmlspecialchars($exam['class_id_affected']); ?>"
                                                data-subjects-affected="<?php echo htmlspecialchars($exam['subjects_affected']); ?>"
                                                data-subject-ids-affected="<?php echo htmlspecialchars($exam['subject_ids_affected']); ?>"
                                                data-first-exam-id="<?php echo htmlspecialchars($exam['first_exam_id'] ?? ''); ?>"
                                                data-second-exam-id="<?php echo htmlspecialchars($exam['second_exam_id'] ?? ''); ?>"
                                                data-integration-exam-id="<?php echo htmlspecialchars($exam['integration_exam_id'] ?? ''); ?>"
                                                data-normal-exam-id="<?php echo htmlspecialchars($exam['normal_exam_id'] ?? ''); ?>"
                                                data-integration-weight="<?php echo htmlspecialchars($exam['integration_weight'] ?? ''); ?>"
                                                data-normal-weight="<?php echo htmlspecialchars($exam['normal_weight'] ?? ''); ?>"
                                                data-first-exam-name="<?php echo htmlspecialchars($exam['first_exam_name'] ?? ''); ?>"
                                                data-second-exam-name="<?php echo htmlspecialchars($exam['second_exam_name'] ?? ''); ?>"
                                                data-integration-exam-name="<?php echo htmlspecialchars($exam['integration_exam_name'] ?? ''); ?>"
                                                data-normal-exam-name-ref="<?php echo htmlspecialchars($exam['normal_exam_name'] ?? ''); ?>"
                                            >
                                                <?php if ($is_first_occurrence): ?>
                                                <td data-label="<?php echo $lang['exam_name']; ?>" rowspan="<?php echo $rowspan; ?>"><?php echo htmlspecialchars($exam['exam_name']); ?></td>
                                                <?php endif; ?>
                                                <td data-label="<?php echo $lang['term']; ?>"><?php echo htmlspecialchars($exam['term']); ?></td>
                                                <td data-label="<?php echo $lang['classes_affected']; ?>"><?php echo htmlspecialchars($exam['class_affected'] ?: 'N/A'); ?></td>
                                                <td data-label="<?php echo $lang['status']; ?>">
                                                    <?php
                                                    // Display individual class status for this specific class
                                                    // Get the class status from exam data - it should be available in the $exam array
                                                    $class_status = $exam['class_status'] ?? 'Draft';
                                                    $class_name = $exam['class_affected'] ?? 'Unknown Class';
                                                    error_log("Displaying status for class '{$class_name}' in exam {$exam['exam_id']}: {$class_status}");
                                                    
                                                    switch ($class_status) {
                                                        case 'Published':
                                                            echo '<span class="px-2 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-800">Published</span>';
                                                            break;
                                                        case 'Draft':
                                                        default:
                                                            echo '<span class="px-2 py-1 rounded-full text-xs font-semibold bg-yellow-100 text-yellow-800">Draft</span>';
                                                            break;
                                                    }
                                                    ?>
                                                </td>
                                                <td data-label="<?php echo $lang['last_updated_by']; ?>"><?php echo htmlspecialchars($exam['updated_by_username'] ?: 'N/A'); ?></td>
                                                <td data-label="<?php echo $lang['actions']; ?>" class="action-buttons-cell">
                                                    <?php if ($is_first_occurrence): ?>
                                                        <?php if ($exam['exam_type'] === 'Normal'): ?>
                                                            <button onclick="openEditExamModal(this)" class="btn btn-edit flex items-center">
                                                                <i class="fas fa-edit mr-1"></i> <?php echo $lang['edit']; ?>
                                                            </button>
                                                        <?php endif; ?>
                                                        
                                                        <?php if ($exam['exam_type'] === 'Average Assessment'): ?>
                                                            <button onclick="openPublishAssessmentModal(this)" class="btn btn-publish flex items-center">
                                                                <i class="fas fa-chart-bar mr-1"></i> <?php echo $lang['publish_assessment']; ?>
                                                            </button>
                                                        <?php endif; ?>
                                                    <?php endif; ?>
                                                    
                                                    <!-- Delete and View buttons for all classes -->
                                                    <button onclick="openDeleteExamModal(this)" class="btn btn-delete flex items-center">
                                                        <i class="fas fa-trash-alt mr-1"></i> <?php echo $lang['delete']; ?>
                                                    </button>
                                                    <button onclick="openViewResultsStatusModal(this)" class="btn btn-view flex items-center">
                                                        <i class="fas fa-eye mr-1"></i> <?php echo $lang['view']; ?>
                                                    </button>
                                                    
                                                    <!-- Individual class publish button -->
                                                    <?php
                                                    // Get this specific class's publishing status
                                                    $stmt_individual_class = $conn->prepare("
                                                        SELECT status 
                                                        FROM exam_class_status ecs
                                                        WHERE ecs.exam_id = ? 
                                                        AND ecs.class_id = ?
                                                        AND (ecs.stream_id IS NULL OR ecs.stream_id = 0)
                                                    ");
                                                    $stmt_individual_class->bind_param("ii", $exam['exam_id'], $exam['class_id_affected']);
                                                    $stmt_individual_class->execute();
                                                    $result_individual = $stmt_individual_class->get_result();
                                                    $class_status_row = $result_individual->fetch_assoc();
                                                    $stmt_individual_class->close();
                                                    
                                                    $class_status = $class_status_row['status'] ?? 'Draft';
                                                    $is_published = ($class_status === 'Published');
                                                    
                                                    if ($is_published): ?>
                                                        <button onclick="toggleClassStatusFromMainTable(<?php echo $exam['exam_id']; ?>, <?php echo $exam['class_id_affected']; ?>, 'unpublish')" 
                                                                class="btn btn-unpublish flex items-center">
                                                            <i class="fas fa-lock mr-1"></i> Unpublish
                                                        </button>
                                                    <?php else: ?>
                                                        <button onclick="toggleClassStatusFromMainTable(<?php echo $exam['exam_id']; ?>, <?php echo $exam['class_id_affected']; ?>, 'publish')" 
                                                                class="btn btn-publish flex items-center">
                                                            <i class="fas fa-unlock mr-1"></i> Publish
                                                        </button>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>

                <!-- Pending Reviews Section -->
                <div id="pendingReviewsSection" class="hidden">
                    <div class="content-card-header">
                        <h3 class="text-lg font-semibold text-orange-600">
                            <i class="fas fa-clock mr-2"></i>Exams Pending Review
                        </h3>
                        <p class="text-sm text-gray-600 mt-1">Review and approve exam submissions from teachers</p>
                    </div>

                    <div class="overflow-x-auto">
                        <table class="table-table">
                            <thead>
                                <tr>
                                    <th>Exam Name</th>
                                    <th>Teacher</th>
                                    <th>Term/Year</th>
                                    <th>Type</th>
                                    <th>Classes</th>
                                    <th>Subjects</th>
                                    <th>Submitted</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="pendingReviewsTableBody">
                                <tr>
                                    <td colspan="8" class="text-center py-8 text-gray-500">
                                        <i class="fas fa-spinner fa-spin text-2xl mb-2"></i>
                                        <br>Loading pending reviews...
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div id="mobile-footer-nav">
        <ul>
            <li>
                <a href="admin_dashboard.php" data-section="dashboard">
                    <i class="fas fa-th-large"></i>
                    <span><?php echo $lang['dashboard_title']; ?></span>
                </a>
            </li>
            <li>
                <a href="admin_user_management.php" data-section="user-management">
                    <i class="fas fa-users-cog"></i>
                    <span><?php echo $lang['user_management_title']; ?></span>
                </a>
            </li>
            <li>
                <a href="admin_students.php" data-section="students">
                    <i class="fas fa-user-graduate"></i>
                    <span><?php echo $lang['students']; ?></span>
                </a>
            </li>
            <li>
                <a href="#" id="moreMenuButton" data-section="more">
                    <i class="fas fa-ellipsis-h"></i>
                    <span><?php echo $lang['more_menu']; ?></span>
                </a>
            </li>
        </ul>
    </div>
    <div id="more-menu-modal">
        <div id="more-menu-modal-header">
            <h3><?php echo $lang['more_menu']; ?></h3>
            <button id="more-menu-close-btn"><i class="fas fa-times"></i></button>
        </div>
        <ul id="more-menu-list">
            <li><a href="admin_teachers.php"><i class="fas fa-chalkboard-teacher"></i> <?php echo $lang['teachers']; ?></a></li>
            <li><a href="admin_staff.php"><i class="fas fa-user-tie"></i> <?php echo $lang['staff']; ?></a></li>
            <li><a href="admin_classes.php"><i class="fas fa-chalkboard"></i> <?php echo $lang['classes']; ?></a></li>
            <li><a href="admin_subjects.php"><i class="fas fa-book"></i> <?php echo $lang['subjects']; ?></a></li>
            <li><a href="admin_exams.php"><i class="fas fa-file-alt"></i> <?php echo $lang['exams']; ?></a></li>
            <li><a href="admin_reports_printouts.php"><i class="fas fa-print"></i> <?php echo $lang['reports']; ?></a></li>
            <li><a href="admin_system_settings.php"><i class="fas fa-cog"></i> <?php echo $lang['settings']; ?></a></li>
            <li class="logout"><a href="logout.php"><i class="fas fa-sign-out-alt"></i> <?php echo $lang['log_out']; ?></a></li>
        </ul>
    </div>
    <div class="overlay" id="overlay"></div>

    <!-- Admin Exam Publishing Modals -->
    
    <!-- View Pending Exam Details Modal -->
    <div id="viewPendingExamModal" class="modal hidden">
        <div class="modal-content max-w-4xl">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 class="text-xl font-semibold mb-4 text-orange-600">Exam Details - Pending Review</h3>
            
            <div id="pendingExamDetails" class="mb-6">
                <!-- Details will be populated by JavaScript -->
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                <div class="bg-blue-50 p-4 rounded-lg">
                    <h4 class="font-semibold text-blue-800 mb-2">📚 Classes Affected</h4>
                    <div id="pendingExamClasses" class="text-sm text-blue-700">
                        <!-- Classes will be populated here -->
                    </div>
                </div>
                <div class="bg-green-50 p-4 rounded-lg">
                    <h4 class="font-semibold text-green-800 mb-2">📖 Subjects</h4>
                    <div id="pendingExamSubjects" class="text-sm text-green-700">
                        <!-- Subjects will be populated here -->
                    </div>
                </div>
            </div>

            <div class="flex justify-end space-x-3">
                <button type="button" onclick="closeModals()" class="btn-secondary">Close</button>
                <button type="button" onclick="openRejectExamModal()" class="btn btn-delete">
                    <i class="fas fa-times mr-2"></i>Request Changes
                </button>
                <button type="button" onclick="openApproveExamModal()" class="btn btn-publish">
                    <i class="fas fa-check mr-2"></i>Approve & Publish
                </button>
            </div>
        </div>
    </div>

    <!-- Approve Exam Modal -->
    <div id="approveExamModal" class="modal hidden">
        <div class="modal-content max-w-md">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 class="text-xl font-semibold mb-4 text-green-700">Approve & Publish Exam</h3>
            
            <div class="mb-4">
                <p class="text-gray-700 mb-3">Are you sure you want to approve and publish this exam?</p>
                <div class="bg-green-50 border border-green-200 rounded-lg p-3 mb-4">
                    <div class="flex items-start">
                        <i class="fas fa-check-circle text-green-600 mr-2 mt-1"></i>
                        <div>
                            <p class="text-sm text-green-800 font-medium">This action will:</p>
                            <ul class="text-xs text-green-700 mt-1 space-y-1">
                                <li>• Publish the exam for student access</li>
                                <li>• Lock ALL subjects for marks entry</li>
                                <li>• Make changes uneditable</li>
                                <li>• Require unpublishing to make changes</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            <form id="approveExamForm">
                <input type="hidden" id="approve_exam_id" name="exam_id">
                <div class="form-group mb-4">
                    <label for="approve_admin_notes" class="block text-sm font-medium text-gray-700 mb-1">
                        Admin Notes (Optional)
                    </label>
                    <textarea id="approve_admin_notes" name="admin_notes" rows="3" 
                              class="p-3 border rounded-lg w-full" 
                              placeholder="Add any notes about this approval..."></textarea>
                </div>
                
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeModals()" class="btn-secondary">Cancel</button>
                    <button type="submit" class="btn btn-publish">
                        <i class="fas fa-check mr-2"></i>Approve & Publish
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Reject Exam Modal -->
    <div id="rejectExamModal" class="modal hidden">
        <div class="modal-content max-w-md">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 class="text-xl font-semibold mb-4 text-orange-700">Request Changes</h3>
            
            <div class="mb-4">
                <p class="text-gray-700 mb-3">Are you sure you want to reject this exam submission?</p>
                <div class="bg-orange-50 border border-orange-200 rounded-lg p-3 mb-4">
                    <div class="flex items-start">
                        <i class="fas fa-exclamation-triangle text-orange-600 mr-2 mt-1"></i>
                        <div>
                            <p class="text-sm text-orange-800 font-medium">This action will:</p>
                            <ul class="text-xs text-orange-700 mt-1 space-y-1">
                                <li>• Return exam to Draft status</li>
                                <li>• Allow teacher to make changes</li>
                                <li>• Unlock marks entry</li>
                                <li>• Teacher can resubmit when ready</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            <form id="rejectExamForm">
                <input type="hidden" id="reject_exam_id" name="exam_id">
                <input type="hidden" id="reject_teacher_id" name="teacher_user_id">
                <div class="form-group mb-4">
                    <label for="reject_admin_notes" class="block text-sm font-medium text-gray-700 mb-1">
                        Feedback Required <span class="text-red-500">*</span>
                    </label>
                    <textarea id="reject_admin_notes" name="admin_notes" rows="4" 
                              class="p-3 border rounded-lg w-full" 
                              placeholder="Please provide specific feedback on what needs to be changed..."
                              required></textarea>
                    <p class="text-xs text-gray-500 mt-1">This feedback will be visible to the teacher</p>
                </div>
                
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeModals()" class="btn-secondary">Cancel</button>
                    <button type="submit" class="btn btn-delete">
                        <i class="fas fa-times mr-2"></i>Request Changes
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- View Publishing History Modal -->
    <div id="publishingHistoryModal" class="modal hidden">
        <div class="modal-content max-w-2xl">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 class="text-xl font-semibold mb-4 text-blue-600">Publishing History</h3>
            
            <div id="publishingHistoryContent" class="mb-4">
                <!-- History will be populated by JavaScript -->
            </div>

            <div class="flex justify-end">
                <button type="button" onclick="closeModals()" class="btn-secondary">Close</button>
            </div>
        </div>
    </div>

    <!-- Select Exam Type Modal -->
    <div id="selectExamTypeModal" class="modal hidden">
        <div class="modal-content max-w-md">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 class="text-xl font-semibold mb-6 text-center"><?php echo $lang['select_exam_type']; ?></h3>
            
            <div class="space-y-4">
                <div class="exam-type-option border border-gray-200 rounded-lg p-4 cursor-pointer hover:bg-gray-50 transition duration-200" onclick="selectExamType('normal')">
                    <div class="flex items-center mb-2">
                        <input type="radio" name="exam_type" value="normal" id="normal_exam_radio" class="mr-3">
                        <label for="normal_exam_radio" class="font-semibold text-lg text-blue-700"><?php echo $lang['normal_exam']; ?></label>
                    </div>
                    <p class="text-sm text-gray-600"><?php echo $lang['exam_type_description_normal']; ?></p>
                </div>

                <div class="exam-type-option border border-gray-200 rounded-lg p-4 cursor-pointer hover:bg-gray-50 transition duration-200" onclick="selectExamType('consolidated')">
                    <div class="flex items-center mb-2">
                        <input type="radio" name="exam_type" value="consolidated" id="consolidated_exam_radio" class="mr-3">
                        <label for="consolidated_exam_radio" class="font-semibold text-lg text-purple-700"><?php echo $lang['consolidated_exam']; ?></label>
                    </div>
                    <p class="text-sm text-gray-600"><?php echo $lang['exam_type_description_consolidated']; ?></p>
                </div>

                <div class="exam-type-option border border-gray-200 rounded-lg p-4 cursor-pointer hover:bg-gray-50 transition duration-200" onclick="selectExamType('term_summary')">
                    <div class="flex items-center mb-2">
                        <input type="radio" name="exam_type" value="term_summary" id="term_summary_exam_radio" class="mr-3">
                        <label for="term_summary_exam_radio" class="font-semibold text-lg text-orange-700"><?php echo $lang['term_summary_exam']; ?></label>
                    </div>
                    <p class="text-sm text-gray-600"><?php echo $lang['exam_type_description_term_summary']; ?></p>
                </div>

                <div class="exam-type-option border border-gray-200 rounded-lg p-4 cursor-pointer hover:bg-gray-50 transition duration-200" onclick="selectExamType('average_assessment')">
                    <div class="flex items-center mb-2">
                        <input type="radio" name="exam_type" value="average_assessment" id="average_assessment_radio" class="mr-3">
                        <label for="average_assessment_radio" class="font-semibold text-lg text-green-700"><?php echo $lang['average_assessment']; ?></label>
                    </div>
                    <p class="text-sm text-gray-600"><?php echo $lang['average_assessment_description']; ?></p>
                </div>
            </div>

            <div class="flex justify-end mt-6">
                <button id="continueExamTypeBtn" onclick="proceedWithSelectedExamType()" class="btn-primary" disabled>
                    <?php echo $lang['continue']; ?>
                </button>
            </div>
        </div>
    </div>

    <!-- Create Normal Exam Modal -->
    <div id="createNormalExamModal" class="modal hidden">
        <div class="modal-content">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-xl font-semibold"><?php echo $lang['create_new_exam']; ?> - <?php echo $lang['normal_exam']; ?></h3>
                <button onclick="backToExamTypeSelection()" class="btn-secondary">
                    <i class="fas fa-arrow-left mr-1"></i> <?php echo $lang['back']; ?>
                </button>
            </div>
            <form action="admin_exams.php" method="POST">
                <input type="hidden" name="action" value="create_normal_exam">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="form-group md:col-span-2">
                        <label for="normal_exam_name"><?php echo $lang['exam_name']; ?></label>
                        <input type="text" id="normal_exam_name" name="exam_name" required class="p-3 border rounded-lg w-full">
                    </div>
                    <div class="form-group">
                        <label for="normal_year">Academic Year</label>
                        <select id="normal_year" name="year" required class="p-3 border rounded-lg w-full">
                            <option value="">-- Select Year --</option>
                            <?php foreach ($academic_years_from_db as $year): ?>
                                <option value="<?php echo htmlspecialchars($year); ?>"><?php echo htmlspecialchars($year); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="normal_term"><?php echo $lang['term']; ?></label>
                        <select id="normal_term" name="term" required class="p-3 border rounded-lg w-full">
                            <option value="">-- Select Term --</option>
                            <?php foreach ($terms_from_db as $term): ?>
                                <option value="<?php echo htmlspecialchars($term); ?>"><?php echo htmlspecialchars($term); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group md:col-span-2">
                        <label for="normal_classes">Select Classes (Hold Ctrl/Cmd to select multiple)</label>
                        <div class="checkbox-group">
                            <?php foreach ($all_classes as $class): ?>
                                <label>
                                    <input type="checkbox" name="classes[]" value="<?php echo htmlspecialchars($class['class_id']); ?>">
                                    <?php echo htmlspecialchars($class['class_name']); ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <div class="form-group md:col-span-2">
                        <label for="normal_subjects">Select Subjects (Hold Ctrl/Cmd to select multiple)</label>
                        <div class="checkbox-group">
                            <?php foreach ($all_subjects as $subject): ?>
                                <label>
                                    <input type="checkbox" name="subjects[]" value="<?php echo htmlspecialchars($subject['subject_id']); ?>">
                                    <?php echo htmlspecialchars($subject['subject_name']); ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <div class="flex justify-end mt-6">
                    <button type="submit" class="btn-primary"><?php echo $lang['create_new_exam']; ?></button>
                </div>
            </form>
        </div>
    </div>

    <!-- Create Consolidated Exam Modal -->
    <div id="createConsolidatedExamModal" class="modal hidden">
        <div class="modal-content">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-xl font-semibold"><?php echo $lang['create_new_exam']; ?> - <?php echo $lang['consolidated_exam']; ?></h3>
                <button onclick="backToExamTypeSelection()" class="btn-secondary">
                    <i class="fas fa-arrow-left mr-1"></i> <?php echo $lang['back']; ?>
                </button>
            </div>
            <form action="admin_exams.php" method="POST">
                <input type="hidden" name="action" value="create_consolidated_exam">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="form-group md:col-span-2">
                        <label for="consolidated_exam_name"><?php echo $lang['exam_name']; ?></label>
                        <input type="text" id="consolidated_exam_name" name="exam_name" required class="p-3 border rounded-lg w-full">
                    </div>
                    <div class="form-group">
                        <label for="consolidated_year">Academic Year</label>
                        <select id="consolidated_year" name="year" required class="p-3 border rounded-lg w-full">
                            <option value="">-- Select Year --</option>
                            <?php foreach ($academic_years_from_db as $year): ?>
                                <option value="<?php echo htmlspecialchars($year); ?>"><?php echo htmlspecialchars($year); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="consolidated_term"><?php echo $lang['term']; ?></label>
                        <select id="consolidated_term" name="term" required class="p-3 border rounded-lg w-full">
                            <option value="">-- Select Term --</option>
                            <?php foreach ($terms_from_db as $term): ?>
                                <option value="<?php echo htmlspecialchars($term); ?>"><?php echo htmlspecialchars($term); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="first_exam_id"><?php echo $lang['select_first_exam']; ?></label>
                        <select id="first_exam_id" name="first_exam_id" required class="p-3 border rounded-lg w-full">
                            <option value="">-- Select First Exam --</option>
                            <!-- Populated by JavaScript based on term/year selection -->
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="second_exam_id"><?php echo $lang['select_second_exam']; ?></label>
                        <select id="second_exam_id" name="second_exam_id" required class="p-3 border rounded-lg w-full">
                            <option value="">-- Select Second Exam --</option>
                            <!-- Populated by JavaScript based on term/year selection -->
                        </select>
                    </div>
                </div>
                <div class="flex justify-end mt-6">
                    <button type="submit" class="btn-primary"><?php echo $lang['create_new_exam']; ?></button>
                </div>
            </form>
        </div>
    </div>

    <!-- Create Term Summary Exam Modal -->
    <div id="createTermSummaryExamModal" class="modal hidden">
        <div class="modal-content">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-xl font-semibold"><?php echo $lang['create_new_exam']; ?> - <?php echo $lang['term_summary_exam']; ?></h3>
                <button onclick="backToExamTypeSelection()" class="btn-secondary">
                    <i class="fas fa-arrow-left mr-1"></i> <?php echo $lang['back']; ?>
                </button>
            </div>
            <form action="admin_exams.php" method="POST">
                <input type="hidden" name="action" value="create_term_summary_exam">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="form-group md:col-span-2">
                        <label for="term_summary_exam_name"><?php echo $lang['exam_name']; ?></label>
                        <input type="text" id="term_summary_exam_name" name="exam_name" required class="p-3 border rounded-lg w-full">
                    </div>
                    <div class="form-group">
                        <label for="term_summary_year">Academic Year</label>
                        <select id="term_summary_year" name="year" required class="p-3 border rounded-lg w-full">
                            <option value="">-- Select Year --</option>
                            <?php foreach ($academic_years_from_db as $year): ?>
                                <option value="<?php echo htmlspecialchars($year); ?>"><?php echo htmlspecialchars($year); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="term_summary_term"><?php echo $lang['term']; ?></label>
                        <select id="term_summary_term" name="term" required class="p-3 border rounded-lg w-full">
                            <option value="">-- Select Term --</option>
                            <?php foreach ($terms_from_db as $term): ?>
                                <option value="<?php echo htmlspecialchars($term); ?>"><?php echo htmlspecialchars($term); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="integration_exam_id"><?php echo $lang['select_integration_activities']; ?></label>
                        <select id="integration_exam_id" name="integration_exam_id" required class="p-3 border rounded-lg w-full">
                            <option value="">-- Select Integration Activities --</option>
                            <!-- Populated by JavaScript based on term/year selection -->
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="normal_exam_id_for_summary"><?php echo $lang['select_normal_exam_for_summary']; ?></label>
                        <select id="normal_exam_id_for_summary" name="normal_exam_id" required class="p-3 border rounded-lg w-full">
                            <option value="">-- Select Normal Exam --</option>
                            <!-- Populated by JavaScript based on term/year selection -->
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="integration_weight"><?php echo $lang['integration_weight']; ?></label>
                        <input type="number" id="integration_weight" name="integration_weight" value="20" min="0" max="100" step="0.01" required class="p-3 border rounded-lg w-full">
                    </div>
                    <div class="form-group">
                        <label for="normal_weight"><?php echo $lang['normal_exam_weight']; ?></label>
                        <input type="number" id="normal_weight" name="normal_weight" value="80" min="0" max="100" step="0.01" required class="p-3 border rounded-lg w-full">
                    </div>
                </div>
                <div class="flex justify-end mt-6">
                    <button type="submit" class="btn-primary"><?php echo $lang['create_new_exam']; ?></button>
                </div>
            </form>
        </div>
    </div>

    <!-- Create Average Assessment Modal -->
    <div id="createAverageAssessmentModal" class="modal hidden">
        <div class="modal-content">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-xl font-semibold"><?php echo $lang['create_new_exam']; ?> - <?php echo $lang['average_assessment']; ?></h3>
                <button onclick="backToExamTypeSelection()" class="btn-secondary">
                    <i class="fas fa-arrow-left mr-1"></i> <?php echo $lang['back']; ?>
                </button>
            </div>
            <form action="admin_exams.php" method="POST">
                <input type="hidden" name="action" value="create_average_assessment">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="form-group md:col-span-2">
                        <label for="average_assessment_exam_name"><?php echo $lang['exam_name']; ?></label>
                        <input type="text" id="average_assessment_exam_name" name="exam_name" required class="p-3 border rounded-lg w-full">
                    </div>
                    <div class="form-group">
                        <label for="average_assessment_year">Academic Year</label>
                        <select id="average_assessment_year" name="year" required class="p-3 border rounded-lg w-full">
                            <option value="">-- Select Year --</option>
                            <?php foreach ($academic_years_from_db as $year): ?>
                                <option value="<?php echo htmlspecialchars($year); ?>"><?php echo htmlspecialchars($year); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="average_assessment_term"><?php echo $lang['term']; ?></label>
                        <select id="average_assessment_term" name="term" required class="p-3 border rounded-lg w-full">
                            <option value="">-- Select Term --</option>
                            <?php foreach ($terms_from_db as $term): ?>
                                <option value="<?php echo htmlspecialchars($term); ?>"><?php echo htmlspecialchars($term); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group md:col-span-2">
                        <label for="average_assessment_classes">Select Classes (Hold Ctrl/Cmd to select multiple)</label>
                        <div class="checkbox-group">
                            <?php foreach ($all_classes as $class): ?>
                                <label>
                                    <input type="checkbox" name="classes[]" value="<?php echo htmlspecialchars($class['class_id']); ?>">
                                    <?php echo htmlspecialchars($class['class_name']); ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <div class="form-group md:col-span-2">
                        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                            <div class="flex items-center mb-2">
                                <i class="fas fa-info-circle text-blue-600 mr-2"></i>
                                <span class="font-semibold text-blue-800">Information</span>
                            </div>
                            <p class="text-sm text-blue-700">
                                <?php echo $lang['average_assessment_description']; ?> This will automatically include all subjects that have integration activity marks for the selected term and year.
                            </p>
                        </div>
                    </div>
                </div>
                <div class="flex justify-end mt-6">
                    <button type="submit" class="btn-primary"><?php echo $lang['create_new_exam']; ?></button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Exam Modal -->
    <div id="editExamModal" class="modal hidden">
        <div class="modal-content">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 class="text-xl font-semibold mb-4"><?php echo $lang['edit']; ?> Exam</h3>
            <form action="admin_exams.php" method="POST">
                <input type="hidden" name="action" value="edit_exam">
                <input type="hidden" name="exam_id" id="edit_exam_id">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="form-group md:col-span-2">
                        <label for="edit_exam_name"><?php echo $lang['exam_name']; ?></label>
                        <input type="text" id="edit_exam_name" name="exam_name" required class="p-3 border rounded-lg w-full">
                    </div>
                    <div class="form-group">
                        <label for="edit_year">Academic Year</label>
                        <select id="edit_year" name="year" required class="p-3 border rounded-lg w-full">
                            <option value="">-- Select Year --</option>
                            <?php foreach ($academic_years_from_db as $year): ?>
                                <option value="<?php echo htmlspecialchars($year); ?>"><?php echo htmlspecialchars($year); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="edit_term"><?php echo $lang['term']; ?></label>
                        <select id="edit_term" name="term" required class="p-3 border rounded-lg w-full">
                            <option value="">-- Select Term --</option>
                            <?php foreach ($terms_from_db as $term): ?>
                                <option value="<?php echo htmlspecialchars($term); ?>"><?php echo htmlspecialchars($term); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group md:col-span-2">
                        <label for="edit_classes">Select Classes (Hold Ctrl/Cmd to select multiple)</label>
                        <div id="edit_classes_checkbox_group" class="checkbox-group">
                            <?php foreach ($all_classes as $class): ?>
                                <label>
                                    <input type="checkbox" name="classes[]" value="<?php echo htmlspecialchars($class['class_id']); ?>">
                                    <?php echo htmlspecialchars($class['class_name']); ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <div class="form-group md:col-span-2">
                        <label for="edit_subjects">Select Subjects (Hold Ctrl/Cmd to select multiple)</label>
                        <div id="edit_subjects_checkbox_group" class="checkbox-group">
                            <?php foreach ($all_subjects as $subject): ?>
                                <label>
                                    <input type="checkbox" name="subjects[]" value="<?php echo htmlspecialchars($subject['subject_id']); ?>">
                                    <?php echo htmlspecialchars($subject['subject_name']); ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <div class="flex justify-end mt-6">
                    <button type="submit" class="btn-primary">Update Exam</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Delete Exam Confirmation Modal -->
    <div id="deleteExamModal" class="modal hidden">
        <div class="modal-content max-w-sm">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 class="text-xl font-semibold mb-4 text-red-700">Confirm Deletion</h3>
            <p class="mb-6">Are you sure you want to delete exam "<strong id="delete_exam_name_display"></strong>"? This action cannot be undone.</p>
            <form action="admin_exams.php" method="POST">
                <input type="hidden" name="action" value="delete_exam">
                <input type="hidden" name="exam_id" id="delete_exam_id">
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeModals()" class="btn-secondary">Cancel</button>
                    <button type="submit" class="bg-red-600 text-white px-4 py-2 rounded-lg shadow-md hover:bg-red-700 transition duration-200"><?php echo $lang['delete']; ?> Exam</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Publish Exam Confirmation Modal -->
    <div id="publishConfirmModal" class="modal hidden">
        <div class="modal-content max-w-sm">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 class="text-xl font-semibold mb-4 text-green-700">Confirm Publish</h3>
            <p class="mb-4">Are you sure you want to <strong>publish</strong> exam "<strong id="publish_exam_name_display"></strong>"?</p>
            <p class="text-sm text-gray-600 mb-4">Publishing this exam will:</p>
            <ul class="text-sm text-gray-600 mb-6 space-y-1">
                <li><i class="fas fa-lock text-red-500 mr-2"></i>Lock ALL subjects in this exam for marks entry</li>
                <li id="integrationActivitiesWarning" style="display: none;"><i class="fas fa-lightbulb text-orange-500 mr-2"></i>Lock ALL integration activities for this exam</li>
                <li><i class="fas fa-eye-slash text-blue-500 mr-2"></i>Hide the exam from teachers' marks entry interface</li>
                <li><i class="fas fa-shield-alt text-green-500 mr-2"></i>Only administrators can unlock by unpublishing</li>
            </ul>
            <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-3 mb-6">
                <div class="flex items-center">
                    <i class="fas fa-exclamation-triangle text-yellow-600 mr-2"></i>
                    <span class="text-sm text-yellow-800 font-medium">This action cannot be undone without admin intervention.</span>
                </div>
            </div>
            <form action="admin_exams.php" method="POST">
                <input type="hidden" name="action" value="confirm_publish_exam">
                <input type="hidden" name="exam_id" id="publish_exam_id">
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeModals()" class="btn-secondary">Cancel</button>
                    <button type="submit" class="btn btn-publish"><?php echo $lang['publish']; ?> Exam</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Unpublish Exam Confirmation Modal -->
    <div id="unpublishConfirmModal" class="modal hidden">
        <div class="modal-content max-w-sm">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 class="text-xl font-semibold mb-4 text-orange-700">Confirm Unpublish</h3>
            <p class="mb-4">Are you sure you want to <strong>unpublish</strong> exam "<strong id="unpublish_exam_name_display"></strong>"?</p>
            <p class="text-sm text-gray-600 mb-4">Unpublishing this exam will:</p>
            <ul class="text-sm text-gray-600 mb-6 space-y-1">
                <li><i class="fas fa-unlock text-green-500 mr-2"></i>Unlock ALL subjects in this exam for marks entry</li>
                <li id="integrationActivitiesUnlockWarning" style="display: none;"><i class="fas fa-lightbulb text-green-500 mr-2"></i>Unlock ALL integration activities for this exam</li>
                <li><i class="fas fa-eye text-blue-500 mr-2"></i>Show the exam to teachers for marks entry</li>
                <li><i class="fas fa-edit text-orange-500 mr-2"></i>Allow teachers to edit and add new marks</li>
            </ul>
            <div class="bg-blue-50 border border-blue-200 rounded-lg p-3 mb-6">
                <div class="flex items-center">
                    <i class="fas fa-info-circle text-blue-600 mr-2"></i>
                    <span class="text-sm text-blue-800 font-medium">Teachers will be able to modify marks again after unpublishing.</span>
                </div>
            </div>
            <form action="admin_exams.php" method="POST">
                <input type="hidden" name="action" value="unpublish_exam">
                <input type="hidden" name="exam_id" id="unpublish_exam_id">
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeModals()" class="btn-secondary">Cancel</button>
                    <button type="submit" class="btn btn-unpublish"><?php echo $lang['unpublish']; ?> Exam</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Add Grading System Modal -->
    <div id="addGradingSystemModal" class="modal hidden">
        <div class="modal-content">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 class="text-xl font-semibold mb-4">Add <?php echo $lang['grading_system']; ?></h3>
            <form action="admin_exams.php" method="POST">
                <input type="hidden" name="action" value="add_grading_system">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="form-group md:col-span-2">
                        <label for="grade_name">Grading System Name</label>
                        <input type="text" id="grade_name" name="grade_name" required class="p-3 border rounded-lg w-full">
                    </div>
                    <div class="form-group">
                        <label for="grading_academic_year">Academic Year</label>
                        <select id="grading_academic_year" name="grading_academic_year" class="p-3 border rounded-lg w-full">
                            <option value="">-- All Years --</option>
                            <?php foreach ($academic_years_from_db as $year): ?>
                                <option value="<?php echo htmlspecialchars($year); ?>"><?php echo htmlspecialchars($year); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="grading_term"><?php echo $lang['term']; ?></label>
                        <select id="grading_term" name="grading_term" class="p-3 border rounded-lg w-full">
                            <option value="">-- All Terms --</option>
                            <?php foreach ($terms_from_db as $term): ?>
                                <option value="<?php echo htmlspecialchars($term); ?>"><?php echo htmlspecialchars($term); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="grading_class_id">Apply to Class (Optional)</label>
                        <select id="grading_class_id" name="grading_class_id" class="p-3 border rounded-lg w-full">
                            <option value="0">-- All Classes --</option>
                            <?php foreach ($all_classes as $class): ?>
                                <option value="<?php echo htmlspecialchars($class['class_id']); ?>"><?php echo htmlspecialchars($class['class_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="grading_subject_id">Apply to Subject (Optional)</label>
                        <select id="grading_subject_id" name="grading_subject_id" class="p-3 border rounded-lg w-full">
                            <option value="0">-- All Subjects --</option>
                            <?php foreach ($all_subjects as $subject): ?>
                                <option value="<?php echo htmlspecialchars($subject['subject_id']); ?>"><?php echo htmlspecialchars($subject['subject_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <h4 class="text-lg font-semibold mt-6 mb-3">Grade Ranges</h4>
                <div id="gradeRangesContainer">
                    <div class="grid grid-cols-5 gap-2 items-end mb-2">
                        <div class="form-group col-span-1">
                            <label for="min_score_0">Min Score</label>
                            <input type="number" id="min_score_0" name="min_score_0" step="0.01" required class="p-2 border rounded-lg w-full">
                        </div>
                        <div class="form-group col-span-1">
                            <label for="max_score_0">Max Score</label>
                            <input type="number" id="max_score_0" name="max_score_0" step="0.01" required class="p-2 border rounded-lg w-full">
                        </div>
                        <div class="form-group col-span-1">
                            <label for="grade_letter_0">Grade Letter</label>
                            <input type="text" id="grade_letter_0" name="grade_letter_0" required class="p-2 border rounded-lg w-full">
                        </div>
                        <div class="form-group col-span-1">
                            <label for="remarks_0">Remarks</label>
                            <input type="text" id="remarks_0" name="remarks_0" class="p-2 border rounded-lg w-full">
                        </div>
                        <div class="col-span-1">
                            <button type="button" onclick="addGradeRangeRow()" class="btn-primary w-full px-2 py-2 text-sm flex items-center justify-center">
                                <i class="fas fa-plus mr-1"></i> Add
                            </button>
                        </div>
                    </div>
                </div>

                <div class="flex justify-end mt-6">
                    <button type="submit" class="btn-primary">Save <?php echo $lang['grading_system']; ?></button>
                </div>
            </form>
        </div>
    </div>

    <!-- View Results Status Modal -->
    <div id="viewResultsStatusModal" class="modal hidden">
        <div class="modal-content">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 class="text-xl font-semibold mb-4">Results Status for Exam: <span id="view_exam_name_display" class="text-indigo-700"></span></h3>
            
            <div class="form-group mb-4">
                <label for="view_class_select" class="block font-medium text-gray-700 mb-2">Select Class:</label>
                <select id="view_class_select" class="p-2 border rounded-lg w-full text-sm">
                    <option value="">-- Select a Class --</option>
                </select>
            </div>

            <div class="form-group mb-4">
                <label for="view_stream_select" class="block font-medium text-gray-700 mb-2">Select Stream:</label>
                <select id="view_stream_select" class="p-2 border rounded-lg w-full text-sm">
                    <option value="">-- Select a Stream --</option>
                </select>
            </div>

            <div class="table-responsive-wrapper mb-4">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Subject</th>
                            <th>Students Enrolled</th>
                            <th>Results Entered</th>
                            <th><?php echo $lang['status']; ?></th>
                        </tr>
                    </thead>
                    <tbody id="viewResultsStatusTableBody">
                        <tr><td colspan="4" class="text-center py-4 text-gray-500">Please select a class and stream to view results status.</td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- View Grading Scales Modal -->
    <div id="viewGradingScalesModal" class="modal hidden">
        <div class="modal-content">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 class="text-xl font-semibold mb-4"><?php echo $lang['view_grading_scales']; ?></h3>
            
            <!-- Filter Controls for Grading Scales -->
            <div class="filter-controls grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <div class="form-group">
                    <label for="filter_grade_academic_year" class="text-sm">Academic Year</label>
                    <select id="filter_grade_academic_year" class="p-2 border rounded-md w-full">
                        <option value="">All Years</option>
                        <?php foreach ($academic_years_from_db as $year): ?>
                            <option value="<?php echo htmlspecialchars($year); ?>"><?php echo htmlspecialchars($year); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="filter_grade_term" class="text-sm"><?php echo $lang['term']; ?></label>
                    <select id="filter_grade_term" class="p-2 border rounded-md w-full">
                        <option value="">All Terms</option>
                        <?php foreach ($terms_from_db as $term): ?>
                            <option value="<?php echo htmlspecialchars($term); ?>"><?php echo htmlspecialchars($term); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="filter_grade_class_id" class="text-sm">Class</label>
                    <select id="filter_grade_class_id" class="p-2 border rounded-md w-full">
                        <option value="0">All Classes</option>
                        <?php foreach ($all_classes as $class): ?>
                            <option value="<?php echo htmlspecialchars($class['class_id']); ?>"><?php echo htmlspecialchars($class['class_name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="filter_grade_subject_id" class="text-sm">Subject</label>
                    <select id="filter_grade_subject_id" class="p-2 border rounded-md w-full">
                        <option value="0">All Subjects</option>
                        <?php foreach ($all_subjects as $subject): ?>
                            <option value="<?php echo htmlspecialchars($subject['subject_id']); ?>"><?php echo htmlspecialchars($subject['subject_name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="md:col-span-2 lg:col-span-4 flex justify-end">
                    <button onclick="fetchAndDisplayGradingScales()" class="btn-primary px-4 py-2">Apply Filters</button>
                    <button onclick="resetGradingScalesFilters()" class="btn-secondary ml-2 px-4 py-2">Reset Filters</button>
                </div>
            </div>

            <div class="table-responsive-wrapper">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th><?php echo $lang['grading_system']; ?></th>
                            <th><?php echo $lang['year']; ?></th>
                            <th><?php echo $lang['term']; ?></th>
                            <th>Class</th>
                            <th>Subject</th>
                            <th>Grade Letter</th>
                            <th>Grade</th>
                            <th>Min Score</th>
                            <th>Max Score</th>
                            <th>Remarks</th>
                            <th><?php echo $lang['last_updated_by']; ?></th>
                            <th><?php echo $lang['actions']; ?></th>
                        </tr>
                    </thead>
                    <tbody id="gradingScalesTableBody">
                        <tr><td colspan="12" class="text-center py-4 text-gray-500">No grading scales found. Apply filters or create new ones.</td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Delete Grading Scale Confirmation Modal -->
    <div id="deleteGradingScaleModal" class="modal hidden">
        <div class="modal-content max-w-sm">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 class="text-xl font-semibold mb-4 text-red-700">Confirm Deletion</h3>
            <p class="mb-6">Are you sure you want to delete the grading scale "<strong id="delete_grading_scale_name_display"></strong>"? This action cannot be undone.</p>
            <form action="admin_exams.php" method="POST">
                <input type="hidden" name="action" value="delete_grading_scale">
                <input type="hidden" name="grading_scale_id" id="delete_grading_scale_id">
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeModals()" class="btn-secondary">Cancel</button>
                    <button type="submit" class="bg-red-600 text-white px-4 py-2 rounded-lg shadow-md hover:bg-red-700 transition duration-200"><?php echo $lang['delete']; ?> Scale</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Grading Scale Modal -->
    <div id="editGradingScaleModal" class="modal hidden">
        <div class="modal-content max-w-2xl">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 class="text-xl font-semibold mb-4">Edit Grading Scale</h3>
            <form action="admin_exams.php" method="POST">
                <input type="hidden" name="action" value="update_grading_scale">
                <input type="hidden" name="edit_grading_scale_id" id="edit_grading_scale_id">
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    <div class="form-group">
                        <label for="edit_grade_name" class="block text-sm font-medium text-gray-700 mb-1">Grading System Name</label>
                        <input type="text" id="edit_grade_name" class="p-2 border rounded-lg w-full bg-gray-100" readonly>
                    </div>
                    <div class="form-group">
                        <label for="edit_academic_year" class="block text-sm font-medium text-gray-700 mb-1">Academic Year</label>
                        <input type="text" id="edit_academic_year" class="p-2 border rounded-lg w-full bg-gray-100" readonly>
                    </div>
                    <div class="form-group">
                        <label for="edit_term_name" class="block text-sm font-medium text-gray-700 mb-1">Term</label>
                        <input type="text" id="edit_term_name" class="p-2 border rounded-lg w-full bg-gray-100" readonly>
                    </div>
                    <div class="form-group">
                        <label for="edit_class_name" class="block text-sm font-medium text-gray-700 mb-1">Class</label>
                        <input type="text" id="edit_class_name" class="p-2 border rounded-lg w-full bg-gray-100" readonly>
                    </div>
                    <div class="form-group md:col-span-2">
                        <label for="edit_subject_name" class="block text-sm font-medium text-gray-700 mb-1">Subject</label>
                        <input type="text" id="edit_subject_name" class="p-2 border rounded-lg w-full bg-gray-100" readonly>
                    </div>
                </div>

                <h4 class="text-lg font-semibold mt-4 mb-3">Grade Range Details</h4>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="form-group">
                        <label for="edit_min_score" class="block text-sm font-medium text-gray-700 mb-1">Min Score <span class="text-red-500">*</span></label>
                        <input type="number" id="edit_min_score" name="edit_min_score" step="0.01" required class="p-2 border rounded-lg w-full">
                    </div>
                    <div class="form-group">
                        <label for="edit_max_score" class="block text-sm font-medium text-gray-700 mb-1">Max Score <span class="text-red-500">*</span></label>
                        <input type="number" id="edit_max_score" name="edit_max_score" step="0.01" required class="p-2 border rounded-lg w-full">
                    </div>
                    <div class="form-group">
                        <label for="edit_grade_letter" class="block text-sm font-medium text-gray-700 mb-1">Grade Letter <span class="text-red-500">*</span></label>
                        <input type="text" id="edit_grade_letter" name="edit_grade_letter" required class="p-2 border rounded-lg w-full">
                    </div>
                    <div class="form-group">
                        <label for="edit_grade" class="block text-sm font-medium text-gray-700 mb-1">Grade</label>
                        <input type="text" id="edit_grade" name="edit_grade" placeholder="D1, D2, etc." class="p-2 border rounded-lg w-full">
                    </div>
                    <div class="form-group md:col-span-2">
                        <label for="edit_remarks" class="block text-sm font-medium text-gray-700 mb-1">Remarks</label>
                        <input type="text" id="edit_remarks" name="edit_remarks" class="p-2 border rounded-lg w-full">
                    </div>
                </div>

                <div class="flex justify-end space-x-3 mt-6">
                    <button type="button" onclick="closeModals()" class="btn-secondary">Cancel</button>
                    <button type="submit" class="btn-primary">Update Grading Scale</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Publish Assessment Streams Modal -->
    <div id="publishAssessmentModal" class="modal hidden">
        <div class="modal-content">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 class="text-xl font-semibold mb-4"><?php echo $lang['publish_assessment']; ?>: <span id="assessment_name_display" class="text-green-700"></span></h3>
            
            <div class="form-group mb-4">
                <label for="assessment_class_select" class="block font-medium text-gray-700 mb-2">Select Class:</label>
                <select id="assessment_class_select" class="p-2 border rounded-lg w-full text-sm" onchange="loadStreamsForAssessment()">
                    <option value="">-- Select a Class --</option>
                </select>
            </div>

            <div class="table-responsive-wrapper mb-4">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th><?php echo $lang['stream_name']; ?></th>
                            <th><?php echo $lang['total_students']; ?></th>
                            <th><?php echo $lang['actions']; ?></th>
                        </tr>
                    </thead>
                    <tbody id="assessmentStreamsTableBody">
                        <tr><td colspan="3" class="text-center py-4 text-gray-500">Please select a class to view streams.</td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Stream Assessment Details Modal -->
    <div id="streamAssessmentDetailsModal" class="modal hidden">
        <div class="modal-content">
            <span class="close-button" onclick="closeModals()">&times;</span>
            <h3 class="text-xl font-semibold mb-4"><?php echo $lang['subjects_marks_summary']; ?>: <span id="stream_details_title" class="text-indigo-700"></span></h3>
            
            <div class="table-responsive-wrapper mb-4">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Class</th>
                            <th>Subject</th>
                            <th><?php echo $lang['subject_teacher']; ?></th>
                            <th><?php echo $lang['students_with_marks']; ?></th>
                            <th><?php echo $lang['marks_status']; ?></th>
                        </tr>
                    </thead>
                    <tbody id="streamAssessmentDetailsTableBody">
                        <tr><td colspan="5" class="text-center py-4 text-gray-500">Loading assessment details...</td></tr>
                    </tbody>
                </table>
            </div>
            <div class="flex justify-end mt-4">
                <button onclick="closeModals()" class="btn-secondary">Close</button>
            </div>
        </div>
    </div>

    <!-- Modern Success Modal -->
    <div id="successModal" class="modal success-modal hidden">
        <div class="modal-content">
            <div class="success-icon-wrapper">
                <svg class="success-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
                    <circle cx="26" cy="26" r="25" fill="none" stroke="white" stroke-width="4"></circle>
                    <path d="M14.1 27.2l7.1 7.2 16.7-16.8" fill="white"></path>
                </svg>
            </div>
            <h2 class="success-title" id="successTitle">Success!</h2>
            <p class="success-message" id="successMessage">Operation completed successfully.</p>
            <div class="modal-footer">
                <button onclick="closeModernModal('successModal')" class="btn-modal btn-modal-success">OK</button>
            </div>
        </div>
    </div>

    <!-- Modern Error Modal -->
    <div id="errorModal" class="modal error-modal hidden">
        <div class="modal-content">
            <div class="error-icon-wrapper">
                <svg class="error-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
                    <circle cx="26" cy="26" r="25" fill="none" stroke="white" stroke-width="4"></circle>
                    <path d="M16 16L36 36M36 16L16 36" fill="none" stroke="white" stroke-width="4" stroke-linecap="round"></path>
                </svg>
            </div>
            <h2 class="error-title" id="errorTitle">Error</h2>
            <p class="error-message" id="errorMessage">An error occurred. Please try again.</p>
            <div class="modal-footer">
                <button onclick="closeModernModal('errorModal')" class="btn-modal btn-modal-danger">OK</button>
            </div>
        </div>
    </div>

    <!-- Modern Warning Modal -->
    <div id="warningModal" class="modal warning-modal hidden">
        <div class="modal-content">
            <div class="warning-icon-wrapper">
                <svg class="warning-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
                    <circle cx="26" cy="26" r="25" fill="none" stroke="white" stroke-width="4"></circle>
                    <path d="M26 14V28M26 36V38" fill="none" stroke="white" stroke-width="4" stroke-linecap="round"></path>
                </svg>
            </div>
            <h2 class="warning-title" id="warningTitle">Warning</h2>
            <p class="warning-message" id="warningMessage">Please review your selection.</p>
            <div class="modal-footer">
                <button onclick="closeModernModal('warningModal')" class="btn-modal btn-modal-secondary">Cancel</button>
                <button id="warningConfirmBtn" class="btn-modal btn-modal-warning">Continue</button>
            </div>
        </div>
    </div>

    <script>
        // PHP data passed to JavaScript
        const allExamsData = <?php echo json_encode($exams_list); ?>;
        const allAcademicYearsFromDb = <?php echo json_encode($academic_years_from_db); ?>;
        const allTermsFromDb = <?php echo json_encode($terms_from_db); ?>;
        const allClassesData = <?php echo json_encode($all_classes); ?>;
        const allSubjectsData = <?php echo json_encode($all_subjects); ?>;
        const allStreamsData = <?php echo json_encode($all_streams); ?>;
        
        // Debug function to check available data
        function debugExamData() {
            console.log('All Exams Data:', allExamsData);
            if (allExamsData && Array.isArray(allExamsData)) {
                console.log('Total exams:', allExamsData.length);
                
                // Show detailed exam information
                allExamsData.forEach((exam, index) => {
                    console.log(`Exam ${index + 1}:`, {
                        id: exam.exam_id,
                        name: exam.exam_name,
                        term: exam.term,
                        year: exam.year,
                        type: exam.exam_type,
                        status: exam.status
                    });
                });
                
                const examTypes = [...new Set(allExamsData.map(exam => exam.exam_type))];
                console.log('Available exam types:', examTypes);
                
                const termsAvailable = [...new Set(allExamsData.map(exam => exam.term))];
                console.log('Available terms:', termsAvailable);
                
                const yearsAvailable = [...new Set(allExamsData.map(exam => exam.year))];
                console.log('Available years:', yearsAvailable);
                
                // Updated to include '0' as a normal exam type
                const normalExams = allExamsData.filter(exam => 
                    exam.exam_type === 'Normal' || 
                    exam.exam_type === '0' ||
                    exam.exam_type === null || 
                    exam.exam_type === '' || 
                    exam.exam_type === undefined
                );
                console.log('Normal/null/0 exams:', normalExams.length);
                
                const avgAssessmentExams = allExamsData.filter(exam => exam.exam_type === 'Average Assessment');
                console.log('Average Assessment exams:', avgAssessmentExams.length);
                
                // Show which exams will be available for TERM 3, 2025 (based on your data)
                const term3_2025_exams = allExamsData.filter(exam => 
                    exam.term === 'TERM 3' && 
                    exam.year === '2025' && 
                    (exam.exam_type === 'Normal' || exam.exam_type === '0' || exam.exam_type === null || exam.exam_type === '' || exam.exam_type === undefined)
                );
                console.log('Exams available for TERM 3, 2025:', term3_2025_exams);
                
            } else {
                console.error('allExamsData is not an array or is undefined');
            }
        }
        
        // Call debug function on page load
        debugExamData();
        
        const schoolNameForJs = "<?php echo $school_name_for_js; ?>";
        const currentUsername = "<?php echo $username; ?>";
        const currentLang = "<?php echo $current_lang; ?>";

        // Language & Translation Logic
        const all_languages_js = <?php echo json_encode($all_languages); ?>;

        function getTranslation(key) {
            return all_languages_js[localStorage.getItem('appLang') || 'en'][key] || key;
        }

        function applyTranslations(lang) {
            const t = all_languages_js[lang];

            // Sidebar & General
            document.getElementById('dashboardLink').innerHTML = `<i class="fas fa-th-large"></i> ${t.dashboard_title}`;
            document.getElementById('userManagementLink').innerHTML = `<i class="fas fa-users-cog"></i> ${t.user_management_title}`;
            document.getElementById('studentsLink').innerHTML = `<i class="fas fa-user-graduate"></i> ${t.students}`;
            document.getElementById('teachersLink').innerHTML = `<i class="fas fa-chalkboard-teacher"></i> ${t.teachers}`;
            document.getElementById('staffLink').innerHTML = `<i class="fas fa-user-tie"></i> ${t.staff}`;
            document.getElementById('classesLink').innerHTML = `<i class="fas fa-chalkboard"></i> ${t.classes}`;
            document.getElementById('subjectsLink').innerHTML = `<i class="fas fa-book"></i> ${t.subjects}`;
            document.getElementById('examsLink').innerHTML = `<i class="fas fa-file-alt"></i> ${t.exams}`;
            document.getElementById('reportsLink').innerHTML = `<i class="fas fa-print"></i> ${t.reports}`;
            document.getElementById('systemSettingsLink').innerHTML = `<i class="fas fa-cog"></i> ${t.settings}`;
            document.getElementById('logoutLinkSidebar').innerHTML = `<i class="fas fa-sign-out-alt"></i> ${t.log_out}`;
            
            // Header
            document.getElementById('searchPlaceholder').placeholder = t.search_placeholder;

            // Mobile Footer
            const footerLinks = document.getElementById('mobile-footer-nav').getElementsByTagName('a');
            for (let link of footerLinks) {
                const section = link.getAttribute('data-section');
                if (section === 'dashboard') link.querySelector('span').textContent = t.dashboard_title;
                if (section === 'user-management') link.querySelector('span').textContent = t.user_management_title;
                if (section === 'students') link.querySelector('span').textContent = t.students;
                if (section === 'more') link.querySelector('span').textContent = t.more_menu;
            }

            // More Menu Modal
            document.getElementById('more-menu-modal-header').querySelector('h3').textContent = t.more_menu;
            document.querySelector('#more-menu-list a[href="admin_teachers.php"]').innerHTML = `<i class="fas fa-chalkboard-teacher"></i> ${t.teachers}`;
            document.querySelector('#more-menu-list a[href="admin_staff.php"]').innerHTML = `<i class="fas fa-user-tie"></i> ${t.staff}`;
            document.querySelector('#more-menu-list a[href="admin_classes.php"]').innerHTML = `<i class="fas fa-chalkboard"></i> ${t.classes}`;
            document.querySelector('#more-menu-list a[href="admin_subjects.php"]').innerHTML = `<i class="fas fa-book"></i> ${t.subjects}`;
            document.querySelector('#more-menu-list a[href="admin_exams.php"]').innerHTML = `<i class="fas fa-file-alt"></i> ${t.exams}`;
            document.querySelector('#more-menu-list a[href="admin_reports_printouts.php"]').innerHTML = `<i class="fas fa-print"></i> ${t.reports}`;
            document.querySelector('#more-menu-list a[href="admin_system_settings.php"]').innerHTML = `<i class="fas fa-cog"></i> ${t.settings}`;
            document.querySelector('#more-menu-list a[href="logout.php"]').innerHTML = `<i class="fas fa-sign-out-alt"></i> ${t.log_out}`;
        }

        // Global DOM element references (initialized on DOMContentLoaded)
        let examTableBody, overlay, sidebar, dashboardContainer, messageBox, filterAcademicYear, filterTerm;
        let pendingReviewsTableBody, pendingReviewsSection;
        let currentPendingExam = null;
        let filterGradeAcademicYear, filterGradeTerm, filterGradeClassId, filterGradeSubjectId, gradingScalesTableBody;

        // Wait for DOM to be fully loaded before accessing elements
        document.addEventListener('DOMContentLoaded', function() {
            // Get references to DOM elements
            examTableBody = document.getElementById('examTableBody');
            overlay = document.getElementById('overlay');
            sidebar = document.querySelector('.sidebar');
            dashboardContainer = document.getElementById('dashboardContainer');
            messageBox = document.getElementById('messageBox');
            filterAcademicYear = document.getElementById('filter_academic_year');
            filterTerm = document.getElementById('filter_term');

            // References for grading scales modal filters
            filterGradeAcademicYear = document.getElementById('filter_grade_academic_year');
            filterGradeTerm = document.getElementById('filter_grade_term');
            filterGradeClassId = document.getElementById('filter_grade_class_id');
            filterGradeSubjectId = document.getElementById('filter_grade_subject_id');
            gradingScalesTableBody = document.getElementById('gradingScalesTableBody');

            // References for pending reviews section
            pendingReviewsTableBody = document.getElementById('pendingReviewsTableBody');
            pendingReviewsSection = document.getElementById('pendingReviewsSection');

            // Language Selector Logic
            const languageSelect = document.getElementById('languageSelect');
            const savedLang = localStorage.getItem('appLang') || currentLang; 

            if (languageSelect) {
                languageSelect.value = savedLang;
                
                languageSelect.addEventListener('change', function() {
                    const newLang = this.value;
                    localStorage.setItem('appLang', newLang);
                    
                    let url = window.location.pathname;
                    let params = new URLSearchParams(window.location.search);
                    params.set('lang', newLang);
                    window.location.href = url + '?' + params.toString();
                });
            }

            // --- Mobile Footer Modal Logic ---
            const moreMenuButton = document.getElementById('moreMenuButton');
            const moreMenuModal = document.getElementById('more-menu-modal');
            const moreMenuCloseBtn = document.getElementById('more-menu-close-btn');

            function toggleMoreMenu(show) {
                const overlayElement = document.getElementById('overlay');
                if (show) {
                    if (moreMenuModal) moreMenuModal.classList.add('show');
                    if (overlayElement) overlayElement.classList.add('show');
                    document.body.style.overflow = 'hidden';
                } else {
                    if (moreMenuModal) moreMenuModal.classList.remove('show');
                    if (overlayElement) overlayElement.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', () => {
                    const moreMenuModal = document.getElementById('more-menu-modal');
                    const overlayElement = document.getElementById('overlay');
                    
                    // Close more menu
                    if (moreMenuModal) moreMenuModal.classList.remove('show');
                    if (overlayElement) overlayElement.classList.remove('show');
                    document.body.style.overflow = '';
                    
                    // Close modals
                    closeModals();
                });
            }

            // --- Sidebar/Menu Toggle Logic ---
            const menuToggle = document.getElementById('menuToggle');

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

            if (dashboardContainer) {
                dashboardContainer.addEventListener('click', (e) => {
                    if (window.innerWidth <= 768 && !sidebar.contains(e.target) && !menuToggle.contains(e.target) && !sidebar.classList.contains('collapsed')) {
                        sidebar.classList.add('collapsed');
                        dashboardContainer.classList.remove('sidebar-collapsed');
                    }
                });
            }

            if (window.innerWidth <= 768 && sidebar) {
                sidebar.classList.add('collapsed');
            }
        }); // End DOMContentLoaded

        // Function to show message and hide after a delay (Global scope)
        function showMessage(message, type) {
            // Try different possible IDs for the message box
            let messageBox = document.getElementById('messageBox') || 
                           document.getElementById('message-box') || 
                           document.querySelector('.message-box');
            
            if (messageBox) {
                messageBox.textContent = message;
                messageBox.className = `message-box ${type}`;
                messageBox.style.display = 'block';
                messageBox.style.opacity = '1';

                setTimeout(() => {
                    messageBox.style.opacity = '0';
                    setTimeout(() => {
                        messageBox.style.display = 'none';
                        messageBox.style.opacity = '1'; // Reset opacity for next time
                    }, 500);
                }, 5000);
            } else {
                console.warn('MessageBox element not found, using console fallback');
                // Fallback to console
                console.log(`%c${type.toUpperCase()}: ${message}`, 
                    `color: ${type === 'success' ? 'green' : type === 'error' ? 'red' : 'orange'}; font-weight: bold;`);
                
                // Also try to create a temporary alert-style message
                if (window.confirm && type === 'error') {
                    alert(message);
                }
            }
        }

        // Display initial message if present from PHP
        <?php if (!empty($message)): ?>
            document.addEventListener('DOMContentLoaded', function() {
                showMessage("<?php echo $message; ?>", "<?php echo $message_type; ?>");
            });
        <?php endif; ?>

        // Function to filter and redirect (must be global for inline onclick handlers)
        function applyFilters() {
            const filterAcademicYear = document.getElementById('filter_academic_year');
            const filterTerm = document.getElementById('filter_term');
            const academicYear = filterAcademicYear ? filterAcademicYear.value : '';
            const term = filterTerm ? filterTerm.value : '';
            let url = 'admin_exams.php';
            const params = [];

            if (academicYear) {
                params.push(`academic_year=${encodeURIComponent(academicYear)}`);
            }
            if (term) {
                params.push(`term=${encodeURIComponent(term)}`);
            }

            if (params.length > 0) {
                url += '?' + params.join('&');
            }
            window.location.href = url;
        }

        function resetFilters() {
            window.location.href = 'admin_exams.php';
        }

        // --- Modal Functions ---
        function openModal(modalId) {
            console.log('🪟 Opening modal:', modalId);
            const modal = document.getElementById(modalId);
            const overlayElement = document.getElementById('overlay');
            
            console.log('🪟 Modal element found:', modal);
            console.log('🪟 Modal ID:', modalId);
            console.log('🪟 Modal classes before:', modal ? modal.className : 'null');
            
            if (modal) {
                modal.classList.remove('hidden');
                console.log('✅ Modal found and shown:', modalId);
                console.log('🪟 Modal classes after:', modal.className);
            } else {
                console.error('❌ Modal not found:', modalId);
            }
            
            if (overlayElement) {
                overlayElement.classList.add('show');
                console.log('✅ Overlay shown');
            } else {
                console.warn('⚠️ Overlay element not found');
            }
        }

        function closeModals() {
            const overlayElement = document.getElementById('overlay');
            document.querySelectorAll('.modal').forEach(modal => {
                modal.classList.add('hidden');
            });
            if (overlayElement) {
                overlayElement.classList.remove('show');
            }
        }

        // Modern Modal Functions
        function openModernModal(modalType, title, message, confirmCallback = null) {
            const modal = document.getElementById(modalType + 'Modal');
            const titleEl = document.getElementById(modalType + 'Title');
            const messageEl = document.getElementById(modalType + 'Message');
            
            if (titleEl) titleEl.textContent = title;
            if (messageEl) messageEl.textContent = message;
            
            // Handle confirm button for warning modal
            const confirmBtn = document.getElementById('warningConfirmBtn');
            if (modalType === 'warning' && confirmCallback) {
                confirmBtn.onclick = function() {
                    confirmCallback();
                    closeModernModal('warningModal');
                };
                confirmBtn.style.display = 'inline-block';
            } else if (modalType === 'warning') {
                confirmBtn.style.display = 'none';
            }
            
            if (modal) {
                modal.classList.remove('hidden');
            }
        }

        function closeModernModal(modalId) {
            const modal = document.getElementById(modalId);
            if (modal) {
                modal.classList.add('hidden');
            }
            
            // Hide overlay if no other modals are visible
            const visibleModals = document.querySelectorAll('.modal:not(.hidden)');
            if (visibleModals.length === 0) {
                const overlayElement = document.getElementById('overlay');
                if (overlayElement) {
                    overlayElement.classList.remove('show');
                }
            }
        }

        // Convenience functions for different modal types
        function showSuccess(title, message) {
            openModernModal('success', title, message);
        }

        function showError(title, message) {
            openModernModal('error', title, message);
        }

        function showWarning(title, message, confirmCallback = null) {
            openModernModal('warning', title, message, confirmCallback);
        }

        // Enhanced showMessage function to use modern modals
        function showMessage(message, type = 'success') {
            console.log('📢 Showing message:', { message, type });
            
            switch(type) {
                case 'success':
                    showSuccess('Success!', message);
                    break;
                case 'error':
                    showError('Error', message);
                    break;
                case 'warning':
                    showWarning('Warning', message);
                    break;
                default:
                    showSuccess('Information', message);
            }
        }

        // Exam Type Selection Functions
        let selectedExamType = null;

        function selectExamType(type) {
            selectedExamType = type;
            
            // Clear all radio buttons first
            document.querySelectorAll('input[name="exam_type"]').forEach(radio => {
                radio.checked = false;
                radio.closest('.exam-type-option').classList.remove('border-blue-500', 'bg-blue-50');
            });
            
            // Select the clicked type
            const radio = document.getElementById(type + '_exam_radio');
            const option = radio.closest('.exam-type-option');
            
            radio.checked = true;
            option.classList.add('border-blue-500', 'bg-blue-50');
            
            // Enable the continue button
            document.getElementById('continueExamTypeBtn').disabled = false;
        }

        function proceedWithSelectedExamType() {
            if (!selectedExamType) return;
            
            closeModals();
            
            switch (selectedExamType) {
                case 'normal':
                    document.getElementById('createNormalExamModal').classList.remove('hidden');
                    break;
                case 'consolidated':
                    document.getElementById('createConsolidatedExamModal').classList.remove('hidden');
                    // Initialize consolidated exam dropdowns
                    setupConsolidatedExamListeners();
                    break;
                case 'term_summary':
                    document.getElementById('createTermSummaryExamModal').classList.remove('hidden');
                    // Initialize term summary exam dropdowns
                    setupTermSummaryExamListeners();
                    break;
                case 'average_assessment':
                    document.getElementById('createAverageAssessmentModal').classList.remove('hidden');
                    break;
            }
            
            overlay.classList.add('show');
        }

        function backToExamTypeSelection() {
            closeModals();
            document.getElementById('selectExamTypeModal').classList.remove('hidden');
            overlay.classList.add('show');
        }

        function openCreateExamModal() {
            selectedExamType = null;
            document.getElementById('continueExamTypeBtn').disabled = true;
            
            // Clear all radio selections
            document.querySelectorAll('input[name="exam_type"]').forEach(radio => {
                radio.checked = false;
                radio.closest('.exam-type-option').classList.remove('border-blue-500', 'bg-blue-50');
            });
            
            document.getElementById('selectExamTypeModal').classList.remove('hidden');
            overlay.classList.add('show');
        }

        // Function to populate exam dropdowns based on term/year selection
        function populateExamDropdowns(termSelect, yearSelect, targetDropdowns) {
            const term = termSelect.value;
            const year = yearSelect.value;
            
            console.log('PopulateExamDropdowns called with:', { term, year });
            
            if (!term || !year) {
                targetDropdowns.forEach(dropdown => {
                    dropdown.innerHTML = '<option value="">-- Please select term and year first --</option>';
                });
                return;
            }
            
            // Check if allExamsData is available
            if (!allExamsData || !Array.isArray(allExamsData)) {
                console.error('allExamsData is not available or not an array');
                targetDropdowns.forEach(dropdown => {
                    dropdown.innerHTML = '<option value="">-- No exam data available --</option>';
                });
                return;
            }
            
            // For integration activities, we need to check for Average Assessment type
            // For normal exams, we check for Normal type, null/empty, or '0' (existing exams)
            const isIntegrationDropdown = targetDropdowns.some(dropdown => 
                dropdown.id === 'integration_exam_id'
            );
            
            let filteredExams;
            if (isIntegrationDropdown) {
                // Filter for both Normal and Average Assessment exams, including '0', null/empty types
                filteredExams = allExamsData.filter(exam => {
                    const matchesTermYear = exam.term === term && exam.year === year;
                    const isValidType = exam.exam_type === 'Normal' || 
                                       exam.exam_type === 'Average Assessment' ||
                                       exam.exam_type === '0' ||
                                       exam.exam_type === null || 
                                       exam.exam_type === '' || 
                                       exam.exam_type === undefined;
                    return matchesTermYear && isValidType;
                });
            } else {
                // Filter for Normal exams, '0', or null/empty (for consolidated and term summary)
                // '0', null/empty exam_type values are treated as Normal (existing exams)
                filteredExams = allExamsData.filter(exam => {
                    const matchesTermYear = exam.term === term && exam.year === year;
                    const isNormalType = exam.exam_type === 'Normal' || 
                                        exam.exam_type === '0' ||
                                        exam.exam_type === null || 
                                        exam.exam_type === '' || 
                                        exam.exam_type === undefined;
                    const isNotConsolidatedOrSummary = exam.exam_type !== 'Consolidated' && 
                                                      exam.exam_type !== 'Term Summary';
                    return matchesTermYear && isNormalType && isNotConsolidatedOrSummary;
                });
            }
            
            console.log('Filtered exams:', filteredExams);
            
            targetDropdowns.forEach(dropdown => {
                const placeholder = dropdown.getAttribute('data-placeholder') || '-- Select Exam --';
                dropdown.innerHTML = `<option value="">${placeholder}</option>`;
                
                if (filteredExams.length === 0) {
                    dropdown.innerHTML += '<option value="">-- No exams found for selected term and year --</option>';
                } else {
                    filteredExams.forEach(exam => {
                        const examTypeLabel = exam.exam_type === 'Average Assessment' ? ' (Integration Activities)' : '';
                        dropdown.innerHTML += `<option value="${exam.exam_id}">${exam.exam_name}${examTypeLabel}</option>`;
                    });
                }
            });
        }

        // Event listeners for consolidated exam dropdowns
        function setupConsolidatedExamListeners() {
            const consolidatedTerm = document.getElementById('consolidated_term');
            const consolidatedYear = document.getElementById('consolidated_year');
            const firstExamSelect = document.getElementById('first_exam_id');
            const secondExamSelect = document.getElementById('second_exam_id');
            
            if (consolidatedTerm && consolidatedYear && firstExamSelect && secondExamSelect) {
                // Set placeholders
                firstExamSelect.setAttribute('data-placeholder', '-- Select First Exam --');
                secondExamSelect.setAttribute('data-placeholder', '-- Select Second Exam --');
                
                // Initialize dropdowns with empty state
                firstExamSelect.innerHTML = '<option value="">-- Select term and year first --</option>';
                secondExamSelect.innerHTML = '<option value="">-- Select term and year first --</option>';
                
                consolidatedTerm.addEventListener('change', () => {
                    populateExamDropdowns(consolidatedTerm, consolidatedYear, [firstExamSelect, secondExamSelect]);
                });
                
                consolidatedYear.addEventListener('change', () => {
                    populateExamDropdowns(consolidatedTerm, consolidatedYear, [firstExamSelect, secondExamSelect]);
                });
                
                // Initial population if values are already selected
                if (consolidatedTerm.value && consolidatedYear.value) {
                    populateExamDropdowns(consolidatedTerm, consolidatedYear, [firstExamSelect, secondExamSelect]);
                }
                
                // Add validation to prevent selecting the same exam twice
                firstExamSelect.addEventListener('change', () => {
                    validateConsolidatedExamSelection();
                });
                
                secondExamSelect.addEventListener('change', () => {
                    validateConsolidatedExamSelection();
                });
            }
        }
        
        // Validation function for consolidated exams
        function validateConsolidatedExamSelection() {
            const firstExamSelect = document.getElementById('first_exam_id');
            const secondExamSelect = document.getElementById('second_exam_id');
            
            if (firstExamSelect && secondExamSelect) {
                const firstExamValue = firstExamSelect.value;
                const secondExamValue = secondExamSelect.value;
                
                // Remove any existing error styling
                firstExamSelect.classList.remove('border-red-500');
                secondExamSelect.classList.remove('border-red-500');
                
                // Remove any existing error message
                const existingError = document.getElementById('consolidated-exam-error');
                if (existingError) {
                    existingError.remove();
                }
                
                if (firstExamValue && secondExamValue && firstExamValue === secondExamValue) {
                    // Add error styling
                    firstExamSelect.classList.add('border-red-500');
                    secondExamSelect.classList.add('border-red-500');
                    
                    // Add error message
                    const errorDiv = document.createElement('div');
                    errorDiv.id = 'consolidated-exam-error';
                    errorDiv.className = 'text-red-600 text-sm mt-2';
                    errorDiv.textContent = 'You cannot select the same exam twice. Please choose different exams.';
                    
                    secondExamSelect.parentNode.appendChild(errorDiv);
                    
                    return false;
                }
                
                return true;
            }
        }

        // Event listeners for term summary exam dropdowns
        function setupTermSummaryExamListeners() {
            const termSummaryTerm = document.getElementById('term_summary_term');
            const termSummaryYear = document.getElementById('term_summary_year');
            const integrationExamSelect = document.getElementById('integration_exam_id');
            const normalExamSelect = document.getElementById('normal_exam_id_for_summary');
            
            if (termSummaryTerm && termSummaryYear && integrationExamSelect && normalExamSelect) {
                // Set placeholders
                integrationExamSelect.setAttribute('data-placeholder', '-- Select Integration Activities --');
                normalExamSelect.setAttribute('data-placeholder', '-- Select Normal Exam --');
                
                // Initialize dropdowns with empty state
                integrationExamSelect.innerHTML = '<option value="">-- Select term and year first --</option>';
                normalExamSelect.innerHTML = '<option value="">-- Select term and year first --</option>';
                
                termSummaryTerm.addEventListener('change', () => {
                    populateExamDropdowns(termSummaryTerm, termSummaryYear, [integrationExamSelect, normalExamSelect]);
                });
                
                termSummaryYear.addEventListener('change', () => {
                    populateExamDropdowns(termSummaryTerm, termSummaryYear, [integrationExamSelect, normalExamSelect]);
                });
                
                // Initial population if values are already selected
                if (termSummaryTerm.value && termSummaryYear.value) {
                    populateExamDropdowns(termSummaryTerm, termSummaryYear, [integrationExamSelect, normalExamSelect]);
                }
                
                // Add validation to prevent selecting the same exam twice
                integrationExamSelect.addEventListener('change', () => {
                    validateTermSummaryExamSelection();
                });
                
                normalExamSelect.addEventListener('change', () => {
                    validateTermSummaryExamSelection();
                });
            }
        }
        
        // Validation function for term summary exams
        function validateTermSummaryExamSelection() {
            const integrationExamSelect = document.getElementById('integration_exam_id');
            const normalExamSelect = document.getElementById('normal_exam_id_for_summary');
            
            if (integrationExamSelect && normalExamSelect) {
                const integrationExamValue = integrationExamSelect.value;
                const normalExamValue = normalExamSelect.value;
                
                // Remove any existing error styling
                integrationExamSelect.classList.remove('border-red-500');
                normalExamSelect.classList.remove('border-red-500');
                
                // Remove any existing error message
                const existingError = document.getElementById('term-summary-exam-error');
                if (existingError) {
                    existingError.remove();
                }
                
                if (integrationExamValue && normalExamValue && integrationExamValue === normalExamValue) {
                    // Add error styling
                    integrationExamSelect.classList.add('border-red-500');
                    normalExamSelect.classList.add('border-red-500');
                    
                    // Add error message
                    const errorDiv = document.createElement('div');
                    errorDiv.id = 'term-summary-exam-error';
                    errorDiv.className = 'text-red-600 text-sm mt-2';
                    errorDiv.textContent = 'Integration activities and normal exam cannot be the same. Please choose different exams.';
                    
                    normalExamSelect.parentNode.appendChild(errorDiv);
                    
                    return false;
                }
                
                return true;
            }
        }

        // Initialize dropdown listeners and exam type option clicks
        setupConsolidatedExamListeners();
        setupTermSummaryExamListeners();
        
        // Add form submission validation
        function setupFormValidation() {
            // Consolidated exam form validation
            const consolidatedForm = document.querySelector('form input[value="create_consolidated_exam"]');
            if (consolidatedForm) {
                consolidatedForm.closest('form').addEventListener('submit', function(e) {
                    if (!validateConsolidatedExamSelection()) {
                        e.preventDefault();
                        alert('Please correct the validation errors before submitting.');
                        return false;
                    }
                });
            }
            
            // Term summary exam form validation
            const termSummaryForm = document.querySelector('form input[value="create_term_summary_exam"]');
            if (termSummaryForm) {
                termSummaryForm.closest('form').addEventListener('submit', function(e) {
                    if (!validateTermSummaryExamSelection()) {
                        e.preventDefault();
                        alert('Please correct the validation errors before submitting.');
                        return false;
                    }
                });
            }
        }
        
        // Setup form validation
        setupFormValidation();

        // Add event listeners for exam type option clicks
        document.addEventListener('click', function(e) {
            if (e.target.closest('.exam-type-option')) {
                const option = e.target.closest('.exam-type-option');
                const radio = option.querySelector('input[type="radio"]');
                if (radio) {
                    selectExamType(radio.value);
                }
            }
        });

        // Publish Assessment Functions
        function openPublishAssessmentModal(button) {
            const row = button.closest('tr');
            const examId = row.dataset.examId;
            const examName = row.dataset.examName;
            const classIds = row.dataset.classIdsAffected ? row.dataset.classIdsAffected.split(',') : [];
            
            document.getElementById('assessment_name_display').textContent = examName;
            
            // Populate class dropdown
            const classSelect = document.getElementById('assessment_class_select');
            classSelect.innerHTML = '<option value="">-- Select a Class --</option>';
            
            classIds.forEach(classId => {
                const classData = allClassesData.find(c => c.class_id == classId);
                if (classData) {
                    classSelect.innerHTML += `<option value="${classData.class_id}">${classData.class_name}</option>`;
                }
            });
            
            // Store exam data for later use
            classSelect.dataset.examId = examId;
            classSelect.dataset.examName = examName;
            
            // Clear streams table
            document.getElementById('assessmentStreamsTableBody').innerHTML = 
                '<tr><td colspan="3" class="text-center py-4 text-gray-500">Please select a class to view streams.</td></tr>';
            
            openModal('publishAssessmentModal');
        }

        function loadStreamsForAssessment() {
            const classSelect = document.getElementById('assessment_class_select');
            const selectedClassId = classSelect.value;
            const examId = classSelect.dataset.examId;
            const examName = classSelect.dataset.examName;
            
            if (!selectedClassId) {
                document.getElementById('assessmentStreamsTableBody').innerHTML = 
                    '<tr><td colspan="3" class="text-center py-4 text-gray-500">Please select a class to view streams.</td></tr>';
                return;
            }
            
            // Filter streams for the selected class
            const classStreams = allStreamsData.filter(stream => stream.class_id == selectedClassId);
            
            if (classStreams.length === 0) {
                document.getElementById('assessmentStreamsTableBody').innerHTML = 
                    `<tr><td colspan="3" class="text-center py-4 text-gray-500">${getTranslation('no_streams_found')}</td></tr>`;
                return;
            }
            
            let html = '';
            classStreams.forEach(stream => {
                html += `
                    <tr>
                        <td data-label="${getTranslation('stream_name')}">${stream.stream_name}</td>
                        <td data-label="${getTranslation('total_students')}">-</td>
                        <td data-label="${getTranslation('actions')}">
                            <button onclick="openStreamAssessmentDetails('${stream.stream_id}', '${stream.stream_name}', '${selectedClassId}', '${examId}', '${examName}')" 
                                    class="btn btn-view flex items-center">
                                <i class="fas fa-eye mr-1"></i> ${getTranslation('view')}
                            </button>
                        </td>
                    </tr>
                `;
            });
            
            document.getElementById('assessmentStreamsTableBody').innerHTML = html;
        }

        function openStreamAssessmentDetails(streamId, streamName, classId, examId, examName) {
            const className = allClassesData.find(c => c.class_id == classId)?.class_name || 'Unknown Class';
            document.getElementById('stream_details_title').textContent = `${className} - ${streamName}`;
            
            // Show loading state
            document.getElementById('streamAssessmentDetailsTableBody').innerHTML = 
                '<tr><td colspan="5" class="text-center py-4 text-gray-500">Loading assessment details...</td></tr>';
            
            closeModals();
            openModal('streamAssessmentDetailsModal');
            
            // Fetch assessment details via AJAX
            fetchStreamAssessmentDetails(streamId, classId, examId);
        }

        async function fetchStreamAssessmentDetails(streamId, classId, examId) {
            try {
                const response = await fetch(`admin_exams.php?action=get_stream_assessment_details&stream_id=${streamId}&class_id=${classId}&exam_id=${examId}`);
                const data = await response.json();
                
                if (data.success) {
                    displayStreamAssessmentDetails(data.subjects);
                } else {
                    document.getElementById('streamAssessmentDetailsTableBody').innerHTML = 
                        `<tr><td colspan="5" class="text-center py-4 text-red-500">Error: ${data.message}</td></tr>`;
                }
            } catch (error) {
                console.error('Error fetching assessment details:', error);
                document.getElementById('streamAssessmentDetailsTableBody').innerHTML = 
                    '<tr><td colspan="5" class="text-center py-4 text-red-500">Error loading assessment details.</td></tr>';
            }
        }

        function displayStreamAssessmentDetails(subjects) {
            if (!subjects || subjects.length === 0) {
                document.getElementById('streamAssessmentDetailsTableBody').innerHTML = 
                    '<tr><td colspan="5" class="text-center py-4 text-gray-500">No subjects found for this stream.</td></tr>';
                return;
            }
            
            let html = '';
            subjects.forEach(subject => {
                const statusClass = subject.students_with_marks > 0 ? 'text-green-600' : 'text-red-600';
                const statusText = subject.students_with_marks > 0 ? 'Has Marks' : 'No Marks';
                
                html += `
                    <tr>
                        <td data-label="Class">${subject.class_name}</td>
                        <td data-label="Subject">${subject.subject_name}</td>
                        <td data-label="${getTranslation('subject_teacher')}">${subject.teacher_name || 'Not Assigned'}</td>
                        <td data-label="${getTranslation('students_with_marks')}">${subject.students_with_marks}/${subject.total_students}</td>
                        <td data-label="${getTranslation('marks_status')}">
                            <span class="${statusClass} font-semibold">${statusText}</span>
                        </td>
                    </tr>
                `;
            });
            
            document.getElementById('streamAssessmentDetailsTableBody').innerHTML = html;
        }

        function openEditExamModal(button) {
            console.log('openEditExamModal called');
            const row = button.closest('tr');
            if (!row) {
                console.error('Could not find table row for edit button');
                return;
            }
            
            const examId = row.getAttribute('data-exam-id');
            const examName = row.getAttribute('data-exam-name');
            const term = row.getAttribute('data-term');
            const year = row.getAttribute('data-year');
            const classAffected = row.getAttribute('data-class-affected');
            const classesAffectedNames = [classAffected].filter(c => c && c !== 'N/A');
            const subjectsAffected = row.getAttribute('data-subjects-affected');
            const subjectsAffectedNames = subjectsAffected ? subjectsAffected.split(', ').filter(s => s && s !== 'N/A') : [];
            
            console.log('Edit exam data:', {examId, examName, term, year});

            document.getElementById('edit_exam_id').value = examId;
            document.getElementById('edit_exam_name').value = examName;
            document.getElementById('edit_term').value = term;
            document.getElementById('edit_year').value = year;

            // Populate classes checkboxes
            const editClassesCheckboxGroup = document.getElementById('edit_classes_checkbox_group');
            editClassesCheckboxGroup.innerHTML = '';
            allClassesData.forEach(classItem => {
                const label = document.createElement('label');
                label.className = 'flex items-center mb-2 cursor-pointer';
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.name = 'classes[]';
                checkbox.value = classItem.class_id;
                checkbox.className = 'mr-2 form-checkbox h-4 w-4 text-indigo-600 transition duration-150 ease-in-out rounded focus:ring-indigo-500';
                if (classesAffectedNames.includes(classItem.class_name)) {
                    checkbox.checked = true;
                }
                label.appendChild(checkbox);
                label.appendChild(document.createTextNode(classItem.class_name));
                editClassesCheckboxGroup.appendChild(label);
            });

            // Populate subjects checkboxes
            const editSubjectsCheckboxGroup = document.getElementById('edit_subjects_checkbox_group');
            editSubjectsCheckboxGroup.innerHTML = '';
            allSubjectsData.forEach(subjectItem => {
                const label = document.createElement('label');
                label.className = 'flex items-center mb-2 cursor-pointer';
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.name = 'subjects[]';
                checkbox.value = subjectItem.subject_id;
                checkbox.className = 'mr-2 form-checkbox h-4 w-4 text-indigo-600 transition duration-150 ease-in-out rounded focus:ring-indigo-500';
                if (subjectsAffectedNames.includes(subjectItem.subject_name)) {
                    checkbox.checked = true;
                }
                label.appendChild(checkbox);
                label.appendChild(document.createTextNode(subjectItem.subject_name));
                editSubjectsCheckboxGroup.appendChild(label);
            });

            openModal('editExamModal');
        }

        function openDeleteExamModal(button) {
            console.log('openDeleteExamModal called');
            const row = button.closest('tr');
            if (!row) {
                console.error('Could not find table row for delete button');
                return;
            }
            
            const examId = row.getAttribute('data-exam-id');
            const examName = row.getAttribute('data-exam-name');
            
            console.log('Delete exam data:', {examId, examName});

            const deleteIdInput = document.getElementById('delete_exam_id');
            const deleteNameDisplay = document.getElementById('delete_exam_name_display');
            
            if (deleteIdInput) {
                deleteIdInput.value = examId;
            } else {
                console.error('delete_exam_id input not found');
            }
            
            if (deleteNameDisplay) {
                deleteNameDisplay.textContent = examName;
            } else {
                console.error('delete_exam_name_display element not found');
            }
            
            openModal('deleteExamModal');
        }

        function openPublishConfirmModal(button) {
            console.log('🔄 openPublishConfirmModal called');
            console.log('🔘 Button element:', button);
            console.log('🔘 Button onclick:', button.getAttribute('onclick'));
            const row = button.closest('tr');
            if (!row) {
                console.error('❌ Could not find table row for publish button');
                return;
            }
            
            console.log('✅ Found table row:', row);
            console.log('📋 Row HTML:', row.outerHTML);
            
            const examId = row.getAttribute('data-exam-id');
            const examName = row.getAttribute('data-exam-name');
            const examType = row.getAttribute('data-exam-type');
            const integrationExamId = row.getAttribute('data-integration-exam-id');
            const firstExamId = row.getAttribute('data-first-exam-id');
            const secondExamId = row.getAttribute('data-second-exam-id');
            const normalExamId = row.getAttribute('data-normal-exam-id');
            const classAffected = row.getAttribute('data-class-affected');
            const subjectsAffected = row.getAttribute('data-subjects-affected');
            const status = row.getAttribute('data-status');
            
            console.log('📊 Publish exam data:', {
                examId, examName, examType, integrationExamId,
                firstExamId, secondExamId, normalExamId,
                classAffected, subjectsAffected, status
            });
            
            // Check for missing critical data
            const missingData = [];
            if (!examId) missingData.push('examId');
            if (!examName) missingData.push('examName');
            if (!examType) missingData.push('examType');
            
            if (missingData.length > 0) {
                console.error('❌ MISSING CRITICAL DATA:', missingData);
                showMessage('Error: Missing critical exam data: ' + missingData.join(', '), 'error');
                return;
            }
            
            console.log('✅ All critical data present');

            const publishIdInput = document.getElementById('publish_exam_id');
            const publishNameDisplay = document.getElementById('publish_exam_name_display');
            const integrationWarning = document.getElementById('integrationActivitiesWarning');
            
            if (publishIdInput) {
                publishIdInput.value = examId;
            } else {
                console.error('publish_exam_id input not found');
            }
            
            if (publishNameDisplay) {
                publishNameDisplay.textContent = examName;
            } else {
                console.error('publish_exam_name_display element not found');
            }
            
            // Show integration activities warning for Term Summary and Average Assessment
            if (integrationWarning) {
                if (examType === 'Term Summary' || examType === 'Average Assessment') {
                    integrationWarning.style.display = 'flex';
                    console.log('Showing integration activities warning for exam type:', examType);
                } else {
                    integrationWarning.style.display = 'none';
                    console.log('Hiding integration activities warning for exam type:', examType);
                }
            }
            
            openModal('publishConfirmModal');
        }

        function openUnpublishConfirmModal(button) {
            const row = button.closest('tr');
            const examId = row.getAttribute('data-exam-id');
            const examName = row.getAttribute('data-exam-name');
            const examType = row.getAttribute('data-exam-type');
            const integrationExamId = row.getAttribute('data-integration-exam-id');

            document.getElementById('unpublish_exam_id').value = examId;
            document.getElementById('unpublish_exam_name_display').textContent = examName;
            
            // Show integration activities unlock warning for Term Summary and Average Assessment
            const integrationUnlockWarning = document.getElementById('integrationActivitiesUnlockWarning');
            if (integrationUnlockWarning) {
                if (examType === 'Term Summary' || examType === 'Average Assessment') {
                    integrationUnlockWarning.style.display = 'flex';
                    console.log('Showing integration activities unlock warning for exam type:', examType);
                } else {
                    integrationUnlockWarning.style.display = 'none';
                    console.log('Hiding integration activities unlock warning for exam type:', examType);
                }
            }
            
            openModal('unpublishConfirmModal');
        }
        // Individual class publishing from main exam table
        async function toggleClassStatusFromMainTable(examId, classId, action) {
            try {
                // For main table publishing, we need to get the current exam name for confirmation
                const examRow = document.querySelector(`tr[data-exam-id="${examId}"]`);
                const examName = examRow?.dataset.examName || 'Exam';
                const actionText = action === 'publish' ? 'Publish' : 'Unpublish';
                
                const confirmMessage = action === 'publish' ? 
                    `Are you sure you want to publish results for ${examName}?` : 
                    `Are you sure you want to unpublish results for ${examName}?`;
                
                // Use modern warning modal for confirmation
                showWarning('Confirm ' + actionText, confirmMessage, async function() {
                    try {
                        const formData = new FormData();
                        formData.append('action', 'manage_class_publishing');
                        formData.append('class_action', action === 'publish' ? 'publish_class' : 'unpublish_class');
                        formData.append('exam_id', examId);
                        formData.append('class_id', classId);
                        formData.append('stream_id', 0); // For class-level publishing without stream specificity
                        
                        const response = await fetch('admin_exams.php', {
                            method: 'POST',
                            body: formData
                        });
                        
                        const data = await response.json();
                        
                        if (data.success) {
                            // Use modern success modal
                            showSuccess('Success!', data.message + ' - Page will reload to update status...');
                            // Reload the page to update all status indicators
                            setTimeout(() => {
                                location.reload();
                            }, 1500); // Give user time to see the success message
                        } else {
                            showError('Error', data.message);
                        }
                    } catch (error) {
                        console.error('Error toggling class status:', error);
                        showError('Error', 'Network error: ' + error.message);
                    }
                });
            } catch (error) {
                console.error('Error toggling class status:', error);
                showError('Error', 'Network error: ' + error.message);
            }
        }

        let gradeRangeCounter = 0;

        function addGradeRangeRow() {
            gradeRangeCounter++;
            const container = document.getElementById('gradeRangesContainer');
            const newRow = document.createElement('div');
            newRow.className = 'grid grid-cols-6 gap-2 items-end mb-2';
            newRow.innerHTML = `
                <div class="form-group col-span-1">
                    <label for="min_score_${gradeRangeCounter}">Min Score</label>
                    <input type="number" id="min_score_${gradeRangeCounter}" name="min_score_${gradeRangeCounter}" step="0.01" required class="p-2 border rounded-lg w-full">
                </div>
                <div class="form-group col-span-1">
                    <label for="max_score_${gradeRangeCounter}">Max Score</label>
                    <input type="number" id="max_score_${gradeRangeCounter}" name="max_score_${gradeRangeCounter}" step="0.01" required class="p-2 border rounded-lg w-full">
                </div>
                <div class="form-group col-span-1">
                    <label for="grade_letter_${gradeRangeCounter}">Grade Letter</label>
                    <input type="text" id="grade_letter_${gradeRangeCounter}" name="grade_letter_${gradeRangeCounter}" required class="p-2 border rounded-lg w-full">
                </div>
                <div class="form-group col-span-1">
                    <label for="grade_${gradeRangeCounter}">Grade</label>
                    <input type="text" id="grade_${gradeRangeCounter}" name="grade_${gradeRangeCounter}" placeholder="D1, D2, etc." class="p-2 border rounded-lg w-full">
                </div>
                <div class="form-group col-span-1">
                    <label for="remarks_${gradeRangeCounter}">Remarks</label>
                    <input type="text" id="remarks_${gradeRangeCounter}" name="remarks_${gradeRangeCounter}" class="p-2 border rounded-lg w-full">
                </div>
                <div class="col-span-1">
                    <button type="button" onclick="removeGradeRangeRow(this)" class="bg-red-500 text-white px-2 py-2 rounded-lg shadow-md hover:bg-red-600 transition duration-200 w-full flex items-center justify-center">
                        <i class="fas fa-minus mr-1"></i> Remove
                    </button>
                </div>
            `;
            container.appendChild(newRow);
        }

        function removeGradeRangeRow(button) {
            button.closest('.grid').remove();
        }

        function openAddGradingSystemModal() {
            document.querySelector('#addGradingSystemModal form').reset();
            const container = document.getElementById('gradeRangesContainer');
            container.innerHTML = `
                <div class="grid grid-cols-6 gap-2 items-end mb-2">
                    <div class="form-group col-span-1">
                        <label for="min_score_0">Min Score</label>
                        <input type="number" id="min_score_0" name="min_score_0" step="0.01" required class="p-2 border rounded-lg w-full">
                    </div>
                    <div class="form-group col-span-1">
                        <label for="max_score_0">Max Score</label>
                        <input type="number" id="max_score_0" name="max_score_0" step="0.01" required class="p-2 border rounded-lg w-full">
                    </div>
                    <div class="form-group col-span-1">
                        <label for="grade_letter_0">Grade Letter</label>
                        <input type="text" id="grade_letter_0" name="grade_letter_0" required class="p-2 border rounded-lg w-full">
                    </div>
                    <div class="form-group col-span-1">
                        <label for="grade_0">Grade</label>
                        <input type="text" id="grade_0" name="grade_0" placeholder="D1, D2, etc." class="p-2 border rounded-lg w-full">
                    </div>
                    <div class="form-group col-span-1">
                        <label for="remarks_0">Remarks</label>
                        <input type="text" id="remarks_0" name="remarks_0" class="p-2 border rounded-lg w-full">
                    </div>
                    <div class="col-span-1">
                        <button type="button" onclick="addGradeRangeRow()" class="btn-primary w-full px-2 py-2 text-sm flex items-center justify-center">
                            <i class="fas fa-plus mr-1"></i> Add
                        </button>
                    </div>
                </div>
            `;
            gradeRangeCounter = 0;

            document.querySelector('#addGradingSystemModal form').onsubmit = function() {
                const gradeRanges = [];
                const rows = container.querySelectorAll('.grid.grid-cols-6');
                rows.forEach((row, index) => {
                    const minScoreInput = row.querySelector(`[name="min_score_${index}"]`);
                    const maxScoreInput = row.querySelector(`[name="max_score_${index}"]`);
                    const gradeLetterInput = row.querySelector(`[name="grade_letter_${index}"]`);
                    const gradeInput = row.querySelector(`[name="grade_${index}"]`);
                    const remarksInput = row.querySelector(`[name="remarks_${index}"]`);

                    if (minScoreInput && maxScoreInput && gradeLetterInput) {
                        gradeRanges.push({
                            min_score: minScoreInput.value,
                            max_score: maxScoreInput.value,
                            grade_letter: gradeLetterInput.value,
                            grade: gradeInput ? gradeInput.value : '',
                            remarks: remarksInput ? remarksInput.value : ''
                        });
                    }
                });
                
                const existingHiddenInput = this.querySelector('input[name="grade_ranges_json"]');
                if (existingHiddenInput) {
                    existingHiddenInput.remove();
                }

                let hiddenInput = document.createElement('input');
                hiddenInput.type = 'hidden';
                hiddenInput.name = 'grade_ranges_json';
                hiddenInput.value = JSON.stringify(gradeRanges);
                this.appendChild(hiddenInput);
                return true;
            };

            openModal('addGradingSystemModal');
        }

        async function openViewResultsStatusModal(button) {
            console.log('🔍 openViewResultsStatusModal called');
            
            // Enhanced error handling and debugging
            const row = button.closest('tr');
            if (!row) {
                console.error('❌ Could not find table row for view button');
                showMessage('Error: Could not find exam data for viewing results.', 'error');
                return;
            }
            
            const examId = row.getAttribute('data-exam-id');
            const examName = row.getAttribute('data-exam-name');
            const classIdAffected = row.getAttribute('data-class-id-affected');
            const subjectIdsAffected = row.getAttribute('data-subject-ids-affected');
            
            console.log('📊 Raw attributes:', {
                examId, 
                examName, 
                classIdAffected, 
                subjectIdsAffected
            });

            if (!examId) {
                console.error('❌ Missing exam ID');
                showMessage('Error: Missing exam ID for viewing results.', 'error');
                return;
            }

            if (!classIdAffected || classIdAffected.trim() === '') {
                console.error('❌ No class affected for this exam');
                showMessage('Error: No class found for this exam.', 'error');
                return;
            }
            
            const classIdsArray = [Number(classIdAffected)].filter(id => id > 0);
            const subjectIdsArray = subjectIdsAffected ? subjectIdsAffected.split(',').map(id => Number(id.trim())).filter(id => id > 0) : [];
            
            console.log('✅ Processed data:', {examId, examName, classIdsArray, subjectIdsArray});

            // Check if required data is available
            if (!allClassesData || allClassesData.length === 0) {
                console.error('❌ No classes data available');
                showMessage('Error: Classes data not loaded. Please refresh the page.', 'error');
                return;
            }

            if (!allStreamsData || allStreamsData.length === 0) {
                console.error('❌ No streams data available');
                showMessage('Error: Streams data not loaded. Please refresh the page.', 'error');
                return;
            }

            document.getElementById('view_exam_name_display').textContent = examName;
            const viewClassSelect = document.getElementById('view_class_select');
            const viewStreamSelect = document.getElementById('view_stream_select');
            const viewResultsStatusTableBody = document.getElementById('viewResultsStatusTableBody');

            // Reset UI components to initial state
            viewClassSelect.innerHTML = '<option value="">-- Select a Class --</option>';
            viewStreamSelect.innerHTML = '<option value="">-- Select a Stream --</option>';
            viewResultsStatusTableBody.innerHTML = '<tr><td colspan="4" class="text-center py-4 text-gray-500">Please select a class and stream to view results status.</td></tr>';

            // Filter classes specific to this exam
            const classesForThisExam = allClassesData.filter(classItem => classIdsArray.includes(classItem.class_id));
            console.log('📚 Classes for this exam:', classesForThisExam);
            
            if (classesForThisExam.length > 0) {
                classesForThisExam.forEach(classItem => {
                    const option = document.createElement('option');
                    option.value = classItem.class_id;
                    option.textContent = classItem.class_name;
                    viewClassSelect.appendChild(option);
                });
                console.log('✅ Populated class dropdown');
            } else {
                viewClassSelect.innerHTML = '<option value="">-- No Classes for this Exam --</option>';
                console.warn('⚠️ No classes found for this exam');
            }

            viewClassSelect.onchange = () => {
                const selectedClassId = viewClassSelect.value;
                viewStreamSelect.innerHTML = '<option value="">-- Select a Stream --</option>';
                viewResultsStatusTableBody.innerHTML = '<tr><td colspan="4" class="text-center py-4 text-gray-500">Please select a stream to view results status.</td></tr>';

                if (selectedClassId) {
                    const streamsForSelectedClass = allStreamsData.filter(stream => stream.class_id == selectedClassId);
                    console.log('🌊 Streams for selected class:', streamsForSelectedClass);
                    
                    if (streamsForSelectedClass.length > 0) {
                        streamsForSelectedClass.forEach(stream => {
                            const option = document.createElement('option');
                            option.value = stream.stream_id;
                            option.textContent = stream.stream_name;
                            viewStreamSelect.appendChild(option);
                        });
                        console.log('✅ Populated stream dropdown with', streamsForSelectedClass.length, 'streams');
                    } else {
                        viewStreamSelect.innerHTML = '<option value="">-- No Streams for this Class --</option>';
                        showMessage('No streams found for the selected class. Results status cannot be viewed.', 'error');
                        console.warn('⚠️ No streams found for class ID:', selectedClassId);
                    }
                }
            };

            viewStreamSelect.onchange = async () => {
                const selectedClassId = viewClassSelect.value;
                const selectedStreamId = viewStreamSelect.value;
                viewResultsStatusTableBody.innerHTML = '<tr><td colspan="4" class="text-center py-4 text-gray-500">Loading results status...</td></tr>';

                if (selectedClassId && selectedStreamId) {
                    console.log('📡 Fetching results status for:', {examId, selectedClassId, selectedStreamId});
                    
                    try {
                        const response = await fetch(`admin_exams_api.php?action=get_exam_results_status&exam_id=${examId}&class_id=${selectedClassId}&stream_id=${selectedStreamId}`, {
                    credentials: 'include',
                    cache: 'no-cache'
                });
                        
                        if (!response.ok) {
                            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                        }
                        
                        const data = await response.json();
                        console.log('📋 Results status response:', data);
                        console.log('📊 Response data structure:', JSON.stringify(data, null, 2));

                        if (data.success) {
                            console.log('✅ Success response received, processing results...');
                            console.log('📋 Results array:', data.results);
                            console.log('🏷️ Table body element:', viewResultsStatusTableBody);
                            
                            viewResultsStatusTableBody.innerHTML = '';
                            if (data.results.length > 0) {
                                console.log(`📊 Processing ${data.results.length} subjects...`);
                                data.results.forEach((item, index) => {
                                    console.log(`📝 Processing subject ${index + 1}:`, item);
                                    const row = document.createElement('tr');
                                    const statusText = item.students_with_grades === item.total_students_enrolled ? 'Entered' : 'Pending';
                                    const statusColor = item.students_with_grades === item.total_students_enrolled ? 'text-green-600' : 'text-orange-600';
                                    
                                    row.innerHTML = `
                                        <td class="font-medium">${item.subject_name}</td>
                                        <td class="text-center">${item.total_students_enrolled}</td>
                                        <td class="text-center">${item.students_with_grades}</td>
                                        <td class="text-center">
                                            <span class="${statusColor} font-semibold">${statusText}</span>
                                            <div class="text-xs text-gray-500">${item.percentage_complete}% complete</div>
                                        </td>
                                    `;
                                    viewResultsStatusTableBody.appendChild(row);
                                    console.log(`✅ Added row for subject: ${item.subject_name}`);
                                });
                                
                                console.log('🎯 All rows added to table body');
                                
                                // Show summary info
                                const completedSubjects = data.results.filter(item => item.students_with_grades === item.total_students_enrolled).length;
                                const totalSubjects = data.results.length;
                                showMessage(`Results status loaded: ${completedSubjects}/${totalSubjects} subjects completed`, 'success');
                                
                            } else {
                                viewResultsStatusTableBody.innerHTML = '<tr><td colspan="4" class="text-center py-4 text-gray-500">No subjects or students found for this class and stream combination for this exam.</td></tr>';
                                console.warn('⚠️ No results found for this combination');
                            }
                        } else {
                            viewResultsStatusTableBody.innerHTML = `<tr><td colspan="4" class="text-center py-4 text-red-500">Error: ${data.message}</td></tr>`;
                            showMessage(`Error fetching results status: ${data.message}`, 'error');
                            console.error('❌ API Error:', data.message);
                        }
                    } catch (error) {
                        viewResultsStatusTableBody.innerHTML = `<tr><td colspan="4" class="text-center py-4 text-red-500">Network error: ${error.message}</td></tr>`;
                        showMessage(`Network error fetching results status: ${error.message}`, 'error');
                        console.error('❌ Network Error:', error);
                    }
                } else {
                    viewResultsStatusTableBody.innerHTML = '<tr><td colspan="4" class="text-center py-4 text-gray-500">Please select a class and stream to view results status.</td></tr>';
                }
            };

            openModal('viewResultsStatusModal');
        }

        async function openViewGradingScalesModal() {
            if (filterGradeAcademicYear) filterGradeAcademicYear.value = '';
            if (filterGradeTerm) filterGradeTerm.value = '';
            if (filterGradeClassId) filterGradeClassId.value = '0';
            if (filterGradeSubjectId) filterGradeSubjectId.value = '0';

            await fetchAndDisplayGradingScales();
            openModal('viewGradingScalesModal');
        }

        async function fetchAndDisplayGradingScales() {
            if (!filterGradeAcademicYear || !filterGradeTerm || !filterGradeClassId || !filterGradeSubjectId || !gradingScalesTableBody) {
                console.error('Required DOM elements not found for grading scales');
                return;
            }

            const academicYear = filterGradeAcademicYear.value;
            const term = filterGradeTerm.value;
            const classId = filterGradeClassId.value;
            const subjectId = filterGradeSubjectId.value;

            gradingScalesTableBody.innerHTML = '<tr><td colspan="12" class="text-center py-4 text-gray-500">Loading grading scales...</td></tr>';

            try {
                const params = new URLSearchParams({
                    action: 'get_grading_scales_data',
                    academic_year: academicYear,
                    term: term,
                    class_id: classId,
                    subject_id: subjectId
                });

                const response = await fetch(`admin_exams.php?${params.toString()}`);
                const data = await response.json();

                if (data.success) {
                    gradingScalesTableBody.innerHTML = '';
                    if (data.data.length > 0) {
                        data.data.forEach(scale => {
                            const row = document.createElement('tr');
                            row.innerHTML = `
                                <td>${scale.grade_name || 'N/A'}</td>
                                <td>${scale.academic_year || 'All Years'}</td>
                                <td>${scale.term_name || 'All Terms'}</td>
                                <td>${scale.class_name || 'All Classes'}</td>
                                <td>${scale.subject_name || 'All Subjects'}</td>
                                <td>${scale.grade_letter}</td>
                                <td>${scale.grade || '-'}</td>
                                <td>${scale.min_score}</td>
                                <td>${scale.max_score}</td>
                                <td>${scale.remarks || 'N/A'}</td>
                                <td>${scale.updated_by_username || 'N/A'}</td>
                                <td class="action-buttons-cell">
                                    <button onclick="openEditGradingScaleModal(${scale.id})" class="btn btn-edit flex items-center mr-2">
                                        <i class="fas fa-edit mr-1"></i> Edit
                                    </button>
                                    <button onclick="openDeleteGradingScaleModal(${scale.id}, '${scale.grade_name} - ${scale.grade_letter}')" class="btn btn-delete flex items-center">
                                        <i class="fas fa-trash-alt mr-1"></i> Delete
                                    </button>
                                </td>
                            `;
                            gradingScalesTableBody.appendChild(row);
                        });
                    } else {
                        gradingScalesTableBody.innerHTML = '<tr><td colspan="12" class="text-center py-4 text-gray-500">No grading scales found matching the selected filters.</td></tr>';
                    }
                } else {
                    gradingScalesTableBody.innerHTML = `<tr><td colspan="12" class="text-center py-4 text-red-500">Error: ${data.message}</td></tr>`;
                    showMessage(`Error fetching grading scales: ${data.message}`, 'error');
                }
            } catch (error) {
                gradingScalesTableBody.innerHTML = `<tr><td colspan="12" class="text-center py-4 text-red-500">Network error: ${error.message}</td></tr>`;
                showMessage(`Network error fetching grading scales: ${error.message}`, 'error');
                console.error('Error fetching grading scales:', error);
            }
        }

        function resetGradingScalesFilters() {
            if (filterGradeAcademicYear) filterGradeAcademicYear.value = '';
            if (filterGradeTerm) filterGradeTerm.value = '';
            if (filterGradeClassId) filterGradeClassId.value = '0';
            if (filterGradeSubjectId) filterGradeSubjectId.value = '0';
            fetchAndDisplayGradingScales();
        }

        function openDeleteGradingScaleModal(gradingScaleId, gradingScaleName) {
            document.getElementById('delete_grading_scale_id').value = gradingScaleId;
            document.getElementById('delete_grading_scale_name_display').textContent = gradingScaleName;
            openModal('deleteGradingScaleModal');
        }

        // Pending Reviews Functions
        
        function togglePendingReviews() {
            const isVisible = !pendingReviewsSection.classList.contains('hidden');
            
            if (isVisible) {
                // Hide pending reviews section
                pendingReviewsSection.classList.add('hidden');
                document.getElementById('pendingReviewsToggle').classList.remove('active');
                document.getElementById('pendingReviewsToggle').innerHTML = 
                    '<i class="fas fa-clock mr-2"></i> Pending Reviews <span id="pendingReviewsCount" class="ml-2 bg-orange-800 text-white text-xs px-2 py-1 rounded-full">0</span>';
            } else {
                // Show pending reviews section
                pendingReviewsSection.classList.remove('hidden');
                document.getElementById('pendingReviewsToggle').classList.add('active');
                document.getElementById('pendingReviewsToggle').innerHTML = 
                    '<i class="fas fa-times mr-2"></i> Hide Pending Reviews <span id="pendingReviewsCount" class="ml-2 bg-orange-800 text-white text-xs px-2 py-1 rounded-full">0</span>';
                
                // Load pending reviews
                loadPendingReviews();
            }
        }
        
        async function loadPendingReviews() {
            try {
                const response = await fetch('ajax_admin_exam_publishing.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'action=get_pending_reviews'
                });
                
                const data = await response.json();
                
                if (data.success) {
                    displayPendingReviews(data.data);
                    updatePendingReviewsCount(data.count);
                } else {
                    pendingReviewsTableBody.innerHTML = `<tr><td colspan="8" class="text-center py-8 text-red-500">Error: ${data.message}</td></tr>`;
                }
            } catch (error) {
                console.error('Error loading pending reviews:', error);
                pendingReviewsTableBody.innerHTML = `<tr><td colspan="8" class="text-center py-8 text-red-500">Network error: ${error.message}</td></tr>`;
            }
        }
        
        function displayPendingReviews(pendingExams) {
            if (!pendingExams || pendingExams.length === 0) {
                pendingReviewsTableBody.innerHTML = `
                    <tr>
                        <td colspan="8" class="text-center py-12">
                            <div class="text-gray-400">
                                <i class="fas fa-check-circle text-6xl mb-4"></i>
                                <h3 class="text-lg font-medium mb-2">All Caught Up!</h3>
                                <p>No exams are currently pending review.</p>
                            </div>
                        </td>
                    </tr>
                `;
                return;
            }
            
            let html = '';
            pendingExams.forEach(exam => {
                const submittedDate = new Date(exam.submitted_at).toLocaleDateString();
                const submittedTime = new Date(exam.submitted_at).toLocaleTimeString();
                
                html += `
                    <tr>
                        <td data-label="Exam Name" class="font-medium">${exam.exam_name}</td>
                        <td data-label="Teacher">${exam.teacher_name}</td>
                        <td data-label="Term/Year">${exam.term} ${exam.year}</td>
                        <td data-label="Type">
                            <span class="badge badge-info">${exam.exam_type}</span>
                        </td>
                        <td data-label="Classes">${exam.class_name}</td>
                        <td data-label="Subjects">${exam.subject_count} subjects</td>
                        <td data-label="Submitted" class="text-sm text-gray-600">
                            ${submittedDate}<br>
                            <span class="text-xs">${submittedTime}</span>
                        </td>
                        <td data-label="Actions" class="action-buttons-cell">
                            <button onclick="viewPendingExam(${exam.exam_id})" class="btn btn-view flex items-center mr-2">
                                <i class="fas fa-eye mr-1"></i> Review
                            </button>
                        </td>
                    </tr>
                `;
            });
            
            pendingReviewsTableBody.innerHTML = html;
        }
        
        function updatePendingReviewsCount(count) {
            const countElement = document.getElementById('pendingReviewsCount');
            if (countElement) {
                countElement.textContent = count;
                countElement.style.display = count > 0 ? 'inline-block' : 'none';
            }
        }
        
        async function viewPendingExam(examId) {
            try {
                const response = await fetch('ajax_admin_exam_publishing.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `action=get_exam_details&exam_id=${examId}`
                });
                
                const data = await response.json();
                
                if (data.success) {
                    currentPendingExam = data.exam;
                    displayPendingExamDetails(data.exam);
                    openModal('viewPendingExamModal');
                } else {
                    showMessage(`Error loading exam details: ${data.message}`, 'error');
                }
            } catch (error) {
                console.error('Error loading exam details:', error);
                showMessage(`Network error loading exam details: ${error.message}`, 'error');
            }
        }
        
        function displayPendingExamDetails(exam) {
            // Display basic exam info
            const detailsHtml = `
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    <div>
                        <h4 class="font-semibold text-gray-800 mb-2">${exam.exam_name}</h4>
                        <p class="text-sm text-gray-600">${exam.exam_type} • ${exam.term} ${exam.year}</p>
                    </div>
                    <div class="text-right">
                        <p class="text-sm text-gray-600">Submitted by: <strong>${exam.teacher_name}</strong></p>
                        <p class="text-xs text-gray-500">${new Date(exam.teacher_submitted_at).toLocaleString()}</p>
                    </div>
                </div>
            `;
            
            document.getElementById('pendingExamDetails').innerHTML = detailsHtml;
            
            // Display classes
            const classesHtml = exam.classes.map(cls => `
                <span class="inline-block bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs mr-2 mb-2">${cls.class_name}</span>
            `).join('');
            document.getElementById('pendingExamClasses').innerHTML = classesHtml || '<span class="text-xs text-gray-500">No classes found</span>';
            
            // Display subjects with marks status
            const subjectsHtml = exam.subjects.map(subject => `
                <div class="flex justify-between items-center mb-2 p-2 bg-gray-50 rounded">
                    <span>${subject.subject_name}</span>
                    <div class="text-right">
                        <span class="text-xs text-gray-600">${subject.students_with_marks}/${subject.total_students} marks</span>
                        <div class="w-20 bg-gray-200 rounded-full h-2 mt-1">
                            <div class="bg-green-500 h-2 rounded-full" style="width: ${subject.completion_percentage}%"></div>
                        </div>
                    </div>
                </div>
            `).join('');
            document.getElementById('pendingExamSubjects').innerHTML = subjectsHtml || '<span class="text-xs text-gray-500">No subjects found</span>';
            
            // Store exam ID for approve/reject actions
            document.getElementById('approve_exam_id').value = exam.exam_id;
            document.getElementById('reject_exam_id').value = exam.exam_id;
        }
        
        function openApproveExamModal() {
            closeModals();
            openModal('approveExamModal');
        }
        
        function openRejectExamModal() {
            closeModals();
            openModal('rejectExamModal');
        }

        async function openEditGradingScaleModal(gradingScaleId) {
            try {
                const response = await fetch(`admin_exams.php?action=get_grading_scale&id=${gradingScaleId}`);
                const data = await response.json();

                if (data.success) {
                    const scale = data.data;
                    
                    // Set hidden ID
                    document.getElementById('edit_grading_scale_id').value = scale.id;
                    
                    // Set read-only fields
                    document.getElementById('edit_grade_name').value = scale.grade_name || 'N/A';
                    document.getElementById('edit_academic_year').value = scale.academic_year || 'All Years';
                    document.getElementById('edit_term_name').value = scale.term_name || 'All Terms';
                    document.getElementById('edit_class_name').value = scale.class_name || 'All Classes';
                    document.getElementById('edit_subject_name').value = scale.subject_name || 'All Subjects';
                    
                    // Set editable fields
                    document.getElementById('edit_min_score').value = scale.min_score;
                    document.getElementById('edit_max_score').value = scale.max_score;
                    document.getElementById('edit_grade_letter').value = scale.grade_letter;
                    document.getElementById('edit_grade').value = scale.grade || '';
                    document.getElementById('edit_remarks').value = scale.remarks || '';
                    
                    // Open the modal
                    openModal('editGradingScaleModal');
                } else {
                    showMessage(`Error loading grading scale: ${data.message}`, 'error');
                }
            } catch (error) {
                showMessage(`Network error loading grading scale: ${error.message}`, 'error');
                console.error('Error loading grading scale:', error);
            }
        }

        // Setup form handlers for admin exam publishing
        document.addEventListener('DOMContentLoaded', function() {
            
            // DEBUG: Add event listener for publish form submission
            // COMMENTED OUT - This was causing issues with publish button functionality
            /*
            document.addEventListener('submit', function(e) {
                const form = e.target;
                const action = form.querySelector('input[name="action"]');
                
                if (action && action.value === 'confirm_publish_exam') {
                    console.log('🚀 PUBLISH FORM SUBMISSION DETECTED');
                    console.log('🚀 Form action:', action.value);
                    console.log('🚀 Form method:', form.method);
                    console.log('🚀 Form action URL:', form.action);
                    console.log('🚀 Exam ID:', form.querySelector('input[name="exam_id"]').value);
                    console.log('🚀 Preventing default submission for debugging');
                    e.preventDefault();
                    
                    // Manual form submission after logging
                    setTimeout(() => {
                        console.log('🚀 Submitting form manually...');
                        form.submit();
                    }, 100);
                }
            });
            */
            // Approve exam form
            const approveForm = document.getElementById('approveExamForm');
            if (approveForm) {
                approveForm.addEventListener('submit', async function(e) {
                    e.preventDefault();
                    
                    const formData = new FormData(this);
                    formData.append('action', 'approve_exam');
                    
                    try {
                        const response = await fetch('ajax_admin_exam_publishing.php', {
                            method: 'POST',
                            body: formData
                        });
                        
                        const data = await response.json();
                        
                        if (data.success) {
                            showMessage(data.message, 'success');
                            closeModals();
                            loadPendingReviews(); // Refresh the list
                        } else {
                            showMessage(data.message, 'error');
                        }
                    } catch (error) {
                        console.error('Error approving exam:', error);
                        showMessage(`Network error: ${error.message}`, 'error');
                    }
                });
            }
            
            // Reject exam form
            const rejectForm = document.getElementById('rejectExamForm');
            if (rejectForm) {
                rejectForm.addEventListener('submit', async function(e) {
                    e.preventDefault();
                    
                    const adminNotes = document.getElementById('reject_admin_notes').value.trim();
                    if (!adminNotes) {
                        showMessage('Please provide feedback for the teacher.', 'error');
                        return;
                    }
                    
                    const formData = new FormData();
                    formData.append('action', 'reject_exam');
                    formData.append('exam_id', document.getElementById('reject_exam_id').value);
                    formData.append('teacher_user_id', currentPendingExam ? currentPendingExam.created_by : 0);
                    formData.append('admin_notes', adminNotes);
                    
                    try {
                        const response = await fetch('ajax_admin_exam_publishing.php', {
                            method: 'POST',
                            body: formData
                        });
                        
                        const data = await response.json();
                        
                        if (data.success) {
                            showMessage(data.message, 'success');
                            closeModals();
                            loadPendingReviews(); // Refresh the list
                        } else {
                            showMessage(data.message, 'error');
                        }
                    } catch (error) {
                        console.error('Error rejecting exam:', error);
                        showMessage(`Network error: ${error.message}`, 'error');
                    }
                });
            }
        });

    </script>
</body>
</html>
<?php
// Close the database connection at the very end
if (isset($conn)) {
    $conn->close();
}
?>