<script>
/* ============================================================
   6️⃣ WAREHOUSE FORM MODULE
============================================================ */
$("#field2").on("keydown", function(e){

    if(e.key === "."){
        e.preventDefault();
    }

});

$("#field2").on("input", function(){

    this.value = this.value.replace(/\./g,'');

});

$(function () {

    let timer = null;

    $("#submitBtn").prop("disabled", true);

    $("#field2").on("keyup", function () {

        clearTimeout(timer);

        let doc_no = $(this).val();

        $("#submitBtn").prop("disabled", true);

        if (doc_no.length === 0) {
            $("#doc_msg").html("");
            $("#doc_spinner").hide();
            return;
        }

        $("#doc_spinner").show();
        $("#doc_msg").html("");

        timer = setTimeout(function () {

            $.ajax({
                url: "query/check_doc_no.php",
                type: "POST",
                data: { doc_no: doc_no,
                 t_type: $("#field4").val(),
                 comp_id: $("#comp_id").val() 
                },
                dataType: "json",

                success: function (res) {

                    $("#doc_spinner").hide();

                    if (res.exists) {

                        $("#doc_msg")
                            .html("Doc no. exists")
                            .css("color", "red");

                        $("#field2").addClass("is-invalid").removeClass("is-valid");

                        $("#submitBtn").prop("disabled", true);

                    } else {

                        $("#doc_msg")
                            .html("")
                            .css("color", "green");

                        $("#field2").addClass("is-valid").removeClass("is-invalid");

                        $("#submitBtn").prop("disabled", false);
                    }

                },

                error: function () {

                    $("#doc_spinner").hide();

                    $("#doc_msg")
                        .html("Error checking document")
                        .css("color", "orange");

                    $("#submitBtn").prop("disabled", true);
                }

            });

        }, 500);

    });

});

$(document).on("keyup", 'input[name="amt[]"]', function () {
    updateRECTotal();
});

$(document).on("keyup", 'input[name="amt2[]"]', function () {
    updateEXPTotal();
});

$(document).on("keyup", 'input[name="amt3[]"]', function () {
    updateCUSTTotal();
});


//-----------------------------load items for add row
let itemOptions = '';

function loadItems(){

    var comp_id = $('#comp_id').val();

    $.ajax({
        url: "query/fetch_items.php",
        type: "GET",
        data: { comp_id: comp_id },
        dataType: "json",
        success: function(data){

            itemOptions = '<option value="">Select item</option>';

            $.each(data, function(index, item){
                itemOptions += '<option value="'+item.id+'">'+item.p_name+'</option>';
            });

            // populate existing selects
            $('select[name="column1[]"]').html(itemOptions);
        }
    });

}

let accountOptions = '';

function loadAccs(){

var comp_id = $('#comp_id').val();

    $.ajax({
        url: "fetch_scripts/fetch_wallets_1.php",
        type: "GET",
        data: { comp_id: comp_id },
        dataType: "json",
        success: function(data){

            accountOptions = '<option value="">Select Account</option>';
            
            let seen = new Set();
            
            $.each(data, function(index, item){
                
                if(!seen.has(item.id)){
                    seen.add(item.id);
                    accountOptions += ('<option value="'+item.id+'">'+item.acc_name+'</option>');
                }
            });

            // populate existing selects
            $('select[name="accs[]"]').html(accountOptions);
        }
    });

}

let customerOptions = '';

function loadCustomers(){

var comp_id = $('#comp_id').val();

    $.ajax({
        url: "fetch_scripts/fetch_customer_1.php",
        type: "GET",
        data: { comp_id: comp_id },
        dataType: "json",
        success: function(data){

            customerOptions = '<option value="">Select Customer</option>';

             let seen = new Set();
            
            $.each(data, function(index, item){
                
                if(!seen.has(item.id)){
                    seen.add(item.id);
                    customerOptions += ('<option value="'+item.id+'">'+item.acc_name+'</option>');
                }
            });

            // populate existing selects
            $('select[name="cust[]"]').html(customerOptions);
        }
    });

}

let expenseOptions = '';

function loadExp(){

var comp_id = $('#comp_id').val();

    $.ajax({
        url: "fetch_scripts/fetch_expense_1.php",
        type: "GET",
        data: { comp_id: comp_id },
        dataType: "json",
        success: function(data){

            expenseOptions = '<option value="">Select Expense</option>';

            let seen = new Set();
            
            $.each(data, function(index, item){
                
                if(!seen.has(item.id)){
                    seen.add(item.id);
                    expenseOptions += ('<option value="'+item.id+'">'+item.acc_name+'</option>');
                }
            });

            // populate existing selects
            $('select[name="exp[]"]').html(expenseOptions);
        }
    });

}
//--------Load single field--------------------------------------

function loadStorex(){

    var comp_id = $('#comp_id').val();

    if(!comp_id){
        console.log("Company ID missing");
        return;
    }

    $.ajax({
        url: "fetch_scripts/fetch_store_1.php",
        type: "GET",
        data: { comp_id: comp_id },
        dataType: "json",
        success: function(data){

            let select = $("#storex");
            select.empty();

            select.append('<option value="">Select Company</option>');

             let seen = new Set();

            $.each(data, function(index, user){
                if(!seen.has(user.id)){
                    seen.add(user.id);
                    select.append('<option value="'+user.id+'">'+user.acc_name+'</option>');
                }
            });

        },
        error: function(xhr, status, error){
            console.log("AJAX Error:", error);
        }
    });

}

function loadFromAccounts(){

    var comp_id = $('#comp_id').val();

    if(!comp_id){
        console.log("Company ID missing");
        return;
    }

    $.ajax({
        url: "fetch_scripts/fetch_wallets_1.php",
        type: "GET",
        data: { comp_id: comp_id },
        dataType: "json",
        success: function(data){

            let select = $("#cash_acc");
            select.empty();

            select.append('<option value="">Select Account</option>');

             let seen = new Set();

            $.each(data, function(index, user){
                if(!seen.has(user.id)){
                    seen.add(user.id);
                    select.append('<option value="'+user.id+'">'+user.acc_name+'</option>');
                }
            });

            if(data.length === 0){
                //select.append('<option value="">No salespersons found</option>');
            }

        },
        error: function(xhr, status, error){
            console.log("AJAX Error:", error);
        }
    });

}

function loadCustx(){

    var comp_id = $('#comp_id').val();

    if(!comp_id){
        console.log("Company ID missing");
        return;
    }

    $.ajax({
        url: "fetch_scripts/fetch_customer_1.php",
        type: "GET",
        data: { comp_id: comp_id },
        dataType: "json",
        success: function(data){

            let select = $("#customerx");
            select.empty();

            select.append('<option value="">Select Customer</option>');

             let seen = new Set();

            $.each(data, function(index, user){
                if(!seen.has(user.id)){
                    seen.add(user.id);
                    select.append('<option value="'+user.id+'">'+user.acc_name+'</option>');
                }
            });

            if(data.length === 0){
             //   select.append('<option value="">No salespersons found</option>');
            }

        },
        error: function(xhr, status, error){
            console.log("AJAX Error:", error);
        }
    });

}

function loadSalespersons(){

    var comp_id = $('#comp_id').val();

    if(!comp_id){
        console.log("Company ID missing");
        return;
    }

    $.ajax({
        url: "fetch_scripts/fetch_salespersons_1.php",
        type: "GET",
        data: { comp_id: comp_id },
        dataType: "json",
        success: function(data){

            console.log("Response:", data);

            let select = $("#field3");
            select.empty();

            select.append('<option value="">Select Sales person</option>');

            let seen = new Set();

            $.each(data, function(index, user){
                if(!seen.has(user.id)){
                    seen.add(user.id);
                    select.append('<option value="'+user.id+'">'+user.acc_name+'</option>');
                }
            });

            if(data.length === 0){
               // select.append('<option value="">No salespersons found</option>');
            }

        },
        error: function(xhr, status, error){
            console.log("AJAX Error:", error);
            console.log("Response Text:", xhr.responseText);
        }
    });

}


function loadSupplier(){

    var comp_id = $('#comp_id').val();

    if(!comp_id){
        console.log("Company ID missing");
        return;
    }

    $.ajax({
        url: "fetch_scripts/fetch_supplier_1.php",
        type: "GET",
        data: { comp_id: comp_id },
        dataType: "json",
        success: function(data){

            let select = $("#supplier");
            select.empty();

            select.append('<option value="">Select Supplier</option>');

            let seen = new Set();

            $.each(data, function(index, user){
                if(!seen.has(user.id)){
                    seen.add(user.id);
                    select.append('<option value="'+user.id+'">'+user.acc_name+'</option>');
                }
            });

            if(data.length === 0){
            //    select.append('<option value="">No salespersons found</option>');
            }

        },
        error: function(xhr, status, error){
            console.log("AJAX Error:", error);
        }
    });

}

