<?php
require_once('source/dbconfig.php');
require_once('source/function.php');
session_start();

// Verify student is logged in
if (!isset($_SESSION['student'])) {
    header("Location: cbt_index.php");
    exit();
}

// Get result ID from URL
$result_id = $_GET['result_id'] ?? 0;

try {
    // 1. Get the basic result information
    $stmt = $DBH->prepare("
        SELECT * FROM tbl_cbt_results 
        WHERE id = :result_id 
        AND registration_no = :reg_no
    ");
    $stmt->execute([
        'result_id' => $result_id,
        'reg_no' => $_SESSION['student']['registration_no']
    ]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$result) {
        throw new Exception("Exam result not found");
    }

    // 2. Decode the answers
    $studentAnswers = json_decode($result['answers'], true);
    $questionIds = array_keys($studentAnswers);

    // 3. Get all questions with correct answers
    $placeholders = implode(',', array_fill(0, count($questionIds), '?'));
    $stmt = $DBH->prepare("
        SELECT id, question_text, option_a, option_b, option_c, option_d, correct_answer, file_path
        FROM tbl_question
        WHERE id IN ($placeholders)
    ");
    $stmt->execute($questionIds);
    $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Organize questions by ID for easy access
    $questionData = [];
    foreach ($questions as $question) {
        $questionData[$question['id']] = $question;
    }

} catch (Exception $e) {
    die("Error: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exam Details - BKMS-BLC CBT Portal</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .result-container {
            max-width: 800px;
            margin: 2rem auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .result-header {
            background-color: #2e7d32;
            color: white;
            padding: 1.5rem;
        }
        .question-card {
            border-left: 4px solid #dee2e6;
            margin-bottom: 1.5rem;
            transition: all 0.3s ease;
        }
        .question-card.correct {
            border-left-color: #28a745;
            background-color: #f8fff8;
        }
        .question-card.incorrect {
            border-left-color: #dc3545;
            background-color: #fff8f8;
        }
        .option-label {
            display: block;
            padding: 10px 15px;
            margin: 5px 0;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            cursor: default;
        }
        .correct-answer {
            background-color: #d4edda;
            border-color: #c3e6cb;
        }
        .student-answer {
            background-color: #f8d7da;
            border-color: #f5c6cb;
        }
        .student-correct {
            background-color: #d4edda;
            border-color: #c3e6cb;
        }
        .question-media {
            margin-bottom: 15px;
            text-align: center;
        }
        .question-media img, .question-media video {
            max-width: 100%;
            max-height: 300px;
            border-radius: 8px;
        }
        .badge-score {
            font-size: 0.9rem;
            padding: 5px 10px;
        }
        .explanation {
            padding: 10px;
            margin-top: 10px;
            border-radius: 5px;
            background-color: #e2e3e5;
        }
    </style>
</head>
<body>
    <div class="result-container">
        <div class="result-header">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h2><i class="bi bi-card-checklist"></i> Exam Details</h2>
                    <p class="mb-0"><?= htmlspecialchars($result['subject']) ?></p>
                </div>
                <div class="text-end">
                    <span class="badge bg-light text-dark fs-6">
                        Score: <?= $result['score'] ?>%
                    </span>
                </div>
            </div>
            <div class="d-flex justify-content-between mt-2">
                <small>
                    <i class="bi bi-person"></i> <?= htmlspecialchars($_SESSION['student']['fullname']) ?>
                </small>
                <small>
                    <i class="bi bi-calendar"></i> <?= date('F j, Y', strtotime($result['date_taken'])) ?>
                </small>
            </div>
        </div>

        <div class="p-4">
            <div class="d-flex justify-content-between mb-4">
                <div>
                    <span class="badge bg-primary"><?= htmlspecialchars($result['class']) ?></span>
                    <span class="badge bg-info"><?= htmlspecialchars($result['term']) ?></span>
                    <span class="badge bg-success"><?= htmlspecialchars($result['session']) ?></span>
                </div>
                <div>
                    <span class="badge-score bg-success">
                        <i class="bi bi-check-circle"></i> <?= $result['correct_answers'] ?> Correct
                    </span>
                    <span class="badge-score bg-danger">
                        <i class="bi bi-x-circle"></i> <?= $result['total_questions'] - $result['correct_answers'] ?> Incorrect
                    </span>
                </div>
            </div>

            <h5 class="mb-3"><i class="bi bi-question-circle"></i> Question Breakdown</h5>
            
            <?php foreach ($questionData as $questionId => $question): 
                $studentAnswer = $studentAnswers[$questionId] ?? null;
                $isCorrect = ($studentAnswer === $question['correct_answer']);
                $optionLabels = ['A' => 'option_a', 'B' => 'option_b', 'C' => 'option_c', 'D' => 'option_d'];
            ?>
                <div class="question-card card mb-3 <?= $isCorrect ? 'correct' : 'incorrect' ?>">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">Question <?= array_search($questionId, $questionIds) + 1 ?></h5>
                        <span class="badge bg-<?= $isCorrect ? 'success' : 'danger' ?>">
                            <?= $isCorrect ? 'Correct' : 'Incorrect' ?>
                        </span>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($question['file_path'])): ?>
                            <div class="question-media">
                                <?php if (preg_match('/\.(jpg|jpeg|png|gif|webp)$/i', $question['file_path'])): ?>
                                    <img src="<?= htmlspecialchars($question['file_path']) ?>" class="img-fluid" alt="Question Image">
                                <?php elseif (preg_match('/\.(mp4|webm|ogg)$/i', $question['file_path'])): ?>
                                    <video controls class="img-fluid">
                                        <source src="<?= htmlspecialchars($question['file_path']) ?>">
                                        Your browser does not support the video tag.
                                    </video>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                        
                        <p class="card-text"><?= htmlspecialchars($question['question_text']) ?></p>
                        
                        <div class="options mt-3">
                            <?php foreach ($optionLabels as $letter => $option): ?>
                                <div class="form-check mb-2">
                                    <input class="form-check-input" 
                                           type="radio" 
                                           disabled
                                           <?= ($studentAnswer === $letter) ? 'checked' : '' ?>>
                                    <label class="form-check-label option-label 
                                        <?= ($question['correct_answer'] === $letter) ? 'correct-answer' : '' ?>
                                        <?= ($studentAnswer === $letter && !$isCorrect) ? 'student-answer' : '' ?>
                                        <?= ($studentAnswer === $letter && $isCorrect) ? 'student-correct' : '' ?>">
                                        <strong><?= $letter ?>.</strong> <?= htmlspecialchars($question[$option]) ?>
                                        <?php if ($question['correct_answer'] === $letter): ?>
                                            <span class="float-end"><i class="bi bi-check-lg"></i> Correct Answer</span>
                                        <?php elseif ($studentAnswer === $letter && !$isCorrect): ?>
                                            <span class="float-end"><i class="bi bi-x-lg"></i> Your Answer</span>
                                        <?php endif; ?>
                                    </label>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        
                        <?php if (!$isCorrect): ?>
                            <div class="explanation mt-3">
                                <strong><i class="bi bi-lightbulb"></i> Explanation:</strong>
                                <p class="mb-0">You selected <strong><?= $studentAnswer ?></strong> but the correct answer was <strong><?= $question['correct_answer'] ?></strong>.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
            
            <div class="d-grid gap-2 mt-4">
                <a href="exam_results.php" class="btn btn-secondary">
                    <i class="bi bi-arrow-left"></i> Back to Results Summary
                </a>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>