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

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

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

    // Validate and extract input
    $courseText = isset($data["courseText"]) ? trim($data["courseText"]) : "";

    // If text is passed → filter by title
    if (!empty($courseText)) {
        $rs = Database::search("SELECT * FROM `course` WHERE `title` LIKE '%" . $courseText . "%' ORDER BY `id` DESC");
    } else {
        // If no text → return all courses
        $rs = Database::search("SELECT * FROM `course` ORDER BY `id` DESC");
    }

    $rows = $rs->num_rows;

    if ($rows > 0) {
        $courses = [];
        while ($course = $rs->fetch_assoc()) {
            $courses[] = [
                "id" => $course["id"],
                "title" => $course["title"],
                "category" => $course["category_id"]
            ];
        }

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

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

echo json_encode($response);
exit;
?>
