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

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

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

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

    // Extract search text if provided
    $lessonText = isset($data["lessonText"]) ? trim($data["lessonText"]) : "";

    // Query based on search text
    if (!empty($lessonText)) {
        $rs = Database::search("SELECT * FROM `lesson` WHERE `title` LIKE '%" . $lessonText . "%' ORDER BY `id` DESC");
    } else {
        $rs = Database::search("SELECT * FROM `lesson` ORDER BY `id` DESC");
    }

    $rows = $rs->num_rows;

    if ($rows > 0) {
        $lessons = [];
        while ($lesson = $rs->fetch_assoc()) {
            $lessons[] = [
                "id" => $lesson["id"],
                "subject" => $lesson["subject_id"],
                "lesson" => $lesson["title"] ?? null,
            ];
        }

        $response["status"] = true;
        $response["data"] = $lessons;
    } else {
        $response["status"] = true;
        $response["message"] = "No lessons found";
        $response["data"] = [];
    }

} catch (Exception $ex) {
    $response["status"] = false;
    $response["message"] = "Error: " . $ex->getMessage();
}

echo json_encode($response);
exit;
?>
