<?php
require_once __DIR__ . '/../includes/bootstrap.php';
require_student();

$quizId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)
    ?: filter_input(INPUT_POST, 'quiz_id', FILTER_VALIDATE_INT);
if (!$quizId) {
    flash('danger', 'الاختبار غير صحيح.');
    redirect('student/dashboard.php');
}

$stmt = db()->prepare('SELECT * FROM students WHERE id = ? LIMIT 1');
$stmt->execute([$_SESSION['student_id']]);
$student = $stmt->fetch();
if (!$student || $student['account_status'] !== 'approved') {
    unset($_SESSION['student_id']);
    flash('warning', 'لا يمكن الدخول إلى الحساب حاليًا.');
    redirect('login.php');
}

$stmt = db()->prepare(
    'SELECT q.*, COUNT(qq.id) AS question_count
     FROM quizzes q
     LEFT JOIN quiz_questions qq ON qq.quiz_id = q.id
     WHERE q.id = ? AND q.grade = ? AND q.is_active = 1
     GROUP BY q.id
     LIMIT 1'
);
$stmt->execute([$quizId, $student['grade']]);
$quiz = $stmt->fetch();
if (!$quiz) {
    flash('danger', 'الاختبار غير موجود أو غير متاح لصفك.');
    redirect('student/dashboard.php');
}
if (!student_has_quiz_access((int) $_SESSION['student_id'], $student, $quiz)) {
    flash('warning', 'هذا الاختبار غير متاح ضمن اشتراكك الحالي.');
    redirect('student/dashboard.php');
}
if ((int) $quiz['question_count'] === 0) {
    flash('warning', 'لم تتم إضافة أسئلة إلى هذا الاختبار بعد.');
    redirect('student/dashboard.php');
}

$stmt = db()->prepare('SELECT * FROM quiz_questions WHERE quiz_id = ? ORDER BY sort_order, id');
$stmt->execute([$quizId]);
$questions = $stmt->fetchAll();
$questionIds = array_map('intval', array_column($questions, 'id'));
$placeholders = implode(',', array_fill(0, count($questionIds), '?'));
$stmt = db()->prepare("SELECT * FROM quiz_options WHERE question_id IN ($placeholders) ORDER BY question_id, sort_order");
$stmt->execute($questionIds);
$optionsByQuestion = [];
foreach ($stmt->fetchAll() as $option) {
    $optionsByQuestion[(int) $option['question_id']][] = $option;
}

$errors = [];
$selectedAnswers = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $postedAnswers = (array) ($_POST['answers'] ?? []);
    $postedHints = (array) ($_POST['hints'] ?? []);

    foreach ($questions as $question) {
        $questionId = (int) $question['id'];
        $selectedOptionId = isset($postedAnswers[$questionId]) ? (int) $postedAnswers[$questionId] : 0;
        $selectedAnswers[$questionId] = $selectedOptionId;
        $validOptionIds = array_map('intval', array_column($optionsByQuestion[$questionId] ?? [], 'id'));
        if (!$selectedOptionId || !in_array($selectedOptionId, $validOptionIds, true)) {
            $errors[] = 'أجب عن جميع الأسئلة قبل إنهاء الاختبار.';
            break;
        }
    }

    if (!$errors) {
        $score = 0;
        $answerRows = [];
        foreach ($questions as $question) {
            $questionId = (int) $question['id'];
            $selectedOptionId = $selectedAnswers[$questionId];
            $isCorrect = 0;
            foreach ($optionsByQuestion[$questionId] as $option) {
                if ((int) $option['id'] === $selectedOptionId && (int) $option['is_correct'] === 1) {
                    $isCorrect = 1;
                    break;
                }
            }
            $score += $isCorrect;
            $hintUsed = !empty($postedHints[$questionId]) ? 1 : 0;
            $answerRows[] = [$questionId, $selectedOptionId, $hintUsed, $isCorrect];
        }

        db()->beginTransaction();
        try {
            $stmt = db()->prepare('INSERT INTO quiz_attempts (student_id, quiz_id, score, total_questions) VALUES (?, ?, ?, ?)');
            $stmt->execute([(int) $_SESSION['student_id'], $quizId, $score, count($questions)]);
            $attemptId = (int) db()->lastInsertId();

            $insert = db()->prepare('INSERT INTO quiz_attempt_answers (attempt_id, question_id, selected_option_id, hint_used, is_correct) VALUES (?, ?, ?, ?, ?)');
            foreach ($answerRows as [$questionId, $selectedOptionId, $hintUsed, $isCorrect]) {
                $insert->execute([$attemptId, $questionId, $selectedOptionId, $hintUsed, $isCorrect]);
            }
            db()->commit();
            redirect('student/quiz_result.php?attempt=' . $attemptId);
        } catch (Throwable $exception) {
            if (db()->inTransaction()) {
                db()->rollBack();
            }
            throw $exception;
        }
    }
}

