<!-- Implementation Examples - Live Demos -->
<div class="top-content" id="admin_examples">
   <div class="row mb-4">
      <div class="col-12">
         <div class="bg-gradient rounded-4 p-4 mb-4" style="background: linear-gradient(135deg, #198754 0%, #146c43 100%);">
            <div class="d-flex align-items-center">
               <div class="bg-white bg-opacity-25 rounded-circle d-inline-flex align-items-center justify-content-center me-3" style="width: 60px; height: 60px;">
                  <i class="bi bi-play-circle display-6 text-white"></i>
               </div>
               <div>
                  <h2 class="display-6 fw-bold text-white mb-0">Live Implementation Examples</h2>
                  <p class="text-white-50 mb-0">Working demos connected to your Admin API - login and see real data</p>
               </div>
            </div>
         </div>
      </div>
   </div>

   <!-- Connection Setup -->
   <div class="card border-0 shadow-sm mb-4" id="example_login">
      <div class="card-header bg-dark text-white">
         <h5 class="mb-0"><i class="bi bi-plug me-2"></i>Step 1: Connect to your API</h5>
      </div>
      <div class="card-body">
         <div class="row g-3 align-items-end">
            <div class="col-md-5">
               <label class="form-label fw-bold">API Base URL</label>
               <input type="text" id="exApiBase" class="form-control" value="<?=base_url();?>" placeholder="https://your-domain.com/">
            </div>
            <div class="col-md-3">
               <label class="form-label fw-bold">Admin Username</label>
               <input type="text" id="exUsername" class="form-control" placeholder="admin">
            </div>
            <div class="col-md-3">
               <label class="form-label fw-bold">Admin Password</label>
               <input type="password" id="exPassword" class="form-control" placeholder="password">
            </div>
            <div class="col-md-1">
               <button class="btn btn-success w-100" id="exConnectBtn" onclick="exConnect()">
                  <i class="bi bi-lightning-fill"></i>
               </button>
            </div>
         </div>
         <div id="exConnectionStatus" class="mt-3"></div>
      </div>
   </div>
</div>

<!-- Example 1: Dashboard Stats -->
<div class="top-content" id="example_dashboard">
   <div class="card border-0 shadow-sm mb-4">
      <div class="card-header bg-white d-flex justify-content-between align-items-center">
         <h5 class="mb-0"><i class="bi bi-speedometer2 text-success me-2"></i>Dashboard Stats Cards</h5>
         <div>
            <span class="badge bg-success me-2" id="dashStatus">Waiting for connection</span>
            <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#dashCode">
               <i class="bi bi-code-slash me-1"></i>View Code
            </button>
         </div>
      </div>
      <!-- Live Demo -->
      <div class="card-body">
         <div class="row g-3" id="exDashCards">
            <div class="col-md-3">
               <div class="card border-0 bg-primary bg-opacity-10 text-center p-3 rounded-3">
                  <i class="bi bi-people display-6 text-primary"></i>
                  <h3 class="mt-2 mb-0 ex-dash-val" data-field="total_users">--</h3>
                  <small class="text-muted">Total Users</small>
               </div>
            </div>
            <div class="col-md-3">
               <div class="card border-0 bg-info bg-opacity-10 text-center p-3 rounded-3">
                  <i class="bi bi-cursor-fill display-6 text-info"></i>
                  <h3 class="mt-2 mb-0 ex-dash-val" data-field="today_clicks">--</h3>
                  <small class="text-muted">Today's Clicks</small>
               </div>
            </div>
            <div class="col-md-3">
               <div class="card border-0 bg-success bg-opacity-10 text-center p-3 rounded-3">
                  <i class="bi bi-cart-check display-6 text-success"></i>
                  <h3 class="mt-2 mb-0 ex-dash-val" data-field="today_sales">--</h3>
                  <small class="text-muted">Today's Sales</small>
               </div>
            </div>
            <div class="col-md-3">
               <div class="card border-0 bg-warning bg-opacity-10 text-center p-3 rounded-3">
                  <i class="bi bi-currency-dollar display-6 text-warning"></i>
                  <h3 class="mt-2 mb-0 ex-dash-val" data-field="total_revenue">--</h3>
                  <small class="text-muted">Total Revenue</small>
               </div>
            </div>
         </div>
         <div class="row g-3 mt-2">
            <div class="col-md-3">
               <div class="card border-0 bg-light text-center p-3 rounded-3">
                  <h5 class="mb-0 ex-dash-val" data-field="total_affiliates">--</h5>
                  <small class="text-muted">Affiliates</small>
               </div>
            </div>
            <div class="col-md-3">
               <div class="card border-0 bg-light text-center p-3 rounded-3">
                  <h5 class="mb-0 ex-dash-val" data-field="total_vendors">--</h5>
                  <small class="text-muted">Vendors</small>
               </div>
            </div>
            <div class="col-md-3">
               <div class="card border-0 bg-light text-center p-3 rounded-3">
                  <h5 class="mb-0 ex-dash-val" data-field="pending_users">--</h5>
                  <small class="text-muted">Pending Users</small>
               </div>
            </div>
            <div class="col-md-3">
               <div class="card border-0 bg-light text-center p-3 rounded-3">
                  <h5 class="mb-0 ex-dash-val" data-field="month_revenue" data-prefix="$">--</h5>
                  <small class="text-muted">Month Revenue</small>
               </div>
            </div>
         </div>
      </div>
      <!-- Code (collapsed) -->
      <div class="collapse" id="dashCode">
         <div class="card-footer bg-dark p-0">
            <div class="d-flex justify-content-between align-items-center px-3 py-2">
               <small class="text-white-50">dashboard-cards.html</small>
               <button class="btn btn-sm btn-outline-light copy-code-btn" data-target="dashCodeBlock">Copy</button>
            </div>
            <pre class="mb-0 p-3" id="dashCodeBlock" style="background:#1e1e1e;color:#d4d4d4;max-height:400px;overflow:auto;font-size:13px;"><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Admin Dashboard&lt;/title&gt;
  &lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"&gt;
