<?php
ini_set('session.cookie_secure', 1);
session_start();
// Initialize the session
require '../includes/session-check.php';

require_once "../includes/header.php";
require '../includes/menu-permissions.php';



$coid = $_SESSION['co_id'];
$uid  =$_SESSION['user_id'];


// Fetch sales people for deliveries and goods returned
$stmt = $pdo->prepare("SELECT DISTINCT  c.id, c.org_name FROM company c JOIN permissions p ON c.id = p.co_id JOIN users u ON u.id = p.user_id WHERE p.pm_acc_lvl IN (0, 1,2, 3, 4,5, 6,7,8,11) AND u.status = 'active' AND p.user_id=:uid ORDER BY c.id ASC");

$stmt->execute([':uid'=>$uid]);
$sel_co = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>



<body>

    <!-- loader -->
    <div id="loader">
        <img src="assets/img/logo-icon.png" alt="icon" class="loading-icon">
    </div>
    <!-- * loader -->

    <!-- App Header -->
    <div class="appHeader bg-primary text-light">
        <div class="left">
            <a href="#" class="headerButton" data-toggle="modal" data-target="#sidebarPanel">
                <ion-icon name="menu-outline"></ion-icon>
            </a>
        </div>
         <div class="pageTitle">appsale</div>
        
    </div>
    <!-- * App Header -->


    <!-- App Capsule -->
    <div id="appCapsule">

        <!-- Wallet Card -->

        <!-- Wallet Card -->
  <div id="toastContainer" class="toast-container"></div> 

     
         <!--  Component Section -->   
         <div id="componentsSection" class="admin-section section mt-1" style="display:none;">

   

    <!-- Real Content -->
    <div class="content-wrapper" style="display:none;">

        <div class="card p-3">

            

        </div>
    </div>
</div>
    <!--  * Component Section -->   
    
 <!--  * Accounts Section --> 
 <?php
  require 'page_views/ledger_accounts.php';
  require 'page_views/customers.php';
  require 'page_views/suppliers.php';
  require 'page_views/permissions.php';
 // require 'page_views/inventory.php';
 // require 'page_views/overview.php';
 // require 'page_views/cashier.php';
  require 'page_views/view.php';
  
  
  ?>
  
   <!--  * Accounts Section -->  
   
    <!--  * Product List Section --> 
 <?php
  require 'page_views/product_list_b.php';
  
  ?>
   <!--  * Product List  Section -->  
 
    <div id="trans" style="display:none;" class="admin-section section mt-1"> 
            
        </div>
        <!-- * Transactions -->
        
       <div id="pg" class="admin-section" style="display:none;">

    <!-- Skeleton -->
  
    <!-- Real Content -->
    <div class="content-wrapper" style="display:none;">

        <!-- Stats -->
        <div id="income" class="section">
            <div class="row mt-2">
                <div class="col-6">
                    <div class="stat-box">
                        <div class="title">Income</div>
                        <div class="value text-success">$ 552.95</div>
                    </div>
                </div>
                <div class="col-6">
                    <div class="stat-box">
                        <div class="title">Expenses</div>
                        <div class="value text-danger">$ 86.45</div>
                    </div>
                </div>
            </div>
            <div class="row mt-2">
                <div class="col-6">
                    <div class="stat-box">
                        <div class="title">Total Bills</div>
                        <div class="value">$ 53.25</div>
                    </div>
                </div>
                <div class="col-6">
                    <div class="stat-box">
                        <div class="title">Savings</div>
                        <div class="value">$ 120.99</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Users Online -->
        <div id="usersonline" class="section mt-1">
            <div class="section-title">
                <h6>Users online</h6>
            </div>

            <div class="card">
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th class="text-light bg-secondary">User</th>
                                <th class="text-light bg-secondary">IP</th>
                                <th class="text-light bg-secondary">Device</th>
                                <th class="text-light bg-secondary">Login Time</th>
                                <th class="text-light bg-secondary">Logout Time</th>
                                <th class="text-light bg-secondary">Status</th>
                                <th class="text-light bg-secondary">Action</th>
                            </tr>
                        </thead>
                        <tbody id="sessions"></tbody>
                    </table>
                </div>
            </div>
        </div>

    </div>
