<?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">
            <img src="assets/img/logo.png" alt="logo" class="logo">
        </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">
                <!-- Balance -->
                <div class="balance">
                    <div class="left">
                        <span class="title">Total Balance</span>
                        <h4 class="title">$ 2,562.50</h4>
                    </div>
                    <div class="right">
                        <a href="#" class="button" data-toggle="modal" data-target="#depositActionSheet">
                            <ion-icon name="add-outline"></ion-icon>
                        </a>
                    </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 class="item">
                        <a href="#" data-toggle="modal" data-target="#sendActionSheet">
                           
                            <strong>Exchange</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="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';
 ?>
 
<script>

/* ============================================================
   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"
    };

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

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

const routes = {

    overview: {
            onEnter() {
                const section = $("#approveusers");
        
                resetApprovalState();
        
                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);

            Promise.all([
                delay(500),
                new Promise(resolve => {
                    fetchuserSessions();
                    resolve();
                })
            ]).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-my-admin-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-my-admin-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();
        }
    });
}


 </script>



</body>


