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

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

    if (empty($course_id)) {
        $response["message"] = "Invalid course ID!";
    } else {
        // 1. Find subjects related to this course
        $subject_rs = Database::search("SELECT `id` FROM `subject` WHERE `course_id` = '$course_id'");
        while ($subject = $subject_rs->fetch_assoc()) {
            $subject_id = $subject["id"];

            // 2. Find lessons related to each subject
            $lesson_rs = Database::search("SELECT `id` FROM `lesson` WHERE `subject_id` = '$subject_id'");
            while ($lesson = $lesson_rs->fetch_assoc()) {
                $lesson_id = $lesson["id"];

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

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

        // 5. Delete all subjects of the course
        Database::iud("DELETE FROM `subject` WHERE `course_id` = '$course_id'");

        // 6. Finally delete the course
        Database::iud("DELETE FROM `course` WHERE `id` = '$course_id'");

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

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

echo json_encode($response);
exit;
?>