function loadDriver(){

    var comp_id = $('#comp_id').val();

    if(!comp_id){
        console.log("Company ID missing");
        return;
    }

    $.ajax({
        url: "fetch_scripts/fetch_salespersons_1.php",
        type: "GET",
        data: { comp_id: comp_id },
        dataType: "json",
        success: function(data){

            let select = $("#driver");
            select.empty();

            select.append('<option value="">Select Driver</option>');

             let seen = new Set();

            $.each(data, function(index, user){
                if(!seen.has(user.id)){
                    seen.add(user.id);
                    select.append('<option value="'+user.id+'">'+user.acc_name+'</option>');
                }
            });

            if(data.length === 0){
                select.append('<option value="">No salespersons found</option>');
            }

        },
        error: function(xhr, status, error){
            console.log("AJAX Error:", error);
        }
    });

}


$(document).ready(function () {
    let transData = {
        "deliveryLink": { trans_type: "DEL", form_name: "Delivery Note" },
        "grLink": { trans_type: "GR", form_name: "Goods Recieved" },
        "stfrLink": { trans_type: "STFR", form_name: "Stock Transfer" },
        "prchLink": { trans_type: "PRCH", form_name: "Purchases" },
    "retprchLink": { trans_type: "RET PRCH", form_name: "Return Purchases" },
        "recLink": { trans_type: "REC", form_name: "Receipt" },
        "bnkLink": { trans_type: "BNK", form_name: "Banking" },
        "expLink": { trans_type: "EXP", form_name: "Expenses" },
        "ctfrLink": { trans_type: "CTFR", form_name: "Transfers" },
        "csinvLink": { trans_type: "CS INV", form_name: "Cash Invoice" },
        "stkinvLink": { trans_type: "STK INV", form_name: "Stock Invoice" },
        "stkinvretLink": { trans_type: "INV RET", form_name: "Invoice Return" },
        "invpmtLink": { trans_type: "INV PMT", form_name: "Invoice Payment" }
    };

    $(document).on("click", "#deliveryLink, #grLink, #stfrLink,#prchLink,#retprchLink, #recLink, #bnkLink, #expLink, #ctfrLink, #csinvLink, #stkinvLink, #stkinvretLink, #invpmtLink", function () {
        
        event.preventDefault();  
        let id = $(this).attr("id");

        if (transData[id]) {
            let { trans_type, form_name } = transData[id];

            console.log("Transaction Type: " + trans_type);

            $("#field4").val(trans_type);
            $("#form_name").val(form_name);

            if (id === "stfrLink") {
                    // Show and enable relevant fields, hide others
                    $("#field3_group").hide();
                    $("#field3").prop("disabled", true); // Enable Sales Person 
                    
                    $("#Customer_group").hide();
                    $("#customerx").prop("disabled", true);
                    
                    $("#cash_group").hide();
                    $("#cash_acc").prop("disabled", true);
                
                    $("#supplier_group").hide();
                    $("#supplier").prop("disabled", true); // Disable Store
                    
                    $("#storex_group").show();
                    $("#storex").prop("disabled", false); // Disable Store
                
                    $("#loc_group").show();
                    $("#loc").prop("disabled", false); // Enable Storefrom field
                    
                    $("#driver_group").show();
                    $("#driver").prop("disabled", false); // Enable Storefrom field
                    $("#total-field").hide();
                    $("#total-purch-field").show();
                    
                    // Buttons
                    $("#remove-acc-button").hide();
                    $("#add-acc-button").hide();
                    
                    $("#remove-inv-button").show();
                    $("#add-inv-button").show();
                    
                    $("#remove-exp-button").hide();
                    $("#add-exp-button").hide();
                    
                    $("#remove-cust-button").hide();
                    $("#add-cust-button").hide();
                    
                    // Example: inventory mode
                    toggleMyTable(true);
                    toggleAccountsTable(false);
                    toggleExpenseTable(false);
                    toggleCustomerTable(false);
                
                    $('#field2').val(''); // Clear the input
                    resetTableRows();
                
                   // Get the current value of the store_id field on page load
                       // var store_id = $('#storeid').val(); 
                        var sel_co = $('#sel_co').val(); 
                    
                        // Trigger the change event if store_id has a value
                        if (sel_co) {
                            $.ajax({
                                url: "fetch_scripts/get_def_store_id.php",
                                type: "GET",
                                data: { sel_co: sel_co }, // Send selected store ID
                                dataType: "json",
                                success: function (response) {
                                    if (response.store_location) {
                                        $("#whm").val(response.store_location);
                                        $("#comp_id").val(response.comp_id);// Assign store location to input
                                         //loadSalespersons();
                                         loadItems();
                                         loadStorex();
                                         loadDriver();
                                    } else {
                                        $("#whm").val("No data available");
                                    }
                                },
                                error: function (xhr, status, error) {
                                    console.error("AJAX Error: " + status + " - " + error);
                                }
                            });
                        }
        
            }
            
                    else   if (id === "deliveryLink") {
                    // Show and enable relevant fields, hide others
                    $("#field3_group").show();
                    $("#field3").prop("disabled", false); // Enable Sales Person 
                    $("#Customer_group").hide();
                    $("#customerx").prop("disabled", true);
                    
                    $("#cash_group").hide();
                    $("#cash_acc").prop("disabled", true);
                
                    $("#field31_group").hide();
                    $("#field31").prop("disabled", true); // Disable Store field
                
                    $("#loc_group").hide();
                    $("#loc").prop("disabled", false); // Enable Storefrom field
                    
                  $("#supplier_group").hide();
                    $("#supplier").prop("disabled", true); // Disable Store 
                    
                    $("#storex_group").hide();
                    $("#storex").prop("disabled", true); // Disable Store
                
                    $("#driver_group").hide();
                    $("#driver").prop("disabled", true); // Disable Driver field
                
                    $("#total-field").show();
                    $("#total-purch-field").hide();
                    
                    // Buttons
                    $("#remove-acc-button").hide();
                    $("#add-acc-button").hide();
                    
                    $("#remove-inv-button").show();
                    $("#add-inv-button").show();
                    
                    $("#remove-exp-button").hide();
                    $("#add-exp-button").hide();
                    
                    $("#remove-cust-button").hide();
                    $("#add-cust-button").hide();
                    
                    // Example: inventory mode
                    toggleMyTable(true);
                    toggleAccountsTable(false);
                    toggleExpenseTable(false);
                    toggleCustomerTable(false);
                    
                    
                    $('#field2').val(''); // Clear the input
                    resetTableRows();
                
                   // Get the current value of the store_id field on page load
                       // var store_id = $('#storeid').val(); 
                        var sel_co = $('#sel_co').val(); 
                    
                        // Trigger the change event if store_id has a value
                        if (sel_co) {
                            $.ajax({
                                url: "fetch_scripts/get_def_store_id.php",
                                type: "GET",
                                data: { sel_co: sel_co }, // Send selected store ID
                                dataType: "json",
                                success: function (response) {
                                    if (response.store_location) {
                                        $("#whm").val(response.store_location);
                                        $("#comp_id").val(response.comp_id);// Assign store location to input
                                         loadSalespersons();
                                         loadItems();
                                    } else {
                                        $("#whm").val("No data available");
                                    }
                                },
                                error: function (xhr, status, error) {
                                    console.error("AJAX Error: " + status + " - " + error);
                                }
                            });
                        }
                }

            
            else  if (id === "grLink" ){
                    // Show and enable relevant fields, hide others
                    $("#field3_group").show();
                    $("#field3").prop("disabled", false); // Enable Sales Person
                    
                    $("#Customer_group").hide();
                    $("#customerx").prop("disabled", true);
                    
                    $("#cash_group").hide();
                    $("#cash_acc").prop("disabled", true);
                
                    $("#field31_group").hide();
                    $("#field31").prop("disabled", true); // Disable Store field
                
                    $("#loc_group").hide();
                    $("#loc").prop("disabled", false); // Enable Storefrom field
                    
                   $("#supplier_group").hide();
                    $("#supplier").prop("disabled", true); // Disable Store 
                    
                    $("#storex_group").hide();
                    $("#storex").prop("disabled", true); // Disable Store
                
                    $("#driver_group").hide();
                    $("#driver").prop("disabled", true); // Disable Driver field
                
                    $("#total-field").show();
                    $("#total-purch-field").hide();
                    
                    // Buttons
                    $("#remove-acc-button").hide();
                    $("#add-acc-button").hide();
                    
                    $("#remove-inv-button").show();
                    $("#add-inv-button").show();
                    
                    $("#remove-exp-button").hide();
                    $("#add-exp-button").hide();
                    
                    $("#remove-cust-button").hide();
                    $("#add-cust-button").hide();
                    
                    // Example: inventory mode
                    toggleMyTable(true);
                    toggleAccountsTable(false);
                    toggleExpenseTable(false);
                    toggleCustomerTable(false);
                    
                    $('#field2').val(''); // Clear the input
                    resetTableRows();
                
                   // Get the current value of the store_id field on page load
                       // var store_id = $('#storeid').val(); 
                        var sel_co = $('#sel_co').val(); 
                    
                        // Trigger the change event if store_id has a value
                        if (sel_co) {
                            $.ajax({
                                url: "fetch_scripts/get_def_store_id.php",
                                type: "GET",
                                data: { sel_co: sel_co }, // Send selected store ID
                                dataType: "json",
                                success: function (response) {
                                    if (response.store_location) {
                                        $("#whm").val(response.store_location);
                                        $("#comp_id").val(response.comp_id);// Assign store location to input
                                         loadSalespersons();
                                         loadItems();
                                    } else {
                                        $("#whm").val("No data available");
                                    }
                                },
                                error: function (xhr, status, error) {
                                    console.error("AJAX Error: " + status + " - " + error);
                                }
                            });
                        }
        
            }
            
                else  if (id === "prchLink" ){
                    // Show and enable relevant fields, hide others
                    $("#field3_group").hide();
                    $("#field3").prop("disabled", true); // Enable Sales Person 
                    
                    $("#Customer_group").hide();
                    $("#customerx").prop("disabled", true);
                    
                    $("#cash_group").hide();
                    $("#cash_acc").prop("disabled", true);
                
                    $("#supplier_group").show();
                    $("#supplier").prop("disabled", false); // Disable Store 
                    
                    $("#storex_group").hide();
                    $("#storex").prop("disabled", true); // Disable Store
                
                    $("#loc_group").show();
                    $("#loc").prop("disabled", false); // Enable Storefrom field
                    
                    $("#driver_group").show();
                    $("#driver").prop("disabled", false); // Enable Storefrom field
                    $("#total-field").hide();
                    $("#total-purch-field").show();
                    
                    // Buttons
                    $("#remove-acc-button").hide();
                    $("#add-acc-button").hide();
                    
                    $("#remove-inv-button").show();
                    $("#add-inv-button").show();
                    
                    $("#remove-exp-button").hide();
                    $("#add-exp-button").hide();
                    
                    $("#remove-cust-button").hide();
                    $("#add-cust-button").hide();
                    
                    // Example: inventory mode
                    toggleMyTable(true);
                    toggleAccountsTable(false);
                    toggleExpenseTable(false);
                    toggleCustomerTable(false);
                
                    $('#field2').val(''); // Clear the input
                    resetTableRows();
                
                   // Get the current value of the store_id field on page load
                       // var store_id = $('#storeid').val(); 
                        var sel_co = $('#sel_co').val(); 
                    
                        // Trigger the change event if store_id has a value
                        if (sel_co) {
                            $.ajax({
                                url: "fetch_scripts/get_def_store_id.php",
                                type: "GET",
                                data: { sel_co: sel_co }, // Send selected store ID
                                dataType: "json",
                                success: function (response) {
                                    if (response.store_location) {
                                        $("#whm").val(response.store_location);
                                        $("#comp_id").val(response.comp_id);// Assign store location to input
                                         loadSalespersons();
                                         loadItems();
                                         loadSupplier();
                                         loadDriver();
                                    } else {
                                        $("#whm").val("No data available");
                                    }
                                },
                                error: function (xhr, status, error) {
                                    console.error("AJAX Error: " + status + " - " + error);
                                }
                            });
                        }
        
            }
            
                else  if (id === "retprchLink" ){
                    // Show and enable relevant fields, hide others
                    $("#field3_group").hide();
                    $("#field3").prop("disabled", true); // Enable Sales Person 
                    
                    $("#Customer_group").hide();
                    $("#customerx").prop("disabled", true);
                    
                    $("#cash_group").hide();
                    $("#cash_acc").prop("disabled", true);
                
                    $("#supplier_group").show();
                    $("#supplier").prop("disabled", false); // Disable Store 
                    
                    $("#storex_group").hide();
                    $("#storex").prop("disabled", true); // Disable Store
                
                    $("#loc_group").show();
                    $("#loc").prop("disabled", false); // Enable Storefrom field
                    
                    $("#driver_group").show();
                    $("#driver").prop("disabled", false); // Enable Storefrom field
                    $("#total-field").hide();
                    $("#total-purch-field").show();
                    
                    // Buttons
                    $("#remove-acc-button").hide();
                    $("#add-acc-button").hide();
                    
                    $("#remove-inv-button").show();
                    $("#add-inv-button").show();
                    
                    $("#remove-exp-button").hide();
                    $("#add-exp-button").hide();
                    
                    $("#remove-cust-button").hide();
                    $("#add-cust-button").hide();
                    
                    // Example: inventory mode
                    toggleMyTable(true);
                    toggleAccountsTable(false);
                    toggleExpenseTable(false);
                    toggleCustomerTable(false);
                
                    $('#field2').val(''); // Clear the input
                    resetTableRows();
                
                   // Get the current value of the store_id field on page load
                       // var store_id = $('#storeid').val(); 
                        var sel_co = $('#sel_co').val(); 
                    
                        // Trigger the change event if store_id has a value
                        if (sel_co) {
                            $.ajax({
                                url: "fetch_scripts/get_def_store_id.php",
                                type: "GET",
                                data: { sel_co: sel_co }, // Send selected store ID
                                dataType: "json",
                                success: function (response) {
                                    if (response.store_location) {
                                        $("#whm").val(response.store_location);
                                        $("#comp_id").val(response.comp_id);// Assign store location to input
                                         loadSalespersons();
                                         loadItems();
                                         loadSupplier();
                                         loadDriver();
                                    } else {
                                        $("#whm").val("No data available");
                                    }
                                },
                                error: function (xhr, status, error) {
                                    console.error("AJAX Error: " + status + " - " + error);
                                }
                            });
                        }
        
            }
            
            
             else  if (id === "recLink" ){
                    // Show and enable relevant fields, hide others
                    $("#field3_group").show();
                    $("#field3").prop("disabled", false); // Enable Sales Person 
                    $("#Customer_group").hide();
                    $("#customerx").prop("disabled", true);
                    
                    $("#cash_group").hide();
                    $("#cash_acc").prop("disabled", true);
                
                    $("#field31_group").hide();
                    $("#field31").prop("disabled", true); // Disable Store field
                
                    $("#loc_group").hide();
                    $("#loc").prop("disabled", false); // Enable Storefrom field
                    
                   $("#supplier_group").hide();
                    $("#supplier").prop("disabled", true); // Disable Store 
                    
                    $("#storex_group").hide();
                    $("#storex").prop("disabled", true); // Disable Store
                
                    $("#driver_group").hide();
                    $("#driver").prop("disabled", true); // Disable Driver field
                
                    $("#total-field").show();
                    $("#total-purch-field").hide();
                    
                    // Buttons
                    $("#remove-acc-button").show();
                    $("#add-acc-button").show();
                    
                    $("#remove-inv-button").hide();
                    $("#add-inv-button").hide();
                    
                    $("#remove-exp-button").hide();
                    $("#add-exp-button").hide();
                    
                    $("#remove-cust-button").hide();
                    $("#add-cust-button").hide();
                    
                    // Example: accounts mode
                    toggleMyTable(false);
                    toggleAccountsTable(true);
                    toggleExpenseTable(false);
                    toggleCustomerTable(false);
                    
                    $('#field2').val(''); // Clear the input
                    resetTableRows();
                
                   // Get the current value of the store_id field on page load
                       // var store_id = $('#storeid').val(); 
                        var sel_co = $('#sel_co').val(); 
                    
                        // Trigger the change event if store_id has a value
                        if (sel_co) {
                            $.ajax({
                                url: "fetch_scripts/get_def_cash_acc_id.php",
                                type: "GET",
                                data: { sel_co: sel_co }, // Send selected store ID
                                dataType: "json",
                                success: function (response) {
                                    if (response.store_location) {
                                        $("#whm").val(response.store_location);
                                        $("#comp_id").val(response.comp_id);// Assign store location to input
                                         loadSalespersons();
                                         //loadItems();
                                         loadAccs();
                                    } else {
                                        $("#whm").val("No data available");
                                    }
                                },
                                error: function (xhr, status, error) {
                                    console.error("AJAX Error: " + status + " - " + error);
                                }
                            });
                        }
        
            }
            
            else  if (id === "ctfrLink" || id === "bnkLink" ){
                    // Show and enable relevant fields, hide others
                    $("#field3_group").hide();
                    $("#field3").prop("disabled", true); // Enable Sales Person 
                    
                    $("#Customer_group").hide();
                    $("#customerx").prop("disabled", true);
                    
                    $("#cash_group").show();
                    $("#cash_acc").prop("disabled", false);
                
                    $("#field31_group").hide();
                    $("#field31").prop("disabled", true); // Disable Store field
                
                    $("#loc_group").hide();
                    $("#loc").prop("disabled", false); // Enable Storefrom field
                    
                   $("#supplier_group").hide();
                    $("#supplier").prop("disabled", true); // Disable Store 
                    
                    $("#storex_group").hide();
                    $("#storex").prop("disabled", true); // Disable Store
                
                    $("#driver_group").hide();
                    $("#driver").prop("disabled", true); // Disable Driver field
                
                    $("#total-field").show();
                    $("#total-purch-field").hide();
                    
                    // Buttons
                    $("#remove-acc-button").show();
                    $("#add-acc-button").show();
                    
                    $("#remove-inv-button").hide();
                    $("#add-inv-button").hide();
                    
                    $("#remove-exp-button").hide();
                    $("#add-exp-button").hide();
                    
                    $("#remove-cust-button").hide();
                    $("#add-cust-button").hide();
                    
                    // Example: accounts mode
                    toggleMyTable(false);
                    toggleAccountsTable(true);
                    toggleExpenseTable(false);
                    toggleCustomerTable(false);
                    
                    $('#field2').val(''); // Clear the input
                    resetTableRows();
                
                   // Get the current value of the store_id field on page load
                       // var store_id = $('#storeid').val(); 
                        var sel_co = $('#sel_co').val(); 
                    
                        // Trigger the change event if store_id has a value
                        if (sel_co) {
                            $.ajax({
                                url: "fetch_scripts/get_def_cash_acc_id.php",
                                type: "GET",
                                data: { sel_co: sel_co }, // Send selected store ID
                                dataType: "json",
                                success: function (response) {
                                    if (response.store_location) {
                                        $("#whm").val(response.store_location);
                                        $("#comp_id").val(response.comp_id);// Assign store location to input
                                         //loadSalespersons();
                                         //loadItems();
                                         loadAccs();
                                         loadFromAccounts();
                                    } else {
                                        $("#whm").val("No data available");
                                    }
                                },
                                error: function (xhr, status, error) {
                                    console.error("AJAX Error: " + status + " - " + error);
                                }
                            });
                        }
                        $("#Bnk_TFR_SelectFormModal").modal("hide");
            }
            
            else   if (id === "stkinvLink") {
                    // Show and enable relevant fields, hide others
                    $("#field3_group").show();
                    $("#field3").prop("disabled", false); // Enable Sales Person
                    
                    $("#Customer_group").show();
                    $("#customerx").prop("disabled", false);
                    
                    $("#cash_group").hide();
                    $("#cash_acc").prop("disabled", true);
                
                    $("#field31_group").hide();
                    $("#field31").prop("disabled", true); // Disable Store field
                
                    $("#loc_group").hide();
                    $("#loc").prop("disabled", false); // Enable Storefrom field
                    
                  $("#supplier_group").hide();
                    $("#supplier").prop("disabled", true); // Disable Store 
                    
                    $("#storex_group").hide();
                    $("#storex").prop("disabled", true); // Disable Store
                
                    $("#driver_group").hide();
                    $("#driver").prop("disabled", true); // Disable Driver field
                
                    $("#total-field").show();
                    $("#total-purch-field").hide();
                    
                    // Buttons
                    $("#remove-acc-button").hide();
                    $("#add-acc-button").hide();
                    
                    $("#remove-inv-button").show();
                    $("#add-inv-button").show();
                    
                    $("#remove-exp-button").hide();
                    $("#add-exp-button").hide();
                    
                    $("#remove-cust-button").hide();
                    $("#add-cust-button").hide();
                    
                    // Example: inventory mode
                    toggleMyTable(true);
                    toggleAccountsTable(false);
                    toggleExpenseTable(false);
                    toggleCustomerTable(false);
                    
                    
                    $('#field2').val(''); // Clear the input
                    resetTableRows();
                
                   // Get the current value of the store_id field on page load
                       // var store_id = $('#storeid').val(); 
                        var sel_co = $('#sel_co').val(); 
                    
                        // Trigger the change event if store_id has a value
                        if (sel_co) {
                            $.ajax({
                                url: "fetch_scripts/get_def_store_id.php",
                                type: "GET",
                                data: { sel_co: sel_co }, // Send selected store ID
                                dataType: "json",
                                success: function (response) {
                                    if (response.store_location) {
                                        $("#whm").val(response.store_location);
                                        $("#comp_id").val(response.comp_id);// Assign store location to input
                                        loadCustx();
                                         loadSalespersons();
                                         loadItems();
                                    } else {
                                        $("#whm").val("No data available");
                                    }
                                },
                                error: function (xhr, status, error) {
                                    console.error("AJAX Error: " + status + " - " + error);
                                }
                            });
                        }
                        $("#InvoiceSelectFormModal").modal("hide");
                }
                
                else   if (id === "stkinvretLink") {
                    // Show and enable relevant fields, hide others
                    $("#field3_group").show();
                    $("#field3").prop("disabled", false); // Enable Sales Person
                    
                    $("#Customer_group").show();
                    $("#customerx").prop("disabled", false);
                    
                    $("#cash_group").hide();
                    $("#cash_acc").prop("disabled", true);
                
                    $("#field31_group").hide();
                    $("#field31").prop("disabled", true); // Disable Store field
                
                    $("#loc_group").hide();
                    $("#loc").prop("disabled", false); // Enable Storefrom field
                    
                  $("#supplier_group").hide();
                    $("#supplier").prop("disabled", true); // Disable Store 
                    
                    $("#storex_group").hide();
                    $("#storex").prop("disabled", true); // Disable Store
                
                    $("#driver_group").hide();
                    $("#driver").prop("disabled", true); // Disable Driver field
                
                    $("#total-field").show();
                    $("#total-purch-field").hide();
                    
                    // Buttons
                    $("#remove-acc-button").hide();
                    $("#add-acc-button").hide();
                    
                    $("#remove-inv-button").show();
                    $("#add-inv-button").show();
                    
                    $("#remove-exp-button").hide();
                    $("#add-exp-button").hide();
                    
                    $("#remove-cust-button").hide();
                    $("#add-cust-button").hide();
                    
                    // Example: inventory mode
                    toggleMyTable(true);
                    toggleAccountsTable(false);
                    toggleExpenseTable(false);
                    toggleCustomerTable(false);
                    
                    
                    $('#field2').val(''); // Clear the input
                    resetTableRows();
                
                   // Get the current value of the store_id field on page load
                       // var store_id = $('#storeid').val(); 
                        var sel_co = $('#sel_co').val(); 
                    
                        // Trigger the change event if store_id has a value
                        if (sel_co) {
                            $.ajax({
                                url: "fetch_scripts/get_def_store_id.php",
                                type: "GET",
                                data: { sel_co: sel_co }, // Send selected store ID
                                dataType: "json",
                                success: function (response) {
                                    if (response.store_location) {
                                        $("#whm").val(response.store_location);
                                        $("#comp_id").val(response.comp_id);// Assign store location to input
                                        loadCustx();
                                         loadSalespersons();
                                         loadItems();
                                    } else {
                                        $("#whm").val("No data available");
                                    }
                                },
                                error: function (xhr, status, error) {
                                    console.error("AJAX Error: " + status + " - " + error);
                                }
                            });
                        }
                }
            
            else  if (id === "expLink" ){
                    // Show and enable relevant fields, hide others
                    $("#field3_group").hide();
                    $("#field3").prop("disabled", true); // Enable Sales Person
                    
                    $("#Customer_group").hide();
                    $("#customerx").prop("disabled", true);
                    
                    $("#cash_group").show();
                    $("#cash_acc").prop("disabled", false);
                
                    $("#field31_group").hide();
                    $("#field31").prop("disabled", true); // Disable Store field
                
                    $("#loc_group").hide();
                    $("#loc").prop("disabled", false); // Enable Storefrom field
                    
                   $("#supplier_group").hide();
                    $("#supplier").prop("disabled", true); // Disable Store 
                    
                    $("#storex_group").hide();
                    $("#storex").prop("disabled", true); // Disable Store
                
                    $("#driver_group").hide();
                    $("#driver").prop("disabled", true); // Disable Driver field
                
                    $("#total-field").show();
                    $("#total-purch-field").hide();
                    
                    // Buttons
                    $("#remove-acc-button").hide();
                    $("#add-acc-button").hide();
                    
                    $("#remove-inv-button").hide();
                    $("#add-inv-button").hide();
                    
                    $("#remove-exp-button").show();
                    $("#add-exp-button").show();
                    
                    $("#remove-cust-button").hide();
                    $("#add-cust-button").hide();
                    
                    
                    // Example: accounts mode
                    toggleMyTable(false);
                    toggleAccountsTable(false);
                    toggleExpenseTable(true);
                    toggleCustomerTable(false);
                    
                    $('#field2').val(''); // Clear the input
                    resetTableRows();
                
                   // Get the current value of the store_id field on page load
                       // var store_id = $('#storeid').val(); 
                        var sel_co = $('#sel_co').val(); 
                    
                        // Trigger the change event if store_id has a value
                        if (sel_co) {
                            $.ajax({
                                url: "fetch_scripts/get_def_cash_acc_id.php",
                                type: "GET",
                                data: { sel_co: sel_co }, // Send selected store ID
                                dataType: "json",
                                success: function (response) {
                                    if (response.store_location) {
                                        $("#whm").val(response.store_location);
                                        $("#comp_id").val(response.comp_id);// Assign store location to input
                                         //loadSalespersons();
                                         //loadItems();
                                         //loadAccs();
                                         loadExp();
                                         loadFromAccounts();
                                    } else {
                                        $("#whm").val("No data available");
                                    }
                                },
                                error: function (xhr, status, error) {
                                    console.error("AJAX Error: " + status + " - " + error);
                                }
                            });
                        }
        
            }
            
             else  if (id === "csinvLink" ){
                    // Show and enable relevant fields, hide others
                    $("#field3_group").show();
                    $("#field3").prop("disabled", false); // Enable Sales Person
                    
                    $("#Customer_group").hide();
                    $("#customerx").prop("disabled", true);
                    
                    $("#cash_group").hide();
                    $("#cash_acc").prop("disabled", true);
                
                    $("#field31_group").hide();
                    $("#field31").prop("disabled", true); // Disable Store field
                
                    $("#loc_group").hide();
                    $("#loc").prop("disabled", false); // Enable Storefrom field
                    
                   $("#supplier_group").hide();
                    $("#supplier").prop("disabled", true); // Disable Store 
                    
                    $("#storex_group").hide();
                    $("#storex").prop("disabled", true); // Disable Store
                
                    $("#driver_group").hide();
                    $("#driver").prop("disabled", true); // Disable Driver field
                
                    $("#total-field").show();
                    $("#total-purch-field").hide();
                    
                    // Buttons
                    $("#remove-acc-button").hide();
                    $("#add-acc-button").hide();
                    
                    $("#remove-inv-button").hide();
                    $("#add-inv-button").hide();
                    
                    $("#remove-exp-button").hide();
                    $("#add-exp-button").hide();
                    
                    $("#remove-cust-button").show();
                    $("#add-cust-button").show();
                    
                    // Example: accounts mode
                    toggleMyTable(false);
                    toggleAccountsTable(false);
                    toggleExpenseTable(false);
                    toggleCustomerTable(true);
                    
                    $('#field2').val(''); // Clear the input
                    resetTableRows();
                
                   // Get the current value of the store_id field on page load
                       // var store_id = $('#storeid').val(); 
                        var sel_co = $('#sel_co').val(); 
                    
                        // Trigger the change event if store_id has a value
                        if (sel_co) {
                            $.ajax({
                                url: "fetch_scripts/get_def_cash_acc_id.php",
                                type: "GET",
                                data: { sel_co: sel_co }, // Send selected store ID
                                dataType: "json",
                                success: function (response) {
                                    if (response.store_location) {
                                        $("#whm").val(response.store_location);
                                        $("#comp_id").val(response.comp_id);// Assign store location to input
                                         loadSalespersons();
                                         //loadItems();
                                         loadCustomers();
                                    } else {
                                        $("#whm").val("No data available");
                                    }
                                },
                                error: function (xhr, status, error) {
                                    console.error("AJAX Error: " + status + " - " + error);
                                }
                            });
                        }
                     $("#InvoiceSelectFormModal").modal("hide");
            }
            
            else  if (id === "invpmtLink" ){
                    // Show and enable relevant fields, hide others
                    $("#field3_group").show();
                    $("#field3").prop("disabled", false); // Enable Sales Person 
                    $("#Customer_group").show();
                    $("#customerx").prop("disabled", false);
                    
                    $("#cash_group").hide();
                    $("#cash_acc").prop("disabled", true);
                
                    $("#field31_group").hide();
                    $("#field31").prop("disabled", true); // Disable Store field
                
                    $("#loc_group").hide();
                    $("#loc").prop("disabled", false); // Enable Storefrom field
                    
                   $("#supplier_group").hide();
                    $("#supplier").prop("disabled", true); // Disable Store 
                    
                    $("#storex_group").hide();
                    $("#storex").prop("disabled", true); // Disable Store
                
                    $("#driver_group").hide();
                    $("#driver").prop("disabled", true); // Disable Driver field
                
                    $("#total-field").show();
                    $("#total-purch-field").hide();
                    
                    // Buttons
                    $("#remove-acc-button").show();
                    $("#add-acc-button").show();
                    
                    $("#remove-inv-button").hide();
                    $("#add-inv-button").hide();
                    
                    $("#remove-exp-button").hide();
                    $("#add-exp-button").hide();
                    
                    $("#remove-cust-button").hide();
                    $("#add-cust-button").hide();
                    
                    // Example: accounts mode
                    toggleMyTable(false);
                    toggleAccountsTable(true);
                    toggleExpenseTable(false);
                    toggleCustomerTable(false);
                    
                    $('#field2').val(''); // Clear the input
                    resetTableRows();
                
                   // Get the current value of the store_id field on page load
                       // var store_id = $('#storeid').val(); 
                        var sel_co = $('#sel_co').val(); 
                    
                        // Trigger the change event if store_id has a value
                        if (sel_co) {
                            $.ajax({
                                url: "fetch_scripts/get_def_cash_acc_id.php",
                                type: "GET",
                                data: { sel_co: sel_co }, // Send selected store ID
                                dataType: "json",
                                success: function (response) {
                                    if (response.store_location) {
                                        $("#whm").val(response.store_location);
                                        $("#comp_id").val(response.comp_id);// Assign store location to input
                                         loadSalespersons();
                                         loadCustx();
                                         //loadItems();
                                         loadAccs();
                                    } else {
                                        $("#whm").val("No data available");
                                    }
                                },
                                error: function (xhr, status, error) {
                                    console.error("AJAX Error: " + status + " - " + error);
                                }
                            });
                        }
        
            }
            

            if ($("#Modaldelivery").length) {
                $("#Modaldelivery").modal("show");
                $("#inventoryActionSheet").modal("hide");
                 $("#cashierActionSheet").modal("hide");
                 $("#PanelRight").modal("hide");
                 $("#PanelRight_1").modal("hide");
            }
        }
    });
});

