<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
$(document).on("click", ".opencashadjModal", function () {
    event.preventDefault();  
    // Close action sheet first
    $("#cashadjModal").modal("show");
    

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

});

$(document).on("click", ".openclosecash", function () {
    event.preventDefault();  
    // Close action sheet first
    $("#closecashModal").modal("show");
    

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

});

// Add Bank & Transfers work flow

$(document).on("click", ".bank_transfer_selector", function () {
    event.preventDefault();
    // Close action sheet first
    $("#PanelRight_1").modal("hide");

    // Wait until it's closed, then open product modal
    setTimeout(function () {
        
    $("#Bnk_TFR_SelectFormModal").modal("show");
    }, 300);

});

$(document).on("click", ".cancelbnkTFRselect", function () {
    
    // Close action sheet first
    $("#Bnk_TFR_SelectFormModal").modal("hide");

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

});
// END  Bank & Transfers work flow

// Add Invoice work flow

$(document).on("click", ".InvoiceSelector", function () {
    event.preventDefault();
    // Close action sheet first
    $("#PanelRight_1").modal("hide");

    // Wait until it's closed, then open product modal
    setTimeout(function () {
        
    $("#InvoiceSelectFormModal").modal("show");
    }, 300);

});

$(document).on("click", ".cancelinvoiceselect", function () {
    
    // Close action sheet first
    $("#InvoiceSelectFormModal").modal("hide");

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

});
// END Invoice work flow

$(document).on("click", ".cancel_csh_mvt_select", function () {
    
    // Close action sheet first
    $("#AccountSelectFormModal").modal("hide");

});

document.getElementById("cshadjForm")
    .addEventListener("submit", function (e) {

        e.preventDefault();

        const formData = new FormData(this);

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

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

                //alert("Warehouses saved successfully");
                showToast("Cash Adjustment saved successfully", "success");
                 //$("#PermissioncatModal").modal("hide");
                 // refreshperm(); // reload table

                this.reset();
               // document.getElementById("permissioncatRows").innerHTML = "";
               // document.getElementById("permcataddRow").click();

            } else {

               // alert("Error: " + (data.message || "Unknown error"));
               showToast(data.message || "Unknown error", "error");

            }
        })
        .catch(err => {
            console.error(err);
            alert("Server error — check console");
        });
    });
    
    document.getElementById("closecashForm")
    .addEventListener("submit", function (e) {

        e.preventDefault();

        const formData = new FormData(this);

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

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

                //alert("Warehouses saved successfully");
                showToast("Cash Close saved successfully", "success");
                 //$("#PermissioncatModal").modal("hide");
                 // refreshperm(); // reload table

                this.reset();
               // document.getElementById("permissioncatRows").innerHTML = "";
               // document.getElementById("permcataddRow").click();
               datesearch_close_cash();

            } else {

               // alert("Error: " + (data.message || "Unknown error"));
               showToast(data.message || "Unknown error", "error");

            }
        })
        .catch(err => {
            console.error(err);
            alert("Server error — check console");
        });
    });
    
//Fetch Recent Sales Reports Overview Records--------------------------------------------------

function load_salesrep_OverviewToday(reset = false) {
    
    let comp_id = $('#sel_co').val();

    // ✅ Reset mode (when store changes)
    if (reset) {
        ovSR_offset = 0;
        ovSR_finished = false;
        ovSR_loading = false;
        $("#overview_salesrep_today").html("");
       
    }

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

    if (ovSR_loading || ovSR_finished) {
        return;
    }

    ovSR_loading = true;
    showLoader9();

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

    $.ajax({
        url: "fetch_scripts/fetch_overview_daily_sales_reports.php",
        type: "GET",
        data: {
            ovSR_limit: ovSR_limit,
            ovSR_offset: ovSR_offset,
           // storeid: storeid,
            comp_id: comp_id
        },
        dataType: "json",

        success: function (response) {

            hideLoader9();

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

                ovSR_finished = true;

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

                return;
            }

            let rows = "";

            response.forEach(function (ovSR) {

                    let variance = (ovSR.result_short || 0);
                   // let t_type = (ovSR.t_type || "").toLowerCase();
                
                    let dateStyle = 'text-rec';
                    let totStyle = 'text-rec';
                
                    let total = Number(ovSR.result_short || 0).toLocaleString('en-UG');
                    
                    let sales = Number(ovSR.daily_sales || 0).toLocaleString('en-UG');
                    
                    let receipts = Number(ovSR.total_debit_CSH || 0).toLocaleString('en-UG');
                    
                if (variance < 0) {
                   
                    totStyle = "text-danger";
                
                }
                
                    rows += `
                    <tr data-toggle="modal" class="fetch-record" data-id="${ovSR.t_tt_doc}"
                        data-loc_id="${ovSR.co_id}"
                        data-usr="${ovSR.t_ct_det}"
                        data-type="${ovSR.t_date}" data-target="#ModalBasic_1">
                        
                        <td class="${dateStyle}">${ovSR.M_date || ''}</td>
                        <td class="${dateStyle}">${ovSR.acc_name || ''}</td>
                        <td class="${dateStyle}">${sales}</td>
                        <td class="${dateStyle}">${receipts}</td>
                        <td class="${totStyle}">${total}</td>
                     
                    </tr>
                    `;
                });
                $("#overview_sales_rep_Loader").hide();
            $(".overview-sales_rep-transactions").show();
            $("#overview_salesrep_today").append(rows);

            ovSR_offset += ovSR_limit;
            ovSR_loading = false;
        },

        error: function () {
            console.error("Failed to load inventory");
            ovSR_loading = false; // ✅ prevent freeze
            hideLoader9();
        }
    });
}    
    //End Fetch Recent Sales Reports-------------------------------------------
    
    //Fetch Pending Todays's Overview Records--------------------------------------------------

