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

require_once "../includes/header.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, 3, 4,5, 6,7) AND u.status = 'active' AND p.pm_acc_categ='sales_person' AND p.user_id=:uid");

$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> 
        <!-- Deposit Action Sheet -->
        <div class="modal fade action-sheet" id="depositActionSheet" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Add Balance</h5>
                    </div>
                    <div class="modal-body">
                        <div class="action-sheet-content">
                            <form>
                                <div class="form-group basic">
                                    <div class="input-wrapper">
                                        <label class="label" for="account1">From</label>
                                        <select class="form-control custom-select" id="account1">
                                            <option value="0">Savings (*** 5019)</option>
                                            <option value="1">Investment (*** 6212)</option>
                                            <option value="2">Mortgage (*** 5021)</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group basic">
                                    <label class="label">Enter Amount</label>
                                    <div class="input-group mb-3">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text" id="input1">$</span>
                                        </div>
                                        <input type="text" class="form-control form-control-lg" value="100">
                                    </div>
                                </div>

                                

                                <div class="form-group basic">
                                    <button type="button" class="btn btn-primary btn-block btn-lg"
                                        data-dismiss="modal">Deposit</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- * Deposit Action Sheet -->

        <!-- Send Action Sheet -->
        <div class="modal fade action-sheet" id="sendActionSheet" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Send Money</h5>
                    </div>
                    <div class="modal-body">
                        <div class="action-sheet-content">
                            <form>
                                <div class="form-group basic">
                                    <div class="input-wrapper">
                                        <label class="label" for="account2">From</label>
                                        <select class="form-control custom-select" id="account2">
                                            <option value="0">Savings (*** 5019)</option>
                                            <option value="1">Investment (*** 6212)</option>
                                            <option value="2">Mortgage (*** 5021)</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group basic">
                                    <div class="input-wrapper">
                                        <label class="label" for="text11">To</label>
                                        <input type="email" class="form-control" id="text11" placeholder="Enter bank ID">
                                        <i class="clear-input"><ion-icon name="close-circle"></ion-icon></i>
                                    </div>
                                </div>

                                <div class="form-group basic">
                                    <label class="label">Enter Amount</label>
                                    <div class="input-group mb-3">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text" id="input14">$</span>
                                        </div>
                                        <input type="text" class="form-control form-control-lg" placeholder="0">
                                    </div>
                                </div>

                                

                                <div class="form-group basic">
                                    <button type="button" class="btn btn-primary btn-block btn-lg"
                                        data-dismiss="modal">Deposit</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- * Send Action Sheet -->
     
         <!--  Component Section -->   
         <div id="componentsSection" 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>

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

        <div class="section-title">
            <h6>Warehouse Details</h6>
        </div>

        <div class="card p-3">

            <form id="warehouseForm">

                <div id="warehouseRows">

                    <!-- First Row -->
                    <div class="warehouse-row row mb-2">
                        <div class="form-group basic  col-md-3">
                            <div class="input-wrapper">
                            <label class="label" for="name2">WarehouseName</label>
                            <input type="text" name="warehouse_name[]" class="form-control" required>
                            </div>
                        </div>
                        <div class="form-group  basic col-md-3">
                            <div class="input-wrapper">
                            <label class="label" for="name2">Location</label>
                            <input type="text" name="location[]" class="form-control"  required>
                            </div>
                        </div>
                        <div class="form-group  basic col-md-2">
                            <div class="input-wrapper">
                            <label class="label" for="name2">Capacity</label>
                            <input type="number" name="capacity[]" class="form-control"  required>
                            </div>
                        </div>
                       <div class="form-group basic  col-md-3">
                            <div class="live-search-wrapper"
                                     data-endpoint="fetch_scripts/get_store_managers.php"
                                     data-hidden-name="manager_id[]"
                                     data-display-fields="firstname,secondname"
                                     data-value-field="id">
                                
                                    <label class="label">Manager</label>
                                
                                    <!-- ❌ REMOVE name from text input -->
                                    <input type="text"
                                           class="form-control liveSearchInput"
                                           placeholder="Search..."
                                           autocomplete="off">
                                
                                    <!-- ✅ ADD name here instead -->
                                    <input type="hidden"
                                           class="liveHiddenInput"
                                           name="manager_id[]">
                                
                                    <div class="liveResults"></div>
                                </div>
                        </div>
                        <div class="form-group basic col-md-2 d-flex align-items-center">
                            <button type="button" class="btn btn-danger btn-sm removeRow" style="display:none;">Remove</button>
                        </div>
                    </div>

                </div>

                <div class="form-group basic mt-2">
                    <div class="right" style="position: fixed; right: 20px; center: 20px; z-index: 9999;">
                    <div id="liveToastContainer"></div>
                </div>
                    <button type="button" id="addRow" class="btn btn-success btn-sm">
                        + Add Row
                    </button>
                </div>

                <div class="mt-3">
                    <button type="submit" class="btn btn-primary btn-block">
                        Add Warehouses
                    </button>
                </div>

            </form>

        </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';
  
  
  ?>
  
   <!--  * 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 class="section-title">
            <h6>Recent Transactions</h6>
            
        </div>
            <div  class="transactions">
                <!-- item -->
                <a href="app-transaction-detail.html" class="item">
                    <div class="detail">
                        <img src="assets/img/sample/brand/1.jpg" alt="img" class="image-block imaged w48">
                        <div>
                            <strong>Amazon</strong>
                            <p>Shopping</p>
                        </div>
                    </div>
                    <div class="right">
                        <div class="price text-danger"> - $ 150</div>
                    </div>
                </a>
                <!-- * item -->
                <!-- item -->
                <a href="app-transaction-detail.html" class="item">
                    <div class="detail">
                        <img src="assets/img/sample/brand/2.jpg" alt="img" class="image-block imaged w48">
                        <div>
                            <strong>Apple</strong>
                            <p>Appstore Purchase</p>
                        </div>
                    </div>
                    <div class="right">
                        <div class="price text-danger">- $ 29</div>
                    </div>
                </a>
                <!-- * item -->
                <!-- item -->
                <a href="app-transaction-detail.html" class="item">
                    <div class="detail">
                        <img src="assets/img/sample/avatar/avatar3.jpg" alt="img" class="image-block imaged w48">
                        <div>
                            <strong>Alex Ljung</strong>
                            <p>Transfer</p>
                        </div>
                    </div>
                    <div class="right">
                        <div class="price">+ $ 1,000</div>
                    </div>
                </a>
                <!-- * item -->
                <!-- item -->
                <a href="app-transaction-detail.html" class="item">
                    <div class="detail">
                        <img src="assets/img/sample/avatar/avatar4.jpg" alt="img" class="image-block imaged w48">
                        <div>
                            <strong>Beatriz Brito</strong>
                            <p>Transfer</p>
                        </div>
                    </div>
                    <div class="right">
                        <div class="price text-danger">- $ 186</div>
                    </div>
                </a>
                <!-- * item -->
            </div>
        </div>
        <!-- * Transactions -->
        
       <div id="pg" class="admin-section" 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;">

        <!-- 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>
     
        <!-- * my cards -->

        <!-- Send Money -->
   
    
        <!-- * Send Money -->

        <!-- Monthly Bills -->
        
        <!-- * Monthly Bills -->


        <!-- Saving Goals -->
    
        <!-- * Saving Goals -->


        <!-- News -->

        <!-- * News -->

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

 //  <!-- * 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';
 
 ?>
 
