<?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 class="section wallet-card-section pt-1">
            <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 ">
        <!-- 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>
        <!-- * Stats -->

        <!-- my cards <div id="usersonline" style="display:none;" class="admin-section section mt-1"> -->
         <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" scope="col">User</th>
                                <th  class="text-light bg-secondary" scope="col">IP</th>
                                <th  class="text-light bg-secondary" scope="col">Device</th>
                                <th  class="text-light bg-secondary" scope="col">Login Time</th>
                                <th  class="text-light bg-secondary" scope="col">Logout Time</th>
                                <th  class="text-light bg-secondary" scope="col">Status</th>
                                <th  class="text-light bg-secondary" scope="col" class="text-end">Action</th>
                            </tr>
                        </thead>
                       <tbody id="sessions">
                          
                        </tbody>
                        
                    </table>
                    <div id="loginLoader" class="text-center mt-3" style="display:none;">
                                <div class="spinner-border text-primary" role="status"></div>
                           </div>
                </div>

            </div>
            
        </div>
        </div>
            
    <div id="approveusers"  class="admin-section section mt-1">
         <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" scope="col">Username</th>
                                <th  class="text-light bg-secondary" scope="col">Firstname</th>
                                <th  class="text-light bg-secondary" scope="col">Secondname</th>
                                <th  class="text-light bg-secondary" scope="col">Email</th>
                                <th  class="text-light bg-secondary" scope="col" class="text-end">Action</th>
                            </tr>
                        </thead>
                       <tbody id="approval">
                          
                        </tbody>
                        
                    </table>
                    <div id="loginLoader2" class="text-center mt-3" style="display:none;">
                                <div class="spinner-border text-primary" role="status"></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>
 
 //----------------------------------------------------------------------------//
/* ROUTING NAVIGATION CONTROLLER */                                            //
//----------------------------------------------------------------------------//

const routes = {

    overview: {
        onEnter: function () {
            resetApprovalState();
            fetchuserApproval(true);
        },
        onLeave: function () {
            resetApprovalState();
        }
    },

    pages: {
        onEnter: function () {},
        onLeave: function () {}
    }
};


function getSectionElement(route) {

    switch(route) {

        case "overview":
            return $("#approveusers");

        case "pages":
            return $("#pg"); // main container

        default:
            return null;
    }
}


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);
    const nextSection = getSectionElement(nextRoute);

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

    // Fade out current
    if (currentSection.length) {
        currentSection.removeClass("active-section");
    }

    setTimeout(() => {

        $(".admin-section").hide();

        if (nextSection) {
            nextSection.show();

            // Small delay so CSS transition triggers properly
            setTimeout(() => {
                nextSection.addClass("active-section");
            }, 10);
        }

        if (routes[nextRoute]?.onEnter) {
            routes[nextRoute].onEnter();
        }

        currentRoute = nextRoute;
        transitionLock = false;

    }, 200);

    // Update nav
    $(".appBottomMenu .item").removeClass("active");
    $("#" + nextRoute).addClass("active");
}



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





 //----------------------------------------------------------------------------//
/* END NAVIGATION CONTROLLER */                                               //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
/* Session check -Activity events */                                          //
//----------------------------------------------------------------------------//
function mysessioncheck() {
    fetch('../includes/my-session-check.php')
        .then(res => res.json())
        .then(data => {
            if (data.status === "expired") {
                
                // ðŸ”¥ Tell other tabs to logout
            localStorage.setItem("logout-event", Date.now());
            
                window.location.href = "app-my-admin-login.php";
            }
        })
        .catch(err => console.error("Session check error:", err));
}

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

            // ðŸ”¥ Tell other tabs to logout
            localStorage.setItem("logout-event", Date.now());

            window.location.href = 'app-my-admin-login.php';
        });
}


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

resetTimer(); // start timer on load

// Listen for logout signal from other tabs
window.addEventListener("storage", function(event) {
    if (event.key === "logout-event") {
        window.location.href = "app-my-admin-login.php";
    }
});
//----------------------------------------------------------------------------//
/* End Session check -Activity events */                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
/* Admin User sessions list */                                            //
//----------------------------------------------------------------------------//

function fetchuserSessions() {
    //document.getElementById("loginLoader").style.display = "block";
    fetch('../includes/fetch_sessions.php')
        .then(res => res.text())
        .then(data => {
          //  document.getElementById("loginLoader").style.display = "none";
            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();
         
    });
}

setInterval(fetchuserSessions, 20000);

fetchuserSessions();

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

//----------------------------------------------------------------------------//
/* End Admin User sessions list */                                            //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
/* Admin User approval list */                                                //
//----------------------------------------------------------------------------//
function resetApprovalState() {
    approvalPage = 0;
    approvalDone = false;
    approvalLoading = false;
    document.getElementById('approval').innerHTML = '';
}

const approvalLimit = 15;

function fetchuserApproval(reset = false) {

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

    approvalLoading = true;
    document.getElementById("loginLoader2").style.display = "block";

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

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

            approvalLoading = false;
            document.getElementById("loginLoader2").style.display = "none";

            if (data.trim() === '') {
                approvalDone = true;

                if (approvalPage === 0) {
                    $("#approveusers").hide();
                }
                return;
            }

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

            approvalPage++;
        })
        .catch(() => {
            approvalLoading = false;
            document.getElementById("loginLoader2").style.display = "none";
        });
}


/* infinite scroll trigger */
const approvalContainer =
    document.querySelector('#approveusers .table-responsive');

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

    // Only load if section is visible
    if (!$("#approveusers").is(":visible")) return;

    if (approvalLoading || approvalDone) return;

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



/* initial load */
//fetchuserApproval(true);


//const POLL_INTERVAL = 5000; // 5 seconds




/* start polling */
//setInterval(refreshApprovalStatuses, POLL_INTERVAL);


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 no rows left → hide table
        if (document.querySelectorAll('#approval tr').length === 0) {
            $("#approveusers").fadeOut();
            //document.getElementById('approveusers').style.display = 'none';
        }
    });
}




//----------------------------------------------------------------------------//
/* End Admin User approval list */                                            //
//----------------------------------------------------------------------------//




 </script>



</body>


