<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| SMI Core Periods
| Full Teacher Exams System
|--------------------------------------------------------------------------
| File: public_html/student-gateway/teacher/exams.php
| Parts: 1/7
|--------------------------------------------------------------------------
| Features:
| - Teacher-scoped exams only
| - Friendly exam builder
| - AJAX quick question save without page refresh
| - Smart question-type fields
| - Default exam weights for SMI assessment system
|--------------------------------------------------------------------------
*/

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

$pdo = db();

date_default_timezone_set('Asia/Riyadh');

/*
|--------------------------------------------------------------------------
| Teacher Auth
|--------------------------------------------------------------------------
*/

if (function_exists('requireTeacher')) {
    requireTeacher();
} elseif (function_exists('requireTeacherLogin')) {
    requireTeacherLogin();
}

$teacher = null;

if (function_exists('currentTeacher')) {
    $teacher = currentTeacher($pdo);
}

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

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

$teacherId = (int)($teacher['id'] ?? $_SESSION['teacher_id'] ?? 0);

if ($teacherId <= 0) {
    header('Location: ../login.php');
    exit;
}

/*
|--------------------------------------------------------------------------
| 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('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('teacherOwnsCourse')) {
    function teacherOwnsCourse(PDO $pdo, int $teacherId, int $courseId): bool
    {
        if ($teacherId <= 0 || $courseId <= 0) {
            return false;
        }

        return safeCount(
            $pdo,
            "
            SELECT COUNT(*)
            FROM core_courses
            WHERE id = ?
              AND teacher_id = ?
            ",
            [$courseId, $teacherId]
        ) > 0;
    }
}

if (!function_exists('teacherOwnsExam')) {
    function teacherOwnsExam(PDO $pdo, int $teacherId, int $examId): bool
    {
        if ($teacherId <= 0 || $examId <= 0) {
            return false;
        }

        return safeCount(
            $pdo,
            "
            SELECT COUNT(*)
            FROM core_exams e
            INNER JOIN core_courses c ON c.id = e.course_id
            WHERE e.id = ?
              AND c.teacher_id = ?
            ",
            [$examId, $teacherId]
        ) > 0;
    }
}

if (!function_exists('getExamDefaultWeight')) {
    function getExamDefaultWeight(string $examType): float
    {
        return match ($examType) {
            'midterm' => 15.00,
            'final' => 30.00,
            'sra' => 5.00,
            'story' => 10.00,
            'placement' => 0.00,
            'quiz' => 0.00,
            'practice' => 0.00,
            'more' => 0.00,
            default => 0.00,
        };
    }
}

if (!function_exists('examTypeLabel')) {
    function examTypeLabel(string $type): string
    {
        return match ($type) {
            'midterm' => 'Midterm Exam',
            'final' => 'Final Exam',
            'sra' => 'SRA Exam',
            'story' => 'Story Exam',
            'placement' => 'Placement Test',
            'quiz' => 'Quizzes',
            'practice' => 'Practice Exam',
            'more' => 'More / Other',
            default => ucfirst(str_replace('_', ' ', $type)),
        };
    }
}

if (!function_exists('questionTypeLabel')) {
    function questionTypeLabel(string $type): string
    {
        return match ($type) {
            'multiple_choice' => 'MCQs',
            '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)),
        };
    }
}

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',
        };
    }
}

/*
|--------------------------------------------------------------------------
| 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
|--------------------------------------------------------------------------
*/

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

/*
|--------------------------------------------------------------------------
| Required Tables + Safe Auto Columns
|--------------------------------------------------------------------------
*/

$requiredTables = [
    'core_courses',
    'core_teachers',
    'core_exams',
    'core_exam_questions',
    'core_exam_options',
    'core_exam_attempts',
    'core_exam_answers',
    'students'
];