function loadOverviewPend(reset = false) {
    
    let comp_id = $('#sel_co').val();

    // ✅ Reset mode (when store changes)
    if (reset) {
        ov_offset = 0;
        ov_finished = false;
        ov_loading = false;
        $("#overviewpending").html("");
       
    }

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

    if (ov_loading || ov_finished) {
        return;
    }

    ov_loading = true;
    showLoader7();

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

    $.ajax({
        url: "fetch_scripts/fetch_overview_pending_transactions.php",
        type: "GET",
        data: {
            ov_limit: ov_limit,
            ov_offset: ov_offset,
           // storeid: storeid,
            comp_id: comp_id
        },
        dataType: "json",

        success: function (response) {

            hideLoader7();

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

                ov_finished = true;

                if (ov_offset === 0) {
                     $("#overviewLoaderpending").hide();
                      // ❌ No data at all → hide whole section
                        $(".pend-overview-transactions").hide();
                        $('.table-container').first().hide();
                        
                    $("#overviewpending").html(`
                        <tr>
                            <td colspan="4" class="text-center text-muted p-3">
                                No Transactions Found
                            </td>
                        </tr>
                    `);
                } else {
                    $('.table-container').first().show();
                    $(".pend-overview-transactions").show();
                    $("#overviewpending").append(`
                        <tr>
                            <td colspan="4" class="text-center text-muted p-3">
                                No more Transactions
                            </td>
                        </tr>
                    `);
                }

                return;
            }

            let rows = "";

            response.forEach(function (ov) {

                    let status = (ov.t_status || "").toLowerCase();
                    let t_type = (ov.t_type || "").toLowerCase();
                
                    let dateStyle = "text-warning";
                
                    let total = Number(ov.total_result || 0).toLocaleString('en-UG');
                
                    rows += `
                    <tr data-toggle="modal" class="fetch-details" data-id="${ov.t_doc_no}"
                        data-loc_id="${ov.co_id}"
                        data-ord="${ov.t_doc_no}"
                        data-type="${ov.t_type}" data-target="#ModalBasic">
                        
                        <td class="${dateStyle}">${ov.t_doc_no || ''}</td>
                        <td class="${dateStyle}">${ov.acc_name || ''}</td>
                        <td class="${dateStyle}">${ov.t_type || ''}</td>
                        <td class="${dateStyle}">${total}</td>
                     
                    </tr>
                    `;
                });
                $("#overviewLoaderpending").hide();
             $('.table-container').first().show();
            $(".pend-overview-transactions").show();
            $("#overviewpending").append(rows);

            ov_offset += ov_limit;
            ov_loading = false;
        },

        error: function () {
            console.error("Failed to load inventory");
            ov_loading = false; // ✅ prevent freeze
            hideLoader7();
        }
    });
}
    
    //Fetch Todays's Overview Records--------------------------------------------------

