<?php
require_once __DIR__ . '/../auth_helper.php';
require_admin();

$msg = ''; $err = '';

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $a = $_POST['admin_action'] ?? '';

        if ($a === 'logout') {
            unset($_SESSION['admin_ok']);
            redirect('login.php');
        }

        if ($a === 'save_announcement') {
            set_setting('announcement', (string)($_POST['announcement'] ?? ''));
            set_setting('announcement_type', (string)($_POST['announcement_type'] ?? 'info'));
            $msg = 'Announcement saved.';
        }

        if ($a === 'save_rules') {
            set_setting('withdraw_min', (string)($_POST['withdraw_min'] ?? '500'));
            set_setting('withdraw_max', (string)($_POST['withdraw_max'] ?? '25000'));
            set_setting('withdraw_fee', (string)($_POST['withdraw_fee'] ?? '0'));
            set_setting('deposit_min', (string)($_POST['deposit_min'] ?? '100'));
            set_setting('deposit_max', (string)($_POST['deposit_max'] ?? '100000'));
            set_setting('daily_withdraw_limit', (string)($_POST['daily_withdraw_limit'] ?? '50000'));
            $msg = 'Rules saved.';
        }

        if ($a === 'save_site_settings') {
            set_setting('site_name', (string)($_POST['site_name'] ?? 'CK444'));
            set_setting('site_status', (string)($_POST['site_status'] ?? '1'));
            set_setting('maintenance_msg', (string)($_POST['maintenance_msg'] ?? ''));
            set_setting('min_balance_withdraw', (string)($_POST['min_balance_withdraw'] ?? '0'));
            $msg = 'Site settings saved.';
        }

        if ($a === 'update_user_balance') {
            $uid = (int)($_POST['user_id'] ?? 0);
            $amt = (float)($_POST['amount'] ?? 0);
            $type = $_POST['balance_type'] ?? 'add';
            $reason = trim($_POST['reason'] ?? 'Admin adjustment');
            if ($uid <= 0) throw new Exception('Invalid user ID.');
            if ($type === 'add') {
                pdo()->prepare('UPDATE users SET balance=balance+? WHERE id=?')->execute([$amt, $uid]);
                addTransaction($uid, 'admin_credit', $amt, 'success', $reason);
                $msg = "Added " . money($amt) . " to user balance.";
            } elseif ($type === 'deduct') {
                $cur = (float)pdo()->prepare('SELECT balance FROM users WHERE id=?')->execute([$uid]) ? pdo()->prepare('SELECT balance FROM users WHERE id=?') : 0;
                pdo()->prepare('UPDATE users SET balance=GREATEST(0,balance-?) WHERE id=?')->execute([$amt, $uid]);
                addTransaction($uid, 'admin_debit', $amt, 'deducted', $reason);
                $msg = "Deducted " . money($amt) . " from user balance.";
            } elseif ($type === 'set') {
                pdo()->prepare('UPDATE users SET balance=? WHERE id=?')->execute([$amt, $uid]);
                addTransaction($uid, 'admin_set', $amt, 'success', $reason);
                $msg = "User balance set to " . money($amt) . ".";
            }
        }

        if ($a === 'toggle_user_status') {
            $uid = (int)($_POST['user_id'] ?? 0);
            $cur = pdo()->prepare('SELECT status FROM users WHERE id=?');
            $cur->execute([$uid]);
            $row = $cur->fetch();
            $newStatus = ($row['status'] === 'active') ? 'banned' : 'active';
            pdo()->prepare('UPDATE users SET status=? WHERE id=?')->execute([$newStatus, $uid]);
            $msg = "User status set to $newStatus.";
        }

        if ($a === 'deposit_decision') {
            $id = (string)($_POST['request_id'] ?? '');
            $decision = (string)($_POST['decision'] ?? '');
            $note = trim((string)($_POST['admin_note'] ?? ''));
            pdo()->beginTransaction();
            $st = pdo()->prepare("SELECT * FROM deposit_requests WHERE id=? AND status='pending' FOR UPDATE");
            $st->execute([$id]);
            $r = $st->fetch();
            if (!$r) throw new Exception('Deposit request not found or already reviewed.');
            if ($decision === 'approve') {
                pdo()->prepare('UPDATE users SET balance=balance+? WHERE id=?')->execute([$r['amount'], $r['user_id']]);
                pdo()->prepare("UPDATE deposit_requests SET status='approved',admin_note=?,reviewed_at=? WHERE id=?")->execute([$note, now_sql(), $id]);
                addTransaction($r['user_id'], 'deposit_approved', (float)$r['amount'], 'success', 'Deposit approved by admin. ' . $note);
                $msg = 'Deposit approved and balance added.';
            } else {
                pdo()->prepare("UPDATE deposit_requests SET status='rejected',admin_note=?,reviewed_at=? WHERE id=?")->execute([$note, now_sql(), $id]);
                addTransaction($r['user_id'], 'deposit_rejected', (float)$r['amount'], 'rejected', 'Deposit rejected. ' . $note);
                $msg = 'Deposit rejected.';
            }
            pdo()->commit();
        }

        if ($a === 'withdraw_decision') {
            $id = (string)($_POST['request_id'] ?? '');
            $decision = (string)($_POST['decision'] ?? '');
            $note = trim((string)($_POST['admin_note'] ?? ''));
            pdo()->beginTransaction();
            $st = pdo()->prepare("SELECT * FROM withdraw_requests WHERE id=? AND status='pending' FOR UPDATE");
            $st->execute([$id]);
            $r = $st->fetch();
            if (!$r) throw new Exception('Withdraw request not found or already reviewed.');
            if ($decision === 'approve') {
                pdo()->prepare("UPDATE withdraw_requests SET status='approved',admin_note=?,reviewed_at=? WHERE id=?")->execute([$note, now_sql(), $id]);
                addTransaction($r['user_id'], 'withdraw_approved', (float)$r['amount'], 'success', 'Withdraw paid by admin. ' . $note);
                $msg = 'Withdraw approved.';
            } else {
                pdo()->prepare('UPDATE users SET balance=balance+? WHERE id=?')->execute([$r['amount'], $r['user_id']]);
                pdo()->prepare("UPDATE withdraw_requests SET status='rejected',admin_note=?,reviewed_at=? WHERE id=?")->execute([$note, now_sql(), $id]);
                addTransaction($r['user_id'], 'withdraw_refund', (float)$r['amount'], 'success', 'Withdraw rejected and refunded. ' . $note);
                $msg = 'Withdraw rejected and refunded.';
            }
            pdo()->commit();
        }

        if ($a === 'add_payment') {
            $st = pdo()->prepare('INSERT INTO payment_methods(country_code,method_key,label,provider,wallet_number,instructions,active,sort_order,created_at) VALUES(?,?,?,?,?,?,?,?,?)');
            $st->execute([
                $_POST['country_code'], trim($_POST['method_key']), trim($_POST['label']),
                trim($_POST['provider']), trim($_POST['wallet_number']), trim($_POST['instructions']),
                (int)!empty($_POST['active']), (int)($_POST['sort_order'] ?? 0), now_sql()
            ]);
            $msg = 'Payment method added.';
        }

        if ($a === 'edit_payment') {
            $st = pdo()->prepare('UPDATE payment_methods SET label=?,provider=?,wallet_number=?,instructions=?,active=?,sort_order=? WHERE id=?');
            $st->execute([trim($_POST['label']), trim($_POST['provider']), trim($_POST['wallet_number']), trim($_POST['instructions']), (int)!empty($_POST['active']), (int)($_POST['sort_order'] ?? 0), (int)$_POST['id']]);
            $msg = 'Payment method updated.';
        }

        if ($a === 'delete_payment') {
            pdo()->prepare('DELETE FROM payment_methods WHERE id=?')->execute([(int)$_POST['id']]);
            $msg = 'Payment method deleted.';
        }

        if ($a === 'add_game') {
            $st = pdo()->prepare('INSERT INTO games(title,icon,provider,category,image_url,game_url,is_hot,active,sort_order,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)');
            $st->execute([
                trim($_POST['title']), trim($_POST['icon'] ?: '🎮'), trim($_POST['provider']),
                trim($_POST['category']), trim($_POST['image_url']), trim($_POST['game_url']),
                (int)!empty($_POST['is_hot']), (int)!empty($_POST['active']),
                (int)($_POST['sort_order'] ?? 100), now_sql()
            ]);
            $msg = 'Game added.';
        }

        if ($a === 'edit_game') {
            $st = pdo()->prepare('UPDATE games SET title=?,icon=?,provider=?,category=?,image_url=?,game_url=?,is_hot=?,active=?,sort_order=? WHERE id=?');
            $st->execute([
                trim($_POST['title']), trim($_POST['icon'] ?: '🎮'), trim($_POST['provider']),
                trim($_POST['category']), trim($_POST['image_url']), trim($_POST['game_url']),
                (int)!empty($_POST['is_hot']), (int)!empty($_POST['active']),
                (int)($_POST['sort_order'] ?? 100), (int)$_POST['id']
            ]);
            $msg = 'Game updated.';
        }

        if ($a === 'delete_game') {
            pdo()->prepare('DELETE FROM games WHERE id=?')->execute([(int)$_POST['id']]);
            $msg = 'Game deleted.';
        }

        if ($a === 'add_bonus') {
            $uid = (int)($_POST['user_id'] ?? 0);
            $amt = (float)($_POST['bonus_amount'] ?? 0);
            $reason = trim($_POST['bonus_reason'] ?? 'Admin bonus');
            if ($uid > 0 && $amt > 0) {
                pdo()->prepare('UPDATE users SET bonus=bonus+? WHERE id=?')->execute([$amt, $uid]);
                addTransaction($uid, 'admin_bonus', $amt, 'success', $reason);
                $msg = "Bonus of " . money($amt) . " added.";
            }
        }
    }
} catch (Throwable $e) {
    if (pdo()->inTransaction()) pdo()->rollBack();
    $err = $e->getMessage();
}

