{"id":197,"date":"2026-05-22T09:21:47","date_gmt":"2026-05-22T09:21:47","guid":{"rendered":"https:\/\/cashchat.se\/dir\/?page_id=197"},"modified":"2026-05-22T12:07:19","modified_gmt":"2026-05-22T12:07:19","slug":"backend","status":"publish","type":"page","link":"https:\/\/cashchat.se\/dir\/backend\/","title":{"rendered":"Backend"},"content":{"rendered":"\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n  <title>Adase Ads \u2013 Complete Dashboard (Offline \/ LocalStorage)<\/title>\n  <script src=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/html2canvas\/1.4.1\/html2canvas.min.js\"><\/script>\n  <script src=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/jspdf\/2.5.1\/jspdf.umd.min.js\"><\/script>\n  <style>\n    * { margin: 0; padding: 0; box-sizing: border-box; }\n    :root {\n      --primary: #0a1f44;\n      --gold: #c49a2b;\n      --bg: #f4f6f9;\n      --card-bg: #ffffff;\n      --text: #1e293b;\n      --shadow: 0 10px 25px -5px rgba(0,0,0,0.05), 0 8px 10px -6px rgba(0,0,0,0.02);\n      --radius: 16px;\n    }\n    body {\n      font-family: 'Inter', system-ui, -apple-system, sans-serif;\n      background: var(--bg);\n      color: var(--text);\n      display: flex;\n      min-height: 100vh;\n    }\n    .sidebar {\n      width: 260px;\n      background: var(--primary);\n      color: #fff;\n      padding: 24px 16px;\n      position: fixed;\n      top: 0; left: 0; bottom: 0;\n      z-index: 100;\n      transition: transform 0.3s ease;\n      display: flex;\n      flex-direction: column;\n    }\n    .sidebar .logo {\n      font-family: 'Playfair Display', serif;\n      font-size: 24px;\n      font-weight: 700;\n      text-align: center;\n      letter-spacing: 2px;\n      margin-bottom: 32px;\n    }\n    .sidebar .logo span { color: var(--gold); }\n    .sidebar nav a {\n      display: flex;\n      align-items: center;\n      gap: 10px;\n      color: rgba(255,255,255,0.8);\n      text-decoration: none;\n      padding: 12px 16px;\n      border-radius: 10px;\n      margin-bottom: 6px;\n      font-weight: 500;\n      transition: background 0.2s, color 0.2s;\n    }\n    .sidebar nav a:hover,\n    .sidebar nav a.active { background: rgba(255,255,255,0.08); color: var(--gold); }\n    .main {\n      margin-left: 260px;\n      flex: 1;\n      padding: 28px 32px;\n      transition: margin-left 0.3s;\n    }\n    .mobile-header {\n      display: none;\n      align-items: center;\n      gap: 16px;\n      background: var(--primary);\n      color: #fff;\n      padding: 14px 20px;\n      position: sticky;\n      top: 0; z-index: 99;\n    }\n    .mobile-header .menu-toggle {\n      background: none; border: none; color: #fff; font-size: 24px; cursor: pointer;\n    }\n    .section {\n      background: var(--card-bg);\n      border-radius: var(--radius);\n      padding: 24px;\n      margin-bottom: 24px;\n      box-shadow: var(--shadow);\n      display: none;\n    }\n    .section.active { display: block; }\n    h2 {\n      font-family: 'Playfair Display', serif;\n      color: var(--primary);\n      font-size: 22px;\n      margin-bottom: 20px;\n      border-bottom: 2px solid var(--gold);\n      padding-bottom: 10px;\n      display: inline-block;\n    }\n    h3 { color: var(--primary); margin: 16px 0 10px; }\n    .wallet-balance { font-size: 32px; font-weight: 700; color: var(--gold); }\n    .btn {\n      display: inline-flex;\n      align-items: center;\n      gap: 6px;\n      background: var(--primary);\n      color: #fff;\n      border: none;\n      padding: 10px 20px;\n      border-radius: 30px;\n      font-weight: 600;\n      cursor: pointer;\n      transition: all 0.2s;\n      font-size: 14px;\n    }\n    .btn-gold { background: var(--gold); color: var(--primary); }\n    .btn-outline {\n      background: transparent;\n      border: 1.5px solid var(--primary);\n      color: var(--primary);\n    }\n    .btn:hover { opacity: 0.9; transform: translateY(-1px); }\n    .btn-danger { background: #dc3545; }\n    .form-group { margin-bottom: 16px; }\n    .form-group label {\n      display: block;\n      font-weight: 600;\n      margin-bottom: 6px;\n      color: var(--primary);\n    }\n    .form-control {\n      width: 100%;\n      padding: 10px 14px;\n      border: 1.5px solid #e2e8f0;\n      border-radius: 10px;\n      font-size: 15px;\n      transition: border 0.2s;\n    }\n    .form-control:focus { border-color: var(--gold); outline: none; }\n    .row { display: flex; gap: 20px; flex-wrap: wrap; }\n    .col { flex: 1; min-width: 200px; }\n    table {\n      width: 100%;\n      border-collapse: collapse;\n      margin-top: 12px;\n    }\n    th, td {\n      padding: 12px 14px;\n      border-bottom: 1px solid #e2e8f0;\n      text-align: left;\n      font-size: 14px;\n    }\n    th { background: #f8fafc; color: var(--primary); font-weight: 600; }\n    .badge {\n      display: inline-block;\n      padding: 2px 10px;\n      border-radius: 12px;\n      font-size: 12px;\n      font-weight: 600;\n    }\n    .badge-success { background: #d4edda; color: #155724; }\n    .badge-warning { background: #fff3cd; color: #856404; }\n    .badge-danger { background: #f8d7da; color: #721c24; }\n    .notification {\n      background: #fff3cd;\n      border-left: 4px solid #ffc107;\n      padding: 12px;\n      border-radius: 8px;\n      margin-bottom: 12px;\n      display: flex;\n      justify-content: space-between;\n      align-items: center;\n    }\n    .auth-container {\n      max-width: 500px;\n      margin: 40px auto;\n      background: var(--card-bg);\n      border-radius: var(--radius);\n      padding: 32px;\n      box-shadow: var(--shadow);\n    }\n    .terms-box {\n      display: flex;\n      align-items: center;\n      gap: 8px;\n      margin: 16px 0;\n      font-size: 14px;\n    }\n    .terms-box input[type=\"checkbox\"] { width: 18px; height: 18px; cursor: pointer; }\n    @media (max-width: 768px) {\n      .sidebar { transform: translateX(-100%); }\n      .sidebar.open { transform: translateX(0); }\n      .main { margin-left: 0; }\n      .mobile-header { display: flex; }\n      .row { flex-direction: column; }\n    }\n  <\/style>\n<\/head>\n<body>\n  <!-- Sidebar -->\n  <aside class=\"sidebar\" id=\"sidebar\">\n    <div class=\"logo\">ADASE <span>ADS<\/span><\/div>\n    <nav>\n      <a href=\"#dashboard\" class=\"active\" data-section=\"dashboard\">\ud83d\udcca Dashboard<\/a>\n      <a href=\"#wallet\" data-section=\"wallet\">\ud83d\udcb0 Wallet<\/a>\n      <a href=\"#invest\" data-section=\"invest\">\ud83d\udcdc Buy Notes<\/a>\n      <a href=\"#history-invest\" data-section=\"history-invest\">\ud83c\udfe6 Investments<\/a>\n      <a href=\"#history-tx\" data-section=\"history-tx\">\ud83e\uddfe Transactions<\/a>\n      <a href=\"#\" id=\"logoutSidebar\">\ud83d\udeaa Logout<\/a>\n      <a href=\"#\" id=\"adminSidebarLink\" style=\"margin-top:20px; border-top:1px solid rgba(255,255,255,0.2); padding-top:15px;\">\ud83d\udd10 Admin<\/a>\n    <\/nav>\n  <\/aside>\n\n  <!-- Mobile header -->\n  <div class=\"mobile-header\">\n    <button class=\"menu-toggle\" id=\"menuToggle\">\u2630<\/button>\n    <span style=\"font-weight:600;\">Adase Dashboard<\/span>\n  <\/div>\n\n  <!-- Main content -->\n  <main class=\"main\" id=\"mainContent\">\n    <!-- ========== USER AUTH ========== -->\n    <div id=\"authSection\">\n      <div class=\"auth-container\">\n        <h2 style=\"text-align:center;\">Welcome<\/h2>\n        <div style=\"display:flex; gap:8px; justify-content:center; margin-bottom:20px;\">\n          <button class=\"btn\" onclick=\"showAuthTab('login')\">Login<\/button>\n          <button class=\"btn btn-outline\" onclick=\"showAuthTab('register')\">Register<\/button>\n        <\/div>\n        <!-- LOGIN -->\n        <div id=\"loginForm\">\n          <div class=\"form-group\"><label>Email<\/label><input type=\"email\" class=\"form-control\" id=\"loginEmail\" placeholder=\"you@example.com\"><\/div>\n          <div class=\"form-group\"><label>Password<\/label><input type=\"password\" class=\"form-control\" id=\"loginPassword\" placeholder=\"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\"><\/div>\n          <button class=\"btn btn-gold\" onclick=\"login()\" style=\"width:100%;\">Login<\/button>\n        <\/div>\n        <!-- REGISTER -->\n        <div id=\"registerForm\" style=\"display:none;\">\n          <div class=\"row\">\n            <div class=\"col\"><div class=\"form-group\"><label>First Name *<\/label><input type=\"text\" class=\"form-control\" id=\"regFirstName\" required><\/div><\/div>\n            <div class=\"col\"><div class=\"form-group\"><label>Last Name *<\/label><input type=\"text\" class=\"form-control\" id=\"regLastName\" required><\/div><\/div>\n          <\/div>\n          <div class=\"form-group\"><label>Email *<\/label><input type=\"email\" class=\"form-control\" id=\"regEmail\" required><\/div>\n          <div class=\"row\">\n            <div class=\"col\"><div class=\"form-group\"><label>Country *<\/label><input type=\"text\" class=\"form-control\" id=\"regCountry\" required><\/div><\/div>\n            <div class=\"col\"><div class=\"form-group\"><label>Mobile Number *<\/label><input type=\"text\" class=\"form-control\" id=\"regMobile\" required><\/div><\/div>\n          <\/div>\n          <div class=\"form-group\"><label>NIN \/ Passport Number *<\/label><input type=\"text\" class=\"form-control\" id=\"regNIN\" required><\/div>\n          <div class=\"row\">\n            <div class=\"col\"><div class=\"form-group\"><label>Password *<\/label><input type=\"password\" class=\"form-control\" id=\"regPassword\" required><\/div><\/div>\n            <div class=\"col\"><div class=\"form-group\"><label>Confirm Password *<\/label><input type=\"password\" class=\"form-control\" id=\"regConfirmPassword\" required><\/div><\/div>\n          <\/div>\n          <div class=\"terms-box\">\n            <input type=\"checkbox\" id=\"acceptTerms\" required>\n            <label for=\"acceptTerms\">I accept the <a href=\"\/terms\" target=\"_blank\" style=\"color:var(--gold);\">Terms and Conditions<\/a><\/label>\n          <\/div>\n          <button class=\"btn btn-gold\" onclick=\"register()\" style=\"width:100%;\">Register<\/button>\n        <\/div>\n      <\/div>\n    <\/div>\n\n    <!-- ========== USER DASHBOARD ========== -->\n    <div id=\"dashboardSections\" style=\"display:none;\">\n      <section class=\"section active\" id=\"section-dashboard\">\n        <h2>Dashboard<\/h2>\n        <div class=\"row\">\n          <div class=\"col\"><p style=\"color:#666;\">Wallet Balance<\/p><div class=\"wallet-balance\" id=\"balanceDisplay\">0 UGX<\/div><\/div>\n          <div class=\"col\" style=\"text-align:right;\"><span id=\"userNameDisplay\"><\/span><\/div>\n        <\/div>\n        <div style=\"margin-top:20px;\">\n          <button class=\"btn btn-gold\" onclick=\"switchSection('wallet')\">\ud83d\udcb5 Add Money<\/button>\n          <button class=\"btn\" onclick=\"switchSection('invest')\">\ud83d\udcdc Buy Notes<\/button>\n        <\/div>\n        <h3 style=\"margin-top:24px;\">\ud83d\udd14 Notifications<\/h3>\n        <div id=\"notificationsPreview\"><\/div>\n      <\/section>\n\n      <section class=\"section\" id=\"section-wallet\">\n        <h2>Wallet<\/h2>\n        <div class=\"row\">\n          <div class=\"col\"><h3>Add Money (Top\u2011up)<\/h3><div class=\"form-group\"><label>Amount (UGX)<\/label><input type=\"number\" class=\"form-control\" id=\"topupAmount\" placeholder=\"e.g., 500000\"><\/div><button class=\"btn btn-gold\" onclick=\"submitTopup()\">Request Top\u2011up<\/button><\/div>\n          <div class=\"col\"><h3>Withdraw<\/h3><div class=\"form-group\"><label>Amount (UGX)<\/label><input type=\"number\" class=\"form-control\" id=\"withdrawAmount\" placeholder=\"e.g., 200000\"><\/div><button class=\"btn btn-outline\" onclick=\"submitWithdraw()\">Request Withdrawal<\/button><\/div>\n        <\/div>\n        <div style=\"margin-top:30px;\">\n          <h3>Transfer to Another User<\/h3>\n          <div class=\"row\">\n            <div class=\"col\"><div class=\"form-group\"><label>Recipient Email<\/label><input type=\"email\" class=\"form-control\" id=\"transferEmail\" placeholder=\"user@example.com\"><\/div><\/div>\n            <div class=\"col\"><div class=\"form-group\"><label>Amount (UGX)<\/label><input type=\"number\" class=\"form-control\" id=\"transferAmount\" placeholder=\"e.g., 100000\"><\/div><\/div>\n          <\/div>\n          <button class=\"btn\" onclick=\"submitTransfer()\">Request Transfer<\/button>\n        <\/div>\n      <\/section>\n\n      <section class=\"section\" id=\"section-invest\">\n        <h2>Buy Convertible Notes<\/h2>\n        <p style=\"color:#666; margin-bottom:20px;\">Minimum 100,000 UGX. Amount deducted from wallet on purchase.<\/p>\n        <div class=\"row\">\n          <div class=\"col\"><div class=\"form-group\"><label>Investment Amount (UGX)<\/label><input type=\"number\" class=\"form-control\" id=\"investAmount\" min=\"100000\" placeholder=\"e.g., 1000000\"><\/div><\/div>\n          <div class=\"col\" style=\"display:flex; align-items:flex-end;\"><button class=\"btn btn-gold\" onclick=\"buyAndDownload()\" style=\"width:100%;\">Buy &amp; Download Certificate<\/button><\/div>\n        <\/div>\n        <p id=\"investMsg\" style=\"margin-top:12px;\"><\/p>\n      <\/section>\n\n      <section class=\"section\" id=\"section-history-invest\">\n        <h2>Investment History<\/h2>\n        <table><thead><tr><th>Certificate No<\/th><th>Principal<\/th><th>Date<\/th><th>Download<\/th><\/tr><\/thead><tbody id=\"investHistoryBody\"><tr><td colspan=\"4\">Loading&#8230;<\/td><\/tr><\/tbody>\n      <\/section>\n\n      <section class=\"section\" id=\"section-history-tx\">\n        <h2>Wallet Transactions<\/h2>\n        <table><thead><tr><th>Type<\/th><th>Amount<\/th><th>Status<\/th><th>Date<\/th><th>Note<\/th><\/tr><\/thead><tbody id=\"txHistoryBody\"><tr><td colspan=\"5\">Loading&#8230;<\/td><\/tr><\/tbody>\n      <\/section>\n    <\/div>\n\n    <!-- ========== ADMIN PANEL ========== -->\n    <div id=\"adminPanel\" style=\"display:none;\">\n      <div style=\"margin-bottom:20px; display:flex; gap:10px; flex-wrap:wrap; align-items:center;\">\n        <button class=\"btn\" onclick=\"switchToUserView()\">\u2b05 User Dashboard<\/button>\n        <button class=\"btn\" onclick=\"switchSection('admin-requests')\">\ud83d\udd01 Requests<\/button>\n        <button class=\"btn\" onclick=\"switchSection('admin-users')\">\ud83d\udc65 Users<\/button>\n        <button class=\"btn btn-outline\" onclick=\"switchSection('admin-notify')\">\ud83d\udce8 Notify<\/button>\n        <button class=\"btn btn-danger\" onclick=\"adminLogout()\" style=\"margin-left:auto;\">Logout Admin<\/button>\n      <\/div>\n\n      <section class=\"section active\" id=\"section-admin-requests\">\n        <h2>Pending Requests<\/h2>\n        <button class=\"btn\" onclick=\"loadAdminRequests()\">Refresh<\/button>\n        <div id=\"adminRequestsContainer\"><\/div>\n      <\/section>\n\n      <section class=\"section\" id=\"section-admin-users\">\n        <h2>Registered Users<\/h2>\n        <button class=\"btn\" onclick=\"loadAdminUsers()\">Refresh<\/button>\n        <div id=\"adminUsersContainer\"><\/div>\n      <\/section>\n\n      <section class=\"section\" id=\"section-admin-notify\">\n        <h2>Send Notification to User<\/h2>\n        <div class=\"row\">\n          <div class=\"col\"><input type=\"text\" class=\"form-control\" id=\"notifyUserId\" placeholder=\"User ID\"><\/div>\n          <div class=\"col\"><input type=\"text\" class=\"form-control\" id=\"notifyMsg\" placeholder=\"Message (e.g., MTN number)\"><\/div>\n        <\/div>\n        <button class=\"btn\" onclick=\"adminSendNotification()\" style=\"margin-top:10px;\">Send<\/button>\n      <\/section>\n    <\/div>\n\n    <!-- ========== ADMIN LOGIN ========== -->\n    <div id=\"adminLoginSection\" style=\"display:none;\">\n      <div class=\"auth-container\" style=\"max-width:400px; margin:80px auto;\">\n        <h2 style=\"text-align:center;\">Admin Login<\/h2>\n        <div class=\"form-group\"><label>Password<\/label><input type=\"password\" class=\"form-control\" id=\"adminPassword\" placeholder=\"Admin password\"><\/div>\n        <button class=\"btn btn-gold\" onclick=\"adminLogin()\" style=\"width:100%;\">Login<\/button>\n        <p style=\"text-align:center; margin-top:15px;\"><a href=\"#\" onclick=\"switchToUserView()\" style=\"color:var(--gold);\">\u2190 Back to User Dashboard<\/a><\/p>\n      <\/div>\n    <\/div>\n  <\/main>\n\n  <script>\n    \/\/ ==================== LOCALSTORAGE DATA MODELS ====================\n    let currentUser = null;\n    let adminToken = localStorage.getItem('adminToken') === 'true';\n\n    \/\/ Helper: load all data\n    function loadData() {\n      let users = JSON.parse(localStorage.getItem('adase_users') || '[]');\n      if (users.length === 0) {\n        \/\/ Create demo admin user (for admin panel login check)\n        users.push({\n          id: 'admin',\n          firstName: 'Admin',\n          lastName: 'Equity',\n          email: 'equity@cashchat.se',\n          password: 'Get.Shares.Now#',\n          role: 'admin',\n          walletBalance: 0,\n          country: 'Uganda',\n          mobile: '0000000000',\n          nin: 'ADMIN123',\n          createdAt: new Date().toISOString()\n        });\n        \/\/ Demo normal user\n        users.push({\n          id: 'user1',\n          firstName: 'John',\n          lastName: 'Investor',\n          email: 'john@example.com',\n          password: 'password123',\n          role: 'user',\n          walletBalance: 500000,\n          country: 'Uganda',\n          mobile: '+256700000001',\n          nin: 'NIN123456',\n          createdAt: new Date().toISOString()\n        });\n        localStorage.setItem('adase_users', JSON.stringify(users));\n      }\n      \/\/ Transactions (topup, withdraw, transfer requests)\n      let transactions = JSON.parse(localStorage.getItem('adase_transactions') || '[]');\n      let investments = JSON.parse(localStorage.getItem('adase_investments') || '[]');\n      let notifications = JSON.parse(localStorage.getItem('adase_notifications') || '[]');\n      return { users, transactions, investments, notifications };\n    }\n\n    function saveData(users, transactions, investments, notifications) {\n      localStorage.setItem('adase_users', JSON.stringify(users));\n      localStorage.setItem('adase_transactions', JSON.stringify(transactions));\n      localStorage.setItem('adase_investments', JSON.stringify(investments));\n      localStorage.setItem('adase_notifications', JSON.stringify(notifications));\n    }\n\n    function getCurrentUserFromStore() {\n      if (!currentUser) return null;\n      const { users } = loadData();\n      return users.find(u => u.email === currentUser.email);\n    }\n\n    function updateCurrentUser(updatedUser) {\n      const { users, transactions, investments, notifications } = loadData();\n      const idx = users.findIndex(u => u.id === updatedUser.id);\n      if (idx !== -1) users[idx] = updatedUser;\n      saveData(users, transactions, investments, notifications);\n      currentUser = updatedUser;\n    }\n\n    \/\/ ==================== UI HELPERS ====================\n    function switchSection(name) {\n      document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));\n      const target = document.getElementById(`section-${name}`);\n      if (target) target.classList.add('active');\n      if (!name.startsWith('admin-')) {\n        document.querySelectorAll('.sidebar nav a').forEach(a => a.classList.remove('active'));\n        const link = document.querySelector(`.sidebar nav a[data-section=\"${name}\"]`);\n        if (link) link.classList.add('active');\n      }\n      document.getElementById('sidebar')?.classList.remove('open');\n      if (name === 'history-invest') fetchInvestments();\n      if (name === 'history-tx') fetchTransactions();\n      if (name === 'admin-requests') loadAdminRequests();\n      if (name === 'admin-users') loadAdminUsers();\n    }\n\n    function showAuthTab(tab) {\n      document.getElementById('loginForm').style.display = tab === 'login' ? 'block' : 'none';\n      document.getElementById('registerForm').style.display = tab === 'register' ? 'block' : 'none';\n    }\n\n    \/\/ ==================== USER AUTH ====================\n    function login() {\n      const email = document.getElementById('loginEmail').value.trim();\n      const password = document.getElementById('loginPassword').value;\n      const { users } = loadData();\n      const user = users.find(u => u.email === email && u.password === password);\n      if (!user) return alert('Invalid email or password');\n      if (user.role === 'admin') return alert('Use Admin Login from sidebar');\n      currentUser = user;\n      document.getElementById('authSection').style.display = 'none';\n      document.getElementById('dashboardSections').style.display = 'block';\n      document.getElementById('adminPanel').style.display = 'none';\n      document.getElementById('adminLoginSection').style.display = 'none';\n      document.getElementById('userNameDisplay').innerText = `${user.firstName} ${user.lastName}`;\n      updateBalanceUI(user.walletBalance);\n      fetchNotifications();\n      fetchInvestments();\n      fetchTransactions();\n      switchSection('dashboard');\n    }\n\n    function register() {\n      const firstName = document.getElementById('regFirstName').value.trim();\n      const lastName = document.getElementById('regLastName').value.trim();\n      const email = document.getElementById('regEmail').value.trim();\n      const country = document.getElementById('regCountry').value.trim();\n      const mobile = document.getElementById('regMobile').value.trim();\n      const nin = document.getElementById('regNIN').value.trim();\n      const password = document.getElementById('regPassword').value;\n      const confirm = document.getElementById('regConfirmPassword').value;\n      if (!firstName || !lastName || !email || !country || !mobile || !nin || !password) return alert('All fields required');\n      if (password !== confirm) return alert('Passwords do not match');\n      if (!document.getElementById('acceptTerms').checked) return alert('Accept Terms');\n      const { users, transactions, investments, notifications } = loadData();\n      if (users.find(u => u.email === email)) return alert('Email already registered');\n      const newUser = {\n        id: 'u' + Date.now(),\n        firstName, lastName, email, country, mobile, nin, password,\n        role: 'user',\n        walletBalance: 0,\n        createdAt: new Date().toISOString()\n      };\n      users.push(newUser);\n      saveData(users, transactions, investments, notifications);\n      alert('Registration successful! Please login.');\n      showAuthTab('login');\n    }\n\n    function userLogout() {\n      currentUser = null;\n      document.getElementById('authSection').style.display = 'block';\n      document.getElementById('dashboardSections').style.display = 'none';\n      document.getElementById('adminPanel').style.display = 'none';\n      document.getElementById('adminLoginSection').style.display = 'none';\n      document.getElementById('loginEmail').value = '';\n      document.getElementById('loginPassword').value = '';\n    }\n\n    function updateBalanceUI(balance) {\n      document.getElementById('balanceDisplay').innerText = balance.toLocaleString() + ' UGX';\n    }\n\n    \/\/ ==================== WALLET ACTIONS ====================\n    function submitTopup() {\n      const amount = parseFloat(document.getElementById('topupAmount').value);\n      if (!amount || amount <= 0) return alert('Enter valid amount');\n      const user = getCurrentUserFromStore();\n      if (!user) return;\n      const { users, transactions, investments, notifications } = loadData();\n      const newTx = {\n        id: 'tx' + Date.now(),\n        userId: user.id,\n        type: 'topup',\n        amount,\n        status: 'pending',\n        createdAt: new Date().toISOString(),\n        description: `Top-up request of UGX ${amount}`\n      };\n      transactions.push(newTx);\n      saveData(users, transactions, investments, notifications);\n      alert('Top-up request sent to admin.');\n      document.getElementById('topupAmount').value = '';\n      fetchTransactions();\n    }\n\n    function submitWithdraw() {\n      const amount = parseFloat(document.getElementById('withdrawAmount').value);\n      if (!amount || amount <= 0) return alert('Enter valid amount');\n      const user = getCurrentUserFromStore();\n      if (!user || user.walletBalance < amount) return alert('Insufficient balance');\n      const { users, transactions, investments, notifications } = loadData();\n      const newTx = {\n        id: 'tx' + Date.now(),\n        userId: user.id,\n        type: 'withdraw',\n        amount,\n        status: 'pending',\n        createdAt: new Date().toISOString(),\n        description: `Withdrawal request of UGX ${amount}`\n      };\n      transactions.push(newTx);\n      saveData(users, transactions, investments, notifications);\n      alert('Withdrawal request sent to admin.');\n      document.getElementById('withdrawAmount').value = '';\n      fetchTransactions();\n    }\n\n    function submitTransfer() {\n      const toEmail = document.getElementById('transferEmail').value.trim();\n      const amount = parseFloat(document.getElementById('transferAmount').value);\n      if (!toEmail || !amount || amount <= 0) return alert('Enter valid email and amount');\n      const user = getCurrentUserFromStore();\n      if (!user || user.walletBalance < amount) return alert('Insufficient balance');\n      const { users, transactions, investments, notifications } = loadData();\n      const recipient = users.find(u => u.email === toEmail);\n      if (!recipient) return alert('Recipient not found');\n      const newTx = {\n        id: 'tx' + Date.now(),\n        userId: user.id,\n        type: 'transfer',\n        amount,\n        toUserId: recipient.id,\n        toUserEmail: recipient.email,\n        status: 'pending',\n        createdAt: new Date().toISOString(),\n        description: `Transfer of UGX ${amount} to ${recipient.email}`\n      };\n      transactions.push(newTx);\n      saveData(users, transactions, investments, notifications);\n      alert('Transfer request sent to admin.');\n      document.getElementById('transferEmail').value = '';\n      document.getElementById('transferAmount').value = '';\n      fetchTransactions();\n    }\n\n    \/\/ ==================== INVESTMENTS ====================\n    async function buyAndDownload() {\n      const principal = parseFloat(document.getElementById('investAmount').value);\n      if (principal < 100000) return alert('Minimum investment is 100,000 UGX');\n      const user = getCurrentUserFromStore();\n      if (!user || user.walletBalance < principal) return alert('Insufficient wallet balance');\n      \/\/ deduct balance\n      user.walletBalance -= principal;\n      const certNumber = 'ADASE-' + Date.now();\n      const { users, transactions, investments, notifications } = loadData();\n      const newInv = {\n        id: 'inv' + Date.now(),\n        userId: user.id,\n        certificateNumber: certNumber,\n        principal,\n        issuedAt: new Date().toISOString(),\n        interestRate: 17,\n        maturity: new Date(new Date().setFullYear(new Date().getFullYear() + 3)).toISOString()\n      };\n      investments.push(newInv);\n      \/\/ record transaction\n      const newTx = {\n        id: 'tx' + Date.now(),\n        userId: user.id,\n        type: 'investment',\n        amount: principal,\n        status: 'approved',\n        createdAt: new Date().toISOString(),\n        description: `Purchase of convertible note ${certNumber}`\n      };\n      transactions.push(newTx);\n      \/\/ update user\n      const idx = users.findIndex(u => u.id === user.id);\n      users[idx] = user;\n      saveData(users, transactions, investments, notifications);\n      currentUser = user;\n      updateBalanceUI(user.walletBalance);\n      alert(`Investment successful! Certificate: ${certNumber}`);\n      fetchInvestments();\n      fetchTransactions();\n      generateCertificate(certNumber, principal, `${user.firstName} ${user.lastName}`);\n      document.getElementById('investAmount').value = '';\n    }\n\n    async function generateCertificate(certNumber, amount, name) {\n      const issueDate = new Date().toISOString().split('T')[0];\n      const maturity = new Date(new Date().setFullYear(new Date().getFullYear() + 3)).toISOString().split('T')[0];\n      const wrapper = document.createElement('div');\n      wrapper.style.position = 'absolute';\n      wrapper.style.left = '-9999px';\n      wrapper.innerHTML = `\n        <div style=\"width:800px;padding:40px;background:#fefdf8;border:6px double #0a1f44;font-family:Inter,sans-serif;\">\n          <div style=\"text-align:center;font-size:28px;font-weight:700;color:#0a1f44;\">ADASE ADS LTD<\/div>\n          <div style=\"text-align:center;font-size:20px;color:#c49a2b;margin:8px 0 20px;\">Convertible Note Certificate<\/div>\n          <p style=\"font-size:16px;\">This certifies that <strong>${name}<\/strong> has invested <strong>UGX ${amount.toLocaleString()}<\/strong> on <strong>${issueDate}<\/strong>.<\/p>\n          <table style=\"width:100%;margin:20px 0;font-size:14px;border-collapse:collapse;\">\n            <tr><td style=\"padding:8px 0;border-bottom:1px dotted #ccc;\">Certificate No<\/td><td style=\"font-weight:bold;\">${certNumber}<\/td><\/tr>\n            <tr><td style=\"padding:8px 0;border-bottom:1px dotted #ccc;\">Interest Rate<\/td><td>17% p.a.<\/td><\/tr>\n            <tr><td style=\"padding:8px 0;border-bottom:1px dotted #ccc;\">Maturity<\/td><td>${maturity}<\/td><\/tr>\n            <tr><td style=\"padding:8px 0;border-bottom:1px dotted #ccc;\">Conversion Discount<\/td><td>20%<\/td><\/tr>\n          <\/table>\n          <p style=\"margin-top:32px;font-style:italic;\">Authorized Signatory<\/p>\n        <\/div>\n      `;\n      document.body.appendChild(wrapper);\n      const canvas = await html2canvas(wrapper.firstChild, { scale: 2 });\n      document.body.removeChild(wrapper);\n      const link = document.createElement('a');\n      link.download = `Adase_Note_${certNumber}.png`;\n      link.href = canvas.toDataURL();\n      link.click();\n    }\n\n    function fetchInvestments() {\n      const user = getCurrentUserFromStore();\n      if (!user) return;\n      const { investments } = loadData();\n      const myInvs = investments.filter(i => i.userId === user.id);\n      const tbody = document.getElementById('investHistoryBody');\n      if (myInvs.length === 0) tbody.innerHTML = '<tr><td colspan=\"4\">No investments yet.<\/td><\/tr>';\n      else {\n        tbody.innerHTML = myInvs.map(i => `\n          <tr><td>${i.certificateNumber}<\/td><td>${i.principal.toLocaleString()} UGX<\/td><td>${new Date(i.issuedAt).toLocaleDateString()}<\/td>\n          <td><button class=\"btn\" onclick=\"generateCertificate('${i.certificateNumber}', ${i.principal}, '${user.firstName} ${user.lastName}')\">Download<\/button><\/td><\/tr>\n        `).join('');\n      }\n    }\n\n    function fetchTransactions() {\n      const user = getCurrentUserFromStore();\n      if (!user) return;\n      const { transactions } = loadData();\n      const myTx = transactions.filter(t => t.userId === user.id).sort((a,b)=>new Date(b.createdAt)-new Date(a.createdAt));\n      const tbody = document.getElementById('txHistoryBody');\n      if (myTx.length === 0) tbody.innerHTML = '<tr><td colspan=\"5\">No transactions<\/td><\/tr>';\n      else {\n        tbody.innerHTML = myTx.map(t => `\n          <tr><td>${t.type}<\/td><td>${t.amount.toLocaleString()} UGX<\/td>\n          <td><span class=\"badge ${t.status==='approved'?'badge-success':t.status==='pending'?'badge-warning':'badge-danger'}\">${t.status}<\/span><\/td>\n          <td>${new Date(t.createdAt).toLocaleString()}<\/td><td>${t.description||''}<\/td><\/tr>\n        `).join('');\n      }\n    }\n\n    function fetchNotifications() {\n      const user = getCurrentUserFromStore();\n      if (!user) return;\n      const { notifications } = loadData();\n      const userNotifs = notifications.filter(n => n.userId === user.id && !n.dismissed);\n      const container = document.getElementById('notificationsPreview');\n      if (userNotifs.length === 0) container.innerHTML = '<p>No new notifications<\/p>';\n      else {\n        container.innerHTML = userNotifs.map(n => `\n          <div class=\"notification\"><span>${n.message} <small>(${new Date(n.createdAt).toLocaleString()})<\/small><\/span>\n          <button class=\"btn\" style=\"padding:4px 10px;\" onclick=\"dismissNotif('${n.id}')\">Dismiss<\/button><\/div>\n        `).join('');\n      }\n    }\n\n    function dismissNotif(id) {\n      const { users, transactions, investments, notifications } = loadData();\n      const notif = notifications.find(n => n.id === id);\n      if (notif) notif.dismissed = true;\n      saveData(users, transactions, investments, notifications);\n      fetchNotifications();\n    }\n\n    \/\/ ==================== ADMIN ====================\n    function adminLogin() {\n      const pwd = document.getElementById('adminPassword').value;\n      if (pwd === 'Get.Shares.Now#') {\n        adminToken = true;\n        localStorage.setItem('adminToken', 'true');\n        showAdminPanel();\n      } else alert('Invalid admin password');\n    }\n\n    function showAdminPanel() {\n      document.getElementById('authSection').style.display = 'none';\n      document.getElementById('dashboardSections').style.display = 'none';\n      document.getElementById('adminPanel').style.display = 'block';\n      document.getElementById('adminLoginSection').style.display = 'none';\n      switchSection('admin-requests');\n    }\n\n    function adminLogout() {\n      adminToken = false;\n      localStorage.removeItem('adminToken');\n      if (currentUser) switchToUserView();\n      else location.reload();\n    }\n\n    function switchToUserView() {\n      if (currentUser) {\n        document.getElementById('authSection').style.display = 'none';\n        document.getElementById('dashboardSections').style.display = 'block';\n        document.getElementById('adminPanel').style.display = 'none';\n        document.getElementById('adminLoginSection').style.display = 'none';\n        switchSection('dashboard');\n      } else {\n        location.reload();\n      }\n    }\n\n    function loadAdminRequests() {\n      const { users, transactions } = loadData();\n      const pending = transactions.filter(t => t.status === 'pending');\n      const topups = pending.filter(t => t.type === 'topup');\n      const withdraws = pending.filter(t => t.type === 'withdraw');\n      const transfers = pending.filter(t => t.type === 'transfer');\n      const renderTable = (items, type) => {\n        if (!items.length) return '<p>None<\/p>';\n        let html = '<table><thead><td>';\n        if (type === 'transfer') html += '<th>From<\/th><th>To<\/th>';\n        else html += '<th>User<\/th>';\n        html += '<th>Amount<\/th><th>Actions<\/th><\/tr><\/thead><tbody>';\n        items.forEach(item => {\n          const fromUser = users.find(u => u.id === item.userId);\n          const fromName = fromUser ? `${fromUser.firstName} ${fromUser.lastName}` : 'Unknown';\n          if (type === 'transfer') {\n            const toUser = users.find(u => u.id === item.toUserId);\n            html += `<tr><td>${fromName} (${fromUser?.email})<\/td><td>${toUser?.email || item.toUserEmail}<\/td><td>${item.amount.toLocaleString()} UGX<\/td>\n            <td><button class=\"btn\" onclick=\"adminApprove('${item.id}')\">Approve<\/button> <button class=\"btn btn-outline\" onclick=\"adminDecline('${item.id}')\">Decline<\/button><\/td><\/tr>`;\n          } else {\n            html += `<tr><td>${fromName} (${fromUser?.email})<\/td><td>${item.amount.toLocaleString()} UGX<\/td>\n            <td><button class=\"btn\" onclick=\"adminApprove('${item.id}')\">Approve<\/button> <button class=\"btn btn-outline\" onclick=\"adminDecline('${item.id}')\">Decline<\/button>\n            <button class=\"btn\" onclick=\"adminRequestPayment('${item.userId}')\">Request Payment<\/button><\/td><\/tr>`;\n          }\n        });\n        html += '<\/tbody><\/table>';\n        return html;\n      };\n      const html = `<h3>Top\u2011ups<\/h3>${renderTable(topups, 'topup')}<h3>Withdrawals<\/h3>${renderTable(withdraws, 'withdraw')}<h3>Transfers<\/h3>${renderTable(transfers, 'transfer')}`;\n      document.getElementById('adminRequestsContainer').innerHTML = html;\n    }\n\n    async function adminApprove(txId) {\n      const { users, transactions, investments, notifications } = loadData();\n      const tx = transactions.find(t => t.id === txId);\n      if (!tx) return;\n      tx.status = 'approved';\n      const user = users.find(u => u.id === tx.userId);\n      if (tx.type === 'topup') {\n        user.walletBalance += tx.amount;\n      } else if (tx.type === 'withdraw') {\n        if (user.walletBalance >= tx.amount) user.walletBalance -= tx.amount;\n        else tx.status = 'declined';\n      } else if (tx.type === 'transfer') {\n        const recipient = users.find(u => u.id === tx.toUserId);\n        if (user.walletBalance >= tx.amount && recipient) {\n          user.walletBalance -= tx.amount;\n          recipient.walletBalance += tx.amount;\n        } else tx.status = 'declined';\n      }\n      saveData(users, transactions, investments, notifications);\n      loadAdminRequests();\n      if (currentUser && currentUser.id === user.id) updateBalanceUI(user.walletBalance);\n    }\n\n    async function adminDecline(txId) {\n      const { users, transactions, investments, notifications } = loadData();\n      const tx = transactions.find(t => t.id === txId);\n      if (tx) tx.status = 'declined';\n      saveData(users, transactions, investments, notifications);\n      loadAdminRequests();\n    }\n\n    function adminRequestPayment(userId) {\n      const msg = prompt('Enter message to request payment details (e.g., MTN number):');\n      if (!msg) return;\n      const { users, transactions, investments, notifications } = loadData();\n      const newNotif = {\n        id: 'notif' + Date.now(),\n        userId,\n        message: msg,\n        createdAt: new Date().toISOString(),\n        dismissed: false\n      };\n      notifications.push(newNotif);\n      saveData(users, transactions, investments, notifications);\n      alert('Notification sent');\n    }\n\n    function loadAdminUsers() {\n      const { users } = loadData();\n      const normalUsers = users.filter(u => u.role !== 'admin');\n      const tbody = document.getElementById('adminUsersContainer');\n      if (normalUsers.length === 0) tbody.innerHTML = '<p>No users found.<\/p>';\n      else {\n        let html = '<table><thead><tr><th>ID<\/th><th>Name<\/th><th>Email<\/th><th>Country<\/th><th>Mobile<\/th><th>NIN<\/th><th>Wallet<\/th><th>Joined<\/th><\/tr><\/thead><tbody>';\n        normalUsers.forEach(u => {\n          html += `<tr><td>${u.id}<\/td><td>${u.firstName} ${u.lastName}<\/td><td>${u.email}<\/td><td>${u.country}<\/td><td>${u.mobile}<\/td><td>${u.nin}<\/td><td>${u.walletBalance.toLocaleString()} UGX<\/td><td>${new Date(u.createdAt).toLocaleDateString()}<\/td><\/tr>`;\n        });\n        html += '<\/tbody><\/table>';\n        tbody.innerHTML = html;\n      }\n    }\n\n    function adminSendNotification() {\n      const userId = document.getElementById('notifyUserId').value.trim();\n      const message = document.getElementById('notifyMsg').value.trim();\n      if (!userId || !message) return alert('Fill both fields');\n      const { users, transactions, investments, notifications } = loadData();\n      const userExists = users.find(u => u.id === userId);\n      if (!userExists) return alert('User ID not found');\n      const newNotif = { id: 'notif' + Date.now(), userId, message, createdAt: new Date().toISOString(), dismissed: false };\n      notifications.push(newNotif);\n      saveData(users, transactions, investments, notifications);\n      alert('Notification sent');\n      document.getElementById('notifyUserId').value = '';\n      document.getElementById('notifyMsg').value = '';\n    }\n\n    \/\/ ==================== INIT ====================\n    document.querySelectorAll('.sidebar nav a[data-section]').forEach(a => {\n      a.addEventListener('click', e => {\n        e.preventDefault();\n        switchSection(a.dataset.section);\n      });\n    });\n    document.getElementById('logoutSidebar')?.addEventListener('click', e => { e.preventDefault(); userLogout(); });\n    document.getElementById('adminSidebarLink')?.addEventListener('click', e => {\n      e.preventDefault();\n      document.getElementById('authSection').style.display = 'none';\n      document.getElementById('dashboardSections').style.display = 'none';\n      document.getElementById('adminPanel').style.display = 'none';\n      document.getElementById('adminLoginSection').style.display = 'block';\n    });\n    document.getElementById('menuToggle')?.addEventListener('click', () => {\n      document.getElementById('sidebar').classList.toggle('open');\n    });\n\n    \/\/ Auto restore session\n    if (adminToken) {\n      showAdminPanel();\n    } else {\n      const storedUser = localStorage.getItem('adase_current_user');\n      if (storedUser) {\n        try {\n          currentUser = JSON.parse(storedUser);\n          document.getElementById('authSection').style.display = 'none';\n          document.getElementById('dashboardSections').style.display = 'block';\n          document.getElementById('userNameDisplay').innerText = `${currentUser.firstName} ${currentUser.lastName}`;\n          updateBalanceUI(currentUser.walletBalance);\n          fetchNotifications(); fetchInvestments(); fetchTransactions();\n          switchSection('dashboard');\n        } catch(e) {}\n      }\n    }\n    window.addEventListener('beforeunload', () => {\n      if (currentUser) localStorage.setItem('adase_current_user', JSON.stringify(currentUser));\n      else localStorage.removeItem('adase_current_user');\n    });\n  <\/script>\n<\/body>\n<\/html>\n\n\n\n<!--nextpage-->\n\n\n\n<script data-wp-block-html=\"js\">\nrequire('dotenv').config();\nconst express = require('express');\nconst mongoose = require('mongoose');\nconst bcrypt = require('bcryptjs');\nconst jwt = require('jsonwebtoken');\nconst cors = require('cors');\n\nconst app = express();\napp.use(cors());\napp.use(express.json());\n\n\/\/ ==================== MongoDB Models ====================\nconst userSchema = new mongoose.Schema({\n  firstName: String,\n  lastName: String,\n  email: { type: String, unique: true },\n  country: String,\n  mobile: String,\n  nin: String,\n  password: String,\n  walletBalance: { type: Number, default: 0 },\n  termsAccepted: { type: Boolean, default: false },\n  createdAt: { type: Date, default: Date.now }\n});\n\nconst transactionSchema = new mongoose.Schema({\n  userId: mongoose.Schema.Types.ObjectId,\n  type: { type: String, enum: ['topup','withdraw','investment','transfer_in','transfer_out'] },\n  amount: Number,\n  status: { type: String, enum: ['pending','approved','declined'], default: 'pending' },\n  description: String,\n  adminNote: String,\n  createdAt: { type: Date, default: Date.now }\n});\n\nconst topupRequestSchema = new mongoose.Schema({\n  userId: mongoose.Schema.Types.ObjectId,\n  amount: Number,\n  status: { type: String, enum: ['pending','approved','declined'], default: 'pending' },\n  adminNote: String,\n  createdAt: { type: Date, default: Date.now }\n});\n\nconst withdrawRequestSchema = new mongoose.Schema({\n  userId: mongoose.Schema.Types.ObjectId,\n  amount: Number,\n  status: { type: String, enum: ['pending','approved','declined'], default: 'pending' },\n  adminNote: String,\n  createdAt: { type: Date, default: Date.now }\n});\n\nconst transferRequestSchema = new mongoose.Schema({\n  fromUserId: mongoose.Schema.Types.ObjectId,\n  toUserEmail: String,\n  amount: Number,\n  status: { type: String, enum: ['pending','approved','declined'], default: 'pending' },\n  adminNote: String,\n  createdAt: { type: Date, default: Date.now }\n});\n\nconst investmentSchema = new mongoose.Schema({\n  userId: mongoose.Schema.Types.ObjectId,\n  principal: Number,\n  interestRate: Number,\n  discountPercent: Number,\n  maturityMonths: Number,\n  certificateNumber: String,\n  issuedAt: { type: Date, default: Date.now }\n});\n\nconst notificationSchema = new mongoose.Schema({\n  userId: mongoose.Schema.Types.ObjectId,\n  message: String,\n  read: { type: Boolean, default: false },\n  createdAt: { type: Date, default: Date.now }\n});\n\n\/\/ NEW: Configuration model for backend settings\nconst configSchema = new mongoose.Schema({\n  key: { type: String, unique: true },\n  value: String,\n});\nconst Config = mongoose.model('Config', configSchema);\n\nconst User = mongoose.model('User', userSchema);\nconst Transaction = mongoose.model('Transaction', transactionSchema);\nconst TopupRequest = mongoose.model('TopupRequest', topupRequestSchema);\nconst WithdrawRequest = mongoose.model('WithdrawRequest', withdrawRequestSchema);\nconst TransferRequest = mongoose.model('TransferRequest', transferRequestSchema);\nconst Investment = mongoose.model('Investment', investmentSchema);\nconst Notification = mongoose.model('Notification', notificationSchema);\n\n\/\/ ==================== Auth Middleware ====================\nconst auth = (req, res, next) => {\n  const token = req.header('x-auth-token');\n  if (!token) return res.status(401).json({ msg: 'No token' });\n  try {\n    const decoded = jwt.verify(token, process.env.JWT_SECRET);\n    req.user = decoded.user;\n    next();\n  } catch (e) {\n    res.status(401).json({ msg: 'Invalid token' });\n  }\n};\n\nconst adminAuth = (req, res, next) => {\n  const token = req.header('x-admin-token');\n  if (!token) return res.status(401).json({ msg: 'Admin token missing' });\n  try {\n    const decoded = jwt.verify(token, process.env.JWT_SECRET);\n    if (decoded.user.email !== process.env.ADMIN_EMAIL) throw new Error();\n    req.admin = decoded.user;\n    next();\n  } catch (e) {\n    res.status(401).json({ msg: 'Admin authorization failed' });\n  }\n};\n\n\/\/ ==================== User APIs ====================\napp.post('\/api\/users\/register', async (req, res) => {\n  const { firstName, lastName, email, country, mobile, nin, password } = req.body;\n  if (!firstName || !lastName || !email || !country || !mobile || !nin || !password) {\n    return res.status(400).json({ msg: 'All fields are required' });\n  }\n  try {\n    let user = await User.findOne({ email });\n    if (user) return res.status(400).json({ msg: 'User already exists' });\n    user = new User({ firstName, lastName, email, country, mobile, nin, password, termsAccepted: true });\n    const salt = await bcrypt.genSalt(10);\n    user.password = await bcrypt.hash(password, salt);\n    await user.save();\n    const payload = { user: { id: user.id, email: user.email } };\n    jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '7d' }, (err, token) => {\n      if (err) throw err;\n      res.json({\n        token,\n        user: {\n          id: user.id,\n          name: `${user.firstName} ${user.lastName}`,\n          email: user.email,\n          walletBalance: user.walletBalance\n        }\n      });\n    });\n  } catch (err) {\n    res.status(500).send('Server error');\n  }\n});\n\napp.post('\/api\/users\/login', async (req, res) => {\n  const { email, password } = req.body;\n  try {\n    let user = await User.findOne({ email });\n    if (!user) return res.status(400).json({ msg: 'Invalid credentials' });\n    const isMatch = await bcrypt.compare(password, user.password);\n    if (!isMatch) return res.status(400).json({ msg: 'Invalid credentials' });\n    const payload = { user: { id: user.id, email: user.email } };\n    jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '7d' }, (err, token) => {\n      if (err) throw err;\n      res.json({\n        token,\n        user: {\n          id: user.id,\n          name: `${user.firstName} ${user.lastName}`,\n          email: user.email,\n          walletBalance: user.walletBalance\n        }\n      });\n    });\n  } catch (err) {\n    res.status(500).send('Server error');\n  }\n});\n\napp.get('\/api\/users\/me', auth, async (req, res) => {\n  const user = await User.findById(req.user.id).select('-password');\n  if (!user) return res.status(404).json({ msg: 'User not found' });\n  res.json({\n    ...user.toObject(),\n    name: `${user.firstName} ${user.lastName}`\n  });\n});\n\n\/\/ ==================== Wallet APIs ====================\napp.post('\/api\/wallet\/topup', auth, async (req, res) => {\n  const { amount } = req.body;\n  if (amount <= 0) return res.status(400).json({ msg: 'Invalid amount' });\n  try {\n    const req = new TopupRequest({ userId: req.user.id, amount });\n    await req.save();\n    res.json({ msg: 'Top-up request submitted' });\n  } catch (err) {\n    res.status(500).send('Server error');\n  }\n});\n\napp.post('\/api\/wallet\/withdraw', auth, async (req, res) => {\n  const { amount } = req.body;\n  if (amount <= 0) return res.status(400).json({ msg: 'Invalid amount' });\n  try {\n    const user = await User.findById(req.user.id);\n    if (user.walletBalance < amount) return res.status(400).json({ msg: 'Insufficient balance' });\n    const req = new WithdrawRequest({ userId: req.user.id, amount });\n    await req.save();\n    res.json({ msg: 'Withdrawal request submitted' });\n  } catch (err) {\n    res.status(500).send('Server error');\n  }\n});\n\napp.post('\/api\/wallet\/transfer', auth, async (req, res) => {\n  const { toEmail, amount } = req.body;\n  if (amount <= 0) return res.status(400).json({ msg: 'Invalid amount' });\n  try {\n    const fromUser = await User.findById(req.user.id);\n    if (fromUser.walletBalance < amount) return res.status(400).json({ msg: 'Insufficient balance' });\n    const toUser = await User.findOne({ email: toEmail });\n    if (!toUser) return res.status(400).json({ msg: 'Recipient not found' });\n    const req = new TransferRequest({ fromUserId: req.user.id, toUserEmail: toEmail, amount });\n    await req.save();\n    res.json({ msg: 'Transfer request submitted for admin approval' });\n  } catch (err) {\n    res.status(500).send('Server error');\n  }\n});\n\n\/\/ ==================== Investment APIs ====================\napp.post('\/api\/invest', auth, async (req, res) => {\n  const { principal } = req.body;\n  if (principal < 100000) return res.status(400).json({ msg: 'Minimum investment is UGX 100,000' });\n  try {\n    const user = await User.findById(req.user.id);\n    if (user.walletBalance < principal) return res.status(400).json({ msg: 'Insufficient wallet balance' });\n    user.walletBalance -= principal;\n    await user.save();\n    const certNumber = 'CN-' + new Date().getFullYear() + '-' + Math.random().toString(36).substr(2, 8).toUpperCase();\n    const investment = new Investment({\n      userId: user.id,\n      principal,\n      interestRate: 17,\n      discountPercent: 20,\n      maturityMonths: 36,\n      certificateNumber: certNumber\n    });\n    await investment.save();\n    await Transaction.create({\n      userId: user.id,\n      type: 'investment',\n      amount: principal,\n      status: 'approved',\n      description: `Convertible note purchase - ${certNumber}`\n    });\n    res.json({ msg: 'Investment successful', certificateNumber: certNumber, newBalance: user.walletBalance });\n  } catch (err) {\n    res.status(500).send('Server error');\n  }\n});\n\napp.get('\/api\/investments', auth, async (req, res) => {\n  try {\n    const investments = await Investment.find({ userId: req.user.id }).sort({ issuedAt: -1 });\n    res.json(investments);\n  } catch (err) {\n    res.status(500).send('Server error');\n  }\n});\n\napp.get('\/api\/transactions', auth, async (req, res) => {\n  try {\n    const txns = await Transaction.find({ userId: req.user.id }).sort({ createdAt: -1 });\n    res.json(txns);\n  } catch (err) {\n    res.status(500).send('Server error');\n  }\n});\n\n\/\/ ==================== Notification APIs ====================\napp.post('\/api\/admin\/notify\/:userId', adminAuth, async (req, res) => {\n  const { message } = req.body;\n  await Notification.create({ userId: req.params.userId, message });\n  res.json({ msg: 'Notification sent' });\n});\n\napp.get('\/api\/notifications', auth, async (req, res) => {\n  const notifs = await Notification.find({ userId: req.user.id, read: false }).sort({ createdAt: -1 });\n  res.json(notifs);\n});\n\napp.post('\/api\/notifications\/read\/:id', auth, async (req, res) => {\n  await Notification.findByIdAndUpdate(req.params.id, { read: true });\n  res.json({ msg: 'Marked read' });\n});\n\n\/\/ ==================== Admin APIs ====================\n\/\/ Admin login \u2013 dynamic password from DB\napp.post('\/api\/admin\/login', async (req, res) => {\n  const { email, password } = req.body;\n  if (email !== process.env.ADMIN_EMAIL) return res.status(400).json({ msg: 'Invalid credentials' });\n\n  \/\/ Check if a custom password hash exists in the DB\n  let storedHash = process.env.ADMIN_PASSWORD_HASH;\n  const dbConfig = await Config.findOne({ key: 'ADMIN_PASSWORD_HASH' });\n  if (dbConfig) storedHash = dbConfig.value;\n\n  const isMatch = await bcrypt.compare(password, storedHash);\n  if (!isMatch) return res.status(400).json({ msg: 'Invalid credentials' });\n\n  const payload = { user: { id: 'admin', email } };\n  jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '1d' }, (err, token) => {\n    if (err) throw err;\n    res.json({ token });\n  });\n});\n\n\/\/ Get admin requests\napp.get('\/api\/admin\/requests', adminAuth, async (req, res) => {\n  try {\n    const topups = await TopupRequest.find().populate('userId','firstName lastName email').sort({ createdAt: -1 });\n    const withdraws = await WithdrawRequest.find().populate('userId','firstName lastName email').sort({ createdAt: -1 });\n    const transfers = await TransferRequest.find().populate('fromUserId','firstName lastName email').sort({ createdAt: -1 });\n    res.json({ topups, withdraws, transfers });\n  } catch (err) {\n    res.status(500).send('Server error');\n  }\n});\n\napp.post('\/api\/admin\/topup\/:id', adminAuth, async (req, res) => {\n  const { status, adminNote } = req.body;\n  try {\n    const topup = await TopupRequest.findById(req.params.id);\n    if (!topup) return res.status(404).json({ msg: 'Not found' });\n    if (status === 'approved') {\n      const user = await User.findById(topup.userId);\n      user.walletBalance += topup.amount;\n      await user.save();\n      await Transaction.create({\n        userId: user.id,\n        type: 'topup',\n        amount: topup.amount,\n        status: 'approved',\n        description: 'Top-up approved',\n        adminNote\n      });\n    }\n    topup.status = status;\n    topup.adminNote = adminNote || '';\n    await topup.save();\n    res.json({ msg: `Top-up ${status}` });\n  } catch (err) {\n    res.status(500).send('Server error');\n  }\n});\n\napp.post('\/api\/admin\/withdraw\/:id', adminAuth, async (req, res) => {\n  const { status, adminNote } = req.body;\n  try {\n    const withdraw = await WithdrawRequest.findById(req.params.id);\n    if (!withdraw) return res.status(404).json({ msg: 'Not found' });\n    if (status === 'approved') {\n      const user = await User.findById(withdraw.userId);\n      if (user.walletBalance < withdraw.amount) return res.status(400).json({ msg: 'Insufficient balance' });\n      user.walletBalance -= withdraw.amount;\n      await user.save();\n      await Transaction.create({\n        userId: user.id,\n        type: 'withdraw',\n        amount: withdraw.amount,\n        status: 'approved',\n        description: 'Withdrawal approved',\n        adminNote\n      });\n    }\n    withdraw.status = status;\n    withdraw.adminNote = adminNote || '';\n    await withdraw.save();\n    res.json({ msg: `Withdrawal ${status}` });\n  } catch (err) {\n    res.status(500).send('Server error');\n  }\n});\n\napp.post('\/api\/admin\/transfer\/:id', adminAuth, async (req, res) => {\n  const { status, adminNote } = req.body;\n  try {\n    const transfer = await TransferRequest.findById(req.params.id);\n    if (!transfer) return res.status(404).json({ msg: 'Not found' });\n    if (status === 'approved') {\n      const fromUser = await User.findById(transfer.fromUserId);\n      const toUser = await User.findOne({ email: transfer.toUserEmail });\n      if (!fromUser || !toUser) return res.status(400).json({ msg: 'User not found' });\n      if (fromUser.walletBalance < transfer.amount) return res.status(400).json({ msg: 'Insufficient balance' });\n      fromUser.walletBalance -= transfer.amount;\n      toUser.walletBalance += transfer.amount;\n      await fromUser.save();\n      await toUser.save();\n      await Transaction.create({ userId: fromUser.id, type: 'transfer_out', amount: transfer.amount, status: 'approved', description: `Transfer to ${transfer.toUserEmail}` });\n      await Transaction.create({ userId: toUser.id, type: 'transfer_in', amount: transfer.amount, status: 'approved', description: `Transfer from ${fromUser.email}` });\n    }\n    transfer.status = status;\n    transfer.adminNote = adminNote || '';\n    await transfer.save();\n    res.json({ msg: `Transfer ${status}` });\n  } catch (err) {\n    res.status(500).send('Server error');\n  }\n});\n\napp.get('\/api\/admin\/users', adminAuth, async (req, res) => {\n  try {\n    const users = await User.find().select('-password').sort({ createdAt: -1 });\n    res.json(users);\n  } catch (err) {\n    res.status(500).send('Server error');\n  }\n});\n\n\/\/ ==================== NEW: Backend Configuration APIs ====================\n\/\/ Get all configuration values\napp.get('\/api\/admin\/config', adminAuth, async (req, res) => {\n  try {\n    const configs = await Config.find();\n    const result = {};\n    configs.forEach(c => { result[c.key] = c.value; });\n    \/\/ Merge with env defaults for empty keys\n    const defaults = {\n      MONGODB_URI: process.env.MONGODB_URI || '',\n      JWT_SECRET: process.env.JWT_SECRET || '',\n      ADMIN_EMAIL: process.env.ADMIN_EMAIL || '',\n      ADMIN_PASSWORD_HASH: '\u25cf\u25cf\u25cf\u25cf\u25cf\u25cf', \/\/ masked \u2013 never return the real hash\n    };\n    res.json({ ...defaults, ...result });\n  } catch (err) {\n    res.status(500).send('Server error');\n  }\n});\n\n\/\/ Update configuration values\napp.post('\/api\/admin\/config', adminAuth, async (req, res) => {\n  const { MONGODB_URI, JWT_SECRET, ADMIN_EMAIL, ADMIN_PASSWORD_HASH } = req.body;\n  try {\n    if (MONGODB_URI) await Config.updateOne({ key: 'MONGODB_URI' }, { value: MONGODB_URI }, { upsert: true });\n    if (JWT_SECRET) await Config.updateOne({ key: 'JWT_SECRET' }, { value: JWT_SECRET }, { upsert: true });\n    if (ADMIN_EMAIL) await Config.updateOne({ key: 'ADMIN_EMAIL' }, { value: ADMIN_EMAIL }, { upsert: true });\n    if (ADMIN_PASSWORD_HASH) {\n      \/\/ Hash the new password before storing\n      const hash = await bcrypt.hash(ADMIN_PASSWORD_HASH, 10);\n      await Config.updateOne({ key: 'ADMIN_PASSWORD_HASH' }, { value: hash }, { upsert: true });\n    }\n    res.json({ msg: 'Configuration saved. Some changes may require a server restart to take full effect.' });\n  } catch (err) {\n    res.status(500).send('Server error');\n  }\n});\n\n\/\/ ==================== Start Server ====================\nconst PORT = process.env.PORT || 3000;\nmongoose.connect(process.env.MONGODB_URI)\n  .then(() => {\n    console.log('MongoDB connected');\n    app.listen(PORT, () => console.log(`Server running on port ${PORT}`));\n  })\n  .catch(err => console.error(err));\n<\/script>\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n  <title>Adase Ads \u2013 Complete Dashboard<\/title>\n  <script src=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/html2canvas\/1.4.1\/html2canvas.min.js\"><\/script>\n  <script src=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/jspdf\/2.5.1\/jspdf.umd.min.js\"><\/script>\n  <style>\n    * { margin: 0; padding: 0; box-sizing: border-box; }\n    :root {\n      --primary: #0a1f44;\n      --gold: #c49a2b;\n      --bg: #f4f6f9;\n      --card-bg: #ffffff;\n      --text: #1e293b;\n      --shadow: 0 10px 25px -5px rgba(0,0,0,0.05), 0 8px 10px -6px rgba(0,0,0,0.02);\n      --radius: 16px;\n    }\n    body {\n      font-family: 'Inter', system-ui, -apple-system, sans-serif;\n      background: var(--bg);\n      color: var(--text);\n      display: flex;\n      min-height: 100vh;\n    }\n    .sidebar {\n      width: 260px;\n      background: var(--primary);\n      color: #fff;\n      padding: 24px 16px;\n      position: fixed;\n      top: 0; left: 0; bottom: 0;\n      z-index: 100;\n      transition: transform 0.3s ease;\n      display: flex;\n      flex-direction: column;\n    }\n    .sidebar .logo {\n      font-family: 'Playfair Display', serif;\n      font-size: 24px;\n      font-weight: 700;\n      text-align: center;\n      letter-spacing: 2px;\n      margin-bottom: 32px;\n    }\n    .sidebar .logo span { color: var(--gold); }\n    .sidebar nav a {\n      display: flex;\n      align-items: center;\n      gap: 10px;\n      color: rgba(255,255,255,0.8);\n      text-decoration: none;\n      padding: 12px 16px;\n      border-radius: 10px;\n      margin-bottom: 6px;\n      font-weight: 500;\n      transition: background 0.2s, color 0.2s;\n    }\n    .sidebar nav a:hover,\n    .sidebar nav a.active { background: rgba(255,255,255,0.08); color: var(--gold); }\n    .main {\n      margin-left: 260px;\n      flex: 1;\n      padding: 28px 32px;\n      transition: margin-left 0.3s;\n    }\n    .mobile-header {\n      display: none;\n      align-items: center;\n      gap: 16px;\n      background: var(--primary);\n      color: #fff;\n      padding: 14px 20px;\n      position: sticky;\n      top: 0; z-index: 99;\n    }\n    .mobile-header .menu-toggle {\n      background: none; border: none; color: #fff; font-size: 24px; cursor: pointer;\n    }\n    .section {\n      background: var(--card-bg);\n      border-radius: var(--radius);\n      padding: 24px;\n      margin-bottom: 24px;\n      box-shadow: var(--shadow);\n      display: none;\n    }\n    .section.active { display: block; }\n    h2 {\n      font-family: 'Playfair Display', serif;\n      color: var(--primary);\n      font-size: 22px;\n      margin-bottom: 20px;\n      border-bottom: 2px solid var(--gold);\n      padding-bottom: 10px;\n      display: inline-block;\n    }\n    h3 { color: var(--primary); margin: 16px 0 10px; }\n    .wallet-balance { font-size: 32px; font-weight: 700; color: var(--gold); }\n    .btn {\n      display: inline-flex;\n      align-items: center;\n      gap: 6px;\n      background: var(--primary);\n      color: #fff;\n      border: none;\n      padding: 10px 20px;\n      border-radius: 30px;\n      font-weight: 600;\n      cursor: pointer;\n      transition: all 0.2s;\n      font-size: 14px;\n    }\n    .btn-gold { background: var(--gold); color: var(--primary); }\n    .btn-outline {\n      background: transparent;\n      border: 1.5px solid var(--primary);\n      color: var(--primary);\n    }\n    .btn:hover { opacity: 0.9; transform: translateY(-1px); }\n    .btn-danger { background: #dc3545; }\n    .form-group { margin-bottom: 16px; }\n    .form-group label {\n      display: block;\n      font-weight: 600;\n      margin-bottom: 6px;\n      color: var(--primary);\n    }\n    .form-control {\n      width: 100%;\n      padding: 10px 14px;\n      border: 1.5px solid #e2e8f0;\n      border-radius: 10px;\n      font-size: 15px;\n      transition: border 0.2s;\n    }\n    .form-control:focus { border-color: var(--gold); outline: none; }\n    .row { display: flex; gap: 20px; flex-wrap: wrap; }\n    .col { flex: 1; min-width: 200px; }\n    table {\n      width: 100%;\n      border-collapse: collapse;\n      margin-top: 12px;\n    }\n    th, td {\n      padding: 12px 14px;\n      border-bottom: 1px solid #e2e8f0;\n      text-align: left;\n      font-size: 14px;\n    }\n    th { background: #f8fafc; color: var(--primary); font-weight: 600; }\n    .badge {\n      display: inline-block;\n      padding: 2px 10px;\n      border-radius: 12px;\n      font-size: 12px;\n      font-weight: 600;\n    }\n    .badge-success { background: #d4edda; color: #155724; }\n    .badge-warning { background: #fff3cd; color: #856404; }\n    .badge-danger { background: #f8d7da; color: #721c24; }\n    .notification {\n      background: #fff3cd;\n      border-left: 4px solid #ffc107;\n      padding: 12px;\n      border-radius: 8px;\n      margin-bottom: 12px;\n      display: flex;\n      justify-content: space-between;\n      align-items: center;\n    }\n    .auth-container {\n      max-width: 500px;\n      margin: 40px auto;\n      background: var(--card-bg);\n      border-radius: var(--radius);\n      padding: 32px;\n      box-shadow: var(--shadow);\n    }\n    .terms-box {\n      display: flex;\n      align-items: center;\n      gap: 8px;\n      margin: 16px 0;\n      font-size: 14px;\n    }\n    .terms-box input[type=\"checkbox\"] { width: 18px; height: 18px; cursor: pointer; }\n    @media (max-width: 768px) {\n      .sidebar { transform: translateX(-100%); }\n      .sidebar.open { transform: translateX(0); }\n      .main { margin-left: 0; }\n      .mobile-header { display: flex; }\n      .row { flex-direction: column; }\n    }\n  <\/style>\n<\/head>\n<body>\n  <!-- Sidebar -->\n  <aside class=\"sidebar\" id=\"sidebar\">\n    <div class=\"logo\">ADASE <span>ADS<\/span><\/div>\n    <nav>\n      <a href=\"#dashboard\" class=\"active\" data-section=\"dashboard\">\ud83d\udcca Dashboard<\/a>\n      <a href=\"#wallet\" data-section=\"wallet\">\ud83d\udcb0 Wallet<\/a>\n      <a href=\"#invest\" data-section=\"invest\">\ud83d\udcdc Buy Notes<\/a>\n      <a href=\"#history-invest\" data-section=\"history-invest\">\ud83c\udfe6 Investments<\/a>\n      <a href=\"#history-tx\" data-section=\"history-tx\">\ud83e\uddfe Transactions<\/a>\n      <a href=\"#\" id=\"logoutSidebar\">\ud83d\udeaa Logout<\/a>\n      <a href=\"#\" id=\"adminSidebarLink\" style=\"margin-top:20px; border-top:1px solid rgba(255,255,255,0.2); padding-top:15px;\">\ud83d\udd10 Admin<\/a>\n    <\/nav>\n  <\/aside>\n\n  <!-- Mobile header -->\n  <div class=\"mobile-header\">\n    <button class=\"menu-toggle\" id=\"menuToggle\">\u2630<\/button>\n    <span style=\"font-weight:600;\">Adase Dashboard<\/span>\n  <\/div>\n\n  <!-- Main content -->\n  <main class=\"main\" id=\"mainContent\">\n    <!-- ========== USER AUTH ========== -->\n    <div id=\"authSection\">\n      <div class=\"auth-container\">\n        <h2 style=\"text-align:center;\">Welcome<\/h2>\n        <div style=\"display:flex; gap:8px; justify-content:center; margin-bottom:20px;\">\n          <button class=\"btn\" onclick=\"showAuthTab('login')\">Login<\/button>\n          <button class=\"btn btn-outline\" onclick=\"showAuthTab('register')\">Register<\/button>\n        <\/div>\n        <!-- LOGIN -->\n        <div id=\"loginForm\">\n          <div class=\"form-group\"><label>Email<\/label><input type=\"email\" class=\"form-control\" id=\"loginEmail\" placeholder=\"you@example.com\"><\/div>\n          <div class=\"form-group\"><label>Password<\/label><input type=\"password\" class=\"form-control\" id=\"loginPassword\" placeholder=\"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\"><\/div>\n          <button class=\"btn btn-gold\" onclick=\"login()\" style=\"width:100%;\">Login<\/button>\n        <\/div>\n        <!-- REGISTER -->\n        <div id=\"registerForm\" style=\"display:none;\">\n          <div class=\"row\">\n            <div class=\"col\"><div class=\"form-group\"><label>First Name *<\/label><input type=\"text\" class=\"form-control\" id=\"regFirstName\" required=\"\"><\/div><\/div>\n            <div class=\"col\"><div class=\"form-group\"><label>Last Name *<\/label><input type=\"text\" class=\"form-control\" id=\"regLastName\" required=\"\"><\/div><\/div>\n          <\/div>\n          <div class=\"form-group\"><label>Email *<\/label><input type=\"email\" class=\"form-control\" id=\"regEmail\" required=\"\"><\/div>\n          <div class=\"row\">\n            <div class=\"col\"><div class=\"form-group\"><label>Country *<\/label><input type=\"text\" class=\"form-control\" id=\"regCountry\" required=\"\"><\/div><\/div>\n            <div class=\"col\"><div class=\"form-group\"><label>Mobile Number *<\/label><input type=\"text\" class=\"form-control\" id=\"regMobile\" required=\"\"><\/div><\/div>\n          <\/div>\n          <div class=\"form-group\"><label>NIN \/ Passport Number *<\/label><input type=\"text\" class=\"form-control\" id=\"regNIN\" required=\"\"><\/div>\n          <div class=\"row\">\n            <div class=\"col\"><div class=\"form-group\"><label>Password *<\/label><input type=\"password\" class=\"form-control\" id=\"regPassword\" required=\"\"><\/div><\/div>\n            <div class=\"col\"><div class=\"form-group\"><label>Confirm Password *<\/label><input type=\"password\" class=\"form-control\" id=\"regConfirmPassword\" required=\"\"><\/div><\/div>\n          <\/div>\n          <div class=\"terms-box\">\n            <input type=\"checkbox\" id=\"acceptTerms\" required=\"\">\n            <label for=\"acceptTerms\">I accept the <a href=\"\/terms\" target=\"_blank\" style=\"color:var(--gold);\">Terms and Conditions<\/a><\/label>\n          <\/div>\n          <button class=\"btn btn-gold\" onclick=\"register()\" style=\"width:100%;\">Register<\/button>\n        <\/div>\n      <\/div>\n    <\/div>\n\n    <!-- ========== USER DASHBOARD ========== -->\n    <div id=\"dashboardSections\" style=\"display:none;\">\n      <section class=\"section active\" id=\"section-dashboard\">\n        <h2>Dashboard<\/h2>\n        <div class=\"row\">\n          <div class=\"col\"><p style=\"color:#666;\">Wallet Balance<\/p><div class=\"wallet-balance\" id=\"balanceDisplay\">0 UGX<\/div><\/div>\n          <div class=\"col\" style=\"text-align:right;\"><span id=\"userNameDisplay\"><\/span><\/div>\n        <\/div>\n        <div style=\"margin-top:20px;\">\n          <button class=\"btn btn-gold\" onclick=\"switchSection('wallet')\">\ud83d\udcb5 Add Money<\/button>\n          <button class=\"btn\" onclick=\"switchSection('invest')\">\ud83d\udcdc Buy Notes<\/button>\n        <\/div>\n        <h3 style=\"margin-top:24px;\">\ud83d\udd14 Notifications<\/h3>\n        <div id=\"notificationsPreview\"><\/div>\n      <\/section>\n\n      <section class=\"section\" id=\"section-wallet\">\n        <h2>Wallet<\/h2>\n        <div class=\"row\">\n          <div class=\"col\"><h3>Add Money (Top\u2011up)<\/h3><div class=\"form-group\"><label>Amount (UGX)<\/label><input type=\"number\" class=\"form-control\" id=\"topupAmount\" placeholder=\"e.g., 500000\"><\/div><button class=\"btn btn-gold\" onclick=\"submitTopup()\">Request Top\u2011up<\/button><\/div>\n          <div class=\"col\"><h3>Withdraw<\/h3><div class=\"form-group\"><label>Amount (UGX)<\/label><input type=\"number\" class=\"form-control\" id=\"withdrawAmount\" placeholder=\"e.g., 200000\"><\/div><button class=\"btn btn-outline\" onclick=\"submitWithdraw()\">Request Withdrawal<\/button><\/div>\n        <\/div>\n        <div style=\"margin-top:30px;\">\n          <h3>Transfer to Another User<\/h3>\n          <div class=\"row\">\n            <div class=\"col\"><div class=\"form-group\"><label>Recipient Email<\/label><input type=\"email\" class=\"form-control\" id=\"transferEmail\" placeholder=\"user@example.com\"><\/div><\/div>\n            <div class=\"col\"><div class=\"form-group\"><label>Amount (UGX)<\/label><input type=\"number\" class=\"form-control\" id=\"transferAmount\" placeholder=\"e.g., 100000\"><\/div><\/div>\n          <\/div>\n          <button class=\"btn\" onclick=\"submitTransfer()\">Request Transfer<\/button>\n        <\/div>\n      <\/section>\n\n      <section class=\"section\" id=\"section-invest\">\n        <h2>Buy Convertible Notes<\/h2>\n        <p style=\"color:#666; margin-bottom:20px;\">Minimum 100,000 UGX. Amount deducted from wallet on purchase.<\/p>\n        <div class=\"row\">\n          <div class=\"col\"><div class=\"form-group\"><label>Investment Amount (UGX)<\/label><input type=\"number\" class=\"form-control\" id=\"investAmount\" min=\"100000\" placeholder=\"e.g., 1000000\"><\/div><\/div>\n          <div class=\"col\" style=\"display:flex; align-items:flex-end;\"><button class=\"btn btn-gold\" onclick=\"buyAndDownload()\" style=\"width:100%;\">Buy &amp; Download Certificate<\/button><\/div>\n        <\/div>\n        <p id=\"investMsg\" style=\"margin-top:12px;\"><\/p>\n      <\/section>\n\n      <section class=\"section\" id=\"section-history-invest\">\n        <h2>Investment History<\/h2>\n        <table><thead><tr><th>Certificate No<\/th><th>Principal<\/th><th>Date<\/th><th>Download<\/th><\/tr><\/thead><tbody id=\"investHistoryBody\"><tr><td colspan=\"4\">Loading&#8230;<\/td><\/tr><\/tbody><\/table>\n      <\/section>\n\n      <section class=\"section\" id=\"section-history-tx\">\n        <h2>Wallet Transactions<\/h2>\n        <table><thead><tr><th>Type<\/th><th>Amount<\/th><th>Status<\/th><th>Date<\/th><th>Note<\/th><\/tr><\/thead><tbody id=\"txHistoryBody\"><tr><td colspan=\"5\">Loading&#8230;<\/td><\/tr><\/tbody><\/table>\n      <\/section>\n    <\/div>\n\n    <!-- ========== ADMIN PANEL ========== -->\n    <div id=\"adminPanel\" style=\"display:none;\">\n      <!-- Admin Navigation Buttons -->\n      <div style=\"margin-bottom:20px; display:flex; gap:10px; flex-wrap:wrap; align-items:center;\">\n        <button class=\"btn\" onclick=\"switchToUserView()\">\u2b05 User Dashboard<\/button>\n        <button class=\"btn\" onclick=\"switchSection('admin-requests')\">\ud83d\udd01 Requests<\/button>\n        <button class=\"btn\" onclick=\"switchSection('admin-users')\">\ud83d\udc65 Users<\/button>\n        <button class=\"btn btn-outline\" onclick=\"switchSection('admin-config')\">\u2699\ufe0f Config<\/button>\n        <button class=\"btn\" onclick=\"switchSection('admin-notify')\">\ud83d\udce8 Notify<\/button>\n        <button class=\"btn btn-danger\" onclick=\"adminLogout()\" style=\"margin-left:auto;\">Logout Admin<\/button>\n      <\/div>\n\n      <!-- Admin Sections (proper IDs) -->\n      <section class=\"section active\" id=\"section-admin-requests\">\n        <h2>Pending Requests<\/h2>\n        <button class=\"btn\" onclick=\"loadAdminRequests()\">Refresh<\/button>\n        <div id=\"adminRequestsContainer\"><\/div>\n      <\/section>\n\n      <section class=\"section\" id=\"section-admin-users\">\n        <h2>Registered Users<\/h2>\n        <button class=\"btn\" onclick=\"loadAdminUsers()\">Refresh<\/button>\n        <div id=\"adminUsersContainer\"><\/div>\n      <\/section>\n\n      <!-- Backend Configuration Section -->\n      <section class=\"section\" id=\"section-admin-config\">\n        <h2>\u2699\ufe0f Backend Configuration<\/h2>\n        <p style=\"color:#666; margin-bottom:16px;\">Change database, secret keys, and admin credentials. Restart the server after saving for some changes to take effect.<\/p>\n        <div class=\"row\">\n          <div class=\"col\">\n            <div class=\"form-group\"><label>MongoDB URI<\/label><input type=\"text\" class=\"form-control\" id=\"configMongoUri\" placeholder=\"mongodb+srv:\/\/...\"><\/div>\n          <\/div>\n          <div class=\"col\">\n            <div class=\"form-group\"><label>JWT Secret<\/label><input type=\"text\" class=\"form-control\" id=\"configJwtSecret\" placeholder=\"strong random secret\"><\/div>\n          <\/div>\n        <\/div>\n        <div class=\"row\">\n          <div class=\"col\">\n            <div class=\"form-group\"><label>Admin Email<\/label><input type=\"email\" class=\"form-control\" id=\"configAdminEmail\" placeholder=\"shares@cashchat.se\"><\/div>\n          <\/div>\n          <div class=\"col\">\n            <div class=\"form-group\"><label>New Admin Password<\/label><input type=\"password\" class=\"form-control\" id=\"configAdminPassword\" placeholder=\"Leave blank to keep current\"><\/div>\n          <\/div>\n        <\/div>\n        <button class=\"btn btn-gold\" onclick=\"saveConfig()\">\ud83d\udcbe Save Configuration<\/button>\n        <p id=\"configMsg\" style=\"margin-top:12px;\"><\/p>\n      <\/section>\n\n      <!-- Send Notification Section -->\n      <section class=\"section\" id=\"section-admin-notify\">\n        <h2>Send Notification to User<\/h2>\n        <div class=\"row\">\n          <div class=\"col\"><input type=\"text\" class=\"form-control\" id=\"notifyUserId\" placeholder=\"User ID\"><\/div>\n          <div class=\"col\"><input type=\"text\" class=\"form-control\" id=\"notifyMsg\" placeholder=\"Message (e.g., MTN number)\"><\/div>\n        <\/div>\n        <button class=\"btn\" onclick=\"adminSendNotification()\" style=\"margin-top:10px;\">Send<\/button>\n      <\/section>\n    <\/div>\n\n    <!-- ========== ADMIN LOGIN ========== -->\n    <div id=\"adminLoginSection\" style=\"display:none;\">\n      <div class=\"auth-container\" style=\"max-width:400px; margin:80px auto;\">\n        <h2 style=\"text-align:center;\">Admin Login<\/h2>\n        <div class=\"form-group\"><label>Password<\/label><input type=\"password\" class=\"form-control\" id=\"adminPassword\" placeholder=\"Admin password\"><\/div>\n        <button class=\"btn btn-gold\" onclick=\"adminLogin()\" style=\"width:100%;\">Login<\/button>\n        <p style=\"text-align:center; margin-top:15px;\"><a href=\"#\" onclick=\"switchToUserView()\" style=\"color:var(--gold);\">\u2190 Back to User Dashboard<\/a><\/p>\n      <\/div>\n    <\/div>\n  <\/main>\n\n  <script>\n    \/\/ ==================== CONFIGURATION ====================\n    \/\/ Set this to your backend URL. For same\u2011origin, use '\/dir\/backend\/api'\n    const API_BASE = '\/dir\/backend\/api';   \/\/ e.g., 'http:\/\/localhost:3000\/api' for local dev\n\n    let token = localStorage.getItem('token');\n    let adminToken = localStorage.getItem('adminToken');\n    let currentUser = null;\n\n    \/\/ Helpers\n    function $(sel) { return document.querySelector(sel); }\n    function $$(sel) { return document.querySelectorAll(sel); }\n\n    function switchSection(name) {\n      \/\/ Deactivate all sections\n      $$('.section').forEach(s => s.classList.remove('active'));\n      \/\/ Activate the target section\n      const target = document.getElementById(`section-${name}`);\n      if (target) target.classList.add('active');\n      \/\/ Highlight sidebar link (only for user sections)\n      if (!name.startsWith('admin-')) {\n        $$('.sidebar nav a').forEach(a => a.classList.remove('active'));\n        const link = document.querySelector(`.sidebar nav a[data-section=\"${name}\"]`);\n        if (link) link.classList.add('active');\n      }\n      document.getElementById('sidebar').classList.remove('open');\n      \/\/ Load data on demand\n      if (name === 'history-invest') fetchInvestments();\n      if (name === 'history-tx') fetchTransactions();\n      if (name === 'admin-requests') loadAdminRequests();\n      if (name === 'admin-users') loadAdminUsers();\n      if (name === 'admin-config') loadConfig();\n    }\n\n    function showAuthTab(tab) {\n      $('#loginForm').style.display = (tab === 'login') ? 'block' : 'none';\n      $('#registerForm').style.display = (tab === 'register') ? 'block' : 'none';\n    }\n\n    \/\/ Generic API call\n    async function apiCall(url, method = 'GET', body = null, isAdmin = false) {\n      const headers = { 'Content-Type': 'application\/json' };\n      if (isAdmin && adminToken) headers['x-admin-token'] = adminToken;\n      else if (token) headers['x-auth-token'] = token;\n      const options = { method, headers };\n      if (body) options.body = JSON.stringify(body);\n      const res = await fetch(API_BASE + url, options);\n      const data = await res.json();\n      if (!res.ok) throw new Error(data.msg || 'Request failed');\n      return data;\n    }\n\n    \/\/ ==================== USER AUTH ====================\n    async function login() {\n      const email = $('#loginEmail').value.trim();\n      const password = $('#loginPassword').value;\n      try {\n        const data = await apiCall('\/users\/login', 'POST', { email, password });\n        token = data.token;\n        localStorage.setItem('token', token);\n        currentUser = data.user;\n        showUserDashboard();\n      } catch (e) { alert(e.message); }\n    }\n\n    async function register() {\n      const fields = {\n        firstName: $('#regFirstName').value.trim(),\n        lastName: $('#regLastName').value.trim(),\n        email: $('#regEmail').value.trim(),\n        country: $('#regCountry').value.trim(),\n        mobile: $('#regMobile').value.trim(),\n        nin: $('#regNIN').value.trim(),\n        password: $('#regPassword').value,\n        confirmPassword: $('#regConfirmPassword').value,\n      };\n      if (!fields.firstName || !fields.lastName || !fields.email || !fields.country || !fields.mobile || !fields.nin || !fields.password || !fields.confirmPassword) {\n        return alert('Please fill in all fields.');\n      }\n      if (fields.password !== fields.confirmPassword) return alert('Passwords do not match.');\n      if (!$('#acceptTerms').checked) return alert('You must accept the Terms and Conditions.');\n\n      try {\n        const data = await apiCall('\/users\/register', 'POST', {\n          firstName: fields.firstName,\n          lastName: fields.lastName,\n          email: fields.email,\n          country: fields.country,\n          mobile: fields.mobile,\n          nin: fields.nin,\n          password: fields.password\n        });\n        token = data.token;\n        localStorage.setItem('token', token);\n        currentUser = data.user;\n        showUserDashboard();\n      } catch (e) { alert(e.message); }\n    }\n\n    function showUserDashboard() {\n      $('#authSection').style.display = 'none';\n      $('#dashboardSections').style.display = 'block';\n      $('#adminPanel').style.display = 'none';\n      $('#adminLoginSection').style.display = 'none';\n      $('#userNameDisplay').textContent = currentUser.name;\n      updateBalance(currentUser.walletBalance);\n      fetchNotifications();\n      fetchInvestments();\n      fetchTransactions();\n      switchSection('dashboard');\n    }\n\n    function userLogout() {\n      localStorage.removeItem('token');\n      token = null;\n      currentUser = null;\n      location.reload();\n    }\n\n    \/\/ ==================== DATA FETCHING ====================\n    function updateBalance(bal) {\n      $('#balanceDisplay').textContent = bal.toLocaleString() + ' UGX';\n    }\n\n    async function refreshUser() {\n      const u = await apiCall('\/users\/me');\n      currentUser = u;\n      updateBalance(u.walletBalance);\n    }\n\n    async function fetchNotifications() {\n      try {\n        const notifs = await apiCall('\/notifications');\n        const container = $('#notificationsPreview');\n        container.innerHTML = notifs.length\n          ? notifs.map(n => `<div class=\"notification\"><span>${n.message} <small>(${new Date(n.createdAt).toLocaleString()})<\/small><\/span><button class=\"btn\" style=\"padding:4px 10px;\" onclick=\"dismissNotif('${n._id}')\">Dismiss<\/button><\/div>`).join('')\n          : '<p>No new notifications<\/p>';\n      } catch (e) {}\n    }\n\n    async function dismissNotif(id) {\n      await apiCall('\/notifications\/read\/' + id, 'POST');\n      fetchNotifications();\n    }\n\n    async function fetchInvestments() {\n      try {\n        const invs = await apiCall('\/investments');\n        $('#investHistoryBody').innerHTML = invs.map(i =>\n          `<tr><td>${i.certificateNumber}<\/td><td>${i.principal.toLocaleString()} UGX<\/td><td>${new Date(i.issuedAt).toLocaleDateString()}<\/td><td><button class=\"btn\" onclick=\"downloadExistingCert('${i.certificateNumber}',${i.principal})\">Download<\/button><\/td><\/tr>`\n        ).join('') || '<tr><td colspan=\"4\">No investments yet.<\/td><\/tr>';\n      } catch (e) { $('#investHistoryBody').innerHTML = '<tr><td colspan=\"4\">Error loading<\/td><\/tr>'; }\n    }\n\n    async function fetchTransactions() {\n      try {\n        const txns = await apiCall('\/transactions');\n        $('#txHistoryBody').innerHTML = txns.map(t =>\n          `<tr><td>${t.type}<\/td><td>${t.amount.toLocaleString()} UGX<\/td><td><span class=\"badge ${t.status==='approved'?'badge-success':t.status==='pending'?'badge-warning':'badge-danger'}\">${t.status}<\/span><\/td><td>${new Date(t.createdAt).toLocaleString()}<\/td><td>${t.description||''}<\/td><\/tr>`\n        ).join('') || '<tr><td colspan=\"5\">No transactions<\/td><\/tr>';\n      } catch (e) { $('#txHistoryBody').innerHTML = '<tr><td colspan=\"5\">Error loading<\/td><\/tr>'; }\n    }\n\n    \/\/ ==================== WALLET ACTIONS ====================\n    async function submitTopup() {\n      const amount = parseFloat($('#topupAmount').value);\n      if (!amount || amount <= 0) return alert('Enter a valid amount');\n      await apiCall('\/wallet\/topup', 'POST', { amount });\n      alert('Top-up request submitted. Admin will review.');\n      $('#topupAmount').value = '';\n    }\n\n    async function submitWithdraw() {\n      const amount = parseFloat($('#withdrawAmount').value);\n      if (!amount || amount <= 0) return alert('Enter a valid amount');\n      await apiCall('\/wallet\/withdraw', 'POST', { amount });\n      alert('Withdrawal request submitted.');\n      $('#withdrawAmount').value = '';\n    }\n\n    async function submitTransfer() {\n      const toEmail = $('#transferEmail').value.trim();\n      const amount = parseFloat($('#transferAmount').value);\n      if (!toEmail || !amount || amount <= 0) return alert('Enter valid email and amount');\n      const res = await apiCall('\/wallet\/transfer', 'POST', { toEmail, amount });\n      alert(res.msg);\n      $('#transferEmail').value = '';\n      $('#transferAmount').value = '';\n    }\n\n    \/\/ ==================== INVEST &#038; CERTIFICATE ====================\n    async function buyAndDownload() {\n      const principal = parseFloat($('#investAmount').value);\n      if (principal < 100000) return alert('Minimum investment is 100,000 UGX');\n      try {\n        const data = await apiCall('\/invest', 'POST', { principal });\n        alert(`Investment successful! Certificate: ${data.certificateNumber}`);\n        await refreshUser();\n        fetchInvestments();\n        fetchTransactions();\n        generateCertificate(data.certificateNumber, principal, currentUser.name);\n        $('#investAmount').value = '';\n      } catch (e) { alert(e.message); }\n    }\n\n    function downloadExistingCert(certNumber, amount) {\n      generateCertificate(certNumber, amount, currentUser.name);\n    }\n\n    async function generateCertificate(certNumber, amount, name) {\n      const issueDate = new Date().toISOString().split('T')[0];\n      const maturity = new Date(new Date().setFullYear(new Date().getFullYear() + 3)).toISOString().split('T')[0];\n      const wrapper = document.createElement('div');\n      wrapper.style.position = 'absolute';\n      wrapper.style.left = '-9999px';\n      wrapper.innerHTML = `\n        <div style=\"width:800px;padding:40px;background:#fefdf8;border:6px double #0a1f44;font-family:Inter,sans-serif;\">\n          <div style=\"text-align:center;font-size:28px;font-weight:700;color:#0a1f44;\">ADASE ADS LTD<\/div>\n          <div style=\"text-align:center;font-size:20px;color:#c49a2b;margin:8px 0 20px;\">Convertible Note Certificate<\/div>\n          <p style=\"font-size:16px;\">This certifies that <strong>${name}<\/strong> has invested <strong>UGX ${amount.toLocaleString()}<\/strong> on <strong>${issueDate}<\/strong>.<\/p>\n          <table style=\"width:100%;margin:20px 0;font-size:14px;border-collapse:collapse;\">\n            <tr><td style=\"padding:8px 0;border-bottom:1px dotted #ccc;\">Certificate No<\/td><td style=\"font-weight:bold;\">${certNumber}<\/td><\/tr>\n            <tr><td style=\"padding:8px 0;border-bottom:1px dotted #ccc;\">Interest Rate<\/td><td>17% p.a.<\/td><\/tr>\n            <tr><td style=\"padding:8px 0;border-bottom:1px dotted #ccc;\">Maturity<\/td><td>${maturity}<\/td><\/tr>\n            <tr><td style=\"padding:8px 0;border-bottom:1px dotted #ccc;\">Conversion Discount<\/td><td>20%<\/td><\/tr>\n          <\/table>\n          <p style=\"margin-top:32px;font-style:italic;\">Authorized Signatory<\/p>\n        <\/div>\n      `;\n      document.body.appendChild(wrapper);\n      const canvas = await html2canvas(wrapper.firstChild, { scale: 2 });\n      document.body.removeChild(wrapper);\n      const link = document.createElement('a');\n      link.download = `Adase_Note_${certNumber}.png`;\n      link.href = canvas.toDataURL();\n      link.click();\n    }\n\n    \/\/ ==================== ADMIN ====================\n    function showAdminLoginOrPanel() {\n      if (adminToken) {\n        showAdminPanel();\n      } else {\n        $('#authSection').style.display = 'none';\n        $('#dashboardSections').style.display = 'none';\n        $('#adminPanel').style.display = 'none';\n        $('#adminLoginSection').style.display = 'block';\n      }\n    }\n\n    async function adminLogin() {\n      const password = $('#adminPassword').value;\n      try {\n        const data = await apiCall('\/admin\/login', 'POST', { email: 'shares@cashchat.se', password }, true);\n        adminToken = data.token;\n        localStorage.setItem('adminToken', adminToken);\n        showAdminPanel();\n      } catch (e) { alert('Admin login failed'); }\n    }\n\n    function showAdminPanel() {\n      $('#authSection').style.display = 'none';\n      $('#dashboardSections').style.display = 'none';\n      $('#adminPanel').style.display = 'block';\n      $('#adminLoginSection').style.display = 'none';\n      \/\/ Load initial admin data\n      switchSection('admin-requests');\n    }\n\n    function adminLogout() {\n      localStorage.removeItem('adminToken');\n      adminToken = null;\n      if (token) showUserDashboard();\n      else location.reload();\n    }\n\n    function switchToUserView() {\n      if (token) {\n        showUserDashboard();\n      } else {\n        $('#authSection').style.display = 'block';\n        $('#dashboardSections').style.display = 'none';\n        $('#adminPanel').style.display = 'none';\n        $('#adminLoginSection').style.display = 'none';\n      }\n    }\n\n    \/\/ ----------------- Admin Data Loading -----------------\n    async function loadAdminRequests() {\n      try {\n        const res = await apiCall('\/admin\/requests', 'GET', null, true);\n        const { topups, withdraws, transfers } = res;\n        let html = '<h3>Top\u2011ups<\/h3>' + renderAdminTable(topups, 'topup') +\n                   '<h3>Withdrawals<\/h3>' + renderAdminTable(withdraws, 'withdraw') +\n                   '<h3>Transfers<\/h3>' + renderAdminTable(transfers, 'transfer');\n        $('#adminRequestsContainer').innerHTML = html;\n      } catch (e) { $('#adminRequestsContainer').innerHTML = 'Error loading requests.'; }\n    }\n\n    function renderAdminTable(items, type) {\n      if (!items.length) return '<p>None<\/p>';\n      let html = '<table><thead><tr>';\n      if (type === 'transfer') html += '<th>From<\/th><th>To<\/th>';\n      else html += '<th>User<\/th>';\n      html += '<th>Amount<\/th><th>Status<\/th><th>Actions<\/th><\/tr><\/thead><tbody>';\n      items.forEach(item => {\n        const userName = item.userId ? (item.userId.firstName||'') + ' ' + (item.userId.lastName||'') : (item.fromUserId ? (item.fromUserId.firstName||'') + ' ' + (item.fromUserId.lastName||'') : '');\n        if (type === 'transfer') {\n          html += `<tr>\n            <td>${userName} (${item.fromUserId?.email})<\/td>\n            <td>${item.toUserEmail}<\/td>\n            <td>${item.amount}<\/td>\n            <td><span class=\"badge ${item.status==='approved'?'badge-success':item.status==='pending'?'badge-warning':'badge-danger'}\">${item.status}<\/span><\/td>\n            <td>${item.status==='pending' ? `<button class=\"btn\" onclick=\"adminApprove('transfer','${item._id}')\">Approve<\/button><button class=\"btn btn-outline\" onclick=\"adminDecline('transfer','${item._id}')\">Decline<\/button>` : ''}<\/td>\n          <\/tr>`;\n        } else {\n          html += `<tr>\n            <td>${userName} (${item.userId?.email})<\/td>\n            <td>${item.amount}<\/td>\n            <td><span class=\"badge ${item.status==='approved'?'badge-success':item.status==='pending'?'badge-warning':'badge-danger'}\">${item.status}<\/span><\/td>\n            <td>${item.status==='pending' ? `<button class=\"btn\" onclick=\"adminApprove('${type}','${item._id}')\">Approve<\/button><button class=\"btn btn-outline\" onclick=\"adminDecline('${type}','${item._id}')\">Decline<\/button><button class=\"btn\" onclick=\"adminRequestPayment('${item.userId?._id}')\">Req Payment<\/button>` : ''}<\/td>\n          <\/tr>`;\n        }\n      });\n      html += '<\/tbody><\/table>';\n      return html;\n    }\n\n    async function adminApprove(type, id) {\n      await apiCall(`\/admin\/${type}\/${id}`, 'POST', { status: 'approved' }, true);\n      loadAdminRequests();\n    }\n\n    async function adminDecline(type, id) {\n      await apiCall(`\/admin\/${type}\/${id}`, 'POST', { status: 'declined' }, true);\n      loadAdminRequests();\n    }\n\n    async function adminRequestPayment(userId) {\n      const msg = prompt('Enter message to request payment details (e.g., MTN number):');\n      if (msg) {\n        await apiCall(`\/admin\/notify\/${userId}`, 'POST', { message: msg }, true);\n        alert('Notification sent');\n      }\n    }\n\n    async function loadAdminUsers() {\n      try {\n        const users = await apiCall('\/admin\/users', 'GET', null, true);\n        let html = '<table><thead><tr><th>ID<\/th><th>Name<\/th><th>Email<\/th><th>Country<\/th><th>Mobile<\/th><th>NIN\/Passport<\/th><th>Wallet<\/th><th>Joined<\/th><\/tr><\/thead><tbody>';\n        users.forEach(u => {\n          html += `<tr>\n            <td>${u._id}<\/td>\n            <td>${u.firstName||''} ${u.lastName||''}<\/td>\n            <td>${u.email}<\/td>\n            <td>${u.country||''}<\/td>\n            <td>${u.mobile||''}<\/td>\n            <td>${u.nin||''}<\/td>\n            <td>${u.walletBalance.toLocaleString()} UGX<\/td>\n            <td>${new Date(u.createdAt).toLocaleDateString()}<\/td>\n          <\/tr>`;\n        });\n        html += '<\/tbody><\/table>';\n        $('#adminUsersContainer').innerHTML = html || '<p>No users found.<\/p>';\n      } catch (e) { $('#adminUsersContainer').innerHTML = 'Error loading users.'; }\n    }\n\n    async function adminSendNotification() {\n      const userId = $('#notifyUserId').value.trim();\n      const message = $('#notifyMsg').value.trim();\n      if (!userId || !message) return alert('Fill both fields');\n      await apiCall(`\/admin\/notify\/${userId}`, 'POST', { message }, true);\n      alert('Notification sent');\n    }\n\n    \/\/ ---------- Backend Configuration ----------\n    async function loadConfig() {\n      try {\n        const config = await apiCall('\/admin\/config', 'GET', null, true);\n        $('#configMongoUri').value = config.MONGODB_URI || '';\n        $('#configJwtSecret').value = config.JWT_SECRET || '';\n        $('#configAdminEmail').value = config.ADMIN_EMAIL || '';\n        $('#configAdminPassword').value = ''; \/\/ always clear for security\n      } catch (e) {\n        alert('Failed to load config');\n      }\n    }\n\n    async function saveConfig() {\n      const MONGODB_URI = $('#configMongoUri').value.trim();\n      const JWT_SECRET = $('#configJwtSecret').value.trim();\n      const ADMIN_EMAIL = $('#configAdminEmail').value.trim();\n      const ADMIN_PASSWORD_HASH = $('#configAdminPassword').value;\n      try {\n        await apiCall('\/admin\/config', 'POST', { MONGODB_URI, JWT_SECRET, ADMIN_EMAIL, ADMIN_PASSWORD_HASH }, true);\n        $('#configMsg').textContent = '\u2705 Configuration saved. Restart server if needed.';\n        $('#configAdminPassword').value = '';\n      } catch (e) {\n        $('#configMsg').textContent = '\u274c Failed to save.';\n      }\n    }\n\n    \/\/ ==================== INITIALIZATION ====================\n    document.querySelectorAll('.sidebar nav a[data-section]').forEach(a => {\n      a.addEventListener('click', e => {\n        e.preventDefault();\n        switchSection(a.dataset.section);\n      });\n    });\n    $('#logoutSidebar').addEventListener('click', e => {\n      e.preventDefault();\n      userLogout();\n    });\n    $('#adminSidebarLink').addEventListener('click', e => {\n      e.preventDefault();\n      showAdminLoginOrPanel();\n    });\n    $('#menuToggle').addEventListener('click', () => {\n      document.getElementById('sidebar').classList.toggle('open');\n    });\n\n    \/\/ Auto-login check\n    if (adminToken) {\n      apiCall('\/admin\/requests', 'GET', null, true)\n        .then(() => showAdminPanel())\n        .catch(() => { localStorage.removeItem('adminToken'); adminToken = null; });\n    } else if (token) {\n      apiCall('\/users\/me')\n        .then(u => { currentUser = u; showUserDashboard(); })\n        .catch(() => { localStorage.removeItem('token'); token = null; });\n    }\n\n    if (window.location.hash === '#admin') {\n      document.getElementById('authSection').style.display = 'none';\n      if (adminToken) showAdminPanel();\n      else document.getElementById('adminLoginSection').style.display = 'block';\n    }\n  <\/script>\n<\/body>\n<\/html>\n","protected":false},"excerpt":{"rendered":"<p>Adase Ads \u2013 Complete Dashboard (Offline \/ LocalStorage) ADASE ADS \ud83d\udcca Dashboard \ud83d\udcb0 Wallet \ud83d\udcdc Buy Notes \ud83c\udfe6 Investments \ud83e\uddfe Transactions \ud83d\udeaa Logout \ud83d\udd10 Admin \u2630 Adase Dashboard Welcome Login Register Email Password Login First Name * Last Name * Email * Country * Mobile Number * NIN \/ Passport Number * Password * Confirm [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"pagelayer_contact_templates":[],"_pagelayer_content":"","footnotes":""},"class_list":["post-197","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/cashchat.se\/dir\/wp-json\/wp\/v2\/pages\/197","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/cashchat.se\/dir\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/cashchat.se\/dir\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/cashchat.se\/dir\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/cashchat.se\/dir\/wp-json\/wp\/v2\/comments?post=197"}],"version-history":[{"count":5,"href":"https:\/\/cashchat.se\/dir\/wp-json\/wp\/v2\/pages\/197\/revisions"}],"predecessor-version":[{"id":203,"href":"https:\/\/cashchat.se\/dir\/wp-json\/wp\/v2\/pages\/197\/revisions\/203"}],"wp:attachment":[{"href":"https:\/\/cashchat.se\/dir\/wp-json\/wp\/v2\/media?parent=197"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}