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

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

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

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 (empty($lesson_id) || empty($language)) {
        $response["message"] = "Missing required fields.";
        echo json_encode($response);
        exit;
    }

    // Load MCQs
    $rs = Database::search("SELECT * FROM `mcq` WHERE `lesson_id`='" . $lesson_id . "' AND `medium_id`='" . $language . "'");
    
    if ($rs && $rs->num_rows > 0) {
        $questions = [];
        while ($row = $rs->fetch_assoc()) {
            $questions[] = $row;
        }

        $_SESSION["exam_questions"] = $questions;
        $_SESSION["lesson_id"] = $lesson_id;
        $_SESSION["language"] = $language;

        $response["status"] = true;
        $response["message"] = "Questions loaded successfully.";
        $response["data"] = $questions;
    } else {
        $response["message"] = "No questions found for this lesson and language.";
    }

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

echo json_encode($response);
exit;
?>
