document.addEventListener('DOMContentLoaded', function () {
    const checkboxes = document.querySelectorAll('.subject-checkbox');

    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', async function () {
            const studentId = this.dataset.studentId;
            const subjectId = this.dataset.subjectId;
            const selected = this.checked ? 1 : 0;

            console.log("Student ID:", studentId);
            console.log("Subject ID:", subjectId);
            console.log("Selected:", selected);

            // ✅ Frontend login check
            if (studentId == 0) {
                // Revert checkbox
                this.checked = !this.checked;

                // Show alert & redirect
                Swal.fire({
                    title: "Please log in first",
                    icon: "warning",
                    confirmButtonText: "Login"
                }).then(() => {
                    window.location = "login.php";
                });

                return;
            }

            // Optional guard: if neither student nor subject ID exist, stop
            if (!studentId || !subjectId) {
                console.error('Missing data attributes.');
                return;
            }

            // Prepare data for backend
            const data = {
                student_id: studentId,
                subject_id: subjectId,
                selected: selected
            };

            try {
                const response = await fetch('Backend/Process/ReadyToPayProcess.php', {
                    method: 'POST',
                    body: JSON.stringify(data),
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    const json = await response.json();

                    // Separate logics for checked/unchecked
                    if (selected === 1) {
                        console.log('✅ Added subject:', json.message);
                        loadReadyToPay(studentId);
                    } else {
                        console.log('❌ Removed subject:', json.message);
                        // Swal.fire({ title: json.message, icon: 'info', timer: 1000, showConfirmButton: false });
                        loadReadyToPay(studentId);
                    }

                } else {
                    console.error('❗ Server error:', response.statusText);
                }
            } catch (error) {
                console.error('⚠️ Fetch error:', error);
            }
        });
    });
});

async function sendreq(studentId) {
    try {
        const res = await fetch("Backend/Process/SendSubjectRequests.php", {
            method: "POST"
        });
        const data = await res.json();

        if (data.status) {
            Swal.fire({
                icon: "success",
                title: "Request Sent!",
                text: data.message,
                confirmButtonColor: "#3085d6",
            });

            // Clear all checkboxes after successful request
            const checkboxes = document.querySelectorAll('.subject-checkbox:checked');
            checkboxes.forEach(checkbox => {
                checkbox.checked = false;
                // Remove selected class from parent
                const parent = checkbox.closest('.subject-item');
                if (parent) {
                    parent.classList.remove('subject-selected');
                }
            });

            // Update subject count to 0
            const countElement = document.querySelector('.subjects-selected');
            if (countElement) {
                countElement.textContent = '0 Subjects Selected';
            }

            // Reload ready-to-pay box (now empty)
            loadReadyToPay(studentId);
            // Reload pending requests after sending
            loadPendingRequests();
        } else {
            Swal.fire({
                icon: "warning",
                title: "Oops...",
                text: data.message,
            });
        }
    } catch (err) {
        Swal.fire({
            icon: "error",
            title: "Server Error",
            text: "Something went wrong!",
        });
        console.error(err);
    }
};



function loadReadyToPay(studentId) {
    fetch("Backend/Process/LoadReadyToPayProcess.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ student_id: studentId })
    })
        .then(res => res.json())
        .then(data => {
            const container = document.getElementById("rpay");
            const totalElement = document.querySelector(".total-amount-value");

            container.innerHTML = ""; // Clear existing

            if (data.status && data.data.length > 0) {
                data.data.forEach(item => {
                    const div = document.createElement("div");
                    div.className = "ready-course-item ";
                    div.dataset.itemId = item.subject_id;
                    div.innerHTML = `
                    <div class="ready-course-left d-flex align-items-center gap-2">
                        <span class="legend-dot orange flex-shrink-0" style="width:17px; height:17px;"> </span>
                        <span>${item.subject_title}</span>
                    </div>
                `;
                    container.appendChild(div);
                });

                // ✅ Update total amount
                totalElement.textContent = `LKR : ${Number(data.total).toFixed(2)}`;
            } else {
                container.innerHTML = `<p class="text-muted p-2">No subjects added yet.</p>`;
                totalElement.textContent = "LKR : 0.00";
            }
        })
        .catch(err => {
            console.error("Error loading Ready to Pay subjects:", err);
        });
}

