async function addCategory() {
    const title = document.getElementById("title").value.trim();
    const description = document.getElementById("description").value.trim();
    const imageInput = document.getElementById("image");
    const category_id = document.getElementById("scategory").value;
    const cat_status = document.getElementById("cat_status").value;

    // Basic validation
    if (!title || !description) {
        Swal.fire({ title: "Please fill all required fields.", icon: "warning" });
        return;
    }

    // Function to send data
    async function sendData(imageBase64 = null) {
        const data = {
            title: title,
            description: description,
            status: cat_status,
            category_id: category_id
        };

        if (imageBase64) {
            data.image = imageBase64; // only include if image exists
        }

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

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

            if (json.status) {
                Swal.fire({
                    title: json.message,
                    icon: "success",
                    draggable: true
                }).then(() => {
                    document.getElementById("title").value = "";
                    document.getElementById("description").value = "";
                    imageInput.value = "";
                });
                clearCategoryFields();
            } else {
                Swal.fire({ title: json.message, icon: "warning", draggable: true });
            }
        } catch (err) {
            Swal.fire({ title: "Error: " + err.message, icon: "error", draggable: true });
        }
    }

    // If image selected → convert to Base64 then send
    if (imageInput.files.length > 0) {
        const reader = new FileReader();
        reader.onload = function () {
            sendData(reader.result);
        };
        reader.readAsDataURL(imageInput.files[0]);
    } else {
        // No image → send without it
        sendData();
    }
}


function clearCategoryFields() {
    document.getElementById("title").value = "";
    document.getElementById("description").value = "";
    const imageBox = document.getElementById("categoryImageBox");
    const img = imageBox.querySelector("img");
    document.getElementById("cat_status").value = "0";
    if (img) img.remove();
    document.getElementById("scategory").selectedIndex = 0;

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

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


function clearPreview(box) {
    const img = box.querySelector("img");
    if (img) {
        img.remove();
    }

    // Also reset the file input so user can re-select
    const input = box.querySelector(".file-input");
    if (input) {
        input.value = "";
    }
}


document.addEventListener("DOMContentLoaded", () => {
    document.getElementById("scategory").addEventListener("change", loadCategory);
});

async function loadCategory() {
    try {
        const categoryId = document.getElementById("scategory").value;
        const title = document.getElementById("title");
        const description = document.getElementById("description");
        const cat_status = document.getElementById("cat_status");

        const cAddBtn = document.getElementById("cAddBtn");
        const cUpdateBtn = document.getElementById("cUpdateBtn");



        const response = await fetch(`Backend/Process/GetCatedgoryAllDataProcess.php?id=${categoryId}`, {
            method: "GET",
            headers: {
                "Content-Type": "application/json"
            }
        });

        if (response.ok) {
            const json = await response.json();
            console.log(json);
            if (json.status) {
                console.log("Category Data:", json.data);
                title.value = json.data.title;
                description.value = json.data.description;
                cat_status.value = json.data.category_status_id;
                addPreview(document.getElementById("categoryImageBox"), json.data.img_path);

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

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

            } else {
                console.warn(json.message);
            }

        } else {
            Swal.fire({
                title: "Something went wrong",
                icon: "error",
                draggable: true
            });
        }

    } catch (error) {
        console.error("Error loading category:", error);
        Swal.fire({
            title: "Error loading category",
            text: error.message,
            icon: "error",
            draggable: true
        });
    }
}

function addPreview(box, path) {
    const input = box.querySelector('.file-input');
    const hiddenInput = box.querySelector('#existingImagePath');

    // remove old preview if exists
    let img = box.querySelector('img');
    if (img) img.remove();

    // create preview
    if (path) {
        const imgEl = document.createElement('img');
        imgEl.src = path.startsWith('Backend/') ? path : 'Backend/' + path;
        imgEl.style.maxWidth = '100%';
        imgEl.style.maxHeight = '100%';
        imgEl.style.borderRadius = '10px';
        imgEl.style.objectFit = 'cover';
        imgEl.style.position = 'absolute';
        imgEl.style.top = '0';
        imgEl.style.left = '0';
        box.appendChild(imgEl);
    }

    // store the DB image path
    if (hiddenInput) {
        hiddenInput.value = path;
    }
}