function loadOverviewToday(reset = false) {
    
    let comp_id = $('#sel_co').val();

    // ✅ Reset mode (when store changes)
    if (reset) {
        ovT_offset = 0;
        ovT_finished = false;
        ovT_loading = false;
        $("#overviewtoday").html("");
       
    }

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

    if (ovT_loading || ovT_finished) {
        return;
    }

    ovT_loading = true;
    showLoader8();

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

    $.ajax({
        url: "fetch_scripts/fetch_overview_todays_transactions.php",
        type: "GET",
        data: {
            ovT_limit: ovT_limit,
            ovT_offset: ovT_offset,
           // storeid: storeid,
            comp_id: comp_id
        },
        dataType: "json",

        success: function (response) {

            hideLoader8();

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

                ovT_finished = true;

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

                return;
            }

            let rows = "";

            response.forEach(function (ovT) {

                    let status = (ovT.t_status || "").toLowerCase();
                    let t_type = (ovT.t_type || "").toLowerCase();
                
                    let dateStyle = '';
                
                    let total = Number(ovT.total_result || 0).toLocaleString('en-UG');
                    
                    if (status === "confirmed" && t_type === "del") {
                    badge = '<span class="badge badge-success">Confirmed</span>';
                    dateStyle = "text-del";
                
                } else if (status === "confirmed" && (t_type === "gr" || t_type === "inv ret")) {
                    badge = '<span class="badge badge-success">Confirmed</span>';
                    dateStyle = "text-pink";
                
                } else  if (status === "confirmed" && t_type === "rec") {
                  
                    dateStyle = "text-rec";
                
                } else if (status === "confirmed" && t_type === "exp") {
                   
                    dateStyle = "text-danger";
                
                }else  if (status === "confirmed" && (t_type === "cs inv" || t_type === "stk inv")) {
                  
                    dateStyle = "text-primary";
                
                }else {
                    dateStyle = "text-warning";
                }
                
                    rows += `
                    <tr data-toggle="modal" class="fetch-details" data-id="${ovT.t_doc_no}"
                        data-loc_id="${ovT.co_id}"
                        data-ord="${ovT.t_doc_no}"
                        data-type="${ovT.t_type}" data-target="#ModalBasic">
                        
                        <td class="${dateStyle}">${ovT.t_doc_no || ''}</td>
                        <td class="${dateStyle}">${ovT.acc_name || ''}</td>
                        <td class="${dateStyle}">${ovT.t_type || ''}</td>
                        <td class="${dateStyle}">${total}</td>
                     
                    </tr>
                    `;
                });
                $("#overviewLoader").hide();
            $(".overview-transactions").show();
            $("#overviewtoday").append(rows);

            ovT_offset += ovT_limit;
            ovT_loading = false;
        },

        error: function () {
            console.error("Failed to load inventory");
            ovT_loading = false; // ✅ prevent freeze
            hideLoader8();
        }
    });
}    
    //Fetch Todays's Records--------------------------------------------------