$stmt = db()->prepare('SELECT MAX(score) AS best_score, MAX(total_questions) AS total_questions, COUNT(*) AS attempts FROM quiz_attempts WHERE student_id = ? AND quiz_id = ?');
$stmt->execute([(int) $_SESSION['student_id'], $quizId]);
$history = $stmt->fetch();

$pageTitle = $quiz['title'];
require_once __DIR__ . '/../includes/header.php';
?>
<div class="dashboard-head watch-heading">
    <div>
        <span class="dashboard-kicker">اختبار رقم <?= (int) $quiz['sort_order'] ?></span>
        <h1><?= e($quiz['title']) ?></h1>
        <p><?= count($questions) ?> سؤال اختيار من متعدد — ستظهر النتيجة والإجابات بعد الإرسال.</p>
    </div>
    <a class="btn btn-outline" href="<?= e(url('student/dashboard.php')) ?>">العودة للمحتوى</a>
</div>

<?php if ((int) ($history['attempts'] ?? 0) > 0): ?>
    <div class="quiz-history-note">سبق أن أجبت عن هذا الاختبار <?= (int) $history['attempts'] ?> مرة، وأفضل نتيجة: <strong><?= (int) $history['best_score'] ?> / <?= (int) $history['total_questions'] ?></strong></div>
<?php endif; ?>

<section class="card quiz-taking-card">
    <?php if (!empty($quiz['description'])): ?>
        <div class="quiz-instructions"><strong>تعليمات الاختبار</strong><p><?= nl2br(e($quiz['description'])) ?></p></div>
    <?php endif; ?>
    <?php if ($errors): ?><div class="errors"><?= e($errors[0]) ?></div><?php endif; ?>

    <form method="post" onsubmit="return confirm('هل انتهيت وتريد إظهار النتيجة؟')">
        <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="quiz_id" value="<?= (int) $quizId ?>">

        <div class="quiz-question-stack">
            <?php foreach ($questions as $index => $question):
                $questionId = (int) $question['id'];
                $hintId = 'kodo-hint-' . $questionId;
            ?>
                <fieldset class="quiz-question-card kodo-question-card">
                    <legend class="sr-only">السؤال <?= $index + 1 ?>: <?= e($question['question_text']) ?></legend>

                    <div class="kodo-question-row">
                        <div class="kodo-question-mascot" aria-hidden="true">
                            <img src="<?= e(url('assets/images/kodo-logo.png')) ?>" alt="">
                            <span>كودو</span>
                        </div>
                        <div class="kodo-speech-bubble">
                            <div class="kodo-speech-heading">
                                <span class="question-number-pill">السؤال <?= $index + 1 ?></span>
                                <strong>كودو بيسألك</strong>
                            </div>
                            <h2><?= e($question['question_text']) ?></h2>

                            <?php if (!empty($question['hint_text'])): ?>
                                <input type="hidden" name="hints[<?= $questionId ?>]" id="hint-used-<?= $questionId ?>" value="0">
                                <button
                                    class="kodo-hint-button"
                                    type="button"
                                    data-hint-target="<?= e($hintId) ?>"
                                    data-hint-input="hint-used-<?= $questionId ?>"
                                    aria-controls="<?= e($hintId) ?>"
                                    aria-expanded="false"
                                >💡 ساعدني يا كودو</button>
                                <div class="kodo-hint-box" id="<?= e($hintId) ?>" hidden>
                                    <img src="<?= e(url('assets/images/kodo-logo.png')) ?>" alt="كودو">
                                    <div><strong>تلميح كودو</strong><p><?= nl2br(e($question['hint_text'])) ?></p></div>
                                </div>
                            <?php else: ?>
                                <div class="kodo-thinking-note">خد وقتك، اقرأ الاختيارات بهدوء واستبعد الإجابات البعيدة عن معنى السؤال.</div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="answer-options">
                        <?php foreach ($optionsByQuestion[$questionId] as $option): ?>
                            <label class="answer-option">
                                <input type="radio" name="answers[<?= $questionId ?>]" value="<?= (int) $option['id'] ?>" <?= ($selectedAnswers[$questionId] ?? 0) === (int) $option['id'] ? 'checked' : '' ?> required>
                                <span class="answer-letter"><?= e(option_letter((int) $option['sort_order'])) ?></span>
                                <span><?= e($option['option_text']) ?></span>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </fieldset>
            <?php endforeach; ?>
        </div>

        <button class="btn btn-primary quiz-submit" type="submit">إنهاء الاختبار وإظهار النتيجة</button>
    </form>
</section>
<script>
document.querySelectorAll('[data-hint-target]').forEach(function (button) {
    button.addEventListener('click', function () {
        var hint = document.getElementById(button.dataset.hintTarget);
        var input = document.getElementById(button.dataset.hintInput);
        if (!hint) return;
        hint.hidden = false;
        if (input) input.value = '1';
        button.setAttribute('aria-expanded', 'true');
        button.classList.add('is-used');
        button.innerHTML = '✓ ظهر تلميح كودو';
        hint.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    });
});
</script>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
