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

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

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

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

    $student_id = $_SESSION["user"]["id"];
    $now = date("Y-m-d H:i:s");

    // ✅ Update expired subjects automatically (in case they just passed expiry)
    Database::iud("
        UPDATE `student_subject`
        SET `student_subject_status_id` = 2
        WHERE `student_id` = '$student_id'
        AND `expire_date` <= '$now'
        AND `student_subject_status_id` != 2
    ");

    // ✅ Fetch subjects that are expired
    $rs = 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.student_subject_status_id = 2
        ORDER BY student_subject.expire_date DESC
    ");

    $subjects = [];
    while ($row = $rs->fetch_assoc()) {
        $subjects[] = $row;
    }

    if (empty($subjects)) {
        $response["message"] = "No expired subjects found.";
    } else {
        $response["status"] = true;
        $response["message"] = "Expired subjects loaded successfully.";
        $response["data"] = $subjects;
    }

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

echo json_encode($response);
exit;
?>