&lt;/head&gt;
&lt;body class="bg-light p-4"&gt;

  &lt;div class="row g-3" id="statsCards"&gt;&lt;/div&gt;

  &lt;script&gt;
    const API_BASE = 'https://your-domain.com/';
    const TOKEN = 'your-admin-jwt-token';

    async function loadDashboard() {
      const res = await fetch(API_BASE + 'Admin_Api/dashboard', {
        headers: { 'Authorization': TOKEN }
      });
      const json = await res.json();

      if (json.status) {
        const d = json.data;
        const stats = [
          { label: 'Total Users',   value: d.total_users,   color: 'primary' },
          { label: 'Today Clicks',  value: d.today_clicks,  color: 'info' },
          { label: 'Today Sales',   value: d.today_sales,   color: 'success' },
          { label: 'Total Revenue', value: '$' + d.total_revenue, color: 'warning' },
          { label: 'Affiliates',    value: d.total_affiliates,    color: 'secondary' },
          { label: 'Vendors',       value: d.total_vendors,       color: 'secondary' },
          { label: 'Pending Users', value: d.pending_users,       color: 'danger' },
          { label: 'Month Revenue', value: '$' + d.month_revenue, color: 'dark' },
        ];

        document.getElementById('statsCards').innerHTML = stats.map(s =&gt;
          '&lt;div class="col-md-3"&gt;' +
          '&lt;div class="card border-0 bg-' + s.color + ' bg-opacity-10 text-center p-3"&gt;' +
          '&lt;h3&gt;' + s.value + '&lt;/h3&gt;' +
          '&lt;small class="text-muted"&gt;' + s.label + '&lt;/small&gt;' +
          '&lt;/div&gt;&lt;/div&gt;'
        ).join('');
      }
    }

    loadDashboard();
  &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre>
         </div>
      </div>
   </div>
</div>

<!-- Example 2: Users Table -->
<div class="top-content" id="example_users">
   <div class="card border-0 shadow-sm mb-4">
      <div class="card-header bg-white d-flex justify-content-between align-items-center">
         <h5 class="mb-0"><i class="bi bi-people text-success me-2"></i>Users Management</h5>
         <div>
            <span class="badge bg-success me-2" id="usersStatus">Waiting for connection</span>
            <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#usersCode">
               <i class="bi bi-code-slash me-1"></i>View Code
            </button>
         </div>
      </div>
      <!-- Live Demo -->
      <div class="card-body">
         <div class="d-flex gap-2 mb-3">
            <input type="text" id="exUserSearch" class="form-control form-control-sm" placeholder="Search users..." style="width:220px" oninput="exLoadUsers()">
            <select id="exUserStatus" class="form-select form-select-sm" style="width:130px" onchange="exLoadUsers()">
               <option value="all">All</option>
               <option value="active">Active</option>
               <option value="pending">Pending</option>
               <option value="blocked">Blocked</option>
            </select>
         </div>
         <div class="table-responsive">
            <table class="table table-hover table-sm mb-0">
               <thead class="table-light">
                  <tr><th>Name</th><th>Email</th><th>Balance</th><th>Clicks</th><th>Sales</th><th>Status</th><th>Action</th></tr>
               </thead>
               <tbody id="exUsersBody">
                  <tr><td colspan="7" class="text-center text-muted py-4"><i class="bi bi-plug me-1"></i>Connect to API first</td></tr>
               </tbody>
            </table>
         </div>
         <div class="d-flex justify-content-between align-items-center mt-2">
            <small class="text-muted" id="exUsersCount"></small>
            <div>
               <button class="btn btn-sm btn-outline-primary" id="exUserPrev" onclick="exUserPage(-1)" disabled>Previous</button>
               <button class="btn btn-sm btn-outline-primary" id="exUserNext" onclick="exUserPage(1)" disabled>Next</button>
            </div>
         </div>
      </div>
      <!-- Code -->
      <div class="collapse" id="usersCode">
         <div class="card-footer bg-dark p-0">
            <div class="d-flex justify-content-between align-items-center px-3 py-2">
               <small class="text-white-50">users-table.html</small>
               <button class="btn btn-sm btn-outline-light copy-code-btn" data-target="usersCodeBlock">Copy</button>
            </div>
            <pre class="mb-0 p-3" id="usersCodeBlock" style="background:#1e1e1e;color:#d4d4d4;max-height:400px;overflow:auto;font-size:13px;"><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Users Management&lt;/title&gt;
  &lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"&gt;
