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

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

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

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

    $lesson_id = isset($data["lesson_id"]) ? trim($data["lesson_id"]) : "";
    $language = isset($data["language"]) ? trim($data["language"]) : "";

    if ($lesson_id === "" || $language === "") {
        $response["message"] = "Missing required fields.";
        echo json_encode($response);
        exit;
    }

    // Fetch all MCQs for the selected lesson & language (ordered)
    $rs = Database::search("SELECT * FROM `mcq` 
        WHERE `lesson_id` = '" . $lesson_id . "' 
        AND `medium_id` = '" . $language . "'
        ORDER BY `id` ASC");

    $questions = [];
    while ($row = $rs->fetch_assoc()) {
        // normalize keys if needed
        $questions[] = $row;
    }

    if (count($questions) === 0) {
        $response["message"] = "No questions found for this lesson/language.";
        echo json_encode($response);
        exit;
    }

    // Save in session for navigation
    $_SESSION["exam_questions"] = $questions;
    $_SESSION["exam_total"] = count($questions);
    $_SESSION["exam_answers"] = []; // question_id => selected option
    $_SESSION["exam_started_at"] = date("Y-m-d H:i:s");

    $response["status"] = true;
    $response["message"] = "Questions loaded successfully.";
    $response["data"] = $questions[0]; // first question
    $response["total"] = count($questions);
} catch (Exception $e) {
    $response["message"] = "Error: " . $e->getMessage();
}

echo json_encode($response);
exit;
?>
