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

$examTitle = $exam['title'] ?? '';
$passMarks = (int)($exam['pass_marks'] ?? 40);
$totalMarks = (int)($exam['total_marks'] ?? 100);
$duration = (int)($exam['duration_minutes'] ?? 60);

// Aggregate stats
$appeared = count($results);
$passCount = 0; $failCount = 0; $totalPct = 0;
foreach ($results as $r) {
    if (($r['status'] ?? '') === 'pass') $passCount++; else $failCount++;
    $totalPct += (float)($r['percentage'] ?? 0);
}
$avgPct = $appeared > 0 ? round($totalPct / $appeared, 1) : 0;
$passPct = $appeared > 0 ? round(($passCount / $appeared) * 100, 1) : 0;
?>
<div class="admin-section">
    <div style="margin-bottom:14px;">
        <a href="<?= $bp ?>/branch/exam-results" style="color:#16a085;text-decoration:none;font-size:0.85rem;">← Back to Exam Results</a>
    </div>

    <!-- Exam header -->
    <div style="background:linear-gradient(135deg,#0d3b3b,#16a085);color:#fff;border-radius:12px;padding:20px;margin-bottom:16px;">
        <h2 style="margin:0;font-size:1.1rem;">
            <?= htmlspecialchars($examTitle, ENT_QUOTES, 'UTF-8') ?>
            <?php if (!empty($exam['title_hindi'])): ?>
                <span style="font-weight:400;opacity:0.9;font-family:'Noto Sans Devanagari',sans-serif;"> · <?= htmlspecialchars($exam['title_hindi'], ENT_QUOTES, 'UTF-8') ?></span>
            <?php endif; ?>
        </h2>
        <div style="margin-top:8px;font-size:0.82rem;opacity:0.85;display:flex;flex-wrap:wrap;gap:14px;">
            <span>📝 <?= (int)($exam['question_count'] ?? 0) ?> Questions</span>
            <span>⏱ <?= $duration ?> min</span>
            <span>🏆 <?= $totalMarks ?> marks</span>
            <span>✓ Pass: <?= $passMarks ?></span>
            <?php if (!empty($exam['start_time'])): ?>
                <span>📅 <?= date('d M Y, g:i A', strtotime($exam['start_time'])) ?><?php if (!empty($exam['end_time'])): ?> → <?= date('g:i A', strtotime($exam['end_time'])) ?><?php endif; ?></span>
            <?php endif; ?>
        </div>
    </div>

    <!-- Stats cards -->
    <div style="display:grid;grid-template-columns:repeat(5,1fr);gap:10px;margin-bottom:18px;">
        <div style="background:#fff;border-radius:10px;padding:14px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
            <div style="font-size:1.6rem;font-weight:700;color:#0d3b3b;"><?= $appeared ?></div>
            <div style="font-size:0.72rem;color:#999;text-transform:uppercase;letter-spacing:0.5px;">Appeared</div>
        </div>
        <div style="background:#fff;border-radius:10px;padding:14px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
            <div style="font-size:1.6rem;font-weight:700;color:#27ae60;"><?= $passCount ?></div>
            <div style="font-size:0.72rem;color:#999;text-transform:uppercase;letter-spacing:0.5px;">Passed</div>
        </div>
        <div style="background:#fff;border-radius:10px;padding:14px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
            <div style="font-size:1.6rem;font-weight:700;color:#e84118;"><?= $failCount ?></div>
            <div style="font-size:0.72rem;color:#999;text-transform:uppercase;letter-spacing:0.5px;">Failed</div>
        </div>
        <div style="background:#fff;border-radius:10px;padding:14px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
            <div style="font-size:1.6rem;font-weight:700;color:#16a085;"><?= $passPct ?>%</div>
            <div style="font-size:0.72rem;color:#999;text-transform:uppercase;letter-spacing:0.5px;">Pass Rate</div>
        </div>
        <div style="background:#fff;border-radius:10px;padding:14px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
            <div style="font-size:1.6rem;font-weight:700;color:#1a4fa0;"><?= $avgPct ?>%</div>
            <div style="font-size:0.72rem;color:#999;text-transform:uppercase;letter-spacing:0.5px;">Avg Score</div>
        </div>
    </div>

    <!-- Students table -->
    <div style="background:#fff;border-radius:10px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
        <?php if (empty($results)): ?>
            <div style="text-align:center;padding:50px 20px;color:#999;">
                <p style="margin:0 0 6px;font-size:0.95rem;">No students have appeared in this exam yet.</p>
                <p style="margin:0;font-size:0.82rem;color:#bbb;">Once students take this exam via /branch-exam portal, their results will appear here automatically.</p>
            </div>
        <?php else: ?>
            <table style="width:100%;border-collapse:collapse;font-size:0.82rem;">
                <thead><tr style="background:#f8f9fa;border-bottom:2px solid #dee2e6;">
                    <th style="padding:10px;text-align:left;">#</th>
                    <th style="padding:10px;text-align:left;">Student</th>
                    <th style="padding:10px;text-align:left;">Enrollment</th>
                    <th style="padding:10px;text-align:center;">Score</th>
                    <th style="padding:10px;text-align:center;">%</th>
                    <th style="padding:10px;text-align:center;">Grade</th>
                    <th style="padding:10px;text-align:center;">Result</th>
                    <th style="padding:10px;text-align:center;">Submitted</th>
                    <th style="padding:10px;text-align:center;">Approved</th>
                    <th style="padding:10px;text-align:right;">Actions</th>
                </tr></thead>
                <tbody>
                <?php foreach ($results as $i => $r):
                    $isApproved = !empty($r['branch_approved']);
                    $isPass = ($r['status'] ?? '') === 'pass';
                    $submittedAt = !empty($r['completed_at']) ? date('d M Y, g:i A', strtotime($r['completed_at'])) : '—';
                ?>
                    <tr style="border-bottom:1px solid #f0f0f0;">
                        <td style="padding:10px;color:#999;font-weight:600;"><?= $i + 1 ?></td>
                        <td style="padding:10px;font-weight:600;color:#0d3b3b;">
                            <?= htmlspecialchars($r['student_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                            <?php if (!empty($r['email'])): ?>
                                <br><span style="font-weight:400;color:#999;font-size:0.74rem;"><?= htmlspecialchars($r['email'], ENT_QUOTES, 'UTF-8') ?></span>
                            <?php endif; ?>
                        </td>
                        <td style="padding:10px;font-family:monospace;color:#666;"><?= htmlspecialchars($r['enrollment_no'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                        <td style="padding:10px;text-align:center;font-weight:700;color:#0d3b3b;">
                            <?= (float)$r['total_obtained'] ?> / <?= (float)$r['total_marks'] ?>
                        </td>
                        <td style="padding:10px;text-align:center;font-weight:600;color:#16a085;"><?= (float)$r['percentage'] ?>%</td>
                        <td style="padding:10px;text-align:center;">
                            <span style="background:#eaf0fb;color:#1a4fa0;padding:2px 8px;border-radius:10px;font-size:0.78rem;font-weight:700;"><?= htmlspecialchars($r['grade'] ?? '—', ENT_QUOTES, 'UTF-8') ?></span>
                        </td>
                        <td style="padding:10px;text-align:center;">
                            <?php if ($isPass): ?>
                                <span style="background:#eafaf1;color:#1a7a4f;padding:3px 10px;border-radius:12px;font-size:0.72rem;font-weight:700;">✓ PASS</span>
                            <?php else: ?>
                                <span style="background:#fff5f5;color:#e84118;padding:3px 10px;border-radius:12px;font-size:0.72rem;font-weight:700;">✗ FAIL</span>
                            <?php endif; ?>
                        </td>
                        <td style="padding:10px;text-align:center;font-size:0.74rem;color:#666;"><?= $submittedAt ?></td>
                        <td style="padding:10px;text-align:center;">
                            <?php if ($isApproved): ?>
                                <span style="background:#eafaf1;color:#1a7a4f;padding:2px 8px;border-radius:10px;font-size:0.7rem;font-weight:600;">✓ Approved</span>
                            <?php else: ?>
                                <span style="background:#fff5e6;color:#f39c12;padding:2px 8px;border-radius:10px;font-size:0.7rem;font-weight:600;">⏳ Pending</span>
                            <?php endif; ?>
                        </td>
                        <td style="padding:10px;text-align:right;white-space:nowrap;">
                            <a href="<?= $bp ?>/branch/exam-results/<?= (int)$exam['id'] ?>/<?= (int)$r['result_id'] ?>/edit" style="background:#7f8c8d;color:#fff;text-decoration:none;padding:4px 10px;border-radius:4px;font-size:0.72rem;font-weight:600;">✎ Edit</a>
                            <?php if ($isApproved): ?>
                                <a href="<?= $bp ?>/branch/exam-results/<?= (int)$r['result_id'] ?>/marksheet" style="background:#3498db;color:#fff;text-decoration:none;padding:4px 10px;border-radius:4px;font-size:0.72rem;font-weight:600;" target="_blank">📄 Marksheet</a>
                                <?php if ($isPass): ?>
                                <a href="<?= $bp ?>/branch/exam-results/<?= (int)$r['result_id'] ?>/certificate" style="background:#9b59b6;color:#fff;text-decoration:none;padding:4px 10px;border-radius:4px;font-size:0.72rem;font-weight:600;" target="_blank">🏆 Certificate</a>
                                <?php endif; ?>
                                <form method="POST" action="<?= $bp ?>/branch/exam-results/<?= (int)$r['result_id'] ?>/unapprove" style="display:inline;">
                                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8') ?>">
                                    <button type="submit" style="background:#fff5e6;color:#f39c12;border:1px solid #f5d68b;padding:4px 10px;border-radius:4px;font-size:0.72rem;font-weight:600;cursor:pointer;" onclick="return confirm('Unapprove this result? Marksheet + Certificate will be disabled.');">↩ Unapprove</button>
                                </form>
                            <?php else: ?>
                                <form method="POST" action="<?= $bp ?>/branch/exam-results/<?= (int)$r['result_id'] ?>/approve" style="display:inline;">
                                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8') ?>">
                                    <button type="submit" style="background:#27ae60;color:#fff;border:none;padding:4px 10px;border-radius:4px;font-size:0.72rem;font-weight:600;cursor:pointer;" onclick="return confirm('Approve this result? This will unlock marksheet + certificate downloads.');">✓ Approve</button>
                                </form>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

    <div style="margin-top:16px;padding:14px;background:#eafaf1;border-radius:8px;font-size:0.8rem;color:#0d3b3b;line-height:1.6;">
        <strong>📌 Workflow:</strong>
        <ol style="margin:6px 0 0 18px;padding:0;">
            <li><strong>Edit Score</strong> — override the auto-graded obtained marks if needed (e.g. for grace marks, partial credit, or to fix a wrong-question penalty). Percentage, grade, and pass/fail status are auto-recalculated.</li>
            <li><strong>Approve</strong> — once you're satisfied with the score, click "Approve" to unlock the marksheet + certificate downloads.</li>
            <li><strong>Marksheet</strong> — opens a printable marksheet (use browser Print → Save as PDF).</li>
            <li><strong>Certificate</strong> — opens a printable certificate of completion (only available if the student passed).</li>
        </ol>
    </div>
</div>
