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

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

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

try {
    // Load all courses
    $course_rs = Database::search("SELECT * FROM `course` ORDER BY `id` DESC");

    if ($course_rs->num_rows > 0) {
        $courses = [];

        while ($course = $course_rs->fetch_assoc()) {

            // Load subjects for each course
            $subject_rs = Database::search("SELECT * FROM `subject` WHERE `course_id` = '" . $course['id'] . "'");
            $subjects = [];

            while ($subject = $subject_rs->fetch_assoc()) {

                // Load lessons for each subject
                $lesson_rs = Database::search("SELECT * FROM `lesson` WHERE `subject_id` = '" . $subject['id'] . "'");
                $lessons = [];

                while ($lesson = $lesson_rs->fetch_assoc()) {
                    $lessons[] = [
                        "id" => $lesson["id"],
                        "title" => $lesson["title"]
                    ];
                }

                $subjects[] = [
                    "id" => $subject["id"],
                    "title" => $subject["title"],
                    "lessons" => $lessons
                ];
            }

            $courses[] = [
                "id" => $course["id"],
                "title" => $course["title"],
                "subjects" => $subjects
            ];
        }

        $response["status"] = true;
        $response["data"] = $courses;
    } else {
        $response["status"] = true;
        $response["message"] = "No courses found";
        $response["data"] = [];
    }
} catch (Exception $e) {
    $response["status"] = false;
    $response["message"] = $e->getMessage();
}

echo json_encode($response);
exit;
?>