</div>

            
   <div id="approveusers" class="admin-section section mt-1" style="display:none;">

    <!-- Skeleton -->
    <div class="skeleton-wrapper">
        <div class="skeleton-box"></div>
        <div class="skeleton-box"></div>
        <div class="skeleton-box"></div>
    </div>

    <!-- Real Content -->
    <div class="content-wrapper" style="display:none;">

        <div class="section-title">
            <h6>Users Pending Approval</h6>
        </div>

        <div class="card">
            <div class="table-responsive" style="max-height:400px; overflow-y:auto;">
                <table class="table">
                    <thead>
                        <tr>
                            <th class="text-light bg-secondary">Username</th>
                            <th class="text-light bg-secondary">Firstname</th>
                            <th class="text-light bg-secondary">Secondname</th>
                            <th class="text-light bg-secondary">Email</th>
                            <th class="text-light bg-secondary">Action</th>
                        </tr>
                    </thead>
                    <tbody id="approval"></tbody>
                </table>
            </div>
        </div>

    </div>
</div>
</div>
     


        <div class="section mt-1">
            <div class="section-title">
            
        </div>
            <div class="card">

                <div class="table-responsive">
                   
                   
                </div>

            </div>
            
        </div>
        <!-- * app footer -->


        <!-- * app footer -->

    </div>
    <!-- * App Capsule -->


    <!-- App Bottom Menu -->
<?php
// Initialize the session
require 'page_views/modals/product_modals.php';
require 'page_views/modals/ledgeraccounts_modals.php';
require 'page_views/modals/customer_modals.php';
require 'page_views/modals/supplier_modals.php';
require 'page_views/modals/permission_modals.php';
require 'page_views/modals/inventory_del_modals.php';
require 'page_views/modals/general_popup_modals.php';
require 'page_views/modals/cashier_modals.php';
require 'page_views/modals/side_menus.php';

 //  <!-- * App Bottom Menu -->

   // <!-- App Sidebar -->

// Initialize the session
require '../includes/admin-side-menu.php';
 //   <!-- * App Sidebar -->
 //   <!-- ///////////// Js Files ////////////////////  -->
 //   <!-- Jquery -->
 require '../includes/js-bottom-scripts.php';
 require '../includes/canv-bottom-menu.php';
// require '../includes/js-menu-scripts.php';
 
 require 'submit_scripts/submit_warehouse.php';
 require 'submit_scripts/submit_products.php';
 require 'submit_scripts/submit_ledger_accounts.php';
 require 'submit_scripts/submit_customer.php';
 require 'submit_scripts/submit_supplier.php';
 require 'submit_scripts/submit_permissions.php';
 require 'submit_scripts/submit_inventory.php';
 require 'submit_scripts/submit_inventory_pending.php';
 require 'submit_scripts/submit_inventory_reports.php';
 require 'submit_scripts/submit_cashier.php';
 require 'submit_scripts/submit_reports.php';
 require 'submit_scripts/submit_view.php';
 require 'submit_scripts/submit_admin.php';
 
 ?>
 
<script>

let storeid = null;

let inv_limit = 30;
let inv_offset = 0;

let inv_loading = false;
let inv_finished = false;

let Pinv_limit = 30;
let Pinv_offset = 0;

let Pinv_loading = false;
let Pinv_finished = false;

let Pcsh_limit = 30;
let Pcsh_offset = 0;

let Pcsh_loading = false;
let Pcsh_finished = false;

let csh_limit = 30;
let csh_offset = 0;

let csh_loading = false;
let csh_finished = false;

let ov_limit = 30;
let ov_offset = 0;

let ov_loading = false;
let ov_finished = false;

let ovRCL_limit = 30;
let ovRCL_offset = 0;

let ovRCL_loading = false;
let ovRCL_finished = false;

