<script>

$(document).on("click", ".inv-row-1", 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
    fetchBalances01(loc_id, ord_no, t_type);
    
    
});

function fetchBalances01(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);
            fetchBalances11(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 fetchBalances11(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);
            fetchBalances22(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 fetchBalances22(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_1.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("click", ".inv-row-2", 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
    fetchCash(loc_id, ord_no, t_type);
    
    
});

function fetchCash(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_cash_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);
            fetchCash1(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 fetchCash1(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_cash_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);
            fetchBalances22(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>
            `);
        }
    });
}

$(document).ready(function () {

    let transData1 = {
        "deliveryLinkrep": { trans_type: "", form_name1: "Search Transactions" },
        "salesLinkrep": { trans_type: "Sales", form_name1: "Sales Report" },
        "stktfrLinkrep": { trans_type: "Stfr", form_name1: "Stock Transfer Report" },
        "prchLinkrep": { trans_type: "Stfr", form_name1: "Purchase Report" },
        "docnoLink": { trans_type: "Stfr", form_name1: "Search Doc No" },
        "recLinkrep": { trans_type: "REC", form_name1: "Cash Report" },
        "expLinkrep": { trans_type: "EXP", form_name1: "Expense Report" },
        "bnkLinkrep": { trans_type: "BNK", form_name1: "Bankings Report" }
    };

    function resetUI() {
        $("#field3_group, #field31_group, #search-input, #docnox, #date, #date2, #date3, #date4, #date5, #date6, #date7, #date8, #loc_group, #driver_group, #trans_type, #dater1, #dater2, #dater3, #dater4, #dateb, #dateb2").hide();

        $("#field3, #field31, #search-input, #docnox,  #date, #date2, #date3, #date4, #date5, #date6, #date7, #date8, #loc, #driver, #trans_type, #dater1, #dater2, #dater3, #dater4, #dateb, #dateb2")
            .prop("disabled", true);
    }

    $(document).on("click", "#deliveryLinkrep, #salesLinkrep, #stktfrLinkrep, #prchLinkrep, #docnoLink, #recLinkrep, #expLinkrep, #bnkLinkrep", function () {
        
        event.preventDefault();
        let id = this.id;

        if (!transData1[id]) return;

        let { trans_type, form_name1 } = transData1[id];

        $("#trans_type").val(trans_type);
        $("#form_name1").val(form_name1);

        // ✅ Reset everything first
        resetUI();

        // ✅ Apply only what is needed
        switch (id) {

            case "salesLinkrep":
                $("#field3_group, #search-input, #date3, #date4").show();
                $("#field3, #search-input, #date3, #date4").prop("disabled", false);
                datesearch1();
                break;

            case "stktfrLinkrep":
                $("#field3_group, #date5, #date6").show();
                $("#field3, #date5, #date6").prop("disabled", false);
                datesearch2();
                break;

            case "prchLinkrep":
                $("#field3_group, #date7, #date8").show();
                $("#field3, #date7, #date8").prop("disabled", false);
                datesearch3();
                break;

            case "docnoLink":
                $("#field3_group, #docnox").show();
                $("#field3, #docnox").prop("disabled", false);
                docsearch();
                break;

            case "deliveryLinkrep":
                $("#field3_group, #date, #date2 , #trans_type").show();
                $("#field3, #date, #date2 , #trans_type").prop("disabled", false);
                datesearch();
                break;
            
            case "recLinkrep":
                $("#field3_group, #dater1, #dater2 , #trans_type").show();
                $("#field3, #dater1, #dater2 , #trans_type").prop("disabled", false);
                datesearch_rec();
                break;
                
            case "bnkLinkrep":
                $("#field3_group, #dateb, #dateb2 , #trans_type").show();
                $("#field3, #dateb, #dateb2 , #trans_type").prop("disabled", false);
                datesearch_bnk();
                break;
                
            case "expLinkrep":
                $("#field3_group, #dater3, #dater4 , #trans_type").show();
                $("#field3, #dater3, #dater4 , #trans_type").prop("disabled", false);
                datesearch_exp();
                break;
        }

        $("#PanelRight").modal("hide");
        $("#PanelRight_1").modal("hide");

        if ($("#delivery").length) {
            $("#delivery").modal("show");
        }
    });
});

    function datesearch1() {
        var searchText = $("#search-input").val().toLowerCase();
    	var date1 = $("#date3").val().toLowerCase();
        var date2 = $("#date4").val().toLowerCase();
  
            $('#currentsales').html(`
                <tr>
                    <td colspan="4" class="text-center">
                        <div class="spinner-border  text-warning" role="status"></div>
                    </td>
                </tr>
            `); // Show centered loading spinner inside the table
        
            $.ajax({
                url: 'query/get_sales_rep_inventory.php', // Fetch data from this PHP script
                type: 'GET',
                data: {query: searchText, date1: date1, date2: date2, storeid:storeid },
                dataType: 'html', // Ensure this matches what your PHP script returns
                success: function(response) {
                    $('#currentsales').html(response); // Populate the table dynamically
                },
                error: function() {
                    $('#currentsales').html(`
                        <tr>
                            <td colspan="4" class="text-center text-danger">Error loading data.</td>
                        </tr>
                    `);
                }
            });
        }
        
           // Debounced live search
let debounceTimer;
$(document).ready(function () {
    $("#date3, #date4, #search-input").on("input", function () {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(function () {
            datesearch1();
        }, 500); // Adjust debounce delay as needed
    });
});

    function datesearch3() {

        let date1 = $("#date7").val();
    let date2 = $("#date8").val();

    
    
            $('#currentsales').html(`
                <tr>
                    <td colspan="4" class="text-center">
                        <div class="spinner-border  text-warning" role="status"></div>
                    </td>
                </tr>
            `); // Show centered loading spinner inside the table
        console.log({
    
            date1,
            date2
        });
            $.ajax({
                url: 'query/get_stk_prch_rep.php', // Fetch data from this PHP script
                type: 'GET',
                data: {date1: date1, date2: date2, storeid: storeid },
                dataType: 'html', // Ensure this matches what your PHP script returns
                success: function(response) {
                    $('#currentsales').html(response); // Populate the table dynamically
                },
                error: function() {
                    $('#currentsales').html(`
                        <tr>
                            <td colspan="4" class="text-center text-danger">Error loading data.</td>
                        </tr>
                    `);
                }
            });
        }


     // Live search as the user types
    $("#date7, #date8").on("input", function () {
        datesearch3();
    });
    
        function datesearch2() {
    	var date1 = $("#date5").val().toLowerCase();
        var date2 = $("#date6").val().toLowerCase();
     
            $('#currentsales').html(`
                <tr>
                    <td colspan="4" class="text-center">
                        <div class="spinner-border  text-warning" role="status"></div>
                    </td>
                </tr>
            `); // Show centered loading spinner inside the table
        
            $.ajax({
                url: 'query/get_stfr_report.php', // Fetch data from this PHP script
                type: 'GET',
                data: {date1: date1, date2: date2, storeid: storeid },
                dataType: 'html', // Ensure this matches what your PHP script returns
                success: function(response) {
                    $('#currentsales').html(response); // Populate the table dynamically
                },
                error: function() {
                    $('#currentsales').html(`
                        <tr>
                            <td colspan="4" class="text-center text-danger">Error loading data.</td>
                        </tr>
                    `);
                }
            });
        }


     // Live search as the user types
    $("#date5, #date6").on("input", function () {
        datesearch2();
    });
    
          function docsearch() {
    	var docno = $("#docnox").val().toLowerCase();
       
            $('#currentsales').html(`
                <tr>
                    <td colspan="4" class="text-center">
                        <div class="spinner-border  text-warning" role="status"></div>
                    </td>
                </tr>
            `); // Show centered loading spinner inside the table
        
            $.ajax({
                url: 'query/get_docno_search_rep.php', // Fetch data from this PHP script
                type: 'GET',
                data: {docno: docno, storeid: storeid },
                dataType: 'html', // Ensure this matches what your PHP script returns
                success: function(response) {
                    $('#currentsales').html(response); // Populate the table dynamically
                },
                error: function() {
                    $('#currentsales').html(`
                        <tr>
                            <td colspan="4" class="text-center text-danger">Error loading data.</td>
                        </tr>
                    `);
                }
            });
        }


              // Debounced live search
            let debounceTimer1;
            $(document).ready(function () {
                $("#docnox").on("input", function () {
                    clearTimeout(debounceTimer);
                    debounceTimer = setTimeout(function () {
                        docsearch();
                    }, 300);
                });
            });
            
            
  	function datesearch() {
    	var date1 = $("#date").val().toLowerCase();
        var date2 = $("#date2").val().toLowerCase();
        var trans_type = $("#trans_type").val().toLowerCase();
        ///var user3_id = $("#user3_id").val().toLowerCase();
            $('#currentsales').html(`
                <tr>
                    <td colspan="4" class="text-center">
                        <div class="spinner-border  text-warning" role="status"></div>
                    </td>
                </tr>
            `); // Show centered loading spinner inside the table
        
            $.ajax({
                url: 'query/get_delivery_report.php', // Fetch data from this PHP script
                type: 'GET',
                data: { date1: date1, date2: date2,  storeid:storeid, trans_type: trans_type },
                dataType: 'html', // Ensure this matches what your PHP script returns
                success: function(response) {
                    $('#currentsales').html(response); // Populate the table dynamically
                },
                error: function() {
                    $('#currentsales').html(`
                        <tr>
                            <td colspan="4" class="text-center text-danger">Error loading data.</td>
                        </tr>
                    `);
                }
            });
        }


     // Live search as the user types
    $("#date, #date2").on("input", function () {
        datesearch();
    });
    $(document).ready(function () {
                $("#trans_type").on("input", function () {
                    clearTimeout(debounceTimer);
                    debounceTimer = setTimeout(function () {
                        datesearch();
                    }, 300);
                });
            });
            
        function datesearch_bnk() {
    	var date1 = $("#dateb").val().toLowerCase();
        var date2 = $("#dateb2").val().toLowerCase();
        var trans_type = $("#trans_type").val().toLowerCase();
        ///var user3_id = $("#user3_id").val().toLowerCase();
            $('#currentsales').html(`
                <tr>
                    <td colspan="4" class="text-center">
                        <div class="spinner-border  text-warning" role="status"></div>
                    </td>
                </tr>
            `); // Show centered loading spinner inside the table
        
            $.ajax({
                url: 'query/get_bank_report.php', // Fetch data from this PHP script
                type: 'GET',
                data: { date1: date1, date2: date2,  storeid:storeid, trans_type: trans_type },
                dataType: 'html', // Ensure this matches what your PHP script returns
                success: function(response) {
                    $('#currentsales').html(response); // Populate the table dynamically
                },
                error: function() {
                    $('#currentsales').html(`
                        <tr>
                            <td colspan="4" class="text-center text-danger">Error loading data.</td>
                        </tr>
                    `);
                }
            });
        }


     // Live search as the user types
    $("#dateb, #dateb2").on("input", function () {
        datesearch_bnk();
    });
            
    function datesearch_rec() {
    	var date1 = $("#dater1").val().toLowerCase();
        var date2 = $("#dater2").val().toLowerCase();
        var trans_type = $("#trans_type").val().toLowerCase();
        ///var user3_id = $("#user3_id").val().toLowerCase();
            $('#currentsales').html(`
                <tr>
                    <td colspan="4" class="text-center">
                        <div class="spinner-border  text-warning" role="status"></div>
                    </td>
                </tr>
            `); // Show centered loading spinner inside the table
        
            $.ajax({
                url: 'query/get_cash_report.php', // Fetch data from this PHP script
                type: 'GET',
                data: { date1: date1, date2: date2,  storeid:storeid, trans_type: trans_type },
                dataType: 'html', // Ensure this matches what your PHP script returns
                success: function(response) {
                    $('#currentsales').html(response); // Populate the table dynamically
                },
                error: function() {
                    $('#currentsales').html(`
                        <tr>
                            <td colspan="4" class="text-center text-danger">Error loading data.</td>
                        </tr>
                    `);
                }
            });
        }


     // Live search as the user types
    $("#dater1, #dater2").on("input", function () {
        datesearch_rec();
    });
    

    function datesearch_exp() {
    	var date3 = $("#dater3").val().toLowerCase();
        var date4 = $("#dater4").val().toLowerCase();
        var trans_type = $("#trans_type").val().toLowerCase();
        ///var user3_id = $("#user3_id").val().toLowerCase();
            $('#currentsales').html(`
                <tr>
                    <td colspan="4" class="text-center">
                        <div class="spinner-border  text-warning" role="status"></div>
                    </td>
                </tr>
            `); // Show centered loading spinner inside the table
        
            $.ajax({
                url: 'query/get_expense_report.php', // Fetch data from this PHP script
                type: 'GET',
                data: { date3: date3, date4: date4,  storeid:storeid, trans_type: trans_type },
                dataType: 'html', // Ensure this matches what your PHP script returns
                success: function(response) {
                    $('#currentsales').html(response); // Populate the table dynamically
                },
                error: function() {
                    $('#currentsales').html(`
                        <tr>
                            <td colspan="4" class="text-center text-danger">Error loading data.</td>
                        </tr>
                    `);
                }
            });
        }


     // Live search as the user types
    $("#dater3, #dater4").on("input", function () {
        datesearch_exp();
    });

</script>