<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.31/jspdf.plugin.autotable.min.js"></script>
<script>
    function hideUI() {
        $("#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, #acc_srch").hide();

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

        $(document).on("click", ".csh_mvt_acc_select", function() {
            $("#PanelRight_1").modal("hide");
            fetchcash_accounts();
            
        });
        
        function fetchcash_accounts() {
            $('#Accountselect').html(`
                <tr>
                    <td colspan="6" class="text-center p-3">
            <div class="spinner-border spinner-border-sm text-primary"></div>
            Loading Accounts...
        </td>
                </tr>
            `); // Show centered loading spinner inside the table
            var store_id = $('#storeid').val(); // Set initial value
            let comp_id = $('#sel_co').val();
        
            $.ajax({
                url: 'query/fetch_csh_mvt_accounts_select.php', // Fetch data from this PHP script
                type: 'GET',
                data: { comp_id: comp_id },
                dataType: 'html', // Ensure this matches what your PHP script returns
                success: function(response) {
                    $('#Accountselect').html(response); // Populate the table dynamically
                },
                error: function() {
                    $('#Accountselect').html(`
                        <tr>
                            <td colspan="4" class="text-center text-danger">Error loading data.</td>
                        </tr>
                    `);
                }
            });
        }
        
        $(document).on("click", ".fetch-acc_Statement_run", function() {
            var loc_id = $(this).data("loc_id");
            var acc_id = $(this).data("aid");
            var accname = $(this).data("accname");
        
            form_name2 = "Cash Movement Report";
            $("#report1").val(form_name2);
        
            $('#loc_id').val(loc_id);
            $('#acc_def1').val(acc_id);
             $("#accnm1").val(accname);
             
             csh_mvt_srch();
            $("#AccountSelectFormModal").modal("hide");
    
        });

            $(document).on("click", ".reconcile-record", function() {
            var loc_id = $(this).data("loc_id");
            var acc_id = $(this).data("acc_id");
            //var t_type = $(this).data("type");
            
            var form_name1 = "Reconcile Transactions";
        
            // Set hidden fields if needed
            $('#loc_id').val(loc_id);
            $('#form_name1').val(form_name1);
        
            // Pass all parameters correctly
           // fetchunclearedbl(loc_id, usr_id, t_type);
           hideUI();
           fetch_reconcile_records(loc_id, acc_id);
            
        });
        
        function fetch_reconcile_records(loc_id, acc_id) {
            $('#currentsales').html(`
                <tr>
                    <td colspan="4" class="text-center">
                        <div class="spinner-border spinner-border-sm text-primary" role="status"></div> Loading Transactions...
                    </td>
                </tr>
            `); // Show centered loading spinner inside the table
          
        
            $.ajax({
                url: 'query/fetch_reconcile_tns.php', // Fetch data from this PHP script
                type: 'GET',
                data: {loc_id: loc_id, acc_id: acc_id },
                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>
                    `);
                }
            });
        }
        
            $(document).on("click", ".fetch-record", function() {
            var loc_id = $(this).data("loc_id");
            var usr = $(this).data("usr");
            var t_type = $(this).data("type");
            
            var form_title_1 = "Daily Report";
        
            // Set hidden fields if needed
            $('#loc_id').val(loc_id);
            $('#form_title_1').val(form_title_1);
        
            // Pass all parameters correctly
           // fetchunclearedbl(loc_id, usr_id, t_type);
           fetchrecords(loc_id, usr, t_type);
            
        });
        
        function fetchrecords(loc_id, usr, t_type) {
            $('#Modalreport_1').html(`
                <tr>
                    <td colspan="4" class="text-center">
                        <div class="spinner-border spinner-border-sm text-primary" role="status"></div> Loading Transactions...
                    </td>
                </tr>
            `); // Show centered loading spinner inside the table
        
            $.ajax({
                url: 'query/fetch_pers_daily_rep.php', // Fetch data from this PHP script
                type: 'GET',
                data: { usr: usr, loc_id: loc_id, t_type: t_type },
                dataType: 'html', // Ensure this matches what your PHP script returns
                success: function(response) {
                    $('#Modalreport_1').html(response); // Populate the table dynamically
                },
                error: function() {
                    $('#Modalreport_1').html(`
                        <tr>
                            <td colspan="4" class="text-center text-danger">Error loading data.</td>
                        </tr>
                    `);
                }
            });
        }
        

            $(document).on("click", ".fetch-unclearedbl", function() {
            var loc_id = $(this).data("loc_id");
            var usr_id = $(this).data("usr");
            var t_type = $(this).data("type");
            
            var form_title_1 = "Sales Team Balances";
        
            // Set hidden fields if needed
            $('#loc_id').val(loc_id);
            $('#form_title_1').val(form_title_1);
        
            // Pass all parameters correctly
            fetchunclearedbl(loc_id, usr_id, t_type);
            
        });
        
            	function fetchunclearedbl() {
            $('#Modalreport_1').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
            var store_id = $('#storeid').val(); // Set initial value
            let comp_id = $('#sel_co').val();
        
            $.ajax({
                url: 'query/fetch_cr_uncleared_bl.php', // Fetch data from this PHP script
                type: 'GET',
                data: { comp_id: comp_id },
                dataType: 'html', // Ensure this matches what your PHP script returns
                success: function(response) {
                    $('#Modalreport_1').html(response); // Populate the table dynamically
                },
                error: function() {
                    $('#Modalreport_1').html(`
                        <tr>
                            <td colspan="4" class="text-center text-danger">Error loading data.</td>
                        </tr>
                    `);
                }
            });
        }

         $(document).on("click", ".fetch-cr_unclbl_yearly", function() {
            var loc_id = $(this).data("loc_id");
            var usr_id = $(this).data("usr");
            
            var form_title_2 = $(this).data("accname");
        
            // Set hidden fields if needed
            $('#loc_id').val(loc_id);
            $('#usr_id').val(usr_id);

            $('#form_title_2').val(form_title_2);
        
            // Pass all parameters correctly
            fetchcr_unclbl_yearly(loc_id, usr_id);
          
            
        });
        
          	function fetchcr_unclbl_yearly(loc_id, usr_id) {
            $('#Modalreport_2').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
            var store_id = $('#storeid').val(); // Set initial value
    
        
            $.ajax({
                url: 'query/fetch_cr_daily_rep_yearly.php', // Fetch data from this PHP script
                type: 'GET',
                data: { loc_id: loc_id,  usr_id: usr_id},
                dataType: 'html', // Ensure this matches what your PHP script returns
                success: function(response) {
                    $('#Modalreport_2').html(response); // Populate the table dynamically
                },
                error: function() {
                    $('#Modalreport_2').html(`
                        <tr>
                            <td colspan="4" class="text-center text-danger">Error loading data.</td>
                        </tr>
                    `);
                }
            });
        }
        
        
     $(document).on("click", ".fetch-cr_unclbl_monthly", function() {
            var loc_id = $(this).data("loc_id");
            var usr_id = $(this).data("usr");
            var t_type = $(this).data("type");
            
            var form_title_3 = $(this).data("accname");
        
            // Set hidden fields if needed
            $('#loc_id').val(loc_id);
            $('#usr_id').val(usr_id);
            $('#t_type').val(t_type);
            
            $('#form_title_3').val(form_title_3);
        
            // Pass all parameters correctly
            fetchcr_unclbl_monthly(loc_id, usr_id, t_type);
            
        });
        
          	function fetchcr_unclbl_monthly(loc_id, usr_id, t_type) {
            $('#Modalreport_3').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
            var store_id = $('#storeid').val(); // Set initial value
        
            $.ajax({
                url: 'query/fetch_cr_monthly_rep.php', // Fetch data from this PHP script
                type: 'GET',
                data: { loc_id: loc_id,  usr_id: usr_id, t_type: t_type,},
                dataType: 'html', // Ensure this matches what your PHP script returns
                success: function(response) {
                    $('#Modalreport_3').html(response); // Populate the table dynamically
                },
                error: function() {
                    $('#Modalreport_3').html(`
                        <tr>
                            <td colspan="4" class="text-center text-danger">Error loading data.</td>
                        </tr>
                    `);
                }
            });
        }

    $(document).on("click", ".fetch-details2", 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);
    
    if (t_type === 'DEL' || t_type === 'GR') {
        inventory_trans_details_head(loc_id, ord_no, t_type);
   
    } 
    
    else if (t_type === 'REC' || t_type === 'EXP') {
        cash_trans_details_head(loc_id, ord_no, t_type);
  
    } else {
        console.error("Invalid t_type:", t_type);
    }
});


  function inventory_trans_details_head(loc_id, ord_no, t_type) {
    let dailyrep = $('#header'); // Cache the selector for better performance
    let dailyrepx = $('#body'); // Cache the selector for better performance
    let dailyrepy = $('#entry'); // 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);
            inventory_details_body(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 cash_trans_details_head(loc_id, ord_no, t_type) {
    let dailyrep = $('#header'); // Cache the selector for better performance
    let dailyrepx = $('#body'); // Cache the selector for better performance
    let dailyrepy = $('#entry'); // 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);
            cash_details_body(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 inventory_details_body(loc_id, ord_no, t_type, usr_id) {
    let dailyrep1 = $('#body'); // 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);
            inventory_details_entry(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 cash_details_body(loc_id, ord_no, t_type, usr_id) {
    let dailyrep1 = $('#body'); // 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);
            cash_details_entry(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 inventory_details_entry(loc_id, ord_no, t_type, usr_id) {
    let dailyrep2 = $('#entry'); // 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-warning" role="status"></div>
            </td>
        </tr>
    `);

    $.ajax({
        url: 'query/fetch_order_details_entry.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>
            `);
        }
    });
}
    
function cash_details_entry(loc_id, ord_no, t_type, usr_id) {
    let dailyrep2 = $('#entry'); // 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-warning" role="status"></div>
            </td>
        </tr>
    `);

    $.ajax({
        url: 'query/fetch_cash_details_entry.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", ".stt-run", function() {
            var loc_id = $(this).data("loc_id");
            var accountno = $(this).data("accountno");
            var stt_type = $(this).data("stt_type");
            
            var statement_run_title = $(this).data("accname");
        
            // Set hidden fields if needed
            $('#loc_id').val(loc_id);
            $('#accountno').val(accountno);
            $('#stt_type').val(stt_type);

            $('#statement_run_title').val(statement_run_title);
        
            // Pass all parameters correctly
            fetch_acc_stt(true);
          
            
    });
        
  function fetch_acc_stt(reset = false) {
    
    let comp_id = $('#sel_co').val();
    let loc_id = $('#loc_id').val();
    let accountno = $('#accountno').val();
    let stt_type = $('#stt_type').val();

    // ✅ Reset mode (when store changes)
    if (reset) {
        stt_offset = 0;
        stt_finished = false;
        stt_loading = false;
        $("#statementrun").html("");
       
    }

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

    if (stt_loading || stt_finished) {
        return;
    }

    stt_loading = true;
    statementLoader();

    console.log("Loading...", { storeid, stt_offset });
    console.log("Account:", accountno);

    $.ajax({
        url: "query/fetch_account_statement_run.php",
        type: "GET",
        data: {
            stt_limit: stt_limit,
            stt_offset: stt_offset,
           // storeid: storeid,
            comp_id: comp_id,
            accountno: accountno,
            stt_type: stt_type
        },
        dataType: "json",

        success: function (response) {

          

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

                stt_finished = true;

                if (stt_offset === 0) {
                      // ❌ No data at all → hide whole section
                        $("#statementLoader").hide();
                        
                        
                    $("#statementrun").html(`
                        <tr>
                            <td colspan="6" class="text-center text-muted p-3">
                                No Transactions Found
                            </td>
                        </tr>
                    `);
                } else {
                   hidestatementLoader();
                    $("#statementrun").append(`
                        <tr>
                            <td colspan="6" class="text-center text-muted p-3">
                                No more Transactions
                            </td>
                        </tr>
                    `);
                }

                return;
            }

            let rows = "";

            response.forEach(function (stt) {

                    let type = (stt.t_type || "").toLowerCase();
                
                    let dateStyle = '';
                    let rowclass = '';
                    let particulars='';
                    let category='';
                    let thead='';
                
                if (stt_type==="stt_accs") {                    
                    if (stt.acc_type==="Cash") {
                      if (stt.t_type === "EXP" || stt.t_type === "BNK") {
                            rowclass = "stt-detail";
                            dateStyle = "text-rec";
                            particulars=(stt.accname_exp || '');
                        } else if (stt.t_type === "REC") {
                            rowclass = "stt-detail";
                            dateStyle = "text-rec";
                            particulars=(stt.acc_rec || '');
                        }
                    }
                    
                    if (stt.acc_type==="Bank") {
                      if (stt.t_type === "EXP" || stt.t_type === "BNK") {
                            rowclass = "stt-detail";
                            dateStyle = "text-rec";
                            particulars=(stt.acc_ent_by || '');
                        } else if (stt.t_type === "REC") {
                            rowclass = "stt-detail";
                            dateStyle = "text-rec";
                            particulars=(stt.acc_rec || '');
                        }
                    }
                } 
                
                if (stt_type==="stt_cr") {                    
                   
                            rowclass = "stt-detail";
                            dateStyle = "text-rec";
                            particulars=(stt.acc_ent_by || '');
                    
                    
                }  
                
                 if (stt_type==="stt_exp") {                    
                   
                            rowclass = "stt-detail";
                            dateStyle = "text-rec";
                            particulars=(stt.accname_exp || '');
                    
                    
                }
                    let credit = (stt.t_credit && Number(stt.t_credit) !== 0)
                    ? Number(stt.t_credit).toLocaleString('en-UG')
                    : '';
                
                    let debit = (stt.t_debit && Number(stt.t_debit) !== 0)
                    ? Number(stt.t_debit).toLocaleString('en-UG')
                    : '';
                    
                    let balance = Number(stt.running_balance || 0).toLocaleString('en-UG');
                
                  rows += `
                    <tr data-toggle="modal" class="stt-run" data-id="${stt.t_cr}"
                        data-loc_id="${stt.co_id}"
                        data-sttount="${stt.t_cr}"
                        data-sttname="${stt.t_cr}"
                        data-type="${stt.t_type}" data-target="#Modelrep">
                        
                        <td class="${dateStyle}">${stt.t_date || ''}</td>
                        <td class="${dateStyle}">${stt.t_doc_no || ''}</td>
                        <td class="${dateStyle}">${particulars}</td>
                        <td class="${dateStyle}">${type}</td>
                        <td class="${dateStyle}">${credit}</td>
                        <td class="${dateStyle}">${debit}</td>
                        <td class="${dateStyle}">${balance}</td>
                    
                    </tr>
                    `;
                });
                
            $("#statementLoader").hide();
              hidestatementLoader();
            $("#statementrun").append(rows);

            stt_offset += stt_limit;
            stt_loading = false;
        },

        error: function () {
            console.error("Failed to load transactions");
            stt_loading = false; // ✅ prevent freeze
            hidestatementLoader();
        }
    });
}

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

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

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

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



$(document).ready(function () {
    let transData = {
        "csh_mvt": { trans_type: "DEL", form_name2: "Cash Movement Report" }
    };

    $(document).on("click", "#csh_mvt", function () {
        
        event.preventDefault();  
        let id = $(this).attr("id");

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

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

            $("#report1").val(form_name2);

            if (id === "csh_mvt") {
                    // 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").hide();
                    $("#storex").prop("disabled", false); // Disable Store
                
                    $("#loc_group").hide();
                    $("#loc").prop("disabled", false); // Enable Storefrom field
                    
                    $("#driver_group").hide();
                    $("#driver").prop("disabled", false); // Enable Storefrom field
                    $("#total-field").hide();
                    $("#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").hide();
                    $("#add-cust-button").hide();
                    
                    // Example: inventory mode
                  
                
                   // $('#field2').val(''); // Clear the input
                   
                  // csh_mvt_srch();
                    // 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) {
                                        $("#acc_def1").val(response.store_location);
                                      $("#accnm1").val(response.accnm);
                                    } else {
                                        $("#acc_def1").val("No account available");
                                    }
                                },
                                error: function (xhr, status, error) {
                                    console.error("AJAX Error: " + status + " - " + error);
                                }
                            });
                        }
                
        
            }
            
                $("#PanelRight_1").modal("hide");

           
        }
    });
});

