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

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

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

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

    $lesson_id = $data["lesson_id"] ?? null;

    if (empty($lesson_id)) {
        $response["message"] = "Invalid lesson ID!";
    } else {
        // Check if lesson exists
        $lesson_rs = Database::search("SELECT * FROM `lesson` WHERE `id` = '$lesson_id'");
        if ($lesson_rs->num_rows === 0) {
            $response["message"] = "Lesson not found!";
            echo json_encode($response);
            exit;
        }

        // 1. Delete all MCQs related to this lesson
        Database::iud("DELETE FROM `mcq` WHERE `lesson_id` = '$lesson_id'");

        // 2. Delete the lesson itself
        Database::iud("DELETE FROM `lesson` WHERE `id` = '$lesson_id'");

        $response["status"] = true;
        $response["message"] = "Lesson and related MCQs deleted successfully!";
    }

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

echo json_encode($response);
exit;
?>
