<?php
include '../../includes/conn.php';
include '../../includes/functions.php';
requireRole('student');

$student_id = $_SESSION['user_id'] ?? 0;
$exam_id = intval($_GET['exam_id'] ?? 0);

if (!$exam_id) {
    die("<div class='alert alert-danger'>Invalid exam ID.</div>");
}

// Fetch exam result + exam details
$stmt = $pdo->prepare("
    SELECT e.title, e.duration, s.name AS session_name, t.name AS term_name,
           r.started_at, r.submitted_at, r.score
    FROM cbt_exam_results r
    JOIN cbt_exams e ON r.exam_id = e.id
    LEFT JOIN sessions s ON e.session_id = s.id
    LEFT JOIN terms t ON e.term_id = t.id
    WHERE r.exam_id = ? AND r.student_id = ?
");
$stmt->execute([$exam_id, $student_id]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$result) {
    die("<div class='alert alert-warning'>You haven’t submitted this exam yet.</div>");
}

// Fetch student info
$student_stmt = $pdo->prepare("
    SELECT first_name, last_name, username, email, photo, c.name AS class_name
    FROM users u
    LEFT JOIN classroom_students cs ON u.id = cs.student_id
    LEFT JOIN classrooms c ON cs.classroom_id = c.id
    WHERE u.id = ?
");
$student_stmt->execute([$student_id]);
$student = $student_stmt->fetch(PDO::FETCH_ASSOC);

// Fetch all questions + answers
$qa_stmt = $pdo->prepare("
    SELECT q.id, q.question_text, q.option_a, q.option_b, q.option_c, q.option_d, 
           q.correct_option, a.selected_option
    FROM cbt_questions q
    LEFT JOIN cbt_answers a ON q.id = a.question_id AND a.student_id = ? AND a.exam_id = ?
    WHERE q.exam_id = ?
");
$qa_stmt->execute([$student_id, $exam_id, $exam_id]);
$questions = $qa_stmt->fetchAll(PDO::FETCH_ASSOC);

$total_questions = count($questions);
$score = intval($result['score']);
$percentage = $total_questions > 0 ? round(($score / $total_questions) * 100, 2) : 0;

// Prepare photo
$photo = $student['photo'] 
    ? 'data:image/jpeg;base64,' . base64_encode($student['photo'])
    : '../../assets/default-avatar.png';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Exam Result - <?= htmlspecialchars($result['title']) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background-color: #f8f9fa; }
        .correct { background-color: #d4edda; }
        .incorrect { background-color: #f8d7da; }
        .question-card { border-left: 5px solid #0d6efd; }
        .score-box {
            font-size: 1.5rem;
            font-weight: bold;
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            padding: 15px;
        }
    </style>
</head>
<body>
<div class="container mt-4">
    <?php if (isset($_GET['already_submitted'])): ?>
    <div class="alert alert-info text-center">
        You have already submitted this exam. Here are your results.
    </div>
    <?php elseif (isset($_GET['success'])): ?>
        <div class="alert alert-success text-center">
            Exam submitted successfully! Below is your result.
        </div>
    <?php endif; ?>
    <div class="row">
        <!-- Student Info -->
        <div class="col-md-4 mb-3">
            <div class="card shadow-sm">
                <div class="card-body text-center">
                    <?php if (!empty($user['photo'])): ?>
                         <img src="data:image/jpeg;base64,<?php echo base64_encode($user['photo']);?>" 
                        alt="User Photo" 
                        style="width:120; height:120; border-radius:50%; object-fit:cover;">
                        <?php else: ?>
                        <img src="user.png" 
                        alt="Default Photo" 
                        style="width:120; height:120; border-radius:50%; object-fit:cover;">
                    <?php endif; ?>
                    <h5><?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?></h5>
                    <p><strong>Username:</strong> <?= htmlspecialchars($student['username']) ?></p>
                    <p><strong>Class:</strong> <?= htmlspecialchars($student['class_name'] ?? 'N/A') ?></p>
                    <p><strong>Email:</strong> <?= htmlspecialchars($student['email']) ?></p>
                </div>
            </div>
            <div class="score-box mt-3 text-center">
                <p><strong>Score:</strong> <?= $score ?> / <?= $total_questions ?></p>
                <p><strong>Percentage:</strong> <?= $percentage ?>%</p>
            </div>
        </div>

        <!-- Exam Summary -->
        <div class="col-md-8">
            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h4><?= htmlspecialchars($result['title']) ?></h4>
                    <small class="text-muted">
                        (Session: <?= htmlspecialchars($result['session_name'] ?? 'N/A') ?>,
                        Term: <?= htmlspecialchars($result['term_name'] ?? 'N/A') ?>)
                    </small>
                    <p class="mt-2 mb-1"><strong>Duration:</strong> <?= htmlspecialchars($result['duration']) ?> minutes</p>
                    <p class="mb-1"><strong>Started:</strong> <?= htmlspecialchars($result['started_at']) ?></p>
                    <p class="mb-3"><strong>Submitted:</strong> <?= htmlspecialchars($result['submitted_at']) ?></p>
                </div>
            </div>

            <!-- Question Results -->
            <?php foreach ($questions as $index => $q): 
                $is_correct = $q['selected_option'] === $q['correct_option'];
                $css_class = $q['selected_option'] ? ($is_correct ? 'correct' : 'incorrect') : '';
            ?>
                <div class="card mb-3 shadow-sm question-card <?= $css_class ?>">
                    <div class="card-body">
                        <p><strong>Q<?= $index+1 ?>:</strong> <?= htmlspecialchars($q['question_text']) ?></p>
                        <?php foreach(['a','b','c','d'] as $opt): ?>
                            <?php
                                $option_text = htmlspecialchars($q['option_'.$opt]);
                                $is_selected = $q['selected_option'] === $opt;
                                $is_answer = $q['correct_option'] === $opt;
                                $badge = '';
                                if ($is_answer) $badge = '<span class="badge bg-success">Correct</span>';
                                elseif ($is_selected && !$is_answer) $badge = '<span class="badge bg-danger">Your choice</span>';
                            ?>
                            <p class="<?= $is_selected ? 'fw-bold' : '' ?>">
                                <?= strtoupper($opt) ?>. <?= $option_text ?> <?= $badge ?>
                            </p>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>
</body>
</html>
