function updateCountdowns() {
    const countdowns = document.querySelectorAll(".countdown");
    const now = new Date().getTime();

    countdowns.forEach(async (span) => {
        const expire = new Date(span.dataset.expire).getTime();
        const distance = expire - now;
        const subjectItem = span.closest(".subject-item");

        if (!subjectItem) return;

        if (distance <= 0) {
            // ✅ Mark countdown as expired
            span.innerText = "Expired";
            span.classList.add("text-muted");

            // ✅ Get subject_id from dataset
            const subjectId = subjectItem.dataset.subjectId;

            if (subjectId) {
                try {
                    // Call backend to mark subject expired
                    const response = await fetch("Backend/Process/expire_subject.php", {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({ subject_id: subjectId }),
                    });

                    const result = await response.json();
                    console.log(result);
                    if (result.status) {
                        console.log("Expired:", result.message);

                        // Remove expired subject from active list
                        subjectItem.remove();

                        // ✅ Add to outdated section
                        if (result.data) addOutdatedSubject(result.data);
                    } else {
                        console.warn("Expire failed:", result.message);
                    }
                } catch (err) {
                    console.error("Error expiring subject:", err);
                }
            }
            return;
        }

        // ✅ Update countdown display
        const days = Math.floor(distance / (1000 * 60 * 60 * 24));
        const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));

        span.innerText = `${days}d ${hours}h ${minutes}m`;
    });
}

// Refresh countdown every minute
setInterval(updateCountdowns, 60000);
updateCountdowns();


async function loadOutdatedSubjects() {
    try {
        const response = await fetch("Backend/Process/load_expired_subjects.php");
        const result = await response.json();

        const container = document.querySelector("#outdatedContent .container");
        const emptyMsg = document.querySelector("#outdatedContent .center-full");

        if (!container) return;

        // Clear existing content
        container.innerHTML = "";

        if (!result.status || result.data.length === 0) {
            emptyMsg.classList.remove("d-none");
            return;
        }

        emptyMsg.classList.add("d-none");

        // Render all outdated subjects
        result.data.forEach(subject => addOutdatedSubject(subject));
    } catch (err) {
        console.error("Error loading outdated subjects:", err);
    }
}

loadOutdatedSubjects();

function addOutdatedSubject(subject) {
    if (!subject) return;

    const container = document.querySelector("#outdatedContent .container");
    if (!container) return;

    let courseSection = container.querySelector(`[data-course-id="${subject.course_id}"]`);
    if (!courseSection) {
        const courseDiv = document.createElement("div");
        courseDiv.classList.add("bg-white", "p-3", "rounded-3", "shadow-sm", "d-flex", "align-items-center", "gap-3", "mb-2");
        courseDiv.dataset.courseId = subject.course_id;
        courseDiv.innerHTML = `
            <span class="legend-dot red flex-shrink-0"></span>
            <strong>${subject.course_name}</strong>
        `;
        container.appendChild(courseDiv);
    }

    const courseRow = document.createElement("div");
    courseRow.classList.add("course-row");
    courseRow.setAttribute("data-aos", "fade-up");
    courseRow.innerHTML = `
        <div class="course-left">
            <span class="dot orange"></span>
            <strong class="subject">${subject.subject_name}</strong>
        </div>
        <button class="request-btn" 
                data-subject-id="${subject.subject_id}" 
                data-course-id="${subject.course_id}">
            Request
        </button>
    `;
    container.appendChild(courseRow);
}



document.addEventListener("click", async (e) => {
    if (e.target.classList.contains("request-btn")) {
        const subjectId = e.target.dataset.subjectId;
        const courseId = e.target.dataset.courseId;

        console.log(subjectId);
        console.log(courseId);

        const confirmReq = confirm("Do you want to request reactivation for this expired subject?");
        if (!confirmReq) return;

        const res = await fetch("Backend/Process/request_expired_subject.php", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ subject_id: subjectId, course_id: courseId })
        });

        const result = await res.json();
        console.log(result);
        alert(result.message);
    }
});
