<?php
$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$exam = $exam ?? [];
$result = $result ?? [];
$questions = $questions ?? [];
$answers = $answers ?? [];
$csrfToken = $csrfToken ?? '';

$currentObtained = (float)($result['total_obtained'] ?? 0);
$totalMarks = (float)($result['total_marks'] ?? 0);
$currentPct = (float)($result['percentage'] ?? 0);
$passMarks = (float)($exam['pass_marks'] ?? 40);
$currentStatus = $result['status'] ?? 'fail';

// Calculate per-question correct/wrong summary
$correct = 0; $wrong = 0; $unanswered = 0;
foreach ($questions as $q) {
    $qid = (int)$q['id'];
    $given = $answers[$qid] ?? null;
    if ($given === null) { $unanswered++; continue; }
    if ($given === $q['correct_answer']) $correct++;
    else $wrong++;
}
?>
<div class="admin-section">
    <div style="margin-bottom:14px;">
        <a href="<?= $bp ?>/branch/exam-results/<?= (int)$exam['id'] ?>" style="color:#16a085;text-decoration:none;font-size:0.85rem;">← Back to Results</a>
    </div>

    <!-- Student info banner -->
    <div style="background:linear-gradient(135deg,#0d3b3b,#16a085);color:#fff;border-radius:12px;padding:20px;margin-bottom:16px;">
        <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:14px;">
            <div>
                <h2 style="margin:0;font-size:1.1rem;">✎ Edit Score — <?= htmlspecialchars($result['student_name'] ?? '', ENT_QUOTES, 'UTF-8') ?></h2>
                <p style="margin:6px 0 0;opacity:0.9;font-size:0.84rem;">
                    <?= htmlspecialchars($exam['title'] ?? '', ENT_QUOTES, 'UTF-8') ?> ·
                    Enrollment: <strong><?= htmlspecialchars($result['enrollment_no'] ?? '', ENT_QUOTES, 'UTF-8') ?></strong> ·
                    Course: <strong><?= htmlspecialchars($result['course_name'] ?? '—', ENT_QUOTES, 'UTF-8') ?></strong>
                </p>
            </div>
            <div style="text-align:right;font-size:0.8rem;opacity:0.85;">
                <div>Submitted: <?= !empty($result['completed_at']) ? date('d M Y, g:i A', strtotime($result['completed_at'])) : '—' ?></div>
            </div>
        </div>
    </div>

    <!-- Auto-grading summary -->
    <div style="background:#fff;border-radius:10px;padding:18px;margin-bottom:16px;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
        <h3 style="margin:0 0 12px;font-size:0.95rem;color:#0d3b3b;">📋 Auto-Grading Summary</h3>
        <div style="display:grid;grid-template-columns:repeat(5,1fr);gap:10px;text-align:center;">
            <div style="padding:10px;background:#f9f9f9;border-radius:8px;">
                <div style="font-size:1.4rem;font-weight:700;color:#0d3b3b;"><?= count($questions) ?></div>
                <div style="font-size:0.7rem;color:#999;text-transform:uppercase;">Total Qs</div>
            </div>
            <div style="padding:10px;background:#eafaf1;border-radius:8px;">
                <div style="font-size:1.4rem;font-weight:700;color:#27ae60;"><?= $correct ?></div>
                <div style="font-size:0.7rem;color:#999;text-transform:uppercase;">Correct</div>
            </div>
            <div style="padding:10px;background:#fff5f5;border-radius:8px;">
                <div style="font-size:1.4rem;font-weight:700;color:#e84118;"><?= $wrong ?></div>
                <div style="font-size:0.7rem;color:#999;text-transform:uppercase;">Wrong</div>
            </div>
            <div style="padding:10px;background:#fff5e6;border-radius:8px;">
                <div style="font-size:1.4rem;font-weight:700;color:#f39c12;"><?= $unanswered ?></div>
                <div style="font-size:0.7rem;color:#999;text-transform:uppercase;">Unanswered</div>
            </div>
            <div style="padding:10px;background:#eaf0fb;border-radius:8px;">
                <div style="font-size:1.4rem;font-weight:700;color:#1a4fa0;"><?= $currentObtained ?>/<?= $totalMarks ?></div>
                <div style="font-size:0.7rem;color:#999;text-transform:uppercase;">Score</div>
            </div>
        </div>
    </div>

    <!-- Question-by-question review -->
    <?php if (!empty($questions)): ?>
    <div style="background:#fff;border-radius:10px;padding:18px;margin-bottom:16px;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
        <h3 style="margin:0 0 12px;font-size:0.95rem;color:#0d3b3b;">🔍 Question-by-Question Review</h3>
        <div style="max-height:400px;overflow-y:auto;">
            <?php foreach ($questions as $i => $q):
                $qid = (int)$q['id'];
                $given = $answers[$qid] ?? null;
                $isCorrect = ($given !== null && $given === $q['correct_answer']);
                $isWrong = ($given !== null && $given !== $q['correct_answer']);
            ?>
            <div style="padding:10px;border-bottom:1px solid #f0f0f0;font-size:0.82rem;">
                <div style="display:flex;justify-content:space-between;align-items:start;gap:10px;">
                    <div style="flex:1;">
                        <div style="font-weight:600;color:#0d3b3b;"><?= $i + 1 ?>. <?= htmlspecialchars($q['question_text'] ?? '', ENT_QUOTES, 'UTF-8') ?></div>
                        <div style="margin-top:4px;color:#666;font-size:0.78rem;">
                            <span style="color:#27ae60;">✓ Correct: <?= strtoupper($q['correct_answer']) ?>. <?= htmlspecialchars($q['option_' . $q['correct_answer']] ?? '', ENT_QUOTES, 'UTF-8') ?></span>
                        </div>
                        <div style="margin-top:2px;font-size:0.78rem;">
                            Student answered:
                            <?php if ($given === null): ?>
                                <span style="color:#f39c12;font-weight:600;">— (no answer)</span>
                            <?php elseif ($isCorrect): ?>
                                <span style="color:#27ae60;font-weight:600;"><?= strtoupper($given) ?>. <?= htmlspecialchars($q['option_' . $given] ?? '', ENT_QUOTES, 'UTF-8') ?></span>
                            <?php else: ?>
                                <span style="color:#e84118;font-weight:600;"><?= strtoupper($given) ?>. <?= htmlspecialchars($q['option_' . $given] ?? '', ENT_QUOTES, 'UTF-8') ?></span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div>
                        <?php if ($isCorrect): ?>
                            <span style="background:#eafaf1;color:#27ae60;padding:2px 8px;border-radius:10px;font-size:0.72rem;font-weight:600;">✓ +<?= (int)$q['marks'] ?></span>
                        <?php elseif ($isWrong): ?>
                            <span style="background:#fff5f5;color:#e84118;padding:2px 8px;border-radius:10px;font-size:0.72rem;font-weight:600;">✗ 0</span>
                        <?php else: ?>
                            <span style="background:#fff5e6;color:#f39c12;padding:2px 8px;border-radius:10px;font-size:0.72rem;font-weight:600;">— 0</span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Edit form -->
    <form method="POST" action="<?= $bp ?>/branch/exam-results/<?= (int)$exam['id'] ?>/<?= (int)$result['id'] ?>">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8') ?>">
        <div style="background:#fff;border-radius:12px;padding:24px;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
            <h3 style="margin:0 0 16px;font-size:1.05rem;color:#0d3b3b;">✎ Override Score</h3>
            <p style="margin:0 0 14px;font-size:0.82rem;color:#666;">Use this to manually adjust the obtained marks (e.g. for grace marks, partial credit, or to fix a wrong-question penalty). Percentage, grade, and pass/fail status will be auto-recalculated.</p>

            <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:14px;margin-bottom:16px;">
                <div>
                    <label style="display:block;font-size:0.78rem;font-weight:600;color:#0d3b3b;margin-bottom:4px;">Obtained Marks *</label>
                    <input type="number" name="total_obtained" id="obtainedInput" value="<?= $currentObtained ?>" min="0" max="<?= $totalMarks ?>" step="0.5" required
                           style="width:100%;padding:10px;border:1px solid #ddd;border-radius:6px;font-size:0.92rem;font-weight:600;color:#0d3b3b;font-family:monospace;">
                    <small style="color:#999;font-size:0.74rem;">Range: 0 to <?= $totalMarks ?></small>
                </div>
                <div>
                    <label style="display:block;font-size:0.78rem;font-weight:600;color:#0d3b3b;margin-bottom:4px;">Total Marks</label>
                    <input type="text" value="<?= $totalMarks ?>" readonly style="width:100%;padding:10px;border:1px solid #eee;border-radius:6px;font-size:0.92rem;color:#999;background:#f9f9f9;font-family:monospace;">
                </div>
                <div>
                    <label style="display:block;font-size:0.78rem;font-weight:600;color:#0d3b3b;margin-bottom:4px;">Pass Marks</label>
                    <input type="text" value="<?= $passMarks ?>" readonly style="width:100%;padding:10px;border:1px solid #eee;border-radius:6px;font-size:0.92rem;color:#999;background:#f9f9f9;font-family:monospace;">
                </div>
                <div>
                    <label style="display:block;font-size:0.78rem;font-weight:600;color:#0d3b3b;margin-bottom:4px;">New % (auto)</label>
                    <input type="text" id="pctDisplay" value="<?= $currentPct ?>%" readonly style="width:100%;padding:10px;border:1px solid #eee;border-radius:6px;font-size:0.92rem;color:#16a085;background:#eafaf1;font-weight:700;font-family:monospace;">
                </div>
            </div>

            <div style="margin-bottom:16px;">
                <label style="display:block;font-size:0.78rem;font-weight:600;color:#0d3b3b;margin-bottom:4px;">Admin Remarks (optional)</label>
                <textarea name="admin_remarks" rows="2" placeholder="e.g. Grace marks given for Q5 due to ambiguous wording" style="width:100%;padding:10px;border:1px solid #ddd;border-radius:6px;font-size:0.86rem;resize:vertical;"><?= htmlspecialchars($result['admin_remarks'] ?? '', ENT_QUOTES, 'UTF-8') ?></textarea>
            </div>

            <!-- Live preview -->
            <div id="previewBox" style="padding:14px;background:#f9f9f9;border-radius:8px;font-size:0.84rem;color:#444;line-height:1.6;">
                <strong>Preview:</strong> Score <span id="previewScore"><?= $currentObtained ?>/<?= $totalMarks ?></span> ·
                Percentage <span id="previewPct" style="color:#16a085;font-weight:700;"><?= $currentPct ?>%</span> ·
                Grade <span id="previewGrade" style="color:#1a4fa0;font-weight:700;"></span> ·
                Status <span id="previewStatus" style="font-weight:700;"><?= $currentStatus === 'pass' ? 'PASS ✓' : 'FAIL ✗' ?></span>
            </div>

            <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:18px;">
                <a href="<?= $bp ?>/branch/exam-results/<?= (int)$exam['id'] ?>" style="padding:12px 24px;border:1px solid #ddd;border-radius:8px;text-decoration:none;color:#666;font-weight:600;font-size:0.9rem;">Cancel</a>
                <button type="submit" style="padding:12px 28px;background:linear-gradient(135deg,#16a085,#117a65);color:#fff;border:none;border-radius:8px;font-weight:600;font-size:0.9rem;cursor:pointer;">💾 Save Updated Score</button>
            </div>
        </div>
    </form>