// Data fetching
$settings = all_settings();
$depPending = get_deposit_requests('pending');
$wPending = get_withdraw_requests('pending');
$completedDep = [];
foreach (get_deposit_requests('all') as $r) {
    if (($r['status'] ?? '') !== 'pending') $completedDep[] = $r;
}
$completedW = [];
foreach (get_withdraw_requests('all') as $r) {
    if (($r['status'] ?? '') !== 'pending') $completedW[] = $r;
}

$usersCount = (int)pdo()->query('SELECT COUNT(*) FROM users')->fetchColumn();
$activeUsers = (int)pdo()->query("SELECT COUNT(*) FROM users WHERE status='active'")->fetchColumn();
$bannedUsers = (int)pdo()->query("SELECT COUNT(*) FROM users WHERE status='banned'")->fetchColumn();
$depCount = count($depPending);
$wCount = count($wPending);
$balSum = (float)pdo()->query('SELECT COALESCE(SUM(balance),0) FROM users')->fetchColumn();
$totalDeposited = (float)pdo()->query("SELECT COALESCE(SUM(amount),0) FROM deposit_requests WHERE status='approved'")->fetchColumn();
$totalWithdrawn = (float)pdo()->query("SELECT COALESCE(SUM(amount),0) FROM withdraw_requests WHERE status='approved'")->fetchColumn();
$todayDep = (float)pdo()->query("SELECT COALESCE(SUM(amount),0) FROM deposit_requests WHERE status='approved' AND DATE(reviewed_at)=CURDATE()")->fetchColumn();
$todayWith = (float)pdo()->query("SELECT COALESCE(SUM(amount),0) FROM withdraw_requests WHERE status='approved' AND DATE(reviewed_at)=CURDATE()")->fetchColumn();

$methods = pdo()->query('SELECT * FROM payment_methods ORDER BY country_code, sort_order, id')->fetchAll();
$games = pdo()->query('SELECT * FROM games ORDER BY sort_order,id')->fetchAll();
$users = latest_users(200);

// Chart data - last 7 days deposits/withdrawals
$chartData = [];
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $label = date('D', strtotime($date));
    $dep = (float)pdo()->prepare("SELECT COALESCE(SUM(amount),0) FROM deposit_requests WHERE status='approved' AND DATE(reviewed_at)=?")->execute([$date]) ? pdo()->prepare("SELECT COALESCE(SUM(amount),0) FROM deposit_requests WHERE status='approved' AND DATE(reviewed_at)=?") : 0;
    $dep2 = pdo()->prepare("SELECT COALESCE(SUM(amount),0) FROM deposit_requests WHERE status='approved' AND DATE(reviewed_at)=?");
    $dep2->execute([$date]);
    $depVal = (float)$dep2->fetchColumn();
    $wit2 = pdo()->prepare("SELECT COALESCE(SUM(amount),0) FROM withdraw_requests WHERE status='approved' AND DATE(reviewed_at)=?");
    $wit2->execute([$date]);
    $witVal = (float)$wit2->fetchColumn();
    $chartData[] = ['label' => $label, 'dep' => $depVal, 'wit' => $witVal];
}