// Add Permission to Categories
$(document).on("click", ".openDelModal", function () {
    
    resetTableRows();
    // Close action sheet first
   // $("#Modaldelivery").modal("show");
    

    // Wait until it's closed, then open product modal
    setTimeout(function () {
    //    $("#inventoryActionSheet").modal("hide");
    }, 400);

});


 function populateColumns(selectElement) {
    var selectedOption = selectElement.value;
    var row = selectElement.closest("tr");  // Ensure we get the correct table row
     // Find hidden columns input
    var column3Input = row.querySelector("input[name='column3[]']"); 
    var column4Input = row.querySelector("input[name='column4[]']");
    var column5Input = row.querySelector("input[name='column5[]']");
    var column6Input = row.querySelector("input[name='column6[]']");
    var column7Input = row.querySelector("input[name='column7[]']");
    var column8Input = row.querySelector("input[name='column8[]']");
    var column9Input = row.querySelector("input[name='column9[]']");
    var column10Input = row.querySelector("input[name='column10[]']");
    var column11Input = row.querySelector("input[name='column11[]']");
    
    if (!selectedOption) {
        column3Input.value = ""; // Clear the field if no option is selected
        column4Input.value = ""; // Clear the field if no option is selected
        column5Input.value = "";
        column6Input.value = "";
        column7Input.value = "";
        column8Input.value = "";
        column9Input.value = "";
        column10Input.value = "";
        column11Input.value = "";
        return;
    }

    // Use Fetch API instead of XMLHttpRequest
    fetch("query/fetch_delivery_data.php?selectedOption=" + encodeURIComponent(selectedOption))
        .then(response => {
            if (!response.ok) {
                throw new Error("HTTP error! Status: " + response.status);
            }
            return response.json();
        })
        .then(data => {
            column3Input.value = data.column3 || ""; // Assign value from
            column4Input.value = data.column4 || ""; // Assign value 
            column5Input.value = data.column5 || ""; 
            column6Input.value = data.column6 || ""; 
            column7Input.value = data.column7 || ""; 
            column8Input.value = data.column8 || ""; 
            column9Input.value = data.column9 || ""; 
            column10Input.value = data.column10 || ""; 
            column11Input.value = data.column11 || ""; 
        })
        .catch(error => {
            console.error("Error fetching data:", error);
        });
}

