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

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

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

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

            e.preventDefault();

            const formData = new FormData(this);

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

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

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

                    showToast("Account added successfully", "success");
                    refreshledger();

                    this.reset();

                } else {

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

                }

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

        });
    }

});

let ledger_limit = 10;
let ledger_offset = 0;
let ledger_loading = false;
let ledger_finished = false;

$(document).ready(function () {

    loadLedger();

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

        if (ledger_loading || ledger_finished) return;

        let container = $(this);

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

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

    });

});

function loadLedger() {

    if (ledger_loading || ledger_finished) return;

    ledger_loading = true;

    showLoader1();

    $.ajax({
        url: "fetch_scripts/fetch_ledgerlist.php",
        type: "GET",
        data: {
            ledger_limit: ledger_limit,
            ledger_offset: ledger_offset
        },
        dataType: "json",
        success: function (response) {

            hideLoader1();

            if (response.length === 0) {

                ledger_finished = true;

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

                return;
            }

            let rows = "";

            response.forEach(function (ledger) {

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

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

            ledger_offset += ledger_limit;
            ledger_loading = false;
        }
    });
}



function refreshledger() {

    ledger_offset = 0;
    ledger_finished = false;
    ledger_loading = false;

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

    loadLedger();
}

function showLoader1() {

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

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

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

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

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

    $.ajax({
        url: "fetch_scripts/get_single_ledger.php",
        type: "POST",
        data: { id: ledgerId },
        dataType: "json",
        success: function (ledger) {

            $("#edit_Ledg_id").val(ledger.id);
            $("#edit_account_name").val(ledger.acc_name);
            $("#edit_acc_type").val(ledger.acc_type);
            $("#edit_acc_categ").val(ledger.acc_categ);
            $("#edit_acc_source").val(ledger.acc_source);
            $("#edit_entry_form").val(ledger.entry_form);
            $("#edit_status").val(ledger.status);
            $("#edit_pnl").val(ledger.PnL);
            $("#edit_bl_sheet").val(ledger.bl_sheet);
            

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

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

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

            $("#editLegderModal").modal("hide");
            refreshledger(); // reload table
        }
    });
});


</script>