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

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

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

try {
    $json = file_get_contents("php://input");
    $data = json_decode($json, true);

    $question_id = isset($data["question_id"]) ? (int)$data["question_id"] : 0;
    $selected_option = isset($data["selected_option"]) ? trim($data["selected_option"]) : "";

    if ($question_id <= 0 || $selected_option === "") {
        $response["message"] = "Missing question id or selected option.";
        echo json_encode($response);
        exit;
    }

    if (!isset($_SESSION["exam_answers"]) || !is_array($_SESSION["exam_answers"])) {
        $_SESSION["exam_answers"] = [];
    }

    // normalize option letter (A/B/C/D)
    $selected_option = strtoupper($selected_option);

    $_SESSION["exam_answers"][$question_id] = $selected_option;

    // optional: compute current marks quickly (not required)
    $marks = 0;
    if (isset($_SESSION["exam_questions"]) && is_array($_SESSION["exam_questions"])) {
        $qmap = [];
        foreach ($_SESSION["exam_questions"] as $q) {
            $qmap[$q["id"]] = $q;
        }
        foreach ($_SESSION["exam_answers"] as $qid => $sel) {
            if (isset($qmap[$qid])) {
                $correct = strtoupper(trim($qmap[$qid]["correct_option"]));
                if ($sel === $correct) $marks++;
            }
        }
    }

    $response["status"] = true;
    $response["message"] = "Answer saved.";
    $response["data"] = ["marks" => $marks];
} catch (Exception $e) {
    $response["message"] = "Error: " . $e->getMessage();
}

echo json_encode($response);
exit;
?>
