<?php
/**
 * Exam Result Page — Gmind Institute
 *
 * Exam result display with score, pass/fail status, breakdown,
 * expandable answer section, and back button.
 *
 * Expected PHP variables:
 *   $exam          — exam record array
 *   $result        — result record with score details
 *   $questions     — array of exam questions with correct answers
 *   $userAnswers   — array of user's answers keyed by question index
 *   $csrfToken     — CSRF token string
 *   $currentPage   — string 'online-exam'
 *   $title         — page title
 */

$exam        = $exam        ?? [];
$result      = $result      ?? [];
$questions   = $questions   ?? [];
$userAnswers = $userAnswers ?? [];

$examTitle    = $exam['title']       ?? 'Exam';
$totalMarks   = (int) ($exam['total_marks'] ?? 0);
$passMarks    = (int) ($exam['pass_marks'] ?? 0);
$obtained     = (float) ($result['obtained_marks'] ?? 0);
$percentage   = $totalMarks > 0 ? round(($obtained / $totalMarks) * 100, 1) : 0;
$isPassed     = $obtained >= $passMarks;
$studentName  = $result['student_name'] ?? 'Student';
$totalQ       = count($questions);
$correct      = (int) ($result['correct_answers'] ?? 0);
$wrong        = (int) ($result['wrong_answers'] ?? 0);
$unanswered   = $totalQ - $correct - $wrong;
?>

<?php include __DIR__ . '/../layouts/header.php'; ?>

<!-- ============================================================
     Exam Result Section
     ============================================================ -->
<section class="exam-result-section section-offwhite" aria-label="Exam result">
    <div class="container">
        <div class="result-wrapper">
            <!-- Result Header -->
            <div class="result-header <?= $isPassed ? 'result-pass' : 'result-fail' ?>">
                <div class="result-icon" aria-hidden="true">
                    <?php if ($isPassed): ?>
                    <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
                    <?php else: ?>
                    <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
                    <?php endif; ?>
                </div>
                <h1><?= $isPassed ? 'Congratulations!' : 'Keep Trying!' ?></h1>
                <p class="result-status"><?= $isPassed ? 'You have passed the exam.' : 'You did not pass this time. Review and try again.' ?></p>
                <p class="result-exam-name"><?= htmlspecialchars($examTitle, ENT_QUOTES, 'UTF-8') ?></p>
                <p class="result-student">Student: <?= htmlspecialchars($studentName, ENT_QUOTES, 'UTF-8') ?></p>
            </div>

            <!-- Score Display -->
            <div class="result-score-card">
                <div class="score-circle <?= $isPassed ? 'score-pass' : 'score-fail' ?>">
                    <span class="score-percentage"><?= $percentage ?>%</span>
                </div>
                <div class="score-details">
                    <div class="score-item">
                        <span class="score-label">Obtained Marks</span>
                        <span class="score-value"><?= number_format($obtained, 0) ?> / <?= $totalMarks ?></span>
                    </div>
                    <div class="score-item">
                        <span class="score-label">Pass Marks</span>
                        <span class="score-value"><?= $passMarks ?></span>
                    </div>
                    <div class="score-item">
                        <span class="score-label">Status</span>
                        <span class="score-value <?= $isPassed ? 'text-pass' : 'text-fail' ?>"><?= $isPassed ? 'PASS' : 'FAIL' ?></span>
                    </div>
                </div>
            </div>

            <!-- Breakdown -->
            <div class="result-breakdown">
                <h2>Score Breakdown</h2>
                <div class="breakdown-grid">
                    <div class="breakdown-item breakdown-correct">
                        <span class="breakdown-number"><?= $correct ?></span>
                        <span class="breakdown-label">Correct Answers</span>
                    </div>
                    <div class="breakdown-item breakdown-wrong">
                        <span class="breakdown-number"><?= $wrong ?></span>
                        <span class="breakdown-label">Wrong Answers</span>
                    </div>
                    <div class="breakdown-item breakdown-unanswered">
                        <span class="breakdown-number"><?= $unanswered ?></span>
                        <span class="breakdown-label">Unanswered</span>
                    </div>
                </div>
            </div>

            <!-- View Answers (Expandable) -->
            <?php if (!empty($questions)): ?>
            <div class="result-answers-section">
                <details class="result-answers-toggle">
                    <summary>
                        View Answers &amp; Explanations
                        <span class="faq-chevron" aria-hidden="true"></span>
                    </summary>
                    <div class="result-answers-list">
                        <?php foreach ($questions as $index => $question): ?>
                            <?php
                            $userAnswer = $userAnswers[$index] ?? null;
                            $correctAnswer = $question['correct_answer'] ?? '';
                            $isCorrect = ($userAnswer === $correctAnswer);
                            ?>
                            <div class="answer-item <?= $isCorrect ? 'answer-correct' : 'answer-incorrect' ?>">
                                <div class="answer-header">
                                    <span class="answer-q-num">Q<?= $index + 1 ?></span>
                                    <span class="answer-status-badge <?= $isCorrect ? 'badge-correct' : ($userAnswer ? 'badge-wrong' : 'badge-skipped') ?>">
                                        <?= $isCorrect ? 'Correct' : ($userAnswer ? 'Wrong' : 'Skipped') ?>
                                    </span>
                                </div>
                                <p class="answer-question"><?= htmlspecialchars($question['question_text'] ?? '', ENT_QUOTES, 'UTF-8') ?></p>
                                <div class="answer-options-mini">
                                    <?php
                                    $options = [
                                        'a' => $question['option_a'] ?? '',
                                        'b' => $question['option_b'] ?? '',
                                        'c' => $question['option_c'] ?? '',
                                        'd' => $question['option_d'] ?? '',
                                    ];
                                    ?>
                                    <?php foreach ($options as $key => $option): ?>
                                    <?php if (!empty($option)): ?>
                                    <span class="answer-option <?= $key === $correctAnswer ? 'option-correct' : '' ?><?= $key === $userAnswer && $key !== $correctAnswer ? 'option-wrong' : '' ?>">
                                        <strong><?= strtoupper($key) ?>.</strong> <?= htmlspecialchars($option, ENT_QUOTES, 'UTF-8') ?>
                                    </span>
                                    <?php endif; ?>
                                    <?php endforeach; ?>
                                </div>
                                <?php if (!$isCorrect): ?>
                                <p class="answer-correct-note">Correct Answer: <strong><?= strtoupper($correctAnswer) ?></strong></p>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </details>
            </div>
            <?php endif; ?>

            <!-- Back Button -->
            <div class="result-actions">
                <a href="<?= url('/exam') ?>" class="btn-primary">Back to Exams</a>
            </div>
        </div>
    </div>
</section>

<?php include __DIR__ . '/../layouts/footer.php'; ?>
