async function addSubject() {
    const course = document.getElementById("sCourse").value.trim();
    const subject = document.getElementById("sSubject").value.trim();
    const price = document.getElementById("sPrice").value.trim();
    const courseCardContainer = document.getElementById("subjectView");

    const data = {
        subject: subject,
        course: course,
        price:price
    }

    console.log(data);

    const dataJSON = JSON.stringify(data);

    try {
        const response = await fetch("Backend/Process/AddSubjectProcess.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 = "";
            loadSubject();
            subjectClear();
        } 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 updateSubject() {
    const course = document.getElementById("sCourse").value.trim();
    const subject = document.getElementById("sSubject").value.trim();
    const price = document.getElementById("sPrice").value.trim();

    const updateBtn = document.getElementById("sUpdateBtn");
    const addBtn = document.getElementById("sAddBtn");

    const data = {
        subject_id: id,
        course_id: course,
        subject: subject,
        price:price
    }

    const dataJSON = JSON.stringify(data);

    try {
        const response = await fetch("Backend/Process/UpdateSubjectProcess.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");
            loadSubject();
            subjectClear();


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



function loadSubUpdateFields(sid, title,course,price) {
    document.getElementById("sSubject").value = title;
    document.getElementById("sCourse").value = course;
    document.getElementById("sPrice").value = price;

    id = sid;

    const updateBtn = document.getElementById("sUpdateBtn");
    const addBtn = document.getElementById("sAddBtn");

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

}



async function loadSubject() {
    const subjectCardContainer = document.getElementById("subjectView");
    const subjectText = document.getElementById("subjectText").value.trim();

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

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

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

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

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

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

async function deleteSubject(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 Subject? All lessons and 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 subjectCardContainer = document.getElementById("subjectView");

                const data = {
                    subject_id: id
                };

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

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

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


function subjectClear() {
    const updateBtn = document.getElementById("sUpdateBtn");
    const addBtn = document.getElementById("sAddBtn");

    document.getElementById("sCourse").value = 0;
    document.getElementById("sSubject").value = "";
    document.getElementById("sPrice").value = "";

    updateBtn.classList.remove("d-block");
    updateBtn.classList.add("d-none");
    addBtn.classList.remove("d-none");
    addBtn.classList.add("d-block");
}
// Subject Registration - Mobile Optimization
const subjectMobileStyle = document.createElement("style");
subjectMobileStyle.innerHTML = `
/* Subject Registration - Mobile Optimization */
@media (max-width: 577px) {
    .subject-card {
        flex-direction: column !important;
        align-items: stretch !important;
        gap: 6px;
        padding: 6px 10px !important;
        font-size: 14px !important;
    }

    .subject-card .subject-title {
        width: 100% !important;
        word-break: break-word;
        margin-bottom: 4px;
        font-size: 14px !important;
    }

    .subject-card button {
        width: 100% !important;
        padding: 5px 0;
        font-size: 13px !important;
    }
}
`;
document.head.appendChild(subjectMobileStyle);