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

    $request_id = isset($data["request_id"]) ? intval($data["request_id"]) : 0;
    $status_id = isset($data["status_id"]) ? intval($data["status_id"]) : 0;

    if ($request_id <= 0 || $status_id <= 0) {
        throw new Exception("Invalid request data.");
    }

    // 🔍 Get request details
    $rs = Database::search("SELECT * FROM `subject_requests` WHERE `id` = '$request_id'");
    if ($rs->num_rows == 0) {
        throw new Exception("Request not found.");
    }

    $req = $rs->fetch_assoc();
    $student_id = $req["student_id"];
    $subject_id = $req["subject_id"];

    // 🔍 Get course_id
    $course_rs = Database::search("SELECT `course_id` FROM `subject` WHERE `id` = '$subject_id'");
    if ($course_rs->num_rows == 0) {
        throw new Exception("Course ID not found for this subject.");
    }

    $course_data = $course_rs->fetch_assoc();
    $course_id = $course_data["course_id"];

    // Set date/time
    $d = new DateTime("now", new DateTimeZone("Asia/Colombo"));
    $purchase_date = $d->format("Y-m-d H:i:s");
    $d->modify("+30 days");
    $expire_date = $d->format("Y-m-d H:i:s");

    // ✅ If request accepted
    if ($status_id == 2) {
        // Check if student already has this subject
        $check = Database::search("
            SELECT * FROM `student_subject` 
            WHERE `student_id` = '$student_id' 
            AND `subject_id` = '$subject_id'
        ");

        if ($check->num_rows > 0) {
            $existing = $check->fetch_assoc();

            // If it’s expired (2), reactivate it
            if ($existing["student_subject_status_id"] == 2) {
                Database::iud("
                    UPDATE `student_subject`
                    SET 
                        `student_subject_status_id` = 1,
                        `purchase_date` = '$purchase_date',
                        `expire_date` = '$expire_date'
                    WHERE 
                        `student_id` = '$student_id' 
                        AND `subject_id` = '$subject_id'
                ");
                $response["message"] = "Expired subject reactivated successfully.";
            } else {
                $response["message"] = "Subject already active for this student.";
            }

        } else {
            // Add new record if subject not found
            Database::iud("
                INSERT INTO `student_subject`
                (`student_id`, `subject_id`, `course_id`, `payment_status_id`, `purchase_date`, `expire_date`, `student_subject_status_id`)
                VALUES (
                    '$student_id',
                    '$subject_id',
                    '$course_id',
                    '1',
                    '$purchase_date',
                    '$expire_date',
                    '1'
                )
            ");
            $response["message"] = "New subject added successfully.";
        }

        // Remove from requests after handling
        Database::iud("DELETE FROM `subject_requests` WHERE `id` = '$request_id'");

        $response["status"] = true;
    }

    // ❌ If rejected
    elseif ($status_id == 3) {
        Database::iud("DELETE FROM `subject_requests` WHERE `id` = '$request_id'");
        $response["status"] = true;
        $response["message"] = "Request rejected successfully.";
    }

    else {
        throw new Exception("Invalid status action.");
    }

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

echo json_encode($response);
exit;
?>
