<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| Exam Builder
|--------------------------------------------------------------------------
*/

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

requireTeacher();

$teacher = currentTeacher($pdo);

if (!$teacher) {
    teacherLogout();
    redirectTo('teacher/login.php');
}

$error = '';
$success = '';

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

if (!$examId) {
    redirectTo('teacher/exams.php');
}

/*
|--------------------------------------------------------------------------
| Local Helpers
|--------------------------------------------------------------------------
*/

if (!function_exists('smiColumnExists')) {

    function smiColumnExists(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('smiCsrfToken')) {

    function smiCsrfToken(): string
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

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

        return $_SESSION['teacher_exam_questions_csrf_token'];
    }
}

if (!function_exists('smiCheckCsrf')) {

    function smiCheckCsrf(): bool
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        $token = $_POST['csrf_token'] ?? '';

        return is_string($token)
            &&
            isset($_SESSION['teacher_exam_questions_csrf_token'])
            &&
            hash_equals($_SESSION['teacher_exam_questions_csrf_token'], $token);
    }
}

$csrfToken = smiCsrfToken();

$questions = [];
$questionOptions = [];

/*
|--------------------------------------------------------------------------
| Get Exam
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    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 e.teacher_id = ?
    LIMIT 1
");

$stmt->execute([
    $examId,
    $teacher['id']
]);

$exam = $stmt->fetch();

if (!$exam) {
    redirectTo('teacher/exams.php');
}

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

if (
    isPost()
    &&
    ($_POST['action'] ?? '') === 'add_question'
) {

    if (!smiCheckCsrf()) {

        $error = 'Security token expired. Please refresh the page and try again.';

    } elseif (!tableExists($pdo, 'core_exam_questions')) {

        $error = 'The table core_exam_questions does not exist. Please create it first.';

    } else {

        $allowedTypes = [
            'multiple_choice',
            'true_false',
            'fill_blank',
            'short_answer',
            'essay'
        ];

        $questionType = trim($_POST['question_type'] ?? '');
        $question = trim($_POST['question'] ?? '');
        $correctAnswer = trim($_POST['correct_answer'] ?? '');
        $marks = (float)($_POST['marks'] ?? 0);
        $questionOrder = (int)($_POST['question_order'] ?? 1);
        $explanation = trim($_POST['explanation'] ?? '');

        $optionA = trim($_POST['option_a'] ?? '');
        $optionB = trim($_POST['option_b'] ?? '');
        $optionC = trim($_POST['option_c'] ?? '');
        $optionD = trim($_POST['option_d'] ?? '');
        $correctOption = trim($_POST['correct_option'] ?? '');

        $attachmentPath = null;

        if ($questionOrder <= 0) {
            $questionOrder = 1;
        }

        if (
            !in_array(
                $questionType,
                $allowedTypes,
                true
            )
        ) {

            $error = 'Invalid question type.';

        } elseif ($question === '') {

            $error = 'Question is required.';

        } elseif ($marks <= 0) {

            $error = 'Marks must be greater than zero.';

        } elseif (
            $questionType === 'multiple_choice'
            &&
            (
                $optionA === ''
                ||
                $optionB === ''
                ||
                $optionC === ''
                ||
                $optionD === ''
                ||
                !in_array($correctOption, ['A','B','C','D'], true)
            )
        ) {

            $error = 'Please complete all multiple choice options and select the correct option.';

        } elseif (
            $questionType === 'true_false'
            &&
            !in_array($correctAnswer, ['true','false'], true)
        ) {

            $error = 'Please select true or false as the correct answer.';

        } elseif (
            in_array($questionType, ['fill_blank','short_answer'], true)
            &&
            $correctAnswer === ''
        ) {

            $error = 'Correct answer is required for this question type.';

        } else {

            if ($questionType === 'multiple_choice') {
                $correctAnswer = $correctOption;
            }

            if ($questionType === 'essay' && $correctAnswer === '') {
                $correctAnswer = '';
            }

            /*
            |--------------------------------------------------------------------------
            | Optional Attachment Upload
            |--------------------------------------------------------------------------
            */

            if (isset($_FILES['attachment']) && is_array($_FILES['attachment']) && ($_FILES['attachment']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
                $extension = strtolower(pathinfo((string)($_FILES['attachment']['name'] ?? ''), PATHINFO_EXTENSION));
                if (!in_array($extension, ['jpg','jpeg','png','webp','pdf','mp3','wav'], true)) {
                    $error = 'Invalid attachment type. Allowed: JPG, PNG, WEBP, PDF, MP3 or WAV.';
                } else {
                    $attachmentPath = uploadFile($_FILES['attachment'], 'exam-attachments') ?? '';
                    if ($attachmentPath === '') {
                        $error = 'Attachment was rejected because its type, content or size is not allowed.';
                    }
                }
            }

            if ($error === '') {

                try {

                    $pdo->beginTransaction();

                    $questionColumn =
                        smiColumnExists($pdo, 'core_exam_questions', 'question')
                        ? 'question'
                        : (
                            smiColumnExists($pdo, 'core_exam_questions', 'question_text')
                            ? 'question_text'
                            : 'question'
                        );

                    $insertColumns = [
                        'exam_id',
                        'question_type',
                        $questionColumn,
                        'correct_answer',
                        'marks'
                    ];

                    $insertValues = [
                        $examId,
                        $questionType,
                        $question,
                        $correctAnswer,
                        $marks
                    ];

                    if (
                        smiColumnExists(
                            $pdo,
                            'core_exam_questions',
                            'question_order'
                        )
                    ) {

                        $insertColumns[] = 'question_order';
                        $insertValues[] = $questionOrder;
                    }

                    if (
                        smiColumnExists(
                            $pdo,
                            'core_exam_questions',
                            'explanation'
                        )
                    ) {

                        $insertColumns[] = 'explanation';
                        $insertValues[] = $explanation !== '' ? $explanation : null;
                    }

                    if (
                        smiColumnExists(
                            $pdo,
                            'core_exam_questions',
                            'attachment_path'
                        )
                    ) {

                        $insertColumns[] = 'attachment_path';
                        $insertValues[] = $attachmentPath;
                    }

                    if (
                        smiColumnExists(
                            $pdo,
                            'core_exam_questions',
                            'created_at'
                        )
                    ) {

                        $insertColumns[] = 'created_at';
                        $insertValues[] = now();
                    }

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

                    $sql =
                        'INSERT INTO core_exam_questions (' .
                        implode(', ', $insertColumns) .
                        ') VALUES (' .
                        $placeholders .
                        ')';

                    $insertStmt = $pdo->prepare($sql);

                    $insertStmt->execute($insertValues);

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

                    if (
                        $questionType === 'multiple_choice'
                        &&
                        tableExists($pdo, 'core_exam_options')
                    ) {

                        $options = [
                            'A' => $optionA,
                            'B' => $optionB,
                            'C' => $optionC,
                            'D' => $optionD
                        ];

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

                            $optionColumns = [
                                'question_id',
                                'option_key',
                                'option_text',
                                'is_correct'
                            ];

                            $optionValues = [
                                $questionId,
                                $optionKey,
                                $optionText,
                                $optionKey === $correctOption ? 1 : 0
                            ];

                            if (
                                smiColumnExists(
                                    $pdo,
                                    'core_exam_options',
                                    'created_at'
                                )
                            ) {

                                $optionColumns[] = 'created_at';
                                $optionValues[] = now();
                            }

                            $optionPlaceholders = implode(
                                ', ',
                                array_fill(
                                    0,
                                    count($optionColumns),
                                    '?'
                                )
                            );

                            $optionSql =
                                'INSERT INTO core_exam_options (' .
                                implode(', ', $optionColumns) .
                                ') VALUES (' .
                                $optionPlaceholders .
                                ')';

                            $optionStmt = $pdo->prepare($optionSql);

                            $optionStmt->execute($optionValues);
                        }
                    }

                    logActivity(
                        $pdo,
                        'teacher',
                        (int)$teacher['id'],
                        'Exam Question Added',
                        'Added question to exam ID: ' . $examId
                    );

                    $pdo->commit();

                    $success = 'Question added successfully.';

                } catch (Throwable $e) {

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

                    if (APP_DEBUG) {
                        die($e->getMessage());
                    }

                    $error = 'Failed to add question.';
                }
            }
        }
    }
}

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

