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

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

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

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

    $student_id = isset($data["student_id"]) ? intval($data["student_id"]) : 0;

    if ($student_id <= 0) {
        $response["message"] = "Invalid student ID.";
        echo json_encode($response);
        exit;
    }

    $rs = Database::search("
        SELECT 
            rtp.subject_id,
            s.title AS subject_title,
            s.price AS subject_price,
            c.title AS course_title
        FROM ready_to_pay rtp
        JOIN subject s ON rtp.subject_id = s.id
        JOIN course c ON s.course_id = c.id
        WHERE rtp.student_id = '$student_id'
        ORDER BY c.title, s.title
    ");

    $total = 0;
    $subjects = [];

    if ($rs->num_rows > 0) {
        while ($row = $rs->fetch_assoc()) {
            $subjects[] = $row;
            $total += floatval($row["subject_price"]);
        }
        $response["status"] = true;
        $response["data"] = $subjects;
        $response["total"] = $total;
    } else {
        $response["message"] = "No subjects found.";
    }

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

echo json_encode($response);
exit;
?>