<script>

let storeid = null;

let inv_limit = 10;
let inv_offset = 0;

let inv_loading = false;
let inv_finished = false;

let Pinv_limit = 10;
let Pinv_offset = 0;

let Pinv_loading = false;
let Pinv_finished = false;

let Pcsh_limit = 10;
let Pcsh_offset = 0;

let Pcsh_loading = false;
let Pcsh_finished = false;

let csh_limit = 10;
let csh_offset = 0;

let csh_loading = false;
let csh_finished = false;

let ov_limit = 10;
let ov_offset = 0;

let ov_loading = false;
let ov_finished = false;

let ovT_limit = 10;
let ovT_offset = 0;

let ovT_loading = false;
let ovT_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").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: "#approveusers, #wallet, #overviewSection",
        pages: "#pg",
        components: "#componentsSection",
        customers: "#customerSection",
        supplier: "#supplierSection",
        permissions: "#permissionsSection",
        accountsledger: "#ledger_accountsSection",
        product_list_b: "#pdtlistbSection",
        inventory: "#inventorySection",
        accounts: "#cashierSection"
    };

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


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

const routes = {

    overview: {
            onEnter() {
                const section = $("#approveusers");
        
                resetApprovalState();
                //resetWarehouseForm();
        
                showSkeleton(section);
        
                Promise.all([
                    fetchuserApproval(true),
                    delay(400)
                ]).then(([hasData]) => {
        
                    if (!hasData) {
                        section.hide(); // 🔥 Never show it
                        return;
                    }
        
                    section.show();
                    setTimeout(() => section.addClass("active-section"), 10);
        
                    hideSkeleton(section);
                });
            },
        
            onLeave() {
                resetApprovalState();
            }
        },

    pages: {
        onEnter() {
            const section = getSectionElement("pages");

            showSkeleton(section);
           // resetWarehouseForm();

            Promise.all([
                delay(500),
                new Promise(resolve => {
                    fetchuserSessions();
                    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() {
            const section = getSectionElement("inventory");
           // resetWarehouseForm();
           // loadManagers();
            showSkeleton(section);
    
            Promise.all([
                delay(400)
            ]).then(() => {
                hideSkeleton(section);
            });
        },
        onLeave() {}
    },
    
    permissions: {
        onEnter() {
            const section = getSectionElement("permissions");
           // resetWarehouseForm();
           // loadManagers();
            showSkeleton(section);
    
            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();
            showSkeleton(section);
          
    
            Promise.all([
                delay(400)
            ]).then(() => {
                hideSkeleton(section);
            });
        },
        onLeave() {}
    },
    
    supplier: {
        onEnter() {
            const section = getSectionElement("supplier");
           // resetWarehouseForm();
           // loadManagers();
            showSkeleton(section);
    
            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);
    
            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();

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


/* ============================================================
   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 * 1000; // 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);


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

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

const approvalLimit = 8;

function resetApprovalState() {
    approvalPage = 0;
    approvalDone = false;
    approvalLoading = false;
    document.getElementById('approval').innerHTML = '';
}

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) {

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

        success: function (response) {

            if (response.store_location) {

                storeid = response.store_location;

                $("#defacc").val(storeid);

                console.log("Store changed →", storeid);

                // ✅ Reset + reload
                loadPendinv(true);
                loadinv(true);
                loadPendcsh(true);
                loadTodaycsh(true);
                currentstocks();
                loadOverviewPend(true);
                loadOverviewToday(true);
            }
        },

        error: function () {
            console.error("Failed to fetch store");
        }
    });
}

$(document).ready(function () {

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

    if (sel_co) {
        fetchStore(sel_co); // initial load
    }

    $('#sel_co').on('change', function () {
        let sel_co = $(this).val();
        fetchStore(sel_co);
       
    });
});



  

 </script>



</body>