&lt;/head&gt;
&lt;body class="bg-light p-4"&gt;

  &lt;div class="d-flex gap-2 mb-3"&gt;
    &lt;input type="text" id="search" class="form-control" placeholder="Search users..." style="width:220px" oninput="loadUsers()"&gt;
    &lt;select id="statusFilter" class="form-select" style="width:130px" onchange="loadUsers()"&gt;
      &lt;option value="all"&gt;All&lt;/option&gt;
      &lt;option value="active"&gt;Active&lt;/option&gt;
      &lt;option value="pending"&gt;Pending&lt;/option&gt;
      &lt;option value="blocked"&gt;Blocked&lt;/option&gt;
    &lt;/select&gt;
  &lt;/div&gt;

  &lt;table class="table table-hover"&gt;
    &lt;thead&gt;&lt;tr&gt;&lt;th&gt;Name&lt;/th&gt;&lt;th&gt;Email&lt;/th&gt;&lt;th&gt;Balance&lt;/th&gt;&lt;th&gt;Status&lt;/th&gt;&lt;th&gt;Action&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;
    &lt;tbody id="usersTable"&gt;&lt;/tbody&gt;
  &lt;/table&gt;

  &lt;script&gt;
    const API_BASE = 'https://your-domain.com/';
    const TOKEN = 'your-admin-jwt-token';
    let page = 0;

    async function loadUsers() {
      const params = new URLSearchParams({
        start_from: page * 20,
        limit: 20,
        search: document.getElementById('search').value,
        status: document.getElementById('statusFilter').value
      });

      const res = await fetch(API_BASE + 'Admin_Api/users?' + params, {
        headers: { 'Authorization': TOKEN }
      });
      const json = await res.json();

      if (json.status) {
        document.getElementById('usersTable').innerHTML = json.data.users.map(u =&gt; {
          const badge = u.status === '1' ? 'success' : u.status === '0' ? 'warning' : 'danger';
          const label = u.status === '1' ? 'Active' : u.status === '0' ? 'Pending' : 'Blocked';
          return '&lt;tr&gt;' +
            '&lt;td&gt;' + u.firstname + ' ' + u.lastname + '&lt;/td&gt;' +
            '&lt;td&gt;' + u.email + '&lt;/td&gt;' +
            '&lt;td&gt;$' + u.balance + '&lt;/td&gt;' +
            '&lt;td&gt;&lt;span class="badge bg-' + badge + '"&gt;' + label + '&lt;/span&gt;&lt;/td&gt;' +
            '&lt;td&gt;&lt;button class="btn btn-sm btn-outline-primary" onclick="toggleUser(\'' + u.id + '\',\'' + u.status + '\')"&gt;Toggle&lt;/button&gt;&lt;/td&gt;' +
            '&lt;/tr&gt;';
        }).join('');
      }
    }

    async function toggleUser(userId, currentStatus) {
      const fd = new FormData();
      fd.append('user_id', userId);
      fd.append('status', currentStatus === '1' ? '2' : '1');

      await fetch(API_BASE + 'Admin_Api/update_user_status', {
        method: 'POST',
        headers: { 'Authorization': TOKEN },
        body: fd
      });
      loadUsers();
    }

    loadUsers();
  &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre>
         </div>
      </div>
   </div>
</div>

<!-- Example 3: Withdrawals -->
<div class="top-content" id="example_withdrawals">
   <div class="card border-0 shadow-sm mb-4">
      <div class="card-header bg-white d-flex justify-content-between align-items-center">
         <h5 class="mb-0"><i class="bi bi-cash-stack text-success me-2"></i>Withdrawal Requests</h5>
         <div>
            <select id="exWdFilter" class="form-select form-select-sm d-inline-block me-2" style="width:130px" onchange="exLoadWithdrawals()">
               <option value="unpaid">Pending</option>
               <option value="paid">Paid</option>
               <option value="rejected">Rejected</option>
            </select>
            <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#wdCode">
               <i class="bi bi-code-slash me-1"></i>View Code
            </button>
         </div>
      </div>
      <!-- Live Demo -->
      <div class="card-body p-0">
         <div class="table-responsive">
            <table class="table table-hover table-sm mb-0">
               <thead class="table-light">
                  <tr><th>User</th><th>Amount</th><th>Method</th><th>Date</th><th>Actions</th></tr>
               </thead>
               <tbody id="exWdBody">
                  <tr><td colspan="5" class="text-center text-muted py-4"><i class="bi bi-plug me-1"></i>Connect to API first</td></tr>
               </tbody>
            </table>
         </div>
      </div>
      <!-- Code -->
      <div class="collapse" id="wdCode">
         <div class="card-footer bg-dark p-0">
            <div class="d-flex justify-content-between align-items-center px-3 py-2">
               <small class="text-white-50">withdrawals.html</small>
               <button class="btn btn-sm btn-outline-light copy-code-btn" data-target="wdCodeBlock">Copy</button>
            </div>
            <pre class="mb-0 p-3" id="wdCodeBlock" style="background:#1e1e1e;color:#d4d4d4;max-height:400px;overflow:auto;font-size:13px;"><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Withdrawal Requests&lt;/title&gt;
  &lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"&gt;
&lt;/head&gt;
&lt;body class="bg-light p-4"&gt;

  &lt;select id="filter" class="form-select mb-3" style="width:150px" onchange="loadWd()"&gt;
    &lt;option value="unpaid"&gt;Pending&lt;/option&gt;
    &lt;option value="paid"&gt;Paid&lt;/option&gt;
    &lt;option value="rejected"&gt;Rejected&lt;/option&gt;
  &lt;/select&gt;

  &lt;table class="table table-hover"&gt;
    &lt;thead&gt;&lt;tr&gt;&lt;th&gt;User&lt;/th&gt;&lt;th&gt;Amount&lt;/th&gt;&lt;th&gt;Method&lt;/th&gt;&lt;th&gt;Date&lt;/th&gt;&lt;th&gt;Actions&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;
    &lt;tbody id="wdTable"&gt;&lt;/tbody&gt;
  &lt;/table&gt;

  &lt;script&gt;
    const API_BASE = 'https://your-domain.com/';
    const TOKEN = 'your-admin-jwt-token';

    async function loadWd() {
      const status = document.getElementById('filter').value;
      const res = await fetch(API_BASE + 'Admin_Api/withdrawals?status=' + status, {
        headers: { 'Authorization': TOKEN }
      });
      const json = await res.json();

      if (json.status) {
        document.getElementById('wdTable').innerHTML = json.data.requests.map(r =&gt; {
          const isPending = r.status === '0';
          const actions = isPending
            ? '&lt;button class="btn btn-sm btn-success me-1" onclick="wdAction(\'' + r.id + '\',\'paid\')"&gt;Approve&lt;/button&gt;' +
              '&lt;button class="btn btn-sm btn-danger" onclick="wdAction(\'' + r.id + '\',\'rejected\')"&gt;Reject&lt;/button&gt;'
            : '&lt;span class="badge bg-' + (r.status === '1' ? 'success' : 'danger') + '"&gt;' + (r.status === '1' ? 'Paid' : 'Rejected') + '&lt;/span&gt;';
          return '&lt;tr&gt;&lt;td&gt;' + (r.firstname || '') + ' ' + (r.lastname || '') + '&lt;/td&gt;' +
            '&lt;td&gt;$' + r.amount + '&lt;/td&gt;&lt;td&gt;' + (r.payment_method || '-') + '&lt;/td&gt;' +
            '&lt;td&gt;' + (r.created_at || '') + '&lt;/td&gt;&lt;td&gt;' + actions + '&lt;/td&gt;&lt;/tr&gt;';
        }).join('');
      }
    }

    async function wdAction(id, status) {
      const fd = new FormData();
      fd.append('request_id', id);
      fd.append('status', status);
      fd.append('admin_note', 'Processed via dashboard');

      await fetch(API_BASE + 'Admin_Api/update_withdrawal_status', {
        method: 'POST',
        headers: { 'Authorization': TOKEN },
        body: fd
      });
      loadWd();
    }

    loadWd();
  &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre>
         </div>
      </div>
   </div>
