<?php
session_start();
include "connection.php";
include "validation.php";

header("Content-Type: application/json");

$response = ["status" => false, "message" => "", "data" => []];

try {
    // Ensure exam data exists
    if (!isset($_SESSION["user_answers"]) || !isset($_SESSION["exam_questions"])) {
        $response["message"] = "No exam answers found. Please attempt the quiz first.";
        echo json_encode($response);
        exit;
    }

    $answers = $_SESSION["user_answers"];
    $questions = $_SESSION["exam_questions"];
    $totalQuestions = count($questions);
    $score = 0;
    $resultData = [];

    foreach ($questions as $index => $q) {
        $userAnswer = isset($answers[$q["id"]]) ? $answers[$q["id"]] : null;
        $isCorrect = ($userAnswer === $q["correct_option"]);

        if ($isCorrect) $score++;

        $resultData[] = [
            "number" => $index + 1,
            "question" => $q["question"],
            "options" => [
                "A" => $q["option_a"],
                "B" => $q["option_b"],
                "C" => $q["option_c"],
                "D" => $q["option_d"]
            ],
            "correct_option" => $q["correct_option"],
            "user_option" => $userAnswer,
            "is_correct" => $isCorrect
        ];
    }

    $response["status"] = true;
    $response["message"] = "Result loaded successfully.";
    $response["data"] = [
        "score" => $score,
        "total" => $totalQuestions,
        "results" => $resultData
    ];

} catch (Exception $e) {
    $response["message"] = "Error: " . $e->getMessage();
}

echo json_encode($response);
exit;
?>