function updateTotal() {

    let total = 0;

    $(".row-total").each(function () {

        let value = parseFloat($(this).val()) || 0;

        total += value;

    });

    $("#total-field").val(total.toLocaleString());

}

function updatePurchTotal() {

    let total = 0;

    $(".row-purch-total").each(function () {

        let value = parseFloat($(this).val()) || 0;

        total += value;

    });

    $("#total-purch-field").val(total.toLocaleString());

}

function updateRECTotal() {

    let total = 0;

    $(".row-rec-total").each(function () {

        let value = parseFloat($(this).val()) || 0;

        total += value;

    });

    $("#total-field").val(total.toLocaleString());

}

function updateEXPTotal() {

    let total = 0;

    $(".row-exp-total").each(function () {

        let value = parseFloat($(this).val()) || 0;

        total += value;

    });

    $("#total-field").val(total.toLocaleString());

}

function updateCUSTTotal() {

    let total = 0;

    $(".row-cust-total").each(function () {

        let value = parseFloat($(this).val()) || 0;

        total += value;

    });

    $("#total-field").val(total.toLocaleString());

}

    function updateAmount(row) {
        var quantity = parseFloat(row.querySelector('input[name="column2[]"]').value);
        var ratesale = parseFloat(row.querySelector('input[name="column3[]"]').value);
        var ratepur = parseFloat(row.querySelector('input[name="column4[]"]').value);
        var salecomm = parseFloat(row.querySelector('input[name="column5[]"]').value);
        var margin = parseFloat(row.querySelector('input[name="column6[]"]').value);
        var sku = parseFloat(row.querySelector('input[name="column7[]"]').value);
        var prchcomm = parseFloat(row.querySelector('input[name="column8[]"]').value);
        var admfee = parseFloat(row.querySelector('input[name="column9[]"]').value);
        var salevat = parseFloat(row.querySelector('input[name="column10[]"]').value);
        var inpvat = parseFloat(row.querySelector('input[name="column11[]"]').value);
        
            var totsale = quantity * ratesale || 0; 
            var totpur = quantity * ratepur || 0; 
            var totsalecomm = quantity * salecomm || 0;
            var totmargin = quantity * margin || 0; 
            var totsku = quantity * sku || 0; 
            var totpurcomm = quantity * prchcomm || 0; 
            var totadmfee = quantity * admfee || 0; 
            var totsalevat = quantity * salevat || 0; 
            var totinpvat = quantity * inpvat || 0; 
          
        
          var col33 = row.querySelector('input[name="column33[]"]');
          col33.value = (totsale.toFixed(0));
          var col44 = row.querySelector('input[name="column44[]"]');
          col44.value = (totpur.toFixed(0));
          var col55 = row.querySelector('input[name="column55[]"]');
          col55.value = (totsalecomm.toFixed(0));
          var col66 = row.querySelector('input[name="column66[]"]');
          col66.value = (totmargin.toFixed(0));
          var col77 = row.querySelector('input[name="column77[]"]');
          col77.value = (totsku.toFixed(0));
          var col88 = row.querySelector('input[name="column88[]"]');
          col88.value = (totpurcomm.toFixed(0));
          var col99 = row.querySelector('input[name="column99[]"]');
          col99.value = (totadmfee.toFixed(0));
          var col100 = row.querySelector('input[name="column100[]"]');
          col100.value = (totsalevat.toFixed(0));
          var col1110 = row.querySelector('input[name="column1110[]"]');
          col1110.value = (totinpvat.toFixed(0));
          
  }
  
