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

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

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

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

            e.preventDefault();

            const formData = new FormData(this);

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

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

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

                    showToast("Customer added successfully", "success");
                    refreshcustomer();

                    this.reset();

                } else {

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

                }

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

        });
    }

});

let customer_limit = 10;
let customer_offset = 0;
let customer_loading = false;
let customer_finished = false;

$(document).ready(function () {

  //  loadcustomer();

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

        if (customer_loading || customer_finished) return;

        let container = $(this);

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

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

    });

});

function loadcustomer() {

    if (customer_loading || customer_finished) return;

    customer_loading = true;

    showLoader2();

    $.ajax({
        url: "fetch_scripts/fetch_customerlist.php",
        type: "GET",
        data: {
            customer_limit: customer_limit,
            customer_offset: customer_offset
        },
        dataType: "json",
        success: function (response) {

            hideLoader2();

            if (response.length === 0) {

                customer_finished = true;

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

                return;
            }

            let rows = "";

            response.forEach(function (customer) {

                let badge = customer.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="customer-row" data-id="${customer.id}">
                    <td>${customer.acc_name}</td>
                    <td>${badge}</td>
                </tr>
                `;
            });

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

            customer_offset += customer_limit;
            customer_loading = false;
        }
    });
}



function refreshcustomer() {

    customer_offset = 0;
    customer_finished = false;
    customer_loading = false;

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

    loadcustomer();
}

function showLoader2() {

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

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

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

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

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

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

            $("#edit_cust_id").val(customer.id);
            $("#edit_cust_name").val(customer.acc_name);
            $("#edit_cust_status").val(customer.status);
           
            

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

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

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

            $("#editcustModal").modal("hide");
            showToast("Customer updated successfully", "success");
            refreshcustomer();
        }
    });
});


</script>