<?php
include "connection.php";

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

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

$lesson = $data["lesson"] ?? null;
$medium = $data["medium1"] ?? null;
$quiz_number = $data["quiz_number"] ?? null;

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

try {
    // ✅ Validation
    if (empty($lesson) || $lesson == 0) {
        throw new Exception("Please select lesson first.");
    }
    if (empty($medium) || $medium == 0) {
        throw new Exception("Please select medium.");
    }
    if (empty($quiz_number) || $quiz_number == 0) {
        throw new Exception("Please select quiz number.");
    }

    // ✅ Check if quiz exists
    $rs = Database::search("
        SELECT * FROM `mcq`
        WHERE `lesson_id` = '".$lesson."'
        AND `medium_id` = '".$medium."'
        AND `question_number` = '".$quiz_number."'
    ");

    if ($rs->num_rows == 0) {
        throw new Exception("Quiz not found or already deleted.");
    }

    // ✅ Delete the selected quiz
    Database::iud("
        DELETE FROM `mcq`
        WHERE `lesson_id` = '".$lesson."'
        AND `medium_id` = '".$medium."'
        AND `question_number` = '".$quiz_number."'
    ");

    // ✅ Renumber remaining questions
    // 1. Initialize a variable
    Database::iud("SET @new_number = 0;");

    // 2. Update question_number sequentially
    Database::iud("
        UPDATE `mcq`
        SET `question_number` = (@new_number := @new_number + 1)
        WHERE `lesson_id` = '".$lesson."'
        AND `medium_id` = '".$medium."'
        ORDER BY `question_number` ASC;
    ");

    $response["status"] = true;
    $response["message"] = "Quiz deleted successfully and question numbers updated.";

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

echo json_encode($response);
exit;
?>