function csh_mvt_srch() {

    let date1 = $("#datestt1").val();
    let date2 = $("#datestt2").val();
    let acc_def1 = $("#acc_def1").val();

    // Loader
    $('#search_statementrun').html(`
        <tr>
            <td colspan="10" class="text-center">
            <div class="spinner-border spinner-border-sm text-primary"></div>
            Loading Transactions...
            </td>
        </tr>
    `);

    // (optional) clear header while loading
    $('#dynamic_header').html('');

    $.ajax({
        url: 'query/get_csh_mvt_report.php',
        type: 'GET',
        data: { date1, date2, acc_def1 },
        dataType: 'json',   // ✅ IMPORTANT CHANGE

        success: function(res) {

            // ✅ inject header into THEAD
            $('#dynamic_header').html(res.header);

            // ✅ inject rows into TBODY
            $('#search_statementrun').html(res.rows);
        },

        error: function() {
            $('#search_statementrun').html(`
                <tr>
                    <td colspan="10" class="text-center text-danger">
                        Error loading data.
                    </td>
                </tr>
            `);
        }
    });
}

     // Live search as the user types
    $("#datestt1, #datestt2").on("input", function () {
        csh_mvt_srch();
    });
    



$("#exportExcel").click(function () {

    let comp_id = $('#sel_co').val();
    let accountno = $('#accountno').val();

    $.get("query/export_statement.php", { comp_id, accountno }, function (data) {

        let rows = JSON.parse(data);

        let csv = "Date,Particulars,Type,Credit,Debit,Balance\n";

        rows.forEach(r => {

    let particulars = '';

    if (r.t_type === "EXP" || r.t_type === "BNK") {
        particulars = r.accname_exp || '';
    } else if (r.t_type === "REC") {
        particulars = r.acc_rec || '';
    }

    csv += `${r.t_date},${particulars},${r.t_type},${r.t_credit || ''},${r.t_debit || ''},${r.running_balance}\n`;
});

        let blob = new Blob([csv], { type: "text/csv" });
        let link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = "statement.csv";
        link.click();
    });
});