</div>

<!-- Example 4: Reports -->
<div class="top-content" id="example_reports">
   <div class="card border-0 shadow-sm mb-4">
      <div class="card-header bg-white d-flex justify-content-between align-items-center">
         <h5 class="mb-0"><i class="bi bi-graph-up text-success me-2"></i>Reports & Analytics</h5>
         <div class="d-flex gap-2 align-items-center">
            <input type="date" id="exDateFrom" class="form-control form-control-sm" style="width:150px" onchange="exLoadReports()">
            <input type="date" id="exDateTo" class="form-control form-control-sm" style="width:150px" onchange="exLoadReports()">
            <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#repCode">
               <i class="bi bi-code-slash me-1"></i>View Code
            </button>
         </div>
      </div>
      <!-- Live Demo -->
      <div class="card-body">
         <canvas id="exReportsChart" height="80"></canvas>
         <div class="row g-3 mt-3" id="exTopAffiliates"></div>
      </div>
      <!-- Code -->
      <div class="collapse" id="repCode">
         <div class="card-footer bg-dark p-0">
            <div class="d-flex justify-content-between align-items-center px-3 py-2">
               <small class="text-white-50">reports-chart.html</small>
               <button class="btn btn-sm btn-outline-light copy-code-btn" data-target="repCodeBlock">Copy</button>
            </div>
            <pre class="mb-0 p-3" id="repCodeBlock" style="background:#1e1e1e;color:#d4d4d4;max-height:400px;overflow:auto;font-size:13px;"><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Reports &amp; Analytics&lt;/title&gt;
  &lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"&gt;
  &lt;script src="https://cdn.jsdelivr.net/npm/chart.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body class="bg-light p-4"&gt;

  &lt;div class="d-flex gap-2 mb-3"&gt;
    &lt;input type="date" id="dateFrom" class="form-control" style="width:180px" onchange="loadReports()"&gt;
    &lt;input type="date" id="dateTo" class="form-control" style="width:180px" onchange="loadReports()"&gt;
  &lt;/div&gt;
  &lt;canvas id="chart" height="100"&gt;&lt;/canvas&gt;
  &lt;div class="row g-3 mt-3" id="topAffiliates"&gt;&lt;/div&gt;

  &lt;script&gt;
    const API_BASE = 'https://your-domain.com/';
    const TOKEN = 'your-admin-jwt-token';
    let chart = null;

    // Set default date range (current month)
    const now = new Date();
    document.getElementById('dateFrom').value = now.getFullYear() + '-' + String(now.getMonth()+1).padStart(2,'0') + '-01';
    document.getElementById('dateTo').value = now.toISOString().split('T')[0];

    async function loadReports() {
      const params = new URLSearchParams({
        date_from: document.getElementById('dateFrom').value,
        date_to: document.getElementById('dateTo').value
      });

      const res = await fetch(API_BASE + 'Admin_Api/reports?' + params, {
        headers: { 'Authorization': TOKEN }
      });
      const json = await res.json();

      if (json.status) {
        const d = json.data;
        const labels = [...new Set([
          ...d.clicks_by_day.map(c =&gt; c.date),
          ...d.sales_by_day.map(s =&gt; s.date)
        ])].sort();

        if (chart) chart.destroy();
        chart = new Chart(document.getElementById('chart'), {
          type: 'line',
          data: {
            labels: labels,
            datasets: [
              {
                label: 'Clicks',
                data: labels.map(l =&gt; { const f = d.clicks_by_day.find(c =&gt; c.date === l); return f ? +f.count : 0; }),
                borderColor: '#0d6efd', tension: 0.3, fill: true
              },
              {
                label: 'Sales',
                data: labels.map(l =&gt; { const f = d.sales_by_day.find(s =&gt; s.date === l); return f ? +f.count : 0; }),
                borderColor: '#198754', tension: 0.3, fill: true
              }
            ]
          },
          options: { responsive: true, scales: { y: { beginAtZero: true } } }
        });

        // Top Affiliates
        document.getElementById('topAffiliates').innerHTML = d.top_affiliates.map(a =&gt;
          '&lt;div class="col-md-4"&gt;&lt;div class="card p-2"&gt;&lt;strong&gt;' + a.firstname + ' ' + a.lastname + '&lt;/strong&gt;' +
          '&lt;small&gt;' + a.total_sales + ' sales &amp;middot; $' + (a.total_revenue || 0) + '&lt;/small&gt;&lt;/div&gt;&lt;/div&gt;'
        ).join('');
      }
    }

    loadReports();
  &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre>
         </div>
      </div>
   </div>
</div>