let ovSR_limit = 30;
let ovSR_offset = 0;

let ovSR_loading = false;
let ovSR_finished = false;

let ovT_limit = 30;
let ovT_offset = 0;

let ovT_loading = false;
let ovT_finished = false;

let acc_limit = 30;
let acc_offset = 0;

let acc_loading = false;
let acc_finished = false;

let exp_limit = 30;
let exp_offset = 0;

let exp_loading = false;
let exp_finished = false;

let rcb_limit = 30;
let rcb_offset = 0;

let rcb_loading = false;
let rcb_finished = false;

let pyb_limit = 30;
let pyb_offset = 0;

let pyb_loading = false;
let pyb_finished = false;

let stb_limit = 30;
let stb_offset = 0;

let stb_loading = false;
let stb_finished = false;

let stt_limit = 30;
let stt_offset = 0;

let stt_loading = false;
let stt_finished = false;

function showToast(message, type = "success") {

    const toastId = "toast_" + Date.now();

    let toastHTML = `
        <div id="${toastId}" class="toast show ${type}">
            <div class="toast-header">
                <strong class="mr-auto">
                    ${type === "success" ? "Success" : "Error"}
                </strong>
                <button type="button" class="ml-2 mb-1 close" onclick="removeToast('${toastId}')">
                    &times;
                </button>
            </div>
            <div class="toast-body">
                ${message}
            </div>
        </div>
    `;

    $("#toastContainer").append(toastHTML);

    setTimeout(function () {
        removeToast(toastId);
    }, 3000);
}

function removeToast(id) {
    $("#" + id).fadeOut(300, function () {
        $(this).remove();
    });
}


document.querySelectorAll(".appBottomMenu .item")
    .forEach(link => {
        link.addEventListener("click", function(e) {
            if (this.getAttribute("href").startsWith("#")) {
                e.preventDefault();
                window.location.hash = this.getAttribute("href");
            }
        });
    });
    
    $(document).on("click", ".menu-link", function (e) {
    e.preventDefault();

    let section = $(this).data("section");

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

    setTimeout(function () {
        showSection(section);
    }, 200);
});

function showSection(sectionId) {
      // Hide only specific sections
   // $("#approveusers, #wallet,#OverviewCard").hide();
    $("#" + sectionId).show();
}
/* ============================================================
   1️⃣ UTILITIES
============================================================ */

function showSkeleton(section) {
    section.find(".skeleton-wrapper").show();
    section.find(".content-wrapper").hide();
}

function hideSkeleton(section) {
    section.find(".skeleton-wrapper").hide();
    section.find(".content-wrapper").show();
}

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

function getSectionElement(route) {
    const sections = {
        overview: "#headlineSection, #OverviewheadlineSection, #OverviewCard, #pend_all_container, #overview_todays_transactions, #currentstocks, #recievables_container_list, #payables_container_list, #salesteam_container_list, #overview_sales_rep_transactions,#overview_reconciliation_transactions",
        pg: "#headlineSection,#InventoryOverviewheadlineSection, #overview_reconciliation_transactions",
        components: "#componentsSection",
        customers: "#customerHeaderSection, #customerSection",
        supplier: "#supplier_HeaderSection, #supplierSection",
        permissions: "#permissions_HeaderSection, #permissionsSection",
        accountsledger: "#ledger_accounts_HeaderSection, #ledger_accountsSection",
        product_list_b: "#productlist_HeaderSection, #pdtlistbSection",
        inventory: "#headlineSection, #InventoryOverviewheadlineSection, #currentstocks, #pending-inventory, #todays-inventory",
        accounts: "#headlineSection,  #AccountsOverviewheadlineSection, #OverviewCard, #AccountCard, #cashierCharts,#pendcash_container, #acc_bal_list,#top_exp_list, #recievables_container_list, #payables_container_list,#salesteam_container_list",
        admin: "#headlineSection, #AdminheadlineSection,#acc_bal_list"
    };

    return sections[route] ? $(sections[route]) : null;
}


