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

$attemptId = filter_input(INPUT_GET, 'attempt', FILTER_VALIDATE_INT);
if (!$attemptId) {
    flash('danger', 'النتيجة غير صحيحة.');
    redirect('student/dashboard.php');
}

$stmt = db()->prepare(
    'SELECT qa.*, q.title, q.grade, q.id AS quiz_id
     FROM quiz_attempts qa
     JOIN quizzes q ON q.id = qa.quiz_id
     WHERE qa.id = ? AND qa.student_id = ?
     LIMIT 1'
);
$stmt->execute([$attemptId, (int) $_SESSION['student_id']]);
$attempt = $stmt->fetch();
if (!$attempt) {
    flash('danger', 'لا يمكنك عرض هذه النتيجة.');
    redirect('student/dashboard.php');
}

$stmt = db()->prepare(
    'SELECT qq.question_text, qq.explanation, qq.sort_order,
            qaa.is_correct, qaa.hint_used,
            selected.option_text AS selected_answer,
            correct.option_text AS correct_answer
     FROM quiz_attempt_answers qaa
     JOIN quiz_questions qq ON qq.id = qaa.question_id
     LEFT JOIN quiz_options selected ON selected.id = qaa.selected_option_id
     LEFT JOIN quiz_options correct ON correct.question_id = qq.id AND correct.is_correct = 1
     WHERE qaa.attempt_id = ?
     ORDER BY qq.sort_order, qq.id'
);
$stmt->execute([$attemptId]);
$answers = $stmt->fetchAll();

$total = max(1, (int) $attempt['total_questions']);
$score = (int) $attempt['score'];
$percent = (int) round(($score / $total) * 100);
if ($percent >= 85) {
    $resultMessage = 'ممتاز يا بطل! أداء قوي جدًا.';
    $resultClass = 'excellent';
} elseif ($percent >= 60) {
    $resultMessage = 'نتيجة جيدة، راجع الأخطاء وحاول مرة أخرى.';
    $resultClass = 'good';
} else {
    $resultMessage = 'محتاج مراجعة بسيطة، والإجابات الصحيحة موجودة بالأسفل.';
    $resultClass = 'needs-work';
}

$pageTitle = 'نتيجة الاختبار';
require_once __DIR__ . '/../includes/header.php';
?>
<div class="result-hero <?= e($resultClass) ?>">
    <img src="<?= e(url('assets/images/kodo-logo.png')) ?>" alt="كودو">
    <div>
        <span>نتيجة <?= e($attempt['title']) ?></span>
        <h1><?= $score ?> من <?= (int) $attempt['total_questions'] ?></h1>
        <strong><?= $percent ?>%</strong>
        <p><?= e($resultMessage) ?></p>
    </div>
</div>

<div class="actions result-actions">
    <a class="btn btn-primary" href="<?= e(url('student/quiz.php?id=' . (int) $attempt['quiz_id'])) ?>">إعادة الاختبار</a>
    <a class="btn btn-outline" href="<?= e(url('student/dashboard.php')) ?>">العودة لكل المحتوى</a>
</div>

<section class="result-review">
    <div class="section-title-row">
        <div><span class="dashboard-kicker">مراجعة الإجابات</span><h2>الإجابة الصحيحة لكل سؤال</h2></div>
        <span class="section-note">تظهر الإجابات بعد إنهاء الاختبار فقط.</span>
    </div>

    <div class="result-answer-list">
        <?php foreach ($answers as $index => $answer): ?>
            <article class="result-answer-card <?= (int) $answer['is_correct'] === 1 ? 'correct' : 'wrong' ?>">
                <div class="result-question-title"><span><?= $index + 1 ?></span><h3><?= e($answer['question_text']) ?></h3></div>
                <div class="result-choice selected-choice">
                    <b>إجابتك:</b>
                    <span><?= e((string) $answer['selected_answer']) ?></span>
                    <em><?= (int) $answer['is_correct'] === 1 ? '✓ صحيحة' : '✕ غير صحيحة' ?></em>
                </div>
                <?php if ((int) ($answer['hint_used'] ?? 0) === 1): ?>
                    <div class="hint-used-badge">💡 استعنت بتلميح كودو في هذا السؤال</div>
                <?php endif; ?>
                <?php if ((int) $answer['is_correct'] !== 1): ?>
                    <div class="result-choice correct-choice-result"><b>الإجابة الصحيحة:</b><span><?= e((string) $answer['correct_answer']) ?></span></div>
                <?php endif; ?>
                <?php if (!empty($answer['explanation'])): ?>
                    <div class="answer-explanation"><b>التوضيح:</b> <?= nl2br(e($answer['explanation'])) ?></div>
                <?php endif; ?>
            </article>
        <?php endforeach; ?>
    </div>
</section>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