function loadPendcsh(reset = false) {

    // ✅ Reset mode (when store changes)
    if (reset) {
        Pcsh_offset = 0;
        Pcsh_finished = false;
        Pcsh_loading = false;
        $("#pendingcash").html("");
       
    }

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

    if (Pcsh_loading || Pcsh_finished) {
        return;
    }

    Pcsh_loading = true;
    showLoader5();

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

    $.ajax({
        url: "fetch_scripts/fetch_cash_pending_transactions.php",
        type: "GET",
        data: {
            Pcsh_limit: Pcsh_limit,
            Pcsh_offset: Pcsh_offset,
            //storeid: storeid
        },
        dataType: "json",

        success: function (response) {

            hideLoader5();

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

                Pcsh_finished = true;

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

                return;
            }

            let rows = "";

            response.forEach(function (Pcsh) {

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

            Pcsh_offset += Pcsh_limit;
            Pcsh_loading = false;
        },

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

function loadTodaycsh(reset = false) {

    // ✅ Reset mode (when store changes)
    if (reset) {
        csh_offset = 0;
        csh_finished = false;
        csh_loading = false;
        $("#todayscash").html("");
       
    }

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

    if (csh_loading || csh_finished) {
        return;
    }

    csh_loading = true;
    showLoader6();

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

    $.ajax({
        url: "fetch_scripts/fetch_cash_today_transactions.php",
        type: "GET",
        data: {
            csh_limit: csh_limit,
            csh_offset: csh_offset
         //   storeid: storeid
        },
        dataType: "json",

        success: function (response) {

            hideLoader6();

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

                csh_finished = true;

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

                return;
            }

            let rows = "";

            response.forEach(function (csh) {

                    let status = (csh.t_status || "").toLowerCase();
                    let t_type = (csh.t_type || "").toLowerCase();
                
                    let dateStyle = '';
                    let rowclass = '';

               if (status === "confirmed" && t_type === "rec") {
                    rowclass = "inv-row-2";
                    dateStyle = "text-del";
                
                } else if (status === "confirmed" && t_type === "exp") {
                    rowclass = "inv-row-2";
                    dateStyle = "text-danger";
                
                } else {
                    dateStyle = "text-warning";
                }
                
                    let total = Number(csh.total_result || 0).toLocaleString('en-UG');
                
                    rows += `
                    <tr data-toggle="modal" class="${rowclass}" data-id="${csh.t_doc_no}"
                        data-loc_id="${csh.co_id}"
                        data-ord="${csh.t_doc_no}"
                        data-type="${csh.t_type}" data-target="#ModalBasic">
                        
                        <td class="${dateStyle}">${csh.t_doc_no || ''}</td>
                        <td class="${dateStyle}">${csh.acc_name || ''}</td>
                        <td class="${dateStyle}">${csh.t_type || ''}</td>
                        <td class="${dateStyle}">${total}</td>
                     
                    </tr>
                    `;
                });
                
            $("#cashLoader").hide();
            $(".cash-transactions").show();
            $("#todayscash").append(rows);

            csh_offset += csh_limit;
            csh_loading = false;
        },

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


function loadaccount_balances(reset = false) {
    
    let comp_id = $('#sel_co').val();

    // ✅ Reset mode (when store changes)
    if (reset) {
        acc_offset = 0;
        acc_finished = false;
        acc_loading = false;
        $("#accounts").html("");
       
    }

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

    if (acc_loading || acc_finished) {
        return;
    }

    acc_loading = true;
   // showLoader6();

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

    $.ajax({
        url: "fetch_scripts/fetch_cash_accounts_bal.php",
        type: "GET",
        data: {
            acc_limit: acc_limit,
            acc_offset: acc_offset,
            //storeid: storeid,
            comp_id: comp_id
        },
        dataType: "json",

        success: function (response) {

            //hideLoader6();

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

                acc_finished = true;

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

                return;
            }

            let rows = "";

            response.forEach(function (acc) {

                    let status = (acc.acc_type || "").toLowerCase();
                    let t_type = (acc.acc_type || "").toLowerCase();
                
                    let dateStyle = '';
                    let rowclass = '';
                     let icon = '';

                      if (status === "cash") {
                            rowclass = "stt-run";
                            dateStyle = "text-rec";
                            icon = '<ion-icon name="cash-outline"></ion-icon>';
                        } else if (status === "bank") {
                            rowclass = "stt-run";
                            dateStyle = "text-del";
                            icon = '<ion-icon name="business-sharp"></ion-icon>';
                        }
                
                    let total = Number(acc.balance || 0).toLocaleString('en-UG');
                
                  rows += `
                    <tr data-toggle="modal" class="stt-run" data-id="${acc.t_cr}"
                        data-loc_id="${acc.co_id}"
                        data-accountno="${acc.t_cr}"
                        data-accname="${acc.acc_name}"
                        data-stt_type="stt_accs"
                        data-type="${acc.t_type}" data-target="#Statement_run">
                        
                        <td class="${dateStyle}">${icon}</td>
                        <td class="${dateStyle}">${acc.acc_name || ''}</td>
                        <td class="${dateStyle}">${acc.acc_type || ''}</td>
                        <td class="${dateStyle}">${total}</td>
                    
                    </tr>
                    `;
                });
                
            $("#accountsLoader").hide();
            $(".accounts-balances").show();
            $("#accounts").append(rows);

            acc_offset += acc_limit;
            acc_loading = false;
        },

        error: function () {
            console.error("Failed to load accounts");
            acc_loading = false; // ✅ prevent freeze
           // hideLoader6();
        }
    });
}


function loadtop_expenses(reset = false) {
    
    let comp_id = $('#sel_co').val();

    // ✅ Reset mode (when store changes)
    if (reset) {
        exp_offset = 0;
        exp_finished = false;
        exp_loading = false;
        $("#top_exp").html("");
       
    }

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

    if (exp_loading || exp_finished) {
        return;
    }

    exp_loading = true;
   // showLoader6();

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

    $.ajax({
        url: "fetch_scripts/fetch_top_expenses.php",
        type: "GET",
        data: {
            exp_limit: exp_limit,
            exp_offset: exp_offset,
           // storeid: storeid,
            comp_id: comp_id
        },
        dataType: "json",

        success: function (response) {

            //hideLoader6();

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

                exp_finished = true;

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

                return;
            }

            let rows = "";

            response.forEach(function (exp) {

                    let status = (exp.acc_type || "").toLowerCase();
                    let t_type = (exp.acc_type || "").toLowerCase();
                
                    let dateStyle = '';
                    let Style2 = '';
                    let Style3 = '';
                    let rowclass = '';
                    
                    dateStyle = "text-rec";
                    Style2 = "text-danger";
                    Style3 = "transparent";
                    
                    if (exp.t_type === "EXP" || exp.t_type === "BNK") {
                            rowclass = "stt-detail";
                            dateStyle = "text-rec";
                            particulars=(stt.accname_exp || '');
                        } else if (exp.t_type === "REC") {
                            rowclass = "stt-detail";
                            dateStyle = "text-rec";
                            particulars=(stt.acc_rec || '');
                        }

                
                    let total = Number(exp.top_expenses || 0).toLocaleString('en-UG');
                
                  rows += `
                    <tr data-toggle="modal" class="stt-run" data-id="${exp.t_cr}"
                        data-loc_id="${exp.co_id}"
                        data-ord="${exp.t_cr}"
                        data-accountno="${exp.t_cr}"
                        data-accname="${exp.acc_name}"
                        data-stt_type="stt_exp"
                        data-type="${exp.acc_type}" data-target="#Statement_run">
                        
                        <td data-toggle="modal" class="${dateStyle}"> ${exp.acc_name || ''}</td>
                      
                        <td class="${Style2}">${total}</td>
                    
                    </tr>
                    `;
                });
                
            $("#topexpLoader").hide();
            $(".top-exp ").show();
            $("#top_exp").append(rows);

            exp_offset += exp_limit;
            exp_loading = false;
        },

        error: function () {
            console.error("Failed to load accounts");
            exp_loading = false; // ✅ prevent freeze
           // hideLoader6();
        }
    });
}

function load_salesteam_balances(reset = false) {
    
    let comp_id = $('#sel_co').val();

    // ✅ Reset mode (when store changes)
    if (reset) {
        stb_offset = 0;
        stb_finished = false;
        stb_loading = false;
        $("#salesteam").html("");
       
    }

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

    if (stb_loading || stb_finished) {
        return;
    }

    stb_loading = true;
    show_sales_team_Loader();

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

    $.ajax({
        url: "fetch_scripts/fetch_salesteam_balance.php",
        type: "GET",
        data: {
            stb_limit: stb_limit,
            stb_offset: stb_offset,
           // storeid: storeid,
            comp_id: comp_id
        },
        dataType: "json",

        success: function (response) {

            hide_sales_team_Loader();

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

                stb_finished = true;

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

                return;
            }

            let rows = "";

            response.forEach(function (stb) {

                    let status = (stb.acc_type || "").toLowerCase();
                    let t_type = (stb.acc_categ || "").toLowerCase();
                
                    let dateStyle = '';
                    let rowclass = '';
                    let categ='';
                    let amtStyle='text-rec';

                      if (t_type === "sales_person") {
                          categ= "sales Person";
                            rowclass = "stt-run";
                            dateStyle = "text-rec";
                        } else if (t_type === "customer") {
                             categ= "Customer";
                            rowclass = "inv-row-2";
                            dateStyle = "text-rec";
                        }
                        
                        if (stb.cr_balance<0) {
                          amtStyle="text-danger";  
                        }
                
                    let total = Number(stb.cr_balance || 0).toLocaleString('en-UG');
                
                  rows += `
                    <tr data-toggle="modal" class="${rowclass}" data-id="${stb.t_cr}"
                        data-loc_id="${stb.co_id}"
                        data-ord="${stb.t_cr}"
                        data-accountno="${stb.t_cr}"
                        data-accname="${stb.acc_name}"
                        data-stt_type="stt_cr"
                        data-type="${stb.t_type}" data-target="#Statement_run">
                        
                        <td class="${dateStyle}">${stb.acc_name || ''}</td>
                        <td class="${dateStyle}">${categ}</td>
                        <td class="${amtStyle}">${total}</td>
                    
                    </tr>
                    `;
                });
                
            $("#salesteamLoader").hide();
            $(".salesteam-list ").show();
            $("#salesteam").append(rows);

            stb_offset += stb_limit;
            stb_loading = false;
        },

        error: function () {
            console.error("Failed to load accounts");
            stb_loading = false; // ✅ prevent freeze
            hide_sales_team_Loader();
        }
    });
}



function load_recievables(reset = false) {
    
    let comp_id = $('#sel_co').val();

    // ✅ Reset mode (when store changes)
    if (reset) {
        rcb_offset = 0;
        rcb_finished = false;
        rcb_loading = false;
        $("#recievables").html("");
       
    }

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

    if (rcb_loading || rcb_finished) {
        return;
    }

    rcb_loading = true;
   // showLoader6();

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

    $.ajax({
        url: "fetch_scripts/fetch_recievables.php",
        type: "GET",
        data: {
            rcb_limit: rcb_limit,
            rcb_offset: rcb_offset,
         //   storeid: storeid,
            comp_id: comp_id
        },
        dataType: "json",

        success: function (response) {

            //hideLoader6();

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

                rcb_finished = true;

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

                return;
            }

            let rows = "";

            response.forEach(function (rcb) {

                    let status = (rcb.acc_type || "").toLowerCase();
                    let t_type = (rcb.acc_categ || "").toLowerCase();
                
                    let dateStyle = '';
                    let rowclass = '';
                    let categ=''

                      if (t_type === "sales_person") {
                          categ= "sales Person";
                            rowclass = "stt-run";
                            dateStyle = "text-rec";
                        } else if (t_type === "customer") {
                             categ= "Customer";
                            rowclass = "inv-row-2";
                            dateStyle = "text-rec";
                        }
                
                    let total = Number(rcb.ABS_cr_balance || 0).toLocaleString('en-UG');
                
                  rows += `
                    <tr data-toggle="modal" class="${rowclass}" data-id="${rcb.t_cr}"
                        data-loc_id="${rcb.co_id}"
                        data-ord="${rcb.t_cr}"
                        data-accountno="${rcb.t_cr}"
                        data-accname="${rcb.acc_name}"
                        data-type="${rcb.t_type}" data-target="#Statement_run">
                        
                        <td class="${dateStyle}">${rcb.acc_name || ''}</td>
                        <td class="${dateStyle}">${categ}</td>
                        <td class="${dateStyle}">${total}</td>
                    
                    </tr>
                    `;
                });
                
            $("#recievableLoader").hide();
            $(".reciev-list ").show();
            $("#recievables").append(rows);

            rcb_offset += rcb_limit;
            rcb_loading = false;
        },

        error: function () {
            console.error("Failed to load accounts");
            rcb_loading = false; // ✅ prevent freeze
           // hideLoader6();
        }
    });
}


function load_payables(reset = false) {
    
    let comp_id = $('#sel_co').val();

    // ✅ Reset mode (when store changes)
    if (reset) {
        pyb_offset = 0;
        pyb_finished = false;
        pyb_loading = false;
        $("#payables").html("");
       
    }

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

    if (pyb_loading || pyb_finished) {
        return;
    }

    pyb_loading = true;
   // showLoader6();

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

    $.ajax({
        url: "fetch_scripts/fetch_payables.php",
        type: "GET",
        data: {
            pyb_limit: pyb_limit,
            pyb_offset: pyb_offset,
          //  storeid: storeid,
            comp_id: comp_id
        },
        dataType: "json",

        success: function (response) {

            //hideLoader6();

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

                pyb_finished = true;

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

                return;
            }

            let rows = "";

            response.forEach(function (pyb) {

                    let status = (pyb.acc_type || "").toLowerCase();
                    let t_type = (pyb.acc_categ || "").toLowerCase();
                
                    let dateStyle = '';
                    let rowclass = '';
                    let categ=''
                    let Style2 = '';
                    
                     Style2 = "text-pink";

                      if (t_type === "sales_person") {
                          categ= "sales Person";
                            rowclass = "inv-row-2";
                            dateStyle = "text-rec";
                        } else if (t_type === "customer") {
                             categ= "Customer";
                            rowclass = "inv-row-2";
                            dateStyle = "text-rec";
                        }
                
                    let total = Number(pyb.cr_balance || 0).toLocaleString('en-UG');
                
                  rows += `
                    <tr data-toggle="modal" class="${rowclass}" data-id="${pyb.t_cr}"
                        data-loc_id="${pyb.co_id}"
                        data-ord="${pyb.t_cr}"
                        data-type="${pyb.t_type}" data-target="#ModalBasic">
                        
                        <td class="${dateStyle}">${pyb.acc_name || ''}</td>
                        <td class="${dateStyle}">${categ}</td>
                        <td class="${Style2}">${total}</td>
                    
                    </tr>
                    `;
                });
                
            $("#payableLoader").hide();
            $(".payab-list ").show();
            $("#payables").append(rows);

            pyb_offset += pyb_limit;
            pyb_loading = false;
        },

        error: function () {
            console.error("Failed to load accounts");
            pyb_loading = false; // ✅ prevent freeze
           // hideLoader6();
        }
    });
}

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

    load_salesteam_balances();

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

        if (stb_loading || stb_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
) {
    load_salesteam_balances();
}

    });

});