/* ============================================================
   2️⃣ SPA ROUTER CONTROLLER
============================================================ */

const routes = {

    overview: {
            onEnter() {
                const section = $("#OverviewCard");
                $("#overviewLoaderpending").show();
                 $("#overviewLoader").show();
                 show_sales_team_Loader();
                 
                unclearedbalance();
                pers_this_mnth_bl();
                prev_mnth_bl();
                resetApprovalState();
                loadOverviewPend(true);
                loadOverviewToday(true);
                load_salesrep_OverviewToday(true);
                load_to_reconcile_Overview(true);
                currstocks();
                 currentstocks();
               // top_exp();
                //resetWarehouseForm();
                
                load_salesteam_balances(true);
                
              
                    section.show();
                    setTimeout(() => section.addClass("active-section"), 10);
            },
        
            onLeave() {
                resetApprovalState();
            }
        },

    pg: {
        onEnter() {
            const section = getSectionElement("inventory");

           load_to_reconcile_Overview(true);

            Promise.all([
                delay(500),
                new Promise(resolve => {
                })
            ]).then(() => hideSkeleton(section));
        },
        onLeave() {}
    },
    
    components: {
        onEnter() {
            const section = getSectionElement("components");
            resetWarehouseForm();
           // loadManagers();
            showSkeleton(section);
    
            Promise.all([
                delay(400)
            ]).then(() => {
                hideSkeleton(section);
            });
        },
        onLeave() {}
    },
    inventory: {
        onEnter() {
    showLoader3();
    showLoader4();
    
        inv_offset = 0;
        inv_finished = false;

        Pinv_offset = 0;
        Pinv_finished = false;

        currstocks();
        loadPendinv(true);
        loadinv(true);
        currentstocks();
        },
        onLeave() {}
    },
    
    permissions: {
        onEnter() {
            const section = getSectionElement("permissions");
           // resetWarehouseForm();
           // loadManagers();
            showSkeleton(section);
            loadPerm(true);
    
            Promise.all([
                delay(400)
            ]).then(() => {
                hideSkeleton(section);
            });
        },
        onLeave() {}
    },
    customers: {
        onEnter() {
            const section = getSectionElement("customers");
           // resetWarehouseForm();
           // loadManagers();
            showSkeleton(section);
            refreshcustomer();
    
            Promise.all([
                delay(400)
            ]).then(() => {
                hideSkeleton(section);
            });
        },
        onLeave() {}
    },
    
    accounts: {
        onEnter() {
            const section = getSectionElement("accounts");
           // resetWarehouseForm();
           // loadManagers();
           loadPendcsh(true);
                loadTodaycsh(true);
               // currentstocks();
                loadOverviewPend(true);
                //loadOverviewToday(true);
                loadaccount_balances(true);
                loadtop_expenses(true);
                load_recievables(true);
                load_payables(true);
                load_salesteam_balances(true);
                cash_acc_balance();
                bankings_today();
                expense_today();
                cash_tfr_in_today();
                cash_tfr_out_today();
                loadCharts() ;
                loadOverviewCharts();
         //   showSkeleton(section);
         
          //$(".table-container").show();
         
             $(".section-title1").show();
             $(".section-title2").hide();
          
    
            Promise.all([
                delay(400)
            ]).then(() => {
               // hideSkeleton(section);
            });
        },
        onLeave() {}
    },
    
    supplier: {
        onEnter() {
            const section = getSectionElement("supplier");
           // resetWarehouseForm();
           // loadManagers();
            showSkeleton(section);
            
            loadsupplier(true);
    
            Promise.all([
                delay(400)
            ]).then(() => {
                hideSkeleton(section);
            });
        },
        onLeave() {}
    },
    accountsledger: {
        onEnter() {
            const section = getSectionElement("accountsledger");
           // resetWarehouseForm();
           // loadManagers();
            showSkeleton(section);
    
            Promise.all([
                delay(400)
            ]).then(() => {
                hideSkeleton(section);
            });
        },
        onLeave() {}
    },
    
    product_list_b: {
        onEnter() {
            const section = getSectionElement("product_list_b");
           // resetProductsFormreset
           // loadManagers();
            showSkeleton(section);
            
            loadProducts(true);
    
            Promise.all([
                delay(400)
            ]).then(() => {
                hideSkeleton(section);
            });
        },
        onLeave() {}
    },
    admin: {
        onEnter() {
            const section = getSectionElement("admin");
           // resetProductsFormreset
           // loadManagers();
            //showSkeleton(section);
            loadcompanies(true);
            
            $(".section-title1").hide();
             $(".section-title2").show();
             
             $(".section-title").hide();
    
            Promise.all([
                delay(400)
            ]).then(() => {
                hideSkeleton(section);
            });
        },
        onLeave() {}
    }    
    

};