foreach ($requiredTables as $table) {
    if (!tableExists($pdo, $table)) {
        if ($table === 'core_exams') {
            safeExec($pdo, "
                CREATE TABLE IF NOT EXISTS 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,
                    exam_weight DECIMAL(6,2) DEFAULT 0.00,
                    status VARCHAR(30) DEFAULT 'draft',
                    created_by_teacher_id INT UNSIGNED NULL,
                    created_by_admin_id INT UNSIGNED NULL,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    updated_at DATETIME NULL,
                    UNIQUE KEY unique_exam_code (exam_code),
                    INDEX idx_course_id (course_id),
                    INDEX idx_teacher_id (teacher_id),
                    INDEX idx_status (status)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ");
        } elseif ($table === 'core_exam_questions') {
            safeExec($pdo, "
                CREATE TABLE IF NOT EXISTS core_exam_questions (
                    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                    exam_id INT UNSIGNED NOT 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)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ");
        } elseif ($table === 'core_exam_options') {
            safeExec($pdo, "
                CREATE TABLE IF NOT EXISTS 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
            ");
        } elseif ($table === 'core_exam_attempts') {
            safeExec($pdo, "
                CREATE TABLE IF NOT EXISTS 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,
                    UNIQUE KEY unique_exam_student_attempt (exam_id, student_id, attempt_number),
                    INDEX idx_exam_id (exam_id),
                    INDEX idx_course_id (course_id),
                    INDEX idx_student_id (student_id)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ");
        } elseif ($table === 'core_exam_answers') {
            safeExec($pdo, "
                CREATE TABLE IF NOT EXISTS 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,
                    UNIQUE KEY unique_attempt_question (attempt_id, question_id),
                    INDEX idx_attempt_id (attempt_id),
                    INDEX idx_exam_id (exam_id),
                    INDEX idx_question_id (question_id),
                    INDEX idx_student_id (student_id)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ");
        }
    }
}

/*
|--------------------------------------------------------------------------
| Safe Missing Columns
|--------------------------------------------------------------------------
*/

addColumnIfMissing($pdo, 'core_exams', 'exam_weight', "DECIMAL(6,2) DEFAULT 0.00");
addColumnIfMissing($pdo, 'core_exams', 'created_by_teacher_id', "INT UNSIGNED NULL");
addColumnIfMissing($pdo, 'core_exams', 'release_results_at', "DATETIME NULL");
addColumnIfMissing($pdo, 'core_exams', 'allow_resume', "TINYINT(1) DEFAULT 1");
addColumnIfMissing($pdo, 'core_exams', 'autosave_enabled', "TINYINT(1) DEFAULT 1");
addColumnIfMissing($pdo, 'core_exams', 'anti_cheating_enabled', "TINYINT(1) DEFAULT 1");
addColumnIfMissing($pdo, 'core_exams', 'gradebook_enabled', "TINYINT(1) DEFAULT 1");
addColumnIfMissing($pdo, 'core_exams', 'certificate_enabled', "TINYINT(1) DEFAULT 0");

addColumnIfMissing($pdo, 'core_exam_questions', 'section_name', "VARCHAR(100) NULL");
addColumnIfMissing($pdo, 'core_exam_questions', 'skill', "VARCHAR(80) NULL");
addColumnIfMissing($pdo, 'core_exam_questions', 'difficulty', "VARCHAR(50) DEFAULT 'medium'");
addColumnIfMissing($pdo, 'core_exam_questions', 'audio_file', "VARCHAR(255) NULL");
addColumnIfMissing($pdo, 'core_exam_questions', 'image_file', "VARCHAR(255) NULL");
addColumnIfMissing($pdo, 'core_exam_questions', 'allow_file_upload', "TINYINT(1) DEFAULT 0");
addColumnIfMissing($pdo, 'core_exam_questions', 'rubric_json', "LONGTEXT NULL");

/*
|--------------------------------------------------------------------------
| Page State + Lists
|--------------------------------------------------------------------------
*/

$pageTitle = 'SMI Teacher Exams System';

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

$allowedTabs = [
    'exams',
    'builder',
    'students',
    'submissions',
    'reports',
    'schedule'
];

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

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

$examTypes = [
    'midterm',
    'final',
    'sra',
    'story',
    'placement',
    'quiz',
    'practice',
    'more'
];

$coreExamTypes = [
    'midterm',
    'final',
    'sra',
    'story'
];

$extraExamTypes = [
    'placement',
    'quiz',
    'practice',
    'more'
];

$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'
];

/*
|--------------------------------------------------------------------------
| Teacher Courses Only
|--------------------------------------------------------------------------
*/

$teacherCourses = safeAll(
    $pdo,
    "
    SELECT *
    FROM core_courses
    WHERE teacher_id = ?
    ORDER BY id DESC
    ",
    [$teacherId]
);

$teacherCourseIds = array_map(
    static fn($course) => (int)$course['id'],
    $teacherCourses
);

if ($selectedExamId > 0 && !teacherOwnsExam($pdo, $teacherId, $selectedExamId)) {
    $selectedExamId = 0;
}

if ($editExamId > 0 && !teacherOwnsExam($pdo, $teacherId, $editExamId)) {
    $editExamId = 0;
}


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

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

    /*
    |--------------------------------------------------------------------------
    | AJAX Question Save will be handled in Part 3
    |--------------------------------------------------------------------------
    */

    if ($action !== 'ajax_add_question') {
        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'] ?? 'midterm'));
                $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'] ?? 100));
                $passingMarks = max(0, (float)($_POST['passing_marks'] ?? 50));
                $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 (!teacherOwnsCourse($pdo, $teacherId, $courseId)) {
                    throw new Exception('You are not allowed to create exams for this course.');
                }

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

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

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

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

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

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

                $examWeight = isset($_POST['exam_weight']) && $_POST['exam_weight'] !== ''
                    ? max(0, (float)$_POST['exam_weight'])
                    : getExamDefaultWeight($examType);

                $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'] ?? ''));
    $openNow = isset($_POST['open_now']) ? 1 : 0;


if ($openNow === 1) {
    $startAt = null;
    $endAt = null;
} else {
    $startAt = trim((string)($_POST['start_at'] ?? ''));
    $endAt   = trim((string)($_POST['end_at'] ?? ''));

    $startAt = $startAt !== '' ? str_replace('T', ' ', $startAt) . ':00' : null;
    $endAt   = $endAt !== '' ? str_replace('T', ' ', $endAt) . ':00' : null;
}
               if ($startAt !== null && $startAt !== '' && strtotime((string)$startAt) === false) {
                    throw new Exception('Invalid start time.');
                }

               if ($endAt !== '' && strtotime($endAt) === false) {
                    throw new Exception('Invalid end time.');
                }

                if (
    $endAt !== null &&
    $startAt !== null &&
    $endAt !== '' &&
    $startAt !== ''
) {
                    $startTime = strtotime($startAt);
                    $endTime = strtotime($endAt);

                    if ($startTime && $endTime && $endTime <= $startTime) {
                        throw new Exception('End time must be after start time.');
                    }
                }

                $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,
                        exam_weight,
                        status,
                        created_by_teacher_id,
                        created_at,
                        updated_at
                    ) VALUES (
                        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW()
                    )
                ");

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

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

                setSuccess('Exam created successfully.');

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

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

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

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

                if (!teacherOwnsExam($pdo, $teacherId, $examId)) {
                    throw new Exception('You are not allowed to update this exam.');
                }

                $courseId = (int)($_POST['course_id'] ?? 0);
                $title = trim((string)($_POST['title'] ?? ''));
                $description = trim((string)($_POST['description'] ?? ''));
                $examType = trim((string)($_POST['exam_type'] ?? 'midterm'));
                $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'] ?? 100));
                $passingMarks = max(0, (float)($_POST['passing_marks'] ?? 50));
                $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 (!teacherOwnsCourse($pdo, $teacherId, $courseId)) {
                    throw new Exception('You are not allowed to assign this exam to this course.');
                }

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

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

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

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

                $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 is already used by another exam.');
                }

                $examWeight = isset($_POST['exam_weight']) && $_POST['exam_weight'] !== ''
                    ? max(0, (float)$_POST['exam_weight'])
                    : getExamDefaultWeight($examType);

                $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'] ?? ''));
                
  $openNow = isset($_POST['open_now']) ? 1 : 0;

if ($openNow === 1) {
    $startAt = null;
    $endAt = null;
} else {
    $startAt = trim((string)($_POST['start_at'] ?? ''));
    $endAt   = trim((string)($_POST['end_at'] ?? ''));

    $startAt = $startAt !== '' ? str_replace('T', ' ', $startAt) . ':00' : null;
    $endAt   = $endAt !== '' ? str_replace('T', ' ', $endAt) . ':00' : null;
}

          if ($startAt !== null && $startAt !== '' && strtotime((string)$startAt) === false) {
                    throw new Exception('Invalid start time.');
                }

if ($endAt !== null && $endAt !== '' && strtotime((string)$endAt) === false) {
                    throw new Exception('Invalid end time.');
                }

             if (
    $endAt !== null &&
    $startAt !== null &&
    $endAt !== '' &&
    $startAt !== ''
) {
                    $startTime = strtotime($startAt);
                    $endTime = strtotime($endAt);

                    if ($startTime && $endTime && $endTime <= $startTime) {
                        throw new Exception('End time must be after start time.');
                    }
                }

                $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 = ?,
                        exam_weight = ?,
                        status = ?,
                        updated_at = NOW()
                    WHERE id = ?
                ");

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

                setSuccess('Exam updated successfully.');

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

            /*
            |--------------------------------------------------------------------------
            | Publish / Close / Archive / Restore
            |--------------------------------------------------------------------------
            */

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

                if (!teacherOwnsExam($pdo, $teacherId, $examId)) {
                    throw new Exception('You are not allowed to change this exam.');
                }

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

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

                if ($action === 'publish_exam') {
                    $questionsCount = safeCount(
                        $pdo,
                        "SELECT COUNT(*) FROM core_exam_questions WHERE exam_id = ?",
                        [$examId]
                    );

                    if ($questionsCount <= 0) {
                        throw new Exception('You cannot publish an exam without questions.');
                    }
                }

                $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.');
                }

                if (!teacherOwnsExam($pdo, $teacherId, $examId)) {
                    throw new Exception('You are not allowed to update this code.');
                }

                $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: ' . $newCode);

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

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

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

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

                if (!teacherOwnsExam($pdo, $teacherId, $examId)) {
                    throw new Exception('You are not allowed to duplicate this 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,
                        exam_weight,
                        status,
                        created_by_teacher_id,
                        created_at,
                        updated_at
                    ) VALUES (
                        ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, 'draft', ?, NOW(), NOW()
                    )
                ");

                $stmt->execute([
                    (int)$exam['course_id'],
                    $teacherId,
                    'Copy of ' . (string)$exam['title'],
                    (string)($exam['description'] ?? ''),
                    (string)($exam['exam_type'] ?? 'more'),
                    $newCode,
                    (int)($exam['duration_minutes'] ?? 60),
                    (float)($exam['total_marks'] ?? 100),
                    (float)($exam['passing_marks'] ?? 50),
                    (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),
                    (float)($exam['exam_weight'] ?? 0),
                    $teacherId
                ]);

                $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,
                            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,
                        $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=builder&exam_id=' . $newExamId);
                exit;
            }

            /*
            |--------------------------------------------------------------------------
            | Delete Draft Exam Only
            |--------------------------------------------------------------------------
            */

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

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

                if (!teacherOwnsExam($pdo, $teacherId, $examId)) {
                    throw new Exception('You are not allowed to delete this exam.');
                }

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

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

                if ((string)($exam['status'] ?? '') !== 'draft') {
                    throw new Exception('Only draft exams can be deleted. Archive it instead.');
                }

                $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.');
                }

                $pdo->beginTransaction();

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

                foreach ($questions as $question) {
                    $pdo->prepare("DELETE FROM core_exam_options WHERE question_id = ?")
                        ->execute([(int)$question['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('Draft 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;
        }
    }
}

/*
|--------------------------------------------------------------------------
| AJAX Quick Add Question
|--------------------------------------------------------------------------
| No page refresh.
| Teacher writes question -> instant save.
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($action ?? '') === 'ajax_add_question') {

    header('Content-Type: application/json; charset=utf-8');

    try {
        verifyCsrf();

        $examId = (int)($_POST['exam_id'] ?? 0);

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

        if (!teacherOwnsExam($pdo, $teacherId, $examId)) {
            throw new Exception('Access denied.');
        }

        $questionType = trim((string)($_POST['question_type'] ?? 'multiple_choice'));
        $questionText = trim((string)($_POST['question_text'] ?? ''));
        $marks = max(0, (float)($_POST['marks'] ?? 1));
        $sectionName = trim((string)($_POST['section_name'] ?? ''));
        $skill = trim((string)($_POST['skill'] ?? 'general'));
        $difficulty = trim((string)($_POST['difficulty'] ?? 'medium'));
        $correctAnswer = trim((string)($_POST['correct_answer'] ?? ''));
        $explanation = trim((string)($_POST['explanation'] ?? ''));

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

        $difficultyLevels = ['easy', 'medium', 'hard', 'elite'];

        if (!in_array($difficulty, $difficultyLevels, true)) {
            $difficulty = 'medium';
        }

        /*
        |--------------------------------------------------------------------------
        | Auto Sort Order
        |--------------------------------------------------------------------------
        */

        $lastOrder = safeOne(
            $pdo,
            "
            SELECT MAX(sort_order) AS max_order
            FROM core_exam_questions
            WHERE exam_id = ?
            ",
            [$examId]
        );

        $sortOrder = (int)($lastOrder['max_order'] ?? 0) + 1;

        /*
        |--------------------------------------------------------------------------
        | Smart Correct Answers
        |--------------------------------------------------------------------------
        */

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

        if ($questionType === 'multiple_choice') {
            $correctOptionIndex = (int)($_POST['correct_option'] ?? 0);

            $options = $_POST['options'] ?? [];

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

            $options = array_values(array_filter(array_map(
                static fn($v) => trim((string)$v),
                $options
            )));

            if (count($options) < 2) {
                throw new Exception('MCQ question requires at least 2 options.');
            }

            if (!isset($options[$correctOptionIndex])) {
                $correctOptionIndex = 0;
            }

            $correctAnswer = (string)$options[$correctOptionIndex];
        }

        /*
        |--------------------------------------------------------------------------
        | Rubric JSON
        |--------------------------------------------------------------------------
        */

        $rubric = [
            'grammar' => (float)($_POST['rubric_grammar'] ?? 0),
            'vocabulary' => (float)($_POST['rubric_vocabulary'] ?? 0),
            'coherence' => (float)($_POST['rubric_coherence'] ?? 0),
            'pronunciation' => (float)($_POST['rubric_pronunciation'] ?? 0),
            'task_response' => (float)($_POST['rubric_task_response'] ?? 0),
        ];

        $rubricJson = json_encode($rubric, JSON_UNESCAPED_UNICODE);

        $allowFileUpload = !empty($_POST['allow_file_upload']) ? 1 : 0;
        $isRequired = !empty($_POST['is_required']) ? 1 : 0;

        /*
        |--------------------------------------------------------------------------
        | Insert Question
        |--------------------------------------------------------------------------
        */

        $stmt = $pdo->prepare("
            INSERT INTO core_exam_questions (
                exam_id,
                section_name,
                skill,
                question_text,
                question_type,
                marks,
                sort_order,
                correct_answer,
                explanation,
                difficulty,
                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,
            $allowFileUpload,
            $rubricJson,
            $isRequired
        ]);

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

        /*
        |--------------------------------------------------------------------------
        | Insert MCQ Options
        |--------------------------------------------------------------------------
        */

        if ($questionType === 'multiple_choice') {
            $correctOptionIndex = (int)($_POST['correct_option'] ?? 0);

            foreach ($options as $index => $optionText) {

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

                $stmt->execute([
                    $questionId,
                    $optionText,
                    $index === $correctOptionIndex ? 1 : 0,
                    $index
                ]);
            }
        }

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

        if (!empty($_POST['save_to_bank'])) {

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

            if ($exam) {

                safeExec($pdo, "
                    CREATE TABLE IF NOT EXISTS 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,
                        rubric_json LONGTEXT NULL,
                        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                        updated_at DATETIME NULL,
                        INDEX idx_course_id (course_id),
                        INDEX idx_teacher_id (teacher_id)
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
                ");

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

                $stmt->execute([
                    (int)$exam['course_id'],
                    $teacherId,
                    $sectionName !== '' ? $sectionName : null,
                    $skill,
                    $questionText,
                    $questionType,
                    $correctAnswer !== '' ? $correctAnswer : null,
                    $explanation !== '' ? $explanation : null,
                    $marks,
                    $difficulty,
                    $rubricJson
                ]);
            }
        }

        /*
        |--------------------------------------------------------------------------
        | Load Saved Question HTML
        |--------------------------------------------------------------------------
        */

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

        $savedOptions = [];

        if ($questionType === 'multiple_choice') {
            $savedOptions = safeAll(
                $pdo,
                "
                SELECT *
                FROM core_exam_options
                WHERE question_id = ?
                ORDER BY sort_order ASC, id ASC
                ",
                [$questionId]
            );
        }

        ob_start();
        ?>

        <div class="question-card" data-question-id="<?php echo (int)$questionId; ?>">

            <div class="question-top">

                <div>
                    <div class="item-sub">
                        <?php echo e(questionTypeLabel($questionType)); ?>
                        ·
                        <?php echo e((string)$marks); ?> marks
                        ·
                        <?php echo e(ucfirst($skill)); ?>
                    </div>

                    <div class="question-text">
                        <?php echo nl2br(e($questionText)); ?>
                    </div>
                </div>

                <div class="actions">

                    <button
                        type="button"
                        class="btn btn-small btn-light edit-question-btn"
                        data-question-id="<?php echo (int)$questionId; ?>"
                    >
                        Edit
                    </button>

                    <button
                        type="button"
                        class="btn btn-small btn-danger delete-question-btn"
                        data-question-id="<?php echo (int)$questionId; ?>"
                    >
                        Delete
                    </button>

                </div>

            </div>

            <?php if ($savedOptions): ?>
                <div class="option-list">

                    <?php foreach ($savedOptions 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 ($correctAnswer !== '' && $questionType !== 'multiple_choice'): ?>
                <div class="item-sub" style="margin-top:10px;">
                    Correct Answer:
                    <strong><?php echo e($correctAnswer); ?></strong>
                </div>
            <?php endif; ?>

        </div>

        <?php
        $html = ob_get_clean();

        echo json_encode([
            'success' => true,
            'message' => 'Question added successfully.',
            'question_id' => $questionId,
            'html' => $html
        ], JSON_UNESCAPED_UNICODE);

    } catch (Throwable $e) {

        echo json_encode([
            'success' => false,
            'message' => $e->getMessage()
        ], JSON_UNESCAPED_UNICODE);
    }

    exit;
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($action ?? '') === 'delete_question') {

    try {
        verifyCsrf();

        $questionId = (int)($_POST['question_id'] ?? 0);

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

        $question = safeOne(
            $pdo,
            "
            SELECT q.*, e.teacher_id
            FROM core_exam_questions q
            INNER JOIN core_exams e ON e.id = q.exam_id
            WHERE q.id = ?
            LIMIT 1
            ",
            [$questionId]
        );

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

        if ((int)($question['teacher_id'] ?? 0) !== $teacherId) {
            throw new Exception('Access denied.');
        }

        $pdo->beginTransaction();

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

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

        $pdo->commit();

        setSuccess('Question deleted successfully.');

    } catch (Throwable $e) {

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

        setError($e->getMessage());
    }

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

/*
|--------------------------------------------------------------------------
| Move Question Up / Down
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($action ?? '') === 'move_question') {

    try {
        verifyCsrf();

        $questionId = (int)($_POST['question_id'] ?? 0);
        $direction = trim((string)($_POST['direction'] ?? 'up'));

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

        $question = safeOne(
            $pdo,
            "
            SELECT q.*, e.teacher_id
            FROM core_exam_questions q
            INNER JOIN core_exams e ON e.id = q.exam_id
            WHERE q.id = ?
            LIMIT 1
            ",
            [$questionId]
        );

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

        if ((int)($question['teacher_id'] ?? 0) !== $teacherId) {
            throw new Exception('Access denied.');
        }

        $currentOrder = (int)($question['sort_order'] ?? 0);
        $examId = (int)$question['exam_id'];

        if ($direction === 'up') {

            $swapQuestion = safeOne(
                $pdo,
                "
                SELECT *
                FROM core_exam_questions
                WHERE exam_id = ?
                  AND sort_order < ?
                ORDER BY sort_order DESC
                LIMIT 1
                ",
                [$examId, $currentOrder]
            );

        } else {

            $swapQuestion = safeOne(
                $pdo,
                "
                SELECT *
                FROM core_exam_questions
                WHERE exam_id = ?
                  AND sort_order > ?
                ORDER BY sort_order ASC
                LIMIT 1
                ",
                [$examId, $currentOrder]
            );
        }

        if ($swapQuestion) {

            $pdo->beginTransaction();

            $pdo->prepare("
                UPDATE core_exam_questions
                SET sort_order = ?
                WHERE id = ?
            ")->execute([
                (int)$swapQuestion['sort_order'],
                $questionId
            ]);

            $pdo->prepare("
                UPDATE core_exam_questions
                SET sort_order = ?
                WHERE id = ?
            ")->execute([
                $currentOrder,
                (int)$swapQuestion['id']
            ]);

            $pdo->commit();
        }

        setSuccess('Question order updated.');

    } catch (Throwable $e) {

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

        setError($e->getMessage());
    }

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



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

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

if (!function_exists('teacherAutoGradeAnswer')) {
    function teacherAutoGradeAnswer(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 > 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 = normalizeTeacherExamAnswer($answerText);
            $rightAnswer = normalizeTeacherExamAnswer($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;
            }
        } else {
            $needsManual = true;
            $score = 0.00;
            $isCorrect = null;
        }

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

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

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

        if (!$attempt) {
            return;
        }

        if ((int)($attempt['teacher_id'] ?? 0) !== $teacherId) {
            return;
        }

        if ((int)($attempt['gradebook_enabled'] ?? 0) !== 1) {
            return;
        }

        $courseId = (int)$attempt['course_id'];
        $studentId = (int)$attempt['student_id'];
        $examId = (int)$attempt['exam_id'];
        $weight = (float)($attempt['exam_weight'] ?? 0);

        $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', 'weight')) {
                $columns[] = 'weight';
                $values[] = $weight;
            }

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

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

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

                $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) {
                try {
                    $pdo->prepare("
                        UPDATE core_grades
                        SET score = ?, updated_at = NOW()
                        WHERE id = ?
                    ")->execute([
                        (float)$attempt['percentage'],
                        (int)$existing['id']
                    ]);
                } catch (Throwable $e) {
                    return;
                }
            } 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;
                }
            }
        }
    }
}

if (!function_exists('teacherRecalculateAttemptScore')) {
    function teacherRecalculateAttemptScore(PDO $pdo, int $attemptId, int $teacherId): void
    {
        $attempt = safeOne(
            $pdo,
            "
            SELECT 
                a.*,
                c.teacher_id
            FROM core_exam_attempts a
            INNER JOIN core_courses c ON c.id = a.course_id
            WHERE a.id = ?
            LIMIT 1
            ",
            [$attemptId]
        );

        if (!$attempt) {
            return;
        }

        if ((int)($attempt['teacher_id'] ?? 0) !== $teacherId) {
            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
        ]);

        teacherSyncAttemptToGradebook($pdo, $attemptId, $teacherId);
    }
}

/*
|--------------------------------------------------------------------------
| POST Actions - Teacher Grading
|--------------------------------------------------------------------------
*/

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

    if (in_array($action, ['manual_grade_answer', 'bulk_grade_attempt', 'recalculate_attempt', 'reopen_attempt', 'cancel_attempt'], true)) {

        try {
            verifyCsrf();

            /*
            |--------------------------------------------------------------------------
            | Manual Grade Single 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,
                        c.teacher_id
                    FROM core_exam_answers a
                    INNER JOIN core_exam_questions q ON q.id = a.question_id
                    INNER JOIN core_exam_attempts at ON at.id = a.attempt_id
                    INNER JOIN core_courses c ON c.id = at.course_id
                    WHERE a.id = ?
                    LIMIT 1
                    ",
                    [$answerId]
                );

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

                if ((int)($answer['teacher_id'] ?? 0) !== $teacherId) {
                    throw new Exception('Access denied.');
                }

                $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_teacher_id = ?,
                        graded_at = NOW(),
                        updated_at = NOW()
                    WHERE id = ?
                ");

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

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

                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 
                        a.*,
                        c.teacher_id
                    FROM core_exam_attempts a
                    INNER JOIN core_courses c ON c.id = a.course_id
                    WHERE a.id = ?
                    LIMIT 1
                    ",
                    [$attemptId]
                );

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

                if ((int)($attempt['teacher_id'] ?? 0) !== $teacherId) {
                    throw new Exception('Access denied.');
                }

                $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_teacher_id = ?,
                            graded_at = NOW(),
                            updated_at = NOW()
                        WHERE id = ?
                    ");

                    $stmt->execute([
                        $scoreAwarded,
                        $isCorrect,
                        $feedback !== '' ? $feedback : null,
                        $teacherId,
                        $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
                    ]);
                }

                teacherRecalculateAttemptScore($pdo, $attemptId, $teacherId);

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

                teacherRecalculateAttemptScore($pdo, $attemptId, $teacherId);

                setSuccess('Attempt score recalculated.');

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

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

            if ($action === 'reopen_attempt') {
                $attemptId = (int)($_POST['attempt_id'] ?? 0);
                $extraMinutes = max(5, (int)($_POST['extra_minutes'] ?? 30));

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

                $attempt = safeOne(
                    $pdo,
                    "
                    SELECT 
                        a.*,
                        c.teacher_id
                    FROM core_exam_attempts a
                    INNER JOIN core_courses c ON c.id = a.course_id
                    WHERE a.id = ?
                    LIMIT 1
                    ",
                    [$attemptId]
                );

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

                if ((int)($attempt['teacher_id'] ?? 0) !== $teacherId) {
                    throw new Exception('Access denied.');
                }

                $expiresAt = date('Y-m-d H:i:s', strtotime('+' . $extraMinutes . ' 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;
            }

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

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

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

                $attempt = safeOne(
                    $pdo,
                    "
                    SELECT 
                        a.*,
                        c.teacher_id
                    FROM core_exam_attempts a
                    INNER JOIN core_courses c ON c.id = a.course_id
                    WHERE a.id = ?
                    LIMIT 1
                    ",
                    [$attemptId]
                );

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

                if ((int)($attempt['teacher_id'] ?? 0) !== $teacherId) {
                    throw new Exception('Access denied.');
                }

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

                setSuccess('Attempt cancelled.');

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

        } catch (Throwable $e) {
            setError($e->getMessage());

            $redirectAttempt = $selectedAttemptId > 0 ? '&attempt_id=' . $selectedAttemptId : '';
            header('Location: exams.php?tab=submissions' . $redirectAttempt);
            exit;
        }
    }
}





/*
|--------------------------------------------------------------------------
| Load Data
|--------------------------------------------------------------------------
*/

$selectedExam = null;
$selectedAttempt = null;
$attemptAnswers = [];
$examQuestions = [];
$questionOptionsMap = [];
$teacherStudentsResults = [];

if ($selectedExamId > 0) {

    $selectedExam = safeOne(
        $pdo,
        "
        SELECT 
            e.*,
            c.title AS course_title
        FROM core_exams e
        INNER JOIN core_courses c ON c.id = e.course_id
        WHERE e.id = ?
          AND c.teacher_id = ?
        LIMIT 1
        ",
        [
            $selectedExamId,
            $teacherId
        ]
    );

    if ($selectedExam) {

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

        foreach ($examQuestions as $question) {

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

        /*
        |--------------------------------------------------------------------------
        | Students Results
        |--------------------------------------------------------------------------
        */

        $teacherStudentsResults = safeAll(
            $pdo,
            "
            SELECT 
                a.*,
                s.full_name,
                s.student_code,
                s.email,
                (
                    SELECT COUNT(*)
                    FROM core_exam_answers ans
                    WHERE ans.attempt_id = a.id
                ) AS answers_count
            FROM core_exam_attempts a
            INNER JOIN students s ON s.id = a.student_id
            WHERE a.exam_id = ?
            ORDER BY a.percentage DESC, a.id DESC
            ",
            [$selectedExamId]
        );
    }
}

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

if ($selectedAttemptId > 0) {

    $selectedAttempt = safeOne(
        $pdo,
        "
        SELECT 
            a.*,
            s.full_name AS student_name,
            s.student_code,
            s.email,
            e.title AS exam_title,
            e.total_marks,
            e.passing_marks,
            c.title AS course_title,
            c.teacher_id
        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
        INNER JOIN core_courses c ON c.id = a.course_id
        WHERE a.id = ?
          AND c.teacher_id = ?
        LIMIT 1
        ",
        [
            $selectedAttemptId,
            $teacherId
        ]
    );

    if ($selectedAttempt) {

        $attemptAnswers = safeAll(
            $pdo,
            "
            SELECT 
                ans.*,
                q.question_text,
                q.question_type,
                q.correct_answer,
                q.marks,
                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]
        );
    }
}

/*
|--------------------------------------------------------------------------
| Teacher Exams
|--------------------------------------------------------------------------
*/

$teacherExams = safeAll(
    $pdo,
    "
    SELECT 
        e.*,
        c.title AS course_title,
        (
            SELECT COUNT(*)
            FROM core_exam_questions q
            WHERE q.exam_id = e.id
        ) AS questions_count,
        (
            SELECT COUNT(*)
            FROM core_exam_attempts a
            WHERE a.exam_id = e.id
        ) AS attempts_count,
        (
            SELECT ROUND(AVG(a.percentage), 2)
            FROM core_exam_attempts a
            WHERE a.exam_id = e.id
              AND a.status IN ('submitted','graded')
        ) AS average_score
    FROM core_exams e
    INNER JOIN core_courses c ON c.id = e.course_id
    WHERE c.teacher_id = ?
    ORDER BY e.id DESC
    ",
    [$teacherId]
);

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

$totalExams = count($teacherExams);

$publishedExams = 0;
$draftExams = 0;
$totalAttempts = 0;
$averageScores = [];

foreach ($teacherExams as $exam) {

    if ((string)($exam['status'] ?? '') === 'published') {
        $publishedExams++;
    }

    if ((string)($exam['status'] ?? '') === 'draft') {
        $draftExams++;
    }

    $totalAttempts += (int)($exam['attempts_count'] ?? 0);

    if (!empty($exam['average_score'])) {
        $averageScores[] = (float)$exam['average_score'];
    }
}

$overallAverage = count($averageScores) > 0
    ? round(array_sum($averageScores) / count($averageScores), 2)
    : 0;

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

$reportTopStudents = safeAll(
    $pdo,
    "
    SELECT 
        a.percentage,
        a.total_score,
        a.result_status,
        s.full_name,
        s.student_code,
        e.title AS exam_title
    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
    INNER JOIN core_courses c ON c.id = a.course_id
    WHERE c.teacher_id = ?
      AND a.status IN ('submitted','graded')
    ORDER BY a.percentage DESC
    LIMIT 10
    ",
    [$teacherId]
);

$reportWeakQuestions = safeAll(
    $pdo,
    "
    SELECT 
        q.id,
        q.question_text,
        q.question_type,
        q.marks,
        COUNT(ans.id) AS answers_count,
        ROUND(AVG(ans.score_awarded),2) AS avg_score
    FROM core_exam_questions q
    LEFT JOIN core_exam_answers ans 
        ON ans.question_id = q.id
    INNER JOIN core_exams e 
        ON e.id = q.exam_id
    INNER JOIN core_courses c 
        ON c.id = e.course_id
    WHERE c.teacher_id = ?
    GROUP BY q.id
    ORDER BY avg_score ASC
    LIMIT 10
    ",
    [$teacherId]
);

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

$activeExams = safeAll(
    $pdo,
    "
    SELECT 
        e.*,
        c.title AS course_title
    FROM core_exams e
    INNER JOIN core_courses c ON c.id = e.course_id
    WHERE c.teacher_id = ?
      AND 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.start_at ASC
    ",
    [$teacherId]
);

$upcomingExams = safeAll(
    $pdo,
    "
    SELECT 
        e.*,
        c.title AS course_title
    FROM core_exams e
    INNER JOIN core_courses c ON c.id = e.course_id
    WHERE c.teacher_id = ?
      AND e.start_at IS NOT NULL
      AND e.start_at > NOW()
    ORDER BY e.start_at ASC
    ",
    [$teacherId]
);

$expiredExams = safeAll(
    $pdo,
    "
    SELECT 
        e.*,
        c.title AS course_title
    FROM core_exams e
    INNER JOIN core_courses c ON c.id = e.course_id
    WHERE c.teacher_id = ?
      AND e.end_at IS NOT NULL
      AND e.end_at < NOW()
      AND e.status = 'published'
    ORDER BY e.end_at DESC
    ",
    [$teacherId]
);

/*
|--------------------------------------------------------------------------
| HTML
|--------------------------------------------------------------------------
*/
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

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

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

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

<style>

:root{
    --primary:#2563eb;
    --primary-dark:#1d4ed8;
    --purple:#7c3aed;
    --green:#059669;
    --orange:#ea580c;
    --red:#dc2626;
    --dark:#0f172a;
    --gray:#64748b;
    --light:#f8fafc;
    --border:#e2e8f0;
    --white:#ffffff;
}

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

body{
    background:#f5f7fb;
    font-family:'Inter',sans-serif;
    color:#0f172a;
}

a{
    text-decoration:none;
}

button,
input,
textarea,
select{
    font-family:inherit;
}

.app-shell{
    max-width:1700px;
    margin:auto;
    padding:24px;
}

.hero{
    background:linear-gradient(135deg,#2563eb 0%,#7c3aed 100%);
    color:white;
    padding:28px;
    border-radius:30px;
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:20px;
    margin-bottom:24px;
    box-shadow:0 20px 50px rgba(37,99,235,.25);
}

.hero h1{
    font-size:32px;
    font-weight:800;
    margin-bottom:8px;
}

.hero p{
    opacity:.92;
    line-height:1.7;
}

.hero-right{
    display:flex;
    gap:14px;
    flex-wrap:wrap;
}

.hero-box{
    background:rgba(255,255,255,.14);
    backdrop-filter:blur(10px);
    padding:18px 20px;
    border-radius:22px;
    min-width:150px;
}

.hero-box span{
    display:block;
    font-size:13px;
    opacity:.85;
    margin-bottom:6px;
}

.hero-box strong{
    font-size:26px;
    font-weight:800;
}

.tabs{
    display:flex;
    gap:12px;
    overflow:auto;
    margin-bottom:24px;
    padding-bottom:4px;
}

.tab{
    background:white;
    border:1px solid var(--border);
    color:#0f172a;
    padding:14px 18px;
    border-radius:18px;
    font-weight:700;
    white-space:nowrap;
    transition:.2s;
}

.tab:hover{
    transform:translateY(-2px);
}

.tab.active{
    background:linear-gradient(135deg,#2563eb,#7c3aed);
    color:white;
    border-color:transparent;
    box-shadow:0 12px 30px rgba(37,99,235,.25);
}

.panel{
    background:white;
    border-radius:28px;
    padding:24px;
    margin-bottom:24px;
    border:1px solid #edf2f7;
    box-shadow:0 10px 35px rgba(15,23,42,.05);
}

.panel-head{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:14px;
    margin-bottom:18px;
}

.panel-title{
    font-size:24px;
    font-weight:800;
}

.panel-subtitle{
    color:#64748b;
    margin-top:5px;
    line-height:1.6;
}

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

.grid-2{
    grid-template-columns:repeat(auto-fit,minmax(260px,1fr));
}

.grid-3{
    grid-template-columns:repeat(auto-fit,minmax(240px,1fr));
}

.grid-4{
    grid-template-columns:repeat(auto-fit,minmax(210px,1fr));
}

.grid-5{
    grid-template-columns:repeat(auto-fit,minmax(180px,1fr));
}

.input,
.select,
.textarea{
    width:100%;
    border:1px solid var(--border);
    border-radius:18px;
    padding:15px 16px;
    background:white;
    font-size:15px;
    outline:none;
    transition:.2s;
}

.input:focus,
.select:focus,
.textarea:focus{
    border-color:#2563eb;
    box-shadow:0 0 0 4px rgba(37,99,235,.12);
}

.textarea{
    min-height:120px;
    resize:vertical;
}

.label{
    display:block;
    margin-bottom:8px;
    font-weight:700;
    color:#334155;
}

.btn{
    border:none;
    outline:none;
    cursor:pointer;
    border-radius:18px;
    padding:14px 18px;
    font-weight:700;
    transition:.2s;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
}

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

.btn-primary{
    background:linear-gradient(135deg,#2563eb,#7c3aed);
    color:white;
}

.btn-light{
    background:#eef2ff;
    color:#1e40af;
}

.btn-danger{
    background:#fee2e2;
    color:#b91c1c;
}

.btn-warning{
    background:#ffedd5;
    color:#c2410c;
}

.btn-success{
    background:#dcfce7;
    color:#166534;
}

.btn-dark{
    background:#0f172a;
    color:white;
}

.btn-small{
    padding:10px 14px;
    border-radius:14px;
    font-size:13px;
}

.badge{
    padding:7px 12px;
    border-radius:999px;
    font-size:12px;
    font-weight:700;
    display:inline-flex;
    align-items:center;
    gap:5px;
}

.badge-green{
    background:#dcfce7;
    color:#166534;
}

.badge-red{
    background:#fee2e2;
    color:#b91c1c;
}

.badge-blue{
    background:#dbeafe;
    color:#1d4ed8;
}

.badge-orange{
    background:#ffedd5;
    color:#c2410c;
}

.badge-gray{
    background:#f1f5f9;
    color:#475569;
}

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

.table-wrap{
    overflow:auto;
}

.table{
    width:100%;
    border-collapse:collapse;
}

.table th{
    background:#f8fafc;
    color:#334155;
    text-align:left;
    padding:16px;
    font-size:13px;
    font-weight:800;
    border-bottom:1px solid var(--border);
}

.table td{
    padding:16px;
    border-bottom:1px solid var(--border);
    vertical-align:top;
}

.item-title{
    font-weight:800;
    margin-bottom:5px;
}

.item-sub{
    color:#64748b;
    font-size:13px;
}

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

.kpi-row{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(200px,1fr));
    gap:18px;
}

.kpi{
    background:white;
    border-radius:24px;
    padding:22px;
    border:1px solid #edf2f7;
    box-shadow:0 10px 30px rgba(15,23,42,.04);
}

.kpi span{
    display:block;
    color:#64748b;
    margin-bottom:10px;
    font-size:14px;
}

.kpi strong{
    font-size:34px;
    font-weight:800;
}

.question-card{
    border:1px solid var(--border);
    border-radius:22px;
    padding:18px;
    margin-bottom:16px;
    background:#fff;
}

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

.question-text{
    font-size:16px;
    font-weight:700;
    line-height:1.7;
    margin-top:8px;
}

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

.option-item{
    padding:14px;
    border-radius:16px;
    background:#f8fafc;
    border:1px solid #e2e8f0;
}

.option-item.correct{
    background:#dcfce7;
    border-color:#86efac;
}

.answer-box{
    border:1px solid var(--border);
    border-radius:24px;
    padding:20px;
    margin-bottom:18px;
}

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

.empty{
    text-align:center;
    padding:60px 20px;
    color:#64748b;
}

.notice{
    padding:16px 18px;
    border-radius:18px;
    margin-bottom:18px;
    font-weight:600;
}

.notice-success{
    background:#dcfce7;
    color:#166534;
}

.notice-error{
    background:#fee2e2;
    color:#b91c1c;
}

.more-options{
    margin-top:16px;
    border-top:1px dashed #cbd5e1;
    padding-top:18px;
}

.toggle-more{
    cursor:pointer;
    color:#2563eb;
    font-weight:700;
    margin-top:10px;
    display:inline-block;
}

.hidden{
    display:none;
}

.smart-question-fields{
    margin-top:18px;
}

@media (max-width:768px){

    .hero{
        flex-direction:column;
        align-items:flex-start;
    }

    .question-top{
        flex-direction:column;
    }

    .actions{
        width:100%;
    }

    .btn{
        width:100%;
    }
}

</style>
</head>
<body>

<div class="app-shell">

    <section class="hero">

        <div>
            <h1>Teacher Exams System</h1>

            <p>
                Create Midterm, Final, SRA, Story, Placement, Quiz,
                and Practice Exams easily with a smart builder,
                instant question save, grading, analytics,
                and student performance tracking.
            </p>
        </div>

        <div class="hero-right">

            <div class="hero-box">
                <span>Total Exams</span>
                <strong><?php echo e((string)$totalExams); ?></strong>
            </div>

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

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

            <div class="hero-box">
                <span>Average</span>
                <strong><?php echo e((string)$overallAverage); ?>%</strong>
            </div>

        </div>

    </section>

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

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

    <nav class="tabs">

        <a href="exams.php?tab=exams"
           class="tab <?php echo $activeTab === 'exams' ? 'active' : ''; ?>">
            Exams
        </a>

        <a href="exams.php?tab=builder<?php echo $selectedExamId > 0 ? '&exam_id=' . $selectedExamId : ''; ?>"
           class="tab <?php echo $activeTab === 'builder' ? 'active' : ''; ?>">
            Exam Builder
        </a>

        <a href="exams.php?tab=students<?php echo $selectedExamId > 0 ? '&exam_id=' . $selectedExamId : ''; ?>"
           class="tab <?php echo $activeTab === 'students' ? 'active' : ''; ?>">
            Students Results
        </a>

        <a href="exams.php?tab=submissions"
           class="tab <?php echo $activeTab === 'submissions' ? 'active' : ''; ?>">
            Submissions
        </a>

        <a href="exams.php?tab=reports"
           class="tab <?php echo $activeTab === 'reports' ? 'active' : ''; ?>">
            Reports
        </a>

        <a href="exams.php?tab=schedule"
           class="tab <?php echo $activeTab === 'schedule' ? 'active' : ''; ?>">
            Schedule
        </a>

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

        <?php
        $editExam = null;

        if ($editExamId > 0) {
            $editExam = safeOne(
                $pdo,
                "
                SELECT e.*
                FROM core_exams e
                INNER JOIN core_courses c ON c.id = e.course_id
                WHERE e.id = ?
                  AND c.teacher_id = ?
                LIMIT 1
                ",
                [
                    $editExamId,
                    $teacherId
                ]
            );
        }
        ?>

        <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">
                        Choose the exam type, course, timing, marks, and publish when ready.
                        Main institute exams have default weights: Midterm 15%, Final 30%, SRA 5%, Story 10%.
                    </div>
                </div>

            </div>

            <?php if (!$teacherCourses): ?>

                <div class="empty">
                    No courses assigned to you yet. Please contact admin.
                </div>

            <?php else: ?>

                <form method="post" class="grid" id="examForm">

                    <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-3">

                        <div>
                            <label class="label">Course</label>
                            <select name="course_id" class="select" required>
                                <option value="">Choose course</option>

                                <?php foreach ($teacherCourses 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')); ?>
                                    </option>
                                <?php endforeach; ?>

                            </select>
                        </div>

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

                        <div>
                            <label class="label">Exam Weight %</label>
                            <input
                                type="number"
                                step="0.01"
                                min="0"
                                name="exam_weight"
                                id="examWeightInput"
                                class="input"
                                value="<?php echo e((string)($editExam['exam_weight'] ?? getExamDefaultWeight('midterm'))); ?>"
                            >
                        </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: Midterm Exam - Grammar"
                            >
                        </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 / Instructions</label>
                        <textarea
                            name="description"
                            class="textarea"
                            placeholder="Write simple instructions for students..."
                        ><?php echo e((string)($editExam['description'] ?? '')); ?></textarea>
                    </div>
<div class="grid grid-2">
    <label class="badge badge-green">
        <input type="checkbox" name="open_now" value="1"
            <?php echo empty($editExam['start_at']) && empty($editExam['end_at']) ? 'checked' : ''; ?>>
        Open Now / No Schedule
    </label>

    <div class="item-sub" style="align-self:center;">
        If checked, the exam will be open immediately after publishing.
    </div>
</div>
                    <div class="grid grid-4">

                        <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"
                                min="1"
                                name="duration_minutes"
                                class="input"
                                value="<?php echo e((string)($editExam['duration_minutes'] ?? 60)); ?>"
                            >
                        </div>

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

                    </div>

                    <div class="grid grid-3">

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

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

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

                    </div>

                    <div class="grid grid-4">

                        <label class="badge badge-gray">
                            <input type="checkbox" name="require_exam_code" value="1"
                                <?php echo !empty($editExam['require_exam_code']) ? 'checked' : ''; ?>>
                            Require Code
                        </label>

                        <label class="badge badge-gray">
                            <input type="checkbox" name="show_result_immediately" value="1"
                                <?php echo !$editExam || !empty($editExam['show_result_immediately']) ? 'checked' : ''; ?>>
                            Show Result
                        </label>

                        <label class="badge badge-gray">
                            <input type="checkbox" name="shuffle_questions" value="1"
                                <?php echo !empty($editExam['shuffle_questions']) ? 'checked' : ''; ?>>
                            Shuffle
                        </label>

                        <label class="badge badge-gray">
                            <input type="checkbox" name="show_correct_answers" value="1"
                                <?php echo !empty($editExam['show_correct_answers']) ? 'checked' : ''; ?>>
                            Show Answers
                        </label>

                    </div>

                    <div class="toggle-more" onclick="toggleMoreOptions('examMoreOptions')">
                        More Options
                    </div>

                    <div class="more-options hidden" id="examMoreOptions">

                        <div class="grid grid-4">

                            <label class="badge badge-gray">
                                <input type="checkbox" name="allow_resume" value="1"
                                    <?php echo !$editExam || !empty($editExam['allow_resume']) ? 'checked' : ''; ?>>
                                Allow Resume
                            </label>

                            <label class="badge badge-gray">
                                <input type="checkbox" name="autosave_enabled" value="1"
                                    <?php echo !$editExam || !empty($editExam['autosave_enabled']) ? 'checked' : ''; ?>>
                                Autosave
                            </label>

                            <label class="badge badge-gray">
                                <input type="checkbox" name="anti_cheating_enabled" value="1"
                                    <?php echo !$editExam || !empty($editExam['anti_cheating_enabled']) ? 'checked' : ''; ?>>
                                Anti-Cheating
                            </label>

                            <label class="badge badge-gray">
                                <input type="checkbox" name="gradebook_enabled" value="1"
                                    <?php echo !$editExam || !empty($editExam['gradebook_enabled']) ? 'checked' : ''; ?>>
                                Gradebook
                            </label>

                        </div>

                        <div class="grid grid-2" style="margin-top:16px;">

                            <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>

                            <label class="badge badge-gray" style="align-self:end;">
                                <input type="checkbox" name="certificate_enabled" value="1"
                                    <?php echo !empty($editExam['certificate_enabled']) ? 'checked' : ''; ?>>
                                Certificate Eligibility
                            </label>

                        </div>

                    </div>

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

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

                </form>

            <?php endif; ?>

        </section>

        <section class="panel">

            <div class="panel-head">

                <div>
                    <div class="panel-title">My Exams</div>
                    <div class="panel-subtitle">
                        Your exams only. Open the builder to add questions quickly without page refresh.
                    </div>
                </div>

            </div>

            <?php if (!$teacherExams): ?>

                <div class="empty">
                    No exams created yet.
                </div>

            <?php else: ?>

                <div class="table-wrap">

                    <table class="table">

                        <thead>
                            <tr>
                                <th>Exam</th>
                                <th>Course</th>
                                <th>Type</th>
                                <th>Weight</th>
                                <th>Status</th>
                                <th>Questions</th>
                                <th>Attempts</th>
                                <th>Average</th>
                                <th>Actions</th>
                            </tr>
                        </thead>

                        <tbody>

                            <?php foreach ($teacherExams as $exam): ?>

                                <tr>

                                    <td>
                                        <div class="item-title">
                                            <?php echo e((string)$exam['title']); ?>
                                        </div>

                                        <div class="item-sub">
                                            Code: <?php echo e((string)($exam['exam_code'] ?? 'N/A')); ?>
                                        </div>
                                    </td>

                                    <td>
                                        <?php echo e((string)($exam['course_title'] ?? 'Course')); ?>
                                    </td>

                                    <td>
                                        <?php echo e(examTypeLabel((string)$exam['exam_type'])); ?>
                                    </td>

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

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

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

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

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

                                    <td>
                                        <div class="actions">

                                            <a class="btn btn-small btn-light"
                                               href="exams.php?tab=exams&edit_exam_id=<?php echo (int)$exam['id']; ?>">
                                                Edit
                                            </a>

                                            <a class="btn btn-small btn-primary"
                                               href="exams.php?tab=builder&exam_id=<?php echo (int)$exam['id']; ?>">
                                                Builder
                                            </a>

                                            <a class="btn btn-small btn-light"
                                               href="exams.php?tab=students&exam_id=<?php echo (int)$exam['id']; ?>">
                                                Students
                                            </a>

                                            <?php if ((string)$exam['status'] !== 'published'): ?>

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

                                            <?php endif; ?>

                                            <?php if ((string)$exam['status'] === 'published'): ?>

                                                <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>

                                            <?php endif; ?>

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

                                        </div>
                                    </td>

                                </tr>

                            <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>

            <?php endif; ?>

        </section>

    <?php endif; ?>

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

        <section class="panel">

            <div class="panel-head">

                <div>
                    <div class="panel-title">Smart Exam Builder</div>
                    <div class="panel-subtitle">
                        Add questions instantly. The page will show only the fields related to the selected question type.
                    </div>
                </div>

            </div>

            <form method="get" class="grid grid-3" style="margin-bottom:20px;">

                <input type="hidden" name="tab" value="builder">

                <select name="exam_id" class="select" required>
                    <option value="">Choose exam</option>

                    <?php foreach ($teacherExams as $exam): ?>
                        <option value="<?php echo (int)$exam['id']; ?>"
                            <?php echo $selectedExamId === (int)$exam['id'] ? 'selected' : ''; ?>>
                            <?php echo e((string)$exam['title']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

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

                <a href="exams.php?tab=exams" class="btn btn-light">
                    Create New Exam
                </a>

            </form>

            <?php if (!$selectedExam): ?>

                <div class="empty">
                    Choose an exam first to start adding questions.
                </div>

            <?php else: ?>

                <div class="kpi-row" style="margin-bottom:20px;">

                    <div class="kpi">
                        <span>Exam</span>
                        <strong style="font-size:20px;">
                            <?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>Weight</span>
                        <strong><?php echo e((string)($selectedExam['exam_weight'] ?? 0)); ?>%</strong>
                    </div>

                </div>

                <div class="panel" style="box-shadow:none;background:#f8fafc;">

                    <div class="panel-title" style="margin-bottom:16px;">
                        Add Question
                    </div>

                    <form id="quickQuestionForm" class="grid">

                        <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">
                        <input type="hidden" name="action" value="ajax_add_question">
                        <input type="hidden" name="exam_id" value="<?php echo (int)$selectedExam['id']; ?>">

                        <div class="grid grid-4">

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

                            <div>
                                <label class="label">Marks</label>
                                <input type="number" step="0.01" name="marks" class="input" value="1">
                            </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 e(ucfirst($skill)); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div>
                                <label class="label">Difficulty</label>
                                <select name="difficulty" class="select">
                                    <option value="easy">Easy</option>
                                    <option value="medium" selected>Medium</option>
                                    <option value="hard">Hard</option>
                                    <option value="elite">Elite</option>
                                </select>
                            </div>

                        </div>

                        <div>
                            <label class="label">Question</label>
                            <textarea
                                name="question_text"
                                class="textarea"
                                required
                                placeholder="Write the question here..."
                            ></textarea>
                        </div>

                        <div id="mcqFields" class="smart-question-fields">

                            <label class="label">MCQ Options</label>

                            <div class="grid grid-2">

                                <?php for ($i = 0; $i < 4; $i++): ?>

                                    <div>
                                        <input
                                            type="text"
                                            name="options[]"
                                            class="input"
                                            placeholder="Option <?php echo $i + 1; ?>"
                                        >

                                        <label class="badge badge-gray" style="margin-top:8px;">
                                            <input
                                                type="radio"
                                                name="correct_option"
                                                value="<?php echo $i; ?>"
                                                <?php echo $i === 0 ? 'checked' : ''; ?>
                                            >
                                            Correct
                                        </label>
                                    </div>

                                <?php endfor; ?>

                            </div>

                            <div class="item-sub" style="margin-top:10px;">
                                Add at least two options. Select the correct one.
                            </div>

                        </div>

                        <div id="trueFalseFields" class="smart-question-fields hidden">

                            <label class="label">Correct Answer</label>

                            <select name="true_false_answer" class="select">
                                <option value="true">True</option>
                                <option value="false">False</option>
                            </select>

                        </div>

                        <div id="textAnswerFields" class="smart-question-fields hidden">

                            <label class="label">Correct Answer</label>

                            <input
                                type="text"
                                name="correct_answer"
                                class="input"
                                placeholder="Write the correct answer. For many acceptable answers use | between them."
                            >

                        </div>

                        <div id="rubricFields" class="smart-question-fields hidden">

                            <label class="label">Rubric / Manual Grading</label>

                            <div class="grid grid-5">

                                <input type="number" name="rubric_grammar" class="input" placeholder="Grammar">
                                <input type="number" name="rubric_vocabulary" class="input" placeholder="Vocabulary">
                                <input type="number" name="rubric_coherence" class="input" placeholder="Coherence">
                                <input type="number" name="rubric_pronunciation" class="input" placeholder="Pronunciation">
                                <input type="number" name="rubric_task_response" class="input" placeholder="Task Response">

                            </div>

                        </div>

                        <div class="toggle-more" onclick="toggleMoreOptions('questionMoreOptions')">
                            More Options
                        </div>

                        <div class="more-options hidden" id="questionMoreOptions">

                            <div class="grid grid-3">

                                <div>
                                    <label class="label">Section</label>
                                    <input
                                        type="text"
                                        name="section_name"
                                        class="input"
                                        placeholder="Reading / Grammar / Story..."
                                    >
                                </div>

                                <label class="badge badge-gray" style="align-self:end;">
                                    <input type="checkbox" name="is_required" value="1" checked>
                                    Required
                                </label>

                                <label class="badge badge-gray" style="align-self:end;">
                                    <input type="checkbox" name="save_to_bank" value="1">
                                    Save to Bank
                                </label>

                            </div>

                            <div style="margin-top:14px;">
                                <label class="label">Explanation</label>
                                <textarea
                                    name="explanation"
                                    class="textarea"
                                    placeholder="Optional explanation shown after result..."
                                ></textarea>
                            </div>

                            <label class="badge badge-gray" style="margin-top:12px;">
                                <input type="checkbox" name="allow_file_upload" value="1">
                                Allow File Upload
                            </label>

                        </div>

                        <div class="actions">

                            <button class="btn btn-primary" type="submit" id="saveQuestionBtn">
                                Save Question
                            </button>

                            <button class="btn btn-light" type="reset">
                                Clear
                            </button>

                        </div>

                        <div id="questionSaveMessage"></div>

                    </form>

                </div>

                <div id="questionsList">

                    <?php if (!$examQuestions): ?>

                        <div class="empty" id="emptyQuestionsBox">
                            No questions yet. Add your first question above.
                        </div>

                    <?php else: ?>

                        <?php foreach ($examQuestions as $question): ?>

                            <div class="question-card" data-question-id="<?php echo (int)$question['id']; ?>">

                                <div class="question-top">

                                    <div>
                                        <div class="item-sub">
                                            <?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">

                                        <form method="post">
                                            <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">
                                            <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" 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']) && (string)$question['question_type'] !== 'multiple_choice'): ?>

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

                </div>

            <?php endif; ?>

        </section>

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

        <section class="panel">

            <div class="panel-head">

                <div>
                    <div class="panel-title">Students Results</div>
                    <div class="panel-subtitle">
                        Choose an exam to see all students who attempted it and their scores.
                    </div>
                </div>

            </div>

            <form method="get" class="grid grid-3" style="margin-bottom:20px;">

                <input type="hidden" name="tab" value="students">

                <select name="exam_id" class="select" required>
                    <option value="">Choose exam</option>

                    <?php foreach ($teacherExams as $exam): ?>
                        <option value="<?php echo (int)$exam['id']; ?>"
                            <?php echo $selectedExamId === (int)$exam['id'] ? 'selected' : ''; ?>>
                            <?php echo e((string)$exam['title']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <button class="btn btn-primary" type="submit">
                    Show Results
                </button>

                <a href="exams.php?tab=exams" class="btn btn-light">
                    Back to Exams
                </a>

            </form>

            <?php if (!$selectedExam): ?>

                <div class="empty">
                    Choose an exam first.
                </div>

            <?php else: ?>

                <div class="kpi-row" style="margin-bottom:20px;">

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

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

                    <div class="kpi">
                        <span>Weight</span>
                        <strong><?php echo e((string)($selectedExam['exam_weight'] ?? 0)); ?>%</strong>
                    </div>

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

                </div>

                <?php if (!$teacherStudentsResults): ?>

                    <div class="empty">
                        No students have taken this exam yet.
                    </div>

                <?php else: ?>

                    <div class="table-wrap">

                        <table class="table">

                            <thead>
                                <tr>
                                    <th>Student</th>
                                    <th>Code</th>
                                    <th>Attempt</th>
                                    <th>Status</th>
                                    <th>Score</th>
                                    <th>Percentage</th>
                                    <th>Result</th>
                                    <th>Submitted</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>

                            <tbody>

                                <?php foreach ($teacherStudentsResults as $result): ?>

                                    <tr>

                                        <td>
                                            <div class="item-title">
                                                <?php echo e((string)$result['full_name']); ?>
                                            </div>

                                            <div class="item-sub">
                                                <?php echo e((string)($result['email'] ?? '')); ?>
                                            </div>
                                        </td>

                                        <td>
                                            <?php echo e((string)($result['student_code'] ?? 'N/A')); ?>
                                        </td>

                                        <td>
                                            #<?php echo e((string)$result['attempt_number']); ?>
                                        </td>

                                        <td>
                                            <span class="badge <?php echo e(attemptStatusBadgeClass((string)$result['status'])); ?>">
                                                <?php echo e(ucfirst(str_replace('_', ' ', (string)$result['status']))); ?>
                                            </span>
                                        </td>

                                        <td>
                                            <?php echo e((string)$result['total_score']); ?>
                                        </td>

                                        <td>
                                            <strong><?php echo e((string)$result['percentage']); ?>%</strong>
                                        </td>

                                        <td>
                                            <span class="badge <?php echo (string)$result['result_status'] === 'pass' ? 'badge-green' : ((string)$result['result_status'] === 'fail' ? 'badge-red' : 'badge-orange'); ?>">
                                                <?php echo e(ucfirst((string)$result['result_status'])); ?>
                                            </span>
                                        </td>

                                        <td>
                                            <?php echo e(formatDateTimeNice($result['submitted_at'] ?? '')); ?>
                                        </td>

                                        <td>
                                            <a
                                                class="btn btn-small btn-primary"
                                                href="exams.php?tab=submissions&attempt_id=<?php echo (int)$result['id']; ?>"
                                            >
                                                Review
                                            </a>
                                        </td>

                                    </tr>

                                <?php endforeach; ?>

                            </tbody>

                        </table>

                    </div>

                <?php endif; ?>

            <?php endif; ?>

        </section>

    <?php endif; ?>


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

        <section class="panel">

            <div class="panel-head">

                <div>
                    <div class="panel-title">Submissions & Grading</div>
                    <div class="panel-subtitle">
                        Review students' answers, grade written/speaking/file questions, and sync results to gradebook.
                    </div>
                </div>

            </div>

            <?php if ($selectedAttempt): ?>

                <div class="kpi-row" style="margin-bottom:20px;">

                    <div class="kpi">
                        <span>Student</span>
                        <strong style="font-size:20px;">
                            <?php echo e((string)$selectedAttempt['student_name']); ?>
                        </strong>
                    </div>

                    <div class="kpi">
                        <span>Exam</span>
                        <strong style="font-size:20px;">
                            <?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>Result</span>
                        <strong style="font-size:20px;">
                            <?php echo e(ucfirst((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 if (!$attemptAnswers): ?>

                        <div class="empty">
                            No answers found for this attempt.
                        </div>

                    <?php else: ?>

                        <?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>

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

                                <div style="margin-top:14px;">

                                    <div class="item-sub" style="margin-bottom:8px;">
                                        Student Answer
                                    </div>

                                    <div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:18px;padding:16px;line-height:1.7;">
                                        <?php echo nl2br(e((string)($answer['answer_text'] ?? $answer['selected_option_text'] ?? 'No answer'))); ?>
                                    </div>

                                </div>

                                <?php if (!empty($answer['correct_answer'])): ?>

                                    <div style="margin-top:14px;">

                                        <div class="item-sub" style="margin-bottom:8px;">
                                            Correct Answer
                                        </div>

                                        <div style="background:#ecfdf5;border:1px solid #bbf7d0;border-radius:18px;padding:16px;line-height:1.7;">
                                            <?php echo nl2br(e((string)$answer['correct_answer'])); ?>
                                        </div>

                                    </div>

                                <?php endif; ?>

                                <div class="grid grid-2" style="margin-top:16px;">

                                    <div>
                                        <label class="label">Score Awarded</label>

                                        <input
                                            type="number"
                                            step="0.01"
                                            min="0"
                                            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'] ?? '')); ?>"
                                            placeholder="Feedback for this answer"
                                        >
                                    </div>

                                </div>

                            </div>

                        <?php endforeach; ?>

                        <div>
                            <label class="label">General Feedback</label>

                            <textarea
                                name="attempt_feedback"
                                class="textarea"
                                placeholder="General feedback for the whole attempt"
                            ><?php echo e((string)($selectedAttempt['feedback'] ?? '')); ?></textarea>
                        </div>

                        <div class="actions">

                            <button class="btn btn-primary" type="submit">
                                Save Grades
                            </button>

                        </div>

                    <?php endif; ?>

                </form>

                <div class="actions" style="margin-top:18px;">

                    <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
                        </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 Minutes
                        </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>

                    <a class="btn btn-light" href="exams.php?tab=students&exam_id=<?php echo (int)$selectedAttempt['exam_id']; ?>">
                        Back to Students
                    </a>

                </div>

            <?php else: ?>

                <div class="empty">
                    Choose an attempt from Students Results to review and grade.
                </div>

            <?php endif; ?>

        </section>

    <?php endif; ?>


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

        <section class="panel">

            <div class="panel-head">

                <div>
                    <div class="panel-title">Reports & Analytics</div>
                    <div class="panel-subtitle">
                        Quick view of strongest students, weak questions, and overall exam performance.
                    </div>
                </div>

            </div>

            <div class="grid grid-2">

                <div class="panel" style="box-shadow:none;background:#f8fafc;">

                    <div class="panel-title" style="margin-bottom:16px;">
                        Top Students
                    </div>

                    <?php if (!$reportTopStudents): ?>

                        <div class="empty">
                            No results yet.
                        </div>

                    <?php else: ?>

                        <?php foreach ($reportTopStudents as $row): ?>

                            <div class="question-card">

                                <div class="item-title">
                                    <?php echo e((string)$row['full_name']); ?>
                                    —
                                    <?php echo e((string)$row['percentage']); ?>%
                                </div>

                                <div class="item-sub">
                                    <?php echo e((string)$row['exam_title']); ?>
                                    ·
                                    <?php echo e((string)$row['student_code']); ?>
                                    ·
                                    <?php echo e(ucfirst((string)$row['result_status'])); ?>
                                </div>

                            </div>

                        <?php endforeach; ?>

                    <?php endif; ?>

                </div>

                <div class="panel" style="box-shadow:none;background:#f8fafc;">

                    <div class="panel-title" style="margin-bottom:16px;">
                        Weak Questions
                    </div>

                    <?php if (!$reportWeakQuestions): ?>

                        <div class="empty">
                            No question analytics yet.
                        </div>

                    <?php else: ?>

                        <?php foreach ($reportWeakQuestions as $row): ?>

                            <div class="question-card">

                                <div class="item-title">
                                    <?php echo e(mb_strimwidth((string)$row['question_text'], 0, 110, '...')); ?>
                                </div>

                                <div class="item-sub">
                                    <?php echo e(questionTypeLabel((string)$row['question_type'])); ?>
                                    ·
                                    Avg Score:
                                    <?php echo e((string)($row['avg_score'] ?? 0)); ?>
                                    /
                                    <?php echo e((string)$row['marks']); ?>
                                    ·
                                    Answers:
                                    <?php echo e((string)$row['answers_count']); ?>
                                </div>

                            </div>

                        <?php endforeach; ?>

                    <?php endif; ?>

                </div>

            </div>

        </section>

    <?php endif; ?>


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

        <section class="panel">

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

            <?php if (!$activeExams): ?>

                <div class="empty">
                    No active exams right now.
                </div>

            <?php else: ?>

                <?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 endif; ?>

        </section>

        <section class="panel">

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

            <?php if (!$upcomingExams): ?>

                <div class="empty">
                    No upcoming exams.
                </div>

            <?php else: ?>

                <?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 endif; ?>

        </section>

        <section class="panel">

            <div class="panel-title" style="margin-bottom:18px;">
                Expired Published Exams
            </div>

            <?php if (!$expiredExams): ?>

                <div class="empty">
                    No expired published exams.
                </div>

            <?php else: ?>

                <?php foreach ($expiredExams 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-warning" type="submit">
                                    Close
                                </button>

                            </form>

                        </div>

                    </div>

                <?php endforeach; ?>

            <?php endif; ?>

        </section>

    <?php endif; ?>

</div>

<script>
function toggleMoreOptions(id){
    const box = document.getElementById(id);

    if(!box){
        return;
    }

    box.classList.toggle('hidden');
}

/*
|--------------------------------------------------------------------------
| Exam Type Auto Weight
|--------------------------------------------------------------------------
*/

const examTypeSelect = document.getElementById('examTypeSelect');
const examWeightInput = document.getElementById('examWeightInput');

if(examTypeSelect && examWeightInput){

    examTypeSelect.addEventListener('change', function(){

        const selected = examTypeSelect.options[examTypeSelect.selectedIndex];

        if(selected && selected.dataset.weight !== undefined){
            examWeightInput.value = selected.dataset.weight;
        }
    });
}

/*
|--------------------------------------------------------------------------
| Smart Question Type Fields
|--------------------------------------------------------------------------
*/

const questionTypeSelect = document.getElementById('questionTypeSelect');

const mcqFields = document.getElementById('mcqFields');
const trueFalseFields = document.getElementById('trueFalseFields');
const textAnswerFields = document.getElementById('textAnswerFields');
const rubricFields = document.getElementById('rubricFields');

function refreshQuestionTypeFields(){

    if(!questionTypeSelect){
        return;
    }

    const type = questionTypeSelect.value;

    [mcqFields, trueFalseFields, textAnswerFields, rubricFields].forEach(function(box){
        if(box){
            box.classList.add('hidden');
        }
    });

    if(type === 'multiple_choice'){
        if(mcqFields){ mcqFields.classList.remove('hidden'); }
    }

    if(type === 'true_false'){
        if(trueFalseFields){ trueFalseFields.classList.remove('hidden'); }
    }

    if(type === 'fill_blank' || type === 'short_answer'){
        if(textAnswerFields){ textAnswerFields.classList.remove('hidden'); }
    }

    if(type === 'essay' || type === 'speaking' || type === 'file_upload' || type === 'listening'){
        if(rubricFields){ rubricFields.classList.remove('hidden'); }
    }
}

if(questionTypeSelect){
    questionTypeSelect.addEventListener('change', refreshQuestionTypeFields);
    refreshQuestionTypeFields();
}

/*
|--------------------------------------------------------------------------
| AJAX Add Question
|--------------------------------------------------------------------------
*/

const quickQuestionForm = document.getElementById('quickQuestionForm');
const questionSaveMessage = document.getElementById('questionSaveMessage');
const questionsList = document.getElementById('questionsList');
const saveQuestionBtn = document.getElementById('saveQuestionBtn');

if(quickQuestionForm){

    quickQuestionForm.addEventListener('submit', async function(e){

        e.preventDefault();

        if(saveQuestionBtn){
            saveQuestionBtn.disabled = true;
            saveQuestionBtn.textContent = 'Saving...';
        }

        if(questionSaveMessage){
            questionSaveMessage.innerHTML = '';
        }

        const formData = new FormData(quickQuestionForm);

        try{

            const response = await fetch('exams.php', {
                method:'POST',
                body:formData
            });

            const data = await response.json();

            if(data.success){

                if(questionSaveMessage){
                    questionSaveMessage.innerHTML = '<div class="notice notice-success">' + data.message + '</div>';
                }

                const emptyBox = document.getElementById('emptyQuestionsBox');

                if(emptyBox){
                    emptyBox.remove();
                }

                if(questionsList && data.html){
                    questionsList.insertAdjacentHTML('afterbegin', data.html);
                }

                quickQuestionForm.reset();
                refreshQuestionTypeFields();

            }else{

                if(questionSaveMessage){
                    questionSaveMessage.innerHTML = '<div class="notice notice-error">' + data.message + '</div>';
                }
            }

        }catch(error){

            if(questionSaveMessage){
                questionSaveMessage.innerHTML = '<div class="notice notice-error">Could not save question. Please try again.</div>';
            }

        }finally{

            if(saveQuestionBtn){
                saveQuestionBtn.disabled = false;
                saveQuestionBtn.textContent = 'Save Question';
            }
        }
    });
}

</script>

</body>
</html>