<?php
include("../database/auth_check.php");

$con = mysqli_connect("localhost", "root", "", "WSAS");

$student_id_num = $_GET['student_id_num'] ?? '';

if (!$student_id_num) {
    echo json_encode([]);
    exit;
}

// get student_id
$stmt = mysqli_prepare($con, "
    SELECT student_id 
    FROM adminstudent 
    WHERE student_id_num = ?
");
$stmt->bind_param("s", $student_id_num);
$stmt->execute();
$res = $stmt->get_result();
$student = $res->fetch_assoc();

if (!$student) {
    echo json_encode([]);
    exit;
}

$student_id = $student['student_id'];

// get SOA schedule 
$enroll = mysqli_fetch_assoc(mysqli_query($con, "
    SELECT date_enrolled 
    FROM enroll_student 
    WHERE student_id = $student_id 
    ORDER BY enroll_id DESC 
    LIMIT 1
"));

if (!$enroll) {
    echo json_encode([]);
    exit;
}

$start = new DateTime($enroll['date_enrolled']);
$today = new DateTime();

$payments = mysqli_query($con, "
    SELECT spay_amount, created_at, spay_status
    FROM student_payment
    WHERE student_id = $student_id
    ORDER BY created_at ASC
");

$data = [];
$paidIndex = 0;

// Downpayment
$data[] = [
    "month" => "Downpayment",
    "due" => "-",
    "status" => "Paid"
];

// monthly 1–4
for ($i = 1; $i <= 4; $i++) {

    $due = clone $start;
    $due->modify("+$i month")->modify("last day of this month");

    $pay = mysqli_fetch_assoc($payments);

    $data[] = [
        "month" => $i,
        "due" => $due->format("F d, Y"),
        "status" => $pay ? $pay['spay_status'] : "-"
    ];
}

echo json_encode($data);