let currentRoute = null;
let transitionLock = false;

function router() {

    if (transitionLock) return;

    const hash = window.location.hash.replace("#", "") || "overview";
    if (currentRoute === hash) return;

    transitionLock = true;

    const nextRoute = hash;
    const currentSection = currentRoute ? getSectionElement(currentRoute) : $();
    const nextSection = getSectionElement(nextRoute);

    /* Leave current */
    if (currentRoute && routes[currentRoute]?.onLeave) {
        routes[currentRoute].onLeave();
    }

    if (currentSection.length) {
        currentSection.removeClass("active-section");
    }

    setTimeout(() => {

        $(".admin-section").hide();
        $(".section-heading").hide();
        $(".table-container").hide();

        if (nextSection?.length) {
            nextSection.show();
            setTimeout(() => nextSection.addClass("active-section"), 10);
        }

        routes[nextRoute]?.onEnter?.();

        currentRoute = nextRoute;
        transitionLock = false;

    }, 200);

    /* Bottom menu active state */
    $("#sidebarPanel").modal("hide");
    $(".appBottomMenu .item").removeClass("active");
    $("#" + nextRoute).addClass("active");
}

window.addEventListener("hashchange", router);
//window.addEventListener("load", router);

window.addEventListener("load", function () {

    let sel_co = $("#sel_co").val();

    if (!sel_co) {
        router();
        return;
    }

    fetchStore(sel_co).done(function () {
        router();
    });

});


/* ============================================================
   3️⃣ SESSION + INACTIVITY HANDLING
============================================================ */

function mysessioncheck() {
    fetch('../includes/my-session-check.php')
        .then(res => res.json())
        .then(data => {
            if (data.status === "expired") {
                localStorage.setItem("logout-event", Date.now());
                window.location.href = "app-user-login.php";
            }
        })
        .catch(err => console.error("Session check error:", err));
}

/* Inactivity Auto Logout */
let inactivityTime = 30 * 60 * 10000; // 15 minutes
let logoutTimer;

function resetTimer() {
    clearTimeout(logoutTimer);
    logoutTimer = setTimeout(logoutUser, inactivityTime);
}

function logoutUser() {
    fetch('../includes/logout.php', { method: 'POST' })
        .finally(() => {
            localStorage.setItem("logout-event", Date.now());
            window.location.href = 'app-user-login.php';
        });
}

["click", "mousemove", "mousedown", "keydown", "scroll", "touchstart"]
    .forEach(event => {
        document.addEventListener(event, resetTimer, true);
    });

resetTimer();

/* Cross-tab logout sync */
window.addEventListener("storage", function(event) {
    if (event.key === "logout-event") {
        window.location.href = "app-user-login.php";
    }
});


/* ============================================================
   4️⃣ ADMIN USER SESSIONS MODULE
============================================================ */

function fetchuserSessions() {
    fetch('../includes/fetch_sessions.php')
        .then(res => res.text())
        .then(data => {
            document.getElementById('sessions').innerHTML = data;
        });
}

function forceLogoutUser(id) {
    if (!confirm("Force logout this user from all devices?")) return;

    fetch('../includes/force_logout.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'user_id=' + id
    }).then(fetchuserSessions);
}

