<?php
require_once __DIR__ . '/auth.php';

// ==========================================
// 0. SET PAKISTAN TIMEZONE (PHP & MySQL)
// ==========================================
date_default_timezone_set('Asia/Karachi');
$today = date('Y-m-d');

try {
    // Ensures MySQL functions like '$today' and NOW() use PKT
    $pdo->exec("SET time_zone = '+05:00'");
} catch (Exception $e) {}

// ==========================================
// 1. ADMIN SETTINGS & REAL P&L CONFIG
// ==========================================
// Enter the total amount of your OWN money you deposited to fund withdrawals
// Update this number whenever you inject your own cash into the system.
$admin_capital = 14000 ; 

// ==========================================
// 2. WINGO POOL UPDATE LOGIC
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_pool'])) {
    $new_balance = (float)$_POST['pool_balance'];
    try {
        $pdo->prepare("UPDATE wingo_pool SET balance = ? WHERE id = 1")->execute([$new_balance]);
    } catch(Exception $e) {}
    header("Location: index.php");
    exit;
}

// Fetch Pool Balance
$wingo_pool = 0;
try {
    $wingo_pool = (float)$pdo->query("SELECT balance FROM wingo_pool WHERE id=1")->fetchColumn();
} catch(Exception $e) {}

// ==========================================
// 3. GENERAL STATS & TAX CALCULATIONS (ACTIVE ONLY)
// ==========================================
$total_users   = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE isbanned = 0 AND is_demo = 0")->fetchColumn();
$today_users   = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE DATE(created_at)='$today' AND isbanned = 0 AND is_demo = 0")->fetchColumn();

$pending_dep   = (int)$pdo->query("SELECT COUNT(*) FROM deposits d JOIN users u ON d.user_id = u.id WHERE d.status='pending' AND u.isbanned = 0 AND u.is_demo = 0")->fetchColumn();
$pending_wd    = (int)$pdo->query("SELECT COUNT(*) FROM withdrawals w JOIN users u ON w.user_id = u.id WHERE w.status='pending' AND u.isbanned = 0 AND u.is_demo = 0")->fetchColumn();
$open_tick     = (int)$pdo->query("SELECT COUNT(*) FROM tickets t JOIN users u ON t.user_id = u.id WHERE t.status IN('Open','In Progress') AND u.isbanned = 0")->fetchColumn();
$total_gc      = (int)$pdo->query("SELECT COUNT(*) FROM giftcodes WHERE status=1")->fetchColumn();