// Add an event listener to the table to listen for changes in the input fields
  document.getElementById('my-table').addEventListener('input', function (event) {
    var target = event.target;
    if (target.tagName === 'INPUT') {
      var row = target.closest('tr');
      updateAmount(row);
      updateTotal();
      updatePurchTotal();
    }
  });

    function addRow() {
      var table = document.getElementById("my-table");
      var newRow = table.insertRow();
    newRow.innerHTML = `

    <td>
         <div class="col-6">
                <div class="form-group basic">
                  <div class="input-wrapper">
                  <select name="column1[]" class="form-control" onchange="populateColumns(this)" required style="width:170px;">
                         ${itemOptions}
                        
                    
        
                 </select>  
               </div>
          </div>
        </div>

            </td>
            <td>
              <div class="col-6">
                <div class="form-group basic">
                  <div class="input-wrapper">
                <input type="number" name="column2[]" placeholder="0"  class="form-control" min="1" required style="width: 110px;">
                <td class="hidden hidden-fields">
                    <input type="hidden" class="form-control"  name="column3[]"  ></td>
                 <td class="hidden hidden-fields">
                    <input type="hidden" class="form-control row-total"  name="column33[]"  ></td>
                 <td class="hidden hidden-fields"><input type="hidden" name="column4[]" class="form-control form-field hidden"></td>
                  <td class="hidden hidden-fields">
                    <input type="hidden" class="form-control row-purch-total"  name="column44[]"  ></td>
                
                 <td class="hidden hidden-fields"><input type="hidden" name="column5[]" class="form-control form-field hidden"></td>
                  <td class="hidden hidden-fields">
                    <input type="hidden" class="form-control"  name="column55[]"  ></td>
                 
                 <td class="hidden hidden-fields"><input type="hidden" name="column6[]" class="form-control form-field hidden"></td>
                  <td class="hidden hidden-fields">
                    <input type="hidden" class="form-control"  name="column66[]"  ></td>
                 
                 <td class="hidden hidden-fields"><input type="hidden" name="column7[]" class="form-control form-field hidden"></td>
                  <td class="hidden hidden-fields">
                    <input type="hidden" class="form-control"  name="column77[]"  ></td>
                 
                 <td class="hidden hidden-fields"><input type="hidden" name="column8[]" class="form-control form-field hidden"></td>
                  <td class="hidden hidden-fields">
                    <input type="hidden" class="form-control"  name="column88[]"  ></td>
                 
                 <td class="hidden hidden-fields"><input type="hidden" name="column9[]" class="form-control form-field hidden"></td>
                  <td class="hidden hidden-fields">
                    <input type="hidden" class="form-control"  name="column99[]"  ></td>
                 
                 <td class="hidden hidden-fields"><input type="hidden" name="column10[]" class="form-control form-field hidden"></td>
                  <td class="hidden hidden-fields">
                    <input type="hidden" class="form-control"  name="column100[]"  ></td>
                 
                 <td class="hidden hidden-fields"><input type="hidden" name="column11[]" class="form-control form-field hidden"></td>
                  <td class="hidden hidden-fields">
                    <input type="hidden" class="form-control"  name="column1110[]"  ></td>
                
                </div>
               
          </div>
        </div>
    `;
    
    // Update amounts for the new row
    updateAmount(newRow);
   updateTotal();
   updatePurchTotal();
    }
    
