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

header("Content-Type: application/json");
$response = ["status" => false, "message" => ""];

try {
    // 1) Auth: accept either session key you used elsewhere
    if (isset($_SESSION["user"]["id"])) {
        $student_id = (int)$_SESSION["user"]["id"];
    } elseif (isset($_SESSION["student"]["id"])) {
        $student_id = (int)$_SESSION["student"]["id"];
    } else {
        throw new Exception("Unauthorized access. Please login.");
    }

    // 2) Read JSON payload
    $data = json_decode(file_get_contents("php://input"), true);
    if (!is_array($data)) $data = [];

    $subject_id = isset($data["subject_id"]) ? (int)$data["subject_id"] : 0;
    $course_id  = isset($data["course_id"])  ? (int)$data["course_id"]  : 0; // optional

    if ($subject_id <= 0) {
        throw new Exception("Invalid or missing subject_id.");
    }

    // 3) Inspect table columns to support different column name variants (robust)
    $cols_rs = Database::search("SHOW COLUMNS FROM `subject_requests`");
    $cols = [];
    while ($c = $cols_rs->fetch_assoc()) {
        $cols[] = $c["Field"];
    }

    // find a datetime column name to use
    $dtField = in_array('requested_at', $cols) ? 'requested_at'
             : (in_array('reqested_at', $cols) ? 'reqested_at'
             : (in_array('requested_date', $cols) ? 'requested_date' : null));

    // find status column name
    $statusField = in_array('request_status_id', $cols) ? 'request_status_id'
                 : (in_array('request_statu_id', $cols) ? 'request_statu_id' : null);

    $hasCourseCol = in_array('course_id', $cols);

    if ($dtField === null || $statusField === null) {
        throw new Exception("subject_requests table missing expected columns (datetime/status).");
    }

    // 4) Prevent duplicate pending requests (status = 1)
    $checkSql = "SELECT * FROM `subject_requests` 
                 WHERE `student_id` = '{$student_id}' 
                   AND `subject_id` = '{$subject_id}' 
                   AND `{$statusField}` = '1' LIMIT 1";
    $check = Database::search($checkSql);
    if ($check->num_rows > 0) {
        throw new Exception("You already have a pending request for this subject.");
    }

    // create timestamp
    $d = new DateTime("now", new DateTimeZone("Asia/Colombo"));
    $now = $d->format("Y-m-d H:i:s");

    // 5) Build insert depending on whether course_id column exists
    if ($hasCourseCol && $course_id > 0) {
        $insertSql = "INSERT INTO `subject_requests`
            (`student_id`,`subject_id`,`course_id`,`{$dtField}`,`{$statusField}`)
            VALUES ('{$student_id}','{$subject_id}','{$course_id}','{$now}','1')";
    } else {
        $insertSql = "INSERT INTO `subject_requests`
            (`student_id`,`subject_id`,`{$dtField}`,`{$statusField}`)
            VALUES ('{$student_id}','{$subject_id}','{$now}','1')";
    }

    Database::iud($insertSql);

    $response["status"] = true;
    $response["message"] = "Request sent to admin successfully.";
} catch (Exception $e) {
    $response["message"] = $e->getMessage();
}

echo json_encode($response);
exit;
?>