<!-- Example 5: Wallet -->
<div class="top-content" id="example_wallet">
   <div class="card border-0 shadow-sm mb-4">
      <div class="card-header bg-white d-flex justify-content-between align-items-center">
         <h5 class="mb-0"><i class="bi bi-wallet2 text-success me-2"></i>Wallet Overview</h5>
         <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#walCode">
            <i class="bi bi-code-slash me-1"></i>View Code
         </button>
      </div>
      <!-- Live Demo -->
      <div class="card-body">
         <div class="row g-3">
            <div class="col-md-4">
               <div class="card border-0 bg-success bg-opacity-10 p-3 rounded-3 text-center">
                  <small class="text-muted">Admin Balance</small>
                  <h3 class="text-success mb-0" id="exWalBalance">--</h3>
               </div>
            </div>
            <div class="col-md-4">
               <div class="card border-0 bg-primary bg-opacity-10 p-3 rounded-3 text-center">
                  <small class="text-muted">External Orders</small>
                  <h3 class="text-primary mb-0" id="exWalExternal">--</h3>
               </div>
            </div>
            <div class="col-md-4">
               <div class="card border-0 bg-info bg-opacity-10 p-3 rounded-3 text-center">
                  <small class="text-muted">Store Sales</small>
                  <h3 class="text-info mb-0" id="exWalStore">--</h3>
               </div>
            </div>
         </div>
         <div class="row g-3 mt-2">
            <div class="col-md-3">
               <div class="card border-0 bg-light p-2 rounded-3 text-center">
                  <small class="text-muted d-block">Integration Clicks</small>
                  <strong id="exWalIntClicks">--</strong>
               </div>
            </div>
            <div class="col-md-3">
               <div class="card border-0 bg-light p-2 rounded-3 text-center">
                  <small class="text-muted d-block">Store Clicks</small>
                  <strong id="exWalStoreClicks">--</strong>
               </div>
            </div>
            <div class="col-md-3">
               <div class="card border-0 bg-light p-2 rounded-3 text-center">
                  <small class="text-muted d-block">Action Clicks</small>
                  <strong id="exWalActionClicks">--</strong>
               </div>
            </div>
            <div class="col-md-3">
               <div class="card border-0 bg-light p-2 rounded-3 text-center">
                  <small class="text-muted d-block">Form Clicks</small>
                  <strong id="exWalFormClicks">--</strong>
               </div>
            </div>
         </div>
         <h6 class="mt-3 mb-2">Recent Transactions</h6>
         <div class="table-responsive">
            <table class="table table-sm table-hover mb-0">
               <thead class="table-light"><tr><th>User</th><th>Amount</th><th>Type</th><th>Status</th><th>Date</th></tr></thead>
               <tbody id="exWalTxBody">
                  <tr><td colspan="5" class="text-center text-muted py-3"><i class="bi bi-plug me-1"></i>Connect to API first</td></tr>
               </tbody>
            </table>
         </div>
      </div>
      <!-- Code -->
      <div class="collapse" id="walCode">
         <div class="card-footer bg-dark p-0">
            <div class="d-flex justify-content-between align-items-center px-3 py-2">
               <small class="text-white-50">wallet-overview.html</small>
               <button class="btn btn-sm btn-outline-light copy-code-btn" data-target="walCodeBlock">Copy</button>
            </div>
            <pre class="mb-0 p-3" id="walCodeBlock" style="background:#1e1e1e;color:#d4d4d4;max-height:400px;overflow:auto;font-size:13px;"><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Wallet Overview&lt;/title&gt;
  &lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"&gt;
&lt;/head&gt;
&lt;body class="bg-light p-4"&gt;

  &lt;div class="row g-3" id="walletStats"&gt;&lt;/div&gt;
  &lt;h5 class="mt-4"&gt;Recent Transactions&lt;/h5&gt;
  &lt;table class="table table-hover"&gt;
    &lt;thead&gt;&lt;tr&gt;&lt;th&gt;User&lt;/th&gt;&lt;th&gt;Amount&lt;/th&gt;&lt;th&gt;Type&lt;/th&gt;&lt;th&gt;Status&lt;/th&gt;&lt;th&gt;Date&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;
    &lt;tbody id="txTable"&gt;&lt;/tbody&gt;
  &lt;/table&gt;

  &lt;script&gt;
    const API_BASE = 'https://your-domain.com/';
    const TOKEN = 'your-admin-jwt-token';

    async function loadWallet() {
      const res = await fetch(API_BASE + 'Admin_Api/wallet', {
        headers: { 'Authorization': TOKEN }
      });
      const json = await res.json();

      if (json.status) {
        const d = json.data;

        // Balance cards
        const stats = [
          { label: 'Admin Balance',     value: '$' + d.admin_balance,          color: 'success' },
          { label: 'External Orders',   value: '$' + d.order_external_total,   color: 'primary' },
          { label: 'Store Sales',       value: '$' + d.sale_localstore_total,  color: 'info' },
          { label: 'Integration Clicks', value: d.click_integration_total,     color: 'secondary' },
          { label: 'Store Clicks',      value: d.click_localstore_total,       color: 'secondary' },
          { label: 'Action Clicks',     value: d.click_action_total,           color: 'secondary' },
        ];

        document.getElementById('walletStats').innerHTML = stats.map(s =&gt;
          '&lt;div class="col-md-4"&gt;&lt;div class="card bg-' + s.color + ' bg-opacity-10 p-3 text-center"&gt;' +
          '&lt;small class="text-muted"&gt;' + s.label + '&lt;/small&gt;&lt;h3&gt;' + s.value + '&lt;/h3&gt;' +
          '&lt;/div&gt;&lt;/div&gt;'
        ).join('');

        // Transactions table
        if (d.transactions &amp;&amp; d.transactions.length) {
          document.getElementById('txTable').innerHTML = d.transactions.map(t =&gt;
            '&lt;tr&gt;&lt;td&gt;' + (t.firstname || '') + ' ' + (t.lastname || '') + '&lt;/td&gt;' +
            '&lt;td&gt;$' + (t.amount || 0) + '&lt;/td&gt;' +
            '&lt;td&gt;' + (t.type || '-') + '&lt;/td&gt;' +
            '&lt;td&gt;&lt;span class="badge bg-' + (t.status === 'paid' ? 'success' : 'warning') + '"&gt;' + (t.status || '-') + '&lt;/span&gt;&lt;/td&gt;' +
            '&lt;td&gt;' + (t.created_date || '') + '&lt;/td&gt;&lt;/tr&gt;'
          ).join('');
        }
      }
    }

    loadWallet();
  &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre>
         </div>
      </div>
   </div>
