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

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

$response = ["status" => false, "message" => "", "data" => null, "index" => 0, "total" => 0];

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

    $index = isset($data["index"]) ? (int)$data["index"] : 0;

    if (!isset($_SESSION["exam_questions"]) || !is_array($_SESSION["exam_questions"])) {
        $response["message"] = "No exam loaded in session.";
        echo json_encode($response);
        exit;
    }

    $questions = $_SESSION["exam_questions"];
    $total = count($questions);

    if ($index < 0 || $index >= $total) {
        $response["message"] = "Index out of range.";
        $response["total"] = $total;
        echo json_encode($response);
        exit;
    }

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

echo json_encode($response);
exit;
?>
