<?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);

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

    if (empty($subject_id)) {
        $response["message"] = "Invalid subject ID!";
    } else {
        // 1. Find all lessons related to this subject
        $lesson_rs = Database::search("SELECT `id` FROM `lesson` WHERE `subject_id` = '$subject_id'");

        while ($lesson = $lesson_rs->fetch_assoc()) {
            $lesson_id = $lesson["id"];

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

        // 3. Delete all lessons of the subject
        Database::iud("DELETE FROM `lesson` WHERE `subject_id` = '$subject_id'");

        // 4. Finally delete the subject itself
        Database::iud("DELETE FROM `subject` WHERE `id` = '$subject_id'");

        $response["status"] = true;
        $response["message"] = "Subject and all related data deleted successfully!";
    }

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

echo json_encode($response);
exit;
?>
