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

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

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

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

    // Validate inputs
    $student_id = isset($data["student_id"]) ? intval($data["student_id"]) : 0;
    $subject_id = isset($data["subject_id"]) ? intval($data["subject_id"]) : 0;
    $selected = isset($data["selected"]) ? intval($data["selected"]) : 0;

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

    // If selected = 1 → insert to table
    if ($selected === 1) {
        $check = Database::search("SELECT * FROM `ready_to_pay` WHERE `student_id` = '$student_id' AND `subject_id` = '$subject_id'");
        if ($check->num_rows === 0) {

            $d = new DateTime();
            $tz = new DateTimeZone("Asia/Colombo");
            $d->setTimezone($tz);
            $date = $d->format("Y-m-d H:i:s");

            Database::iud("INSERT INTO `ready_to_pay`(`student_id`, `subject_id`,`created_at`) VALUES('$student_id', '$subject_id','$date')");
            $response["status"] = true;
            $response["message"] = "Subject added to Ready to Pay list.";
        } else {
            $response["status"] = true;
            $response["message"] = "Already added.";
        }
    }
    // If selected = 0 → delete from table
    else {
        Database::iud("DELETE FROM `ready_to_pay` WHERE `student_id` = '$student_id' AND `subject_id` = '$subject_id'");
        $response["status"] = true;
        $response["message"] = "Subject removed from Ready to Pay list.";
    }
} catch (Exception $e) {
    $response["message"] = $e->getMessage();
}

echo json_encode($response);
exit;
