<?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);

    $subject_id = isset($data["subject_id"]) ? intval($data["subject_id"]) : 0;
    $student_id = $_SESSION["student"]["id"] ?? 0;

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

    // Check if already requested
    $check = Database::search("SELECT * FROM `subject_requests` WHERE `student_id` = '$student_id' AND `subject_id` = '$subject_id'");
    if ($check->num_rows > 0) {
        $response["message"] = "You have already requested this subject.";
        echo json_encode($response);
        exit;
    }

    // Insert request again
    Database::iud("INSERT INTO `subject_requests`(`student_id`, `subject_id`, `created_at`) 
                   VALUES ('$student_id', '$subject_id', NOW())");

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

echo json_encode($response);
exit;
?>
