<?php
/**
 * Exam Result Page — Gmind Institute
 *
 * Exam result display with score, pass/fail status, breakdown,
 * attempt navigation, 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
 *   $userName      — logged-in user's name
 *   $studentName   — student display name
 *   $allAttempts   — array of all attempts for this exam by this student
 *   $correct       — number of correct answers
 *   $wrong         — number of wrong answers
 *   $maxAttempts   — maximum allowed attempts
 */

$exam        = $exam        ?? [];
$result      = $result      ?? [];
$questions   = $questions   ?? [];
$userAnswers = $userAnswers ?? [];
$userName    = $userName    ?? '';
$studentName = $studentName ?? '';
$allAttempts = $allAttempts ?? [];
$correct     = $correct     ?? 0;
$wrong       = $wrong       ?? 0;
$maxAttempts = $maxAttempts ?? 3;

$examTitle    = getBilingual($exam, 'title') ?: ($exam['title'] ?? ($result['exam_title'] ?? 'Exam'));
$totalMarks   = (int) ($result['total_marks'] ?? ($exam['total_marks'] ?? 0));
$passMarks    = (int) ($exam['pass_marks'] ?? ($result['exam_pass_marks'] ?? 0));
$obtained     = (float) ($result['total_obtained'] ?? 0);
$percentage   = (float) ($result['percentage'] ?? 0);
$isPassed     = $obtained >= $passMarks;
$totalQ       = count($questions);
$unanswered   = max(0, $totalQ - $correct - $wrong);
$attemptNumber = (int) ($result['attempt_number'] ?? 1);
$currentAttemptId = (int) ($result['id'] ?? 0);
$examId       = (int) ($result['exam_id'] ?? ($exam['id'] ?? 0));
$basePath = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$attemptCount = count($allAttempts);
$canRetake = ($attemptCount < $maxAttempts);
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 ? __('exam.congratulations') : __('exam.keep_trying') ?></h1>
                <p class="result-status"><?= $isPassed ? __('exam.pass') : __('exam.fail') ?></p>
                <p class="result-exam-name"><?= htmlspecialchars($examTitle, ENT_QUOTES, 'UTF-8') ?></p>
                <p class="result-student"><?= __('exam.student') ?>: <?= htmlspecialchars($studentName, ENT_QUOTES, 'UTF-8') ?></p>
                <p style="font-size:0.85rem;color:rgba(255,255,255,0.8);margin-top:4px;"><?= __('exam.attempt') ?> <?= $attemptNumber ?> <?= __('exam.of') ?> <?= $maxAttempts ?></p>
            </div>

            <!-- Attempt Navigation -->
            <?php if (count($allAttempts) > 1): ?>
            <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin:20px 0;padding:14px;background:#fff;border-radius:10px;box-shadow:0 2px 10px rgba(0,0,0,0.06);">
                <span style="font-size:0.85rem;color:#555;font-weight:600;margin-right:4px;"><?= __('exam.view_attempt') ?>:</span>
                <?php foreach ($allAttempts as $attempt): ?>
                    <?php
                    $aId = (int) ($attempt['id'] ?? 0);
                    $aNum = (int) ($attempt['attempt_number'] ?? 0);
                    $aPct = (float) ($attempt['percentage'] ?? 0);
                    $aStatus = $attempt['status'] ?? '';
                    $isActive = ($aId === $currentAttemptId);
                    ?>
                    <a href="<?= $basePath ?>/exam/<?= $examId ?>/result/<?= $aId ?>"
                       style="display:inline-flex;align-items:center;gap:4px;padding:6px 14px;border-radius:50px;font-size:0.8rem;font-weight:600;text-decoration:none;
                       <?= $isActive ? 'background-color:#1a4fa0;color:#fff;' : 'background-color:#f4f7fc;color:#555;' ?>
                       <?= $aStatus === 'pass' ? '' : '' ?>">
                        <?php if ($aStatus === 'pass'): ?>
                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><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="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><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; ?>
                        <?= __('exam.attempt') ?> <?= $aNum ?> (<?= number_format($aPct, 1) ?>%)
                    </a>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <!-- Score Display -->
            <div class="result-score-card">
                <div class="score-circle <?= $isPassed ? 'score-pass' : 'score-fail' ?>">
                    <span class="score-percentage"><?= number_format($percentage, 1) ?>%</span>
                </div>
                <div class="score-details">
                    <div class="score-item">
                        <span class="score-label"><?= __('exam.obtained_marks') ?></span>
                        <span class="score-value"><?= number_format($obtained, 0) ?> / <?= $totalMarks ?></span>
                    </div>
                    <div class="score-item">
                        <span class="score-label"><?= __('exam.pass_marks_label') ?></span>
                        <span class="score-value"><?= $passMarks ?></span>
                    </div>
                    <div class="score-item">
                        <span class="score-label"><?= __('exam.status') ?></span>
                        <span class="score-value <?= $isPassed ? 'text-pass' : 'text-fail' ?>"><?= $isPassed ? __('exam.pass_status') : __('exam.fail_status') ?></span>
                    </div>
                    <div class="score-item">
                        <span class="score-label"><?= __('exam.attempt') ?></span>
                        <span class="score-value"><?= $attemptNumber ?> <?= __('exam.of') ?> <?= $maxAttempts ?></span>
                    </div>
                </div>
            </div>

            <!-- Breakdown -->
            <div class="result-breakdown">
                <h2><?= __('exam.score_breakdown') ?></h2>
                <div class="breakdown-grid">
                    <div class="breakdown-item breakdown-correct">
                        <span class="breakdown-number"><?= $correct ?></span>
                        <span class="breakdown-label"><?= __('exam.correct') ?></span>
                    </div>
                    <div class="breakdown-item breakdown-wrong">
                        <span class="breakdown-number"><?= $wrong ?></span>
                        <span class="breakdown-label"><?= __('exam.wrong') ?></span>
                    </div>
                    <div class="breakdown-item breakdown-unanswered">
                        <span class="breakdown-number"><?= $unanswered ?></span>
                        <span class="breakdown-label"><?= __('exam.unanswered') ?></span>
                    </div>
                </div>
            </div>

            <!-- View Answers (Expandable) -->
            <?php if (!empty($questions)): ?>
            <div class="result-answers-section">
                <details class="result-answers-toggle">
                    <summary>
                        <?= __('exam.view_answers') ?>
                        <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 ? __('exam.correct') : ($userAnswer ? __('exam.wrong') : __('exam.skipped')) ?>
                                    </span>
                                </div>
                                <p class="answer-question"><?= htmlspecialchars(getBilingual($question, 'question_text') ?: ($question['question_text'] ?? ''), ENT_QUOTES, 'UTF-8') ?></p>
                                <div class="answer-options-mini">
                                    <?php
                                    $options = [
                                        'a' => getBilingual($question, 'option_a') ?: ($question['option_a'] ?? ''),
                                        'b' => getBilingual($question, 'option_b') ?: ($question['option_b'] ?? ''),
                                        'c' => getBilingual($question, 'option_c') ?: ($question['option_c'] ?? ''),
                                        'd' => getBilingual($question, 'option_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"><?= __('exam.correct_answer') ?>: <strong><?= strtoupper($correctAnswer) ?></strong></p>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </details>
            </div>
            <?php endif; ?>

            <!-- Action Buttons -->
            <div class="result-actions" style="display:flex;gap:12px;flex-wrap:wrap;justify-content:center;">
                <a href="<?= $basePath ?>/exam" class="btn-primary" style="text-decoration:none;"><?= __('exam.back_to_exams') ?></a>
                <?php if ($canRetake): ?>
                <a href="<?= $basePath ?>/exam/<?= $examId ?>" class="btn-enroll btn-enroll-scarlet" style="text-decoration:none;">
                    <?= __('exam.retake_exam') ?> (<?= __('exam.attempt') ?> <?= $attemptCount + 1 ?> <?= __('exam.of') ?> <?= $maxAttempts ?>)
                </a>
                <?php else: ?>
                <span style="padding:12px 24px;background:#999;color:#fff;border-radius:6px;font-weight:600;font-size:0.92rem;"><?= __('exam.all') ?> <?= $maxAttempts ?> <?= __('exam.attempts_used') ?></span>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

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