async function addCourse() {
    const category = document.getElementById("cCategory").value.trim();
    const course = document.getElementById("cCourse").value.trim();
    const courseCardContainer = document.getElementById("coursView");

    const data = {
        category: category,
        course: course
    }

    const dataJSON = JSON.stringify(data);

    try {
        const response = await fetch("Backend/Process/AddCourseProcess.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
            });
            courseCardContainer.innerHTML = "";
            loadCourse();
            CourseClear();
        } 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 updateCourse() {
    const category = document.getElementById("cCategory").value.trim();
    const course = document.getElementById("cCourse").value.trim();

    const updateBtn = document.getElementById("courseUpdateBtn");
    const addBtn = document.getElementById("courseAddBtn");

    const data = {
        course_id: id,
        category: category,
        title: course
    }

    const dataJSON = JSON.stringify(data);

    try {
        const response = await fetch("Backend/Process/UpdateCourseProsess.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");
            loadCourse();
            CourseClear();;


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

function loadUpdateFields(cid, title, category) {
    document.getElementById("cCourse").value = title;
    document.getElementById("cCategory").value = category;

    id = cid;

    const updateBtn = document.getElementById("courseUpdateBtn");
    const addBtn = document.getElementById("courseAddBtn");

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

}


async function loadCourse() {
    const courseCardContainer = document.getElementById("coursView");
    const courseText = document.getElementById("courseText").value.trim();

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

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

        // Send request
        const response = await fetch("Backend/Process/LoadAllCoursData.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) {
            courseCardContainer.innerHTML = ""; // Clear placeholder

            data.data.forEach(course => {
                const card = `
                    <div onclick="loadUpdateFields('${course.id}','${course.title}','${course.category}');" class="course-card d-flex justify-content-between align-items-center rounded-3 shadow-sm"
                        style="background:linear-gradient(90deg,#00997a,#6bd1b7); color:#fff; font-weight:600; padding: 6px 10px; font-size: 14px;">
                        <span class="course-title">${course.title.toUpperCase()}</span>
                        <div class="d-flex gap-2">
                            <button onclick="deleteCourse(${course.id});" class="btn btn-danger btn-sm px-2 fw-semibold">Delete</button>
                        </div>
                    </div>
                `;
                courseCardContainer.innerHTML += card;
            });

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

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





async function deleteCourse(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 course, all related subjects, lessons, and MCQs will also be permanently deleted!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Yes, delete it!",
        cancelButtonText: "No, cancel!",
        reverseButtons: true
    }).then(async (result) => {
        if (result.isConfirmed) {

            try {
                const courseCardContainer = document.getElementById("coursView");

                const data = {
                    course_id: id
                };

                const response = await fetch("Backend/Process/DeleteCourseProcess.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
                    courseCardContainer.innerHTML = "";
                    loadCourse();
                    CourseClear();
                } else {
                    swalWithBootstrapButtons.fire({
                        title: "Warning!",
                        text: json.message,
                        icon: "warning"
                    });
                }

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

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

        }
    });
}


function CourseClear() {
    const updateBtn = document.getElementById("courseUpdateBtn");
    const addBtn = document.getElementById("courseAddBtn");

    document.getElementById("cCategory").value = 0;
    document.getElementById("cCourse").value = "";

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