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

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

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

try {
    // ✅ Check session
    if (!isset($_SESSION["user"]["id"])) {
        throw new Exception("Unauthorized access.");
    }

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

    // ✅ Get JSON data
    $data = json_decode(file_get_contents("php://input"), true);
    $subject_id = isset($data["subject_id"]) ? intval($data["subject_id"]) : 0;

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

    // ✅ Get subject expiry info
    $rs = Database::search("
        SELECT expire_date, student_subject_status_id 
        FROM student_subject
        WHERE student_id = '$student_id' 
        AND subject_id = '$subject_id'
        LIMIT 1
    ");

    if ($rs->num_rows == 0) {
        throw new Exception("Subject not found for this student.");
    }

    $row = $rs->fetch_assoc();
    $expire_date = $row["expire_date"];
    $status_id = $row["student_subject_status_id"];

    // ✅ Server time + 2-minute grace
    $now = new DateTime("now", new DateTimeZone("Asia/Colombo"));
    $grace = clone $now;
    $grace->modify("+2 minutes");

    $expire_dt = new DateTime($expire_date, new DateTimeZone("Asia/Colombo"));

    // ✅ If not yet expired (even with grace)
    if ($expire_dt > $grace) {
        throw new Exception("Subject not yet expired on server time.");
    }

    // ✅ Update only if not already expired
    if ($status_id != 2) {
        Database::iud("
            UPDATE student_subject
            SET student_subject_status_id = 2
            WHERE student_id = '$student_id'
            AND subject_id = '$subject_id'
        ");
    }

    // ✅ Fetch subject & course info
    $info = Database::search("
        SELECT 
            student_subject.*,
            subject.title AS subject_name,
            course.title AS course_name
        FROM student_subject
        INNER JOIN subject ON student_subject.subject_id = subject.id
        INNER JOIN course  ON student_subject.course_id = course.id
        WHERE student_subject.student_id = '$student_id'
        AND student_subject.subject_id = '$subject_id'
    ");

    $subject_data = $info->fetch_assoc();

    $response["status"] = true;
    $response["message"] = "Subject expired successfully.";
    $response["data"] = $subject_data;
} catch (Exception $e) {
    $response["message"] = $e->getMessage();
}

echo json_encode($response);
exit;
?>
