<?php
/**
 * Admin Dashboard — PDO-only (uses config.php), responsive + attractive UI
 * Improvements:
 *   - Orange/white brand styling (via Tailwind CDN config)
 *   - Volume chart groups by account_name (SUM(volume))
 *   - KYC doughnut fixed (approved vs pending)
 *   - Clean grids/cards; mobile-first; consistent shadows/spacing
 */
@session_start();
session_start();
error_reporting(0);
include('config.php');

require_once ('auth_guard.php');
if (!isset($conn) || !($conn instanceof PDO)) {
  die('Database connection not established. Check config.php (PDO).');
}

/* ---------- Small PDO helpers ---------- */
function scalar(PDO $conn, string $sql) {
  $st = $conn->query($sql); if(!$st) return null; return $st->fetchColumn();
}
function rows(PDO $conn, string $sql): array {
  $st = $conn->query($sql); if(!$st) return []; return $st->fetchAll(PDO::FETCH_ASSOC);
}

/* ---------- Core Metrics ---------- */
$totUsers        = (int) scalar($conn, "SELECT COUNT(*) FROM aspnetusers");
$verifiedUsers   = (int) scalar($conn, "SELECT COUNT(*) FROM aspnetusers WHERE email_confirmed = 1");
$unverifiedUsers = (int) scalar($conn, "SELECT COUNT(*) FROM aspnetusers WHERE email_confirmed = 0");
$kycApproved     = (int) scalar($conn, "SELECT COUNT(*) FROM kyc_update WHERE Status = 1");
$kycPending      = (int) scalar($conn, "SELECT COUNT(*) FROM kyc_update WHERE Status = 0");
/* ---------- Finance (Approved vs Pending) ---------- */
$approvedDepositTotal  = (float)(scalar($conn, "SELECT IFNULL(SUM(deposit_amount),0)  FROM wallet_deposit  WHERE Status = 1") ?? 0);
$approvedWithdrawTotal = (float)(scalar($conn, "SELECT IFNULL(SUM(withdraw_amount),0) FROM wallet_withdraw WHERE Status = 1") ?? 0);

$pendingDepRow = rows($conn, "SELECT COUNT(*) AS cnt, IFNULL(SUM(deposit_amount),0)  AS amt FROM wallet_deposit  WHERE Status = 0");
$pendingDepCount  = (int)($pendingDepRow[0]['cnt'] ?? 0);
$pendingDepAmount = (float)($pendingDepRow[0]['amt'] ?? 0.0);

$pendingWdrRow = rows($conn, "SELECT COUNT(*) AS cnt, IFNULL(SUM(withdraw_amount),0) AS amt FROM wallet_withdraw WHERE Status = 0");
$pendingWdrCount  = (int)($pendingWdrRow[0]['cnt'] ?? 0);
$pendingWdrAmount = (float)($pendingWdrRow[0]['amt'] ?? 0.0);

$liveAccounts    = (int) scalar($conn, "SELECT COUNT(*) FROM liveaccount");
$sumBalance      = (float) (scalar($conn, "SELECT IFNULL(SUM(Balance),0) FROM liveaccount") ?? 0);
$sumEquity       = (float) (scalar($conn, "SELECT IFNULL(SUM(equity),0) FROM liveaccount") ?? 0);

/* ---------- Finance (All-time) ---------- */
$totalDeposit    = (float) (scalar($conn, "SELECT IFNULL(SUM(deposit_amount),0) FROM total_balance") ?? 0);
$totalWithdraw   = (float) (scalar($conn, "SELECT IFNULL(SUM(withdraw_amount),0) FROM total_balance") ?? 0);
$netFlow         = $totalDeposit - $totalWithdraw;

/* ---------- Operations ---------- */
$logins24h       = (int) scalar($conn, "SELECT COUNT(*) FROM login_history WHERE created_date_js >= NOW() - INTERVAL 24 HOUR");
$uniqueIPs24h    = (int) scalar($conn, "SELECT COUNT(DISTINCT ip) FROM login_history WHERE created_date_js >= NOW() - INTERVAL 24 HOUR");
$logins7d        = (int) scalar($conn, "SELECT COUNT(*) FROM login_history WHERE created_date_js >= NOW() - INTERVAL 7 DAY");