function removeRow() {
      var table = document.getElementById("my-table");
      if (table.rows.length > 2) {
        table.deleteRow(-1);
        updateTotal();
        updatePurchTotal();
      }
    }

function resetTableRows() {
    let table = document.getElementById("my-table");
    let table2 = document.getElementById("accounts-table");
    let table3 = document.getElementById("expense-table");
    let table4 = document.getElementById("customer-table");

    // Keep only the first row (header row or a default row)
    while (table.rows.length > 2) { // Keeps the first row (if table has headers, adjust index accordingly)
        table.deleteRow(1);  // Always remove the second row
    }
    
    while (table2.rows.length > 2) { // Keeps the first row (if table has headers, adjust index accordingly)
        table2.deleteRow(1);  // Always remove the second row
    }
    
    while (table3.rows.length > 2) { // Keeps the first row (if table has headers, adjust index accordingly)
        table3.deleteRow(1);  // Always remove the second row
    }
    
    while (table4.rows.length > 2) { // Keeps the first row (if table has headers, adjust index accordingly)
        table4.deleteRow(1);  // Always remove the second row
    }
    updateTotal();
    updatePurchTotal();
     $("#doc_msg")
                            .html("")
                            .css("color", "green");
    // Reset the first row input fields
    $('#my-table tbody tr:first-child input, #my-table tbody tr:first-child select').val('');
    $('#accounts-table tbody tr:first-child input, #accounts-table tbody tr:first-child select').val('');
    $('#expense-table tbody tr:first-child input, #expense-table tbody tr:first-child select').val('');
    $('#customer-table tbody tr:first-child input, #customer-table tbody tr:first-child select').val('');
}

        function removeRECRow() {
              var table = document.getElementById("accounts-table");
              if (table.rows.length > 2) {
                table.deleteRow(-1);
                updateRECTotal();
              }
            }

    function addRECRow() {
      var table = document.getElementById("accounts-table");
      var newRow = table.insertRow();
    newRow.innerHTML = `

            <td>
                    
                        <div class="form-group basic">
                            <select name="accs[]" class="form-control" style="width:170px;">
                                 ${accountOptions}
                            </select>
                        </div>
                  
                        </td>
                        <td>
                   
                        <div class="form-group basic">
                            <input type="number" name="amt[]" class="form-control row-rec-total" >
                        </div>
                  
                        </td>
    `;
    
    // Update amounts for the new row
    updateRECTotal();
    }
    
    function removeEXPRow() {
              var table = document.getElementById("expense-table");
              if (table.rows.length > 2) {
                table.deleteRow(-1);
                updateEXPTotal();
              }
            }

    function addEXPRow() {
      var table = document.getElementById("expense-table");
      var newRow = table.insertRow();
    newRow.innerHTML = `

            <td>
                    
           <div class="form-group basic">
                <select name="exp[]" class="form-control" >
                       ${expenseOptions}
                </select>
            </div>
            </td>
            
            <td>
            <div class="form-group basic">
               <input type="text" name="desc[]" class="form-control" >
            </div>
            
            </td>
            <td>
       
            <div class="form-group basic">
                <input type="number" name="amt2[]" class="form-control row-exp-total" >
            </div>
       
            </td>
    `;
    
    // Update amounts for the new row
    updateEXPTotal();
    }
    
        function removeCUSTRow() {
              var table = document.getElementById("customer-table");
              if (table.rows.length > 2) {
                table.deleteRow(-1);
                updateCUSTTotal();
              }
            }

    function addCUSTRow() {
      var table = document.getElementById("customer-table");
      var newRow = table.insertRow();
    newRow.innerHTML = `

            <td>
                    
              <div class="form-group basic">
                        <select name="cust[]" class="form-control" style="width:170px;">
                            ${customerOptions}
                        </select>
                    </div>
               
                    </td>
                    <td>
               
                    <div class="form-group basic">
                        <input type="number" name="amt3[]" class="form-control row-cust-total" >
                    </div>
                  
                        </td>
    `;
    
    // Update amounts for the new row
    updateCUSTTotal();
    }


function toggleMyTable(show) {
    if (show) {
        $("#my-table").show();

        // Enable inputs
        $("#my-table").find("input, select").prop("disabled", false);

        // Make them required
        $("#my-table").find('select[name="column1[]"]').prop("required", true);
        $("#my-table").find('input[name="column2[]"]').prop("required", true);

    } else {
        $("#my-table").hide();

        // Disable inputs (VERY IMPORTANT)
        $("#my-table").find("input, select").prop("disabled", true);

        // Remove required
        $("#my-table").find('select[name="column1[]"]').prop("required", false);
        $("#my-table").find('input[name="column2[]"]').prop("required", false);

        // Optional: clear values to avoid junk submission
        $("#my-table").find("input, select").val("");
    }
}

