<script>
/* ============================================================
   6️⃣ LEDGER ACCOUNTS FORM MODULE
============================================================ */

/* Submit  Accounts */
document.addEventListener("DOMContentLoaded", function(){

    const form = document.getElementById("supplierForm");

    if(form){
        form.addEventListener("submit", function(e){

            e.preventDefault();

            const formData = new FormData(this);

            fetch('../includes/save_supplier.php', {
                method: 'POST',
                body: formData
            })
            .then(res => res.json())
            .then(data => {

                if (data.status === "success") {

                    $("#supplierModalBasic").modal("hide");

                    showToast("Supplier added successfully", "success");
                    refreshsupplier();

                    this.reset();

                } else {

                    showToast(data.message || "Unknown error", "error");

                }

            })
            .catch(err => {
                console.error(err);
                alert("Server error — check console");
            });

        });
    }

});

let supplier_limit = 10;
let supplier_offset = 0;
let supplier_loading = false;
let supplier_finished = false;

$(document).ready(function () {

    loadsupplier();

    $("#supplierScroll").on("scroll", function () {

        if (supplier_loading || supplier_finished) return;

        let container = $(this);

        let scrollTop = container.scrollTop();
        let scrollHeight = container[0].scrollHeight;
        let height = container.height();

        if (scrollTop + height >= scrollHeight - 50) {
            loadsupplier();
        }

    });

});

function loadsupplier() {

    if (supplier_loading || supplier_finished) return;

    supplier_loading = true;

    showLoader3();

    $.ajax({
        url: "fetch_scripts/fetch_supplierlist.php",
        type: "GET",
        data: {
            supplier_limit: supplier_limit,
            supplier_offset: supplier_offset
        },
        dataType: "json",
        success: function (response) {

            hideLoader3();

            if (response.length === 0) {

                supplier_finished = true;

                $("#supplierlist").append(`
                <tr>
                    <td colspan="4" class="text-center text-muted p-3">
                        No more Suppliers
                    </td>
                </tr>
                `);

                return;
            }

            let rows = "";

            response.forEach(function (supplier) {

                let badge = supplier.status.toLowerCase() === "active"
                    ? '<span class="badge badge-success">Active</span>'
                    : '<span class="badge badge-danger">Inactive</span>';
                    
                //let salePrice = Number(product.p_sale_px).toLocaleString();
                //let purchasePrice = Number(product.p_prch_px).toLocaleString();

                rows += `
                <tr class="supplier-row" data-id="${supplier.id}">
                    <td>${supplier.acc_name}</td>
                    <td>${badge}</td>
                </tr>
                `;
            });

            $("#supplierlist").append(rows);

            supplier_offset += supplier_limit;
            supplier_loading = false;
        }
    });
}



function refreshsupplier() {

    supplier_offset = 0;
    supplier_finished = false;
    supplier_loading = false;

    $("#supplierlist").html("");

    loadsupplier();
}

function showLoader3() {

    let loader = `
    <tr id="loadingRow">
        <td colspan="4" class="text-center p-3">
            <div class="spinner-border spinner-border-sm text-primary"></div>
            Loading suppliers...
        </td>
    </tr>
    `;

    $("#supplierlist").append(loader);
}

function hideLoader3() {
    $("#loadingRow").remove();
}

$(document).on("click", ".supplier-row", function () {

    let supplierId = $(this).data("id");

    $.ajax({
        url: "fetch_scripts/get_single_customer.php",
        type: "POST",
        data: { id: supplierId },
        dataType: "json",
        success: function (supplier) {

            $("#edit_sup_id").val(supplier.id);
            $("#edit_sup_name").val(supplier.acc_name);
            $("#edit_sup_status").val(supplier.status);
           
            

            $("#editsupModal").modal("show");
        }
    });
});

$("#editsupForm").submit(function (e) {
    e.preventDefault();

    $.ajax({
        url: "fetch_scripts/update_supplier.php",
        type: "POST",
        data: $(this).serialize(),
        success: function (response) {

            $("#editsupModal").modal("hide");
            showToast("Suppliers updated successfully", "success");
            refreshsupplier();
        }
    });
});


</script>