<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| SMI Core Periods
| Full Admin Exams System
|--------------------------------------------------------------------------
| File: public_html/student-gateway/admin/exams.php
| Parts: 1/7
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/admin-auth.php';

$pdo = db();

date_default_timezone_set('Asia/Riyadh');

/*
|--------------------------------------------------------------------------
| Admin Auth
|--------------------------------------------------------------------------
*/

if (function_exists('requireAdmin')) {
    requireAdmin();
} elseif (function_exists('requireAdminLogin')) {
    requireAdminLogin();
}

$admin = null;

if (function_exists('currentAdmin')) {
    $admin = currentAdmin($pdo);
}

if (!$admin && !empty($_SESSION['core_admin_id'])) {
    $stmt = $pdo->prepare("SELECT * FROM core_admins WHERE id = ? LIMIT 1");
    $stmt->execute([(int)$_SESSION['core_admin_id']]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}

if (!$admin) {
    header('Location: ../login.php');
    exit;
}

$adminId = (int)($admin['id'] ?? $_SESSION['core_admin_id'] ?? 0);

/*
|--------------------------------------------------------------------------
| Safe Helpers
|--------------------------------------------------------------------------
*/

if (!function_exists('e')) {
    function e($value): string
    {
        return htmlspecialchars((string)($value ?? ''), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

if (!function_exists('safeOne')) {
    function safeOne(PDO $pdo, string $sql, array $params = []): ?array
    {
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            return $row ?: null;
        } catch (Throwable $e) {
            return null;
        }
    }
}

if (!function_exists('safeAll')) {
    function safeAll(PDO $pdo, string $sql, array $params = []): array
    {
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } catch (Throwable $e) {
            return [];
        }
    }
}

if (!function_exists('safeCount')) {
    function safeCount(PDO $pdo, string $sql, array $params = []): int
    {
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            return (int)$stmt->fetchColumn();
        } catch (Throwable $e) {
            return 0;
        }
    }
}

if (!function_exists('tableExists')) {
    function tableExists(PDO $pdo, string $table): bool
    {
        try {
            $stmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM information_schema.TABLES
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = ?
            ");
            $stmt->execute([$table]);
            return (int)$stmt->fetchColumn() > 0;
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('columnExists')) {
    function columnExists(PDO $pdo, string $table, string $column): bool
    {
        try {
            $stmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM information_schema.COLUMNS
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = ?
                  AND COLUMN_NAME = ?
            ");
            $stmt->execute([$table, $column]);
            return (int)$stmt->fetchColumn() > 0;
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('indexExists')) {
    function indexExists(PDO $pdo, string $table, string $index): bool
    {
        try {
            $stmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM information_schema.STATISTICS
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = ?
                  AND INDEX_NAME = ?
            ");
            $stmt->execute([$table, $index]);
            return (int)$stmt->fetchColumn() > 0;
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('safeExec')) {
    function safeExec(PDO $pdo, string $sql): bool
    {
        try {
            $pdo->exec($sql);
            return true;
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('addColumnIfMissing')) {
    function addColumnIfMissing(PDO $pdo, string $table, string $column, string $definition): void
    {
        if (tableExists($pdo, $table) && !columnExists($pdo, $table, $column)) {
            safeExec($pdo, "ALTER TABLE `$table` ADD COLUMN `$column` $definition");
        }
    }
}

if (!function_exists('addIndexIfMissing')) {
    function addIndexIfMissing(PDO $pdo, string $table, string $indexName, string $indexSql): void
    {
        if (tableExists($pdo, $table) && !indexExists($pdo, $table, $indexName)) {
            safeExec($pdo, "ALTER TABLE `$table` ADD $indexSql");
        }
    }
}

if (!function_exists('formatDateTimeNice')) {
    function formatDateTimeNice($value): string
    {
        if (empty($value) || $value === '0000-00-00 00:00:00') {
            return 'N/A';
        }

        $time = strtotime((string)$value);
        return $time ? date('M d, Y - h:i A', $time) : 'N/A';
    }
}

if (!function_exists('formatDateNice')) {
    function formatDateNice($value): string
    {
        if (empty($value) || $value === '0000-00-00') {
            return 'N/A';
        }

        $time = strtotime((string)$value);
        return $time ? date('M d, Y', $time) : 'N/A';
    }
}

if (!function_exists('generateExamCode')) {
    function generateExamCode(PDO $pdo): string
    {
        do {
            $code = 'EX-' . strtoupper(substr(bin2hex(random_bytes(4)), 0, 8));

            $exists = safeCount(
                $pdo,
                "SELECT COUNT(*) FROM core_exams WHERE exam_code = ?",
                [$code]
            );
        } while ($exists > 0);

        return $code;
    }
}

if (!function_exists('statusBadgeClass')) {
    function statusBadgeClass(string $status): string
    {
        return match ($status) {
            'published' => 'badge-green',
            'draft' => 'badge-gray',
            'closed' => 'badge-red',
            'archived' => 'badge-dark',
            default => 'badge-gray',
        };
    }
}

if (!function_exists('attemptStatusBadgeClass')) {
    function attemptStatusBadgeClass(string $status): string
    {
        return match ($status) {
            'submitted' => 'badge-blue',
            'graded' => 'badge-green',
            'in_progress' => 'badge-orange',
            'expired' => 'badge-red',
            'cancelled' => 'badge-dark',
            default => 'badge-gray',
        };
    }
}

if (!function_exists('examTypeLabel')) {
    function examTypeLabel(string $type): string
    {
        return match ($type) {
            'quiz' => 'Quiz',
            'midterm' => 'Midterm Exam',
            'final' => 'Final Exam',
            'placement' => 'Placement Test',
            'practice' => 'Practice Exam',
            'homework_exam' => 'Homework Exam',
            default => ucfirst(str_replace('_', ' ', $type)),
        };
    }
}

if (!function_exists('questionTypeLabel')) {
    function questionTypeLabel(string $type): string
    {
        return match ($type) {
            'multiple_choice' => 'Multiple Choice',
            'true_false' => 'True / False',
            'fill_blank' => 'Fill in the Blank',
            'short_answer' => 'Short Answer',
            'essay' => 'Essay',
            'listening' => 'Listening',
            'speaking' => 'Speaking',
            'file_upload' => 'File Upload',
            default => ucfirst(str_replace('_', ' ', $type)),
        };
    }
}

/*
|--------------------------------------------------------------------------
| CSRF
|--------------------------------------------------------------------------
*/

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$csrfToken = (string)$_SESSION['csrf_token'];

function verifyCsrf(): void
{
    $token = (string)($_POST['csrf_token'] ?? '');

    if (
        empty($_SESSION['csrf_token']) ||
        !hash_equals((string)$_SESSION['csrf_token'], $token)
    ) {
        throw new Exception('Security token expired. Please refresh the page and try again.');
    }
}

/*
|--------------------------------------------------------------------------
| Flash Messages
|--------------------------------------------------------------------------
*/

$successMessage = (string)($_SESSION['success'] ?? '');
$errorMessage = (string)($_SESSION['error'] ?? '');

unset($_SESSION['success'], $_SESSION['error']);

function setSuccess(string $message): void
{
    $_SESSION['success'] = $message;
}

function setError(string $message): void
{
    $_SESSION['error'] = $message;
}

/*
|--------------------------------------------------------------------------
| Auto Migration - Safe, No DROP, No DELETE
|--------------------------------------------------------------------------
*/

function ensureExamSystemTables(PDO $pdo): void
{
    /*
    |--------------------------------------------------------------------------
    | core_exams
    |--------------------------------------------------------------------------
    */

    if (!tableExists($pdo, 'core_exams')) {
        safeExec($pdo, "
            CREATE TABLE core_exams (
                id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                course_id INT UNSIGNED NOT NULL,
                teacher_id INT UNSIGNED NULL,
                title VARCHAR(255) NOT NULL,
                description TEXT NULL,
                exam_type VARCHAR(50) DEFAULT 'quiz',
                exam_code VARCHAR(80) NULL,
                start_at DATETIME NULL,
                end_at DATETIME NULL,
                duration_minutes INT UNSIGNED DEFAULT 60,
                total_marks DECIMAL(8,2) DEFAULT 0.00,
                passing_marks DECIMAL(8,2) DEFAULT 0.00,
                max_attempts INT UNSIGNED DEFAULT 1,
                shuffle_questions TINYINT(1) DEFAULT 0,
                show_result_immediately TINYINT(1) DEFAULT 1,
                show_correct_answers TINYINT(1) DEFAULT 0,
                require_exam_code TINYINT(1) DEFAULT 0,
                release_results_at DATETIME NULL,
                allow_resume TINYINT(1) DEFAULT 1,
                autosave_enabled TINYINT(1) DEFAULT 1,
                anti_cheating_enabled TINYINT(1) DEFAULT 1,
                gradebook_enabled TINYINT(1) DEFAULT 1,
                certificate_enabled TINYINT(1) DEFAULT 0,
                retake_policy VARCHAR(50) DEFAULT 'highest',
                retake_wait_hours INT UNSIGNED DEFAULT 0,
                status VARCHAR(30) DEFAULT 'draft',
                created_by_admin_id INT UNSIGNED NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME NULL,
                INDEX idx_course_id (course_id),
                INDEX idx_teacher_id (teacher_id),
                INDEX idx_status (status),
                UNIQUE KEY unique_exam_code (exam_code)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    }

    $examColumns = [
        'course_id' => "INT UNSIGNED NOT NULL DEFAULT 0",
        'teacher_id' => "INT UNSIGNED NULL",
        'title' => "VARCHAR(255) NOT NULL DEFAULT ''",
        'description' => "TEXT NULL",
        'exam_type' => "VARCHAR(50) DEFAULT 'quiz'",
        'exam_code' => "VARCHAR(80) NULL",
        'start_at' => "DATETIME NULL",
        'end_at' => "DATETIME NULL",
        'duration_minutes' => "INT UNSIGNED DEFAULT 60",
        'total_marks' => "DECIMAL(8,2) DEFAULT 0.00",
        'passing_marks' => "DECIMAL(8,2) DEFAULT 0.00",
        'max_attempts' => "INT UNSIGNED DEFAULT 1",
        'shuffle_questions' => "TINYINT(1) DEFAULT 0",
        'show_result_immediately' => "TINYINT(1) DEFAULT 1",
        'show_correct_answers' => "TINYINT(1) DEFAULT 0",
        'require_exam_code' => "TINYINT(1) DEFAULT 0",
        'release_results_at' => "DATETIME NULL",
        'allow_resume' => "TINYINT(1) DEFAULT 1",
        'autosave_enabled' => "TINYINT(1) DEFAULT 1",
        'anti_cheating_enabled' => "TINYINT(1) DEFAULT 1",
        'gradebook_enabled' => "TINYINT(1) DEFAULT 1",
        'certificate_enabled' => "TINYINT(1) DEFAULT 0",
        'retake_policy' => "VARCHAR(50) DEFAULT 'highest'",
        'retake_wait_hours' => "INT UNSIGNED DEFAULT 0",
        'status' => "VARCHAR(30) DEFAULT 'draft'",
        'created_by_admin_id' => "INT UNSIGNED NULL",
        'created_at' => "DATETIME DEFAULT CURRENT_TIMESTAMP",
        'updated_at' => "DATETIME NULL"
    ];

    foreach ($examColumns as $column => $definition) {
        addColumnIfMissing($pdo, 'core_exams', $column, $definition);
    }

    addIndexIfMissing($pdo, 'core_exams', 'idx_course_id', 'INDEX idx_course_id (course_id)');
    addIndexIfMissing($pdo, 'core_exams', 'idx_teacher_id', 'INDEX idx_teacher_id (teacher_id)');
    addIndexIfMissing($pdo, 'core_exams', 'idx_status', 'INDEX idx_status (status)');

    /*
    |--------------------------------------------------------------------------
    | core_exam_questions
    |--------------------------------------------------------------------------
    */

    if (!tableExists($pdo, 'core_exam_questions')) {
        safeExec($pdo, "
            CREATE TABLE core_exam_questions (
                id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                exam_id INT UNSIGNED NOT NULL,
                bank_question_id INT UNSIGNED NULL,
                section_name VARCHAR(100) NULL,
                skill VARCHAR(80) NULL,
                question_text LONGTEXT NOT NULL,
                question_type VARCHAR(50) NOT NULL DEFAULT 'multiple_choice',
                marks DECIMAL(8,2) DEFAULT 1.00,
                sort_order INT UNSIGNED DEFAULT 0,
                correct_answer LONGTEXT NULL,
                explanation TEXT NULL,
                difficulty VARCHAR(50) DEFAULT 'medium',
                audio_file VARCHAR(255) NULL,
                image_file VARCHAR(255) NULL,
                allow_file_upload TINYINT(1) DEFAULT 0,
                rubric_json LONGTEXT NULL,
                is_required TINYINT(1) DEFAULT 1,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME NULL,
                INDEX idx_exam_id (exam_id),
                INDEX idx_question_type (question_type)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    }

    $questionColumns = [
        'exam_id' => "INT UNSIGNED NOT NULL DEFAULT 0",
        'bank_question_id' => "INT UNSIGNED NULL",
        'section_name' => "VARCHAR(100) NULL",
        'skill' => "VARCHAR(80) NULL",
        'question_text' => "LONGTEXT NOT NULL",
        'question_type' => "VARCHAR(50) NOT NULL DEFAULT 'multiple_choice'",
        'marks' => "DECIMAL(8,2) DEFAULT 1.00",
        'sort_order' => "INT UNSIGNED DEFAULT 0",
        'correct_answer' => "LONGTEXT NULL",
        'explanation' => "TEXT NULL",
        'difficulty' => "VARCHAR(50) DEFAULT 'medium'",
        'audio_file' => "VARCHAR(255) NULL",
        'image_file' => "VARCHAR(255) NULL",
        'allow_file_upload' => "TINYINT(1) DEFAULT 0",
        'rubric_json' => "LONGTEXT NULL",
        'is_required' => "TINYINT(1) DEFAULT 1",
        'created_at' => "DATETIME DEFAULT CURRENT_TIMESTAMP",
        'updated_at' => "DATETIME NULL"
    ];

    foreach ($questionColumns as $column => $definition) {
        addColumnIfMissing($pdo, 'core_exam_questions', $column, $definition);
    }

    addIndexIfMissing($pdo, 'core_exam_questions', 'idx_exam_id', 'INDEX idx_exam_id (exam_id)');
    addIndexIfMissing($pdo, 'core_exam_questions', 'idx_question_type', 'INDEX idx_question_type (question_type)');

    /*
    |--------------------------------------------------------------------------
    | core_exam_options
    |--------------------------------------------------------------------------
    */

    if (!tableExists($pdo, 'core_exam_options')) {
        safeExec($pdo, "
            CREATE TABLE core_exam_options (
                id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                question_id INT UNSIGNED NOT NULL,
                option_text TEXT NOT NULL,
                is_correct TINYINT(1) DEFAULT 0,
                sort_order INT UNSIGNED DEFAULT 0,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                INDEX idx_question_id (question_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    }

    $optionColumns = [
        'question_id' => "INT UNSIGNED NOT NULL DEFAULT 0",
        'option_text' => "TEXT NOT NULL",
        'is_correct' => "TINYINT(1) DEFAULT 0",
        'sort_order' => "INT UNSIGNED DEFAULT 0",
        'created_at' => "DATETIME DEFAULT CURRENT_TIMESTAMP"
    ];

    foreach ($optionColumns as $column => $definition) {
        addColumnIfMissing($pdo, 'core_exam_options', $column, $definition);
    }

    addIndexIfMissing($pdo, 'core_exam_options', 'idx_question_id', 'INDEX idx_question_id (question_id)');

    /*
    |--------------------------------------------------------------------------
    | core_exam_attempts
    |--------------------------------------------------------------------------
    */

    if (!tableExists($pdo, 'core_exam_attempts')) {
        safeExec($pdo, "
            CREATE TABLE core_exam_attempts (
                id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                exam_id INT UNSIGNED NOT NULL,
                course_id INT UNSIGNED NOT NULL,
                student_id INT UNSIGNED NOT NULL,
                attempt_number INT UNSIGNED DEFAULT 1,
                exam_code_used VARCHAR(80) NULL,
                started_at DATETIME NULL,
                submitted_at DATETIME NULL,
                expires_at DATETIME NULL,
                status VARCHAR(30) DEFAULT 'in_progress',
                total_score DECIMAL(8,2) DEFAULT 0.00,
                percentage DECIMAL(6,2) DEFAULT 0.00,
                result_status VARCHAR(30) DEFAULT 'pending',
                auto_graded_score DECIMAL(8,2) DEFAULT 0.00,
                manual_graded_score DECIMAL(8,2) DEFAULT 0.00,
                feedback TEXT NULL,
                suspicious_events_count INT UNSIGNED DEFAULT 0,
                last_autosave_at DATETIME NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME NULL,
                INDEX idx_exam_id (exam_id),
                INDEX idx_course_id (course_id),
                INDEX idx_student_id (student_id),
                UNIQUE KEY unique_exam_student_attempt (exam_id, student_id, attempt_number)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    }

    $attemptColumns = [
        'exam_id' => "INT UNSIGNED NOT NULL DEFAULT 0",
        'course_id' => "INT UNSIGNED NOT NULL DEFAULT 0",
        'student_id' => "INT UNSIGNED NOT NULL DEFAULT 0",
        'attempt_number' => "INT UNSIGNED DEFAULT 1",
        'exam_code_used' => "VARCHAR(80) NULL",
        'started_at' => "DATETIME NULL",
        'submitted_at' => "DATETIME NULL",
        'expires_at' => "DATETIME NULL",
        'status' => "VARCHAR(30) DEFAULT 'in_progress'",
        'total_score' => "DECIMAL(8,2) DEFAULT 0.00",
        'percentage' => "DECIMAL(6,2) DEFAULT 0.00",
        'result_status' => "VARCHAR(30) DEFAULT 'pending'",
        'auto_graded_score' => "DECIMAL(8,2) DEFAULT 0.00",
        'manual_graded_score' => "DECIMAL(8,2) DEFAULT 0.00",
        'feedback' => "TEXT NULL",
        'suspicious_events_count' => "INT UNSIGNED DEFAULT 0",
        'last_autosave_at' => "DATETIME NULL",
        'created_at' => "DATETIME DEFAULT CURRENT_TIMESTAMP",
        'updated_at' => "DATETIME NULL"
    ];

    foreach ($attemptColumns as $column => $definition) {
        addColumnIfMissing($pdo, 'core_exam_attempts', $column, $definition);
    }

    addIndexIfMissing($pdo, 'core_exam_attempts', 'idx_exam_id', 'INDEX idx_exam_id (exam_id)');
    addIndexIfMissing($pdo, 'core_exam_attempts', 'idx_course_id', 'INDEX idx_course_id (course_id)');
    addIndexIfMissing($pdo, 'core_exam_attempts', 'idx_student_id', 'INDEX idx_student_id (student_id)');

    /*
    |--------------------------------------------------------------------------
    | core_exam_answers
    |--------------------------------------------------------------------------
    */

    if (!tableExists($pdo, 'core_exam_answers')) {
        safeExec($pdo, "
            CREATE TABLE core_exam_answers (
                id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                attempt_id INT UNSIGNED NOT NULL,
                exam_id INT UNSIGNED NOT NULL,
                question_id INT UNSIGNED NOT NULL,
                student_id INT UNSIGNED NOT NULL,
                answer_text LONGTEXT NULL,
                selected_option_id INT UNSIGNED NULL,
                uploaded_file VARCHAR(255) NULL,
                is_correct TINYINT(1) NULL,
                score_awarded DECIMAL(8,2) DEFAULT 0.00,
                teacher_feedback TEXT NULL,
                graded_by_teacher_id INT UNSIGNED NULL,
                graded_by_admin_id INT UNSIGNED NULL,
                graded_at DATETIME NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME NULL,
                INDEX idx_attempt_id (attempt_id),
                INDEX idx_exam_id (exam_id),
                INDEX idx_question_id (question_id),
                INDEX idx_student_id (student_id),
                UNIQUE KEY unique_attempt_question (attempt_id, question_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    }

    $answerColumns = [
        'attempt_id' => "INT UNSIGNED NOT NULL DEFAULT 0",
        'exam_id' => "INT UNSIGNED NOT NULL DEFAULT 0",
        'question_id' => "INT UNSIGNED NOT NULL DEFAULT 0",
        'student_id' => "INT UNSIGNED NOT NULL DEFAULT 0",
        'answer_text' => "LONGTEXT NULL",
        'selected_option_id' => "INT UNSIGNED NULL",
        'uploaded_file' => "VARCHAR(255) NULL",
        'is_correct' => "TINYINT(1) NULL",
        'score_awarded' => "DECIMAL(8,2) DEFAULT 0.00",
        'teacher_feedback' => "TEXT NULL",
        'graded_by_teacher_id' => "INT UNSIGNED NULL",
        'graded_by_admin_id' => "INT UNSIGNED NULL",
        'graded_at' => "DATETIME NULL",
        'created_at' => "DATETIME DEFAULT CURRENT_TIMESTAMP",
        'updated_at' => "DATETIME NULL"
    ];

    foreach ($answerColumns as $column => $definition) {
        addColumnIfMissing($pdo, 'core_exam_answers', $column, $definition);
    }

    addIndexIfMissing($pdo, 'core_exam_answers', 'idx_attempt_id', 'INDEX idx_attempt_id (attempt_id)');
    addIndexIfMissing($pdo, 'core_exam_answers', 'idx_exam_id', 'INDEX idx_exam_id (exam_id)');
    addIndexIfMissing($pdo, 'core_exam_answers', 'idx_question_id', 'INDEX idx_question_id (question_id)');
    addIndexIfMissing($pdo, 'core_exam_answers', 'idx_student_id', 'INDEX idx_student_id (student_id)');

    /*
    |--------------------------------------------------------------------------
    | core_question_bank
    |--------------------------------------------------------------------------
    */

    if (!tableExists($pdo, 'core_question_bank')) {
        safeExec($pdo, "
            CREATE TABLE core_question_bank (
                id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                course_id INT UNSIGNED NULL,
                teacher_id INT UNSIGNED NULL,
                section_name VARCHAR(100) NULL,
                skill VARCHAR(80) NULL,
                question_text LONGTEXT NOT NULL,
                question_type VARCHAR(50) NOT NULL DEFAULT 'multiple_choice',
                correct_answer LONGTEXT NULL,
                explanation TEXT NULL,
                marks DECIMAL(8,2) DEFAULT 1.00,
                difficulty VARCHAR(50) DEFAULT 'medium',
                tags VARCHAR(255) NULL,
                audio_file VARCHAR(255) NULL,
                image_file VARCHAR(255) NULL,
                rubric_json LONGTEXT NULL,
                created_by_admin_id INT UNSIGNED NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME NULL,
                INDEX idx_course_id (course_id),
                INDEX idx_teacher_id (teacher_id),
                INDEX idx_type (question_type),
                INDEX idx_skill (skill)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    }

    /*
    |--------------------------------------------------------------------------
    | core_exam_activity_logs
    |--------------------------------------------------------------------------
    */

    if (!tableExists($pdo, 'core_exam_activity_logs')) {
        safeExec($pdo, "
            CREATE TABLE core_exam_activity_logs (
                id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                exam_id INT UNSIGNED NOT NULL,
                attempt_id INT UNSIGNED NULL,
                student_id INT UNSIGNED NULL,
                event_type VARCHAR(80) NOT NULL,
                event_detail TEXT NULL,
                ip_address VARCHAR(80) NULL,
                user_agent TEXT NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                INDEX idx_exam_id (exam_id),
                INDEX idx_attempt_id (attempt_id),
                INDEX idx_student_id (student_id),
                INDEX idx_event_type (event_type)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    }

    /*
    |--------------------------------------------------------------------------
    | core_exam_autosaves
    |--------------------------------------------------------------------------
    */

    if (!tableExists($pdo, 'core_exam_autosaves')) {
        safeExec($pdo, "
            CREATE TABLE core_exam_autosaves (
                id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                attempt_id INT UNSIGNED NOT NULL,
                exam_id INT UNSIGNED NOT NULL,
                student_id INT UNSIGNED NOT NULL,
                answers_json LONGTEXT NULL,
                saved_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME NULL,
                UNIQUE KEY unique_attempt_autosave (attempt_id),
                INDEX idx_exam_id (exam_id),
                INDEX idx_student_id (student_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    }

    /*
    |--------------------------------------------------------------------------
    | Optional gradebook compatibility
    |--------------------------------------------------------------------------
    */

    if (tableExists($pdo, 'core_grade_items')) {
        addColumnIfMissing($pdo, 'core_grade_items', 'exam_id', "INT UNSIGNED NULL");
        addIndexIfMissing($pdo, 'core_grade_items', 'idx_exam_id', 'INDEX idx_exam_id (exam_id)');
    }

    if (tableExists($pdo, 'core_final_grades')) {
        addColumnIfMissing($pdo, 'core_final_grades', 'exam_score', "DECIMAL(8,2) DEFAULT 0.00");
        addColumnIfMissing($pdo, 'core_final_grades', 'exam_percentage', "DECIMAL(6,2) DEFAULT 0.00");
    }
}

ensureExamSystemTables($pdo);

/*
|--------------------------------------------------------------------------
| Page State
|--------------------------------------------------------------------------
*/

$pageTitle = 'SMI Admin Exams System';

$activeTab = (string)($_GET['tab'] ?? 'exams');

$allowedTabs = [
    'exams',
    'questions',
    'bank',
    'submissions',
    'reports',
    'codes',
    'schedule'
];

if (!in_array($activeTab, $allowedTabs, true)) {
    $activeTab = 'exams';
}

$selectedExamId = (int)($_GET['exam_id'] ?? 0);
$selectedCourseId = (int)($_GET['course_id'] ?? 0);
$selectedAttemptId = (int)($_GET['attempt_id'] ?? 0);

/*
|--------------------------------------------------------------------------
| Common Lists
|--------------------------------------------------------------------------
*/

$courses = safeAll(
    $pdo,
    "
    SELECT 
        c.*,
        t.full_name AS teacher_full_name,
        t.name AS teacher_name,
        t.email AS teacher_email
    FROM core_courses c
    LEFT JOIN core_teachers t ON t.id = c.teacher_id
    ORDER BY c.id DESC
    "
);

$teachers = safeAll(
    $pdo,
    "
    SELECT *
    FROM core_teachers
    ORDER BY COALESCE(full_name, name, email) ASC
    "
);

$examTypes = [
    'quiz',
    'midterm',
    'final',
    'placement',
    'practice',
    'homework_exam'
];

$examStatuses = [
    'draft',
    'published',
    'closed',
    'archived'
];

$questionTypes = [
    'multiple_choice',
    'true_false',
    'fill_blank',
    'short_answer',
    'essay',
    'listening',
    'speaking',
    'file_upload'
];

$skills = [
    'reading',
    'grammar',
    'vocabulary',
    'listening',
    'writing',
    'speaking',
    'general'
];


/*
|--------------------------------------------------------------------------
| POST Actions - Exams Management
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');

    try {
        verifyCsrf();

        /*
        |--------------------------------------------------------------------------
        | Create Exam
        |--------------------------------------------------------------------------
        */

        if ($action === 'create_exam') {
            $courseId = (int)($_POST['course_id'] ?? 0);
            $title = trim((string)($_POST['title'] ?? ''));
            $description = trim((string)($_POST['description'] ?? ''));
            $examType = trim((string)($_POST['exam_type'] ?? 'quiz'));
            $startAt = trim((string)($_POST['start_at'] ?? ''));
            $endAt = trim((string)($_POST['end_at'] ?? ''));
            $durationMinutes = max(1, (int)($_POST['duration_minutes'] ?? 60));
            $totalMarks = max(0, (float)($_POST['total_marks'] ?? 0));
            $passingMarks = max(0, (float)($_POST['passing_marks'] ?? 0));
            $maxAttempts = max(1, (int)($_POST['max_attempts'] ?? 1));
            $status = trim((string)($_POST['status'] ?? 'draft'));

            if ($courseId <= 0) {
                throw new Exception('Please choose a course.');
            }

            if ($title === '') {
                throw new Exception('Exam title is required.');
            }

            if (!in_array($examType, $examTypes, true)) {
                $examType = 'quiz';
            }

            if (!in_array($status, $examStatuses, true)) {
                $status = 'draft';
            }

            $course = safeOne(
                $pdo,
                "SELECT * FROM core_courses WHERE id = ? LIMIT 1",
                [$courseId]
            );

            if (!$course) {
                throw new Exception('Selected course was not found.');
            }

            $teacherId = (int)($course['teacher_id'] ?? 0);

            if ($teacherId <= 0 && !empty($_POST['teacher_id'])) {
                $teacherId = (int)$_POST['teacher_id'];
            }

            $examCode = trim((string)($_POST['exam_code'] ?? ''));

            if ($examCode === '') {
                $examCode = generateExamCode($pdo);
            }

            $shuffleQuestions = !empty($_POST['shuffle_questions']) ? 1 : 0;
            $showResultImmediately = !empty($_POST['show_result_immediately']) ? 1 : 0;
            $showCorrectAnswers = !empty($_POST['show_correct_answers']) ? 1 : 0;
            $requireExamCode = !empty($_POST['require_exam_code']) ? 1 : 0;
            $allowResume = !empty($_POST['allow_resume']) ? 1 : 0;
            $autosaveEnabled = !empty($_POST['autosave_enabled']) ? 1 : 0;
            $antiCheatingEnabled = !empty($_POST['anti_cheating_enabled']) ? 1 : 0;
            $gradebookEnabled = !empty($_POST['gradebook_enabled']) ? 1 : 0;
            $certificateEnabled = !empty($_POST['certificate_enabled']) ? 1 : 0;

            $releaseResultsAt = trim((string)($_POST['release_results_at'] ?? ''));
            $retakePolicy = trim((string)($_POST['retake_policy'] ?? 'highest'));
            $retakeWaitHours = max(0, (int)($_POST['retake_wait_hours'] ?? 0));

            if (!in_array($retakePolicy, ['highest', 'latest', 'first'], true)) {
                $retakePolicy = 'highest';
            }

            $stmt = $pdo->prepare("
                INSERT INTO core_exams (
                    course_id,
                    teacher_id,
                    title,
                    description,
                    exam_type,
                    exam_code,
                    start_at,
                    end_at,
                    duration_minutes,
                    total_marks,
                    passing_marks,
                    max_attempts,
                    shuffle_questions,
                    show_result_immediately,
                    show_correct_answers,
                    require_exam_code,
                    release_results_at,
                    allow_resume,
                    autosave_enabled,
                    anti_cheating_enabled,
                    gradebook_enabled,
                    certificate_enabled,
                    retake_policy,
                    retake_wait_hours,
                    status,
                    created_by_admin_id,
                    created_at,
                    updated_at
                ) VALUES (
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW()
                )
            ");

            $stmt->execute([
                $courseId,
                $teacherId > 0 ? $teacherId : null,
                $title,
                $description,
                $examType,
                $examCode,
                $startAt !== '' ? date('Y-m-d H:i:s', strtotime($startAt)) : null,
                $endAt !== '' ? date('Y-m-d H:i:s', strtotime($endAt)) : null,
                $durationMinutes,
                $totalMarks,
                $passingMarks,
                $maxAttempts,
                $shuffleQuestions,
                $showResultImmediately,
                $showCorrectAnswers,
                $requireExamCode,
                $releaseResultsAt !== '' ? date('Y-m-d H:i:s', strtotime($releaseResultsAt)) : null,
                $allowResume,
                $autosaveEnabled,
                $antiCheatingEnabled,
                $gradebookEnabled,
                $certificateEnabled,
                $retakePolicy,
                $retakeWaitHours,
                $status,
                $adminId > 0 ? $adminId : null
            ]);

            $newExamId = (int)$pdo->lastInsertId();

            setSuccess('Exam created successfully.');

            header('Location: exams.php?tab=questions&exam_id=' . $newExamId);
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Update Exam
        |--------------------------------------------------------------------------
        */

        if ($action === 'update_exam') {
            $examId = (int)($_POST['exam_id'] ?? 0);

            if ($examId <= 0) {
                throw new Exception('Invalid exam.');
            }

            $exam = safeOne($pdo, "SELECT * FROM core_exams WHERE id = ? LIMIT 1", [$examId]);

            if (!$exam) {
                throw new Exception('Exam was not found.');
            }

            $courseId = (int)($_POST['course_id'] ?? 0);
            $title = trim((string)($_POST['title'] ?? ''));
            $description = trim((string)($_POST['description'] ?? ''));
            $examType = trim((string)($_POST['exam_type'] ?? 'quiz'));
            $examCode = trim((string)($_POST['exam_code'] ?? ''));
            $startAt = trim((string)($_POST['start_at'] ?? ''));
            $endAt = trim((string)($_POST['end_at'] ?? ''));
            $durationMinutes = max(1, (int)($_POST['duration_minutes'] ?? 60));
            $totalMarks = max(0, (float)($_POST['total_marks'] ?? 0));
            $passingMarks = max(0, (float)($_POST['passing_marks'] ?? 0));
            $maxAttempts = max(1, (int)($_POST['max_attempts'] ?? 1));
            $status = trim((string)($_POST['status'] ?? 'draft'));

            if ($courseId <= 0) {
                throw new Exception('Please choose a course.');
            }

            if ($title === '') {
                throw new Exception('Exam title is required.');
            }

            if (!in_array($examType, $examTypes, true)) {
                $examType = 'quiz';
            }

            if (!in_array($status, $examStatuses, true)) {
                $status = 'draft';
            }

            if ($examCode === '') {
                $examCode = generateExamCode($pdo);
            }

            $course = safeOne(
                $pdo,
                "SELECT * FROM core_courses WHERE id = ? LIMIT 1",
                [$courseId]
            );

            if (!$course) {
                throw new Exception('Selected course was not found.');
            }

            $teacherId = (int)($course['teacher_id'] ?? 0);

            if ($teacherId <= 0 && !empty($_POST['teacher_id'])) {
                $teacherId = (int)$_POST['teacher_id'];
            }

            $existingCode = safeOne(
                $pdo,
                "SELECT id FROM core_exams WHERE exam_code = ? AND id <> ? LIMIT 1",
                [$examCode, $examId]
            );

            if ($existingCode) {
                throw new Exception('This exam code already exists. Please use another code.');
            }

            $shuffleQuestions = !empty($_POST['shuffle_questions']) ? 1 : 0;
            $showResultImmediately = !empty($_POST['show_result_immediately']) ? 1 : 0;
            $showCorrectAnswers = !empty($_POST['show_correct_answers']) ? 1 : 0;
            $requireExamCode = !empty($_POST['require_exam_code']) ? 1 : 0;
            $allowResume = !empty($_POST['allow_resume']) ? 1 : 0;
            $autosaveEnabled = !empty($_POST['autosave_enabled']) ? 1 : 0;
            $antiCheatingEnabled = !empty($_POST['anti_cheating_enabled']) ? 1 : 0;
            $gradebookEnabled = !empty($_POST['gradebook_enabled']) ? 1 : 0;
            $certificateEnabled = !empty($_POST['certificate_enabled']) ? 1 : 0;

            $releaseResultsAt = trim((string)($_POST['release_results_at'] ?? ''));
            $retakePolicy = trim((string)($_POST['retake_policy'] ?? 'highest'));
            $retakeWaitHours = max(0, (int)($_POST['retake_wait_hours'] ?? 0));

            if (!in_array($retakePolicy, ['highest', 'latest', 'first'], true)) {
                $retakePolicy = 'highest';
            }

            $stmt = $pdo->prepare("
                UPDATE core_exams
                SET
                    course_id = ?,
                    teacher_id = ?,
                    title = ?,
                    description = ?,
                    exam_type = ?,
                    exam_code = ?,
                    start_at = ?,
                    end_at = ?,
                    duration_minutes = ?,
                    total_marks = ?,
                    passing_marks = ?,
                    max_attempts = ?,
                    shuffle_questions = ?,
                    show_result_immediately = ?,
                    show_correct_answers = ?,
                    require_exam_code = ?,
                    release_results_at = ?,
                    allow_resume = ?,
                    autosave_enabled = ?,
                    anti_cheating_enabled = ?,
                    gradebook_enabled = ?,
                    certificate_enabled = ?,
                    retake_policy = ?,
                    retake_wait_hours = ?,
                    status = ?,
                    updated_at = NOW()
                WHERE id = ?
            ");

            $stmt->execute([
                $courseId,
                $teacherId > 0 ? $teacherId : null,
                $title,
                $description,
                $examType,
                $examCode,
                $startAt !== '' ? date('Y-m-d H:i:s', strtotime($startAt)) : null,
                $endAt !== '' ? date('Y-m-d H:i:s', strtotime($endAt)) : null,
                $durationMinutes,
                $totalMarks,
                $passingMarks,
                $maxAttempts,
                $shuffleQuestions,
                $showResultImmediately,
                $showCorrectAnswers,
                $requireExamCode,
                $releaseResultsAt !== '' ? date('Y-m-d H:i:s', strtotime($releaseResultsAt)) : null,
                $allowResume,
                $autosaveEnabled,
                $antiCheatingEnabled,
                $gradebookEnabled,
                $certificateEnabled,
                $retakePolicy,
                $retakeWaitHours,
                $status,
                $examId
            ]);

            setSuccess('Exam updated successfully.');

            header('Location: exams.php?tab=exams&exam_id=' . $examId);
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Quick Status Actions
        |--------------------------------------------------------------------------
        */

        if (in_array($action, ['publish_exam', 'close_exam', 'archive_exam', 'restore_exam'], true)) {
            $examId = (int)($_POST['exam_id'] ?? 0);

            if ($examId <= 0) {
                throw new Exception('Invalid exam.');
            }

            $exam = safeOne($pdo, "SELECT * FROM core_exams WHERE id = ? LIMIT 1", [$examId]);

            if (!$exam) {
                throw new Exception('Exam was not found.');
            }

            $newStatus = match ($action) {
                'publish_exam' => 'published',
                'close_exam' => 'closed',
                'archive_exam' => 'archived',
                'restore_exam' => 'draft',
                default => 'draft',
            };

            $stmt = $pdo->prepare("
                UPDATE core_exams
                SET status = ?, updated_at = NOW()
                WHERE id = ?
            ");

            $stmt->execute([$newStatus, $examId]);

            setSuccess('Exam status updated successfully.');

            header('Location: exams.php?tab=exams&exam_id=' . $examId);
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Regenerate Exam Code
        |--------------------------------------------------------------------------
        */

        if ($action === 'regenerate_exam_code') {
            $examId = (int)($_POST['exam_id'] ?? 0);

            if ($examId <= 0) {
                throw new Exception('Invalid exam.');
            }

            $exam = safeOne($pdo, "SELECT * FROM core_exams WHERE id = ? LIMIT 1", [$examId]);

            if (!$exam) {
                throw new Exception('Exam was not found.');
            }

            $newCode = generateExamCode($pdo);

            $stmt = $pdo->prepare("
                UPDATE core_exams
                SET exam_code = ?, updated_at = NOW()
                WHERE id = ?
            ");

            $stmt->execute([$newCode, $examId]);

            setSuccess('New exam code generated successfully: ' . $newCode);

            header('Location: exams.php?tab=codes&exam_id=' . $examId);
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Toggle Exam Code Requirement
        |--------------------------------------------------------------------------
        */

        if ($action === 'toggle_exam_code_requirement') {
            $examId = (int)($_POST['exam_id'] ?? 0);

            if ($examId <= 0) {
                throw new Exception('Invalid exam.');
            }

            $exam = safeOne($pdo, "SELECT * FROM core_exams WHERE id = ? LIMIT 1", [$examId]);

            if (!$exam) {
                throw new Exception('Exam was not found.');
            }

            $newValue = (int)!((int)($exam['require_exam_code'] ?? 0));

            $stmt = $pdo->prepare("
                UPDATE core_exams
                SET require_exam_code = ?, updated_at = NOW()
                WHERE id = ?
            ");

            $stmt->execute([$newValue, $examId]);

            setSuccess('Exam code requirement updated successfully.');

            header('Location: exams.php?tab=codes&exam_id=' . $examId);
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Duplicate Exam
        |--------------------------------------------------------------------------
        */

        if ($action === 'duplicate_exam') {
            $examId = (int)($_POST['exam_id'] ?? 0);

            if ($examId <= 0) {
                throw new Exception('Invalid exam.');
            }

            $exam = safeOne($pdo, "SELECT * FROM core_exams WHERE id = ? LIMIT 1", [$examId]);

            if (!$exam) {
                throw new Exception('Exam was not found.');
            }

            $pdo->beginTransaction();

            $newCode = generateExamCode($pdo);

            $stmt = $pdo->prepare("
                INSERT INTO core_exams (
                    course_id,
                    teacher_id,
                    title,
                    description,
                    exam_type,
                    exam_code,
                    start_at,
                    end_at,
                    duration_minutes,
                    total_marks,
                    passing_marks,
                    max_attempts,
                    shuffle_questions,
                    show_result_immediately,
                    show_correct_answers,
                    require_exam_code,
                    release_results_at,
                    allow_resume,
                    autosave_enabled,
                    anti_cheating_enabled,
                    gradebook_enabled,
                    certificate_enabled,
                    retake_policy,
                    retake_wait_hours,
                    status,
                    created_by_admin_id,
                    created_at,
                    updated_at
                ) VALUES (
                    ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, 'draft', ?, NOW(), NOW()
                )
            ");

            $stmt->execute([
                (int)$exam['course_id'],
                !empty($exam['teacher_id']) ? (int)$exam['teacher_id'] : null,
                'Copy of ' . (string)$exam['title'],
                (string)($exam['description'] ?? ''),
                (string)($exam['exam_type'] ?? 'quiz'),
                $newCode,
                (int)($exam['duration_minutes'] ?? 60),
                (float)($exam['total_marks'] ?? 0),
                (float)($exam['passing_marks'] ?? 0),
                (int)($exam['max_attempts'] ?? 1),
                (int)($exam['shuffle_questions'] ?? 0),
                (int)($exam['show_result_immediately'] ?? 1),
                (int)($exam['show_correct_answers'] ?? 0),
                (int)($exam['require_exam_code'] ?? 0),
                (int)($exam['allow_resume'] ?? 1),
                (int)($exam['autosave_enabled'] ?? 1),
                (int)($exam['anti_cheating_enabled'] ?? 1),
                (int)($exam['gradebook_enabled'] ?? 1),
                (int)($exam['certificate_enabled'] ?? 0),
                (string)($exam['retake_policy'] ?? 'highest'),
                (int)($exam['retake_wait_hours'] ?? 0),
                $adminId > 0 ? $adminId : null
            ]);

            $newExamId = (int)$pdo->lastInsertId();

            $questions = safeAll(
                $pdo,
                "SELECT * FROM core_exam_questions WHERE exam_id = ? ORDER BY sort_order ASC, id ASC",
                [$examId]
            );

            foreach ($questions as $question) {
                $stmt = $pdo->prepare("
                    INSERT INTO core_exam_questions (
                        exam_id,
                        bank_question_id,
                        section_name,
                        skill,
                        question_text,
                        question_type,
                        marks,
                        sort_order,
                        correct_answer,
                        explanation,
                        difficulty,
                        audio_file,
                        image_file,
                        allow_file_upload,
                        rubric_json,
                        is_required,
                        created_at,
                        updated_at
                    ) VALUES (
                        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW()
                    )
                ");

                $stmt->execute([
                    $newExamId,
                    !empty($question['bank_question_id']) ? (int)$question['bank_question_id'] : null,
                    $question['section_name'] ?? null,
                    $question['skill'] ?? null,
                    (string)$question['question_text'],
                    (string)$question['question_type'],
                    (float)$question['marks'],
                    (int)$question['sort_order'],
                    $question['correct_answer'] ?? null,
                    $question['explanation'] ?? null,
                    $question['difficulty'] ?? 'medium',
                    $question['audio_file'] ?? null,
                    $question['image_file'] ?? null,
                    (int)($question['allow_file_upload'] ?? 0),
                    $question['rubric_json'] ?? null,
                    (int)($question['is_required'] ?? 1),
                ]);

                $newQuestionId = (int)$pdo->lastInsertId();

                $options = safeAll(
                    $pdo,
                    "SELECT * FROM core_exam_options WHERE question_id = ? ORDER BY sort_order ASC, id ASC",
                    [(int)$question['id']]
                );

                foreach ($options as $option) {
                    $stmt = $pdo->prepare("
                        INSERT INTO core_exam_options (
                            question_id,
                            option_text,
                            is_correct,
                            sort_order,
                            created_at
                        ) VALUES (
                            ?, ?, ?, ?, NOW()
                        )
                    ");

                    $stmt->execute([
                        $newQuestionId,
                        (string)$option['option_text'],
                        (int)$option['is_correct'],
                        (int)$option['sort_order']
                    ]);
                }
            }

            $pdo->commit();

            setSuccess('Exam duplicated successfully.');

            header('Location: exams.php?tab=questions&exam_id=' . $newExamId);
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Delete Exam
        |--------------------------------------------------------------------------
        */

        if ($action === 'delete_exam') {
            $examId = (int)($_POST['exam_id'] ?? 0);

            if ($examId <= 0) {
                throw new Exception('Invalid exam.');
            }

            $exam = safeOne($pdo, "SELECT * FROM core_exams WHERE id = ? LIMIT 1", [$examId]);

            if (!$exam) {
                throw new Exception('Exam was not found.');
            }

            $attemptsCount = safeCount(
                $pdo,
                "SELECT COUNT(*) FROM core_exam_attempts WHERE exam_id = ?",
                [$examId]
            );

            if ($attemptsCount > 0) {
                throw new Exception('This exam has student attempts and cannot be deleted. Archive it instead.');
            }

            $pdo->beginTransaction();

            $questionIds = safeAll(
                $pdo,
                "SELECT id FROM core_exam_questions WHERE exam_id = ?",
                [$examId]
            );

            foreach ($questionIds as $q) {
                $pdo->prepare("DELETE FROM core_exam_options WHERE question_id = ?")
                    ->execute([(int)$q['id']]);
            }

            $pdo->prepare("DELETE FROM core_exam_questions WHERE exam_id = ?")
                ->execute([$examId]);

            $pdo->prepare("DELETE FROM core_exams WHERE id = ?")
                ->execute([$examId]);

            $pdo->commit();

            setSuccess('Exam deleted successfully.');

            header('Location: exams.php?tab=exams');
            exit;
        }

    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        setError($e->getMessage());

        $redirectTab = in_array($activeTab, $allowedTabs, true) ? $activeTab : 'exams';
        $redirectExam = $selectedExamId > 0 ? '&exam_id=' . $selectedExamId : '';

        header('Location: exams.php?tab=' . urlencode($redirectTab) . $redirectExam);
        exit;
    }
}

/*
|--------------------------------------------------------------------------
| POST Actions - Questions + Question Bank
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');

    try {
        verifyCsrf();

        /*
        |--------------------------------------------------------------------------
        | Add Question To Exam
        |--------------------------------------------------------------------------
        */

        if ($action === 'add_question') {
            $examId = (int)($_POST['exam_id'] ?? 0);

            if ($examId <= 0) {
                throw new Exception('Invalid exam.');
            }

            $exam = safeOne($pdo, "SELECT * FROM core_exams WHERE id = ? LIMIT 1", [$examId]);

            if (!$exam) {
                throw new Exception('Exam was not found.');
            }

            $questionText = trim((string)($_POST['question_text'] ?? ''));
            $questionType = trim((string)($_POST['question_type'] ?? 'multiple_choice'));
            $sectionName = trim((string)($_POST['section_name'] ?? ''));
            $skill = trim((string)($_POST['skill'] ?? 'general'));
            $marks = max(0.1, (float)($_POST['marks'] ?? 1));
            $correctAnswer = trim((string)($_POST['correct_answer'] ?? ''));
            $explanation = trim((string)($_POST['explanation'] ?? ''));
            $difficulty = trim((string)($_POST['difficulty'] ?? 'medium'));
            $sortOrder = (int)($_POST['sort_order'] ?? 0);
            $isRequired = !empty($_POST['is_required']) ? 1 : 0;
            $saveToBank = !empty($_POST['save_to_bank']) ? 1 : 0;
            $allowFileUpload = !empty($_POST['allow_file_upload']) ? 1 : 0;

            if ($questionText === '') {
                throw new Exception('Question text is required.');
            }

            if (!in_array($questionType, $questionTypes, true)) {
                $questionType = 'multiple_choice';
            }

            if (!in_array($skill, $skills, true)) {
                $skill = 'general';
            }

            if (!in_array($difficulty, ['easy', 'medium', 'hard', 'elite'], true)) {
                $difficulty = 'medium';
            }

            $rubricJson = null;

            if (in_array($questionType, ['essay', 'speaking'], true)) {
                $rubric = [
                    'grammar' => (int)($_POST['rubric_grammar'] ?? 0),
                    'vocabulary' => (int)($_POST['rubric_vocabulary'] ?? 0),
                    'coherence' => (int)($_POST['rubric_coherence'] ?? 0),
                    'pronunciation' => (int)($_POST['rubric_pronunciation'] ?? 0),
                    'task_response' => (int)($_POST['rubric_task_response'] ?? 0),
                ];

                $rubricJson = json_encode($rubric, JSON_UNESCAPED_UNICODE);
            }

            $audioFile = null;
            $imageFile = null;

            $stmt = $pdo->prepare("
                INSERT INTO core_exam_questions (
                    exam_id,
                    section_name,
                    skill,
                    question_text,
                    question_type,
                    marks,
                    sort_order,
                    correct_answer,
                    explanation,
                    difficulty,
                    audio_file,
                    image_file,
                    allow_file_upload,
                    rubric_json,
                    is_required,
                    created_at,
                    updated_at
                ) VALUES (
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW()
                )
            ");

            $stmt->execute([
                $examId,
                $sectionName !== '' ? $sectionName : null,
                $skill,
                $questionText,
                $questionType,
                $marks,
                $sortOrder,
                $correctAnswer !== '' ? $correctAnswer : null,
                $explanation !== '' ? $explanation : null,
                $difficulty,
                $audioFile,
                $imageFile,
                $allowFileUpload,
                $rubricJson,
                $isRequired
            ]);

            $questionId = (int)$pdo->lastInsertId();

            /*
            |--------------------------------------------------------------------------
            | Options For Multiple Choice / True False
            |--------------------------------------------------------------------------
            */

            if ($questionType === 'multiple_choice') {
                $options = $_POST['options'] ?? [];
                $correctIndex = (int)($_POST['correct_option'] ?? -1);

                if (!is_array($options)) {
                    $options = [];
                }

                $cleanOptions = [];

                foreach ($options as $index => $optionText) {
                    $optionText = trim((string)$optionText);

                    if ($optionText !== '') {
                        $cleanOptions[] = [
                            'text' => $optionText,
                            'is_correct' => ((int)$index === $correctIndex) ? 1 : 0,
                            'sort_order' => (int)$index
                        ];
                    }
                }

                if (count($cleanOptions) < 2) {
                    throw new Exception('Multiple choice questions require at least two options.');
                }

                $hasCorrect = false;

                foreach ($cleanOptions as $option) {
                    if ((int)$option['is_correct'] === 1) {
                        $hasCorrect = true;
                    }

                    $stmt = $pdo->prepare("
                        INSERT INTO core_exam_options (
                            question_id,
                            option_text,
                            is_correct,
                            sort_order,
                            created_at
                        ) VALUES (
                            ?, ?, ?, ?, NOW()
                        )
                    ");

                    $stmt->execute([
                        $questionId,
                        $option['text'],
                        $option['is_correct'],
                        $option['sort_order']
                    ]);
                }

                if (!$hasCorrect) {
                    throw new Exception('Please select the correct option.');
                }
            }

            if ($questionType === 'true_false') {
                $trueFalseAnswer = trim((string)($_POST['true_false_answer'] ?? 'true'));

                if (!in_array($trueFalseAnswer, ['true', 'false'], true)) {
                    $trueFalseAnswer = 'true';
                }

                $pdo->prepare("
                    UPDATE core_exam_questions
                    SET correct_answer = ?
                    WHERE id = ?
                ")->execute([$trueFalseAnswer, $questionId]);

                $options = [
                    ['True', $trueFalseAnswer === 'true' ? 1 : 0, 1],
                    ['False', $trueFalseAnswer === 'false' ? 1 : 0, 2],
                ];

                foreach ($options as $option) {
                    $stmt = $pdo->prepare("
                        INSERT INTO core_exam_options (
                            question_id,
                            option_text,
                            is_correct,
                            sort_order,
                            created_at
                        ) VALUES (
                            ?, ?, ?, ?, NOW()
                        )
                    ");

                    $stmt->execute([
                        $questionId,
                        $option[0],
                        $option[1],
                        $option[2]
                    ]);
                }
            }

            /*
            |--------------------------------------------------------------------------
            | Save To Question Bank
            |--------------------------------------------------------------------------
            */

            if ($saveToBank) {
                $stmt = $pdo->prepare("
                    INSERT INTO core_question_bank (
                        course_id,
                        teacher_id,
                        section_name,
                        skill,
                        question_text,
                        question_type,
                        correct_answer,
                        explanation,
                        marks,
                        difficulty,
                        tags,
                        audio_file,
                        image_file,
                        rubric_json,
                        created_by_admin_id,
                        created_at,
                        updated_at
                    ) VALUES (
                        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW()
                    )
                ");

                $stmt->execute([
                    (int)($exam['course_id'] ?? 0),
                    !empty($exam['teacher_id']) ? (int)$exam['teacher_id'] : null,
                    $sectionName !== '' ? $sectionName : null,
                    $skill,
                    $questionText,
                    $questionType,
                    $correctAnswer !== '' ? $correctAnswer : null,
                    $explanation !== '' ? $explanation : null,
                    $marks,
                    $difficulty,
                    trim((string)($_POST['tags'] ?? '')),
                    $audioFile,
                    $imageFile,
                    $rubricJson,
                    $adminId > 0 ? $adminId : null
                ]);
            }

            /*
            |--------------------------------------------------------------------------
            | Recalculate Total Marks
            |--------------------------------------------------------------------------
            */

            $total = safeOne(
                $pdo,
                "SELECT COALESCE(SUM(marks),0) AS total_marks FROM core_exam_questions WHERE exam_id = ?",
                [$examId]
            );

            $pdo->prepare("
                UPDATE core_exams
                SET total_marks = ?, updated_at = NOW()
                WHERE id = ?
            ")->execute([
                (float)($total['total_marks'] ?? 0),
                $examId
            ]);

            setSuccess('Question added successfully.');

            header('Location: exams.php?tab=questions&exam_id=' . $examId);
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Update Question
        |--------------------------------------------------------------------------
        */

        if ($action === 'update_question') {
            $questionId = (int)($_POST['question_id'] ?? 0);

            if ($questionId <= 0) {
                throw new Exception('Invalid question.');
            }

            $question = safeOne(
                $pdo,
                "SELECT * FROM core_exam_questions WHERE id = ? LIMIT 1",
                [$questionId]
            );

            if (!$question) {
                throw new Exception('Question was not found.');
            }

            $examId = (int)$question['exam_id'];

            $questionText = trim((string)($_POST['question_text'] ?? ''));
            $questionType = trim((string)($_POST['question_type'] ?? 'multiple_choice'));
            $sectionName = trim((string)($_POST['section_name'] ?? ''));
            $skill = trim((string)($_POST['skill'] ?? 'general'));
            $marks = max(0.1, (float)($_POST['marks'] ?? 1));
            $correctAnswer = trim((string)($_POST['correct_answer'] ?? ''));
            $explanation = trim((string)($_POST['explanation'] ?? ''));
            $difficulty = trim((string)($_POST['difficulty'] ?? 'medium'));
            $sortOrder = (int)($_POST['sort_order'] ?? 0);
            $isRequired = !empty($_POST['is_required']) ? 1 : 0;
            $allowFileUpload = !empty($_POST['allow_file_upload']) ? 1 : 0;

            if ($questionText === '') {
                throw new Exception('Question text is required.');
            }

            if (!in_array($questionType, $questionTypes, true)) {
                $questionType = 'multiple_choice';
            }

            if (!in_array($skill, $skills, true)) {
                $skill = 'general';
            }

            if (!in_array($difficulty, ['easy', 'medium', 'hard', 'elite'], true)) {
                $difficulty = 'medium';
            }

            $rubricJson = null;

            if (in_array($questionType, ['essay', 'speaking'], true)) {
                $rubric = [
                    'grammar' => (int)($_POST['rubric_grammar'] ?? 0),
                    'vocabulary' => (int)($_POST['rubric_vocabulary'] ?? 0),
                    'coherence' => (int)($_POST['rubric_coherence'] ?? 0),
                    'pronunciation' => (int)($_POST['rubric_pronunciation'] ?? 0),
                    'task_response' => (int)($_POST['rubric_task_response'] ?? 0),
                ];

                $rubricJson = json_encode($rubric, JSON_UNESCAPED_UNICODE);
            }

            $stmt = $pdo->prepare("
                UPDATE core_exam_questions
                SET
                    section_name = ?,
                    skill = ?,
                    question_text = ?,
                    question_type = ?,
                    marks = ?,
                    sort_order = ?,
                    correct_answer = ?,
                    explanation = ?,
                    difficulty = ?,
                    allow_file_upload = ?,
                    rubric_json = ?,
                    is_required = ?,
                    updated_at = NOW()
                WHERE id = ?
            ");

            $stmt->execute([
                $sectionName !== '' ? $sectionName : null,
                $skill,
                $questionText,
                $questionType,
                $marks,
                $sortOrder,
                $correctAnswer !== '' ? $correctAnswer : null,
                $explanation !== '' ? $explanation : null,
                $difficulty,
                $allowFileUpload,
                $rubricJson,
                $isRequired,
                $questionId
            ]);

            /*
            |--------------------------------------------------------------------------
            | Refresh Options
            |--------------------------------------------------------------------------
            */

            if (in_array($questionType, ['multiple_choice', 'true_false'], true)) {
                $pdo->prepare("DELETE FROM core_exam_options WHERE question_id = ?")
                    ->execute([$questionId]);
            }

            if ($questionType === 'multiple_choice') {
                $options = $_POST['options'] ?? [];
                $correctIndex = (int)($_POST['correct_option'] ?? -1);

                if (!is_array($options)) {
                    $options = [];
                }

                $cleanOptions = [];

                foreach ($options as $index => $optionText) {
                    $optionText = trim((string)$optionText);

                    if ($optionText !== '') {
                        $cleanOptions[] = [
                            'text' => $optionText,
                            'is_correct' => ((int)$index === $correctIndex) ? 1 : 0,
                            'sort_order' => (int)$index
                        ];
                    }
                }

                if (count($cleanOptions) < 2) {
                    throw new Exception('Multiple choice questions require at least two options.');
                }

                foreach ($cleanOptions as $option) {
                    $stmt = $pdo->prepare("
                        INSERT INTO core_exam_options (
                            question_id,
                            option_text,
                            is_correct,
                            sort_order,
                            created_at
                        ) VALUES (
                            ?, ?, ?, ?, NOW()
                        )
                    ");

                    $stmt->execute([
                        $questionId,
                        $option['text'],
                        $option['is_correct'],
                        $option['sort_order']
                    ]);
                }
            }

            if ($questionType === 'true_false') {
                $trueFalseAnswer = trim((string)($_POST['true_false_answer'] ?? 'true'));

                if (!in_array($trueFalseAnswer, ['true', 'false'], true)) {
                    $trueFalseAnswer = 'true';
                }

                $pdo->prepare("
                    UPDATE core_exam_questions
                    SET correct_answer = ?
                    WHERE id = ?
                ")->execute([$trueFalseAnswer, $questionId]);

                $options = [
                    ['True', $trueFalseAnswer === 'true' ? 1 : 0, 1],
                    ['False', $trueFalseAnswer === 'false' ? 1 : 0, 2],
                ];

                foreach ($options as $option) {
                    $stmt = $pdo->prepare("
                        INSERT INTO core_exam_options (
                            question_id,
                            option_text,
                            is_correct,
                            sort_order,
                            created_at
                        ) VALUES (
                            ?, ?, ?, ?, NOW()
                        )
                    ");

                    $stmt->execute([
                        $questionId,
                        $option[0],
                        $option[1],
                        $option[2]
                    ]);
                }
            }

            $total = safeOne(
                $pdo,
                "SELECT COALESCE(SUM(marks),0) AS total_marks FROM core_exam_questions WHERE exam_id = ?",
                [$examId]
            );

            $pdo->prepare("
                UPDATE core_exams
                SET total_marks = ?, updated_at = NOW()
                WHERE id = ?
            ")->execute([
                (float)($total['total_marks'] ?? 0),
                $examId
            ]);

            setSuccess('Question updated successfully.');

            header('Location: exams.php?tab=questions&exam_id=' . $examId);
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Delete Question
        |--------------------------------------------------------------------------
        */

        if ($action === 'delete_question') {
            $questionId = (int)($_POST['question_id'] ?? 0);

            if ($questionId <= 0) {
                throw new Exception('Invalid question.');
            }

            $question = safeOne(
                $pdo,
                "SELECT * FROM core_exam_questions WHERE id = ? LIMIT 1",
                [$questionId]
            );

            if (!$question) {
                throw new Exception('Question was not found.');
            }

            $examId = (int)$question['exam_id'];

            $answersCount = safeCount(
                $pdo,
                "SELECT COUNT(*) FROM core_exam_answers WHERE question_id = ?",
                [$questionId]
            );

            if ($answersCount > 0) {
                throw new Exception('This question already has student answers and cannot be deleted.');
            }

            $pdo->prepare("DELETE FROM core_exam_options WHERE question_id = ?")
                ->execute([$questionId]);

            $pdo->prepare("DELETE FROM core_exam_questions WHERE id = ?")
                ->execute([$questionId]);

            $total = safeOne(
                $pdo,
                "SELECT COALESCE(SUM(marks),0) AS total_marks FROM core_exam_questions WHERE exam_id = ?",
                [$examId]
            );

            $pdo->prepare("
                UPDATE core_exams
                SET total_marks = ?, updated_at = NOW()
                WHERE id = ?
            ")->execute([
                (float)($total['total_marks'] ?? 0),
                $examId
            ]);

            setSuccess('Question deleted successfully.');

            header('Location: exams.php?tab=questions&exam_id=' . $examId);
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Move Question
        |--------------------------------------------------------------------------
        */

        if ($action === 'move_question') {
            $questionId = (int)($_POST['question_id'] ?? 0);
            $direction = (string)($_POST['direction'] ?? 'up');

            $question = safeOne(
                $pdo,
                "SELECT * FROM core_exam_questions WHERE id = ? LIMIT 1",
                [$questionId]
            );

            if (!$question) {
                throw new Exception('Question was not found.');
            }

            $examId = (int)$question['exam_id'];
            $currentOrder = (int)($question['sort_order'] ?? 0);
            $newOrder = $direction === 'down' ? $currentOrder + 1 : max(0, $currentOrder - 1);

            $pdo->prepare("
                UPDATE core_exam_questions
                SET sort_order = ?, updated_at = NOW()
                WHERE id = ?
            ")->execute([$newOrder, $questionId]);

            setSuccess('Question order updated.');

            header('Location: exams.php?tab=questions&exam_id=' . $examId);
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Add Bank Question
        |--------------------------------------------------------------------------
        */

        if ($action === 'add_bank_question') {
            $courseId = (int)($_POST['course_id'] ?? 0);
            $teacherId = (int)($_POST['teacher_id'] ?? 0);
            $sectionName = trim((string)($_POST['section_name'] ?? ''));
            $skill = trim((string)($_POST['skill'] ?? 'general'));
            $questionText = trim((string)($_POST['question_text'] ?? ''));
            $questionType = trim((string)($_POST['question_type'] ?? 'multiple_choice'));
            $correctAnswer = trim((string)($_POST['correct_answer'] ?? ''));
            $explanation = trim((string)($_POST['explanation'] ?? ''));
            $marks = max(0.1, (float)($_POST['marks'] ?? 1));
            $difficulty = trim((string)($_POST['difficulty'] ?? 'medium'));
            $tags = trim((string)($_POST['tags'] ?? ''));

            if ($questionText === '') {
                throw new Exception('Question text is required.');
            }

            if (!in_array($questionType, $questionTypes, true)) {
                $questionType = 'multiple_choice';
            }

            if (!in_array($skill, $skills, true)) {
                $skill = 'general';
            }

            $stmt = $pdo->prepare("
                INSERT INTO core_question_bank (
                    course_id,
                    teacher_id,
                    section_name,
                    skill,
                    question_text,
                    question_type,
                    correct_answer,
                    explanation,
                    marks,
                    difficulty,
                    tags,
                    created_by_admin_id,
                    created_at,
                    updated_at
                ) VALUES (
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW()
                )
            ");

            $stmt->execute([
                $courseId > 0 ? $courseId : null,
                $teacherId > 0 ? $teacherId : null,
                $sectionName !== '' ? $sectionName : null,
                $skill,
                $questionText,
                $questionType,
                $correctAnswer !== '' ? $correctAnswer : null,
                $explanation !== '' ? $explanation : null,
                $marks,
                $difficulty,
                $tags,
                $adminId > 0 ? $adminId : null
            ]);

            setSuccess('Question added to bank successfully.');

            header('Location: exams.php?tab=bank');
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Add Question From Bank To Exam
        |--------------------------------------------------------------------------
        */

        if ($action === 'add_bank_to_exam') {
            $examId = (int)($_POST['exam_id'] ?? 0);
            $bankQuestionId = (int)($_POST['bank_question_id'] ?? 0);

            if ($examId <= 0 || $bankQuestionId <= 0) {
                throw new Exception('Invalid exam or bank question.');
            }

            $exam = safeOne($pdo, "SELECT * FROM core_exams WHERE id = ? LIMIT 1", [$examId]);
            $bankQuestion = safeOne($pdo, "SELECT * FROM core_question_bank WHERE id = ? LIMIT 1", [$bankQuestionId]);

            if (!$exam || !$bankQuestion) {
                throw new Exception('Exam or question bank item was not found.');
            }

            $nextOrder = safeOne(
                $pdo,
                "SELECT COALESCE(MAX(sort_order),0) + 1 AS next_order FROM core_exam_questions WHERE exam_id = ?",
                [$examId]
            );

            $stmt = $pdo->prepare("
                INSERT INTO core_exam_questions (
                    exam_id,
                    bank_question_id,
                    section_name,
                    skill,
                    question_text,
                    question_type,
                    marks,
                    sort_order,
                    correct_answer,
                    explanation,
                    difficulty,
                    audio_file,
                    image_file,
                    rubric_json,
                    is_required,
                    created_at,
                    updated_at
                ) VALUES (
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NOW(), NOW()
                )
            ");

            $stmt->execute([
                $examId,
                $bankQuestionId,
                $bankQuestion['section_name'] ?? null,
                $bankQuestion['skill'] ?? 'general',
                (string)$bankQuestion['question_text'],
                (string)$bankQuestion['question_type'],
                (float)$bankQuestion['marks'],
                (int)($nextOrder['next_order'] ?? 1),
                $bankQuestion['correct_answer'] ?? null,
                $bankQuestion['explanation'] ?? null,
                $bankQuestion['difficulty'] ?? 'medium',
                $bankQuestion['audio_file'] ?? null,
                $bankQuestion['image_file'] ?? null,
                $bankQuestion['rubric_json'] ?? null
            ]);

            $newQuestionId = (int)$pdo->lastInsertId();

            /*
            |--------------------------------------------------------------------------
            | If Bank Question Has Simple Correct Answer, Create Options For True/False
            |--------------------------------------------------------------------------
            */

            if ((string)$bankQuestion['question_type'] === 'true_false') {
                $answer = strtolower((string)($bankQuestion['correct_answer'] ?? 'true'));

                if (!in_array($answer, ['true', 'false'], true)) {
                    $answer = 'true';
                }

                $options = [
                    ['True', $answer === 'true' ? 1 : 0, 1],
                    ['False', $answer === 'false' ? 1 : 0, 2],
                ];

                foreach ($options as $option) {
                    $pdo->prepare("
                        INSERT INTO core_exam_options (
                            question_id,
                            option_text,
                            is_correct,
                            sort_order,
                            created_at
                        ) VALUES (?, ?, ?, ?, NOW())
                    ")->execute([
                        $newQuestionId,
                        $option[0],
                        $option[1],
                        $option[2]
                    ]);
                }
            }

            $total = safeOne(
                $pdo,
                "SELECT COALESCE(SUM(marks),0) AS total_marks FROM core_exam_questions WHERE exam_id = ?",
                [$examId]
            );

            $pdo->prepare("
                UPDATE core_exams
                SET total_marks = ?, updated_at = NOW()
                WHERE id = ?
            ")->execute([
                (float)($total['total_marks'] ?? 0),
                $examId
            ]);

            setSuccess('Question added from bank to exam.');

            header('Location: exams.php?tab=questions&exam_id=' . $examId);
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Delete Bank Question
        |--------------------------------------------------------------------------
        */

        if ($action === 'delete_bank_question') {
            $bankQuestionId = (int)($_POST['bank_question_id'] ?? 0);

            if ($bankQuestionId <= 0) {
                throw new Exception('Invalid bank question.');
            }

            $usedCount = safeCount(
                $pdo,
                "SELECT COUNT(*) FROM core_exam_questions WHERE bank_question_id = ?",
                [$bankQuestionId]
            );

            if ($usedCount > 0) {
                throw new Exception('This bank question is already used in exams and cannot be deleted.');
            }

            $pdo->prepare("DELETE FROM core_question_bank WHERE id = ?")
                ->execute([$bankQuestionId]);

            setSuccess('Bank question deleted successfully.');

            header('Location: exams.php?tab=bank');
            exit;
        }

    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        setError($e->getMessage());

        $redirectExam = $selectedExamId > 0 ? '&exam_id=' . $selectedExamId : '';
        header('Location: exams.php?tab=' . urlencode($activeTab) . $redirectExam);
        exit;
    }
}

/*
|--------------------------------------------------------------------------
| Grading + Attempts Helper Functions
|--------------------------------------------------------------------------
*/

if (!function_exists('normalizeAnswer')) {
    function normalizeAnswer(string $value): string
    {
        $value = trim(mb_strtolower($value, 'UTF-8'));
        $value = preg_replace('/\s+/u', ' ', $value) ?? $value;
        return $value;
    }
}

if (!function_exists('autoGradeAnswer')) {
    function autoGradeAnswer(PDO $pdo, array $question, ?int $selectedOptionId, string $answerText): array
    {
        $questionType = (string)($question['question_type'] ?? '');
        $marks = (float)($question['marks'] ?? 0);
        $correctAnswer = (string)($question['correct_answer'] ?? '');

        $score = 0.00;
        $isCorrect = null;
        $needsManual = false;

        if ($questionType === 'multiple_choice' || $questionType === 'true_false') {
            if ($selectedOptionId && $selectedOptionId > 0) {
                $option = safeOne(
                    $pdo,
                    "
                    SELECT *
                    FROM core_exam_options
                    WHERE id = ?
                      AND question_id = ?
                    LIMIT 1
                    ",
                    [
                        $selectedOptionId,
                        (int)$question['id']
                    ]
                );

                if ($option && (int)($option['is_correct'] ?? 0) === 1) {
                    $score = $marks;
                    $isCorrect = 1;
                } else {
                    $score = 0.00;
                    $isCorrect = 0;
                }
            } else {
                $score = 0.00;
                $isCorrect = 0;
            }
        } elseif ($questionType === 'fill_blank') {
            $studentAnswer = normalizeAnswer($answerText);
            $rightAnswer = normalizeAnswer($correctAnswer);

            $acceptedAnswers = array_map(
                'trim',
                explode('|', $rightAnswer)
            );

            $acceptedAnswers = array_filter($acceptedAnswers);

            if ($rightAnswer !== '' && in_array($studentAnswer, $acceptedAnswers, true)) {
                $score = $marks;
                $isCorrect = 1;
            } elseif ($rightAnswer !== '' && $studentAnswer === $rightAnswer) {
                $score = $marks;
                $isCorrect = 1;
            } else {
                $score = 0.00;
                $isCorrect = 0;
            }
        } elseif (in_array($questionType, ['short_answer', 'essay', 'speaking', 'file_upload', 'listening'], true)) {
            $needsManual = true;
            $score = 0.00;
            $isCorrect = null;
        } else {
            $needsManual = true;
            $score = 0.00;
            $isCorrect = null;
        }

        return [
            'score' => $score,
            'is_correct' => $isCorrect,
            'needs_manual' => $needsManual
        ];
    }
}

if (!function_exists('recalculateAttemptScore')) {
    function recalculateAttemptScore(PDO $pdo, int $attemptId): void
    {
        $attempt = safeOne(
            $pdo,
            "SELECT * FROM core_exam_attempts WHERE id = ? LIMIT 1",
            [$attemptId]
        );

        if (!$attempt) {
            return;
        }

        $exam = safeOne(
            $pdo,
            "SELECT * FROM core_exams WHERE id = ? LIMIT 1",
            [(int)$attempt['exam_id']]
        );

        if (!$exam) {
            return;
        }

        $questionsTotal = safeOne(
            $pdo,
            "
            SELECT COALESCE(SUM(marks), 0) AS total_marks
            FROM core_exam_questions
            WHERE exam_id = ?
            ",
            [(int)$exam['id']]
        );

        $totalMarks = (float)($questionsTotal['total_marks'] ?? 0);

        if ($totalMarks <= 0) {
            $totalMarks = (float)($exam['total_marks'] ?? 0);
        }

        $scoreRow = safeOne(
            $pdo,
            "
            SELECT
                COALESCE(SUM(score_awarded), 0) AS score,
                SUM(CASE WHEN is_correct IS NULL THEN 1 ELSE 0 END) AS pending_manual
            FROM core_exam_answers
            WHERE attempt_id = ?
            ",
            [$attemptId]
        );

        $score = (float)($scoreRow['score'] ?? 0);
        $pendingManual = (int)($scoreRow['pending_manual'] ?? 0);

        $percentage = $totalMarks > 0
            ? round(($score / $totalMarks) * 100, 2)
            : 0.00;

        $passingMarks = (float)($exam['passing_marks'] ?? 0);

        if ($pendingManual > 0) {
            $resultStatus = 'pending';
            $attemptStatus = 'submitted';
        } else {
            $resultStatus = $score >= $passingMarks ? 'pass' : 'fail';
            $attemptStatus = 'graded';
        }

        $autoScoreRow = safeOne(
            $pdo,
            "
            SELECT COALESCE(SUM(score_awarded),0) AS auto_score
            FROM core_exam_answers a
            INNER JOIN core_exam_questions q ON q.id = a.question_id
            WHERE a.attempt_id = ?
              AND q.question_type IN ('multiple_choice','true_false','fill_blank')
            ",
            [$attemptId]
        );

        $manualScoreRow = safeOne(
            $pdo,
            "
            SELECT COALESCE(SUM(score_awarded),0) AS manual_score
            FROM core_exam_answers a
            INNER JOIN core_exam_questions q ON q.id = a.question_id
            WHERE a.attempt_id = ?
              AND q.question_type NOT IN ('multiple_choice','true_false','fill_blank')
            ",
            [$attemptId]
        );

        $stmt = $pdo->prepare("
            UPDATE core_exam_attempts
            SET
                total_score = ?,
                percentage = ?,
                result_status = ?,
                status = ?,
                auto_graded_score = ?,
                manual_graded_score = ?,
                updated_at = NOW()
            WHERE id = ?
        ");

        $stmt->execute([
            $score,
            $percentage,
            $resultStatus,
            $attemptStatus,
            (float)($autoScoreRow['auto_score'] ?? 0),
            (float)($manualScoreRow['manual_score'] ?? 0),
            $attemptId
        ]);

        if ((int)($exam['gradebook_enabled'] ?? 0) === 1) {
            syncAttemptToGradebook($pdo, $attemptId);
        }
    }
}

if (!function_exists('syncAttemptToGradebook')) {
    function syncAttemptToGradebook(PDO $pdo, int $attemptId): void
    {
        if (!tableExists($pdo, 'core_grade_items')) {
            return;
        }

        $attempt = safeOne(
            $pdo,
            "
            SELECT a.*, e.title AS exam_title
            FROM core_exam_attempts a
            INNER JOIN core_exams e ON e.id = a.exam_id
            WHERE a.id = ?
            LIMIT 1
            ",
            [$attemptId]
        );

        if (!$attempt) {
            return;
        }

        $courseId = (int)$attempt['course_id'];
        $studentId = (int)$attempt['student_id'];
        $examId = (int)$attempt['exam_id'];

        $gradeItem = safeOne(
            $pdo,
            "
            SELECT *
            FROM core_grade_items
            WHERE exam_id = ?
              AND course_id = ?
            LIMIT 1
            ",
            [$examId, $courseId]
        );

        if (!$gradeItem) {
            $columns = ['course_id', 'title', 'type', 'max_score', 'exam_id', 'created_at'];
            $values = [
                $courseId,
                (string)$attempt['exam_title'],
                'exam',
                100,
                $examId,
                date('Y-m-d H:i:s')
            ];

            if (columnExists($pdo, 'core_grade_items', 'created_by_admin_id')) {
                $columns[] = 'created_by_admin_id';
                $values[] = null;
            }

            $placeholders = implode(',', array_fill(0, count($columns), '?'));

            $stmt = $pdo->prepare("
                INSERT INTO core_grade_items (
                    " . implode(',', $columns) . "
                ) VALUES (
                    $placeholders
                )
            ");

            try {
                $stmt->execute($values);
                $gradeItemId = (int)$pdo->lastInsertId();
            } catch (Throwable $e) {
                return;
            }
        } else {
            $gradeItemId = (int)$gradeItem['id'];
        }

        if (tableExists($pdo, 'core_grades')) {
            $existing = safeOne(
                $pdo,
                "
                SELECT *
                FROM core_grades
                WHERE grade_item_id = ?
                  AND student_id = ?
                LIMIT 1
                ",
                [$gradeItemId, $studentId]
            );

            if ($existing) {
                $pdo->prepare("
                    UPDATE core_grades
                    SET score = ?, updated_at = NOW()
                    WHERE id = ?
                ")->execute([
                    (float)$attempt['percentage'],
                    (int)$existing['id']
                ]);
            } else {
                $columns = ['grade_item_id', 'student_id', 'score', 'created_at'];
                $values = [$gradeItemId, $studentId, (float)$attempt['percentage'], date('Y-m-d H:i:s')];

                if (columnExists($pdo, 'core_grades', 'course_id')) {
                    $columns[] = 'course_id';
                    $values[] = $courseId;
                }

                $placeholders = implode(',', array_fill(0, count($columns), '?'));

                try {
                    $stmt = $pdo->prepare("
                        INSERT INTO core_grades (
                            " . implode(',', $columns) . "
                        ) VALUES (
                            $placeholders
                        )
                    ");

                    $stmt->execute($values);
                } catch (Throwable $e) {
                    return;
                }
            }
        }
    }
}

/*
|--------------------------------------------------------------------------
| POST Actions - Submissions + Manual Grading
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');

    try {
        verifyCsrf();

        /*
        |--------------------------------------------------------------------------
        | Manual Grade Answer
        |--------------------------------------------------------------------------
        */

        if ($action === 'manual_grade_answer') {
            $answerId = (int)($_POST['answer_id'] ?? 0);
            $scoreAwarded = max(0, (float)($_POST['score_awarded'] ?? 0));
            $teacherFeedback = trim((string)($_POST['teacher_feedback'] ?? ''));

            if ($answerId <= 0) {
                throw new Exception('Invalid answer.');
            }

            $answer = safeOne(
                $pdo,
                "
                SELECT 
                    a.*,
                    q.marks,
                    q.exam_id
                FROM core_exam_answers a
                INNER JOIN core_exam_questions q ON q.id = a.question_id
                WHERE a.id = ?
                LIMIT 1
                ",
                [$answerId]
            );

            if (!$answer) {
                throw new Exception('Answer was not found.');
            }

            $maxMarks = (float)($answer['marks'] ?? 0);

            if ($scoreAwarded > $maxMarks) {
                throw new Exception('Score cannot exceed question marks.');
            }

            $isCorrect = $scoreAwarded > 0 ? 1 : 0;

            $stmt = $pdo->prepare("
                UPDATE core_exam_answers
                SET
                    score_awarded = ?,
                    is_correct = ?,
                    teacher_feedback = ?,
                    graded_by_admin_id = ?,
                    graded_at = NOW(),
                    updated_at = NOW()
                WHERE id = ?
            ");

            $stmt->execute([
                $scoreAwarded,
                $isCorrect,
                $teacherFeedback !== '' ? $teacherFeedback : null,
                $adminId > 0 ? $adminId : null,
                $answerId
            ]);

            recalculateAttemptScore($pdo, (int)$answer['attempt_id']);

            setSuccess('Answer graded successfully.');

            header('Location: exams.php?tab=submissions&attempt_id=' . (int)$answer['attempt_id']);
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Bulk Grade Attempt
        |--------------------------------------------------------------------------
        */

        if ($action === 'bulk_grade_attempt') {
            $attemptId = (int)($_POST['attempt_id'] ?? 0);

            if ($attemptId <= 0) {
                throw new Exception('Invalid attempt.');
            }

            $attempt = safeOne(
                $pdo,
                "SELECT * FROM core_exam_attempts WHERE id = ? LIMIT 1",
                [$attemptId]
            );

            if (!$attempt) {
                throw new Exception('Attempt was not found.');
            }

            $scores = $_POST['scores'] ?? [];
            $feedbacks = $_POST['feedbacks'] ?? [];

            if (!is_array($scores)) {
                $scores = [];
            }

            if (!is_array($feedbacks)) {
                $feedbacks = [];
            }

            foreach ($scores as $answerId => $scoreValue) {
                $answerId = (int)$answerId;
                $scoreAwarded = max(0, (float)$scoreValue);
                $feedback = trim((string)($feedbacks[$answerId] ?? ''));

                $answer = safeOne(
                    $pdo,
                    "
                    SELECT 
                        a.*,
                        q.marks
                    FROM core_exam_answers a
                    INNER JOIN core_exam_questions q ON q.id = a.question_id
                    WHERE a.id = ?
                      AND a.attempt_id = ?
                    LIMIT 1
                    ",
                    [$answerId, $attemptId]
                );

                if (!$answer) {
                    continue;
                }

                $maxMarks = (float)($answer['marks'] ?? 0);

                if ($scoreAwarded > $maxMarks) {
                    $scoreAwarded = $maxMarks;
                }

                $isCorrect = $scoreAwarded > 0 ? 1 : 0;

                $stmt = $pdo->prepare("
                    UPDATE core_exam_answers
                    SET
                        score_awarded = ?,
                        is_correct = ?,
                        teacher_feedback = ?,
                        graded_by_admin_id = ?,
                        graded_at = NOW(),
                        updated_at = NOW()
                    WHERE id = ?
                ");

                $stmt->execute([
                    $scoreAwarded,
                    $isCorrect,
                    $feedback !== '' ? $feedback : null,
                    $adminId > 0 ? $adminId : null,
                    $answerId
                ]);
            }

            $generalFeedback = trim((string)($_POST['attempt_feedback'] ?? ''));

            if ($generalFeedback !== '') {
                $pdo->prepare("
                    UPDATE core_exam_attempts
                    SET feedback = ?, updated_at = NOW()
                    WHERE id = ?
                ")->execute([$generalFeedback, $attemptId]);
            }

            recalculateAttemptScore($pdo, $attemptId);

            setSuccess('Attempt graded successfully.');

            header('Location: exams.php?tab=submissions&attempt_id=' . $attemptId);
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Recalculate Attempt
        |--------------------------------------------------------------------------
        */

        if ($action === 'recalculate_attempt') {
            $attemptId = (int)($_POST['attempt_id'] ?? 0);

            if ($attemptId <= 0) {
                throw new Exception('Invalid attempt.');
            }

            recalculateAttemptScore($pdo, $attemptId);

            setSuccess('Attempt score recalculated successfully.');

            header('Location: exams.php?tab=submissions&attempt_id=' . $attemptId);
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Cancel Attempt
        |--------------------------------------------------------------------------
        */

        if ($action === 'cancel_attempt') {
            $attemptId = (int)($_POST['attempt_id'] ?? 0);

            if ($attemptId <= 0) {
                throw new Exception('Invalid attempt.');
            }

            $pdo->prepare("
                UPDATE core_exam_attempts
                SET status = 'cancelled', updated_at = NOW()
                WHERE id = ?
            ")->execute([$attemptId]);

            setSuccess('Attempt cancelled successfully.');

            header('Location: exams.php?tab=submissions');
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Reopen Attempt
        |--------------------------------------------------------------------------
        */

        if ($action === 'reopen_attempt') {
            $attemptId = (int)($_POST['attempt_id'] ?? 0);

            if ($attemptId <= 0) {
                throw new Exception('Invalid attempt.');
            }

            $minutes = max(5, (int)($_POST['extra_minutes'] ?? 30));
            $expiresAt = date('Y-m-d H:i:s', strtotime('+' . $minutes . ' minutes'));

            $pdo->prepare("
                UPDATE core_exam_attempts
                SET
                    status = 'in_progress',
                    expires_at = ?,
                    updated_at = NOW()
                WHERE id = ?
            ")->execute([$expiresAt, $attemptId]);

            setSuccess('Attempt reopened successfully.');

            header('Location: exams.php?tab=submissions&attempt_id=' . $attemptId);
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Release Attempt Result
        |--------------------------------------------------------------------------
        */

        if ($action === 'release_attempt_result') {
            $attemptId = (int)($_POST['attempt_id'] ?? 0);

            if ($attemptId <= 0) {
                throw new Exception('Invalid attempt.');
            }

            if (columnExists($pdo, 'core_exam_attempts', 'result_released')) {
                $pdo->prepare("
                    UPDATE core_exam_attempts
                    SET result_released = 1, updated_at = NOW()
                    WHERE id = ?
                ")->execute([$attemptId]);
            }

            setSuccess('Result released successfully.');

            header('Location: exams.php?tab=submissions&attempt_id=' . $attemptId);
            exit;
        }

    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        setError($e->getMessage());

        $redirectAttempt = $selectedAttemptId > 0 ? '&attempt_id=' . $selectedAttemptId : '';
        $redirectExam = $selectedExamId > 0 ? '&exam_id=' . $selectedExamId : '';

        header('Location: exams.php?tab=submissions' . $redirectAttempt . $redirectExam);
        exit;
    }
}

/*
|--------------------------------------------------------------------------
| Data Loading - Filters
|--------------------------------------------------------------------------
*/

$search = trim((string)($_GET['search'] ?? ''));
$filterCourseId = (int)($_GET['filter_course_id'] ?? 0);
$filterTeacherId = (int)($_GET['filter_teacher_id'] ?? 0);
$filterStatus = trim((string)($_GET['filter_status'] ?? ''));
$filterType = trim((string)($_GET['filter_type'] ?? ''));
$dateFrom = trim((string)($_GET['date_from'] ?? ''));
$dateTo = trim((string)($_GET['date_to'] ?? ''));

$where = "1=1";
$params = [];

if ($search !== '') {
    $where .= " AND (e.title LIKE ? OR e.exam_code LIKE ? OR c.title LIKE ?)";
    $like = '%' . $search . '%';
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}

if ($filterCourseId > 0) {
    $where .= " AND e.course_id = ?";
    $params[] = $filterCourseId;
}

if ($filterTeacherId > 0) {
    $where .= " AND e.teacher_id = ?";
    $params[] = $filterTeacherId;
}

if ($filterStatus !== '' && in_array($filterStatus, $examStatuses, true)) {
    $where .= " AND e.status = ?";
    $params[] = $filterStatus;
}

if ($filterType !== '' && in_array($filterType, $examTypes, true)) {
    $where .= " AND e.exam_type = ?";
    $params[] = $filterType;
}

if ($dateFrom !== '') {
    $where .= " AND DATE(e.start_at) >= ?";
    $params[] = $dateFrom;
}

if ($dateTo !== '') {
    $where .= " AND DATE(e.end_at) <= ?";
    $params[] = $dateTo;
}

/*
|--------------------------------------------------------------------------
| Dashboard Stats
|--------------------------------------------------------------------------
*/

$totalExams = safeCount($pdo, "SELECT COUNT(*) FROM core_exams");
$publishedExams = safeCount($pdo, "SELECT COUNT(*) FROM core_exams WHERE status = 'published'");
$draftExams = safeCount($pdo, "SELECT COUNT(*) FROM core_exams WHERE status = 'draft'");
$closedExams = safeCount($pdo, "SELECT COUNT(*) FROM core_exams WHERE status = 'closed'");
$archivedExams = safeCount($pdo, "SELECT COUNT(*) FROM core_exams WHERE status = 'archived'");
$totalAttempts = safeCount($pdo, "SELECT COUNT(*) FROM core_exam_attempts");

$averageScoreRow = safeOne(
    $pdo,
    "
    SELECT AVG(percentage) AS avg_score
    FROM core_exam_attempts
    WHERE status IN ('submitted','graded')
    "
);

$averageScore = round((float)($averageScoreRow['avg_score'] ?? 0), 2);

$passCount = safeCount(
    $pdo,
    "
    SELECT COUNT(*)
    FROM core_exam_attempts
    WHERE result_status = 'pass'
    "
);

$gradedCount = safeCount(
    $pdo,
    "
    SELECT COUNT(*)
    FROM core_exam_attempts
    WHERE result_status IN ('pass','fail')
    "
);

$passRate = $gradedCount > 0
    ? round(($passCount / $gradedCount) * 100, 1)
    : 0;

/*
|--------------------------------------------------------------------------
| Exams List
|--------------------------------------------------------------------------
*/

$exams = safeAll(
    $pdo,
    "
    SELECT
        e.*,
        c.title AS course_title,
        c.level AS course_level,
        c.course_code,
        t.full_name AS teacher_full_name,
        t.name AS teacher_name,
        COUNT(DISTINCT a.id) AS attempts_count,
        AVG(a.percentage) AS avg_percentage,
        SUM(CASE WHEN a.result_status = 'pass' THEN 1 ELSE 0 END) AS pass_count,
        SUM(CASE WHEN a.result_status IN ('pass','fail') THEN 1 ELSE 0 END) AS graded_count
    FROM core_exams e
    LEFT JOIN core_courses c ON c.id = e.course_id
    LEFT JOIN core_teachers t ON t.id = e.teacher_id
    LEFT JOIN core_exam_attempts a ON a.exam_id = e.id
    WHERE $where
    GROUP BY e.id
    ORDER BY e.id DESC
    ",
    $params
);

/*
|--------------------------------------------------------------------------
| Selected Exam
|--------------------------------------------------------------------------
*/

$selectedExam = null;

if ($selectedExamId > 0) {
    $selectedExam = safeOne(
        $pdo,
        "
        SELECT
            e.*,
            c.title AS course_title,
            c.level AS course_level,
            c.course_code,
            t.full_name AS teacher_full_name,
            t.name AS teacher_name
        FROM core_exams e
        LEFT JOIN core_courses c ON c.id = e.course_id
        LEFT JOIN core_teachers t ON t.id = e.teacher_id
        WHERE e.id = ?
        LIMIT 1
        ",
        [$selectedExamId]
    );
}

/*
|--------------------------------------------------------------------------
| Exam Questions
|--------------------------------------------------------------------------
*/

$examQuestions = [];
$questionOptionsMap = [];

if ($selectedExam) {
    $examQuestions = safeAll(
        $pdo,
        "
        SELECT *
        FROM core_exam_questions
        WHERE exam_id = ?
        ORDER BY sort_order ASC, id ASC
        ",
        [$selectedExamId]
    );

    foreach ($examQuestions as $q) {
        $questionOptionsMap[(int)$q['id']] = safeAll(
            $pdo,
            "
            SELECT *
            FROM core_exam_options
            WHERE question_id = ?
            ORDER BY sort_order ASC, id ASC
            ",
            [(int)$q['id']]
        );
    }
}

/*
|--------------------------------------------------------------------------
| Question Bank
|--------------------------------------------------------------------------
*/

$bankSearch = trim((string)($_GET['bank_search'] ?? ''));
$bankCourseId = (int)($_GET['bank_course_id'] ?? 0);
$bankSkill = trim((string)($_GET['bank_skill'] ?? ''));
$bankType = trim((string)($_GET['bank_type'] ?? ''));
$bankDifficulty = trim((string)($_GET['bank_difficulty'] ?? ''));

$bankWhere = "1=1";
$bankParams = [];

if ($bankSearch !== '') {
    $bankWhere .= " AND (qb.question_text LIKE ? OR qb.tags LIKE ? OR qb.correct_answer LIKE ?)";
    $bankLike = '%' . $bankSearch . '%';
    $bankParams[] = $bankLike;
    $bankParams[] = $bankLike;
    $bankParams[] = $bankLike;
}

if ($bankCourseId > 0) {
    $bankWhere .= " AND qb.course_id = ?";
    $bankParams[] = $bankCourseId;
}

if ($bankSkill !== '' && in_array($bankSkill, $skills, true)) {
    $bankWhere .= " AND qb.skill = ?";
    $bankParams[] = $bankSkill;
}

if ($bankType !== '' && in_array($bankType, $questionTypes, true)) {
    $bankWhere .= " AND qb.question_type = ?";
    $bankParams[] = $bankType;
}

if ($bankDifficulty !== '' && in_array($bankDifficulty, ['easy','medium','hard','elite'], true)) {
    $bankWhere .= " AND qb.difficulty = ?";
    $bankParams[] = $bankDifficulty;
}

$questionBank = safeAll(
    $pdo,
    "
    SELECT
        qb.*,
        c.title AS course_title,
        t.full_name AS teacher_full_name,
        t.name AS teacher_name
    FROM core_question_bank qb
    LEFT JOIN core_courses c ON c.id = qb.course_id
    LEFT JOIN core_teachers t ON t.id = qb.teacher_id
    WHERE $bankWhere
    ORDER BY qb.id DESC
    LIMIT 300
    ",
    $bankParams
);

/*
|--------------------------------------------------------------------------
| Attempts / Submissions
|--------------------------------------------------------------------------
*/

$submissionSearch = trim((string)($_GET['submission_search'] ?? ''));
$submissionExamId = (int)($_GET['submission_exam_id'] ?? 0);
$submissionCourseId = (int)($_GET['submission_course_id'] ?? 0);
$submissionStatus = trim((string)($_GET['submission_status'] ?? ''));

$submissionWhere = "1=1";
$submissionParams = [];

if ($submissionSearch !== '') {
    $submissionWhere .= " AND (s.full_name LIKE ? OR s.student_code LIKE ? OR e.title LIKE ?)";
    $sLike = '%' . $submissionSearch . '%';
    $submissionParams[] = $sLike;
    $submissionParams[] = $sLike;
    $submissionParams[] = $sLike;
}

if ($submissionExamId > 0) {
    $submissionWhere .= " AND a.exam_id = ?";
    $submissionParams[] = $submissionExamId;
}

if ($submissionCourseId > 0) {
    $submissionWhere .= " AND a.course_id = ?";
    $submissionParams[] = $submissionCourseId;
}

if ($submissionStatus !== '') {
    $submissionWhere .= " AND a.status = ?";
    $submissionParams[] = $submissionStatus;
}

$attempts = safeAll(
    $pdo,
    "
    SELECT
        a.*,
        e.title AS exam_title,
        e.exam_code,
        e.total_marks AS exam_total_marks,
        e.passing_marks,
        c.title AS course_title,
        s.full_name AS student_name,
        s.student_code,
        s.email AS student_email
    FROM core_exam_attempts a
    INNER JOIN core_exams e ON e.id = a.exam_id
    LEFT JOIN core_courses c ON c.id = a.course_id
    LEFT JOIN students s ON s.id = a.student_id
    WHERE $submissionWhere
    ORDER BY a.id DESC
    LIMIT 300
    ",
    $submissionParams
);

/*
|--------------------------------------------------------------------------
| Selected Attempt Details
|--------------------------------------------------------------------------
*/

$selectedAttempt = null;
$attemptAnswers = [];

if ($selectedAttemptId > 0) {
    $selectedAttempt = safeOne(
        $pdo,
        "
        SELECT
            a.*,
            e.title AS exam_title,
            e.exam_code,
            e.total_marks AS exam_total_marks,
            e.passing_marks,
            e.show_correct_answers,
            e.show_result_immediately,
            c.title AS course_title,
            s.full_name AS student_name,
            s.student_code,
            s.email AS student_email
        FROM core_exam_attempts a
        INNER JOIN core_exams e ON e.id = a.exam_id
        LEFT JOIN core_courses c ON c.id = a.course_id
        LEFT JOIN students s ON s.id = a.student_id
        WHERE a.id = ?
        LIMIT 1
        ",
        [$selectedAttemptId]
    );

    if ($selectedAttempt) {
        $attemptAnswers = safeAll(
            $pdo,
            "
            SELECT
                ans.*,
                q.question_text,
                q.question_type,
                q.marks,
                q.correct_answer,
                q.explanation,
                q.section_name,
                q.skill,
                opt.option_text AS selected_option_text
            FROM core_exam_answers ans
            INNER JOIN core_exam_questions q ON q.id = ans.question_id
            LEFT JOIN core_exam_options opt ON opt.id = ans.selected_option_id
            WHERE ans.attempt_id = ?
            ORDER BY q.sort_order ASC, q.id ASC
            ",
            [$selectedAttemptId]
        );
    }
}

/*
|--------------------------------------------------------------------------
| Reports Data
|--------------------------------------------------------------------------
*/

$reportExamId = (int)($_GET['report_exam_id'] ?? 0);
$reportCourseId = (int)($_GET['report_course_id'] ?? 0);

$reportWhere = "1=1";
$reportParams = [];

if ($reportExamId > 0) {
    $reportWhere .= " AND a.exam_id = ?";
    $reportParams[] = $reportExamId;
}

if ($reportCourseId > 0) {
    $reportWhere .= " AND a.course_id = ?";
    $reportParams[] = $reportCourseId;
}

$reportSummary = safeOne(
    $pdo,
    "
    SELECT
        COUNT(*) AS attempts_count,
        AVG(a.percentage) AS avg_percentage,
        MAX(a.percentage) AS highest_percentage,
        MIN(a.percentage) AS lowest_percentage,
        SUM(CASE WHEN a.result_status = 'pass' THEN 1 ELSE 0 END) AS pass_count,
        SUM(CASE WHEN a.result_status = 'fail' THEN 1 ELSE 0 END) AS fail_count,
        SUM(CASE WHEN a.result_status = 'pending' THEN 1 ELSE 0 END) AS pending_count
    FROM core_exam_attempts a
    WHERE $reportWhere
    ",
    $reportParams
);

$questionDifficultyReport = safeAll(
    $pdo,
    "
    SELECT
        q.id,
        q.question_text,
        q.question_type,
        q.marks,
        COUNT(ans.id) AS answers_count,
        AVG(ans.score_awarded) AS avg_score,
        SUM(CASE WHEN ans.is_correct = 1 THEN 1 ELSE 0 END) AS correct_count,
        SUM(CASE WHEN ans.is_correct = 0 THEN 1 ELSE 0 END) AS wrong_count
    FROM core_exam_questions q
    LEFT JOIN core_exam_answers ans ON ans.question_id = q.id
    LEFT JOIN core_exam_attempts a ON a.id = ans.attempt_id
    WHERE ($reportExamId = 0 OR q.exam_id = ?)
    GROUP BY q.id
    ORDER BY avg_score ASC
    LIMIT 100
    ",
    [$reportExamId]
);

$topStudentsReport = safeAll(
    $pdo,
    "
    SELECT
        s.full_name,
        s.student_code,
        c.title AS course_title,
        e.title AS exam_title,
        a.percentage,
        a.total_score,
        a.result_status,
        a.submitted_at
    FROM core_exam_attempts a
    INNER JOIN students s ON s.id = a.student_id
    INNER JOIN core_exams e ON e.id = a.exam_id
    LEFT JOIN core_courses c ON c.id = a.course_id
    WHERE $reportWhere
      AND a.status IN ('submitted','graded')
    ORDER BY a.percentage DESC
    LIMIT 20
    ",
    $reportParams
);

/*
|--------------------------------------------------------------------------
| Schedule Data
|--------------------------------------------------------------------------
*/

$upcomingExams = safeAll(
    $pdo,
    "
    SELECT
        e.*,
        c.title AS course_title,
        t.full_name AS teacher_full_name,
        t.name AS teacher_name
    FROM core_exams e
    LEFT JOIN core_courses c ON c.id = e.course_id
    LEFT JOIN core_teachers t ON t.id = e.teacher_id
    WHERE e.start_at IS NOT NULL
      AND e.start_at >= NOW()
      AND e.status IN ('draft','published')
    ORDER BY e.start_at ASC
    LIMIT 100
    "
);

$activeExams = safeAll(
    $pdo,
    "
    SELECT
        e.*,
        c.title AS course_title
    FROM core_exams e
    LEFT JOIN core_courses c ON c.id = e.course_id
    WHERE e.status = 'published'
      AND (e.start_at IS NULL OR e.start_at <= NOW())
      AND (e.end_at IS NULL OR e.end_at >= NOW())
    ORDER BY e.end_at ASC
    LIMIT 100
    "
);

$expiredOpenExams = safeAll(
    $pdo,
    "
    SELECT
        e.*,
        c.title AS course_title
    FROM core_exams e
    LEFT JOIN core_courses c ON c.id = e.course_id
    WHERE e.status = 'published'
      AND e.end_at IS NOT NULL
      AND e.end_at < NOW()
    ORDER BY e.end_at DESC
    LIMIT 100
    "
);

/*
|--------------------------------------------------------------------------
| Codes Data
|--------------------------------------------------------------------------
*/

$codeExams = safeAll(
    $pdo,
    "
    SELECT
        e.*,
        c.title AS course_title,
        COUNT(a.id) AS attempts_count
    FROM core_exams e
    LEFT JOIN core_courses c ON c.id = e.course_id
    LEFT JOIN core_exam_attempts a ON a.exam_id = e.id
    GROUP BY e.id
    ORDER BY e.id DESC
    LIMIT 200
    "
);

/*
|--------------------------------------------------------------------------
| Small UI State Helpers
|--------------------------------------------------------------------------
*/

$editExamId = (int)($_GET['edit_exam_id'] ?? 0);
$editExam = null;

if ($editExamId > 0) {
    $editExam = safeOne(
        $pdo,
        "SELECT * FROM core_exams WHERE id = ? LIMIT 1",
        [$editExamId]
    );
}

$editQuestionId = (int)($_GET['edit_question_id'] ?? 0);
$editQuestion = null;
$editQuestionOptions = [];

if ($editQuestionId > 0) {
    $editQuestion = safeOne(
        $pdo,
        "SELECT * FROM core_exam_questions WHERE id = ? LIMIT 1",
        [$editQuestionId]
    );

    if ($editQuestion) {
        $editQuestionOptions = safeAll(
            $pdo,
            "SELECT * FROM core_exam_options WHERE question_id = ? ORDER BY sort_order ASC, id ASC",
            [$editQuestionId]
        );
    }
}


?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title><?php echo e($pageTitle); ?></title>

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">

<style>
:root{
    --blue:#2563eb;
    --blue-dark:#1d4ed8;
    --indigo:#312e81;
    --purple:#7c3aed;
    --green:#059669;
    --orange:#f97316;
    --red:#dc2626;
    --yellow:#ca8a04;
    --dark:#0f172a;
    --text:#0f172a;
    --muted:#64748b;
    --line:#e2e8f0;
    --bg:#f6f8fc;
    --card:#ffffff;
    --shadow:0 24px 70px rgba(15,23,42,.09);
    --soft-shadow:0 12px 35px rgba(15,23,42,.06);
}

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

body{
    min-height:100vh;
    font-family:'Inter',sans-serif;
    color:var(--text);
    background:
        radial-gradient(circle at top left,rgba(37,99,235,.14),transparent 30%),
        radial-gradient(circle at top right,rgba(124,58,237,.10),transparent 34%),
        linear-gradient(135deg,#fbfdff,#eef5ff);
}

a{
    color:inherit;
    text-decoration:none;
}

.app{
    width:100%;
    max-width:1780px;
    margin:0 auto;
    padding:18px;
}

.topbar{
    display:flex;
    justify-content:space-between;
    align-items:flex-start;
    gap:18px;
    margin-bottom:18px;
}

.page-title{
    font-size:38px;
    font-weight:900;
    letter-spacing:-1px;
    line-height:1.1;
}

.page-subtitle{
    margin-top:8px;
    color:var(--muted);
    font-size:14px;
    line-height:1.8;
    font-weight:750;
    max-width:900px;
}

.top-actions{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
}

.btn{
    border:0;
    border-radius:15px;
    padding:12px 15px;
    font-family:inherit;
    font-size:12px;
    font-weight:900;
    cursor:pointer;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:7px;
    transition:.2s ease;
    white-space:nowrap;
}

.btn:hover{
    transform:translateY(-1px);
}

.btn-primary{
    background:linear-gradient(135deg,var(--blue),var(--blue-dark));
    color:#fff;
    box-shadow:0 14px 30px rgba(37,99,235,.22);
}

.btn-light{
    background:#fff;
    color:var(--blue-dark);
    border:1px solid #bfdbfe;
}

.btn-danger{
    background:linear-gradient(135deg,var(--red),#ef4444);
    color:#fff;
}

.btn-success{
    background:linear-gradient(135deg,var(--green),#10b981);
    color:#fff;
}

.btn-warning{
    background:linear-gradient(135deg,var(--orange),#fb923c);
    color:#fff;
}

.btn-dark{
    background:linear-gradient(135deg,#0f172a,#334155);
    color:#fff;
}

.btn-small{
    padding:9px 11px;
    font-size:11px;
    border-radius:12px;
}

.alert{
    padding:15px 17px;
    border-radius:18px;
    margin-bottom:16px;
    font-size:13px;
    font-weight:850;
    line-height:1.7;
}

.alert-success{
    background:#ecfdf5;
    color:#047857;
    border:1px solid #a7f3d0;
}

.alert-error{
    background:#fef2f2;
    color:#b91c1c;
    border:1px solid #fecaca;
}

.hero{
    position:relative;
    overflow:hidden;
    border-radius:34px;
    padding:28px;
    color:#fff;
    background:
        radial-gradient(circle at 12% 10%,rgba(255,255,255,.18),transparent 28%),
        linear-gradient(135deg,#0f172a,#1d4ed8,#312e81);
    box-shadow:0 30px 75px rgba(37,99,235,.24);
    margin-bottom:18px;
}

.hero::after{
    content:"EXAMS";
    position:absolute;
    right:24px;
    bottom:-30px;
    font-size:110px;
    font-weight:900;
    letter-spacing:-8px;
    color:rgba(255,255,255,.06);
}

.hero h2{
    position:relative;
    z-index:2;
    font-size:31px;
    font-weight:900;
    margin-bottom:9px;
}

.hero p{
    position:relative;
    z-index:2;
    max-width:930px;
    color:#dbeafe;
    font-size:14px;
    line-height:1.85;
    font-weight:750;
}

.stats-grid{
    position:relative;
    z-index:2;
    display:grid;
    grid-template-columns:repeat(8,1fr);
    gap:12px;
    margin-top:22px;
}

.stat-card{
    background:rgba(255,255,255,.14);
    border:1px solid rgba(255,255,255,.20);
    border-radius:21px;
    padding:16px;
    backdrop-filter:blur(12px);
}

.stat-card span{
    display:block;
    color:#bfdbfe;
    font-size:10px;
    font-weight:900;
    margin-bottom:6px;
}

.stat-card strong{
    display:block;
    font-size:24px;
    font-weight:900;
}

.tabs{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
    margin-bottom:18px;
}

.tab{
    padding:12px 15px;
    border-radius:16px;
    background:#fff;
    color:#64748b;
    border:1px solid var(--line);
    font-size:12px;
    font-weight:900;
    box-shadow:var(--soft-shadow);
}

.tab.active{
    background:linear-gradient(135deg,var(--blue),var(--indigo));
    color:#fff;
    border-color:transparent;
}

.panel{
    background:#fff;
    border:1px solid var(--line);
    border-radius:28px;
    padding:18px;
    box-shadow:var(--soft-shadow);
    margin-bottom:18px;
}

.panel-head{
    display:flex;
    justify-content:space-between;
    align-items:flex-end;
    gap:16px;
    flex-wrap:wrap;
    margin-bottom:16px;
}

.panel-title{
    font-size:21px;
    font-weight:900;
    letter-spacing:-.3px;
}

.panel-subtitle{
    color:var(--muted);
    font-size:12px;
    font-weight:750;
    line-height:1.7;
    margin-top:5px;
}

.grid{
    display:grid;
    gap:12px;
}

.grid-2{
    grid-template-columns:repeat(2,1fr);
}

.grid-3{
    grid-template-columns:repeat(3,1fr);
}

.grid-4{
    grid-template-columns:repeat(4,1fr);
}

.grid-5{
    grid-template-columns:repeat(5,1fr);
}

.input,
.select,
.textarea{
    width:100%;
    border:1px solid #d1d5db;
    background:#fff;
    border-radius:16px;
    padding:0 14px;
    min-height:48px;
    font-family:inherit;
    font-size:13px;
    font-weight:800;
    outline:none;
}

.textarea{
    min-height:105px;
    padding:13px 14px;
    resize:vertical;
    line-height:1.7;
}

.input:focus,
.select:focus,
.textarea:focus{
    border-color:var(--blue);
    box-shadow:0 0 0 4px rgba(37,99,235,.10);
}

.label{
    display:block;
    font-size:11px;
    font-weight:900;
    color:#475569;
    margin-bottom:7px;
}

.check-row{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
    align-items:center;
}

.check-pill{
    display:inline-flex;
    align-items:center;
    gap:7px;
    padding:10px 12px;
    border-radius:14px;
    background:#f8fafc;
    border:1px solid #e2e8f0;
    font-size:12px;
    font-weight:850;
    color:#475569;
}

.table-wrap{
    overflow-x:auto;
    border-radius:22px;
    border:1px solid var(--line);
}

.table{
    width:100%;
    border-collapse:collapse;
    min-width:1100px;
    background:#fff;
}

.table th{
    text-align:left;
    padding:14px 15px;
    background:#f8fafc;
    color:#64748b;
    font-size:11px;
    font-weight:900;
    border-bottom:1px solid var(--line);
}

.table td{
    padding:14px 15px;
    border-bottom:1px solid #f1f5f9;
    font-size:13px;
    font-weight:750;
    vertical-align:top;
}

.table tr:last-child td{
    border-bottom:0;
}

.item-title{
    font-weight:900;
    color:#0f172a;
    line-height:1.5;
}

.item-sub{
    margin-top:4px;
    font-size:11px;
    color:#64748b;
    font-weight:750;
    line-height:1.5;
}

.badge{
    display:inline-flex;
    align-items:center;
    gap:5px;
    padding:7px 10px;
    border-radius:999px;
    font-size:10px;
    font-weight:900;
    border:1px solid transparent;
    white-space:nowrap;
}

.badge-green{
    background:#ecfdf5;
    color:#047857;
    border-color:#a7f3d0;
}

.badge-blue{
    background:#eff6ff;
    color:#1d4ed8;
    border-color:#bfdbfe;
}

.badge-orange{
    background:#fff7ed;
    color:#c2410c;
    border-color:#fed7aa;
}

.badge-red{
    background:#fef2f2;
    color:#b91c1c;
    border-color:#fecaca;
}

.badge-gray{
    background:#f8fafc;
    color:#475569;
    border-color:#e2e8f0;
}

.badge-dark{
    background:#0f172a;
    color:#fff;
    border-color:#0f172a;
}

.actions{
    display:flex;
    gap:7px;
    flex-wrap:wrap;
}

.empty{
    border:1px dashed #cbd5e1;
    background:#fff;
    border-radius:28px;
    padding:40px 20px;
    text-align:center;
    color:#64748b;
    font-size:13px;
    font-weight:850;
    line-height:1.8;
}

.question-card{
    border:1px solid var(--line);
    background:#fff;
    border-radius:24px;
    padding:16px;
    margin-bottom:12px;
    box-shadow:var(--soft-shadow);
}

.question-top{
    display:flex;
    justify-content:space-between;
    gap:14px;
    flex-wrap:wrap;
    margin-bottom:12px;
}

.question-text{
    font-size:14px;
    font-weight:850;
    line-height:1.7;
    color:#0f172a;
}

.option-list{
    display:grid;
    gap:7px;
    margin-top:10px;
}

.option-item{
    padding:10px 12px;
    border-radius:14px;
    background:#f8fafc;
    border:1px solid #edf2f7;
    font-size:12px;
    font-weight:750;
}

.option-item.correct{
    background:#ecfdf5;
    border-color:#a7f3d0;
    color:#047857;
}

.kpi-row{
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:12px;
}

.kpi{
    background:#fff;
    border:1px solid var(--line);
    border-radius:22px;
    padding:16px;
    box-shadow:var(--soft-shadow);
}

.kpi span{
    color:#64748b;
    font-size:11px;
    font-weight:900;
}

.kpi strong{
    display:block;
    margin-top:6px;
    font-size:25px;
    font-weight:900;
}

.answer-box{
    border:1px solid var(--line);
    border-radius:22px;
    padding:15px;
    margin-bottom:12px;
    background:#fff;
}

.answer-box h4{
    font-size:14px;
    font-weight:900;
    margin-bottom:8px;
}

.answer-meta{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
    margin-bottom:10px;
}

.report-grid{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:18px;
}

.copy-code{
    font-family:monospace;
    font-size:14px;
    font-weight:900;
    background:#0f172a;
    color:#fff;
    padding:9px 11px;
    border-radius:12px;
    display:inline-flex;
}

@media(max-width:1350px){
    .stats-grid{
        grid-template-columns:repeat(4,1fr);
    }

    .grid-5,
    .grid-4{
        grid-template-columns:repeat(2,1fr);
    }

    .kpi-row{
        grid-template-columns:repeat(2,1fr);
    }

    .report-grid{
        grid-template-columns:1fr;
    }
}

@media(max-width:760px){
    .app{
        padding:12px;
    }

    .topbar{
        flex-direction:column;
    }

    .page-title{
        font-size:30px;
    }

    .hero{
        padding:22px;
    }

    .hero h2{
        font-size:25px;
    }

    .stats-grid,
    .grid-2,
    .grid-3,
    .grid-4,
    .grid-5,
    .kpi-row{
        grid-template-columns:1fr;
    }

    .tabs{
        display:grid;
        grid-template-columns:1fr 1fr;
    }

    .tab{
        text-align:center;
    }
}
</style>
</head>

<body>

<div class="app">

    <div class="topbar">
        <div>
            <div class="page-title">
                Admin Exams System
            </div>

            <div class="page-subtitle">
                Full SMI Core Periods exam center: exams, questions, question bank, submissions,
                grading, codes, schedule, reports, analytics, autosave support, and anti-cheating logs.
            </div>
        </div>

        <div class="top-actions">
            <a href="dashboard.php" class="btn btn-light">Dashboard</a>
            <a href="courses.php" class="btn btn-primary">Courses</a>
        </div>
    </div>

    <?php if ($successMessage): ?>
        <div class="alert alert-success">
            <?php echo e($successMessage); ?>
        </div>
    <?php endif; ?>

    <?php if ($errorMessage): ?>
        <div class="alert alert-error">
            <?php echo e($errorMessage); ?>
        </div>
    <?php endif; ?>

    <section class="hero">
        <h2>
            Complete Exam Control Center
        </h2>

        <p>
            Manage all exams from one premium dashboard. Create exams, attach questions, use the question bank,
            grade submissions, publish schedules, generate codes, and monitor performance analytics.
        </p>

        <div class="stats-grid">
            <div class="stat-card">
                <span>Total Exams</span>
                <strong><?php echo e((string)$totalExams); ?></strong>
            </div>

            <div class="stat-card">
                <span>Published</span>
                <strong><?php echo e((string)$publishedExams); ?></strong>
            </div>

            <div class="stat-card">
                <span>Draft</span>
                <strong><?php echo e((string)$draftExams); ?></strong>
            </div>

            <div class="stat-card">
                <span>Closed</span>
                <strong><?php echo e((string)$closedExams); ?></strong>
            </div>

            <div class="stat-card">
                <span>Archived</span>
                <strong><?php echo e((string)$archivedExams); ?></strong>
            </div>

            <div class="stat-card">
                <span>Attempts</span>
                <strong><?php echo e((string)$totalAttempts); ?></strong>
            </div>

            <div class="stat-card">
                <span>Avg Score</span>
                <strong><?php echo e((string)$averageScore); ?>%</strong>
            </div>

            <div class="stat-card">
                <span>Pass Rate</span>
                <strong><?php echo e((string)$passRate); ?>%</strong>
            </div>
        </div>
    </section>

    <nav class="tabs">
        <a class="tab <?php echo $activeTab === 'exams' ? 'active' : ''; ?>" href="exams.php?tab=exams">Exams</a>
        <a class="tab <?php echo $activeTab === 'questions' ? 'active' : ''; ?>" href="exams.php?tab=questions<?php echo $selectedExamId > 0 ? '&exam_id=' . (int)$selectedExamId : ''; ?>">Questions</a>
        <a class="tab <?php echo $activeTab === 'bank' ? 'active' : ''; ?>" href="exams.php?tab=bank">Question Bank</a>
        <a class="tab <?php echo $activeTab === 'submissions' ? 'active' : ''; ?>" href="exams.php?tab=submissions">Submissions</a>
        <a class="tab <?php echo $activeTab === 'reports' ? 'active' : ''; ?>" href="exams.php?tab=reports">Reports</a>
        <a class="tab <?php echo $activeTab === 'codes' ? 'active' : ''; ?>" href="exams.php?tab=codes">Codes</a>
        <a class="tab <?php echo $activeTab === 'schedule' ? 'active' : ''; ?>" href="exams.php?tab=schedule">Schedule</a>
    </nav>

    <?php if ($activeTab === 'exams'): ?>

        <section class="panel">
            <div class="panel-head">
                <div>
                    <div class="panel-title">
                        <?php echo $editExam ? 'Edit Exam' : 'Create New Exam'; ?>
                    </div>
                    <div class="panel-subtitle">
                        Create and configure exams with timing, attempts, code access, result policy, gradebook sync, and anti-cheating controls.
                    </div>
                </div>
            </div>

            <form method="post" class="grid">
                <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                <input type="hidden" name="action" value="<?php echo $editExam ? 'update_exam' : 'create_exam'; ?>">

                <?php if ($editExam): ?>
                    <input type="hidden" name="exam_id" value="<?php echo (int)$editExam['id']; ?>">
                <?php endif; ?>

                <div class="grid grid-4">
                    <div>
                        <label class="label">Course</label>
                        <select name="course_id" class="select" required>
                            <option value="">Choose course</option>
                            <?php foreach ($courses as $course): ?>
                                <option value="<?php echo (int)$course['id']; ?>"
                                    <?php echo (int)($editExam['course_id'] ?? 0) === (int)$course['id'] ? 'selected' : ''; ?>>
                                    <?php echo e((string)($course['title'] ?? 'Course')); ?>
                                    <?php if (!empty($course['course_code'])): ?>
                                        - <?php echo e((string)$course['course_code']); ?>
                                    <?php endif; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div>
                        <label class="label">Teacher Optional</label>
                        <select name="teacher_id" class="select">
                            <option value="">Auto from course</option>
                            <?php foreach ($teachers as $teacherRow): ?>
                                <option value="<?php echo (int)$teacherRow['id']; ?>"
                                    <?php echo (int)($editExam['teacher_id'] ?? 0) === (int)$teacherRow['id'] ? 'selected' : ''; ?>>
                                    <?php echo e((string)($teacherRow['full_name'] ?? $teacherRow['name'] ?? $teacherRow['email'] ?? 'Teacher')); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div>
                        <label class="label">Exam Type</label>
                        <select name="exam_type" class="select">
                            <?php foreach ($examTypes as $type): ?>
                                <option value="<?php echo e($type); ?>"
                                    <?php echo (string)($editExam['exam_type'] ?? 'quiz') === $type ? 'selected' : ''; ?>>
                                    <?php echo e(examTypeLabel($type)); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div>
                        <label class="label">Status</label>
                        <select name="status" class="select">
                            <?php foreach ($examStatuses as $statusItem): ?>
                                <option value="<?php echo e($statusItem); ?>"
                                    <?php echo (string)($editExam['status'] ?? 'draft') === $statusItem ? 'selected' : ''; ?>>
                                    <?php echo e(ucfirst($statusItem)); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="grid grid-2">
                    <div>
                        <label class="label">Exam Title</label>
                        <input type="text" name="title" class="input" required
                               value="<?php echo e((string)($editExam['title'] ?? '')); ?>"
                               placeholder="Example: Final Grammar Exam">
                    </div>

                    <div>
                        <label class="label">Exam Code</label>
                        <input type="text" name="exam_code" class="input"
                               value="<?php echo e((string)($editExam['exam_code'] ?? '')); ?>"
                               placeholder="Auto-generated if empty">
                    </div>
                </div>

                <div>
                    <label class="label">Description</label>
                    <textarea name="description" class="textarea" placeholder="Brief exam description"><?php echo e((string)($editExam['description'] ?? '')); ?></textarea>
                </div>

                <div class="grid grid-5">
                    <div>
                        <label class="label">Start At</label>
                        <input type="datetime-local" name="start_at" class="input"
                               value="<?php echo !empty($editExam['start_at']) ? e(date('Y-m-d\TH:i', strtotime((string)$editExam['start_at']))) : ''; ?>">
                    </div>

                    <div>
                        <label class="label">End At</label>
                        <input type="datetime-local" name="end_at" class="input"
                               value="<?php echo !empty($editExam['end_at']) ? e(date('Y-m-d\TH:i', strtotime((string)$editExam['end_at']))) : ''; ?>">
                    </div>

                    <div>
                        <label class="label">Duration Minutes</label>
                        <input type="number" name="duration_minutes" class="input" min="1"
                               value="<?php echo e((string)($editExam['duration_minutes'] ?? 60)); ?>">
                    </div>

                    <div>
                        <label class="label">Total Marks</label>
                        <input type="number" step="0.01" name="total_marks" class="input"
                               value="<?php echo e((string)($editExam['total_marks'] ?? 0)); ?>">
                    </div>

                    <div>
                        <label class="label">Passing Marks</label>
                        <input type="number" step="0.01" name="passing_marks" class="input"
                               value="<?php echo e((string)($editExam['passing_marks'] ?? 0)); ?>">
                    </div>
                </div>

                <div class="grid grid-4">
                    <div>
                        <label class="label">Max Attempts</label>
                        <input type="number" name="max_attempts" class="input" min="1"
                               value="<?php echo e((string)($editExam['max_attempts'] ?? 1)); ?>">
                    </div>

                    <div>
                        <label class="label">Release Results At</label>
                        <input type="datetime-local" name="release_results_at" class="input"
                               value="<?php echo !empty($editExam['release_results_at']) ? e(date('Y-m-d\TH:i', strtotime((string)$editExam['release_results_at']))) : ''; ?>">
                    </div>

                    <div>
                        <label class="label">Retake Policy</label>
                        <select name="retake_policy" class="select">
                            <?php foreach (['highest' => 'Highest Score', 'latest' => 'Latest Score', 'first' => 'First Score'] as $key => $label): ?>
                                <option value="<?php echo e($key); ?>"
                                    <?php echo (string)($editExam['retake_policy'] ?? 'highest') === $key ? 'selected' : ''; ?>>
                                    <?php echo e($label); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div>
                        <label class="label">Retake Wait Hours</label>
                        <input type="number" name="retake_wait_hours" class="input" min="0"
                               value="<?php echo e((string)($editExam['retake_wait_hours'] ?? 0)); ?>">
                    </div>
                </div>

                <div class="check-row">
                    <?php
                    $checks = [
                        'shuffle_questions' => 'Shuffle Questions',
                        'show_result_immediately' => 'Show Result Immediately',
                        'show_correct_answers' => 'Show Correct Answers',
                        'require_exam_code' => 'Require Exam Code',
                        'allow_resume' => 'Allow Resume',
                        'autosave_enabled' => 'Autosave',
                        'anti_cheating_enabled' => 'Anti-Cheating Logs',
                        'gradebook_enabled' => 'Gradebook Sync',
                        'certificate_enabled' => 'Certificate Eligibility',
                    ];
                    ?>

                    <?php foreach ($checks as $field => $label): ?>
                        <?php
                        $defaultChecked = in_array($field, ['show_result_immediately','allow_resume','autosave_enabled','anti_cheating_enabled','gradebook_enabled'], true);
                        $checked = $editExam
                            ? ((int)($editExam[$field] ?? 0) === 1)
                            : $defaultChecked;
                        ?>
                        <label class="check-pill">
                            <input type="checkbox" name="<?php echo e($field); ?>" value="1" <?php echo $checked ? 'checked' : ''; ?>>
                            <?php echo e($label); ?>
                        </label>
                    <?php endforeach; ?>
                </div>

                <div class="actions">
                    <button type="submit" class="btn btn-primary">
                        <?php echo $editExam ? 'Update Exam' : 'Create Exam'; ?>
                    </button>

                    <?php if ($editExam): ?>
                        <a href="exams.php?tab=exams" class="btn btn-light">Cancel Edit</a>
                    <?php endif; ?>
                </div>
            </form>
        </section>

        <section class="panel">
            <div class="panel-head">
                <div>
                    <div class="panel-title">All Exams</div>
                    <div class="panel-subtitle">Search, filter, publish, duplicate, archive, and open exam modules.</div>
                </div>
            </div>

            <form method="get" class="grid grid-5" style="margin-bottom:16px;">
                <input type="hidden" name="tab" value="exams">

                <input type="text" name="search" class="input" placeholder="Search title/code/course"
                       value="<?php echo e($search); ?>">

                <select name="filter_course_id" class="select">
                    <option value="0">All Courses</option>
                    <?php foreach ($courses as $course): ?>
                        <option value="<?php echo (int)$course['id']; ?>" <?php echo $filterCourseId === (int)$course['id'] ? 'selected' : ''; ?>>
                            <?php echo e((string)$course['title']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <select name="filter_teacher_id" class="select">
                    <option value="0">All Teachers</option>
                    <?php foreach ($teachers as $teacherRow): ?>
                        <option value="<?php echo (int)$teacherRow['id']; ?>" <?php echo $filterTeacherId === (int)$teacherRow['id'] ? 'selected' : ''; ?>>
                            <?php echo e((string)($teacherRow['full_name'] ?? $teacherRow['name'] ?? $teacherRow['email'] ?? 'Teacher')); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <select name="filter_status" class="select">
                    <option value="">All Status</option>
                    <?php foreach ($examStatuses as $statusItem): ?>
                        <option value="<?php echo e($statusItem); ?>" <?php echo $filterStatus === $statusItem ? 'selected' : ''; ?>>
                            <?php echo e(ucfirst($statusItem)); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <button type="submit" class="btn btn-primary">Filter</button>
            </form>

            <?php if (!$exams): ?>
                <div class="empty">No exams found.</div>
            <?php else: ?>
                <div class="table-wrap">
                    <table class="table">
                        <thead>
                        <tr>
                            <th>Exam</th>
                            <th>Course / Teacher</th>
                            <th>Code</th>
                            <th>Status</th>
                            <th>Schedule</th>
                            <th>Attempts</th>
                            <th>Performance</th>
                            <th>Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($exams as $exam): ?>
                            <?php
                            $examId = (int)$exam['id'];
                            $examAvg = round((float)($exam['avg_percentage'] ?? 0), 1);
                            $graded = (int)($exam['graded_count'] ?? 0);
                            $examPassRate = $graded > 0
                                ? round(((int)($exam['pass_count'] ?? 0) / $graded) * 100, 1)
                                : 0;
                            ?>
                            <tr>
                                <td>
                                    <div class="item-title"><?php echo e((string)$exam['title']); ?></div>
                                    <div class="item-sub">
                                        <?php echo e(examTypeLabel((string)$exam['exam_type'])); ?>
                                        · <?php echo e((string)$exam['duration_minutes']); ?> min
                                        · <?php echo e((string)$exam['total_marks']); ?> marks
                                    </div>
                                </td>

                                <td>
                                    <div class="item-title"><?php echo e((string)($exam['course_title'] ?? 'N/A')); ?></div>
                                    <div class="item-sub">
                                        Teacher:
                                        <?php echo e((string)($exam['teacher_full_name'] ?? $exam['teacher_name'] ?? 'N/A')); ?>
                                    </div>
                                </td>

                                <td>
                                    <span class="copy-code"><?php echo e((string)($exam['exam_code'] ?? 'N/A')); ?></span>
                                </td>

                                <td>
                                    <span class="badge <?php echo e(statusBadgeClass((string)$exam['status'])); ?>">
                                        <?php echo e(ucfirst((string)$exam['status'])); ?>
                                    </span>
                                </td>

                                <td>
                                    <div class="item-sub">
                                        Start: <?php echo e(formatDateTimeNice($exam['start_at'] ?? '')); ?><br>
                                        End: <?php echo e(formatDateTimeNice($exam['end_at'] ?? '')); ?>
                                    </div>
                                </td>

                                <td>
                                    <strong><?php echo e((string)($exam['attempts_count'] ?? 0)); ?></strong>
                                </td>

                                <td>
                                    <div class="item-sub">
                                        Avg: <?php echo e((string)$examAvg); ?>%<br>
                                        Pass: <?php echo e((string)$examPassRate); ?>%
                                    </div>
                                </td>

                                <td>
                                    <div class="actions">
                                        <a class="btn btn-small btn-light" href="exams.php?tab=exams&edit_exam_id=<?php echo $examId; ?>">Edit</a>
                                        <a class="btn btn-small btn-primary" href="exams.php?tab=questions&exam_id=<?php echo $examId; ?>">Questions</a>
                                        <a class="btn btn-small btn-light" href="exams.php?tab=submissions&submission_exam_id=<?php echo $examId; ?>">Submissions</a>
                                        <a class="btn btn-small btn-light" href="exams.php?tab=reports&report_exam_id=<?php echo $examId; ?>">Reports</a>

                                        <form method="post" style="display:inline;">
                                            <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                                            <input type="hidden" name="exam_id" value="<?php echo $examId; ?>">
                                            <input type="hidden" name="action" value="publish_exam">
                                            <button class="btn btn-small btn-success" type="submit">Publish</button>
                                        </form>

                                        <form method="post" style="display:inline;">
                                            <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                                            <input type="hidden" name="exam_id" value="<?php echo $examId; ?>">
                                            <input type="hidden" name="action" value="close_exam">
                                            <button class="btn btn-small btn-warning" type="submit">Close</button>
                                        </form>

                                        <form method="post" style="display:inline;">
                                            <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                                            <input type="hidden" name="exam_id" value="<?php echo $examId; ?>">
                                            <input type="hidden" name="action" value="duplicate_exam">
                                            <button class="btn btn-small btn-dark" type="submit">Duplicate</button>
                                        </form>

                                        <form method="post" style="display:inline;" onsubmit="return confirm('Archive this exam?');">
                                            <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                                            <input type="hidden" name="exam_id" value="<?php echo $examId; ?>">
                                            <input type="hidden" name="action" value="archive_exam">
                                            <button class="btn btn-small btn-danger" type="submit">Archive</button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </section>

    <?php endif; ?>
    
        <?php if ($activeTab === 'questions'): ?>

        <section class="panel">
            <div class="panel-head">
                <div>
                    <div class="panel-title">Exam Questions</div>
                    <div class="panel-subtitle">Select an exam, then add questions, options, skills, marks, rubrics, and bank links.</div>
                </div>
            </div>

            <form method="get" class="grid grid-3" style="margin-bottom:16px;">
                <input type="hidden" name="tab" value="questions">

                <select name="exam_id" class="select" required>
                    <option value="">Choose exam</option>
                    <?php foreach ($exams as $exam): ?>
                        <option value="<?php echo (int)$exam['id']; ?>" <?php echo $selectedExamId === (int)$exam['id'] ? 'selected' : ''; ?>>
                            <?php echo e((string)$exam['title']); ?> - <?php echo e((string)($exam['course_title'] ?? 'Course')); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <button type="submit" class="btn btn-primary">Open Exam</button>

                <?php if ($selectedExam): ?>
                    <a href="exams.php?tab=bank&exam_id=<?php echo (int)$selectedExam['id']; ?>" class="btn btn-light">Open Question Bank</a>
                <?php endif; ?>
            </form>

            <?php if (!$selectedExam): ?>
                <div class="empty">Choose an exam first to manage questions.</div>
            <?php else: ?>

                <div class="kpi-row" style="margin-bottom:16px;">
                    <div class="kpi">
                        <span>Selected Exam</span>
                        <strong style="font-size:18px;"><?php echo e((string)$selectedExam['title']); ?></strong>
                    </div>

                    <div class="kpi">
                        <span>Questions</span>
                        <strong><?php echo e((string)count($examQuestions)); ?></strong>
                    </div>

                    <div class="kpi">
                        <span>Total Marks</span>
                        <strong><?php echo e((string)$selectedExam['total_marks']); ?></strong>
                    </div>

                    <div class="kpi">
                        <span>Status</span>
                        <strong style="font-size:18px;"><?php echo e(ucfirst((string)$selectedExam['status'])); ?></strong>
                    </div>
                </div>

                <section class="panel" style="box-shadow:none;">
                    <div class="panel-title" style="margin-bottom:12px;">
                        <?php echo $editQuestion ? 'Edit Question' : 'Add New Question'; ?>
                    </div>

                    <form method="post" class="grid">
                        <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                        <input type="hidden" name="action" value="<?php echo $editQuestion ? 'update_question' : 'add_question'; ?>">
                        <input type="hidden" name="exam_id" value="<?php echo (int)$selectedExam['id']; ?>">

                        <?php if ($editQuestion): ?>
                            <input type="hidden" name="question_id" value="<?php echo (int)$editQuestion['id']; ?>">
                        <?php endif; ?>

                        <div class="grid grid-4">
                            <div>
                                <label class="label">Question Type</label>
                                <select name="question_type" class="select">
                                    <?php foreach ($questionTypes as $type): ?>
                                        <option value="<?php echo e($type); ?>" <?php echo (string)($editQuestion['question_type'] ?? 'multiple_choice') === $type ? 'selected' : ''; ?>>
                                            <?php echo e(questionTypeLabel($type)); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div>
                                <label class="label">Section</label>
                                <input type="text" name="section_name" class="input" placeholder="Reading / Grammar / Writing"
                                       value="<?php echo e((string)($editQuestion['section_name'] ?? '')); ?>">
                            </div>

                            <div>
                                <label class="label">Skill</label>
                                <select name="skill" class="select">
                                    <?php foreach ($skills as $skill): ?>
                                        <option value="<?php echo e($skill); ?>" <?php echo (string)($editQuestion['skill'] ?? 'general') === $skill ? 'selected' : ''; ?>>
                                            <?php echo e(ucfirst($skill)); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div>
                                <label class="label">Difficulty</label>
                                <select name="difficulty" class="select">
                                    <?php foreach (['easy','medium','hard','elite'] as $diff): ?>
                                        <option value="<?php echo e($diff); ?>" <?php echo (string)($editQuestion['difficulty'] ?? 'medium') === $diff ? 'selected' : ''; ?>>
                                            <?php echo e(ucfirst($diff)); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <div>
                            <label class="label">Question Text</label>
                            <textarea name="question_text" class="textarea" required placeholder="Write the full question here"><?php echo e((string)($editQuestion['question_text'] ?? '')); ?></textarea>
                        </div>

                        <div class="grid grid-4">
                            <div>
                                <label class="label">Marks</label>
                                <input type="number" step="0.01" name="marks" class="input" value="<?php echo e((string)($editQuestion['marks'] ?? 1)); ?>">
                            </div>

                            <div>
                                <label class="label">Sort Order</label>
                                <input type="number" name="sort_order" class="input" value="<?php echo e((string)($editQuestion['sort_order'] ?? 0)); ?>">
                            </div>

                            <div>
                                <label class="label">Correct Answer</label>
                                <input type="text" name="correct_answer" class="input" placeholder="For fill blank / short answer"
                                       value="<?php echo e((string)($editQuestion['correct_answer'] ?? '')); ?>">
                            </div>

                            <div>
                                <label class="label">True/False Answer</label>
                                <select name="true_false_answer" class="select">
                                    <option value="true" <?php echo (string)($editQuestion['correct_answer'] ?? '') === 'true' ? 'selected' : ''; ?>>True</option>
                                    <option value="false" <?php echo (string)($editQuestion['correct_answer'] ?? '') === 'false' ? 'selected' : ''; ?>>False</option>
                                </select>
                            </div>
                        </div>

                        <div>
                            <label class="label">Multiple Choice Options</label>
                            <div class="grid grid-2">
                                <?php for ($i = 0; $i < 4; $i++): ?>
                                    <?php
                                    $optionText = (string)($editQuestionOptions[$i]['option_text'] ?? '');
                                    $isCorrectOption = !empty($editQuestionOptions[$i]['is_correct']);
                                    ?>
                                    <div>
                                        <input type="text" name="options[<?php echo $i; ?>]" class="input"
                                               placeholder="Option <?php echo $i + 1; ?>"
                                               value="<?php echo e($optionText); ?>">
                                        <label class="check-pill" style="margin-top:7px;">
                                            <input type="radio" name="correct_option" value="<?php echo $i; ?>" <?php echo $isCorrectOption ? 'checked' : ''; ?>>
                                            Correct Option
                                        </label>
                                    </div>
                                <?php endfor; ?>
                            </div>
                        </div>

                        <div>
                            <label class="label">Explanation</label>
                            <textarea name="explanation" class="textarea" placeholder="Optional explanation shown after result if allowed"><?php echo e((string)($editQuestion['explanation'] ?? '')); ?></textarea>
                        </div>

                        <div class="grid grid-5">
                            <div>
                                <label class="label">Rubric Grammar</label>
                                <input type="number" name="rubric_grammar" class="input" value="0">
                            </div>
                            <div>
                                <label class="label">Rubric Vocabulary</label>
                                <input type="number" name="rubric_vocabulary" class="input" value="0">
                            </div>
                            <div>
                                <label class="label">Rubric Coherence</label>
                                <input type="number" name="rubric_coherence" class="input" value="0">
                            </div>
                            <div>
                                <label class="label">Rubric Pronunciation</label>
                                <input type="number" name="rubric_pronunciation" class="input" value="0">
                            </div>
                            <div>
                                <label class="label">Rubric Task Response</label>
                                <input type="number" name="rubric_task_response" class="input" value="0">
                            </div>
                        </div>

                        <div class="check-row">
                            <label class="check-pill">
                                <input type="checkbox" name="is_required" value="1" <?php echo !$editQuestion || (int)($editQuestion['is_required'] ?? 1) === 1 ? 'checked' : ''; ?>>
                                Required
                            </label>

                            <label class="check-pill">
                                <input type="checkbox" name="allow_file_upload" value="1" <?php echo (int)($editQuestion['allow_file_upload'] ?? 0) === 1 ? 'checked' : ''; ?>>
                                Allow File Upload
                            </label>

                            <?php if (!$editQuestion): ?>
                                <label class="check-pill">
                                    <input type="checkbox" name="save_to_bank" value="1">
                                    Save To Question Bank
                                </label>
                            <?php endif; ?>
                        </div>

                        <div class="actions">
                            <button type="submit" class="btn btn-primary">
                                <?php echo $editQuestion ? 'Update Question' : 'Add Question'; ?>
                            </button>

                            <?php if ($editQuestion): ?>
                                <a href="exams.php?tab=questions&exam_id=<?php echo (int)$selectedExam['id']; ?>" class="btn btn-light">Cancel Edit</a>
                            <?php endif; ?>
                        </div>
                    </form>
                </section>

                <?php if (!$examQuestions): ?>
                    <div class="empty">No questions added yet.</div>
                <?php else: ?>
                    <?php foreach ($examQuestions as $index => $question): ?>
                        <div class="question-card">
                            <div class="question-top">
                                <div>
                                    <div class="item-sub">
                                        Q<?php echo $index + 1; ?> ·
                                        <?php echo e(questionTypeLabel((string)$question['question_type'])); ?> ·
                                        <?php echo e((string)$question['marks']); ?> marks ·
                                        <?php echo e(ucfirst((string)($question['skill'] ?? 'general'))); ?>
                                    </div>

                                    <div class="question-text">
                                        <?php echo nl2br(e((string)$question['question_text'])); ?>
                                    </div>
                                </div>

                                <div class="actions">
                                    <a class="btn btn-small btn-light" href="exams.php?tab=questions&exam_id=<?php echo (int)$selectedExam['id']; ?>&edit_question_id=<?php echo (int)$question['id']; ?>">Edit</a>

                                    <form method="post" style="display:inline;">
                                        <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                                        <input type="hidden" name="action" value="move_question">
                                        <input type="hidden" name="question_id" value="<?php echo (int)$question['id']; ?>">
                                        <input type="hidden" name="direction" value="up">
                                        <button class="btn btn-small btn-light" type="submit">↑</button>
                                    </form>

                                    <form method="post" style="display:inline;">
                                        <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                                        <input type="hidden" name="action" value="move_question">
                                        <input type="hidden" name="question_id" value="<?php echo (int)$question['id']; ?>">
                                        <input type="hidden" name="direction" value="down">
                                        <button class="btn btn-small btn-light" type="submit">↓</button>
                                    </form>

                                    <form method="post" style="display:inline;" onsubmit="return confirm('Delete this question?');">
                                        <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                                        <input type="hidden" name="action" value="delete_question">
                                        <input type="hidden" name="question_id" value="<?php echo (int)$question['id']; ?>">
                                        <button class="btn btn-small btn-danger" type="submit">Delete</button>
                                    </form>
                                </div>
                            </div>

                            <?php $opts = $questionOptionsMap[(int)$question['id']] ?? []; ?>
                            <?php if ($opts): ?>
                                <div class="option-list">
                                    <?php foreach ($opts as $opt): ?>
                                        <div class="option-item <?php echo (int)$opt['is_correct'] === 1 ? 'correct' : ''; ?>">
                                            <?php echo e((string)$opt['option_text']); ?>
                                            <?php if ((int)$opt['is_correct'] === 1): ?>
                                                ✅
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>

                            <?php if (!empty($question['correct_answer'])): ?>
                                <div class="item-sub" style="margin-top:10px;">
                                    Correct Answer: <strong><?php echo e((string)$question['correct_answer']); ?></strong>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>

            <?php endif; ?>
        </section>

    <?php endif; ?>

    <?php if ($activeTab === 'bank'): ?>

        <section class="panel">
            <div class="panel-head">
                <div>
                    <div class="panel-title">Question Bank</div>
                    <div class="panel-subtitle">Create reusable questions and attach them to exams quickly.</div>
                </div>
            </div>

            <form method="post" class="grid" style="margin-bottom:18px;">
                <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                <input type="hidden" name="action" value="add_bank_question">

                <div class="grid grid-4">
                    <select name="course_id" class="select">
                        <option value="0">General Question</option>
                        <?php foreach ($courses as $course): ?>
                            <option value="<?php echo (int)$course['id']; ?>">
                                <?php echo e((string)$course['title']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <select name="question_type" class="select">
                        <?php foreach ($questionTypes as $type): ?>
                            <option value="<?php echo e($type); ?>"><?php echo e(questionTypeLabel($type)); ?></option>
                        <?php endforeach; ?>
                    </select>

                    <select name="skill" class="select">
                        <?php foreach ($skills as $skill): ?>
                            <option value="<?php echo e($skill); ?>"><?php echo e(ucfirst($skill)); ?></option>
                        <?php endforeach; ?>
                    </select>

                    <select name="difficulty" class="select">
                        <?php foreach (['easy','medium','hard','elite'] as $diff): ?>
                            <option value="<?php echo e($diff); ?>"><?php echo e(ucfirst($diff)); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <textarea name="question_text" class="textarea" required placeholder="Question text"></textarea>

                <div class="grid grid-4">
                    <input type="text" name="correct_answer" class="input" placeholder="Correct answer">
                    <input type="number" step="0.01" name="marks" class="input" value="1" placeholder="Marks">
                    <input type="text" name="section_name" class="input" placeholder="Section">
                    <input type="text" name="tags" class="input" placeholder="Tags">
                </div>

                <textarea name="explanation" class="textarea" placeholder="Explanation"></textarea>

                <button type="submit" class="btn btn-primary">Add To Bank</button>
            </form>

            <form method="get" class="grid grid-5" style="margin-bottom:16px;">
                <input type="hidden" name="tab" value="bank">
                <?php if ($selectedExamId > 0): ?>
                    <input type="hidden" name="exam_id" value="<?php echo (int)$selectedExamId; ?>">
                <?php endif; ?>

                <input type="text" name="bank_search" class="input" placeholder="Search bank"
                       value="<?php echo e($bankSearch); ?>">

                <select name="bank_course_id" class="select">
                    <option value="0">All Courses</option>
                    <?php foreach ($courses as $course): ?>
                        <option value="<?php echo (int)$course['id']; ?>" <?php echo $bankCourseId === (int)$course['id'] ? 'selected' : ''; ?>>
                            <?php echo e((string)$course['title']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <select name="bank_skill" class="select">
                    <option value="">All Skills</option>
                    <?php foreach ($skills as $skill): ?>
                        <option value="<?php echo e($skill); ?>" <?php echo $bankSkill === $skill ? 'selected' : ''; ?>>
                            <?php echo e(ucfirst($skill)); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <select name="bank_type" class="select">
                    <option value="">All Types</option>
                    <?php foreach ($questionTypes as $type): ?>
                        <option value="<?php echo e($type); ?>" <?php echo $bankType === $type ? 'selected' : ''; ?>>
                            <?php echo e(questionTypeLabel($type)); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <button type="submit" class="btn btn-primary">Filter</button>
            </form>

            <?php if (!$questionBank): ?>
                <div class="empty">No question bank items found.</div>
            <?php else: ?>
                <div class="table-wrap">
                    <table class="table">
                        <thead>
                        <tr>
                            <th>Question</th>
                            <th>Type</th>
                            <th>Skill</th>
                            <th>Course</th>
                            <th>Marks</th>
                            <th>Difficulty</th>
                            <th>Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($questionBank as $bank): ?>
                            <tr>
                                <td>
                                    <div class="item-title"><?php echo e(mb_strimwidth((string)$bank['question_text'], 0, 120, '...')); ?></div>
                                    <div class="item-sub"><?php echo e((string)($bank['tags'] ?? '')); ?></div>
                                </td>
                                <td><?php echo e(questionTypeLabel((string)$bank['question_type'])); ?></td>
                                <td><?php echo e(ucfirst((string)($bank['skill'] ?? 'general'))); ?></td>
                                <td><?php echo e((string)($bank['course_title'] ?? 'General')); ?></td>
                                <td><?php echo e((string)$bank['marks']); ?></td>
                                <td><span class="badge badge-gray"><?php echo e(ucfirst((string)$bank['difficulty'])); ?></span></td>
                                <td>
                                    <div class="actions">
                                        <?php if ($selectedExamId > 0): ?>
                                            <form method="post">
                                                <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                                                <input type="hidden" name="action" value="add_bank_to_exam">
                                                <input type="hidden" name="exam_id" value="<?php echo (int)$selectedExamId; ?>">
                                                <input type="hidden" name="bank_question_id" value="<?php echo (int)$bank['id']; ?>">
                                                <button class="btn btn-small btn-primary" type="submit">Add To Exam</button>
                                            </form>
                                        <?php endif; ?>

                                        <form method="post" onsubmit="return confirm('Delete this bank question?');">
                                            <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                                            <input type="hidden" name="action" value="delete_bank_question">
                                            <input type="hidden" name="bank_question_id" value="<?php echo (int)$bank['id']; ?>">
                                            <button class="btn btn-small btn-danger" type="submit">Delete</button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </section>

    <?php endif; ?>

    <?php if ($activeTab === 'submissions'): ?>

        <section class="panel">
            <div class="panel-head">
                <div>
                    <div class="panel-title">Submissions & Manual Grading</div>
                    <div class="panel-subtitle">Review attempts, grade essays/speaking/file-upload answers, recalculate scores, and sync gradebook.</div>
                </div>
            </div>

            <?php if ($selectedAttempt): ?>
                <div class="kpi-row" style="margin-bottom:16px;">
                    <div class="kpi">
                        <span>Student</span>
                        <strong style="font-size:18px;"><?php echo e((string)$selectedAttempt['student_name']); ?></strong>
                    </div>
                    <div class="kpi">
                        <span>Exam</span>
                        <strong style="font-size:18px;"><?php echo e((string)$selectedAttempt['exam_title']); ?></strong>
                    </div>
                    <div class="kpi">
                        <span>Score</span>
                        <strong><?php echo e((string)$selectedAttempt['percentage']); ?>%</strong>
                    </div>
                    <div class="kpi">
                        <span>Status</span>
                        <strong style="font-size:18px;"><?php echo e((string)$selectedAttempt['result_status']); ?></strong>
                    </div>
                </div>

                <form method="post" class="grid">
                    <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                    <input type="hidden" name="action" value="bulk_grade_attempt">
                    <input type="hidden" name="attempt_id" value="<?php echo (int)$selectedAttempt['id']; ?>">

                    <?php foreach ($attemptAnswers as $answer): ?>
                        <div class="answer-box">
                            <div class="answer-meta">
                                <span class="badge badge-blue"><?php echo e(questionTypeLabel((string)$answer['question_type'])); ?></span>
                                <span class="badge badge-gray"><?php echo e((string)$answer['marks']); ?> marks</span>
                                <span class="badge <?php echo $answer['is_correct'] === null ? 'badge-orange' : ((int)$answer['is_correct'] === 1 ? 'badge-green' : 'badge-red'); ?>">
                                    <?php echo $answer['is_correct'] === null ? 'Manual Needed' : ((int)$answer['is_correct'] === 1 ? 'Correct' : 'Wrong'); ?>
                                </span>
                            </div>

                            <h4><?php echo nl2br(e((string)$answer['question_text'])); ?></h4>

                            <div class="item-sub">
                                Student Answer:
                            </div>

                            <div style="padding:12px;border-radius:14px;background:#f8fafc;border:1px solid #e2e8f0;margin:8px 0 12px;">
                                <?php echo nl2br(e((string)($answer['answer_text'] ?? $answer['selected_option_text'] ?? 'No answer'))); ?>
                            </div>

                            <div class="grid grid-2">
                                <div>
                                    <label class="label">Score Awarded</label>
                                    <input type="number" step="0.01" class="input"
                                           name="scores[<?php echo (int)$answer['id']; ?>]"
                                           value="<?php echo e((string)$answer['score_awarded']); ?>">
                                </div>

                                <div>
                                    <label class="label">Feedback</label>
                                    <input type="text" class="input"
                                           name="feedbacks[<?php echo (int)$answer['id']; ?>]"
                                           value="<?php echo e((string)($answer['teacher_feedback'] ?? '')); ?>">
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>

                    <div>
                        <label class="label">General Attempt Feedback</label>
                        <textarea name="attempt_feedback" class="textarea"><?php echo e((string)($selectedAttempt['feedback'] ?? '')); ?></textarea>
                    </div>

                    <div class="actions">
                        <button type="submit" class="btn btn-primary">Save Grading</button>
                    </div>
                </form>

                <div class="actions" style="margin-top:14px;">
                    <form method="post">
                        <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                        <input type="hidden" name="action" value="recalculate_attempt">
                        <input type="hidden" name="attempt_id" value="<?php echo (int)$selectedAttempt['id']; ?>">
                        <button class="btn btn-light" type="submit">Recalculate Score</button>
                    </form>

                    <form method="post">
                        <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                        <input type="hidden" name="action" value="reopen_attempt">
                        <input type="hidden" name="attempt_id" value="<?php echo (int)$selectedAttempt['id']; ?>">
                        <input type="hidden" name="extra_minutes" value="30">
                        <button class="btn btn-warning" type="submit">Reopen 30 Min</button>
                    </form>

                    <form method="post" onsubmit="return confirm('Cancel this attempt?');">
                        <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                        <input type="hidden" name="action" value="cancel_attempt">
                        <input type="hidden" name="attempt_id" value="<?php echo (int)$selectedAttempt['id']; ?>">
                        <button class="btn btn-danger" type="submit">Cancel Attempt</button>
                    </form>
                </div>

                <hr style="border:0;border-top:1px solid #e2e8f0;margin:22px 0;">
            <?php endif; ?>

            <form method="get" class="grid grid-5" style="margin-bottom:16px;">
                <input type="hidden" name="tab" value="submissions">

                <input type="text" name="submission_search" class="input" placeholder="Search student/exam"
                       value="<?php echo e($submissionSearch); ?>">

                <select name="submission_exam_id" class="select">
                    <option value="0">All Exams</option>
                    <?php foreach ($exams as $exam): ?>
                        <option value="<?php echo (int)$exam['id']; ?>" <?php echo $submissionExamId === (int)$exam['id'] ? 'selected' : ''; ?>>
                            <?php echo e((string)$exam['title']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <select name="submission_course_id" class="select">
                    <option value="0">All Courses</option>
                    <?php foreach ($courses as $course): ?>
                        <option value="<?php echo (int)$course['id']; ?>" <?php echo $submissionCourseId === (int)$course['id'] ? 'selected' : ''; ?>>
                            <?php echo e((string)$course['title']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <select name="submission_status" class="select">
                    <option value="">All Status</option>
                    <?php foreach (['in_progress','submitted','graded','expired','cancelled'] as $s): ?>
                        <option value="<?php echo e($s); ?>" <?php echo $submissionStatus === $s ? 'selected' : ''; ?>>
                            <?php echo e(ucfirst(str_replace('_',' ',$s))); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <button type="submit" class="btn btn-primary">Filter</button>
            </form>

            <?php if (!$attempts): ?>
                <div class="empty">No submissions found.</div>
            <?php else: ?>
                <div class="table-wrap">
                    <table class="table">
                        <thead>
                        <tr>
                            <th>Student</th>
                            <th>Exam</th>
                            <th>Course</th>
                            <th>Attempt</th>
                            <th>Status</th>
                            <th>Score</th>
                            <th>Submitted</th>
                            <th>Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($attempts as $attempt): ?>
                            <tr>
                                <td>
                                    <div class="item-title"><?php echo e((string)($attempt['student_name'] ?? 'Student')); ?></div>
                                    <div class="item-sub"><?php echo e((string)($attempt['student_code'] ?? '')); ?></div>
                                </td>
                                <td><?php echo e((string)$attempt['exam_title']); ?></td>
                                <td><?php echo e((string)($attempt['course_title'] ?? 'N/A')); ?></td>
                                <td>#<?php echo e((string)$attempt['attempt_number']); ?></td>
                                <td>
                                    <span class="badge <?php echo e(attemptStatusBadgeClass((string)$attempt['status'])); ?>">
                                        <?php echo e(ucfirst(str_replace('_',' ',(string)$attempt['status']))); ?>
                                    </span>
                                </td>
                                <td><?php echo e((string)$attempt['percentage']); ?>%</td>
                                <td><?php echo e(formatDateTimeNice($attempt['submitted_at'] ?? '')); ?></td>
                                <td>
                                    <a href="exams.php?tab=submissions&attempt_id=<?php echo (int)$attempt['id']; ?>" class="btn btn-small btn-primary">
                                        Review
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </section>

    <?php endif; ?>

    <?php if ($activeTab === 'reports'): ?>

        <section class="panel">
            <div class="panel-head">
                <div>
                    <div class="panel-title">Exam Reports & Analytics</div>
                    <div class="panel-subtitle">Analyze performance, pass rate, difficult questions, and top students.</div>
                </div>
            </div>

            <form method="get" class="grid grid-3" style="margin-bottom:16px;">
                <input type="hidden" name="tab" value="reports">

                <select name="report_exam_id" class="select">
                    <option value="0">All Exams</option>
                    <?php foreach ($exams as $exam): ?>
                        <option value="<?php echo (int)$exam['id']; ?>" <?php echo $reportExamId === (int)$exam['id'] ? 'selected' : ''; ?>>
                            <?php echo e((string)$exam['title']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <select name="report_course_id" class="select">
                    <option value="0">All Courses</option>
                    <?php foreach ($courses as $course): ?>
                        <option value="<?php echo (int)$course['id']; ?>" <?php echo $reportCourseId === (int)$course['id'] ? 'selected' : ''; ?>>
                            <?php echo e((string)$course['title']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <button type="submit" class="btn btn-primary">Generate Report</button>
            </form>

            <div class="kpi-row" style="margin-bottom:18px;">
                <div class="kpi">
                    <span>Attempts</span>
                    <strong><?php echo e((string)($reportSummary['attempts_count'] ?? 0)); ?></strong>
                </div>
                <div class="kpi">
                    <span>Average</span>
                    <strong><?php echo e((string)round((float)($reportSummary['avg_percentage'] ?? 0), 1)); ?>%</strong>
                </div>
                <div class="kpi">
                    <span>Highest</span>
                    <strong><?php echo e((string)round((float)($reportSummary['highest_percentage'] ?? 0), 1)); ?>%</strong>
                </div>
                <div class="kpi">
                    <span>Pending</span>
                    <strong><?php echo e((string)($reportSummary['pending_count'] ?? 0)); ?></strong>
                </div>
            </div>

            <div class="report-grid">
                <section class="panel" style="box-shadow:none;">
                    <div class="panel-title" style="margin-bottom:12px;">Most Difficult Questions</div>

                    <?php foreach ($questionDifficultyReport as $qr): ?>
                        <div class="question-card">
                            <div class="item-title"><?php echo e(mb_strimwidth((string)$qr['question_text'], 0, 130, '...')); ?></div>
                            <div class="item-sub">
                                Type: <?php echo e(questionTypeLabel((string)$qr['question_type'])); ?> ·
                                Avg Score: <?php echo e((string)round((float)($qr['avg_score'] ?? 0), 2)); ?> /
                                <?php echo e((string)$qr['marks']); ?> ·
                                Answers: <?php echo e((string)($qr['answers_count'] ?? 0)); ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </section>

                <section class="panel" style="box-shadow:none;">
                    <div class="panel-title" style="margin-bottom:12px;">Top Students</div>

                    <?php foreach ($topStudentsReport as $studentRow): ?>
                        <div class="question-card">
                            <div class="item-title">
                                <?php echo e((string)$studentRow['full_name']); ?>
                                - <?php echo e((string)$studentRow['percentage']); ?>%
                            </div>
                            <div class="item-sub">
                                <?php echo e((string)$studentRow['exam_title']); ?> ·
                                <?php echo e((string)$studentRow['course_title']); ?> ·
                                <?php echo e((string)$studentRow['result_status']); ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </section>
            </div>
        </section>

    <?php endif; ?>

    <?php if ($activeTab === 'codes'): ?>

        <section class="panel">
            <div class="panel-head">
                <div>
                    <div class="panel-title">Exam Codes</div>
                    <div class="panel-subtitle">Generate, copy, and control exam code requirements.</div>
                </div>
            </div>

            <div class="table-wrap">
                <table class="table">
                    <thead>
                    <tr>
                        <th>Exam</th>
                        <th>Course</th>
                        <th>Code</th>
                        <th>Required</th>
                        <th>Attempts</th>
                        <th>Actions</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($codeExams as $exam): ?>
                        <tr>
                            <td><?php echo e((string)$exam['title']); ?></td>
                            <td><?php echo e((string)($exam['course_title'] ?? 'N/A')); ?></td>
                            <td><span class="copy-code"><?php echo e((string)$exam['exam_code']); ?></span></td>
                            <td>
                                <span class="badge <?php echo (int)$exam['require_exam_code'] === 1 ? 'badge-green' : 'badge-gray'; ?>">
                                    <?php echo (int)$exam['require_exam_code'] === 1 ? 'Required' : 'Not Required'; ?>
                                </span>
                            </td>
                            <td><?php echo e((string)($exam['attempts_count'] ?? 0)); ?></td>
                            <td>
                                <div class="actions">
                                    <form method="post">
                                        <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                                        <input type="hidden" name="action" value="regenerate_exam_code">
                                        <input type="hidden" name="exam_id" value="<?php echo (int)$exam['id']; ?>">
                                        <button class="btn btn-small btn-primary" type="submit">Regenerate</button>
                                    </form>

                                    <form method="post">
                                        <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                                        <input type="hidden" name="action" value="toggle_exam_code_requirement">
                                        <input type="hidden" name="exam_id" value="<?php echo (int)$exam['id']; ?>">
                                        <button class="btn btn-small btn-light" type="submit">Toggle Required</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </section>

    <?php endif; ?>

    <?php if ($activeTab === 'schedule'): ?>

        <section class="panel">
            <div class="panel-title" style="margin-bottom:14px;">Active Exams</div>

            <?php foreach ($activeExams as $exam): ?>
                <div class="question-card">
                    <div class="item-title"><?php echo e((string)$exam['title']); ?></div>
                    <div class="item-sub">
                        <?php echo e((string)$exam['course_title']); ?> ·
                        Ends: <?php echo e(formatDateTimeNice($exam['end_at'] ?? '')); ?>
                    </div>
                </div>
            <?php endforeach; ?>

            <?php if (!$activeExams): ?>
                <div class="empty">No active exams right now.</div>
            <?php endif; ?>
        </section>

        <section class="panel">
            <div class="panel-title" style="margin-bottom:14px;">Upcoming Exams</div>

            <?php foreach ($upcomingExams as $exam): ?>
                <div class="question-card">
                    <div class="item-title"><?php echo e((string)$exam['title']); ?></div>
                    <div class="item-sub">
                        <?php echo e((string)$exam['course_title']); ?> ·
                        Starts: <?php echo e(formatDateTimeNice($exam['start_at'] ?? '')); ?>
                    </div>
                </div>
            <?php endforeach; ?>

            <?php if (!$upcomingExams): ?>
                <div class="empty">No upcoming exams.</div>
            <?php endif; ?>
        </section>

        <section class="panel">
            <div class="panel-title" style="margin-bottom:14px;">Expired But Still Published</div>

            <?php foreach ($expiredOpenExams as $exam): ?>
                <div class="question-card">
                    <div class="question-top">
                        <div>
                            <div class="item-title"><?php echo e((string)$exam['title']); ?></div>
                            <div class="item-sub">
                                <?php echo e((string)$exam['course_title']); ?> ·
                                Ended: <?php echo e(formatDateTimeNice($exam['end_at'] ?? '')); ?>
                            </div>
                        </div>

                        <form method="post">
                            <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                            <input type="hidden" name="action" value="close_exam">
                            <input type="hidden" name="exam_id" value="<?php echo (int)$exam['id']; ?>">
                            <button class="btn btn-small btn-warning" type="submit">Close</button>
                        </form>
                    </div>
                </div>
            <?php endforeach; ?>

            <?php if (!$expiredOpenExams): ?>
                <div class="empty">No expired published exams.</div>
            <?php endif; ?>
        </section>

    <?php endif; ?>

</div>

<script>
document.querySelectorAll('.copy-code').forEach(function (el) {
    el.style.cursor = 'pointer';

    el.addEventListener('click', function () {
        navigator.clipboard.writeText(el.textContent.trim()).then(function () {
            const old = el.textContent;
            el.textContent = 'Copied!';
            setTimeout(function () {
                el.textContent = old;
            }, 900);
        });
    });
});

document.querySelectorAll('form').forEach(function(form){
    form.addEventListener('submit', function(){
        const btn = form.querySelector('button[type="submit"]');
        if(btn){
            btn.style.opacity = '.75';
            btn.style.pointerEvents = 'none';
        }
    });
});
</script>

</body>
</html>