</div>

<!-- Chart.js CDN for reports -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<!-- Live Examples Engine -->
<script>
let exToken = localStorage.getItem('adminApiToken') || '';
let exBase = localStorage.getItem('adminApiBase') || '';
let exChart = null;
let exUserPageNum = 0;

function exSaveSession() {
   localStorage.setItem('adminApiToken', exToken);
   localStorage.setItem('adminApiBase', exBase);
}

function exClearSession() {
   exToken = '';
   localStorage.removeItem('adminApiToken');
   localStorage.removeItem('adminApiBase');
}

function exApi(path, opts = {}) {
   return fetch(exBase + path, {
      ...opts,
      headers: { 'Authorization': exToken, ...(opts.headers || {}) }
   }).then(r => {
      if (!r.ok && r.status === 401) {
         exClearSession();
         document.getElementById('exConnectionStatus').innerHTML = '<div class="alert alert-danger py-2 mb-0"><i class="bi bi-shield-x me-1"></i>Session expired. Please login again.</div>';
         document.getElementById('exConnectBtn').classList.replace('btn-outline-success', 'btn-success');
         document.getElementById('exConnectBtn').innerHTML = '<i class="bi bi-lightning-fill"></i>';
      }
      return r.json();
   });
}

async function exShowConnected(adminName) {
   var statusEl = document.getElementById('exConnectionStatus');
   statusEl.innerHTML = '<div class="alert alert-success py-2 mb-0">' +
      '<div class="d-flex align-items-center justify-content-between">' +
      '<div><i class="bi bi-shield-check me-1"></i>Admin authenticated' + (adminName ? ': <strong>' + adminName + '</strong>' : '') + '</div>' +
      '<div><button class="btn btn-sm btn-outline-danger py-0 px-2" onclick="exLogout()">Logout</button> <div class="spinner-border spinner-border-sm text-success ms-2" id="exLoadingSpinner"></div></div>' +
      '</div>' +
      '<small class="text-muted">Loading live data into all sections below...</small></div>';
   document.getElementById('exConnectBtn').classList.replace('btn-success', 'btn-outline-success');
   document.getElementById('exConnectBtn').innerHTML = '<i class="bi bi-check-lg"></i>';

   await exLoadAll();

   var spinner = document.getElementById('exLoadingSpinner');
   if (spinner) spinner.style.display = 'none';
}

function exLogout() {
   exClearSession();
   document.getElementById('exConnectionStatus').innerHTML = '<div class="alert alert-info py-2 mb-0"><i class="bi bi-box-arrow-right me-1"></i>Logged out. Enter credentials to reconnect.</div>';
   document.getElementById('exConnectBtn').classList.replace('btn-outline-success', 'btn-success');
   document.getElementById('exConnectBtn').innerHTML = '<i class="bi bi-lightning-fill"></i>';
   document.getElementById('exConnectBtn').disabled = false;
}

async function exConnect() {
   exBase = document.getElementById('exApiBase').value.replace(/\/$/, '') + '/';
   const username = document.getElementById('exUsername').value;
   const password = document.getElementById('exPassword').value;
   const statusEl = document.getElementById('exConnectionStatus');

   if (!username || !password) {
      statusEl.innerHTML = '<div class="alert alert-warning py-2 mb-0"><i class="bi bi-exclamation-triangle me-1"></i>Enter admin username and password</div>';
      return;
   }

   statusEl.innerHTML = '<div class="d-flex align-items-center text-muted"><div class="spinner-border spinner-border-sm me-2"></div>Authenticating as admin...</div>';
   document.getElementById('exConnectBtn').disabled = true;

   try {
      const fd = new FormData();
      fd.append('username', username);
      fd.append('password', password);
      fd.append('device_type', '3');
      fd.append('device_token', 'admin-api-docs-' + Date.now());

      const res = await fetch(exBase + 'User/login', { method: 'POST', body: fd });
      const json = await res.json();

      if (json.status && json.data) {
         if (json.data.role !== 'admin') {
            statusEl.innerHTML = '<div class="alert alert-danger py-2 mb-0"><i class="bi bi-shield-x me-1"></i><strong>Access Denied:</strong> The account "<strong>' + username + '</strong>" is not an admin account (role: ' + json.data.role + '). Please use admin credentials.</div>';
            document.getElementById('exConnectBtn').disabled = false;
            return;
         }

         exToken = json.data.token;
         exSaveSession();
         exShowConnected(json.data.firstname + ' ' + json.data.lastname);
      } else {
         statusEl.innerHTML = '<div class="alert alert-danger py-2 mb-0"><i class="bi bi-x-circle me-1"></i>' + (json.message || 'Login failed. Check credentials.') + '</div>';
      }
   } catch (err) {
      statusEl.innerHTML = '<div class="alert alert-danger py-2 mb-0"><i class="bi bi-x-circle me-1"></i>Connection failed: ' + err.message + '<br><small class="text-muted">Make sure the API Base URL is correct and the server is running.</small></div>';
   }
   document.getElementById('exConnectBtn').disabled = false;
}

async function exLoadAll() {
   exLoadDashboard();
   exLoadUsers();
   exLoadWithdrawals();
   exLoadReports();
   exLoadWallet();
}

