// =======================
// Load Students Function
// =======================
async function loadStudents(searchText = "") {
    const text = searchText !== "" ? searchText : document.getElementById("search").value.trim();
    const tbody = document.getElementById("student_table_body");
    tbody.innerHTML = "";

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

        const json = await response.json();

        if (json.status) {
            json.data.forEach(student => {
                const isActive = student.status === "Active";
                const statusClass = isActive ? "status-activated" : "status-deactivated";

                const row = `
                    <tr>
                        <td>${student.firstName}</td>
                        <td>${student.lastName}</td>
                        <td>${student.nic}</td>
                        <td>${student.mobile}</td>
                        <td>${student.email}</td>
                        <td>${student.password}</td>
                        <td>${student.registerd_date}</td>
                        <td>
                            <span class="${statusClass} toggle-status-span"
                                  data-student-id="${student.id}"
                                  style="cursor: pointer;">
                                ${student.status}
                            </span>
                        </td>
                    </tr>
                `;

                tbody.innerHTML += row;
            });
        }
    } catch (err) {
        console.error("Error loading students:", err);
    }
}

// =======================
// Search Input Event
// =======================

let typingTimer;
const searchInput = document.getElementById("search");

if (searchInput) {
    searchInput.addEventListener("keyup", () => {
        clearTimeout(typingTimer);

        typingTimer = setTimeout(() => {
            const text = searchInput.value.trim();

            if (text === "") {
                loadStudents(""); // Load all students
            } else {
                loadStudents(text); // Load filtered results
            }

        }, 350);
    });
}

// =======================
// Toggle Status Function
// =======================

document.addEventListener("click", (e) => {
    const target = e.target.closest(".toggle-status-span");
    if (target) {
        e.preventDefault();
        e.stopPropagation();
        const studentId = target.dataset.studentId;
        if (studentId) {
            toggleStatus(studentId, target);
        }
    }
});

async function toggleStatus(studentId) {
    try {
        studentId = parseInt(studentId);

        if (isNaN(studentId) || studentId <= 0) {
            alert("Invalid student ID");
            return;
        }

        const response = await fetch("Backend/Process/UpdateStudentStatus.php", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ id: studentId })
        });

        const json = await response.json();

        if (json.status) {
            loadStudents(); // Reload table
        } else {
            alert(json.message || "Failed to update status.");
        }

    } catch (err) {
        console.error("Error toggling status:", err);
        alert("Error: " + err.message);
    }
}

// =======================
// Access Panel Loader
// =======================

async function loadAccessStudents() {
    const searchInput = document.querySelector("#addAccessPanel input[type='text']");
    const text = searchInput ? searchInput.value.trim() : "";
    const tbody = document.getElementById("tbody");

    if (!tbody) return;

    tbody.innerHTML = "";

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

        const json = await response.json();

        if (json.status) {
            json.data.forEach(student => {
                const isActive = student.status === "Active";
                const statusClass = isActive ? "status-activated" : "status-deactivated";

                const row = `
                    <tr>
                        <td>${student.firstName}</td>
                        <td>${student.lastName}</td>
                        <td>${student.nic}</td>
                        <td>${student.mobile}</td>
                        <td>${student.email}</td>
                        <td>${student.password}</td>
                        <td>${student.registerd_date}</td>
                        <td>
                            <span class="${statusClass} toggle-status-span"
                                  data-student-id="${student.id}">
                                ${student.status}
                            </span>
                        </td>
                    </tr>
                `;
                tbody.innerHTML += row;
            });
        } else {
            tbody.innerHTML = `<tr><td colspan="8" class="text-center text-muted">${json.message}</td></tr>`;
        }
    } catch (err) {
        console.error("Error loading access students:", err);
        tbody.innerHTML = `<tr><td colspan="8" class="text-center text-danger">Error loading students</td></tr>`;
    }
}