<?php
// Initialize the session
require '../includes/session-check.php';

require_once "../includes/header.php";

?>



<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 class="right">
            <a href="app-notifications.html" class="headerButton">
                <ion-icon class="icon" name="notifications-outline"></ion-icon>
                <span class="badge badge-danger">4</span>
            </a>
            <a href="app-settings.html" class="headerButton">
                <img src="assets/img/sample/avatar/avatar1.jpg" alt="image" class="imaged w32">
                <span class="badge badge-danger">6</span>
            </a>
        </div>
    </div>
    <!-- * App Header -->


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

        <!-- Wallet Card -->
        <div id="wallet" class="section admin-section wallet-card-section  pt-1">
             <!-- Skeleton -->
    <div class="skeleton-wrapper">
        <div class="skeleton-box"></div>
        <div class="skeleton-box"></div>
        <div class="skeleton-box"></div>
    </div>
            <div class="wallet-card col-8">
                <!-- Balance -->
                <div class="balance">
                    <div class="left">
                        <span class="title">Synamics</span>
                        <h5 class="title text-secondary">Cash On Hand </h5>
                        <h5 class="title text-secondary">Expenses</h5>
                        <h5 class="title text-secondary">Banked</h5>
                    </div>
                    <div class="right">
                        <span class="title text-secondary">______</span>
                        <h4 class="title"> $ 2,562.50</h5>
                        <h4 class="title">$ 5,562.50</h4>
                        <h4 class="title">$ 6,562.50</h4>
                    </div>
                </div>
                <!-- * Balance -->
                <!-- Wallet Footer -->
                <div class="wallet-footer">
                    <div class="item">
                        <a href="#" data-toggle="modal" data-target="#depositActionSheet">
                           
                            <strong>Withdraw</strong>
                        </a>
                    </div>
                    <div class="item">
                        <a href="#" data-toggle="modal" data-target="#sendActionSheet">
                            
                            <strong>Send</strong>
                        </a>
                    </div>
                    <div class="item">
                        <a href="app-cards.html">
                           
                            <strong>Cards</strong>
                        </a>
                    </div>
                    

                </div>
                <!-- * Wallet Footer -->
            </div>
        </div>
        <!-- Wallet Card -->

        <!-- 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 -->
        
         <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-2">
                               <div class="manager-search-wrapper">
                               <label class="label">Manager</label>
                                <input type="text" class="form-control managerSearchInput"  autocomplete="off" required>
                                <input type="hidden" name="manager_id[]" class="managerHiddenInput">
                                <div class="managerResults"></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>

        
 
    <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

 //  <!-- * 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 'page_views/warehous.php';
 ?>
 
<script>

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

    const container = document.getElementById("liveToastContainer");

    const toast = document.createElement("div");
    toast.className = "toast";
    toast.setAttribute("role", "alert");
    toast.setAttribute("aria-live", "assertive");
    toast.setAttribute("aria-atomic", "true");

    toast.innerHTML = `
        <div class="toast-header">
            <strong class="mr-auto text-${type === 'success' ? 'success' : 'danger'}">
                ${type === 'success' ? 'Success' : 'Error'}
            </strong>
            <button type="button" class="ml-2 mb-1 close" onclick="this.closest('.toast').remove()">
                &times;
            </button>
        </div>
        <div class="toast-body">
            ${message}
        </div>
    `;

    container.appendChild(toast);

    // Show animation
    toast.classList.add("show");

    // Auto remove
    setTimeout(() => {
        toast.classList.remove("show");
        setTimeout(() => toast.remove(), 300);
    }, duration);
}


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

/* ============================================================
   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",
        pages: "#pg",
        components: "#componentsSection"
    };

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

};

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 */
    $(".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 = 15 * 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();
        }
    });
}



/* ============================================================
   MANAGER LIVE SEARCH MODULE (FULL STABLE VERSION)
============================================================ */

/* Debounce Utility */
function debounce(fn, delay = 300) {
    let timeout;
    return function (...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => fn.apply(this, args), delay);
    };
}

/* Select Manager */
function selectManager(wrapper, item) {

    const input = wrapper.querySelector(".managerSearchInput");
    const hiddenInput = wrapper.querySelector(".managerHiddenInput");
    const resultsBox = wrapper.querySelector(".managerResults");

    input.value = item.textContent;
    hiddenInput.value = item.dataset.id;

    resultsBox.innerHTML = "";
    resultsBox.style.display = "none";
}

/* Scroll Active Item Into View */
function scrollIntoViewIfNeeded(element, container) {

    const elTop = element.offsetTop;
    const elBottom = elTop + element.offsetHeight;

    const containerTop = container.scrollTop;
    const containerBottom = containerTop + container.offsetHeight;

    if (elBottom > containerBottom) {
        container.scrollTop = elBottom - container.offsetHeight;
    } else if (elTop < containerTop) {
        container.scrollTop = elTop;
    }
}

/* =========================
   LIVE SEARCH (DEBOUNCED)
========================= */
document.addEventListener("input", debounce(function (e) {

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

    const input = e.target;
    const wrapper = input.closest(".manager-search-wrapper");
    const resultsBox = wrapper.querySelector(".managerResults");
    const hiddenInput = wrapper.querySelector(".managerHiddenInput");

    const searchValue = input.value.trim().toLowerCase();

    resultsBox.innerHTML = "";
    hiddenInput.value = "";

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

    const filtered = managersCache.filter(user =>
        (user.firstname + " " + user.secondname)
            .toLowerCase()
            .includes(searchValue)
    );

    filtered.forEach((user, index) => {

        const div = document.createElement("div");
        div.textContent = user.firstname + " " + user.secondname;
        div.dataset.id = user.id;

        if (index === 0) {
            div.classList.add("active"); // Important for keyboard start
        }

        div.addEventListener("click", function () {
            selectManager(wrapper, div);
        });

        resultsBox.appendChild(div);
    });

    resultsBox.style.display = filtered.length ? "block" : "none";

}, 300));

/* =========================
   KEYBOARD NAVIGATION
========================= */
document.addEventListener("keydown", function (e) {

    const input = document.activeElement;

    if (!input || !input.classList.contains("managerSearchInput")) return;

    const wrapper = input.closest(".manager-search-wrapper");
    const resultsBox = wrapper.querySelector(".managerResults");
    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");

            const next = items[index + 1];
            next.classList.add("active");
            scrollIntoViewIfNeeded(next, resultsBox);
        }
    }

    if (e.key === "ArrowUp") {
        e.preventDefault();

        if (index > 0) {
            if (active) active.classList.remove("active");

            const prev = items[index - 1];
            prev.classList.add("active");
            scrollIntoViewIfNeeded(prev, resultsBox);
        }
    }

    if (e.key === "Enter") {
        e.preventDefault();

        active = resultsBox.querySelector(".active");
        if (active) {
            selectManager(wrapper, active);
        }
    }
});

/* =========================
   CLOSE DROPDOWN OUTSIDE CLICK
========================= */
document.addEventListener("click", function (e) {

    if (!e.target.closest(".manager-search-wrapper")) {

        document.querySelectorAll(".managerResults").forEach(box => {
            box.style.display = "none";
        });
    }
});


 </script>



</body>


