<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/rbac.php';
require_once '../includes/functions.php';
require_once '../includes/middleware.php';

// Check if user is student or higher
studentOrHigher();

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

$attemptId = intval($_GET['id'] ?? 0);
if (!$attemptId) {
    header('Location: ../student/exams.php');
    exit;
}

// Get attempt details with exam info
$stmt = $db->prepare("
    SELECT ea.*, e.title as exam_title, e.description as exam_description,
           e.passing_score, c.title as course_title, e.time_limit
    FROM exam_attempts ea
    JOIN exams e ON ea.exam_id = e.id
    LEFT JOIN courses c ON e.course_id = c.id
    WHERE ea.id = ? AND ea.student_id = ?
");
$stmt->execute([$attemptId, $userId]);
$attempt = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$attempt) {
    die('Attempt not found or access denied.');
}

$page_title = 'Exam Review - ' . htmlspecialchars($attempt['exam_title']);
$use_tailwind = true;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?> | Mutalex Academy</title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Configure Tailwind -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A',
                        'background-light': '#F8FAFC',
                        'text-dark': '#1F2937',
                        'accent-subtle': '#E5E7EB',
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        html, body { height: 100%; }
        ::-webkit-scrollbar { width: 8px; height: 8px; }
        ::-webkit-scrollbar-thumb { background-color: #D1D5DB; border-radius: 4px; }
        ::-webkit-scrollbar-track { background-color: transparent; }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

    <div class="min-h-screen flex flex-col">
        <!-- Header -->
        <header class="bg-white shadow-sm border-b border-accent-subtle">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
                <div class="flex justify-between items-center">
                    <div>
                        <h1 class="text-2xl font-bold text-text-dark">Exam Review</h1>
                        <p class="text-sm text-gray-600"><?php echo htmlspecialchars($attempt['exam_title']); ?></p>
                    </div>
                    <a href="../student/exams.php" class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition">
                        Back to My Exams
                    </a>
                </div>
            </header>

        <!-- Main Content -->
        <main class="flex-1 overflow-y-auto">
            <div class="max-w-4xl mx-auto p-6">
                <!-- Exam Summary -->
                <div class="bg-white rounded-xl shadow-sm border border-accent-subtle p-6 mb-6">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
                        <div class="text-center">
                            <div class="text-3xl font-bold <?php echo $attempt['percentage'] >= $attempt['passing_score'] ? 'text-green-600' : 'text-red-600'; ?>">
                                <?php echo round($attempt['percentage']); ?>%
                            </div>
                            <div class="text-sm text-gray-600">Score</div>
                        </div>
                        <div class="text-center">
                            <div class="text-3xl font-bold text-primary-blue">
                                <?php echo $attempt['score']; ?>/<?php echo $attempt['max_score']; ?>
                            </div>
                            <div class="text-sm text-gray-600">Points</div>
                        </div>
                        <div class="text-center">
                            <div class="text-3xl font-bold <?php echo $attempt['is_passed'] ? 'text-green-600' : 'text-red-600'; ?>">
                                <?php echo $attempt['is_passed'] ? 'PASSED' : 'FAILED'; ?>
                            </div>
                            <div class="text-sm text-gray-600">Result</div>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 text-sm">
                        <div>
                            <span class="font-medium text-gray-700">Course:</span>
                            <span class="text-gray-600"><?php echo htmlspecialchars($attempt['course_title'] ?? 'N/A'); ?></span>
                        </div>
                        <div>
                            <span class="font-medium text-gray-700">Attempt:</span>
                            <span class="text-gray-600">#<?php echo $attempt['attempt_number']; ?></span>
                        </div>
                        <div>
                            <span class="font-medium text-gray-700">Started:</span>
                            <span class="text-gray-600"><?php echo date('M j, Y H:i', strtotime($attempt['started_at'])); ?></span>
                        </div>
                        <div>
                            <span class="font-medium text-gray-700">Completed:</span>
                            <span class="text-gray-600"><?php echo $attempt['completed_at'] ? date('M j, Y H:i', strtotime($attempt['completed_at'])) : 'N/A'; ?></span>
                        </div>
                        <div>
                            <span class="font-medium text-gray-700">Time Spent:</span>
                            <span class="text-gray-600"><?php echo gmdate('H:i:s', $attempt['time_spent']); ?></span>
                        </div>
                        <div>
                            <span class="font-medium text-gray-700">Time Limit:</span>
                            <span class="text-gray-600"><?php echo $attempt['time_limit'] ? $attempt['time_limit'] . ' min' : 'No limit'; ?></span>
                        </div>
                    </div>
                </div>

                <!-- Questions Review -->
                <div class="space-y-6">
                    <h2 class="text-xl font-semibold text-gray-800">Question Review</h2>

                    <?php
                    // Get questions and answers
                    $stmt = $db->prepare("
                        SELECT q.*, eq.points,
                               JSON_UNQUOTE(JSON_EXTRACT(ea.answers, CONCAT('$.', q.id))) as student_answer
                        FROM exam_questions eq
                        JOIN questions q ON eq.question_id = q.id
                        LEFT JOIN exam_attempts ea ON ea.id = ?
                        WHERE eq.exam_id = ?
                        ORDER BY eq.sort_order
                    ");
                    $stmt->execute([$attemptId, $attempt['exam_id']]);
                    $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

                    foreach ($questions as $index => $question):
                        // Get correct options
                        $stmt = $db->prepare("SELECT * FROM question_options WHERE question_id = ? ORDER BY sort_order");
                        $stmt->execute([$question['id']]);
                        $options = $stmt->fetchAll(PDO::FETCH_ASSOC);

                        // Parse student answer
                        $studentAnswer = json_decode($question['student_answer'], true);
                        if (is_string($studentAnswer)) {
                            $studentAnswer = [$studentAnswer];
                        }

                        // Calculate if answer is correct
                        $isCorrect = false;
                        $correctOptions = array_filter($options, fn($opt) => $opt['is_correct']);

                        if ($question['question_type'] === 'mcq_single' || $question['question_type'] === 'true_false') {
                            $isCorrect = !empty($studentAnswer) && isset($correctOptions[$studentAnswer[0] ?? '']);
                        } elseif ($question['question_type'] === 'mcq_multiple') {
                            $correctIds = array_column($correctOptions, 'id');
                            $isCorrect = !empty($studentAnswer) && empty(array_diff($correctIds, $studentAnswer)) && empty(array_diff($studentAnswer, $correctIds));
                        }
                    ?>
                        <div class="bg-white rounded-xl shadow-sm border border-accent-subtle p-6">
                            <div class="flex justify-between items-start mb-4">
                                <h3 class="text-lg font-semibold text-gray-800">Question <?php echo $index + 1; ?></h3>
                                <div class="flex items-center space-x-2">
                                    <span class="text-sm text-gray-500"><?php echo $question['points']; ?> points</span>
                                    <span class="px-2 py-1 text-xs font-medium rounded-full <?php echo $isCorrect ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                                        <?php echo $isCorrect ? 'Correct' : 'Incorrect'; ?>
                                    </span>
                                </div>
                            </div>

                            <div class="mb-4">
                                <div class="prose max-w-none">
                                    <?php echo nl2br(htmlspecialchars($question['content'])); ?>
                                </div>
                            </div>

                            <div class="space-y-2">
                                <?php if (in_array($question['question_type'], ['mcq_single', 'mcq_multiple', 'true_false'])): ?>
                                    <?php foreach ($options as $option): ?>
                                        <div class="flex items-center space-x-3 p-2 rounded-lg <?php
                                            $isSelected = in_array($option['id'], $studentAnswer ?? []);
                                            $isCorrectOption = $option['is_correct'];
                                            if ($isSelected && $isCorrectOption) echo 'bg-green-50 border border-green-200';
                                            elseif ($isSelected && !$isCorrectOption) echo 'bg-red-50 border border-red-200';
                                            elseif (!$isSelected && $isCorrectOption) echo 'bg-green-50 border border-green-200';
                                        ?>">
                                            <div class="flex items-center space-x-2">
                                                <?php if ($question['question_type'] === 'mcq_multiple'): ?>
                                                    <input type="checkbox" <?php echo $isSelected ? 'checked' : ''; ?> disabled class="text-primary-blue">
                                                <?php else: ?>
                                                    <input type="radio" <?php echo $isSelected ? 'checked' : ''; ?> disabled class="text-primary-blue">
                                                <?php endif; ?>
                                                <span class="<?php echo $isCorrectOption ? 'font-semibold text-green-700' : 'text-gray-700'; ?>">
                                                    <?php echo htmlspecialchars($option['option_text']); ?>
                                                    <?php if ($isCorrectOption): ?>
                                                        <span class="text-green-600 ml-2">(Correct)</span>
                                                    <?php endif; ?>
                                                </span>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>

                                <?php elseif (in_array($question['question_type'], ['essay', 'short_answer', 'code'])): ?>
                                    <div class="bg-gray-50 p-4 rounded-lg">
                                        <h4 class="font-medium text-gray-800 mb-2">Your Answer:</h4>
                                        <div class="text-gray-700 <?php echo $question['question_type'] === 'code' ? 'font-mono text-sm' : ''; ?>">
                                            <?php echo nl2br(htmlspecialchars($studentAnswer[0] ?? 'No answer provided')); ?>
                                        </div>
                                    </div>
                                    <?php if (!empty($correctOptions)): ?>
                                        <div class="bg-green-50 p-4 rounded-lg border border-green-200">
                                            <h4 class="font-medium text-green-800 mb-2">Correct Answer:</h4>
                                            <div class="text-green-700">
                                                <?php echo nl2br(htmlspecialchars($correctOptions[0]['option_text'] ?? 'Manual grading required')); ?>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </main>
    </div>
</body>
</html>