function toggleAccountsTable(show) {
    if (show) {
        $("#accounts-table").show();

        // Enable inputs
        $("#accounts-table").find("input, select").prop("disabled", false);

        // Make required
        $("#accounts-table").find('select[name="accs[]"]').prop("required", true);
        $("#accounts-table").find('input[name="amt[]"]').prop("required", true);

    } else {
        $("#accounts-table").hide();

        // Disable inputs (prevents validation + submission)
        $("#accounts-table").find("input, select").prop("disabled", true);

        // Remove required
        $("#accounts-table").find('select[name="accs[]"]').prop("required", false);
        $("#accounts-table").find('input[name="amt[]"]').prop("required", false);

        // Optional: clear values
        $("#accounts-table").find("input, select").val("");
    }
}

function toggleExpenseTable(show) {
    if (show) {
        $("#expense-table").show();

        // Enable inputs
        $("#expense-table").find("input, select").prop("disabled", false);

        // Make required
        $("#expense-table").find('select[name="exp[]"]').prop("required", true);
   $("#expense-table").find('input[name="desc[]"]').prop("required", false);
        $("#expense-table").find('input[name="amt2[]"]').prop("required", true);

    } else {
        $("#expense-table").hide();

        // Disable inputs (prevents validation + submission)
        $("#expense-table").find("input, select").prop("disabled", true);

        // Remove required
        $("#expense-table").find('select[name="exp[]"]').prop("required", false);
         $("#expense-table").find('input[name="desc[]"]').prop("required", false);
        $("#expense-table").find('input[name="amt2[]"]').prop("required", false);

        // Optional: clear values
        $("#expense-table").find("input, select").val("");
    }
}

function toggleCustomerTable(show) {
    if (show) {
        $("#customer-table").show();

        // Enable inputs
        $("#customer-table").find("input, select").prop("disabled", false);

        // Make required
        $("#customer-table").find('select[name="cust[]"]').prop("required", true);
        $("#customer-table").find('input[name="amt3[]"]').prop("required", true);

    } else {
        $("#customer-table").hide();

        // Disable inputs (prevents validation + submission)
        $("#customer-table").find("input, select").prop("disabled", true);

        // Remove required
        $("#customer-table").find('select[name="cust[]"]').prop("required", false);
        $("#customer-table").find('input[name="amt3[]"]').prop("required", false);

        // Optional: clear values
        $("#customer-table").find("input, select").val("");
    }
}


$('#add_delivery').on("submit", function(event) {  
    event.preventDefault();  
    if($("#field2").hasClass("is-invalid")){
        e.preventDefault();
        alert("Document number already exists");
    }
 

    let submitButton = $(this).find(':submit');
    submitButton.prop('disabled', true).text('Processing...');

    $.ajax({  
        url: "../includes/sale_order_submit_2.php",  
        method: "POST",  
        data: $(this).serialize(),  
        beforeSend: function() { 
            loader1();
            loader2();
            loader3();
            loader4();
              
       //  $("#Modaldelivery").modal('hide');
       
         // ✅ Reset table + reload
            inv_offset = 0;
            inv_finished = false;
            inv_loading = false;
            
        // ✅ Reset table + reload
            Pinv_offset = 0;
            Pinv_finished = false;
            Pinv_loading = false;
            
        // ✅ Reset table + reload
            csh_offset = 0;
            csh_finished = false;
            csh_loading = false;
            
        // ✅ Reset table + reload
            Pcsh_offset = 0;
            Pcsh_finished = false;
            Pcsh_loading = false;

   // $("#todaysinventory").html(""); // clear table

           //showLoader4();
            //loader();
           // $("#pleasehold").modal('show'); // Show loading modal  
        }  
    })
    .done(function(response) { 
        showToast("Submitted successfully", "success");
         resetTableRows();
         $('#add_delivery')[0].reset();// Reset the form after success
     
    loadPendinv(true); // 👈 call your fetch function with reset 
    loadinv(true); // 👈 call your fetch function with reset
       // $("#pleasehold").modal('hide');
       currentstocks();
       loadPendcsh(true); 
       loadTodaycsh(true); 
       
       
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
      //  $("#pleasehold").modal('hide');
        alert("Error: " + textStatus + "\n" + errorThrown + "\nResponse: " + jqXHR.responseText);
    })
    .always(function() {
        submitButton.prop('disabled', false).text('Submit'); // Reset button state
    });
});



//Fetch Todays's Records--------------------------------------------------

function loadinv(reset = false) {

    // ✅ Reset mode (when store changes)
    if (reset) {
        inv_offset = 0;
        inv_finished = false;
        inv_loading = false;
        $("#todaysinventory").html("");
       
    }

    if (!storeid) {
        console.warn("storeid not ready");
        return;
    }

    if (inv_loading || inv_finished) {
        return;
    }

    inv_loading = true;
    showLoader3();

    console.log("Loading...", { storeid, inv_offset });

    $.ajax({
        url: "fetch_scripts/fetch_sale_transactions.php",
        type: "GET",
        data: {
            inv_limit: inv_limit,
            inv_offset: inv_offset,
            storeid: storeid
        },
        dataType: "json",

        success: function (response) {

            hideLoader3();

            if (!response || response.length === 0) {

                inv_finished = true;

                if (inv_offset === 0) {
                      // ❌ No data at all → hide whole section
                        $(".todays-transactions").hide();
                        
                    $("#todaysinventory").html(`
                        <tr>
                            <td colspan="4" class="text-center text-muted p-3">
                                No Transactions Found
                            </td>
                        </tr>
                    `);
                } else {
                    $(".todays-transactions").show();
                    $("#todaysinventory").append(`
                        <tr>
                            <td colspan="4" class="text-center text-muted p-3">
                                No more Transactions
                            </td>
                        </tr>
                    `);
                }

                return;
            }

            let rows = "";

            response.forEach(function (inv) {

                    let status = (inv.t_status || "").toLowerCase();
                    let t_type = (inv.t_type || "").toLowerCase();
                
                   let badge = '';
                   let dateStyle = '';

               if (status === "confirmed" && t_type === "del") {
                    badge = '<span class="badge badge-success">Confirmed</span>';
                    dateStyle = "text-del";
                
                } else if (status === "confirmed" && t_type === "gr") {
                    badge = '<span class="badge badge-success">Confirmed</span>';
                    dateStyle = "text-pink";
                
                } else {
                    dateStyle = "text-warning";
                }
                                
                    let total = Number(inv.total_result || 0).toLocaleString('en-UG');
                
                    rows += `
                    <tr data-toggle="modal" class="inv-row" data-id="${inv.t_doc_no}"
                        data-loc_id="${inv.co_id}"
                        data-ord="${inv.t_doc_no}"
                        data-type="${inv.t_type}" data-target="#ModalBasic">
                        <td class="${dateStyle}">${inv.t_doc_no || ''}</td>
                        <td class="${dateStyle}">${inv.acc_name || ''}</td>
                        <td class="${dateStyle}">${inv.t_type || ''}</td>
                        <td class="${dateStyle}">${total}</td>
                     
                    </tr>
                    `;
                });
            $(".todays-transactions").show();
            $("#todaysinventory").append(rows);

            inv_offset += inv_limit;
            inv_loading = false;
        },

        error: function () {
            console.error("Failed to load inventory");
            inv_loading = false; // ✅ prevent freeze
            hideLoader3();
        }
    });
}

$(document).on("click", ".inv-row", function() {
    var loc_id = $(this).data("loc_id");
    var ord_no = $(this).data("ord");
    var t_type = $(this).data("type");

    // Set hidden fields if needed
    $('#loc_id').val(loc_id);
    $('#ord_no').val(ord_no);
    $('#t_type').val(t_type);

    // Pass all parameters correctly
    fetchBalances(loc_id, ord_no, t_type);
    
    
});

function fetchBalances(loc_id, ord_no, t_type, usr_id) {
    let dailyrep = $('#dailyrep'); // Cache the selector for better performance
    let dailyrepx = $('#dailyrep1'); // Cache the selector for better performance
    let dailyrepy = $('#dailyrep2'); // Cache the selector for better performance


    // Show loading indicator
    dailyrep.html(`
        <tr>
            <td colspan="4" class="text-center">
                <div class="spinner-border spinner-border-sm text-primary" role="status"></div>
            </td>
        </tr>
    `);
     dailyrepx.html(`
        <tr>
            <td colspan="4" class="text-center">
                <div class="spinner-border spinner-border-sm text-light" role="status"></div>
            </td>
        </tr>
    `);
    
    dailyrepy.html(`
        <tr>
            <td colspan="4" class="text-center">
                <div class="spinner-border spinner-border-sm text-light" role="status"></div>
            </td>
        </tr>
    `);

    $.ajax({
        url: 'query/fetch_order_details_head.php',
        type: 'GET',
        data: {loc_id: loc_id, ord_no: ord_no, t_type: t_type },
        dataType: 'html',
        success: function(response) {
            dailyrep.html(response);
            fetchBalances1(loc_id, ord_no, t_type);
            
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error("AJAX Error:", textStatus, errorThrown, jqXHR.responseText);
            dailyrep.html(`
                <tr>
                    <td colspan="4" class="text-center text-danger">
                        Failed to load data. Please refresh and try again.
                    </td>
                </tr>
            `);
        }
    });
}