async function clearReadyToPay() {
    try {
        const res = await fetch("Backend/Process/clear_ready_to_pay.php", {
            method: "POST"
        });
        const data = await res.json();

        if (data.status) {
            console.log("✅ " + data.message);
            document.getElementById("rpay").innerHTML = ""; // clear UI box
            document.querySelector(".total-amount-value").innerText = "LKR : 0.00"; // reset price
        } else {
            console.warn("⚠️ " + data.message);
        }
    } catch (err) {
        console.error("Server error:", err);
    }
}

window.addEventListener("load", () => {
    clearReadyToPay();
    loadPendingRequests();
});

// Load pending requests for the user
async function loadPendingRequests() {
    try {
        const res = await fetch("Backend/Process/LoadPendingRequests.php", {
            method: "POST",
            headers: { "Content-Type": "application/json" }
        });
        const data = await res.json();

        const pendingSection = document.getElementById("pendingRequestsSection");
        const noPendingDiv = document.getElementById("noPendingRequests");
        const pendingList = document.getElementById("pendingRequestsList");

        if (data.status && data.data && data.data.length > 0) {
            // Show pending section
            if (pendingSection) pendingSection.style.display = "block";
            if (noPendingDiv) noPendingDiv.style.display = "none";

            // Display pending requests
            if (pendingList) {
                pendingList.innerHTML = "";
                data.data.forEach((request, index) => {
                    const requestItem = document.createElement("div");
                    requestItem.className = "d-flex justify-content-between align-items-center mb-2 p-2";
                    requestItem.style.cssText = "background: #f8f9fa; border-radius: 8px; border-left: 3px solid #d92626;";
                    requestItem.innerHTML = `
                        <div class="d-flex align-items-center">
                            <span class="badge bg-danger me-2">${index + 1}</span>
                            <span class="fw-semibold">${request.subject_title}</span>
                        </div>
                        <small class="text-muted">${formatDate(request.requested_at)}</small>
                    `;
                    pendingList.appendChild(requestItem);
                });
            }
        } else {
            // Hide pending section
            if (pendingSection) pendingSection.style.display = "none";
            if (noPendingDiv) noPendingDiv.style.display = "block";
            if (pendingList) pendingList.innerHTML = "";
        }
    } catch (err) {
        console.error("Error loading pending requests:", err);
    }
}

// Format date for display
function formatDate(dateString) {
    if (!dateString) return "";
    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", {
        year: "numeric",
        month: "short",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit"
    });
}

// Cancel all pending requests
async function cancelRequests() {
    try {
        Swal.fire({
            title: "Cancel Requests?",
            text: "Are you sure you want to cancel all pending requests?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#d92626",
            cancelButtonColor: "#6c757d",
            confirmButtonText: "Yes, cancel them",
            cancelButtonText: "No, keep them"
        }).then(async (result) => {
            if (result.isConfirmed) {
                const res = await fetch("Backend/Process/DeletePendingRequests.php", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" }
                });
                const data = await res.json();

                if (data.status) {
                    Swal.fire({
                        icon: "success",
                        title: "Cancelled!",
                        text: data.message,
                        confirmButtonColor: "#d92626",
                    }).then(() => {
                        // Reload pending requests (should be empty now)
                        loadPendingRequests();
                        // Redirect to index
                        window.location.href = "index.php";
                    });
                } else {
                    Swal.fire({
                        icon: "error",
                        title: "Error",
                        text: data.message || "Failed to cancel requests",
                        confirmButtonColor: "#d92626",
                    });
                }
            }
        });
    } catch (err) {
        console.error("Error cancelling requests:", err);
        Swal.fire({
            icon: "error",
            title: "Error",
            text: "Something went wrong while cancelling requests",
            confirmButtonColor: "#d92626",
        });
    }
}