/* Poll sessions */
//setInterval(fetchuserSessions, 20000);
//fetchuserSessions();

document.getElementById("logoutBtn")
    .addEventListener("click", logoutUser);
    
    


$(document).on('click', '.approve-btn', function () {

    let btn = $(this);
    let doc_no = btn.data('doc');

    //if (!confirm("Approve this transaction?")) {
    //    return;
    //}

    $.ajax({
        url: '../includes/approve_bank_transaction.php',
        type: 'POST',
        data: {
            doc_no: doc_no
        },

        beforeSend: function () {
            btn.prop('disabled', true).text('Approving...');
        },

success: function (response) {

    if (response.status === 'success') {

        let amount = parseFloat(btn.data('amount')) || 0;

        btn.fadeOut(300, function () {
            $(this).remove();
        });

        let currentRow = btn.closest('tr');

        // exact date group
        let group = currentRow.data('group');

        // exact totals row
        let totalRow = $('.daily-total-row[data-group="' + group + '"]').last();

        let totalSpan = totalRow.find('.daily-total-amount');

        let currentTotal = parseFloat(
            totalSpan.text().replace(/,/g, '').trim()
        ) || 0;

        let newTotal = currentTotal + amount;

        totalSpan.text(
            newTotal.toLocaleString()
        );

    } else {

        alert(response.message || 'Approval failed');

        btn.prop('disabled', false).text('Approve');
    }
},

        error: function () {

            alert('Server error');

            btn.prop('disabled', false).text('Approve');
        }
    });

});


/* ============================================================
   5️⃣ ADMIN USER APPROVAL MODULE
============================================================ */

let approvalPage = 0;
let approvalDone = false;
let approvalLoading = false;

const approvalLimit = 8;

function resetApprovalState() {
    $(".pend-overview-transactions").hide();
     $('.table-container').first().hide();
   // $(".pend-overview-transactions").hide();
    $(".overview-transactions").hide();
    approvalPage = 0;
    approvalDone = false;
    approvalLoading = false;
    document.getElementById('approval').innerHTML = '';
    
let ovT_limit = 30;
let ovT_offset = 0;

let ovT_loading = false;
let ovT_finished = false;
}

function fetchuserApproval(reset = false) {

    if (approvalLoading || approvalDone) {
        return Promise.resolve(false);
    }

    if (reset) {
        approvalPage = 0;
        approvalDone = false;
        document.getElementById('approval').innerHTML = '';
    }

    approvalLoading = true;

    return fetch(`../includes/fetch_user_approval.php?page=${approvalPage}&limit=${approvalLimit}`)
        .then(res => res.text())
        .then(data => {

            approvalLoading = false;

            if (data.trim() === '') {
                approvalDone = true;
                return false; // 🔥 No data
            }

            document.getElementById('approval')
                .insertAdjacentHTML('beforeend', data);

            approvalPage++;
            return true; // 🔥 Data exists
        })
        .catch(() => {
            approvalLoading = false;
            return false;
        });
}


/* Infinite Scroll */
const approvalContainer =
    document.querySelector('#approveusers .table-responsive');

approvalContainer.addEventListener('scroll', function () {

    if (!$("#approveusers").is(":visible")) return;
    if (approvalLoading || approvalDone) return;

    if (this.scrollTop + this.clientHeight >= this.scrollHeight - 25) {
        fetchuserApproval();
    }
});

/* Approve User */
function admin_approve_User(id) {
    if (!confirm("Approve this new user?")) return;

    fetch('../includes/admin_approve_user.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'user_id=' + id
    }).then(() => {

        const tr = document.getElementById("userRow_" + id);
        if (tr) tr.remove();

        if (document.querySelectorAll('#approval tr').length === 0) {
            $("#approveusers").fadeOut();
        }
    });
}


/* ============================================================
   5️⃣UNIVERSAL LIVE SEARCH MODULE
============================================================ */

