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

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

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

    $rows = $rs->num_rows;

    if ($rows > 0) {
        $subjects = [];
        while ($subject = $rs->fetch_assoc()) {
            $subjects[] = [
                "id" => $subject["id"],
                "title" => $subject["title"],
                "price" => $subject["price"],
                "course" => $subject["course_id"] ?? null, // adjust if your table has this column             
            ];
        }

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

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

echo json_encode($response);
exit;
?>