function fetchBalances1(loc_id, ord_no, t_type, usr_id) {
    let dailyrep1 = $('#dailyrep1'); // Cache the selector for better performance

    // Show loading indicator
    dailyrep1.html(`
        <tr>
            <td colspan="4" class="text-center">
                <div class="spinner-border spinner-border-sm text-warning" role="status"></div>
            </td>
        </tr>
    `);

    $.ajax({
        url: 'query/fetch_order_details_trans.php',
        type: 'GET',
        data: {loc_id: loc_id, ord_no: ord_no, t_type: t_type },
        dataType: 'html',
        success: function(response) {
            dailyrep1.html(response);
            fetchBalances2(loc_id, ord_no, t_type);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error("AJAX Error:", textStatus, errorThrown, jqXHR.responseText);
            dailyrep1.html(`
                <tr>
                    <td colspan="4" class="text-center text-danger">
                        Failed to load data. Please refresh and try again.
                    </td>
                </tr>
            `);
        }
    });
}

function fetchBalances2(loc_id, ord_no, t_type) {
    let dailyrep2 = $('#dailyrep2'); // Cache the selector for better performance

    // Show loading indicator
    dailyrep2.html(`
        <tr>
            <td colspan="4" class="text-center">
                <div class="spinner-border spinner-border-sm text-secondary" role="status"></div>
            </td>
        </tr>
    `);

    $.ajax({
        url: 'query/fetch_entry_details.php',
        type: 'GET',
        data: {loc_id: loc_id, ord_no: ord_no, t_type: t_type },
        dataType: 'html',
        success: function(response) {
            dailyrep2.html(response);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error("AJAX Error:", textStatus, errorThrown, jqXHR.responseText);
            dailyrep2.html(`
                <tr>
                    <td colspan="4" class="text-center text-danger">
                        Failed to load data. Please refresh and try again.
                    </td>
                </tr>
            `);
        }
    });
}

$(document).on("submit", "#DeleteForm", function(event) {  
    event.preventDefault();  // Prevent default form submission

    console.log("Submitting Form:", $(this).serialize()); // Debugging

    $.ajax({  
        url: "query/delete_inv.php",  
        method: "POST",  
        data: $(this).serialize(),  
        beforeSend: function () {  
            console.log("AJAX Request Sent...");
            $('#ModalBasic').modal('hide'); // Hide modal
            loader1();
            loader2();
            loader3();
            loader4();
        },  
        success: function (response) {  
        // ✅ Reset table + reload
            inv_offset = 0;
            inv_finished = false;
            inv_loading = false;
            
        // ✅ Reset table + reload
            Pinv_offset = 0;
            Pinv_finished = false;
            Pinv_loading = false;
            
        // ✅ Reset table + reload
            csh_offset = 0;
            csh_finished = false;
            csh_loading = false;
            
        // ✅ Reset table + reload
            Pcsh_offset = 0;
            Pcsh_finished = false;
            Pcsh_loading = false;

    $("#todaysinventory").html(""); // clear table
    
    loadPendinv(true); 
    loadinv(true); // 👈 call your fetch function with reset
    currentstocks();
    loadPendcsh(true); 
    loadTodaycsh(true); 

            
            
        },
        error: function (xhr, status, error) {
            console.error("AJAX Error:", error, xhr.responseText);
            alert("Submission failed! Error: " + xhr.responseText);
        }
    });  
});

	  function loader1() {
            $('#todaysinventory').html(`
                <tr>
                    <td colspan="5" class="text-center">
                        <div class="spinner-border spinner-border-sm text-danger"></div>
                    </td>
                </tr>
            `); // Show centered loading spinner inside the table
	  }
	  
	  function loader2() {
            $('#pendinginventory').html(`
                <tr>
                    <td colspan="5" class="text-center">
                       <div class="spinner-border spinner-border-sm text-danger"></div>
                    </td>
                </tr>
            `); // Show centered loading spinner inside the table
	  }
	  
	  function loader3() {
            $('#pendingcash').html(`
                <tr>
                    <td colspan="5" class="text-center">
                       <div class="spinner-border spinner-border-sm text-danger"></div>
                    </td>
                </tr>
            `); // Show centered loading spinner inside the table
	  }
	  
	  function loader4() {
            $('#todayscash').html(`
                <tr>
                    <td colspan="5" class="text-center">
                       <div class="spinner-border spinner-border-sm text-danger"></div>
                    </td>
                </tr>
            `); // Show centered loading spinner inside the table
	  }




$(document).ready(function () {
    
    showLoader3();

    loadinv();

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

        if (inv_loading || inv_finished) return;

        let container = $(this);

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

        if (
    container[0].scrollHeight > container.innerHeight() &&
    scrollTop + height >= scrollHeight - 50
) {
    loadinv();
}

    });

});



function showLoader3() {

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

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

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

//----------------------------------------------------------------------
//Fetch Todays's Records--------------------------------------------------

function loadPendinv(reset = false) {

    // ✅ Reset mode (when store changes)
    if (reset) {
        Pinv_offset = 0;
        Pinv_finished = false;
        Pinv_loading = false;
        $("#pendinginventory").html("");
       
    }

    if (!storeid) {
        console.warn("storeid not ready");
        return;
    }

    if (Pinv_loading || Pinv_finished) {
        return;
    }

    Pinv_loading = true;
    showLoader4();

    console.log("Loading...", { storeid, Pinv_offset });

    $.ajax({
        url: "fetch_scripts/fetch_inv_pending_transactions.php",
        type: "GET",
        data: {
            Pinv_limit: Pinv_limit,
            Pinv_offset: Pinv_offset,
            storeid: storeid
        },
        dataType: "json",

        success: function (response) {

            hideLoader4();

            if (!response || response.length === 0) {

                Pinv_finished = true;

                if (Pinv_offset === 0) {
                      // ❌ No data at all → hide whole section
                        $(".pending-invoice-transactions").hide();
                        
                    $("#pendinginventory").html(`
                        <tr>
                            <td colspan="4" class="text-center text-muted p-3">
                                No Transactions Found
                            </td>
                        </tr>
                    `);
                } else {
                    $(".pending-invoice-transactions").show();
                    $("#pendinginventory").append(`
                        <tr>
                            <td colspan="4" class="text-center text-muted p-3">
                                No more Transactions
                            </td>
                        </tr>
                    `);
                }

                return;
            }

            let rows = "";

            response.forEach(function (Pinv) {

                    let status = (Pinv.t_status || "").toLowerCase();
                    let t_type = (Pinv.t_type || "").toLowerCase();
                
                    let dateStyle = "text-warning";
                
                    let total = Number(Pinv.total_result || 0).toLocaleString('en-UG');
                
                    rows += `
                    <tr data-toggle="modal" class="inv-row" data-id="${Pinv.t_doc_no}"
                        data-loc_id="${Pinv.co_id}"
                        data-ord="${Pinv.t_doc_no}"
                        data-type="${Pinv.t_type}" data-target="#ModalBasic">
                        
                        <td class="${dateStyle}">${Pinv.t_doc_no || ''}</td>
                        <td class="${dateStyle}">${Pinv.acc_name || ''}</td>
                        <td class="${dateStyle}">${Pinv.t_type || ''}</td>
                        <td class="${dateStyle}">${total}</td>
                     
                    </tr>
                    `;
                });
            $(".pending-invoice-transactions").show();
            $("#pendinginventory").append(rows);

            Pinv_offset += Pinv_limit;
            Pinv_loading = false;
        },

        error: function () {
            console.error("Failed to load inventory");
            Pinv_loading = false; // ✅ prevent freeze
            hideLoader4();
        }
    });
}

$(document).ready(function () {
    
    showLoader4();

    loadPendinv();

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

        if (Pinv_loading || Pinv_finished) return;

        let container = $(this);

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

        if (
    container[0].scrollHeight > container.innerHeight() &&
    scrollTop + height >= scrollHeight - 50
) {
    loadPendinv();
}

    });

});



function showLoader4() {
    if ($("#loadingRow").length) return; // prevent duplicate

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

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

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

       function currentstocks() {
            $('#currstocks').html(`
                <tr>
                    <td colspan="4" class="text-center">
                       <div class="spinner-border spinner-border-sm text-primary"></div>
            Loading Transactions...
                    </td>
                </tr>
            `); // Show centered loading spinner inside the table
        
            $.ajax({
                url: 'query/fetch_this_mnth_inv_details.php', // Fetch data from this PHP script
                type: 'GET',
                data: { storeid: storeid },
                dataType: 'html', // Ensure this matches what your PHP script returns
                success: function(response) {
                    $('#currstocks').html(response); // Populate the table dynamically
                },
                error: function() {
                    $('#currstocks').html(`
                        <tr>
                            <td colspan="4" class="text-center text-danger">Error loading data.</td>
                        </tr>
                    `);
                }
            });
        }

</script>