document.addEventListener("DOMContentLoaded", function () {

    function debounce(func, delay = 300) {
        let timeout;
        return (...args) => {
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(this, args), delay);
        };
    }
    
    // ✅ ADD IT HERE
    function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }

    document.addEventListener("input", debounce(function (e) {

        if (!e.target.classList.contains("liveSearchInput")) return;

        const input = e.target;
        const wrapper = input.closest(".live-search-wrapper");
        const resultsBox = wrapper.querySelector(".liveResults");
        const hiddenInput = wrapper.querySelector(".liveHiddenInput");

        const endpoint = wrapper.dataset.endpoint;
        const displayFields = wrapper.dataset.displayFields.split(",");
        const valueField = wrapper.dataset.valueField;

        const query = input.value.trim();

        hiddenInput.value = "";

        if (query.length < 1) {
            resultsBox.style.display = "none";
            return;
        }

        fetch(`${endpoint}?search=${encodeURIComponent(query)}`)
            .then(res => res.json())
            .then(data => {

                resultsBox.innerHTML = "";

                if (!data.length) {
                    resultsBox.style.display = "none";
                    return;
                }

                data.forEach(item => {

                    let displayText = displayFields
                        .map(field => item[field])
                        .join(" ");
                    
                    const div = document.createElement("div");
                    
                    const safeQuery = escapeRegExp(query);
const regex = new RegExp(`(${safeQuery})`, "gi");
                    const highlighted = displayText.replace(regex, `<mark>$1</mark>`);
                    
                    div.innerHTML = highlighted;
                    div.dataset.value = item[valueField];

                    div.addEventListener("click", function () {
                        input.value = displayText;
                        hiddenInput.value = this.dataset.value;
                        resultsBox.style.display = "none";
                    });

                    resultsBox.appendChild(div);
                });

                resultsBox.style.display = "block";

                // Activate first result
                if (resultsBox.firstChild) {
                    resultsBox.firstChild.classList.add("active");
                }

            });

    }, 300));


    document.addEventListener("keydown", function (e) {

        if (!e.target.classList.contains("liveSearchInput")) return;

        const input = e.target;
        const wrapper = input.closest(".live-search-wrapper");
        const resultsBox = wrapper.querySelector(".liveResults");
        const hiddenInput = wrapper.querySelector(".liveHiddenInput");

        const items = resultsBox.querySelectorAll("div");
        if (!items.length) return;

        let active = resultsBox.querySelector(".active");
        let index = Array.from(items).indexOf(active);

        if (e.key === "ArrowDown") {
            e.preventDefault();
            if (index < items.length - 1) {
                if (active) active.classList.remove("active");
                items[index + 1].classList.add("active");
            }
        }

        if (e.key === "ArrowUp") {
            e.preventDefault();
            if (index > 0) {
                if (active) active.classList.remove("active");
                items[index - 1].classList.add("active");
            }
        }

        if (e.key === "Enter") {
            e.preventDefault();
            if (active) {
                input.value = active.textContent;
                hiddenInput.value = active.dataset.value;
                resultsBox.style.display = "none";
            }
        }

    });


    document.addEventListener("click", function (e) {
        document.querySelectorAll(".liveResults").forEach(box => {
            if (!box.closest(".live-search-wrapper").contains(e.target)) {
                box.style.display = "none";
            }
        });
    });

});

function fetchStore(sel_co) {

    return $.ajax({
        url: "fetch_scripts/get_def_store_id.php",
        type: "GET",
        data: { sel_co: sel_co },
        dataType: "json"
    }).done(function (response) {

        storeid = response.store_location;
        $("#defacc").val(storeid);

    });

}

$(document).ready(function () {

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

    if (sel_co) {
        fetchStore(sel_co);
    }

});

$('#sel_co').on('change', function () {

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

    $.ajax({
        url: "../includes/update_session_company.php",
        type: "POST",
        data: { co_id: sel_co }

    }).done(function () {

        fetchStore(sel_co).done(function () {

            // Reload only the current page
            routes[currentRoute]?.onEnter();

        });

    });

});

  

 </script>



</body>