function admin_request_card(array $r, string $type): void
{
    $isD = $type === 'deposit';
    $id = htmlspecialchars($r['id']);
    $amount = htmlspecialchars(money($r['amount']));
    $method = htmlspecialchars($r['method_label'] ?? '');
    $phone = htmlspecialchars($r['phone'] ?? $r['user_id']);
    $country = htmlspecialchars($r['country_name'] ?? $r['country_code'] ?? '');
    $created = htmlspecialchars($r['created_at']);
    ?>
    <div class="req-card" data-id="<?= $id ?>">
        <div class="req-card-header">
            <div class="req-user-info">
                <div class="req-avatar"><?= strtoupper(substr($phone, 0, 2)) ?></div>
                <div>
                    <div class="req-phone"><?= $phone ?></div>
                    <div class="req-meta"><?= $country ?> · <?= $method ?></div>
                </div>
            </div>
            <div class="req-amount"><?= $amount ?></div>
        </div>
        <div class="req-details">
            <?php if ($isD): ?>
                <div class="req-detail-row"><span>Wallet</span><span><?= e($r['wallet_number']) ?></span></div>
                <div class="req-detail-row"><span>TrxID</span><span class="trxid"><?= e($r['trxid']) ?></span></div>
                <?php if (!empty($r['screenshot'])): ?>
                    <div class="req-detail-row"><span>Screenshot</span><a href="../<?= e($r['screenshot']) ?>" target="_blank" class="view-ss-link"><i class="fa fa-image"></i> View</a></div>
                <?php endif; ?>
            <?php else: ?>
                <div class="req-detail-row"><span>Name</span><span><?= e($r['full_name']) ?></span></div>
                <div class="req-detail-row"><span>Account</span><span><?= e($r['account_number']) ?></span></div>
            <?php endif; ?>
            <div class="req-detail-row"><span>Submitted</span><span><?= $created ?></span></div>
        </div>
        <form method="post" class="req-action-form">
            <input type="hidden" name="admin_action" value="<?= $isD ? 'deposit_decision' : 'withdraw_decision' ?>">
            <input type="hidden" name="request_id" value="<?= $id ?>">
            <input class="req-note-input" name="admin_note" placeholder="Note / reason (optional)...">
            <div class="req-btn-row">
                <button class="btn-approve" name="decision" value="approve">
                    <i class="fa fa-check"></i> Approve
                </button>
                <button class="btn-reject" name="decision" value="reject">
                    <i class="fa fa-times"></i> Reject
                </button>
            </div>
        </form>
    </div>
<?php }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
    <title>Admin Panel — CK444.COM</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Space+Mono:ital,wght@0,400;0,700;1,400&family=Syne:wght@400;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg:       #090c12;
            --bg2:      #0e1320;
            --bg3:      #131926;
            --bg4:      #1a2235;
            --border:   rgba(255,255,255,0.07);
            --border2:  rgba(255,255,255,0.12);
            --gold:     #f5c842;
            --gold2:    #ffda6a;
            --gold-dim: rgba(245,200,66,0.15);
            --green:    #22d689;
            --green-dim:rgba(34,214,137,0.13);
            --red:      #ff4f6a;
            --red-dim:  rgba(255,79,106,0.13);
            --blue:     #4f9eff;
            --blue-dim: rgba(79,158,255,0.13);
            --purple:   #a855f7;
            --text:     #e8eaf2;
            --text2:    #8b92a8;
            --text3:    #5a6278;
            --radius:   14px;
            --radius-sm:9px;
            --shadow:   0 8px 40px rgba(0,0,0,0.5);
            --font-head:'Syne', sans-serif;
            --font-mono:'Space Mono', monospace;
        }

        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

        html { scroll-behavior: smooth; }

        body {
            background: var(--bg);
            color: var(--text);
            font-family: var(--font-mono);
            font-size: 13px;
            line-height: 1.6;
            min-height: 100vh;
            overflow-x: hidden;
        }

        /* ─── SIDEBAR ─── */
        .sidebar {
            position: fixed;
            left: 0; top: 0; bottom: 0;
            width: 220px;
            background: var(--bg2);
            border-right: 1px solid var(--border);
            display: flex;
            flex-direction: column;
            z-index: 100;
            transition: transform .3s cubic-bezier(.4,0,.2,1);
        }

        .sidebar-logo {
            padding: 24px 20px 20px;
            border-bottom: 1px solid var(--border);
        }

        .sidebar-logo .site-name {
            font-family: var(--font-head);
            font-size: 20px;
            font-weight: 800;
            color: var(--gold);
            letter-spacing: 2px;
        }

        .sidebar-logo .admin-badge {
            font-size: 10px;
            color: var(--text3);
            letter-spacing: 3px;
            text-transform: uppercase;
        }

        .sidebar-nav {
            flex: 1;
            padding: 16px 0;
            overflow-y: auto;
        }

        .sidebar-nav a, .sidebar-nav button {
            display: flex;
            align-items: center;
            gap: 12px;
            width: 100%;
            padding: 11px 20px;
            color: var(--text2);
            text-decoration: none;
            font-family: var(--font-mono);
            font-size: 12.5px;
            background: none;
            border: none;
            cursor: pointer;
            transition: all .2s;
            position: relative;
        }

        .sidebar-nav a i, .sidebar-nav button i {
            width: 18px;
            text-align: center;
            font-size: 14px;
        }

        .sidebar-nav a:hover, .sidebar-nav button:hover {
            color: var(--text);
            background: rgba(255,255,255,0.04);
        }

        .sidebar-nav a.active {
            color: var(--gold);
            background: var(--gold-dim);
        }

        .sidebar-nav a.active::before {
            content: '';
            position: absolute;
            left: 0; top: 0; bottom: 0;
            width: 3px;
            background: var(--gold);
            border-radius: 0 2px 2px 0;
        }

        .nav-badge {
            margin-left: auto;
            background: var(--red);
            color: #fff;
            font-size: 10px;
            font-weight: 700;
            padding: 1px 7px;
            border-radius: 20px;
            min-width: 20px;
            text-align: center;
        }

        .nav-section-label {
            font-size: 10px;
            color: var(--text3);
            text-transform: uppercase;
            letter-spacing: 2px;
            padding: 16px 20px 6px;
        }

        .sidebar-footer {
            padding: 16px 20px;
            border-top: 1px solid var(--border);
        }

        .btn-logout {
            display: flex;
            align-items: center;
            gap: 10px;
            width: 100%;
            padding: 10px 14px;
            background: var(--red-dim);
            color: var(--red);
            border: 1px solid rgba(255,79,106,0.2);
            border-radius: var(--radius-sm);
            font-family: var(--font-mono);
            font-size: 12px;
            cursor: pointer;
            transition: all .2s;
        }

        .btn-logout:hover {
            background: var(--red);
            color: #fff;
        }

        /* ─── MAIN ─── */
        .main {
            margin-left: 220px;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* ─── TOPBAR ─── */
        .topbar {
            position: sticky;
            top: 0;
            background: rgba(9,12,18,.9);
            backdrop-filter: blur(20px);
            border-bottom: 1px solid var(--border);
            padding: 0 28px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            z-index: 90;
        }

        .topbar-title {
            font-family: var(--font-head);
            font-size: 17px;
            font-weight: 700;
            color: var(--text);
        }

        .topbar-right {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .topbar-time {
            font-size: 11px;
            color: var(--text3);
        }

        .status-indicator {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 11px;
            color: var(--green);
        }

        .status-dot {
            width: 7px; height: 7px;
            background: var(--green);
            border-radius: 50%;
            animation: pulse-dot 2s infinite;
        }

        @keyframes pulse-dot {
            0%, 100% { opacity: 1; transform: scale(1); }
            50% { opacity: .5; transform: scale(1.3); }
        }

        /* ─── CONTENT ─── */
        .content {
            flex: 1;
            padding: 28px;
        }

        .panel { display: none; }
        .panel.active { display: block; }

        /* ─── ALERTS ─── */
        .alert {
            padding: 13px 18px;
            border-radius: var(--radius-sm);
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 13px;
            animation: slideDown .3s ease;
        }

        @keyframes slideDown {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .alert-success { background: var(--green-dim); border: 1px solid rgba(34,214,137,.25); color: var(--green); }
        .alert-error { background: var(--red-dim); border: 1px solid rgba(255,79,106,.25); color: var(--red); }

        /* ─── STATS GRID ─── */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 16px;
            margin-bottom: 28px;
        }

        .stat-box {
            background: var(--bg2);
            border: 1px solid var(--border);
            border-radius: var(--radius);
            padding: 20px;
            position: relative;
            overflow: hidden;
            transition: border-color .2s, transform .2s;
        }

        .stat-box:hover {
            border-color: var(--border2);
            transform: translateY(-2px);
        }

        .stat-box::after {
            content: '';
            position: absolute;
            top: 0; left: 0; right: 0;
            height: 2px;
        }

        .stat-box.gold::after { background: linear-gradient(90deg, var(--gold), transparent); }
        .stat-box.green::after { background: linear-gradient(90deg, var(--green), transparent); }
        .stat-box.red::after { background: linear-gradient(90deg, var(--red), transparent); }
        .stat-box.blue::after { background: linear-gradient(90deg, var(--blue), transparent); }
        .stat-box.purple::after { background: linear-gradient(90deg, var(--purple), transparent); }

        .stat-icon {
            width: 38px; height: 38px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            margin-bottom: 14px;
        }

        .stat-box.gold .stat-icon { background: var(--gold-dim); color: var(--gold); }
        .stat-box.green .stat-icon { background: var(--green-dim); color: var(--green); }
        .stat-box.red .stat-icon { background: var(--red-dim); color: var(--red); }
        .stat-box.blue .stat-icon { background: var(--blue-dim); color: var(--blue); }
        .stat-box.purple .stat-icon { background: rgba(168,85,247,.13); color: var(--purple); }

        .stat-value {
            font-family: var(--font-head);
            font-size: 24px;
            font-weight: 800;
            color: var(--text);
            line-height: 1.2;
        }

        .stat-label {
            font-size: 11px;
            color: var(--text3);
            margin-top: 4px;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .stat-sub {
            font-size: 11px;
            color: var(--text3);
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1px solid var(--border);
        }

        /* ─── CHART ─── */
        .chart-wrap {
            background: var(--bg2);
            border: 1px solid var(--border);
            border-radius: var(--radius);
            padding: 20px;
            margin-bottom: 28px;
        }

        .chart-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 16px;
        }

        .chart-title {
            font-family: var(--font-head);
            font-size: 15px;
            font-weight: 700;
        }

        .chart-legend {
            display: flex;
            gap: 16px;
            font-size: 11px;
            color: var(--text2);
        }

        .chart-legend span { display: flex; align-items: center; gap: 6px; }
        .legend-dot { width: 8px; height: 8px; border-radius: 50%; }

        .bar-chart {
            display: flex;
            align-items: flex-end;
            gap: 10px;
            height: 120px;
        }

        .bar-group {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 4px;
            height: 100%;
            justify-content: flex-end;
        }

        .bar-pair {
            display: flex;
            gap: 3px;
            align-items: flex-end;
            width: 100%;
        }

        .bar {
            flex: 1;
            border-radius: 4px 4px 0 0;
            min-height: 3px;
            transition: opacity .2s;
        }

        .bar:hover { opacity: .8; }
        .bar.dep { background: var(--green); }
        .bar.wit { background: var(--red); }

        .bar-label {
            font-size: 10px;
            color: var(--text3);
            text-align: center;
        }

        /* ─── GRID LAYOUTS ─── */
        .grid-2 {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        /* ─── CARDS ─── */
        .card {
            background: var(--bg2);
            border: 1px solid var(--border);
            border-radius: var(--radius);
            padding: 22px;
        }

        .card-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 18px;
            padding-bottom: 14px;
            border-bottom: 1px solid var(--border);
        }

        .card-title {
            font-family: var(--font-head);
            font-size: 15px;
            font-weight: 700;
            color: var(--text);
        }

        .card-count {
            background: var(--bg4);
            color: var(--text2);
            font-size: 11px;
            padding: 3px 10px;
            border-radius: 20px;
            border: 1px solid var(--border);
        }

        /* ─── REQUEST CARDS ─── */
        .req-list { display: flex; flex-direction: column; gap: 14px; }

        .req-card {
            background: var(--bg3);
            border: 1px solid var(--border);
            border-radius: var(--radius-sm);
            padding: 16px;
            transition: border-color .2s;
        }

        .req-card:hover { border-color: var(--border2); }

        .req-card-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 12px;
        }

        .req-user-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .req-avatar {
            width: 36px; height: 36px;
            background: var(--gold-dim);
            color: var(--gold);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: var(--font-head);
            font-size: 12px;
            font-weight: 800;
        }

        .req-phone { font-weight: 700; font-size: 13px; }
        .req-meta { font-size: 11px; color: var(--text3); }

        .req-amount {
            font-family: var(--font-head);
            font-size: 18px;
            font-weight: 800;
            color: var(--gold);
        }

        .req-details {
            display: flex;
            flex-direction: column;
            gap: 5px;
            margin-bottom: 12px;
        }

        .req-detail-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 12px;
        }

        .req-detail-row span:first-child { color: var(--text3); }
        .req-detail-row span:last-child { color: var(--text2); text-align: right; max-width: 60%; word-break: break-all; }

        .trxid {
            font-family: var(--font-mono);
            font-size: 11px !important;
            background: var(--bg4);
            padding: 2px 6px;
            border-radius: 4px;
        }

        .view-ss-link {
            color: var(--blue);
            text-decoration: none;
            font-size: 12px;
        }

        .req-note-input {
            width: 100%;
            background: var(--bg4);
            border: 1px solid var(--border);
            border-radius: var(--radius-sm);
            color: var(--text);
            font-family: var(--font-mono);
            font-size: 12px;
            padding: 8px 12px;
            margin-bottom: 10px;
            transition: border-color .2s;
        }

        .req-note-input:focus {
            outline: none;
            border-color: var(--gold);
        }

        .req-btn-row {
            display: flex;
            gap: 8px;
        }

        .btn-approve, .btn-reject {
            flex: 1;
            padding: 9px;
            border-radius: var(--radius-sm);
            font-family: var(--font-mono);
            font-size: 12px;
            font-weight: 700;
            cursor: pointer;
            border: none;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            transition: all .2s;
        }

        .btn-approve {
            background: var(--green-dim);
            color: var(--green);
            border: 1px solid rgba(34,214,137,.25);
        }

        .btn-approve:hover {
            background: var(--green);
            color: #000;
        }

        .btn-reject {
            background: var(--red-dim);
            color: var(--red);
            border: 1px solid rgba(255,79,106,.25);
        }

        .btn-reject:hover {
            background: var(--red);
            color: #fff;
        }

        /* ─── EMPTY STATE ─── */
        .empty-state {
            text-align: center;
            padding: 48px 20px;
            color: var(--text3);
        }

        .empty-state i { font-size: 36px; margin-bottom: 12px; opacity: .4; display: block; }
        .empty-state p { font-size: 13px; }

        /* ─── TABLE ─── */
        .table-wrap { overflow-x: auto; }

        table.admin-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 12.5px;
        }

        .admin-table th {
            text-align: left;
            padding: 10px 14px;
            color: var(--text3);
            font-size: 10px;
            text-transform: uppercase;
            letter-spacing: 1.5px;
            border-bottom: 1px solid var(--border);
            font-weight: 400;
            white-space: nowrap;
        }

        .admin-table td {
            padding: 11px 14px;
            border-bottom: 1px solid var(--border);
            color: var(--text2);
            vertical-align: middle;
        }

        .admin-table tr:last-child td { border-bottom: none; }

        .admin-table tr:hover td {
            background: rgba(255,255,255,.02);
        }

        /* ─── STATUS BADGES ─── */
        .badge {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            padding: 3px 10px;
            border-radius: 20px;
            font-size: 10px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .badge-approved { background: var(--green-dim); color: var(--green); border: 1px solid rgba(34,214,137,.2); }
        .badge-rejected { background: var(--red-dim); color: var(--red); border: 1px solid rgba(255,79,106,.2); }
        .badge-pending  { background: rgba(245,200,66,.13); color: var(--gold); border: 1px solid rgba(245,200,66,.2); }
        .badge-active   { background: var(--green-dim); color: var(--green); border: 1px solid rgba(34,214,137,.2); }
        .badge-banned   { background: var(--red-dim); color: var(--red); border: 1px solid rgba(255,79,106,.2); }

        /* ─── USER CARDS ─── */
        .user-card {
            background: var(--bg3);
            border: 1px solid var(--border);
            border-radius: var(--radius-sm);
            overflow: hidden;
            transition: border-color .2s;
        }

        .user-card:hover { border-color: var(--border2); }

        .user-card-summary {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 14px 16px;
            cursor: pointer;
            list-style: none;
        }

        .user-card-summary::-webkit-details-marker { display: none; }

        .user-summary-left {
            display: flex;
            align-items: center;
            gap: 11px;
        }

        .user-av {
            width: 38px; height: 38px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--blue-dim), var(--gold-dim));
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: var(--font-head);
            font-weight: 800;
            font-size: 13px;
            color: var(--text);
            border: 1px solid var(--border);
        }

        .user-name { font-weight: 700; font-size: 13px; }
        .user-info-line { font-size: 11px; color: var(--text3); }

        .user-balance-chip {
            font-family: var(--font-head);
            font-size: 14px;
            font-weight: 700;
            color: var(--gold);
        }

        .user-detail-body {
            padding: 14px 16px;
            border-top: 1px solid var(--border);
            background: var(--bg4);
        }

        .user-detail-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            margin-bottom: 14px;
        }

        .user-detail-grid p {
            font-size: 12px;
        }

        .user-detail-grid p b {
            color: var(--text3);
            font-weight: 400;
            display: block;
            font-size: 10px;
            text-transform: uppercase;
            letter-spacing: .5px;
            margin-bottom: 2px;
        }

        .user-actions {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        /* ─── FORMS ─── */
        .form-row {
            margin-bottom: 14px;
        }

        .form-row label {
            display: block;
            font-size: 11px;
            color: var(--text3);
            margin-bottom: 6px;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .form-row input,
        .form-row textarea,
        .form-row select {
            width: 100%;
            background: var(--bg3);
            border: 1px solid var(--border);
            border-radius: var(--radius-sm);
            color: var(--text);
            font-family: var(--font-mono);
            font-size: 13px;
            padding: 10px 12px;
            transition: border-color .2s;
        }

        .form-row input:focus,
        .form-row textarea:focus,
        .form-row select:focus {
            outline: none;
            border-color: var(--gold);
        }

        .form-row textarea { resize: vertical; min-height: 80px; }

        .form-row select option { background: var(--bg2); }

        .form-cols {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
        }

        .form-cols-3 {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 12px;
        }

        .btn-primary {
            width: 100%;
            padding: 11px;
            background: var(--gold);
            color: #000;
            border: none;
            border-radius: var(--radius-sm);
            font-family: var(--font-mono);
            font-size: 13px;
            font-weight: 700;
            cursor: pointer;
            transition: all .2s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 7px;
        }

        .btn-primary:hover {
            background: var(--gold2);
            transform: translateY(-1px);
        }

        .btn-secondary {
            padding: 8px 14px;
            background: var(--bg4);
            color: var(--text2);
            border: 1px solid var(--border);
            border-radius: var(--radius-sm);
            font-family: var(--font-mono);
            font-size: 12px;
            cursor: pointer;
            transition: all .2s;
        }

        .btn-secondary:hover {
            border-color: var(--border2);
            color: var(--text);
        }

        .btn-danger {
            padding: 7px 12px;
            background: var(--red-dim);
            color: var(--red);
            border: 1px solid rgba(255,79,106,.2);
            border-radius: var(--radius-sm);
            font-family: var(--font-mono);
            font-size: 11px;
            cursor: pointer;
            transition: all .2s;
        }

        .btn-danger:hover {
            background: var(--red);
            color: #fff;
        }

        .btn-blue {
            padding: 7px 12px;
            background: var(--blue-dim);
            color: var(--blue);
            border: 1px solid rgba(79,158,255,.2);
            border-radius: var(--radius-sm);
            font-family: var(--font-mono);
            font-size: 11px;
            cursor: pointer;
            transition: all .2s;
        }

        .btn-blue:hover { background: var(--blue); color: #fff; }

        .checkbox-row {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 12px;
            color: var(--text2);
            cursor: pointer;
            margin-bottom: 12px;
        }

        .checkbox-row input[type=checkbox] {
            width: 16px; height: 16px;
            accent-color: var(--gold);
        }

        /* ─── GAME IMAGE ─── */
        .game-thumb {
            width: 42px; height: 36px;
            object-fit: cover;
            border-radius: 6px;
            border: 1px solid var(--border);
        }

        .game-icon-fallback {
            width: 42px; height: 36px;
            background: var(--bg4);
            border-radius: 6px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
        }

        /* ─── PAYMENT METHOD CARD ─── */
        .method-card {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 13px 16px;
            background: var(--bg3);
            border: 1px solid var(--border);
            border-radius: var(--radius-sm);
            margin-bottom: 10px;
        }

        .method-info { flex: 1; }
        .method-name { font-weight: 700; font-size: 13px; }
        .method-sub { font-size: 11px; color: var(--text3); }
        .method-wallet { font-family: var(--font-mono); font-size: 12px; color: var(--text2); }

        /* ─── SEARCH BAR ─── */
        .search-bar {
            position: relative;
            margin-bottom: 18px;
        }

        .search-bar input {
            width: 100%;
            background: var(--bg3);
            border: 1px solid var(--border);
            border-radius: var(--radius-sm);
            color: var(--text);
            font-family: var(--font-mono);
            font-size: 13px;
            padding: 10px 12px 10px 38px;
            transition: border-color .2s;
        }

        .search-bar input:focus {
            outline: none;
            border-color: var(--gold);
        }

        .search-bar i {
            position: absolute;
            left: 13px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text3);
        }

        /* ─── SECTION HEADER ─── */
        .section-head {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 20px;
        }

        .section-title {
            font-family: var(--font-head);
            font-size: 22px;
            font-weight: 800;
        }

        /* ─── TABS (inline) ─── */
        .inline-tabs {
            display: flex;
            gap: 4px;
            background: var(--bg3);
            padding: 4px;
            border-radius: var(--radius-sm);
            border: 1px solid var(--border);
            margin-bottom: 20px;
            width: fit-content;
        }

        .inline-tab {
            padding: 7px 18px;
            border-radius: 6px;
            font-family: var(--font-mono);
            font-size: 12px;
            color: var(--text3);
            cursor: pointer;
            transition: all .2s;
            border: none;
            background: none;
        }

        .inline-tab.active {
            background: var(--bg2);
            color: var(--text);
            border: 1px solid var(--border);
        }

        /* ─── MOBILE HAMBURGER ─── */
        .mobile-menu-btn {
            display: none;
            background: none;
            border: none;
            color: var(--text);
            font-size: 20px;
            cursor: pointer;
        }

        .sidebar-overlay {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,.6);
            z-index: 99;
        }

        /* ─── RESPONSIVE ─── */
        @media (max-width: 1100px) {
            .stats-grid { grid-template-columns: repeat(2, 1fr); }
        }

        @media (max-width: 860px) {
            .sidebar {
                transform: translateX(-100%);
            }

            .sidebar.open {
                transform: translateX(0);
            }

            .sidebar-overlay.open { display: block; }

            .main { margin-left: 0; }

            .mobile-menu-btn { display: block; }

            .grid-2 { grid-template-columns: 1fr; }

            .stats-grid { grid-template-columns: repeat(2, 1fr); }

            .user-detail-grid { grid-template-columns: 1fr 1fr; }

            .form-cols { grid-template-columns: 1fr; }
            .form-cols-3 { grid-template-columns: 1fr; }
        }

        @media (max-width: 520px) {
            .stats-grid { grid-template-columns: 1fr 1fr; }
            .content { padding: 16px; }
            .stat-value { font-size: 20px; }
        }

        /* ─── SCROLLBAR ─── */
        ::-webkit-scrollbar { width: 5px; height: 5px; }
        ::-webkit-scrollbar-track { background: var(--bg); }
        ::-webkit-scrollbar-thumb { background: var(--bg4); border-radius: 3px; }
        ::-webkit-scrollbar-thumb:hover { background: var(--text3); }

        /* ─── DIVIDER ─── */
        .divider {
            border: none;
            border-top: 1px solid var(--border);
            margin: 20px 0;
        }

        .mb-20 { margin-bottom: 20px; }
        .mt-12 { margin-top: 12px; }
        .text-muted { color: var(--text3); font-size: 12px; }
        .text-gold { color: var(--gold); }
        .text-green { color: var(--green); }
        .text-red { color: var(--red); }
        .fw7 { font-weight: 700; }
    </style>
</head>
<body>

<!-- Sidebar Overlay -->
<div class="sidebar-overlay" id="sidebarOverlay" onclick="closeSidebar()"></div>

<!-- ─── SIDEBAR ─── -->
<aside class="sidebar" id="sidebar">
    <div class="sidebar-logo">
        <div class="site-name">CK444</div>
        <div class="admin-badge">Control Panel</div>
    </div>
    <nav class="sidebar-nav">
        <div class="nav-section-label">Overview</div>
        <a href="#" class="active" onclick="showPanel('dashboard',this)">
            <i class="fa fa-chart-line"></i> Dashboard
        </a>
        <div class="nav-section-label">Finance</div>
        <a href="#" onclick="showPanel('deposits',this)">
            <i class="fa fa-arrow-down-to-line"></i> Deposits
            <?php if ($depCount > 0): ?>
                <span class="nav-badge"><?= $depCount ?></span>
            <?php endif; ?>
        </a>
        <a href="#" onclick="showPanel('withdrawals',this)">
            <i class="fa fa-arrow-up-from-line"></i> Withdrawals
            <?php if ($wCount > 0): ?>
                <span class="nav-badge"><?= $wCount ?></span>
            <?php endif; ?>
        </a>
        <a href="#" onclick="showPanel('history',this)">
            <i class="fa fa-clock-rotate-left"></i> History
        </a>
        <div class="nav-section-label">Platform</div>
        <a href="#" onclick="showPanel('users',this)">
            <i class="fa fa-users"></i> Users
            <span class="nav-badge" style="background:var(--blue)"><?= $usersCount ?></span>
        </a>
        <a href="#" onclick="showPanel('payment',this)">
            <i class="fa fa-credit-card"></i> Payment Methods
        </a>
        <a href="#" onclick="showPanel('games',this)">
            <i class="fa fa-gamepad"></i> Games
        </a>
        <a href="#" onclick="showPanel('settings',this)">
            <i class="fa fa-gear"></i> Settings
        </a>
        <div class="nav-section-label">Site</div>
        <a href="../index.php" target="_blank">
            <i class="fa fa-arrow-up-right-from-square"></i> Open Site
        </a>
    </nav>
    <div class="sidebar-footer">
        <form method="post">
            <input type="hidden" name="admin_action" value="logout">
            <button class="btn-logout" type="submit">
                <i class="fa fa-right-from-bracket"></i> Logout
            </button>
        </form>
    </div>
</aside>

<!-- ─── MAIN ─── -->
<div class="main">
    <header class="topbar">
        <div style="display:flex;align-items:center;gap:14px">
            <button class="mobile-menu-btn" onclick="openSidebar()">
                <i class="fa fa-bars"></i>
            </button>
            <div class="topbar-title" id="topbarTitle">Dashboard</div>
        </div>
        <div class="topbar-right">
            <div class="status-indicator">
                <div class="status-dot"></div>
                <span>Live</span>
            </div>
            <div class="topbar-time" id="topbarTime"></div>
        </div>
    </header>

    <div class="content">
        <?php if ($msg): ?>
            <div class="alert alert-success"><i class="fa fa-circle-check"></i> <?= e($msg) ?></div>
        <?php endif; ?>
        <?php if ($err): ?>
            <div class="alert alert-error"><i class="fa fa-triangle-exclamation"></i> <?= e($err) ?></div>
        <?php endif; ?>

        <!-- ═══════════════════════════════════════════════════ -->
        <!-- DASHBOARD PANEL -->
        <!-- ═══════════════════════════════════════════════════ -->
        <div class="panel active" id="panel-dashboard">
            <div class="section-head">
                <h1 class="section-title">Overview</h1>
            </div>

            <div class="stats-grid">
                <div class="stat-box gold">
                    <div class="stat-icon"><i class="fa fa-users"></i></div>
                    <div class="stat-value"><?= number_format($usersCount) ?></div>
                    <div class="stat-label">Total Users</div>
                    <div class="stat-sub">
                        <span class="text-green"><?= $activeUsers ?> active</span> ·
                        <span class="text-red"><?= $bannedUsers ?> banned</span>
                    </div>
                </div>
                <div class="stat-box green">
                    <div class="stat-icon"><i class="fa fa-wallet"></i></div>
                    <div class="stat-value"><?= e(money($balSum)) ?></div>
                    <div class="stat-label">Total User Balance</div>
                    <div class="stat-sub">Across all accounts</div>
                </div>
                <div class="stat-box blue">
                    <div class="stat-icon"><i class="fa fa-arrow-down"></i></div>
                    <div class="stat-value"><?= e(money($totalDeposited)) ?></div>
                    <div class="stat-label">Total Deposited</div>
                    <div class="stat-sub">Today: <span class="text-green"><?= e(money($todayDep)) ?></span></div>
                </div>
                <div class="stat-box red">
                    <div class="stat-icon"><i class="fa fa-arrow-up"></i></div>
                    <div class="stat-value"><?= e(money($totalWithdrawn)) ?></div>
                    <div class="stat-label">Total Withdrawn</div>
                    <div class="stat-sub">Today: <span class="text-red"><?= e(money($todayWith)) ?></span></div>
                </div>
                <div class="stat-box purple">
                    <div class="stat-icon"><i class="fa fa-hourglass-half"></i></div>
                    <div class="stat-value"><?= $depCount ?></div>
                    <div class="stat-label">Pending Deposits</div>
                    <div class="stat-sub">Awaiting review</div>
                </div>
                <div class="stat-box purple">
                    <div class="stat-icon"><i class="fa fa-clock"></i></div>
                    <div class="stat-value"><?= $wCount ?></div>
                    <div class="stat-label">Pending Withdrawals</div>
                    <div class="stat-sub">Awaiting payment</div>
                </div>
            </div>

            <!-- Chart -->
            <div class="chart-wrap">
                <div class="chart-header">
                    <div class="card-title">7-Day Finance Overview</div>
                    <div class="chart-legend">
                        <span><span class="legend-dot" style="background:var(--green)"></span>Deposits</span>
                        <span><span class="legend-dot" style="background:var(--red)"></span>Withdrawals</span>
                    </div>
                </div>
                <?php
                $maxVal = 1;
                foreach ($chartData as $d) $maxVal = max($maxVal, $d['dep'], $d['wit']);
                ?>
                <div class="bar-chart">
                    <?php foreach ($chartData as $d): ?>
                        <div class="bar-group">
                            <div class="bar-pair">
                                <div class="bar dep" style="height:<?= round(($d['dep'] / $maxVal) * 100) ?>px" title="Dep: <?= money($d['dep']) ?>"></div>
                                <div class="bar wit" style="height:<?= round(($d['wit'] / $maxVal) * 100) ?>px" title="Wit: <?= money($d['wit']) ?>"></div>
                            </div>
                            <div class="bar-label"><?= $d['label'] ?></div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Quick actions if pending -->
            <?php if ($depCount > 0 || $wCount > 0): ?>
                <div class="card">
                    <div class="card-header">
                        <div class="card-title">⚡ Pending Actions Required</div>
                    </div>
                    <div style="display:flex;gap:12px;flex-wrap:wrap">
                        <?php if ($depCount > 0): ?>
                            <button class="btn-secondary" onclick="showPanel('deposits',null)">
                                <i class="fa fa-arrow-down"></i> Review <?= $depCount ?> Deposit<?= $depCount > 1 ? 's' : '' ?>
                            </button>
                        <?php endif; ?>
                        <?php if ($wCount > 0): ?>
                            <button class="btn-secondary" onclick="showPanel('withdrawals',null)">
                                <i class="fa fa-arrow-up"></i> Review <?= $wCount ?> Withdrawal<?= $wCount > 1 ? 's' : '' ?>
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- ═══════════════════════════════════════════════════ -->
        <!-- DEPOSITS PANEL -->
        <!-- ═══════════════════════════════════════════════════ -->
        <div class="panel" id="panel-deposits">
            <div class="section-head">
                <h1 class="section-title">Deposit Requests</h1>
                <div class="card-count"><?= $depCount ?> pending</div>
            </div>

            <?php if (!$depPending): ?>
                <div class="empty-state">
                    <i class="fa fa-inbox"></i>
                    <p>No pending deposit requests.</p>
                </div>
            <?php else: ?>
                <div class="req-list">
                    <?php foreach ($depPending as $r) admin_request_card($r, 'deposit'); ?>
                </div>
            <?php endif; ?>
        </div>

        <!-- ═══════════════════════════════════════════════════ -->
        <!-- WITHDRAWALS PANEL -->
        <!-- ═══════════════════════════════════════════════════ -->
        <div class="panel" id="panel-withdrawals">
            <div class="section-head">
                <h1 class="section-title">Withdrawal Requests</h1>
                <div class="card-count"><?= $wCount ?> pending</div>
            </div>

            <?php if (!$wPending): ?>
                <div class="empty-state">
                    <i class="fa fa-inbox"></i>
                    <p>No pending withdrawal requests.</p>
                </div>
            <?php else: ?>
                <div class="req-list">
                    <?php foreach ($wPending as $r) admin_request_card($r, 'withdraw'); ?>
                </div>
            <?php endif; ?>
        </div>

        <!-- ═══════════════════════════════════════════════════ -->
        <!-- HISTORY PANEL -->
        <!-- ═══════════════════════════════════════════════════ -->
        <div class="panel" id="panel-history">
            <div class="section-head">
                <h1 class="section-title">Transaction History</h1>
            </div>

            <div class="inline-tabs">
                <button class="inline-tab active" onclick="switchHistTab('dep',this)">Deposits</button>
                <button class="inline-tab" onclick="switchHistTab('wit',this)">Withdrawals</button>
            </div>

            <div id="hist-dep" class="card">
                <div class="table-wrap">
                    <table class="admin-table">
                        <thead>
                            <tr>
                                <th>User</th>
                                <th>Amount</th>
                                <th>Method</th>
                                <th>TrxID</th>
                                <th>Status</th>
                                <th>Reviewed</th>
                                <th>Note</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($completedDep as $r): ?>
                                <tr>
                                    <td class="fw7"><?= e($r['phone'] ?? $r['user_id']) ?></td>
                                    <td class="text-gold fw7"><?= e(money($r['amount'])) ?></td>
                                    <td><?= e($r['method_label']) ?></td>
                                    <td><span class="trxid"><?= e($r['trxid']) ?></span></td>
                                    <td><span class="badge badge-<?= e($r['status']) ?>"><?= e($r['status']) ?></span></td>
                                    <td class="text-muted"><?= e($r['reviewed_at']) ?></td>
                                    <td class="text-muted"><?= e($r['admin_note']) ?></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (!$completedDep): ?>
                                <tr><td colspan="7" style="text-align:center;padding:30px;color:var(--text3)">No completed deposits.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div id="hist-wit" class="card" style="display:none">
                <div class="table-wrap">
                    <table class="admin-table">
                        <thead>
                            <tr>
                                <th>User</th>
                                <th>Amount</th>
                                <th>Method</th>
                                <th>Account</th>
                                <th>Status</th>
                                <th>Reviewed</th>
                                <th>Note</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($completedW as $r): ?>
                                <tr>
                                    <td class="fw7"><?= e($r['phone'] ?? $r['user_id']) ?></td>
                                    <td class="text-red fw7"><?= e(money($r['amount'])) ?></td>
                                    <td><?= e($r['method_label']) ?></td>
                                    <td><?= e($r['account_number']) ?></td>
                                    <td><span class="badge badge-<?= e($r['status']) ?>"><?= e($r['status']) ?></span></td>
                                    <td class="text-muted"><?= e($r['reviewed_at']) ?></td>
                                    <td class="text-muted"><?= e($r['admin_note']) ?></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (!$completedW): ?>
                                <tr><td colspan="7" style="text-align:center;padding:30px;color:var(--text3)">No completed withdrawals.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- ═══════════════════════════════════════════════════ -->
        <!-- USERS PANEL -->
        <!-- ═══════════════════════════════════════════════════ -->
        <div class="panel" id="panel-users">
            <div class="section-head">
                <h1 class="section-title">Users</h1>
                <div class="card-count"><?= $usersCount ?> total</div>
            </div>

            <div class="search-bar mb-20">
                <i class="fa fa-search"></i>
                <input type="text" id="userSearch" placeholder="Search by phone, email, country..." oninput="filterUsers(this.value)">
            </div>

            <div id="userList" style="display:flex;flex-direction:column;gap:10px">
                <?php foreach ($users as $u):
                    $s = user_admin_summary($u['id']);
                    $initials = strtoupper(substr($u['phone'], 0, 2));
                ?>
                    <details class="user-card" data-search="<?= strtolower(e($u['phone'] . ' ' . ($u['email'] ?? '') . ' ' . $u['country_name'])) ?>">
                        <summary class="user-card-summary">
                            <div class="user-summary-left">
                                <div class="user-av"><?= $initials ?></div>
                                <div>
                                    <div class="user-name"><?= e($u['phone']) ?></div>
                                    <div class="user-info-line">
                                        <?= e($u['country_name']) ?> ·
                                        <span class="badge badge-<?= e($u['status']) ?>" style="padding:1px 8px;font-size:9px"><?= e($u['status']) ?></span>
                                    </div>
                                </div>
                            </div>
                            <div class="user-balance-chip"><?= e(money($u['balance'])) ?></div>
                        </summary>
                        <div class="user-detail-body">
                            <div class="user-detail-grid">
                                <p><b>UID</b><?= e($u['id']) ?></p>
                                <p><b>Phone</b><?= e($u['phone']) ?></p>
                                <p><b>Email</b><?= e($u['email'] ?? '—') ?></p>
                                <p><b>Country</b><?= e($u['country_name']) ?> (<?= e($u['dial_code']) ?>)</p>
                                <p><b>Balance</b><span class="text-gold"><?= e(money($u['balance'])) ?></span></p>
                                <p><b>Bonus</b><?= e(money($u['bonus'])) ?></p>
                                <p><b>Safe Income</b><?= e(money($u['safe_income'])) ?></p>
                                <p><b>Referral</b><?= e($u['referral_code']) ?></p>
                                <p><b>Invite Code</b><?= e($u['invite_code']) ?></p>
                                <p><b>Transactions</b><?= (int)$s['tx'] ?></p>
                                <p><b>Total Deposited</b><span class="text-green"><?= e(money($s['deposit_total'])) ?></span></p>
                                <p><b>Total Withdrawn</b><span class="text-red"><?= e(money($s['withdraw_total'])) ?></span></p>
                                <p><b>Joined</b><?= e($u['created_at']) ?></p>
                                <p><b>Last Login</b><?= e($u['last_login']) ?></p>
                            </div>
                            <div class="user-actions">
                                <!-- Balance Adjustment -->
                                <form method="post" style="display:flex;gap:6px;align-items:center;flex-wrap:wrap">
                                    <input type="hidden" name="admin_action" value="update_user_balance">
                                    <input type="hidden" name="user_id" value="<?= (int)$u['id'] ?>">
                                    <input style="width:100px;background:var(--bg2);border:1px solid var(--border);border-radius:6px;color:var(--text);font-family:var(--font-mono);font-size:12px;padding:6px 10px" name="amount" type="number" step="0.01" placeholder="Amount" required>
                                    <select style="background:var(--bg2);border:1px solid var(--border);border-radius:6px;color:var(--text);font-family:var(--font-mono);font-size:12px;padding:6px 8px" name="balance_type">
                                        <option value="add">+ Add</option>
                                        <option value="deduct">− Deduct</option>
                                        <option value="set">= Set</option>
                                    </select>
                                    <input style="width:130px;background:var(--bg2);border:1px solid var(--border);border-radius:6px;color:var(--text);font-family:var(--font-mono);font-size:12px;padding:6px 10px" name="reason" placeholder="Reason" value="Admin adjustment">
                                    <button class="btn-blue" type="submit"><i class="fa fa-coins"></i> Update Balance</button>
                                </form>
                                <!-- Toggle Status -->
                                <form method="post">
                                    <input type="hidden" name="admin_action" value="toggle_user_status">
                                    <input type="hidden" name="user_id" value="<?= (int)$u['id'] ?>">
                                    <button class="<?= $u['status'] === 'banned' ? 'btn-blue' : 'btn-danger' ?>" type="submit" onclick="return confirm('Toggle user status?')">
                                        <?php if ($u['status'] === 'banned'): ?>
                                            <i class="fa fa-unlock"></i> Unban
                                        <?php else: ?>
                                            <i class="fa fa-ban"></i> Ban User
                                        <?php endif; ?>
                                    </button>
                                </form>
                                <!-- Bonus -->
                                <form method="post" style="display:flex;gap:6px;align-items:center">
                                    <input type="hidden" name="admin_action" value="add_bonus">
                                    <input type="hidden" name="user_id" value="<?= (int)$u['id'] ?>">
                                    <input style="width:100px;background:var(--bg2);border:1px solid var(--border);border-radius:6px;color:var(--text);font-family:var(--font-mono);font-size:12px;padding:6px 10px" name="bonus_amount" type="number" step="0.01" placeholder="Bonus">
                                    <button class="btn-secondary" type="submit"><i class="fa fa-gift"></i> Add Bonus</button>
                                </form>
                            </div>
                        </div>
                    </details>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- ═══════════════════════════════════════════════════ -->
        <!-- PAYMENT METHODS PANEL -->
        <!-- ═══════════════════════════════════════════════════ -->
        <div class="panel" id="panel-payment">
            <div class="section-head">
                <h1 class="section-title">Payment Methods</h1>
            </div>
            <div class="grid-2">
                <div class="card">
                    <div class="card-header">
                        <div class="card-title">Add New Method</div>
                    </div>
                    <form method="post">
                        <input type="hidden" name="admin_action" value="add_payment">
                        <div class="form-row">
                            <label>Country</label>
                            <select name="country_code">
                                <option value="BD">🇧🇩 Bangladesh</option>
                                <option value="PK">🇵🇰 Pakistan</option>
                                <option value="IN">🇮🇳 India</option>
                                <option value="MY">🇲🇾 Malaysia</option>
                            </select>
                        </div>
                        <div class="form-cols">
                            <div class="form-row">
                                <label>Method Key</label>
                                <input name="method_key" placeholder="bkash / easypaisa" required>
                            </div>
                            <div class="form-row">
                                <label>Label</label>
                                <input name="label" placeholder="bKash Personal" required>
                            </div>
                        </div>
                        <div class="form-cols">
                            <div class="form-row">
                                <label>Provider</label>
                                <input name="provider" placeholder="bKash / JazzCash">
                            </div>
                            <div class="form-row">
                                <label>Sort Order</label>
                                <input name="sort_order" type="number" value="10">
                            </div>
                        </div>
                        <div class="form-row">
                            <label>Wallet / Account Number</label>
                            <input name="wallet_number" required>
                        </div>
                        <div class="form-row">
                            <label>Instructions</label>
                            <textarea name="instructions" placeholder="Send money to this number and enter TrxID..."></textarea>
                        </div>
                        <label class="checkbox-row">
                            <input type="checkbox" name="active" checked> Active (visible to users)
                        </label>
                        <button class="btn-primary" type="submit"><i class="fa fa-plus"></i> Add Payment Method</button>
                    </form>
                </div>
                <div class="card">
                    <div class="card-header">
                        <div class="card-title">Current Methods</div>
                        <div class="card-count"><?= count($methods) ?></div>
                    </div>
                    <?php if (!$methods): ?>
                        <div class="empty-state">
                            <i class="fa fa-credit-card"></i>
                            <p>No payment methods yet.</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($methods as $m): ?>
                            <div class="method-card">
                                <div class="method-info">
                                    <div class="method-name"><?= e($m['label']) ?></div>
                                    <div class="method-sub"><?= e($m['country_code']) ?> · <?= e($m['provider']) ?> · Sort: <?= e($m['sort_order']) ?></div>
                                    <div class="method-wallet"><?= e($m['wallet_number']) ?></div>
                                    <span class="badge <?= $m['active'] ? 'badge-active' : 'badge-banned' ?>" style="margin-top:4px">
                                        <?= $m['active'] ? 'Active' : 'Inactive' ?>
                                    </span>
                                </div>
                                <form method="post">
                                    <input type="hidden" name="admin_action" value="delete_payment">
                                    <input type="hidden" name="id" value="<?= (int)$m['id'] ?>">
                                    <button class="btn-danger" onclick="return confirm('Delete this payment method?')">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </form>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- ═══════════════════════════════════════════════════ -->
        <!-- GAMES PANEL -->
        <!-- ═══════════════════════════════════════════════════ -->
        <div class="panel" id="panel-games">
            <div class="section-head">
                <h1 class="section-title">Games</h1>
                <div class="card-count"><?= count($games) ?> games</div>
            </div>
            <div class="grid-2 mb-20">
                <div class="card">
                    <div class="card-header">
                        <div class="card-title">Add New Game</div>
                    </div>
                    <form method="post">
                        <input type="hidden" name="admin_action" value="add_game">
                        <div class="form-cols">
                            <div class="form-row">
                                <label>Title</label>
                                <input name="title" required>
                            </div>
                            <div class="form-row">
                                <label>Icon (emoji)</label>
                                <input name="icon" value="🎮">
                            </div>
                        </div>
                        <div class="form-cols">
                            <div class="form-row">
                                <label>Provider</label>
                                <input name="provider" placeholder="Pragmatic / Evolution">
                            </div>
                            <div class="form-row">
                                <label>Category</label>
                                <select name="category">
                                    <option>slots</option>
                                    <option>casino</option>
                                    <option>sports</option>
                                    <option>crash</option>
                                    <option>fishing</option>
                                    <option>lottery</option>
                                    <option>pvc</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-row">
                            <label>Image URL</label>
                            <input name="image_url" placeholder="assets/games/example.jpg">
                        </div>
                        <div class="form-row">
                            <label>Game URL</label>
                            <input name="game_url" placeholder="game.php?game=name">
                        </div>
                        <div class="form-cols">
                            <div class="form-row">
                                <label>Sort Order</label>
                                <input name="sort_order" type="number" value="100">
                            </div>
                            <div style="display:flex;gap:20px;align-items:flex-end;padding-bottom:14px">
                                <label class="checkbox-row" style="margin:0">
                                    <input type="checkbox" name="is_hot" checked> Hot 🔥
                                </label>
                                <label class="checkbox-row" style="margin:0">
                                    <input type="checkbox" name="active" checked> Active
                                </label>
                            </div>
                        </div>
                        <button class="btn-primary" type="submit"><i class="fa fa-plus"></i> Add Game</button>
                    </form>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <div class="card-title">All Games</div>
                </div>
                <div class="table-wrap">
                    <table class="admin-table">
                        <thead>
                            <tr>
                                <th>Image</th>
                                <th>Title</th>
                                <th>Category</th>
                                <th>Provider</th>
                                <th>Sort</th>
                                <th>Flags</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($games as $g): ?>
                                <tr>
                                    <td>
                                        <?php if ($g['image_url']): ?>
                                            <img class="game-thumb" src="../<?= e($g['image_url']) ?>" alt="">
                                        <?php else: ?>
                                            <div class="game-icon-fallback"><?= e($g['icon']) ?></div>
                                        <?php endif; ?>
                                    </td>
                                    <td class="fw7"><?= e($g['icon']) ?> <?= e($g['title']) ?></td>
                                    <td><span class="badge badge-pending"><?= e($g['category']) ?></span></td>
                                    <td class="text-muted"><?= e($g['provider']) ?></td>
                                    <td class="text-muted"><?= e($g['sort_order']) ?></td>
                                    <td>
                                        <?php if ($g['is_hot']): ?><span class="badge badge-approved">🔥 Hot</span><?php endif; ?>
                                        <?php if (!$g['active']): ?><span class="badge badge-banned">Off</span><?php endif; ?>
                                    </td>
                                    <td>
                                        <form method="post" style="display:inline">
                                            <input type="hidden" name="admin_action" value="delete_game">
                                            <input type="hidden" name="id" value="<?= (int)$g['id'] ?>">
                                            <button class="btn-danger" onclick="return confirm('Delete game?')"><i class="fa fa-trash"></i></button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- ═══════════════════════════════════════════════════ -->
        <!-- SETTINGS PANEL -->
        <!-- ═══════════════════════════════════════════════════ -->
        <div class="panel" id="panel-settings">
            <div class="section-head">
                <h1 class="section-title">Settings</h1>
            </div>

            <div class="grid-2">
                <!-- Announcement -->
                <div class="card">
                    <div class="card-header">
                        <div class="card-title">📢 Announcement</div>
                    </div>
                    <form method="post">
                        <input type="hidden" name="admin_action" value="save_announcement">
                        <div class="form-row">
                            <label>Type</label>
                            <select name="announcement_type">
                                <option value="info" <?= ($settings['announcement_type'] ?? '') === 'info' ? 'selected' : '' ?>>ℹ️ Info</option>
                                <option value="warning" <?= ($settings['announcement_type'] ?? '') === 'warning' ? 'selected' : '' ?>>⚠️ Warning</option>
                                <option value="success" <?= ($settings['announcement_type'] ?? '') === 'success' ? 'selected' : '' ?>>✅ Success</option>
                            </select>
                        </div>
                        <div class="form-row">
                            <label>Message</label>
                            <textarea name="announcement" placeholder="Enter announcement text..."><?= e($settings['announcement'] ?? '') ?></textarea>
                        </div>
                        <button class="btn-primary" type="submit"><i class="fa fa-save"></i> Save Announcement</button>
                    </form>
                </div>

                <!-- Site Settings -->
                <div class="card">
                    <div class="card-header">
                        <div class="card-title">⚙️ Site Settings</div>
                    </div>
                    <form method="post">
                        <input type="hidden" name="admin_action" value="save_site_settings">
                        <div class="form-row">
                            <label>Site Name</label>
                            <input name="site_name" value="<?= e($settings['site_name'] ?? 'CK444') ?>">
                        </div>
                        <div class="form-row">
                            <label>Site Status</label>
                            <select name="site_status">
                                <option value="1" <?= ($settings['site_status'] ?? '1') === '1' ? 'selected' : '' ?>>🟢 Online</option>
                                <option value="0" <?= ($settings['site_status'] ?? '1') === '0' ? 'selected' : '' ?>>🔴 Maintenance</option>
                            </select>
                        </div>
                        <div class="form-row">
                            <label>Maintenance Message</label>
                            <textarea name="maintenance_msg" placeholder="We'll be back soon..."><?= e($settings['maintenance_msg'] ?? '') ?></textarea>
                        </div>
                        <button class="btn-primary" type="submit"><i class="fa fa-save"></i> Save Settings</button>
                    </form>
                </div>

                <!-- Withdraw / Deposit Rules -->
                <div class="card">
                    <div class="card-header">
                        <div class="card-title">💳 Finance Rules</div>
                    </div>
                    <form method="post">
                        <input type="hidden" name="admin_action" value="save_rules">
                        <div class="form-cols">
                            <div class="form-row">
                                <label>Min Deposit</label>
                                <input name="deposit_min" type="number" step="0.01" value="<?= e($settings['deposit_min'] ?? '100') ?>">
                            </div>
                            <div class="form-row">
                                <label>Max Deposit</label>
                                <input name="deposit_max" type="number" step="0.01" value="<?= e($settings['deposit_max'] ?? '100000') ?>">
                            </div>
                        </div>
                        <div class="form-cols">
                            <div class="form-row">
                                <label>Min Withdraw</label>
                                <input name="withdraw_min" type="number" step="0.01" value="<?= e($settings['withdraw_min'] ?? '500') ?>">
                            </div>
                            <div class="form-row">
                                <label>Max Withdraw</label>
                                <input name="withdraw_max" type="number" step="0.01" value="<?= e($settings['withdraw_max'] ?? '25000') ?>">
                            </div>
                        </div>
                        <div class="form-cols">
                            <div class="form-row">
                                <label>Withdraw Fee %</label>
                                <input name="withdraw_fee" type="number" step="0.01" value="<?= e($settings['withdraw_fee'] ?? '0') ?>">
                            </div>
                            <div class="form-row">
                                <label>Daily Withdraw Limit</label>
                                <input name="daily_withdraw_limit" type="number" step="0.01" value="<?= e($settings['daily_withdraw_limit'] ?? '50000') ?>">
                            </div>
                        </div>
                        <button class="btn-primary" type="submit"><i class="fa fa-save"></i> Save Rules</button>
                    </form>
                </div>
            </div>
        </div>
    </div><!-- /content -->
</div><!-- /main -->

<script>
// ─── PANEL NAVIGATION ───
function showPanel(name, linkEl) {
    document.querySelectorAll('.panel').forEach(p => p.classList.remove('active'));
    document.getElementById('panel-' + name)?.classList.add('active');
    document.querySelectorAll('.sidebar-nav a').forEach(a => a.classList.remove('active'));
    if (linkEl) {
        linkEl.classList.add('active');
    } else {
        document.querySelectorAll('.sidebar-nav a').forEach(a => {
            if (a.getAttribute('onclick') && a.getAttribute('onclick').includes("'" + name + "'")) {
                a.classList.add('active');
            }
        });
    }
    const titles = {
        dashboard: 'Dashboard', deposits: 'Deposits', withdrawals: 'Withdrawals',
        history: 'History', users: 'Users', payment: 'Payment Methods',
        games: 'Games', settings: 'Settings'
    };
    document.getElementById('topbarTitle').textContent = titles[name] || name;
    closeSidebar();
}

// ─── HISTORY TABS ───
function switchHistTab(tab, btn) {
    document.querySelectorAll('#panel-history .inline-tab').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    document.getElementById('hist-dep').style.display = tab === 'dep' ? '' : 'none';
    document.getElementById('hist-wit').style.display = tab === 'wit' ? '' : 'none';
}

// ─── USER SEARCH ───
function filterUsers(q) {
    q = q.toLowerCase();
    document.querySelectorAll('#userList [data-search]').forEach(el => {
        el.style.display = el.dataset.search.includes(q) ? '' : 'none';
    });
}

// ─── SIDEBAR MOBILE ───
function openSidebar() {
    document.getElementById('sidebar').classList.add('open');
    document.getElementById('sidebarOverlay').classList.add('open');
}

function closeSidebar() {
    document.getElementById('sidebar').classList.remove('open');
    document.getElementById('sidebarOverlay').classList.remove('open');
}

// ─── CLOCK ───
function updateClock() {
    const now = new Date();
    document.getElementById('topbarTime').textContent = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
}
updateClock();
setInterval(updateClock, 1000);

// ─── AUTO-DISMISS ALERTS ───
setTimeout(() => {
    document.querySelectorAll('.alert').forEach(a => {
        a.style.transition = 'opacity .5s';
        a.style.opacity = '0';
        setTimeout(() => a.remove(), 500);
    });
}, 4000);
</script>
</body>
</html>