$dep_stats = $pdo->query("
    SELECT 
        COALESCE(SUM(d.amount), 0) as gross_dep,
        COALESCE(SUM(
            CASE 
                WHEN LOWER(d.method) LIKE '%jazz%' OR LOWER(d.method) = 'pkrph' THEN d.amount * 0.08
                WHEN LOWER(d.method) LIKE '%easy%' OR LOWER(d.method) = 'pkrph-easy' THEN d.amount * 0.12
                ELSE 0 
            END
        ), 0) as dep_taxes
    FROM deposits d JOIN users u ON d.user_id = u.id WHERE d.status='approved' AND u.is_demo = 0 AND u.isbanned = 0
")->fetch(PDO::FETCH_ASSOC);

$total_dep_gross = (float)$dep_stats['gross_dep'];
$total_dep_tax   = (float)$dep_stats['dep_taxes'];
$total_dep_net   = $total_dep_gross - $total_dep_tax;

$today_dep_amt = (float)$pdo->query("SELECT COALESCE(SUM(d.amount),0) FROM deposits d JOIN users u ON d.user_id = u.id WHERE d.status='approved' AND DATE(d.created_at)='$today' AND u.is_demo = 0 AND u.isbanned = 0")->fetchColumn();

// --- WITHDRAWALS & PAYOUT TAXES ---
// Pay-OUT: PKR : 4% + 10
$wd_stats = $pdo->query("
    SELECT 
        COALESCE(SUM(w.amount), 0) as gross_wd,
        COALESCE(SUM((w.amount * 0.04) + 10), 0) as wd_taxes,
        COUNT(*) as wd_count
    FROM withdrawals w JOIN users u ON w.user_id = u.id WHERE w.status='approved' AND u.is_demo = 0 AND u.isbanned = 0
")->fetch(PDO::FETCH_ASSOC);

$total_wd_gross = (float)$wd_stats['gross_wd'];
$total_wd_tax   = (float)$wd_stats['wd_taxes'];
$total_wd_cost  = $total_wd_gross + $total_wd_tax; 

$today_wd_amt  = (float)$pdo->query("SELECT COALESCE(SUM(w.amount),0) FROM withdrawals w JOIN users u ON w.user_id = u.id WHERE w.status='approved' AND DATE(w.created_at)='$today' AND u.is_demo = 0 AND u.isbanned = 0")->fetchColumn();

// ==========================================
// 4. NEW DEEP STATS & REAL CASH FLOW
// ==========================================
// Only count balances of active users
$total_balance = (float)$pdo->query("SELECT COALESCE(SUM(balance),0) FROM users WHERE isbanned = 0 AND is_demo = 0")->fetchColumn();

// Game Stats
$bets_30s = $pdo->query("SELECT COUNT(*) as c, COALESCE(SUM(b.amount),0) as a, COALESCE(SUM(b.payout),0) as p, SUM(CASE WHEN b.status='win' THEN 1 ELSE 0 END) as wins, SUM(CASE WHEN b.status='loss' THEN 1 ELSE 0 END) as losses FROM wingo_bets b JOIN users u ON b.user_id = u.id WHERE u.is_demo = 0 AND u.isbanned = 0")->fetch(PDO::FETCH_ASSOC);
$today_bets_30s = $pdo->query("SELECT COUNT(*) as c, COALESCE(SUM(b.amount),0) as a, COALESCE(SUM(b.payout),0) as p, SUM(CASE WHEN b.status='win' THEN 1 ELSE 0 END) as wins, SUM(CASE WHEN b.status='loss' THEN 1 ELSE 0 END) as losses FROM wingo_bets b JOIN users u ON b.user_id = u.id WHERE DATE(b.created_at)='$today' AND u.is_demo = 0 AND u.isbanned = 0")->fetch(PDO::FETCH_ASSOC);

$bets_1m = $pdo->query("SELECT COUNT(*) as c, COALESCE(SUM(b.amount),0) as a, COALESCE(SUM(b.payout),0) as p, SUM(CASE WHEN b.status='win' THEN 1 ELSE 0 END) as wins, SUM(CASE WHEN b.status='loss' THEN 1 ELSE 0 END) as losses FROM wingo_bets_1min b JOIN users u ON b.user_id = u.id WHERE u.is_demo = 0 AND u.isbanned = 0")->fetch(PDO::FETCH_ASSOC);
$today_bets_1m = $pdo->query("SELECT COUNT(*) as c, COALESCE(SUM(b.amount),0) as a, COALESCE(SUM(b.payout),0) as p, SUM(CASE WHEN b.status='win' THEN 1 ELSE 0 END) as wins, SUM(CASE WHEN b.status='loss' THEN 1 ELSE 0 END) as losses FROM wingo_bets_1min b JOIN users u ON b.user_id = u.id WHERE DATE(b.created_at)='$today' AND u.is_demo = 0 AND u.isbanned = 0")->fetch(PDO::FETCH_ASSOC);

$total_bets_count = $bets_30s['c'] + $bets_1m['c'];
$total_bets_amt   = $bets_30s['a'] + $bets_1m['a'];
$today_bets_count = $today_bets_30s['c'] + $today_bets_1m['c'];
$today_bets_amt   = $today_bets_30s['a'] + $today_bets_1m['a'];

// Win/Loss & House Metrics
$all_time_wins = $bets_30s['wins'] + $bets_1m['wins'];
$all_time_losses = $bets_30s['losses'] + $bets_1m['losses'];
$today_wins = $today_bets_30s['wins'] + $today_bets_1m['wins'];
$today_losses = $today_bets_30s['losses'] + $today_bets_1m['losses'];

$all_wl_ratio = $all_time_losses > 0 ? number_format($all_time_wins / $all_time_losses, 2) : $all_time_wins;
$today_wl_ratio = $today_losses > 0 ? number_format($today_wins / $today_losses, 2) : $today_wins;

// GAME Profit (Bets - Payouts)
$all_time_payout = $bets_30s['p'] + $bets_1m['p'];
$today_payout = $today_bets_30s['p'] + $today_bets_1m['p'];

$house_profit_all = $total_bets_amt - $all_time_payout;
$house_win_pct_all = $total_bets_amt > 0 ? ($house_profit_all / $total_bets_amt) * 100 : 0;
$house_profit_today = $today_bets_amt - $today_payout;
$house_win_pct_today = $today_bets_amt > 0 ? ($house_profit_today / $today_bets_amt) * 100 : 0;

// REAL CASH FLOW (The absolute truth)
$real_user_deposits_net = $total_dep_net - $admin_capital; 
$real_pnl = $real_user_deposits_net - $total_wd_cost;

// ==========================================
// 5. DAILY TIP GENERATOR
// ==========================================
$daily_tip = "System running smoothly. Active users are stable.";
if ($real_pnl < 0) {
    $daily_tip = "URGENT: You are operating at a net CASH loss of Rs" . number_format(abs($real_pnl), 0) . ". The gateway fees and withdrawals are outpacing real user deposits. Adjust game win logic or reduce withdrawal frequency.";
} elseif ($house_win_pct_today > 45) {
    $daily_tip = "Game win percentage is very high today. Remember the psychology of satisfaction: letting users win occasionally keeps them returning.";
} elseif ($pending_dep > 10) {
    $daily_tip = "High number of pending deposits. Approve these quickly to encourage immediate betting volume!";
} elseif ($today_users < 3) {
    $daily_tip = "Low new user acquisition today. Consider generating and sharing gift codes, or contacting your top agents.";
}

// ==========================================
// 6. CHART DATA (Last 7 Days - Active Only)
// ==========================================
$chart_labels = $chart_users = $chart_deps = [];
for ($i=6;$i>=0;$i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $chart_labels[] = date('M d', strtotime("-$i days"));
    $chart_users[]  = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE DATE(created_at)='$d' AND isbanned=0 AND is_demo=0")->fetchColumn();
    $chart_deps[]   = (float)$pdo->query("SELECT COALESCE(SUM(d.amount),0) FROM deposits d JOIN users u ON d.user_id = u.id WHERE d.status='approved' AND DATE(d.created_at)='$d' AND u.is_demo=0 AND u.isbanned=0")->fetchColumn();
}

// ==========================================
// 7. LEADERBOARDS & DEEP ANALYTICS (ACTIVE ONLY)
// ==========================================
$fetch_lb = function($query) use ($pdo) {
    try { return $pdo->query($query)->fetchAll(); } 
    catch(Exception $e) { return []; }
};

// Winners & Losers
$top_profiters = $fetch_lb("SELECT u.number, SUM(b.payout - b.amount) as amt FROM wingo_bets b JOIN users u ON b.user_id = u.id WHERE DATE(b.created_at) = '$today' AND b.status = 'win' AND u.isbanned=0 AND u.is_demo=0 GROUP BY b.user_id ORDER BY amt DESC LIMIT 5");
$top_losers_today = $fetch_lb("SELECT u.number, SUM(b.amount) as amt FROM wingo_bets b JOIN users u ON b.user_id = u.id WHERE DATE(b.created_at) = '$today' AND b.status = 'loss' AND u.isbanned=0 AND u.is_demo=0 GROUP BY b.user_id ORDER BY amt DESC LIMIT 5");

// Betting Volume
$top_bettor_all = $fetch_lb("SELECT u.number, SUM(b.amount) as amt FROM wingo_bets b JOIN users u ON b.user_id = u.id WHERE u.isbanned=0 AND u.is_demo=0 GROUP BY b.user_id ORDER BY amt DESC LIMIT 5");
$top_bettor_today = $fetch_lb("SELECT u.number, SUM(b.amount) as amt FROM wingo_bets b JOIN users u ON b.user_id = u.id WHERE DATE(b.created_at) = '$today' AND u.isbanned=0 AND u.is_demo=0 GROUP BY b.user_id ORDER BY amt DESC LIMIT 5");

// Financial Movers
$top_dep_all = $fetch_lb("SELECT u.number, SUM(d.amount) as amt FROM deposits d JOIN users u ON d.user_id = u.id WHERE d.status='approved' AND u.isbanned=0 AND u.is_demo=0 GROUP BY u.id ORDER BY amt DESC LIMIT 5");
$top_dep_today = $fetch_lb("SELECT u.number, SUM(d.amount) as amt FROM deposits d JOIN users u ON d.user_id = u.id WHERE d.status='approved' AND DATE(d.created_at) = '$today' AND u.isbanned=0 AND u.is_demo=0 GROUP BY u.id ORDER BY amt DESC LIMIT 5");
$top_wd_all = $fetch_lb("SELECT u.number, SUM(w.amount) as amt FROM withdrawals w JOIN users u ON w.user_id = u.id WHERE w.status='approved' AND u.isbanned=0 AND u.is_demo=0 GROUP BY u.id ORDER BY amt DESC LIMIT 5");
$top_wd_today = $fetch_lb("SELECT u.number, SUM(w.amount) as amt FROM withdrawals w JOIN users u ON w.user_id = u.id WHERE w.status='approved' AND DATE(w.created_at) = '$today' AND u.isbanned=0 AND u.is_demo=0 GROUP BY u.id ORDER BY amt DESC LIMIT 5");

$top_agents = $fetch_lb("SELECT referrer.number, COUNT(referred.id) as amt FROM users referrer JOIN users referred ON referrer.refercode = referred.referedby WHERE referred.referedby IS NOT NULL AND referred.referedby != '' AND referrer.isbanned=0 AND referred.isbanned=0 AND referrer.is_demo=0 AND referred.is_demo=0 GROUP BY referrer.id ORDER BY amt DESC LIMIT 5");
$top_balances = $fetch_lb("SELECT number, balance as amt FROM users WHERE isbanned=0 AND is_demo=0 ORDER BY balance DESC LIMIT 5");

// ==========================================
// 8. LATEST ACTIONS (Wingo & Deposits)
// ==========================================
$wingo_30s_bets = $fetch_lb("SELECT b.*, u.number FROM wingo_bets b JOIN users u ON b.user_id = u.id WHERE u.is_demo = 0 AND u.isbanned = 0 ORDER BY b.id DESC LIMIT 10");
$wingo_1m_bets  = $fetch_lb("SELECT b.*, u.number FROM wingo_bets_1min b JOIN users u ON b.user_id = u.id WHERE u.is_demo = 0 AND u.isbanned = 0 ORDER BY b.id DESC LIMIT 10");
$last_20_deposits = $fetch_lb("SELECT d.*, u.number FROM deposits d JOIN users u ON d.user_id = u.id WHERE u.is_demo = 0 AND u.isbanned = 0 ORDER BY d.id DESC LIMIT 20");

?><!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Dashboard — PakClub Admin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{background:#0b0e18;color:#e8eaf0;font-family:'Segoe UI',sans-serif;display:flex;min-height:100vh}
.main{flex:1;display:flex;flex-direction:column;overflow-x:hidden}
.topbar{background:#111827;border-bottom:1px solid rgba(255,255,255,.07);padding:16px 28px;display:flex;align-items:center;justify-content:space-between}
.topbar h2{font-size:20px;font-weight:700;color:#fff}
.topbar-right{display:flex;align-items:center;gap:16px;color:#8892a4;font-size:13px}
.content{padding:28px;flex:1}

/* Tip Box */
.daily-tip {background: #1e2130; border-left: 4px solid #f59e0b; padding: 18px 24px; border-radius: 8px; margin-bottom: 28px; display:flex; align-items:center; gap: 16px;}
.tip-icon {font-size: 24px; color: #f59e0b;}
.tip-content h4 {color: #fff; margin-bottom: 4px; font-size: 15px;}
.tip-content p {color: #9ca3af; font-size: 13px;}

/* Wingo Pool Form */
.pool-manager {background: #1e2130; border: 1px solid rgba(255,255,255,.07); border-radius: 14px; padding: 20px; margin-bottom: 28px; display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:16px;}
.pool-title {font-weight: 700; color: #fff; display:flex; align-items:center; gap:10px; font-size:16px;}
.pool-form {display:flex; gap:10px; flex-wrap:wrap; align-items:center;}
.pool-input {background: #111827; border: 1px solid rgba(255,255,255,.1); padding: 10px 16px; border-radius: 8px; color:#fff; font-weight:bold; font-size:16px; width: 200px; outline:none;}
.pool-btn {background: #22c55e; color: #fff; border: none; padding: 10px 20px; border-radius: 8px; font-weight: 600; cursor: pointer; transition: background .2s;}
.pool-btn:hover {background: #16a34a;}

/* Stats Grid */
.stats-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:16px;margin-bottom:28px}
.stat-card{background:#1e2130;border:1px solid rgba(255,255,255,.07);border-radius:14px;padding:22px 20px;display:flex;flex-direction:column;gap:10px;transition:transform .2s; position:relative; overflow:hidden;}
.stat-card:hover{transform:translateY(-2px)}
.stat-icon{width:44px;height:44px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:18px}
.stat-val{font-size:22px;font-weight:800;color:#fff; z-index:1;}
.stat-label{font-size:11px;color:#8892a4;text-transform:uppercase;letter-spacing:.6px; z-index:1; white-space:nowrap;}
.stat-sub{font-size:12px;margin-top:4px; z-index:1;}
.stat-sub.up{color:#22c55e} .stat-sub.warn{color:#f59e0b} .stat-sub.info{color:#3b82f6} .stat-sub.neutral{color:#a855f7} .stat-sub.danger{color:#ef4444}

/* Icon Colors */
.icon-orange{background:rgba(242,109,15,.15);color:#f26d0f}
.icon-green{background:rgba(34,197,94,.15);color:#22c55e}
.icon-blue{background:rgba(59,130,246,.15);color:#3b82f6}
.icon-red{background:rgba(239,68,68,.15);color:#ef4444}
.icon-purple{background:rgba(168,85,247,.15);color:#a855f7}
.icon-yellow{background:rgba(245,158,11,.15);color:#f59e0b}
.icon-pink{background:rgba(236,72,153,.15);color:#ec4899}
.icon-teal{background:rgba(20,184,166,.15);color:#14b8a6}
.icon-cyan{background:rgba(6,182,212,.15);color:#06b6d4}

/* Panels */
.panels{display:grid;grid-template-columns:repeat(auto-fit, minmax(280px, 1fr));gap:20px;margin-bottom:24px}
.panel{background:#1e2130;border:1px solid rgba(255,255,255,.07);border-radius:14px;overflow:hidden;display:flex;flex-direction:column;}
.panel-head{padding:18px 20px;border-bottom:1px solid rgba(255,255,255,.07);display:flex;align-items:center;justify-content:space-between;background:rgba(0,0,0,0.2)}
.panel-title{font-size:15px;font-weight:600;color:#fff;display:flex;align-items:center;gap:8px;}
.panel-link{font-size:12px;color:#f26d0f;text-decoration:none;font-weight:600;}
.chart-wrap{padding:20px;height:250px}

/* Tables */
.table-responsive{overflow-x:auto; -webkit-overflow-scrolling: touch;}
table{width:100%;border-collapse:collapse;font-size:13px}
th{text-align:left;padding:12px 16px;color:#8892a4;font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:.7px;border-bottom:1px solid rgba(255,255,255,.05);background:rgba(0,0,0,0.1); white-space:nowrap;}
td{padding:12px 16px;border-bottom:1px solid rgba(255,255,255,.04);color:#c9ccd6; white-space:nowrap;}
tr:last-child td{border-bottom:none}
tr:hover td{background:rgba(255,255,255,.02)}

/* Pills & Badges */
.pill{padding:4px 10px;border-radius:20px;font-size:11px;font-weight:700;display:inline-block;text-align:center;}
.pill-pending{background:rgba(245,158,11,.15);color:#f59e0b}
.pill-approved{background:rgba(34,197,94,.15);color:#22c55e}
.pill-rejected, .pill-failed, .pill-canceled{background:rgba(239,68,68,.15);color:#ef4444}
.pill-win{background:rgba(34,197,94,.15);color:#22c55e}
.pill-loss{background:rgba(239,68,68,.15);color:#ef4444}
.dot{display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:5px;}

/* Clean Colors - No Glow */
.color-red{background:#ef4444;}
.color-green{background:#22c55e;}
.color-violet{background:#a855f7;}

/* Leaderboard Rows */
.lb-row{display:flex;align-items:center;justify-content:space-between;padding:12px 20px;border-bottom:1px solid rgba(255,255,255,.04);}
.lb-row:last-child{border-bottom:none;}
.lb-user{display:flex;align-items:center;gap:12px;}
.lb-rank{font-size:16px;font-weight:800;color:#4b5563;width:20px;text-align:center;}
.lb-rank.gold{color:#fbbf24;} .lb-rank.silver{color:#9ca3af;} .lb-rank.bronze{color:#b45309;}
.lb-name{font-weight:600;color:#fff;font-size:13px;}
.lb-score{font-weight:700;font-size:13px;}

@media(max-width:900px){.panels{grid-template-columns:1fr}}
@media(max-width:600px){
    .stats-grid{grid-template-columns:repeat(2, 1fr);}
    .pool-manager{flex-direction:column; align-items:stretch;}
    .pool-form{flex-direction:column; align-items:stretch;}
    .pool-input{width:100%;}
    .topbar-right{display:none;}
}
</style>
</head><body>
<?php include 'sidebar.php'; ?>
<div class="main">
  <div class="topbar">
    <h2><i class="fa-solid fa-gauge-high" style="color:#f26d0f;margin-right:10px"></i>Dashboard Overview</h2>
    <div class="topbar-right">
        <span style="color:#22c55e;font-weight:600;margin-right:10px"><i class="fa-solid fa-filter"></i> Banned Users Filtered</span>
        <i class="fa-solid fa-clock"></i><?= date('D, d M Y H:i (T)') ?>
    </div>
  </div>
  <div class="content">

    <div class="daily-tip">
        <div class="tip-icon"><i class="fa-solid fa-lightbulb"></i></div>
        <div class="tip-content">
            <h4>Daily Strategy Tip</h4>
            <p><?= htmlspecialchars($daily_tip) ?></p>
        </div>
    </div>

    <div class="pool-manager">
        <div class="pool-title"><i class="fa-solid fa-coins" style="color:#fbbf24;"></i> Active Wingo Pool Balance</div>
        <form class="pool-form" method="POST">
            <input type="number" step="0.01" name="pool_balance" value="<?= htmlspecialchars((string)$wingo_pool) ?>" class="pool-input" required>
            <button type="submit" name="update_pool" class="pool-btn">Update Pool</button>
        </form>
    </div>

    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon icon-blue"><i class="fa-solid fa-users"></i></div>
        <div class="stat-val"><?= number_format($total_users) ?></div>
        <div class="stat-label">Active Users</div>
        <div class="stat-sub info">+<?= $today_users ?> today</div>
      </div>

      <div class="stat-card" style="border-color: <?= $real_pnl >= 0 ? 'rgba(34,197,94,0.3)' : 'rgba(239,68,68,0.3)' ?>;">
        <div class="stat-icon <?= $real_pnl >= 0 ? 'icon-green' : 'icon-red' ?>">
            <i class="fa-solid <?= $real_pnl >= 0 ? 'fa-arrow-trend-up' : 'fa-arrow-trend-down' ?>"></i>
        </div>
        <div class="stat-val" style="color: <?= $real_pnl >= 0 ? '#22c55e' : '#ef4444' ?>">
            Rs<?= number_format($real_pnl, 0) ?>
        </div>
        <div class="stat-label">Real Cash Flow (P&L)</div>
        <div class="stat-sub neutral">Net Deps - WDs - Admin Capital</div>
      </div>



      <div class="stat-card">
        <div class="stat-icon icon-red"><i class="fa-solid fa-receipt"></i></div>
        <div class="stat-val">Rs<?= number_format($total_dep_tax + $total_wd_tax, 0) ?></div>
        <div class="stat-label">Gateway Taxes Lost</div>
        <div class="stat-sub warn">Dep Tax: Rs<?= number_format($total_dep_tax) ?> | WD: Rs<?= number_format($total_wd_tax) ?></div>
      </div>

      <div class="stat-card" style="border-color: rgba(168, 85, 247, 0.3);">
        <div class="stat-icon icon-purple"><i class="fa-solid fa-building-columns"></i></div>
        <div class="stat-val"><?= number_format($house_win_pct_today, 1) ?>%</div>
        <div class="stat-label">Today's Game Win Margin</div>
        <div class="stat-sub neutral">All time: <?= number_format($house_win_pct_all, 1) ?>%</div>
      </div>
      <div class="stat-card">
        <div class="stat-icon icon-cyan"><i class="fa-solid fa-scale-balanced"></i></div>
        <div class="stat-val"><?= $today_wl_ratio ?></div>
        <div class="stat-label">Today's W/L Ratio</div>
        <div class="stat-sub info">All time: <?= $all_wl_ratio ?></div>
      </div>

      <div class="stat-card">
        <div class="stat-icon icon-green"><i class="fa-solid fa-money-bill-wave"></i></div>
        <div class="stat-val">Rs<?= number_format($today_dep_amt,0) ?></div>
        <div class="stat-label">Today's Gross Deposits</div>
        <div class="stat-sub up">All time: Rs<?= number_format($total_dep_gross,0) ?></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon icon-red"><i class="fa-solid fa-money-bill-transfer"></i></div>
        <div class="stat-val">Rs<?= number_format($today_wd_amt,0) ?></div>
        <div class="stat-label">Today's Gross Withdraws</div>
        <div class="stat-sub neutral">All time: Rs<?= number_format($total_wd_gross,0) ?></div>
      </div>

      <div class="stat-card" style="border-color: rgba(20, 184, 166, 0.3);">
        <div class="stat-icon icon-teal"><i class="fa-solid fa-wallet"></i></div>
        <div class="stat-val">Rs<?= number_format($total_balance, 0) ?></div>
        <div class="stat-label">Total Active Balances</div>
        <div class="stat-sub info">Held by <?= number_format($total_users) ?> active users</div>
      </div>
      <div class="stat-card">
        <div class="stat-icon icon-orange"><i class="fa-solid fa-dice"></i></div>
        <div class="stat-val">Rs<?= number_format($today_bets_amt,0) ?></div>
        <div class="stat-label">Today's Bet Volume</div>
        <div class="stat-sub warn">All Time: Rs<?= number_format($total_bets_amt,0) ?></div>
      </div>

      <div class="stat-card">
        <div class="stat-icon icon-yellow"><i class="fa-solid fa-hourglass-half"></i></div>
        <div class="stat-val"><?= $pending_dep ?></div>
        <div class="stat-label">Pending Deposits</div>
        <?php if($pending_dep>0): ?><div class="stat-sub warn"><a href="deposits.php" style="color:inherit">Review now →</a></div><?php endif; ?>
      </div>
      <div class="stat-card">
        <div class="stat-icon icon-red"><i class="fa-solid fa-clock-rotate-left"></i></div>
        <div class="stat-val"><?= $pending_wd ?></div>
        <div class="stat-label">Pending Withdraws</div>
        <?php if($pending_wd>0): ?><div class="stat-sub warn"><a href="withdrawals.php" style="color:inherit">Review now →</a></div><?php endif; ?>
      </div>
    </div>

    <div class="panels">
      <div class="panel" style="grid-column: 1 / -1;">
        <div class="panel-head">
            <span class="panel-title"><i class="fa-solid fa-chart-line"></i> 7-Day Growth & Deposit Activity (Active Users Only)</span>
        </div>
        <div class="chart-wrap"><canvas id="actChart"></canvas></div>
      </div>
    </div>

    <?php 
    // Reusable template for leaderboards
    function render_lb($title, $icon, $color, $data, $prefix='', $suffix='', $empty_msg='No data') {
        echo '<div class="panel"><div class="panel-head"><span class="panel-title"><i class="fa-solid '.$icon.'" style="color:'.$color.'"></i> '.$title.'</span></div><div>';
        if(!$data) {
            echo '<div style="padding:20px;text-align:center;color:#6b7280;font-size:13px;">'.$empty_msg.'</div>';
        } else {
            $rank = 1; foreach($data as $row) {
                $cls = $rank==1?'gold':($rank==2?'silver':($rank==3?'bronze':''));
                $val = is_numeric($row['amt']) ? number_format((float)$row['amt'], 2) : $row['amt'];
                echo '<div class="lb-row"><div class="lb-user"><span class="lb-rank '.$cls.'">#'.$rank.'</span><span class="lb-name">'.htmlspecialchars($row['number']).'</span></div><span class="lb-score" style="color:'.$color.';">'.$prefix.str_replace('.00','',$val).$suffix.'</span></div>';
                $rank++;
            }
        }
        echo '</div></div>';
    }
    ?>

    <div class="panels" style="grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));">
        <?php 
        render_lb("Today's Top Depositors", "fa-arrow-down", "#22c55e", $top_dep_today, "Rs");
        render_lb("Today's Top Withdrawers", "fa-arrow-up", "#ef4444", $top_wd_today, "Rs");
        render_lb("Today's Top Bettors", "fa-dice", "#f59e0b", $top_bettor_today, "Rs");
        
        render_lb("All Time Biggest Depositors", "fa-vault", "#10b981", $top_dep_all, "Rs");
        render_lb("All Time Biggest Withdrawers", "fa-money-bill-transfer", "#ec4899", $top_wd_all, "Rs");
        render_lb("All Time Top Bettors", "fa-coins", "#f26d0f", $top_bettor_all, "Rs");
        ?>
    </div>

    <div class="panels" style="grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));">
        <?php
        render_lb("Today's Top Winners", "fa-trophy", "#eab308", $top_profiters, "+Rs");
        render_lb("Today's Top Losers", "fa-face-frown", "#ef4444", $top_losers_today, "-Rs");
        render_lb("Top Network Agents", "fa-network-wired", "#3b82f6", $top_agents, "", " refs");
        render_lb("Top Wallet Balances", "fa-sack-dollar", "#14b8a6", $top_balances, "Rs");
        ?>
    </div>

    <div class="panels" style="grid-template-columns: 1fr;">
      <div class="panel">
        <div class="panel-head">
            <span class="panel-title"><i class="fa-solid fa-money-bill-transfer" style="color:#10b981"></i> Last 20 Deposits (All Statuses)</span>
            <a href="deposits.php" class="panel-link">View all</a>
        </div>
        <div class="table-responsive">
            <table>
                <tr>
                    <th>User</th>
                    <th>Method</th>
                    <th>Amount</th>
                    <th>Status</th>
                    <th>Date & Time</th>
                </tr>
                <?php if(!$last_20_deposits) echo '<tr><td colspan="5" style="text-align:center;padding:15px">No deposits found</td></tr>'; ?>
                <?php foreach($last_20_deposits as $d): ?>
                <tr>
                    <td style="font-weight:bold;"><?= htmlspecialchars($d['number']) ?></td>
                    <td><?= htmlspecialchars(strtoupper((string)($d['method'] ?? 'N/A'))) ?></td>
                    <td style="color:#22c55e; font-weight:600;">Rs<?= number_format((float)$d['amount']) ?></td>
                    <td><span class="pill pill-<?= strtolower($d['status']) ?>"><?= ucfirst($d['status']) ?></span></td>
                    <td><?= date('d M Y, h:i A', strtotime($d['created_at'])) ?></td>
                </tr>
                <?php endforeach; ?>
            </table>
        </div>
      </div>
    </div>

    <div class="panels" style="grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));">
      <div class="panel">
        <div class="panel-head">
            <span class="panel-title"><i class="fa-solid fa-bolt" style="color:#f26d0f"></i> Wingo 30s - Last 10 Bets</span>
        </div>
        <div class="table-responsive">
            <table>
                <tr><th>User</th><th>Amount</th><th>Selection</th><th>Status</th><th>Payout</th></tr>
                <?php if(!$wingo_30s_bets) echo '<tr><td colspan="5" style="text-align:center;padding:15px">No bets yet</td></tr>'; ?>
                <?php foreach($wingo_30s_bets as $b): ?>
                <tr>
                    <td style="font-weight:bold;"><?= htmlspecialchars($b['number']) ?></td>
                    <td>Rs<?= number_format((float)$b['amount']) ?></td>
                    <td>
                        <?php if($b['size']) echo "<span class='pill' style='background:rgba(255,255,255,0.1)'>".ucfirst($b['size'])."</span>"; ?>
                        <?php if($b['color']): ?>
                            <?php foreach(explode(',',$b['color']) as $c) echo "<span class='dot color-".trim($c)."'></span>"; ?>
                        <?php endif; ?>
                    </td>
                    <td><span class="pill pill-<?= $b['status'] ?>"><?= ucfirst($b['status']) ?></span></td>
                    <td style="font-weight:600; color:<?= $b['status']=='win'?'#22c55e':($b['status']=='loss'?'#ef4444':'#9ca3af') ?>">
                        <?= $b['status']=='win' ? '+Rs'.number_format((float)$b['payout']) : ($b['status']=='loss'? '-Rs'.number_format((float)$b['amount']) : '...') ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </table>
        </div>
      </div>

      <div class="panel">
        <div class="panel-head">
            <span class="panel-title"><i class="fa-solid fa-stopwatch" style="color:#3b82f6"></i> Wingo 1 Min - Last 10 Bets</span>
        </div>
        <div class="table-responsive">
            <table>
                <tr><th>User</th><th>Amount</th><th>Selection</th><th>Status</th><th>Payout</th></tr>
                <?php if(!$wingo_1m_bets) echo '<tr><td colspan="5" style="text-align:center;padding:15px">No bets yet</td></tr>'; ?>
                <?php foreach($wingo_1m_bets as $b): ?>
                <tr>
                    <td style="font-weight:bold;"><?= htmlspecialchars($b['number']) ?></td>
                    <td>Rs<?= number_format((float)$b['amount']) ?></td>
                    <td>
                        <?php if($b['size']) echo "<span class='pill' style='background:rgba(255,255,255,0.1)'>".ucfirst($b['size'])."</span>"; ?>
                        <?php if($b['color']): ?>
                            <?php foreach(explode(',',$b['color']) as $c) echo "<span class='dot color-".trim($c)."'></span>"; ?>
                        <?php endif; ?>
                    </td>
                    <td><span class="pill pill-<?= $b['status'] ?>"><?= ucfirst($b['status']) ?></span></td>
                    <td style="font-weight:600; color:<?= $b['status']=='win'?'#22c55e':($b['status']=='loss'?'#ef4444':'#9ca3af') ?>">
                        <?= $b['status']=='win' ? '+Rs'.number_format((float)$b['payout']) : ($b['status']=='loss'? '-Rs'.number_format((float)$b['amount']) : '...') ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </table>
        </div>
      </div>
    </div>

  </div>
</div>
<script>
const ctx=document.getElementById('actChart').getContext('2d');
new Chart(ctx,{type:'bar',data:{
  labels:<?= json_encode($chart_labels) ?>,
  datasets:[
    {label:'Active Users Joined',data:<?= json_encode($chart_users) ?>,backgroundColor:'rgba(59,130,246,1)',borderRadius:4},
    {label:'Deposits (Rs)',data:<?= json_encode($chart_deps) ?>,backgroundColor:'rgba(242,109,15,1)',borderRadius:4,yAxisID:'y1'}
  ]
},options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{labels:{color:'#9ca3af',font:{size:11}}}},scales:{
  x:{ticks:{color:'#6b7280'},grid:{color:'rgba(255,255,255,.04)'}},
  y:{ticks:{color:'#6b7280'},grid:{color:'rgba(255,255,255,.04)'}},
  y1:{position:'right',ticks:{color:'#f26d0f'},grid:{display:false}}
}}});
</script>
</body></html>