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

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

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

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

    $student_id = $data["student_id"] ?? null;
    $subject_id = $data["subject_id"] ?? null;

    if (empty($student_id) || empty($subject_id)) {
        throw new Exception("Missing student or subject ID.");
    }

    // ✅ Check if student already has this subject
    $checkSubject = Database::search("
        SELECT * FROM `student_subject`
        WHERE `student_id` = '{$student_id}'
        AND `subject_id` = '{$subject_id}'
    ");

    if ($checkSubject->num_rows > 0) {
        throw new Exception("You already have this subject.");
    }

    // ✅ Check if already requested
    $checkRequest = Database::search("
        SELECT * FROM `subject_requests`
        WHERE `student_id` = '{$student_id}'
        AND `subject_id` = '{$subject_id}'
    ");

    if ($checkRequest->num_rows > 0) {
        throw new Exception("Already requested this subject.");
    }

    // ✅ Get current date/time
    $d = new DateTime("now", new DateTimeZone("Asia/Colombo"));
    $date = $d->format("Y-m-d H:i:s");

    // ✅ Insert new request
    Database::iud("
        INSERT INTO `subject_requests`
        (`student_id`, `subject_id`, `reqested_at`, `request_status_id`)
        VALUES ('{$student_id}', '{$subject_id}', '{$date}', '1')
    ");

    $response["status"] = true;
    $response["message"] = "Subject request sent successfully.";

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

echo json_encode($response);
exit;
?>