$("#exportPDF").click(function () {

    let comp_id = $('#sel_co').val();
    let accountno = $('#accountno').val();

    if (!accountno) {
        alert("Select account first");
        return;
    }

    // 🔹 Dynamic values
    let accountName = $('#statement_run_title').val() || 'Account';
    let companyName = $('#sel_co option:selected').text() || 'Company';
    let dateFrom = $('#datestt1').val() || '';
    let dateTo = $('#datestt2').val() || '';

    // 🔹 Format date nicely
    function formatDate(d) {
        if (!d) return '';
        let dt = new Date(d);
        return dt.toLocaleDateString('en-GB', {
            day: '2-digit',
            month: 'short',
            year: 'numeric'
        });
    }

    let periodText = (dateFrom && dateTo)
        ? `Period: ${formatDate(dateFrom)} → ${formatDate(dateTo)}`
        : '';

    $.ajax({
        url: "query/export_statement.php",
        type: "GET",
        data: { comp_id, accountno },
        dataType: "json",

        success: function (rows) {

            if (!rows || rows.length === 0) {
                alert("No data to export");
                return;
            }

            const { jsPDF } = window.jspdf;
            let doc = new jsPDF();

            let pageWidth = doc.internal.pageSize.getWidth();

            // ================= HEADER =================

            // 1. COMPANY NAME (CENTER)
            doc.setFontSize(14);
            doc.setFont(undefined, 'bold');
            doc.text(companyName, pageWidth / 2, 10, { align: "center" });

            // 2. TITLE + ACCOUNT (SAME ROW)
            doc.setFontSize(12);
            doc.setFont(undefined, 'normal');

            doc.text("Account Statement", 14, 18);
            doc.text(accountName.toUpperCase(), pageWidth - 14, 18, { align: "right" });

            // 3. PERIOD
            if (periodText) {
                doc.setFontSize(10);
                doc.text(periodText, pageWidth / 2, 24, { align: "center" });
            }

            // 4. LINE SEPARATOR
            doc.setLineWidth(0.3);
            doc.line(14, 26, pageWidth - 14, 26);

            // ================= HELPERS =================

            function formatAmount(value) {
                return (value && Number(value) !== 0)
                    ? Number(value).toLocaleString('en-UG', {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2
                    })
                    : '';
            }

            function getParticulars(r) {
                if (r.t_type === "EXP" || r.t_type === "BNK") {
                    return r.accname_exp || '';
                } else if (r.t_type === "REC") {
                    return r.acc_rec || '';
                }
                return '';
            }

            // ================= TABLE =================

            doc.autoTable({
                startY: 30,

                head: [['Date', 'Particulars', 'Type', 'Credit', 'Debit', 'Balance']],

                body: rows.map(r => [
                    r.t_date || '',
                    getParticulars(r),
                    (r.t_type || '').toLowerCase(),
                    formatAmount(r.t_credit),
                    formatAmount(r.t_debit),
                    Number(r.running_balance || 0).toLocaleString('en-UG', {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2
                    })
                ]),

                styles: {
                    fontSize: 10,
                    cellPadding: 2
                },

                headStyles: {
                    fillColor: [40, 40, 40]
                },

                columnStyles: {
                    3: { halign: 'right' }, // Credit
                    4: { halign: 'right' }, // Debit
                    5: { halign: 'right' }  // Balance
                },

                didDrawPage: function (data) {
                    let pageHeight = doc.internal.pageSize.height || doc.internal.pageSize.getHeight();

                    doc.setFontSize(10);
                    doc.text(
                        "Page " + doc.internal.getNumberOfPages(),
                        data.settings.margin.left,
                        pageHeight - 5
                    );
                }
            });

            // ================= SAVE =================
            doc.save("Account_Statement.pdf");
        },

        error: function () {
            alert("Failed to export PDF");
        }
    });
});



</script>