async function exLoadDashboard() {
   try {
      document.getElementById('dashStatus').textContent = 'Loading...';
      document.getElementById('dashStatus').className = 'badge bg-secondary me-2';
      const json = await exApi('Admin_Api/dashboard');
      if (json.status === true) {
         document.querySelectorAll('.ex-dash-val').forEach(el => {
            const field = el.dataset.field;
            const prefix = el.dataset.prefix || '';
            if (json.data[field] !== undefined) {
               el.textContent = prefix + json.data[field];
            }
         });
         document.getElementById('dashStatus').textContent = 'Live';
         document.getElementById('dashStatus').className = 'badge bg-success me-2';
      } else {
         document.getElementById('dashStatus').textContent = json.message || 'Failed';
         document.getElementById('dashStatus').className = 'badge bg-danger me-2';
      }
   } catch (e) {
      document.getElementById('dashStatus').textContent = 'Error: ' + e.message;
      document.getElementById('dashStatus').className = 'badge bg-danger me-2';
   }
}

async function exLoadUsers() {
   if (!exToken) return;
   const search = document.getElementById('exUserSearch').value;
   const status = document.getElementById('exUserStatus').value;

   try {
      document.getElementById('usersStatus').textContent = 'Loading...';
      document.getElementById('usersStatus').className = 'badge bg-secondary me-2';
      const params = new URLSearchParams({ start_from: exUserPageNum * 20, limit: 20, search: search, status: status });
      const json = await exApi('Admin_Api/users?' + params);

      if (json.status === true) {
         const tbody = document.getElementById('exUsersBody');
         if (!json.data.users || json.data.users.length === 0) {
            tbody.innerHTML = '<tr><td colspan="7" class="text-center text-muted py-3">No users found</td></tr>';
         } else {
            tbody.innerHTML = json.data.users.map(u => {
               const sBadge = u.status === '1' ? '<span class="badge bg-success">Active</span>'
                  : u.status === '0' ? '<span class="badge bg-warning text-dark">Pending</span>'
                  : '<span class="badge bg-danger">Blocked</span>';
               return '<tr>' +
                  '<td>' + (u.firstname || '') + ' ' + (u.lastname || '') + '</td>' +
                  '<td><small>' + (u.email || '') + '</small></td>' +
                  '<td>$' + (u.balance || '0') + '</td>' +
                  '<td>' + (u.total_clicks || '0') + '</td>' +
                  '<td>' + (u.total_sales || '0') + '</td>' +
                  '<td>' + sBadge + '</td>' +
                  '<td><button class="btn btn-sm btn-outline-primary py-0" onclick="exToggleUser(\'' + u.id + '\',\'' + u.status + '\')">Toggle</button></td>' +
                  '</tr>';
            }).join('');
         }
         document.getElementById('exUsersCount').textContent = 'Total: ' + json.data.total_count;
         document.getElementById('exUserNext').disabled = !json.data.has_more;
         document.getElementById('exUserPrev').disabled = exUserPageNum === 0;
         document.getElementById('usersStatus').textContent = json.data.total_count + ' users';
         document.getElementById('usersStatus').className = 'badge bg-success me-2';
      } else {
         document.getElementById('usersStatus').textContent = json.message || 'Failed';
         document.getElementById('usersStatus').className = 'badge bg-danger me-2';
      }
   } catch (e) {
      document.getElementById('usersStatus').textContent = 'Error: ' + e.message;
      document.getElementById('usersStatus').className = 'badge bg-danger me-2';
   }
}

function exUserPage(dir) {
   exUserPageNum += dir;
   if (exUserPageNum < 0) exUserPageNum = 0;
   exLoadUsers();
}

async function exToggleUser(userId, currentStatus) {
   const newStatus = currentStatus === '1' ? '2' : '1';
   const fd = new FormData();
   fd.append('user_id', userId);
   fd.append('status', newStatus);
   try {
      const json = await exApi('Admin_Api/update_user_status', { method: 'POST', body: fd });
      if (json.status === true) exLoadUsers();
      else alert(json.message || 'Failed to update user status');
   } catch (e) {
      alert('Error: ' + e.message);
   }
}

async function exLoadWithdrawals() {
   if (!exToken) return;
   const status = document.getElementById('exWdFilter').value;

   try {
      const json = await exApi('Admin_Api/withdrawals?status=' + status);
      if (json.status === true) {
         const tbody = document.getElementById('exWdBody');
         const requests = json.data.requests || [];
         if (requests.length === 0) {
            tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted py-3">No ' + status + ' requests</td></tr>';
         } else {
            tbody.innerHTML = requests.map(r => {
               const isPending = r.status === '0' || r.status === 'unpaid';
               const actions = isPending
                  ? '<button class="btn btn-sm btn-success py-0 me-1" onclick="exWdAction(\'' + r.id + '\',\'paid\')">Approve</button>' +
                    '<button class="btn btn-sm btn-danger py-0" onclick="exWdAction(\'' + r.id + '\',\'rejected\')">Reject</button>'
                  : '<span class="badge bg-' + (r.status === '1' || r.status === 'paid' ? 'success' : 'danger') + '">' + (r.status === '1' || r.status === 'paid' ? 'Paid' : 'Rejected') + '</span>';
               return '<tr>' +
                  '<td>' + (r.firstname || '') + ' ' + (r.lastname || '') + '</td>' +
                  '<td>$' + (r.amount || '0') + '</td>' +
                  '<td>' + (r.payment_method || '-') + '</td>' +
                  '<td><small>' + (r.created_at || '') + '</small></td>' +
                  '<td>' + actions + '</td></tr>';
            }).join('');
         }
      } else {
         document.getElementById('exWdBody').innerHTML = '<tr><td colspan="5" class="text-center text-muted py-3">' + (json.message || 'Failed to load') + '</td></tr>';
      }
   } catch (e) {
      document.getElementById('exWdBody').innerHTML = '<tr><td colspan="5" class="text-center text-danger py-3">Error: ' + e.message + '</td></tr>';
   }
}