if (
    isPost()
    &&
    ($_POST['action'] ?? '') === 'delete_question'
) {

    if (!smiCheckCsrf()) {

        $error = 'Security token expired. Please refresh the page and try again.';

    } elseif (!tableExists($pdo, 'core_exam_questions')) {

        $error = 'Questions table does not exist.';

    } else {

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

        if ($questionId <= 0) {

            $error = 'Invalid question selected.';

        } else {

            try {

                $checkStmt = $pdo->prepare("
                    SELECT q.id
                    FROM core_exam_questions q
                    INNER JOIN core_exams e ON e.id = q.exam_id
                    WHERE q.id = ?
                    AND q.exam_id = ?
                    AND e.teacher_id = ?
                    LIMIT 1
                ");

                $checkStmt->execute([
                    $questionId,
                    $examId,
                    $teacher['id']
                ]);

                $questionExists = $checkStmt->fetch();

                if (!$questionExists) {

                    $error = 'Question not found or not allowed.';

                } else {

                    $pdo->beginTransaction();

                    if (tableExists($pdo, 'core_exam_options')) {

                        $deleteOptionsStmt = $pdo->prepare("
                            DELETE FROM core_exam_options
                            WHERE question_id = ?
                        ");

                        $deleteOptionsStmt->execute([
                            $questionId
                        ]);
                    }

                    $deleteQuestionStmt = $pdo->prepare("
                        DELETE FROM core_exam_questions
                        WHERE id = ?
                        AND exam_id = ?
                    ");

                    $deleteQuestionStmt->execute([
                        $questionId,
                        $examId
                    ]);

                    logActivity(
                        $pdo,
                        'teacher',
                        (int)$teacher['id'],
                        'Exam Question Deleted',
                        'Deleted question ID: ' . $questionId . ' from exam ID: ' . $examId
                    );

                    $pdo->commit();

                    $success = 'Question deleted successfully.';
                }

            } catch (Throwable $e) {

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

                if (APP_DEBUG) {
                    die($e->getMessage());
                }

                $error = 'Failed to delete question.';
            }
        }
    }
}

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

if (tableExists($pdo, 'core_exam_questions')) {

    $questionColumn =
        smiColumnExists($pdo, 'core_exam_questions', 'question')
        ? 'question'
        : (
            smiColumnExists($pdo, 'core_exam_questions', 'question_text')
            ? 'question_text'
            : 'question'
        );

    $selectQuestionOrder =
        smiColumnExists($pdo, 'core_exam_questions', 'question_order')
        ? 'q.question_order'
        : 'q.id AS question_order';

    $selectExplanation =
        smiColumnExists($pdo, 'core_exam_questions', 'explanation')
        ? 'q.explanation'
        : 'NULL AS explanation';

    $selectAttachment =
        smiColumnExists($pdo, 'core_exam_questions', 'attachment_path')
        ? 'q.attachment_path'
        : 'NULL AS attachment_path';

    $qStmt = $pdo->prepare("
        SELECT
            q.id,
            q.exam_id,
            q.question_type,
            q.$questionColumn AS question,
            q.correct_answer,
            q.marks,
            $selectQuestionOrder,
            $selectExplanation,
            $selectAttachment
        FROM core_exam_questions q
        WHERE q.exam_id = ?
        ORDER BY question_order ASC, q.id ASC
    ");

    $qStmt->execute([
        $examId
    ]);

    $questions = $qStmt->fetchAll();

    if (
        $questions
        &&
        tableExists($pdo, 'core_exam_options')
    ) {

        $questionIds = array_map(
            static function ($question): int {
                return (int)$question['id'];
            },
            $questions
        );

        if ($questionIds) {

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

            $optionStmt = $pdo->prepare("
                SELECT *
                FROM core_exam_options
                WHERE question_id IN ($placeholders)
                ORDER BY question_id ASC, option_key ASC
            ");

            $optionStmt->execute($questionIds);

            $allOptions = $optionStmt->fetchAll();

            foreach ($allOptions as $option) {

                $questionOptions[
                    (int)$option['question_id']
                ][] = $option;
            }
        }
    }
}

?>

<!DOCTYPE html>
<html lang="en">

<head>

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

<title>Exam Builder</title>

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

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

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

.page{
    padding:35px;
}

.topbar{
    display:flex;
    justify-content:space-between;
    align-items:center;
    margin-bottom:30px;
}

.title{
    font-size:42px;
    font-weight:900;
}

.back-btn{
    text-decoration:none;
    background:#eff6ff;
    color:#2563eb;
    padding:14px 22px;
    border-radius:18px;
    font-weight:900;
}

.hero{
    background:linear-gradient(135deg,#7c3aed,#4f46e5);
    color:#fff;
    border-radius:34px;
    padding:40px;
    margin-bottom:30px;
}

.hero h1{
    font-size:42px;
    margin-bottom:14px;
    font-weight:900;
}

.hero p{
    color:#ede9fe;
    line-height:2;
}

.alert{
    padding:18px 22px;
    border-radius:18px;
    margin-bottom:24px;
    font-weight:800;
}

.alert.error{
    background:#fef2f2;
    color:#dc2626;
}

.alert.success{
    background:#dcfce7;
    color:#16a34a;
}

.notice{
    padding:16px 18px;
    background:#fffbeb;
    color:#92400e;
    border:1px solid #fde68a;
    border-radius:18px;
    margin-bottom:18px;
    font-weight:800;
    line-height:1.7;
}

.layout{
    display:grid;
    grid-template-columns:430px 1fr;
    gap:24px;
}

.card{
    background:#fff;
    border-radius:32px;
    padding:30px;
    border:1px solid #e2e8f0;
    box-shadow:0 18px 50px rgba(15,23,42,0.06);
}

.card h2{
    font-size:28px;
    margin-bottom:24px;
    font-weight:900;
}

.group{
    margin-bottom:20px;
}

.group label{
    display:block;
    margin-bottom:10px;
    font-weight:800;
}

.group input,
.group select,
.group textarea{
    width:100%;
    padding:16px 18px;
    border-radius:18px;
    border:1px solid #ddd6fe;
    font-family:inherit;
    font-size:15px;
    background:#fff;
}

.group input:focus,
.group select:focus,
.group textarea:focus{
    outline:none;
    border-color:#7c3aed;
    box-shadow:0 0 0 5px rgba(124,58,237,0.10);
}

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

.small-grid{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:14px;
}

.type-box{
    display:none;
}

.type-box.active{
    display:block;
}

.submit-btn{
    width:100%;
    border:none;
    background:linear-gradient(135deg,#7c3aed,#4f46e5);
    color:#fff;
    padding:18px;
    border-radius:20px;
    font-size:16px;
    font-weight:900;
    cursor:pointer;
}

.question{
    background:#f8fafc;
    border:1px solid #e2e8f0;
    border-radius:24px;
    padding:22px;
    margin-bottom:18px;
}

.question-header{
    display:flex;
    justify-content:space-between;
    gap:14px;
    align-items:flex-start;
    margin-bottom:12px;
}

.question h3{
    font-size:21px;
    margin-bottom:12px;
    font-weight:900;
    line-height:1.5;
}

.question p{
    color:#64748b;
    line-height:1.8;
    margin-bottom:8px;
}

.badge{
    display:inline-block;
    padding:9px 14px;
    border-radius:999px;
    background:#ede9fe;
    color:#7c3aed;
    font-size:12px;
    font-weight:900;
    margin-top:8px;
}

.badge.blue{
    background:#eff6ff;
    color:#2563eb;
}

.badge.green{
    background:#dcfce7;
    color:#16a34a;
}

.badge.gray{
    background:#f1f5f9;
    color:#334155;
}

.options-list{
    display:grid;
    gap:8px;
    margin-top:14px;
}

.option-row{
    padding:12px 14px;
    border-radius:14px;
    background:#ffffff;
    border:1px solid #e2e8f0;
    color:#475569;
    font-weight:700;
}

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

.explanation{
    margin-top:14px;
    padding:14px;
    background:#fff7ed;
    border:1px solid #fed7aa;
    color:#9a3412;
    border-radius:16px;
    line-height:1.8;
}

.attachment-link{
    display:inline-block;
    margin-top:14px;
    text-decoration:none;
    background:#eef2ff;
    color:#4338ca;
    padding:10px 14px;
    border-radius:14px;
    font-size:13px;
    font-weight:900;
}

.delete-btn{
    border:none;
    background:#fef2f2;
    color:#dc2626;
    padding:10px 14px;
    border-radius:14px;
    font-weight:900;
    cursor:pointer;
}

.empty{
    text-align:center;
    padding:55px;
    color:#64748b;
    border:1px dashed #cbd5e1;
    border-radius:24px;
}

@media(max-width:1100px){
    .layout{
        grid-template-columns:1fr;
    }
}

@media(max-width:700px){
    .page{
        padding:20px;
    }

    .topbar{
        flex-direction:column;
        align-items:flex-start;
        gap:16px;
    }

    .title{
        font-size:34px;
    }

    .hero h1{
        font-size:34px;
    }

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

    .question-header{
        flex-direction:column;
    }
}
</style>

</head>

<body>

<div class="page">

    <div class="topbar">

        <h1 class="title">
            Exam Builder
        </h1>

        <a href="exams.php" class="back-btn">
            ← Back
        </a>

    </div>

    <div class="hero">

        <h1>
            <?php echo e($exam['title']); ?>
        </h1>

        <p>
            Course: <?php echo e($exam['course_title']); ?>
            <br>
            Exam Code: <?php echo e($exam['exam_code']); ?>
        </p>

    </div>

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

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

    <?php if(!tableExists($pdo, 'core_exam_questions')): ?>

        <div class="notice">
            The table core_exam_questions does not exist yet. Please create it first.
        </div>

    <?php endif; ?>

    <?php if(!tableExists($pdo, 'core_exam_options')): ?>

        <div class="notice">
            The table core_exam_options does not exist yet. Multiple choice options will not be saved until this table is created.
        </div>

    <?php endif; ?>

    <div class="layout">

        <div class="card">

            <h2>
                Add Question
            </h2>

            <form method="POST" enctype="multipart/form-data">

                <input type="hidden" name="csrf_token" value="<?php echo e($csrfToken); ?>">

                <input type="hidden" name="action" value="add_question">

                <input type="hidden" name="exam_id" value="<?php echo e((string)$examId); ?>">

                <div class="group">
                    <label>Question Type</label>
                    <select name="question_type" id="question_type" required>
                        <option value="">Select Type</option>
                        <option value="multiple_choice">Multiple Choice</option>
                        <option value="true_false">True / False</option>
                        <option value="fill_blank">Fill in the Blank</option>
                        <option value="short_answer">Short Answer</option>
                        <option value="essay">Essay</option>
                    </select>
                </div>

                <div class="group">
                    <label>Question</label>
                    <textarea name="question" required></textarea>
                </div>

                <div class="type-box" id="multiple_choice_box">

                    <div class="small-grid">

                        <div class="group">
                            <label>Option A</label>
                            <input type="text" name="option_a">
                        </div>

                        <div class="group">
                            <label>Option B</label>
                            <input type="text" name="option_b">
                        </div>

                        <div class="group">
                            <label>Option C</label>
                            <input type="text" name="option_c">
                        </div>

                        <div class="group">
                            <label>Option D</label>
                            <input type="text" name="option_d">
                        </div>

                    </div>

                    <div class="group">
                        <label>Correct Option</label>
                        <select name="correct_option">
                            <option value="">Select Correct Option</option>
                            <option value="A">A</option>
                            <option value="B">B</option>
                            <option value="C">C</option>
                            <option value="D">D</option>
                        </select>
                    </div>

                </div>

                <div class="type-box" id="true_false_box">

                    <div class="group">
                        <label>Correct Answer</label>
                        <select name="true_false_answer">
                            <option value="">Select Answer</option>
                            <option value="true">True</option>
                            <option value="false">False</option>
                        </select>
                    </div>

                </div>

                <div class="type-box" id="standard_answer_box">

                    <div class="group">
                        <label>Correct Answer / Model Answer</label>
                        <textarea name="standard_correct_answer"></textarea>
                    </div>

                </div>

                <input type="hidden" name="correct_answer" id="correct_answer_hidden" value="">

                <div class="small-grid">

                    <div class="group">
                        <label>Marks</label>
                        <input type="number" step="0.01" min="0.01" name="marks" required>
                    </div>

                    <div class="group">
                        <label>Question Order</label>
                        <input type="number" min="1" name="question_order" value="1" required>
                    </div>

                </div>

                <div class="group">
                    <label>Explanation Optional</label>
                    <textarea name="explanation"></textarea>
                </div>

                <div class="group">
                    <label>Attachment Optional Image / Audio / PDF</label>
                    <input
                    type="file"
                    name="attachment"
                    accept=".jpg,.jpeg,.png,.gif,.webp,.pdf,.mp3,.wav,.m4a,.ogg,image/*,audio/*,application/pdf">
                </div>

                <button type="submit" class="submit-btn">
                    Add Question
                </button>

            </form>

        </div>

        <div class="card">

            <h2>
                Questions
            </h2>

            <?php if($questions): ?>

                <?php foreach($questions as $index => $question): ?>

                    <div class="question">

                        <div class="question-header">

                            <div>

                                <h3>
                                    Question <?php echo e((string)($index + 1)); ?>
                                </h3>

                                <p>
                                    <?php echo e((string)$question['question']); ?>
                                </p>

                            </div>

                            <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="exam_id" value="<?php echo e((string)$examId); ?>">

                                <input type="hidden" name="question_id" value="<?php echo e((string)$question['id']); ?>">

                                <button type="submit" class="delete-btn">
                                    Delete
                                </button>

                            </form>

                        </div>

                        <span class="badge">
                            <?php echo e((string)$question['question_type']); ?>
                        </span>

                        <span class="badge blue">
                            <?php echo e((string)$question['marks']); ?> Marks
                        </span>

                        <span class="badge green">
                            Order: <?php echo e((string)$question['question_order']); ?>
                        </span>

                        <?php if((string)$question['question_type'] === 'multiple_choice'): ?>

                            <div class="options-list">

                                <?php foreach(($questionOptions[(int)$question['id']] ?? []) as $option): ?>

                                    <div class="option-row <?php echo ((int)$option['is_correct'] === 1) ? 'correct' : ''; ?>">

                                        <?php echo e((string)$option['option_key']); ?>)

                                        <?php echo e((string)$option['option_text']); ?>

                                        <?php if((int)$option['is_correct'] === 1): ?>
                                            — Correct
                                        <?php endif; ?>

                                    </div>

                                <?php endforeach; ?>

                            </div>

                        <?php else: ?>

                            <?php if((string)($question['correct_answer'] ?? '') !== ''): ?>

                                <span class="badge green">
                                    Correct Answer:
                                    <?php echo e((string)$question['correct_answer']); ?>
                                </span>

                            <?php elseif((string)$question['question_type'] === 'essay'): ?>

                                <span class="badge gray">
                                    Manual Grading
                                </span>

                            <?php endif; ?>

                        <?php endif; ?>

                        <?php if((string)($question['explanation'] ?? '') !== ''): ?>

                            <div class="explanation">

                                <strong>Explanation:</strong>
                                <br>
                                <?php echo e((string)$question['explanation']); ?>

                            </div>

                        <?php endif; ?>

                        <?php if((string)($question['attachment_path'] ?? '') !== ''): ?>

                            <a
                            class="attachment-link"
                            href="../<?php echo e((string)$question['attachment_path']); ?>"
                            target="_blank">

                                View Attachment

                            </a>

                        <?php endif; ?>

                    </div>

                <?php endforeach; ?>

            <?php else: ?>

                <div class="empty">
                    No questions added yet.
                </div>

            <?php endif; ?>

        </div>

    </div>

</div>

<script>

const questionType = document.getElementById('question_type');
const multipleChoiceBox = document.getElementById('multiple_choice_box');
const trueFalseBox = document.getElementById('true_false_box');
const standardAnswerBox = document.getElementById('standard_answer_box');

function updateQuestionTypeBoxes() {

    if (!questionType) {
        return;
    }

    const type = questionType.value;

    if (multipleChoiceBox) {
        multipleChoiceBox.classList.remove('active');
    }

    if (trueFalseBox) {
        trueFalseBox.classList.remove('active');
    }

    if (standardAnswerBox) {
        standardAnswerBox.classList.remove('active');
    }

    if (type === 'multiple_choice' && multipleChoiceBox) {
        multipleChoiceBox.classList.add('active');
    }

    if (type === 'true_false' && trueFalseBox) {
        trueFalseBox.classList.add('active');
    }

    if (
        (
            type === 'fill_blank'
            ||
            type === 'short_answer'
            ||
            type === 'essay'
        )
        &&
        standardAnswerBox
    ) {
        standardAnswerBox.classList.add('active');
    }
}

if (questionType) {

    questionType.addEventListener(
        'change',
        updateQuestionTypeBoxes
    );

    updateQuestionTypeBoxes();
}

document.addEventListener('submit', function(event) {

    const form = event.target;

    if (!form || !form.querySelector('#correct_answer_hidden')) {
        return;
    }

    const typeSelect = form.querySelector('[name="question_type"]');
    const hidden = form.querySelector('[name="correct_answer"]');

    if (!typeSelect || !hidden) {
        return;
    }

    const type = typeSelect.value;

    if (type === 'true_false') {

        const trueFalse = form.querySelector('[name="true_false_answer"]');

        hidden.value = trueFalse ? trueFalse.value : '';
    }

    if (
        type === 'fill_blank'
        ||
        type === 'short_answer'
        ||
        type === 'essay'
    ) {

        const standard = form.querySelector('[name="standard_correct_answer"]');

        hidden.value = standard ? standard.value : '';
    }

    if (type === 'multiple_choice') {
        hidden.value = '';
    }

});

</script>

</body>
</html>