$(document).ready(function () {
    
    //showLoader7();

    loadaccount_balances();

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

        if (acc_loading || acc_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
) {
    loadaccount_balances();
}

    });

});


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

    load_salesrep_OverviewToday();

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

        if (ovSR_loading || ovSR_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 - 25
) {
    load_salesrep_OverviewToday();
}

    });

});

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

    loadOverviewPend();

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

        if (ov_loading || ov_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
) {
    loadOverviewPend();
}

    });

});

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

    loadOverviewToday();

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

        if (ovT_loading || ovT_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
) {
    loadOverviewToday();
}

    });

});


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

    loadPendcsh();

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

        if (Pcsh_loading || Pcsh_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
) {
    loadPendcsh();
}

    });

});

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

    loadTodaycsh();

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

        if (csh_loading || csh_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
) {
    loadTodaycsh();
}

    });

});

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

    fetch_acc_stt();

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

        if (stt_loading || stt_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
) {
    fetch_acc_stt();
}

    });

});


function show_sales_team_Loader() {
    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-warning"></div>
            Loading Transactions...
        </td>
    </tr>
    `;

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

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

function showLoader5() {
    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>
    `;

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

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

function showLoader6() {
    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>
    `;

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

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

   function showLoader7() {
    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>
    `;

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

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

   function showLoader8() {
    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>
    `;

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

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

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

    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>
    `;

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

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



$(document).on("click", ".fetch-details", 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' || t_type === 'CS INV' || t_type === 'INV RET' || t_type === 'INV PMT' || t_type === 'STK INV' || t_type === 'LO') {
        fetch_inventory_details_head(loc_id, ord_no, t_type);
   
    } 
    
    else if (t_type === 'REC' || t_type === 'EXP' ) {
        fetch_cash_details_head(loc_id, ord_no, t_type);
  
    } else {
        console.error("Invalid t_type:", t_type);
    }
});

  function fetch_inventory_details_head(loc_id, ord_no, t_type) {
    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);
            fetch_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 fetch_cash_details_head(loc_id, ord_no, t_type) {
    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);
            fetch_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 fetch_inventory_details_body(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);
            fetch_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 fetch_cash_details_body(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);
            fetch_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 fetch_inventory_details_entry(loc_id, ord_no, t_type, usr_id) {
    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-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 fetch_cash_details_entry(loc_id, ord_no, t_type, usr_id) {
    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-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("submit", "#confirmationForm", function(event) {  
    event.preventDefault();  // Prevent default form submission

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

    $.ajax({  
        url: "query/submit_confirmation.php",  
        method: "POST",  
        data: $(this).serialize(),  
        beforeSend: function () {  
            console.log("AJAX Request Sent...");
            $('#ModalBasic').modal('hide'); // Hide modal
            $("#overviewpending").html("");
            $("#overviewtoday").html("");
            showLoader7();
            showLoader8();
          
        },  
        success: function (response) {  
           // console.log("AJAX Success:", response); // Debugging
            unclearedbalance();
            pers_this_mnth_bl();
      
           loadOverviewPend(true); 
           loadOverviewToday(true); 
           load_salesrep_OverviewToday(true); 
        },
        error: function (xhr, status, error) {
            console.error("AJAX Error:", error, xhr.responseText);
            alert("Submission failed! Error: " + xhr.responseText);
        }
    });  
});

   function cash_acc_balance() {
           $('#cash_acc_bl').html(`
                <span class="spinner-grow spinner-grow-sm text-light"></span>
            `);
     // Show centered loading spinner
    
    let comp_id = $('#sel_co').val();

            $.ajax({
                url: 'query/fetch_cash_acc_bl.php', // Fetch data from this PHP script
                type: 'GET',
                data: { comp_id: comp_id },
                dataType: 'html',
                success: function(response) {
                    $('#cash_acc_bl').html(response); // Populate the modal dynamically
                },
                error: function() {
                    $('#cash_acc_bl').html('<li>Error loading data.</li>'); // Handle errors
                }
            });
        }
        
    function bankings_today() {
           $('#bnkd_today').html(`
                <span class="spinner-grow spinner-grow-sm text-light"></span>
            `);
     // Show centered loading spinner
    
    let comp_id = $('#sel_co').val();

            $.ajax({
                url: 'query/fetch_bnkd_today.php', // Fetch data from this PHP script
                type: 'GET',
                data: { comp_id: comp_id },
                dataType: 'html',
                success: function(response) {
                    $('#bnkd_today').html(response); // Populate the modal dynamically
                },
                error: function() {
                    $('#bnkd_today').html('<li>Error loading data.</li>'); // Handle errors
                }
            });
        }
        
    function cash_tfr_in_today() {
           $('#ctfr_in_today').html(`
                <span class="spinner-grow spinner-grow-sm text-light"></span>
            `);
     // Show centered loading spinner
    
    let comp_id = $('#sel_co').val();

            $.ajax({
                url: 'query/fetch_ctfr_in_today.php', // Fetch data from this PHP script
                type: 'GET',
                data: { comp_id: comp_id },
                dataType: 'html',
                success: function(response) {
                    $('#ctfr_in_today').html(response); // Populate the modal dynamically
                },
                error: function() {
                    $('#ctfr_in_today').html('<li>Error loading data.</li>'); // Handle errors
                }
            });
        }
        
        function cash_tfr_out_today() {
           $('#ctfr_out_today').html(`
                <span class="spinner-grow spinner-grow-sm text-light"></span>
            `);
     // Show centered loading spinner
    
    let comp_id = $('#sel_co').val();

            $.ajax({
                url: 'query/fetch_ctfr_out_today.php', // Fetch data from this PHP script
                type: 'GET',
                data: { comp_id: comp_id },
                dataType: 'html',
                success: function(response) {
                    $('#ctfr_out_today').html(response); // Populate the modal dynamically
                },
                error: function() {
                    $('#ctfr_out_today').html('<li>Error loading data.</li>'); // Handle errors
                }
            });
        }
        
    function expense_today() {
           $('#exp_today').html(`
                <span class="spinner-grow spinner-grow-sm text-light"></span>
            `);
     // Show centered loading spinner
    
    let comp_id = $('#sel_co').val();

            $.ajax({
                url: 'query/fetch_expense_today.php', // Fetch data from this PHP script
                type: 'GET',
                data: { comp_id: comp_id },
                dataType: 'html',
                success: function(response) {
                    $('#exp_today').html(response); // Populate the modal dynamically
                },
                error: function() {
                    $('#exp_today').html('<li>Error loading data.</li>'); // Handle errors
                }
            });
        }
        

   function unclearedbalance() {
            $('#pers_bl').html(`
        <span class="spinner-grow spinner-grow-sm text-danger"></span>
    `); // Show centered loading spinner
    
    let comp_id = $('#sel_co').val();

            $.ajax({
                url: 'query/fetch_overview_ALL_bl.php', // Fetch data from this PHP script
                type: 'GET',
                data: { comp_id: comp_id },
                dataType: 'html',
                success: function(response) {
                    $('#pers_bl').html(response); // Populate the modal dynamically
                },
                error: function() {
                    $('#pers_bl').html('<li>Error loading data.</li>'); // Handle errors
                }
            });
        }

            $(document).ready(function() {
           // unclearedbalance();
        });
        
   function pers_this_mnth_bl() {
            $('#pers_this_month_bl').html(`
         <span class="spinner-grow spinner-grow-sm text-warning"></span>
    `); // Show centered loading spinner
    
    let comp_id = $('#sel_co').val();
    
            $.ajax({
                url: 'query/fetch_overview_this_mnth_bl.php', // Fetch data from this PHP script
                type: 'GET',
                 data: { comp_id: comp_id },
                dataType: 'html',
                success: function(response) {
                    $('#pers_this_month_bl').html(response); // Populate the modal dynamically
                },
                error: function() {
                    $('#pers_this_month_bl').html('<li>Error loading data.</li>'); // Handle errors
                }
            });
        }

            $(document).ready(function() {
           // pers_this_mnth_bl();
        });
        
        
        function prev_mnth_bl() {
            $('#prev_bl').html(`
        <span class="spinner-grow spinner-grow-sm text-primary"></span>
    `); // Show centered loading spinner
    
    let comp_id = $('#sel_co').val();

            $.ajax({
                url: 'query/fetch_overview_prev_mnth_bl.php', // Fetch data from this PHP script
                type: 'GET',
                data: { comp_id: comp_id },
                dataType: 'html',
                success: function(response) {
                    $('#prev_bl').html(response); // Populate the modal dynamically
                },
                error: function() {
                    $('#prev_bl').html('<li>Error loading data.</li>'); // Handle errors
                }
            });
        }

            $(document).ready(function() {
           // prev_mnth_bl();
            // currstocks();
        });
        
        
 function currstocks() {
            $('#currstocks').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
            
            let comp_id = $('#sel_co').val();
        
            $.ajax({
                url: 'query/fetch_this_mnth_stocksales.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) {
                    $('#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>
                    `);
                }
            });
        }
        


// =============================
// GLOBAL CHART INSTANCES
// =============================
let statusChart = null;
let dailyChart = null;


// =============================
// LOAD DATA FROM SERVER
// =============================
function loadCharts() {

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

    $.ajax({
        url: 'query/charts_accounts_data.php',
        method: 'GET',
        data: { comp_id: comp_id },
        dataType: 'json',
        success: function(data) {

            console.log(data);
        $("#dailyLoader").hide();
        $("#statusLoader").hide();
            renderDailyRevenue(data.daily);
            renderStatusChart(data.sales, data.collected);
        }
    });
}


// =============================
// DAILY REVENUE CHART
// =============================
function renderDailyRevenue(data) {

    // Destroy old chart safely
    if (dailyChart) {
        dailyChart.destroy();
    }

    const labels = data.map(r => formatDateShort(r.date));
    const values = data.map(r => Number(r.amount));

    const ctx = document.getElementById('dailyRevenueChart');

    dailyChart = new Chart(ctx, {
        type: 'bar', // change to 'bar' if needed
        data: {
            labels: labels,
            datasets: [{
                label: 'Revenue',
                data: values,
                fill: true,
                tension: 0.3
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,

            plugins: {
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return 'UGX ' + formatNumber(context.raw);
                        }
                    }
                },
                legend: {
                    display: false
                }
            },

            scales: {
                x: {
                    grid: {
                        display: false
                    },
                    ticks: {
                        autoSkip: true,
                        maxTicksLimit: 6,
                        maxRotation: 0,
                        minRotation: 0
                    }
                },
                y: {
                    grid: {
                        drawBorder: false
                    },
                    ticks: {
                        callback: function(value) {
                            return formatNumber(value);
                        }
                    }
                }
            }
        }
    });
}


// =============================
// STATUS (PENDING vs COLLECTED)
// =============================
function renderStatusChart(sales, collected) {

    if (statusChart) {
        statusChart.destroy();
    }

    const ctx = document.getElementById('statusChart');

    statusChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ['Sales', 'Collected'],
            datasets: [{
                data: [
                    Number(sales),
                    Number(collected)
                ],
                
                hoverOffset: 5
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,

            plugins: {
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return context.label + ': UGX ' + formatNumber(context.raw);
                        }
                    }
                }
            }
        }
    });
}


// =============================
// FORMAT NUMBERS (K, M, B)
// =============================
function formatNumber(num) {
    num = Number(num);

    if (num >= 1_000_000_000) return (num / 1_000_000_000).toFixed(1) + 'B';
    if (num >= 1_000_000) return (num / 1_000_000).toFixed(1) + 'M';
    if (num >= 1_000) return (num / 1_000).toFixed(1) + 'K';

    return num;
}


// =============================
// FORMAT DATE (1 Apr)
// =============================
function formatDateShort(dateStr) {
    const date = new Date(dateStr);

    return date.toLocaleDateString('en-GB', {
        day: 'numeric',
        month: 'short'
    });
}

</script>