async function exWdAction(id, status) {
   const fd = new FormData();
   fd.append('request_id', id);
   fd.append('status', status);
   try {
      const json = await exApi('Admin_Api/update_withdrawal_status', { method: 'POST', body: fd });
      if (json.status === true) exLoadWithdrawals();
      else alert(json.message || 'Failed to update withdrawal');
   } catch (e) {
      alert('Error: ' + e.message);
   }
}

async function exLoadReports() {
   if (!exToken) return;
   const dateFrom = document.getElementById('exDateFrom').value;
   const dateTo = document.getElementById('exDateTo').value;

   try {
      const params = new URLSearchParams();
      if (dateFrom) params.append('date_from', dateFrom);
      if (dateTo) params.append('date_to', dateTo);

      const json = await exApi('Admin_Api/reports?' + params);
      if (json.status === true) {
         const d = json.data;
         const clickLabels = d.clicks_by_day.map(c => c.date);
         const saleLabels = d.sales_by_day.map(s => s.date);
         const allLabels = [...new Set([...clickLabels, ...saleLabels])].sort();

         if (exChart) exChart.destroy();
         exChart = new Chart(document.getElementById('exReportsChart'), {
            type: 'line',
            data: {
               labels: allLabels,
               datasets: [
                  {
                     label: 'Clicks',
                     data: allLabels.map(l => { const f = d.clicks_by_day.find(c => c.date === l); return f ? parseInt(f.count) : 0; }),
                     borderColor: '#0d6efd', backgroundColor: 'rgba(13,110,253,0.1)', tension: 0.3, fill: true
                  },
                  {
                     label: 'Sales',
                     data: allLabels.map(l => { const f = d.sales_by_day.find(s => s.date === l); return f ? parseInt(f.count) : 0; }),
                     borderColor: '#198754', backgroundColor: 'rgba(25,135,84,0.1)', tension: 0.3, fill: true
                  }
               ]
            },
            options: { responsive: true, plugins: { legend: { position: 'top' } }, scales: { y: { beginAtZero: true } } }
         });

         const container = document.getElementById('exTopAffiliates');
         if (d.top_affiliates.length > 0) {
            container.innerHTML = '<div class="col-12"><h6>Top Affiliates</h6></div>' +
               d.top_affiliates.slice(0, 6).map(a =>
                  '<div class="col-md-4"><div class="card border-0 bg-light p-2 rounded-3">' +
                  '<strong>' + a.firstname + ' ' + a.lastname + '</strong>' +
                  '<small class="text-muted">' + a.total_sales + ' sales &middot; $' + (a.total_revenue || '0') + '</small>' +
                  '</div></div>'
               ).join('');
         } else {
            container.innerHTML = '<div class="col-12"><small class="text-muted">No sales data in this period</small></div>';
         }
      }
   } catch (e) {}
}

async function exLoadWallet() {
   if (!exToken) return;
   try {
      const json = await exApi('Admin_Api/wallet');
      if (json.status === true && json.data) {
         const d = json.data;
         document.getElementById('exWalBalance').textContent = '$' + (d.admin_balance || '0');
         document.getElementById('exWalExternal').textContent = '$' + (d.order_external_total || '0');
         document.getElementById('exWalStore').textContent = '$' + (d.sale_localstore_total || '0');
         document.getElementById('exWalIntClicks').textContent = d.click_integration_total || '0';
         document.getElementById('exWalStoreClicks').textContent = d.click_localstore_total || '0';
         document.getElementById('exWalActionClicks').textContent = d.click_action_total || '0';
         document.getElementById('exWalFormClicks').textContent = d.click_form_total || '0';

         const tbody = document.getElementById('exWalTxBody');
         if (d.transactions && d.transactions.length > 0) {
            tbody.innerHTML = d.transactions.slice(0, 10).map(t =>
               '<tr><td>' + (t.firstname || '') + ' ' + (t.lastname || '') + '</td>' +
               '<td>$' + (t.amount || '0') + '</td>' +
               '<td><span class="badge bg-light text-dark">' + (t.type || '-') + '</span></td>' +
               '<td><span class="badge bg-' + (t.status === 'paid' ? 'success' : 'warning text-dark') + '">' + (t.status || '-') + '</span></td>' +
               '<td><small>' + (t.created_date || '') + '</small></td></tr>'
            ).join('');
         } else {
            tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted py-3">No transactions</td></tr>';
         }
      } else {
         document.getElementById('exWalTxBody').innerHTML = '<tr><td colspan="5" class="text-center text-muted py-3">' + (json.message || 'Failed to load wallet') + '</td></tr>';
      }
   } catch (e) {
      document.getElementById('exWalTxBody').innerHTML = '<tr><td colspan="5" class="text-center text-danger py-3">Error: ' + e.message + '</td></tr>';
   }
}

// Set default date range (current month)
(function() {
   const now = new Date();
   document.getElementById('exDateFrom').value = now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0') + '-01';
   document.getElementById('exDateTo').value = now.toISOString().split('T')[0];
})();

// Auto-restore session on page load
(function() {
   if (exToken && exBase) {
      document.getElementById('exApiBase').value = exBase.replace(/\/$/, '');
      exShowConnected(null);
   }
})();

// Copy code button
$(document).on('click', '.copy-code-btn', function() {
   const targetId = $(this).data('target');
   const text = document.getElementById(targetId).textContent;
   const $btn = $(this);
   navigator.clipboard.writeText(text).then(function() {
      $btn.html('<i class="bi bi-check me-1"></i>Copied!').addClass('btn-success').removeClass('btn-outline-light');
      setTimeout(() => { $btn.html('<i class="bi bi-clipboard me-1"></i>Copy').removeClass('btn-success').addClass('btn-outline-light'); }, 2000);
   });
});
</script>