</div>

<script>
(function() {
    var obtInput = document.getElementById('obtainedInput');
    var pctDisplay = document.getElementById('pctDisplay');
    var previewScore = document.getElementById('previewScore');
    var previewPct = document.getElementById('previewPct');
    var previewGrade = document.getElementById('previewGrade');
    var previewStatus = document.getElementById('previewStatus');
    var totalMarks = <?= $totalMarks ?>;
    var passMarks = <?= $passMarks ?>;

    function updatePreview() {
        var obt = parseFloat(obtInput.value) || 0;
        if (obt < 0) obt = 0;
        if (obt > totalMarks) obt = totalMarks;
        var pct = totalMarks > 0 ? ((obt / totalMarks) * 100).toFixed(1) : 0;
        var grade = 'F';
        if (pct >= 90) grade = 'A+';
        else if (pct >= 80) grade = 'A';
        else if (pct >= 70) grade = 'B+';
        else if (pct >= 60) grade = 'B';
        else if (pct >= 45) grade = 'C';
        else if (pct >= 33) grade = 'D';
        var status = (obt >= passMarks || pct >= 33) ? 'PASS ✓' : 'FAIL ✗';
        var statusColor = (obt >= passMarks || pct >= 33) ? '#27ae60' : '#e84118';

        pctDisplay.value = pct + '%';
        previewScore.textContent = obt + '/' + totalMarks;
        previewPct.textContent = pct + '%';
        previewGrade.textContent = grade;
        previewStatus.textContent = status;
        previewStatus.style.color = statusColor;
    }

    obtInput.addEventListener('input', updatePreview);
    updatePreview();
})();
</script>