$topCountries    = rows($conn, "
  SELECT country, COUNT(*) AS cnt
  FROM login_history
  WHERE created_date_js >= NOW() - INTERVAL 7 DAY
  GROUP BY country
  ORDER BY cnt DESC
  LIMIT 5
");

/* ---------- Queues ---------- */
$pendingPayout   = rows($conn, "SELECT COUNT(*) AS cnt, IFNULL(SUM(withdraw_amount),0) AS amt FROM wallet_withdraw WHERE Status = 0");
$pendingCount    = (int)($pendingPayout[0]['cnt'] ?? 0);
$pendingAmount   = (float)($pendingPayout[0]['amt'] ?? 0.0);
$approvedPayoutToday = (float) (scalar($conn, "SELECT IFNULL(SUM(withdraw_amount),0) FROM wallet_withdraw WHERE Status = 1 AND DATE(withdraw_date)=CURDATE()") ?? 0);

/* ---------- Lists ---------- */
/* NEW: group by account_name, sum(volume) for chart */
$volumesByType = rows($conn, "
  SELECT account_name, SUM(volume) AS total_volume
  FROM liveaccount                        -- <— adjust table/column names if different
  GROUP BY account_name
  ORDER BY total_volume DESC
  LIMIT 10
");

/* Recent users */
$recentUsers = rows($conn, "
  SELECT fullname, email, country, kyc_verify, client_status, reg_date
  FROM aspnetusers
  ORDER BY reg_date DESC
  LIMIT 8
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Admin Dashboard</title>

  <!-- TailwindCSS (with brand color added) -->
  <script>
    tailwind = undefined;
  </script>
  <script src="https://cdn.tailwindcss.com"></script>
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            brand: {
              50:  '#fff7ed',
              100: '#ffedd5',
              200: '#fed7aa',
              300: '#fdba74',
              400: '#fb923c',
              500: '#ff6a00', /* main orange */
              600: '#e65c00',
              700: '#cc4c00',
              800: '#9a3a00',
              900: '#7a2e00'
            }
          },
          boxShadow: {
            card: '0 10px 25px rgba(0,0,0,.08)'
          },
          borderRadius: {
            '2xl': '1rem',
          }
        }
      }
    }
  </script>

  <!-- Chart.js (single include) -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>

  <!-- jQuery + DataTables -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css" />
  <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

  <!-- Icons -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/remixicon/4.2.0/remixicon.min.css" rel="stylesheet"/>

  <style>
    .card{ box-shadow: var(--tw-shadow, 0 10px 25px rgba(0,0,0,.08)); }
    .glass{ backdrop-filter: blur(6px); background: linear-gradient(145deg, rgba(255,255,255,.9), rgba(255,255,255,.78)); }
    .pretty-table { border-collapse: separate; border-spacing: 0; }
    .pretty-table thead .th{
      position: sticky; top: 0; background: #fff; z-index: 5;
      text-align: left; font-weight: 500; font-size: .75rem;
      text-transform: uppercase; letter-spacing: .04em;
      color: #64748b; padding: .75rem 1rem; border-bottom: 1px solid #e2e8f0; white-space: nowrap;
    }
    .pretty-table .td { padding: .875rem 1rem; border-bottom: 1px solid #f1f5f9; vertical-align: middle; }
    .pretty-table .tr:nth-child(even) { background: #fcfcfd; }
    .pretty-table .tr:hover { background: #f8fafc; }
    .badge{
      display:inline-flex; align-items:center; gap:.4rem;
      padding:.25rem .55rem; border-radius:999px; font-size:.75rem; font-weight:600; white-space:nowrap;
    }
    .badge-emerald{ background:#ecfdf5; color:#047857; }
    .badge-amber{ background:#fffbeb; color:#b45309; }
  </style>

  <?php //include "title.php";?>
</head>
<body class="min-h-screen bg-gradient-to-b from-white to-brand-50 text-gray-900">

<?php include __DIR__ . '/header.php'; ?>  <?php include __DIR__ . '/side_bar.php'; ?>
<div class="flex flex-col md:flex-row">


  <main class="flex-1 p-4 sm:p-6 md:ml-64">
    <div class="max-w-7xl mx-auto">

    

      <!-- KPI Row -->
<!-- ✨ ULTRA-ATTRACTIVE KPI STRIP (drop-in) -->
<!-- ========== PREMIUM KPI STRIP (aligned layout) ========== -->
<section class="relative overflow-hidden rounded-3xl my-4">
  <!-- animated border glow -->
  <div class="absolute inset-0 rounded-3xl p-[1px] bg-[conic-gradient(at_10%_10%,#ff6a00,rgba(255,106,0,.08),#7c3aed,rgba(124,58,237,.08),#10b981,rgba(16,185,129,.08),#ff6a00)] animate-[spin_12s_linear_infinite]"></div>

  <!-- glass body -->
  <div class="relative rounded-3xl bg-white/80 backdrop-blur-xl">
    <!-- soft blobs -->
    <div class="pointer-events-none absolute -top-24 -left-24 w-72 h-72 rounded-full bg-orange-200/30 blur-3xl"></div>
    <div class="pointer-events-none absolute -bottom-24 -right-24 w-72 h-72 rounded-full bg-indigo-200/30 blur-3xl"></div>

    <!-- tiles -->
    <div class="relative grid gap-3 p-3 sm:p-4 md:p-5 grid-cols-2 md:grid-cols-3 xl:grid-cols-6">

      <!-- USERS -->
      <div class="relative rounded-2xl bg-white/90 border border-white/60 hover:bg-white transition shadow-sm hover:shadow-md flex flex-col">
        <div class="flex items-center gap-3 px-4 pt-4">
          <span class="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-tr from-orange-400 to-orange-600 text-white shadow">
            <i class="ri-team-fill text-lg"></i>
          </span>
          <p class="text-xs font-semibold uppercase tracking-wide text-gray-500">Users</p>
        </div>
        <div class="px-4 flex-1 flex flex-col justify-center">
          <span class="text-xl font-extrabold text-gray-900 counter" data-target="<?= (int)$totUsers ?>">0</span>
        </div>
        <div class="px-4 pb-4 flex items-center justify-between text-xs">
          <span class="text-emerald-600">✔ Verified: <?=number_format($verifiedUsers)?></span>
          <span class="text-amber-600">✖ Unverified: <?=number_format($unverifiedUsers)?></span>
        </div>
        <div class="spark-wrap"><canvas class="spark" data-points="6,9,8,10,12,14,13,16"></canvas></div>
      </div>

      <!-- KYC -->
      <div class="relative rounded-2xl bg-white/90 border border-white/60 hover:bg-white transition shadow-sm hover:shadow-md flex flex-col">
        <div class="flex items-center gap-3 px-4 pt-4">
          <span class="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-tr from-emerald-400 to-emerald-600 text-white shadow">
            <i class="ri-pass-valid-fill text-lg"></i>
          </span>
          <p class="text-xs font-semibold uppercase tracking-wide text-gray-500">KYC</p>
        </div>
        <div class="px-4 flex-1 flex flex-col justify-center">
          <span class="text-xl font-extrabold text-gray-900 counter" data-target="<?= (int)$kycApproved ?>">0</span>
        </div>
        <div class="px-4 pb-4 flex items-center justify-between text-xs">
          <span class="text-emerald-600">✔ Appr: <?=number_format($kycApproved)?></span>
          <span class="text-amber-600">⏳ Pend: <?=number_format($kycPending)?></span>
        </div>
        <div class="spark-wrap"><canvas class="spark" data-points="2,3,3,4,5,6,6,7"></canvas></div>
      </div>

      <!-- LIVE ACCOUNTS -->
      <div class="relative rounded-2xl bg-white/90 border border-white/60 hover:bg-white transition shadow-sm hover:shadow-md flex flex-col">
        <div class="flex items-center gap-3 px-4 pt-4">
          <span class="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-tr from-indigo-400 to-indigo-600 text-white shadow">
            <i class="ri-account-circle-fill text-lg"></i>
          </span>
          <p class="text-xs font-semibold uppercase tracking-wide text-gray-500">Live Accounts</p>
        </div>
        <div class="px-4 flex-1 flex flex-col justify-center">
          <span class="text-xl font-extrabold text-gray-900 counter" data-target="<?= (int)$liveAccounts ?>">0</span>
        </div>
        <div class="px-4 pb-4 flex items-center justify-between text-xs">
          <span class="text-gray-600">AUM (Equity)</span>
          <span class="text-gray-800 font-medium">$<?=number_format($sumEquity,2)?></span>
        </div>
        <div class="spark-wrap"><canvas class="spark" data-points="1,4,5,6,6,7,7,7"></canvas></div>
      </div>

      <!-- BALANCE -->
<!-- DEPOSITS -->
<div class="relative rounded-2xl bg-white/90 border border-white/60 hover:bg-white transition shadow-sm hover:shadow-md flex flex-col">
  <div class="flex items-center gap-3 px-4 pt-4">
    <span class="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-tr from-amber-400 to-amber-600 text-white shadow">
      <i class="ri-wallet-3-fill text-lg"></i>
    </span>
    <p class="text-xs font-semibold uppercase tracking-wide text-gray-500">Deposits</p>
  </div>
  <div class="px-4 flex-1 flex flex-col justify-center">
    <!-- TOP: Approved amount -->
    <span class="text-xl font-extrabold text-gray-900">
      $<?= number_format($approvedDepositTotal, 2) ?>
    </span>
  </div>
  <!-- BOTTOM: Pending amount + count -->
  <div class="px-4 pb-4 flex items-center justify-between text-xs">
    <span class="text-gray-600">Pending</span>
    <span class="text-gray-800 font-medium">
      $<?= number_format($pendingDepAmount, 2) ?> (<?= number_format($pendingDepCount) ?>)
    </span>
  </div>
  <div class="spark-wrap"><canvas class="spark" data-points="0,2,1,3,2,4,3,5"></canvas></div>
</div>
<!-- PAYOUT QUEUE -->
<!-- WITHDRAWALS -->
<div class="relative rounded-2xl bg-white/90 border border-white/60 hover:bg-white transition shadow-sm hover:shadow-md flex flex-col">
  <div class="flex items-center gap-3 px-4 pt-4">
    <span class="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-tr from-rose-400 to-rose-600 text-white shadow">
      <i class="ri-bank-card-2-fill text-lg"></i>
    </span>
    <p class="text-xs font-semibold uppercase tracking-wide text-gray-500">Withdrawals</p>
  </div>
  <div class="px-4 flex-1 flex flex-col justify-center">
    <!-- TOP: Approved amount -->
    <span class="text-xl font-extrabold text-gray-900">
      $<?= number_format($approvedWithdrawTotal, 2) ?>
    </span>
  </div>
  <!-- BOTTOM: Pending amount + count -->
  <div class="px-4 pb-4 flex items-center justify-between text-xs">
    <span class="text-gray-600">Pending</span>
    <span class="text-gray-800 font-medium">
      $<?= number_format($pendingWdrAmount, 2) ?> (<?= number_format($pendingWdrCount) ?>)
    </span>
  </div>
  <div class="spark-wrap"><canvas class="spark" data-points="0,1,0,2,1,1,0,1"></canvas></div>
</div>

      <!-- LOGINS -->
      <div class="relative rounded-2xl bg-white/90 border border-white/60 hover:bg-white transition shadow-sm hover:shadow-md flex flex-col">
        <div class="flex items-center gap-3 px-4 pt-4">
          <span class="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-tr from-blue-400 to-blue-600 text-white shadow">
            <i class="ri-login-box-fill text-lg"></i>
          </span>
          <p class="text-xs font-semibold uppercase tracking-wide text-gray-500">Logins (24h)</p>
        </div>
        <div class="px-4 flex-1 flex flex-col justify-center">
          <span class="text-xl font-extrabold text-gray-900 counter" data-target="<?= (int)$logins24h ?>">0</span>
        </div>
        <div class="px-4 pb-4 flex items-center justify-between text-xs">
          <span class="text-gray-600">Unique IPs</span>
          <span class="text-gray-800 font-medium"><?=number_format($uniqueIPs24h)?></span>
        </div>
        <div class="spark-wrap"><canvas class="spark" data-points="2,5,3,6,4,7,5,3"></canvas></div>
      </div>

      
    </div>
  </div>
</section>

<!-- helper styles (once) -->
<style>
  @keyframes spin { to { transform: rotate(1turn) } }
  .tabular-nums{ font-variant-numeric: tabular-nums; }
  .spark-wrap{
    position: relative;
    height: 34px;              /* tweak 28–40px if desired */
    overflow: hidden;
    border-radius: 0 0 1rem 1rem; /* matches rounded-2xl bottom */
    pointer-events: none;
    z-index: 0;
  }
  .spark{ display:block; width:100% !important; height:100% !important; }
</style>

<!-- counters + sparklines (pure JS) -->
<script>
(function(){
  // Count-up animation
  document.querySelectorAll('.counter').forEach(el=>{
    const target = +el.dataset.target || 0;
    const dur = 900; const start = performance.now();
    function tick(t){
      const p = Math.min(1,(t-start)/dur);
      el.textContent = Math.round(target * (0.2 + 0.8*Math.pow(p,0.85)));
      if(p<1) requestAnimationFrame(tick);
    }
    requestAnimationFrame(tick);
  });

  // Sparkline bars
  function drawSpark(c){
    const wrap   = c.parentElement;
    const points = (c.dataset.points||'2,3,4,3,5,4,6').split(',').map(n=>+n||0);
    const w = c.width  = wrap.clientWidth;
    const h = c.height = wrap.clientHeight;
    const ctx = c.getContext('2d');
    const max = Math.max(1, ...points);
    const pad = 6, gap = 3;
    const barW = Math.max(2, (w - pad*2 - gap*(points.length-1)) / points.length);
    const grad = ctx.createLinearGradient(0,0,0,h);
    grad.addColorStop(0,'#ff6a00'); grad.addColorStop(1,'rgba(255,106,0,.38)');
    ctx.clearRect(0,0,w,h);
    points.forEach((v,i)=>{
      const x  = pad + i*(barW+gap);
      const bh = (v/max) * (h-2);
      ctx.fillStyle = grad; ctx.fillRect(x, h-bh, barW, bh);
      ctx.fillStyle='rgba(2,6,23,.06)'; ctx.fillRect(x, h-1, barW, 1);
    });
  }
  const sparks = Array.from(document.querySelectorAll('canvas.spark'));
  sparks.forEach(drawSpark);
  let rf; window.addEventListener('resize', ()=>{ cancelAnimationFrame(rf); rf=requestAnimationFrame(()=>sparks.forEach(drawSpark)); });
})();
</script>


      <!-- Finance Overview -->
      <section class="mt-6">
        <div class="card rounded-2xl p-0 bg-white border border-gray-100 overflow-hidden">
          <div class="px-5 py-4 bg-gradient-to-r from-brand-50 via-white to-brand-50 border-b border-brand-100 flex flex-col lg:flex-row lg:items-center justify-between gap-3">
            <div class="flex items-center gap-3">
              <span class="inline-flex h-11 w-11 items-center justify-center rounded-xl bg-brand-100 text-brand-700">
                <i class="ri-exchange-dollar-fill text-xl"></i>
              </span>
              <div>
                <h3 class="text-base font-semibold leading-tight">Finance Overview</h3>
                <p class="text-xs text-gray-600">All-time comparison of deposits vs withdrawals</p>
              </div>
            </div>
            <div class="flex flex-wrap items-center gap-2 text-sm">
              <span class="inline-flex items-center gap-1 px-2 py-1 rounded-lg bg-emerald-50 text-emerald-700 border border-emerald-100">
                <i class="ri-arrow-up-circle-fill"></i> Deposits: $<?=number_format($totalDeposit, 2)?>
              </span>
              <span class="inline-flex items-center gap-1 px-2 py-1 rounded-lg bg-rose-50 text-rose-700 border border-rose-100">
                <i class="ri-arrow-down-circle-fill"></i> Withdrawals: $<?=number_format($totalWithdraw, 2)?>
              </span>
              <span class="inline-flex items-center gap-1 px-2 py-1 rounded-lg <?= $netFlow>=0 ? 'bg-blue-50 text-blue-700 border border-blue-100' : 'bg-amber-50 text-amber-700 border border-amber-100'; ?>">
                <i class="ri-scales-3-fill"></i> Net: $<?=number_format($netFlow, 2)?>
              </span>
            </div>
          </div>

          <div class="p-5">
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-5">
              <div class="lg:col-span-2 card rounded-xl p-5 bg-white/70 border border-gray-100">
                <div class="h-52"><canvas id="financeStacked"></canvas></div>
                <?php if ($totalDeposit==0 && $totalWithdraw==0): ?>
                  <p class="text-center text-gray-400 text-sm mt-4">No deposit/withdrawal data available</p>
                <?php endif; ?>
              </div>

              <!-- Side cards -->
              <div class="flex flex-col gap-4">
                <div class="rounded-xl border border-emerald-100 bg-emerald-50/60 p-4">
                  <div class="text-sm text-emerald-700 flex items-center gap-2">
                    <i class="ri-funds-fill text-lg"></i> Total Deposits
                  </div>
                  <div class="text-2xl font-semibold text-emerald-900 mt-1">$<?=number_format($totalDeposit, 2)?></div>
                  <p class="text-xs text-emerald-700/80 mt-1">All-time cumulative</p>
                </div>
                <div class="rounded-xl border border-rose-100 bg-rose-50/60 p-4">
                  <div class="text-sm text-rose-700 flex items-center gap-2">
                    <i class="ri-money-dollar-circle-fill text-lg"></i> Total Withdrawals
                  </div>
                  <div class="text-2xl font-semibold text-rose-900 mt-1">$<?=number_format($totalWithdraw, 2)?></div>
                  <p class="text-xs text-rose-700/80 mt-1">All-time cumulative</p>
                </div>
                <div class="rounded-xl border <?= $netFlow>=0 ? 'border-blue-100 bg-blue-50/60' : 'border-amber-100 bg-amber-50/60'; ?> p-4">
                  <div class="text-sm <?= $netFlow>=0 ? 'text-blue-700' : 'text-amber-700'; ?> flex items-center gap-2">
                    <i class="ri-bar-chart-2-fill text-lg"></i> Net Flow
                  </div>
                  <div class="text-2xl font-semibold <?= $netFlow>=0 ? 'text-blue-900' : 'text-amber-900'; ?> mt-1">
                    $<?=number_format($netFlow, 2)?>
                  </div>
                  <p class="text-xs <?= $netFlow>=0 ? 'text-blue-700/80' : 'text-amber-700/80'; ?> mt-1">Deposits − Withdrawals</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <!-- Security & Activity (KYC + Top Countries) -->
      <section class="mt-6 grid grid-cols-1 lg:grid-cols-2 gap-4">
        <!-- KYC Doughnut (FIXED) -->
        <div class="card rounded-2xl p-4 bg-white border border-gray-100">
          <div class="flex items-center gap-2">
            <i class="ri-pass-valid-fill text-xl text-emerald-600"></i>
            <h3 class="text-base font-semibold">KYC Completion</h3>
          </div>
          <div class="h-64 sm:h-72 mt-2"><canvas id="kycPie"></canvas></div>
          <?php if (($kycApproved+$kycPending)===0): ?>
            <p class="text-center text-gray-400 text-sm mt-4">No KYC data available</p>
          <?php endif; ?>
        </div>

        <!-- Top Countries -->
        <div class="card rounded-2xl p-4 bg-white border border-gray-100">
          <div class="flex items-center gap-2">
            <i class="ri-map-pin-2-fill text-xl text-brand-600"></i>
            <h3 class="text-base font-semibold">Top Countries (Logins • Last 7 days)</h3>
          </div>
          <div class="h-64 sm:h-72 mt-2"><canvas id="countryBar"></canvas></div>
          <?php if (count($topCountries)===0): ?>
            <p class="text-center text-gray-400 text-sm mt-4">No login data for the last 7 days</p>
          <?php endif; ?>
        </div>
      </section>

      <!-- Queues -->
      <?php
        $pendingDep = rows($conn, "SELECT COUNT(*) AS cnt, IFNULL(SUM(deposit_amount),0) AS amt FROM wallet_deposit WHERE Status = 0");
        $pendingDepCount  = (int)($pendingDep[0]['cnt'] ?? 0);
        $pendingDepAmount = (float)($pendingDep[0]['amt'] ?? 0);
        $approvedDepositToday = (float)(scalar($conn, "SELECT IFNULL(SUM(deposit_amount),0) FROM wallet_deposit WHERE Status = 1 AND DATE(deposted_date)=CURDATE()") ?? 0);

        $pendingWdr = rows($conn, "SELECT COUNT(*) AS cnt, IFNULL(SUM(withdraw_amount),0) AS amt FROM wallet_withdraw WHERE Status = 0");
        $pendingWdrCount  = (int)($pendingWdr[0]['cnt'] ?? 0);
        $pendingWdrAmount = (float)($pendingWdr[0]['amt'] ?? 0);
        $approvedPayoutToday = (float)(scalar($conn, "SELECT IFNULL(SUM(withdraw_amount),0) FROM wallet_withdraw WHERE Status = 1 AND DATE(withdraw_date)=CURDATE()") ?? 0);
      ?>

      <section class="mt-6 grid grid-cols-1 gap-6">
        <!-- Pending Deposits -->
        <div class="card rounded-2xl p-0 bg-white border border-gray-100 overflow-hidden">
          <div class="px-5 py-4 bg-gradient-to-r from-emerald-50 to-white border-b border-emerald-100 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div class="flex items-center gap-3">
              <span class="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-emerald-100 text-emerald-700">
                <i class="ri-bank-card-fill text-lg"></i>
              </span>
              <div>
                <h3 class="text-base font-semibold">Pending Deposits</h3>
                <div class="flex items-center gap-2 text-xs mt-1">
                  <span class="px-2 py-0.5 rounded-lg bg-emerald-50 text-emerald-700 border border-emerald-100">
                    <?=$pendingDepCount?> pending
                  </span>
                  <span class="px-2 py-0.5 rounded-lg bg-emerald-50 text-emerald-700 border border-emerald-100">
                    Total: $<?=number_format($pendingDepAmount,2)?>
                  </span>
                </div>
              </div>
            </div>
            <div class="text-xs text-gray-500">
              Approved today: <span class="font-medium">$<?=number_format($approvedDepositToday,2)?></span>
            </div>
          </div>
          <div class="p-4 overflow-x-auto">
            <table id="depositQueueTable" class="display w-full text-sm">
              <thead>
                <tr>
                  <th>Trade ID</th>
                  <th>Amount ($)</th>
                  <th>Type</th>
                  <th>Requested</th>
                  <th>Status</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody class="[&_tr:nth-child(even)]:bg-emerald-50/30">
                <?php
                $depRows = rows($conn, "SELECT id,email, trade_id, deposit_amount, deposit_type, deposted_date FROM wallet_deposit WHERE Status=0 ORDER BY deposted_date DESC LIMIT 50");
                if (!count($depRows)) {
                  echo '<tr><td colspan="6" class="text-center text-gray-500 py-6">No pending deposits</td></tr>';
                } else {
                  foreach ($depRows as $rw) {
                   echo '<tr>';
echo '<td class="text-center">' . htmlspecialchars($rw['trade_id']) . '</td>';
echo '<td class="text-center">$' . number_format((float)$rw['deposit_amount'], 2) . '</td>';
echo '<td class="text-center">' . htmlspecialchars($rw['deposit_type']) . '</td>';
echo '<td class="text-center">' . htmlspecialchars($rw['deposted_date']) . '</td>';
echo '<td class="text-center"><span class="px-2 py-0.5 rounded-full bg-amber-50 text-amber-700 border border-amber-200 text-xs">Pending</span></td>';
echo '<td class="text-center"><a href="view_wallet_deposit.php?id=' . htmlspecialchars($rw['id']) . '&email=' . htmlspecialchars($rw['email']) . '&deposit=' . htmlspecialchars($rw['deposit_amount']) . '" class="px-4 py-2 bg-orange-500 rounded-lg hover:bg-blue-600 transition text-white text-xs font-semibold shadow-lg inline-flex items-center gap-1">
                 <i class="fas fa-eye"></i>View</a></td>';
echo '</tr>';

                  }
                }
                ?>
              </tbody>
            </table>
          </div>
        </div>

        <!-- Pending Withdrawals -->
        <div class="card rounded-2xl p-0 bg-white border border-gray-100 overflow-hidden">
          <div class="px-5 py-4 bg-gradient-to-r from-rose-50 to-white border-b border-rose-100 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div class="flex items-center gap-3">
              <span class="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-rose-100 text-rose-700">
                <i class="ri-bank-card-fill text-lg"></i>
              </span>
              <div>
                <h3 class="text-base font-semibold">Pending Withdrawals</h3>
                <div class="flex items-center gap-2 text-xs mt-1">
                  <span class="px-2 py-0.5 rounded-lg bg-rose-50 text-rose-700 border border-rose-100">
                    <?=$pendingWdrCount?> pending
                  </span>
                  <span class="px-2 py-0.5 rounded-lg bg-rose-50 text-rose-700 border border-rose-100">
                    Total: $<?=number_format($pendingWdrAmount,2)?>
                  </span>
                </div>
              </div>
            </div>
            <div class="text-xs text-gray-500">
              Approved today: <span class="font-medium">$<?=number_format($approvedPayoutToday,2)?></span>
            </div>
          </div>
          <div class="p-4 overflow-x-auto">
            <table id="withdrawQueueTable" class="display w-full text-sm">
              <thead>
                <tr>
                  <th>Trade ID</th>
                  <th>Amount ($)</th>
                  <th>Type</th>
                  <th>Requested</th>
                  <th>Status</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody class="[&_tr:nth-child(even)]:bg-rose-50/30">
              <?php
$wdrRows = rows($conn, "SELECT id, email, trade_id, withdraw_amount, withdraw_type, withdraw_date 
                        FROM wallet_withdraw
                        WHERE Status = 0
                        ORDER BY withdraw_date DESC
                        LIMIT 50");

if (!count($wdrRows)) {
  echo '<tr><td colspan="6" class="text-center text-gray-500 py-6">No pending withdrawals</td></tr>';
} else {
  foreach ($wdrRows as $rw) {
    $view_link = ($rw['withdraw_type'] === 'crypto' || $rw['withdraw_type'] === 'usdttrc')
                  ? 'view_withdrawal1.php'
                  : 'view_withdrawal.php';

    echo '<tr>';
      echo '<td class="text-center">' . htmlspecialchars($rw['trade_id']) . '</td>';
      echo '<td class="text-center">$' . number_format((float)$rw['withdraw_amount'], 2) . '</td>';
      echo '<td class="text-center">' . htmlspecialchars($rw['withdraw_type']) . '</td>';
      echo '<td class="text-center">' . htmlspecialchars($rw['withdraw_date']) . '</td>';
      echo '<td class="text-center"><span class="px-2 py-0.5 rounded-full bg-amber-50 text-amber-700 border border-amber-200 text-xs">Pending</span></td>';
      echo '<td class="text-center">
              <a href="'.$view_link
                    .'?id='.htmlspecialchars($rw['id'])
                    .'&email='.htmlspecialchars($rw['email'])
                    .'&withdraw='.htmlspecialchars($rw['withdraw_amount']).'"
                 class="px-4 py-2 bg-orange-500 rounded-lg hover:bg-blue-600 transition text-white text-xs font-semibold shadow-lg inline-flex items-center gap-1">
                 <i class="fas fa-eye"></i> View
              </a>
            </td>';
    echo '</tr>';
  }
}
?>


              </tbody>
            </table>
          </div>
        </div>
      </section>

      <!-- Volume by Account Type + Recent Users -->
      <section class="mt-6 grid grid-cols-1 xl:grid-cols-2 gap-4">
        <div class="card rounded-2xl p-4 bg-white border border-gray-100">
          <h3 class="text-base font-semibold mb-2 flex items-center gap-2">
            <i class="ri-pie-chart-2-fill text-brand-600"></i> Volume by Account Type
          </h3>
<div class="mx-auto w-full max-w-[320px] aspect-square">
  <canvas id="volumePie"></canvas>
</div>          <?php if (empty($volumesByType)): ?>
            <p class="text-center text-gray-400 text-sm mt-4">No volume data</p>
          <?php endif; ?>
        </div>

        <div class="card rounded-2xl bg-white border border-gray-100 shadow-sm">
          <div class="px-4 pt-4 pb-3 flex items-center justify-between">
            <h3 class="text-base font-semibold flex items-center gap-2 text-slate-800">
              <i class="ri-user-3-fill text-brand-600"></i>
              Recent Users
            </h3>
            <div class="hidden md:flex items-center gap-3 text-xs">
              <span class="inline-flex items-center gap-1 rounded-full bg-emerald-50 text-emerald-700 px-2.5 py-0.5">
                <span class="h-2 w-2 rounded-full bg-emerald-500"></span> Approved
              </span>
              <span class="inline-flex items-center gap-1 rounded-full bg-amber-50 text-amber-700 px-2.5 py-0.5">
                <span class="h-2 w-2 rounded-full bg-amber-500"></span> Pending
              </span>
            </div>
          </div>

          <div class="overflow-x-auto">
            <table id="recentUsers" class="w-full text-sm pretty-table">
              <thead>
                <tr>
                  <th class="th">Name</th>
                  <th class="th">Email</th>
                  <th class="th">KYC</th>
                  <th class="th">Registered</th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($recentUsers)): ?>
                  <tr><td colspan="4" class="py-8 text-center text-gray-500">No users found</td></tr>
                <?php else: ?>
                  <?php
                    $avatarBg = ['bg-orange-600','bg-rose-600','bg-emerald-600','bg-blue-600','bg-violet-600','bg-amber-600'];
                    foreach ($recentUsers as $u):
                      $name    = trim($u['fullname'] ?? '');
                      $email   = trim($u['email'] ?? '');
                      $kyc     = (int)($u['kyc_verify'] ?? 0);
                      $regRaw  = $u['reg_date'] ?? '';
                      $regTs   = $regRaw ? strtotime($regRaw) : false;
                      $regDisp = $regTs ? date('M j, Y', $regTs) : htmlspecialchars($regRaw ?: '—');

                      $initials = '—';
                      if ($name !== '') {
                        $parts = preg_split('/\s+/', $name);
                        $first = mb_substr($parts[0], 0, 1, 'UTF-8');
                        $last  = isset($parts[count($parts)-1]) ? mb_substr($parts[count($parts)-1], 0, 1, 'UTF-8') : '';
                        $initials = strtoupper($first . $last);
                      } elseif ($email !== '') {
                        $initials = strtoupper(mb_substr($email, 0, 1, 'UTF-8'));
                      }
                      $idx = $email !== '' ? (crc32($email) % count($avatarBg)) : 0;
                      $chipClass = $avatarBg[$idx];
                      $kycBadge = $kyc
                        ? '<span class="badge badge-emerald"><i class="ri-check-line"></i> Approved</span>'
                        : '<span class="badge badge-amber"><i class="ri-time-line"></i> Pending</span>';
                  ?>
                  <tr class="tr">
                    <td class="td">
                      <div class="flex items-center gap-3">
                        <div class="h-7 w-7 rounded-full text-white text-xs font-semibold flex items-center justify-center <?=$chipClass?>">
                          <?= htmlspecialchars($initials) ?>
                        </div>
                        <div class="font-medium text-slate-800"></div>
                      </div>
                    </td>
                    <td class="td">
                      <?php if ($email): ?>
                        <a href="mailto:<?= htmlspecialchars($email) ?>" class="text-slate-700 hover:text-brand-600"><?= htmlspecialchars($email) ?></a>
                      <?php else: ?>—<?php endif; ?>
                    </td>
                    <td class="td"><?= $kycBadge ?></td>
                    <td class="td"><span class="text-slate-700"><?= $regDisp ?></span></td>
                  </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </section>

      <?php include __DIR__ . '/footer.php'; ?>
    </div>
  </main>
</div>

<!-- DataTables init -->
<script>
$(function(){
  const common = {
    autoWidth:false,
    pageLength:8,
    lengthMenu:[[8,16,32,64,-1],[8,16,32,64,'All']],
    language:{ search:'', searchPlaceholder:'Search...' }
  };
  $('#depositQueueTable').DataTable({ ...common, order:[[3,'desc']] });
  $('#withdrawQueueTable').DataTable({ ...common, order:[[3,'desc']] });

  if (window.jQuery && jQuery.fn && jQuery.fn.DataTable) {
    $('#recentUsers').DataTable({
      responsive: true,
      pageLength: 8,
      lengthChange: false,
      order: [[3, 'desc']], // Registered desc
      language: { search: "", searchPlaceholder: "Search users..." },
      dom: '<"dt-top flex items-center justify-between gap-2"f>t<"dt-bottom flex items-center justify-between gap-2"ip>'
    });
    $('.dataTables_filter input').addClass('border border-slate-200 rounded-lg px-3 py-2 focus:outline-none focus:ring focus:border-brand-500').css({width:'220px'});
    $('.dataTables_info').addClass('text-slate-500');
    $('.dataTables_paginate').addClass('text-slate-700');
  }
});
</script>

<!-- Charts -->
<script>
(function(){
  // Finance stacked (Deposits vs Withdrawals)
  const canvas = document.getElementById('financeStacked');
  if (canvas){
    const totalDeposits  = <?= json_encode((float)$totalDeposit) ?>;
    const totalWithdraws = <?= json_encode((float)$totalWithdraw) ?>;
    const hasTotals = (totalDeposits > 0 || totalWithdraws > 0);
    const ctx = canvas.getContext('2d');

    const gradDep = ctx.createLinearGradient(0, 0, canvas.width, 0);
    gradDep.addColorStop(0, 'rgba(16,185,129,0.35)');
    gradDep.addColorStop(1, 'rgba(16,185,129,0.10)');
    const gradWdr = ctx.createLinearGradient(0, 0, canvas.width, 0);
    gradWdr.addColorStop(0, 'rgba(244,63,94,0.35)');
    gradWdr.addColorStop(1, 'rgba(244,63,94,0.10)');

    const valueLabels = {
      id: 'valueLabels',
      afterDatasetsDraw(chart){
        if (!hasTotals) return;
        const { ctx } = chart;
        ctx.save();
        ctx.font = '600 12px system-ui, -apple-system, Segoe UI, Roboto';
        ctx.textBaseline = 'middle';
        const ds0 = chart.getDatasetMeta(0);
        const ds1 = chart.getDatasetMeta(1);
        [ds0, ds1].forEach((meta, i) => {
          const item = meta.data[0]; if (!item) return;
          const val = i === 0 ? totalDeposits : totalWithdraws;
          const { x, y } = item.tooltipPosition();
          const offset = i === 0 ? -30 : 30;
          ctx.fillStyle = '#0f172a';
          ctx.textAlign = i === 0 ? 'right' : 'left';
          ctx.fillText('$' + Number(val).toLocaleString(), x + offset, y);
        });
        ctx.restore();
      }
    };

    const data = hasTotals ? {
      labels: ['All-time'],
      datasets: [
        { label: 'Deposits',    data: [totalDeposits],  backgroundColor: gradDep, borderColor: '#10b981', borderWidth: 1.5, borderRadius: 14, barThickness: 36, stack: 'x' },
        { label: 'Withdrawals', data: [totalWithdraws], backgroundColor: gradWdr, borderColor: '#f43f5e', borderWidth: 1.5, borderRadius: 14, barThickness: 36, stack: 'x' }
      ]
    } : { labels: [], datasets:[{label:'No data', data:[]}] };

    if (window.financeStackedChart) window.financeStackedChart.destroy();
    window.financeStackedChart = new Chart(ctx, {
      type: 'bar',
      data,
      options: {
        indexAxis: 'y',
        responsive: true,
        maintainAspectRatio: false,
        animation: { duration: 850, easing: 'easeOutQuart' },
        scales: {
          x: { stacked: true, beginAtZero: true, ticks: { color: '#64748B' }, grid: { color: '#E5E7EB', drawBorder: false } },
          y: { stacked: true, ticks: { color: '#64748B', font: { weight: 600 } }, grid: { display: false } }
        },
        plugins: {
          legend: { labels: { usePointStyle: true } },
          tooltip: {
            backgroundColor: 'rgba(255,255,255,.95)',
            titleColor: '#0F172A', bodyColor: '#0F172A',
            borderColor: '#E5E7EB', borderWidth: 1, padding: 10,
            callbacks: { label: (ctx) => '$' + Number(ctx.parsed.x).toLocaleString() }
          }
        }
      },
      plugins: [valueLabels]
    });
  }

  // KYC doughnut (Approved vs Pending) — FIXED
  (function(){
    const el = document.getElementById('kycPie'); if (!el) return;
    const approved = <?= json_encode((int)$kycApproved) ?>;
    const pending  = <?= json_encode((int)$kycPending) ?>;
    new Chart(el.getContext('2d'), {
      type: 'doughnut',
      data: {
        labels: ['Approved','Pending'],
        datasets: [{
          data: [approved, pending],
          backgroundColor: ['#10b981','#f59e0b'],
          borderColor: ['#059669','#d97706']
        }]
      },
      options: {
        responsive: true,
        plugins: {
          legend: { position: 'bottom' }
        },
        cutout: '65%'
      }
    });
  })();

  // Top Countries (Logins – last 7 days)
  (function(){
    const el = document.getElementById('countryBar'); if (!el) return;
    const labels = [
      <?php foreach ($topCountries as $r) echo "'".addslashes($r['country'])."',"; ?>
    ];
    const dataVals = [
      <?php foreach ($topCountries as $r) echo (int)$r['cnt'].","; ?>
    ];
    new Chart(el.getContext('2d'), {
      type: 'bar',
      data: {
        labels: labels,
        datasets: [{
          label: 'Logins',
          data: dataVals,
          backgroundColor: '#60a5fa',
          borderColor: '#3b82f6'
        }]
      },
      options: {
        responsive:true,
        scales: {
          y: { beginAtZero: true, ticks:{ precision:0 } }
        },
        plugins: { legend: { display:false } }
      }
    });
  })();

  // Volume by Account Type (SUM volume by account_name)
  (function(){
    const el = document.getElementById('volumePie'); if (!el) return;
    const labels = [
      <?php foreach ($volumesByType as $r) echo "'".addslashes($r['account_name'])."',"; ?>
    ];
    const dataVals = [
      <?php foreach ($volumesByType as $r) echo (float)$r['total_volume'].","; ?>
    ];
    new Chart(el.getContext('2d'), {
      type: 'pie',
      data: {
        labels: labels,
        datasets: [{
          data: dataVals,
          backgroundColor: ['#f59e0b','#10b981','#3b82f6','#ef4444','#8b5cf6','#ec4899','#22d3ee','#84cc16','#f97316','#6366f1']
        }]
      },
      options: {
        responsive:true,
        plugins: { legend: { position:'bottom' } }
      }
    });
  })();
})();
</script>
</body>
</html>
