async function addLesson() {
    const subject = document.getElementById("lSubject").value.trim();
    const lesson = document.getElementById("lLesson").value.trim();
    const lessonCardContainer = document.getElementById("lessonView");

    const data = {
        subject: subject,
        lesson: lesson
    }

    const dataJSON = JSON.stringify(data);

    try {
        const response = await fetch("Backend/Process/AddLessonProcess.php", {
            method: "POST",
            body: dataJSON,
            headers: {
                "Content-Type": "application/json"
            }

        });

        const json = await response.json();
        console.log(json);

        if (json.status) {
            Swal.fire({
                title: json.message,
                icon: "success",
                draggable: true
            });
            lessonCardContainer.innerHTML = "";
            loadLesson();
            lessonClear();
        } else {
            Swal.fire({
                title: json.message,
                icon: "warning",
                draggable: true
            });
        }
    } catch (err) {
        Swal.fire({ title: "Error: " + err.message, icon: "error", draggable: true });
    }
}

var id = "";

async function updateLesson() {
    const subject = document.getElementById("lSubject").value.trim();
    const lesson = document.getElementById("lLesson").value.trim();

    const updateBtn = document.getElementById("lUpdateBtn");
    const addBtn = document.getElementById("lAddBtn");

    const data = {
        subject_id: subject,
        lesson_id: id,
        lesson:lesson
    }

    const dataJSON = JSON.stringify(data);

    try {
        const response = await fetch("Backend/Process/UpdateLessonProcess.php", {
            method: "POST",
            body: dataJSON,
            headers: {
                "Content-Type": "application/json"
            }

        });

        const json = await response.json();
        console.log(json);

        if (json.status) {
            Swal.fire({
                title: json.message,
                icon: "success",
                draggable: true
            });

            updateBtn.classList.remove("d-block");
            updateBtn.classList.add("d-none");
            addBtn.classList.remove("d-none");
            addBtn.classList.add("d-block");
            loadLesson();
            lessonClear();


        } else {
            Swal.fire({
                title: json.message,
                icon: "warning",
                draggable: true
            });
        }
    } catch (err) {
        Swal.fire({ title: "Error: " + err.message, icon: "error", draggable: true });
    }
}



function loadlesUpdateFields(lid, subject,lesson) {
    document.getElementById("lSubject").value = subject;
    document.getElementById("lLesson").value = lesson;

    console.log(subject);
    console.log(lesson);

    id = lid;

    const updateBtn = document.getElementById("lUpdateBtn");
    const addBtn = document.getElementById("lAddBtn");

    updateBtn.classList.remove("d-none");
    updateBtn.classList.add("d-block");
    addBtn.classList.remove("d-block");
    addBtn.classList.add("d-none");

}


async function loadLesson() {
    const lessonCardContainer = document.getElementById("lessonView");
    const lessonText = document.getElementById("lessonText").value.trim();

    // Clear the container before new data
    lessonCardContainer.innerHTML = `<div class="text-center p-3 text-muted">Loading...</div>`;

    try {
        // Prepare JSON payload
        const textObject = { lessonText: lessonText };
        const textJSON = JSON.stringify(textObject);

        // Send request
        const response = await fetch("Backend/Process/LoadAllLessonData.php", {
            method: "POST",
            body: textJSON,
            headers: {
                "Content-Type": "application/json"
            }
        });

        if (!response.ok) {
            throw new Error("Network response was not ok");
        }

        const data = await response.json();
        console.log(data);

        // Handle response
        if (data.status && data.data && data.data.length > 0) {
            lessonCardContainer.innerHTML = ""; // Clear placeholder

            data.data.forEach(lesson => {
                const card = `
                    <div onclick="loadlesUpdateFields('${lesson.id}', '${lesson.subject}','${lesson.lesson}')" class="d-flex justify-content-between align-items-center rounded-3"
                        style="background:linear-gradient(90deg,#8e2de2,#a4508b); color:#fff; font-weight:600; padding: 6px 10px; font-size: 14px;">
                        <span>${lesson.lesson}</span>
                        <div class="d-flex gap-2">
                            <button onclick="deleteLesson(${lesson.id})" class="btn btn-danger btn-sm px-3 fw-semibold">Delete</button>
                        </div>
                    </div>
                `;
                lessonCardContainer.innerHTML += card;
            });

        } else {
            lessonCardContainer.innerHTML = `<div class="text-center p-3">No lessons found</div>`;
        }

    } catch (err) {
        console.error("Error loading courses:", err);
        lessonCardContainer.innerHTML = `<div class="text-center p-3 text-danger">Error loading lessons</div>`;
    }
}

async function deleteLesson(id) {
    const swalWithBootstrapButtons = Swal.mixin({
        customClass: {
            confirmButton: "btn btn-success",
            cancelButton: "btn btn-danger"
        },
        buttonsStyling: true
    });

    swalWithBootstrapButtons.fire({
        title: "Are you sure?",
        text: "If you delete this Lesson? All MCQs related to it will be permanently removed!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Yes, delete it!",
        cancelButtonText: "No, cancel!",
        reverseButtons: true
    }).then(async (result) => {
        if (result.isConfirmed) {

            try {
                const lessonCardContainer = document.getElementById("lessonView");

                const data = {
                    lesson_id: id
                };

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

                const json = await response.json();
                console.log(json);

                if (json.status) {
                    await swalWithBootstrapButtons.fire({
                        title: "Deleted!",
                        text: json.message,
                        icon: "success"
                    });

                    // Refresh UI
                    lessonCardContainer.innerHTML = "";
                    loadLesson();
                    lessonClear();
                } else {
                    lessonCardContainer.fire({
                        title: "Warning!",
                        text: json.message,
                        icon: "warning"
                    });
                }

            } catch (err) {
                swalWithBootstrapButtons.fire({
                    title: "Error!",
                    text: "Error deleting course: " + err.message,
                    icon: "error"
                });
                lessonClear();
            }

        } else if (result.dismiss === Swal.DismissReason.cancel) {
            swalWithBootstrapButtons.fire({
                title: "Cancelled",
                text: "Your lesson is safe :)",
                icon: "error"
            });
            lessonClear();
        }
    });
}


function lessonClear() {
    const updateBtn = document.getElementById("lUpdateBtn");
    const addBtn = document.getElementById("lAddBtn");

    document.getElementById("lSubject").value = 0;
    document.getElementById("lLesson").value = "";


    updateBtn.classList.remove("d-block");
    updateBtn.classList.add("d-none");
    addBtn.classList.remove("d-none");
    addBtn.classList.add("d-block");
}