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

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

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

try {
    if (!isset($_SESSION["user"])) {
        $response["message"] = "Unauthorized access.";
        echo json_encode($response);
        exit;
    }

    $student_id = $_SESSION["user"]["id"];

    // Load ready-to-pay subjects for this student
    $rs = Database::search("SELECT * FROM `ready_to_pay` WHERE `student_id` = '" . $student_id . "'");
    if ($rs->num_rows == 0) {
        $response["message"] = "No subjects in ready to pay list.";
        echo json_encode($response);
        exit;
    }

    while ($row = $rs->fetch_assoc()) {
        $subject_id = $row["subject_id"];

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

        // Prevent duplicate requests
        $check = Database::search("SELECT * FROM `subject_requests` WHERE `student_id` = '" . $student_id . "' AND `subject_id` = '" . $subject_id . "'");
        if ($check->num_rows == 0) {
            Database::iud("INSERT INTO `subject_requests` (`student_id`, `subject_id`,`requested_at`, `request_status_id`) 
            VALUES ('" . $student_id . "', '" . $subject_id . "', '" . $date. "', '1') ");

            
        }
    }

    // Clear ready_to_pay table after sending requests
    Database::iud("DELETE FROM `ready_to_pay` WHERE `student_id` = '" . $student_id . "'");

    $response["status"] = true;
    $response["message"] = "Your subject requests have been sent successfully.";
} catch (Exception $e) {
    $response["message"] = "Error: " . $e->getMessage();
}

echo json_encode($response);
exit;
