<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'Dashboard';
include 'side.php';
require_once 'admin_protect.php';

$conn = getConnection();
date_default_timezone_set('Africa/Nairobi');

// ── Helper ────────────────────────────────────────────────────────────────
function safeQueryValue($conn, $sql, $column = 'count', $default = 0) {
    $result = $conn->query($sql);
    if (!$result) { error_log("Dashboard query failed: " . $conn->error); return $default; }
    $row = $result->fetch_assoc();
    return ($row && isset($row[$column])) ? $row[$column] : $default;
}

// ════════════════════════════════════════════════════════════════════════════
// ADMIN ALWAYS SEES KES — ALL MONEY CONVERTED TO KES BEFORE SUMMING
//
// exchange_rate convention: 1 local unit = exchange_rate KES
//   Kenya = 1.0, Uganda ≈ 0.026, Tanzania ≈ 0.043
// To convert local → KES:  local_amount * exchange_rate
// To convert KES   → local: kes_amount  / exchange_rate  (user display only)
//
// In SQL:  amount_in_local * GREATEST(COALESCE(c.exchange_rate,1),0.0001) = KES
// ════════════════════════════════════════════════════════════════════════════

// ── USER STATS ────────────────────────────────────────────────────────────
$stats['total_users']        = intval(safeQueryValue($conn,"SELECT COUNT(*) as count FROM users"));
$stats['active_users']       = intval(safeQueryValue($conn,"SELECT COUNT(*) as count FROM users WHERE status='active'"));
$stats['inactive_users']     = intval(safeQueryValue($conn,"SELECT COUNT(*) as count FROM users WHERE status='inactive'"));
$stats['new_users_today']    = intval(safeQueryValue($conn,"SELECT COUNT(*) as count FROM users WHERE DATE(created_at)=CURDATE()"));
$stats['activated_today']    = intval(safeQueryValue($conn,"SELECT COUNT(*) as count FROM users WHERE DATE(activation_date)=CURDATE()"));

// ── TODAY ACTIVATION REVENUE → KES ───────────────────────────────────────
// activation_fee stored in LOCAL currency → multiply by exchange_rate → KES
$stats['today_activation_revenue'] = floatval(safeQueryValue($conn,"
    SELECT COALESCE(SUM(
        c.activation_fee * GREATEST(COALESCE(c.exchange_rate,1), 0.0001)
    ),0) as total
    FROM users u
    JOIN countries c ON u.country = c.name
    WHERE u.status='active' AND DATE(u.activation_date)=CURDATE()
",'total'));

// ── TODAY COMMISSIONS → KES ───────────────────────────────────────────────
// commission_levels stored in LOCAL currency → multiply by exchange_rate → KES
$stats['today_total_commissions'] = floatval(safeQueryValue($conn,"
    SELECT COALESCE(SUM(country_kes),0) as total FROM (
        SELECT
            u_cnt.country_id,
            u_cnt.user_count * cl_kes.total_commission_kes as country_kes
        FROM (
            SELECT c.id as country_id, COUNT(u.id) as user_count
            FROM users u JOIN countries c ON u.country=c.name
            WHERE u.status='active' AND DATE(u.activation_date)=CURDATE()
            GROUP BY c.id
        ) u_cnt
        JOIN (
            SELECT cl.country_id,
                SUM(cl.commission * GREATEST(COALESCE(c.exchange_rate,1),0.0001)) as total_commission_kes
            FROM commission_levels cl
            JOIN countries c ON c.id=cl.country_id
            GROUP BY cl.country_id
        ) cl_kes ON u_cnt.country_id=cl_kes.country_id
    ) combined
",'total'));

$stats['today_admin_earnings'] = $stats['today_activation_revenue'] - $stats['today_total_commissions'];

// ── TODAY COMMISSIONS ACTUALLY PAID → KES ────────────────────────────────
// referral_bonus transactions stored in LOCAL currency → * exchange_rate → KES
$stats['today_commission_paid'] = floatval(safeQueryValue($conn,"
    SELECT COALESCE(SUM(
        t.amount * GREATEST(COALESCE(c.exchange_rate,1), 0.0001)
    ),0) as total
    FROM transactions t
    JOIN users u ON u.id=t.user_id
    LEFT JOIN countries c ON c.name=u.country
    WHERE t.type='referral_bonus' AND t.status='completed'
    AND DATE(t.created_at)=CURDATE()
",'total'));

// ── ALL-TIME ACTIVATION REVENUE → KES ────────────────────────────────────
$stats['total_activation_revenue'] = floatval(safeQueryValue($conn,"
    SELECT COALESCE(SUM(
        c.activation_fee * GREATEST(COALESCE(c.exchange_rate,1), 0.0001)
    ),0) as total
    FROM users u JOIN countries c ON u.country=c.name
    WHERE u.status='active'
",'total'));

// ── ALL-TIME COMMISSIONS OWED → KES ──────────────────────────────────────
$stats['total_commissions_owed'] = floatval(safeQueryValue($conn,"
    SELECT COALESCE(SUM(country_kes),0) as total FROM (
        SELECT
            u_cnt.country_id,
            u_cnt.user_count * cl_kes.total_commission_kes as country_kes
        FROM (
            SELECT c.id as country_id, COUNT(u.id) as user_count
            FROM users u JOIN countries c ON u.country=c.name
            WHERE u.status='active'
            GROUP BY c.id
        ) u_cnt
        JOIN (
            SELECT cl.country_id,
                SUM(cl.commission * GREATEST(COALESCE(c.exchange_rate,1),0.0001)) as total_commission_kes
            FROM commission_levels cl
            JOIN countries c ON c.id=cl.country_id
            GROUP BY cl.country_id
        ) cl_kes ON u_cnt.country_id=cl_kes.country_id
    ) combined
",'total'));

$stats['total_admin_earnings'] = $stats['total_activation_revenue'] - $stats['total_commissions_owed'];

// ── ALL-TIME COMMISSIONS PAID → KES ──────────────────────────────────────
$stats['total_commission_paid'] = floatval(safeQueryValue($conn,"
    SELECT COALESCE(SUM(
        t.amount * GREATEST(COALESCE(c.exchange_rate,1), 0.0001)
    ),0) as total
    FROM transactions t
    JOIN users u ON u.id=t.user_id
    LEFT JOIN countries c ON c.name=u.country
    WHERE t.type='referral_bonus' AND t.status='completed'
",'total'));

// ── WALLET STATS → KES ───────────────────────────────────────────────────
// Wallets store LOCAL currency → multiply each by user's exchange_rate → KES
$walletResult = $conn->query("
    SELECT
        COALESCE(SUM(w.referral_wallet      * GREATEST(COALESCE(c.exchange_rate,1),0.0001)),0) as total_referral,
        COALESCE(SUM(w.bonus_wallet         * GREATEST(COALESCE(c.exchange_rate,1),0.0001)),0) as total_bonus,
        COALESCE(SUM(w.video_wallet         * GREATEST(COALESCE(c.exchange_rate,1),0.0001)),0) as total_video,
        COALESCE(SUM(w.trivia_wallet        * GREATEST(COALESCE(c.exchange_rate,1),0.0001)),0) as total_trivia,
        COALESCE(SUM(w.survey_wallet        * GREATEST(COALESCE(c.exchange_rate,1),0.0001)),0) as total_survey,
        COALESCE(SUM(w.ads_wallet           * GREATEST(COALESCE(c.exchange_rate,1),0.0001)),0) as total_ads,
        COALESCE(SUM(w.spin_wallet          * GREATEST(COALESCE(c.exchange_rate,1),0.0001)),0) as total_spin,
        COALESCE(SUM(w.blog_wallet          * GREATEST(COALESCE(c.exchange_rate,1),0.0001)),0) as total_blog,
        COALESCE(SUM(w.meme_wallet          * GREATEST(COALESCE(c.exchange_rate,1),0.0001)),0) as total_meme,
        COALESCE(SUM(w.chat_wallet          * GREATEST(COALESCE(c.exchange_rate,1),0.0001)),0) as total_chat,
        COALESCE(SUM(w.transcription_wallet * GREATEST(COALESCE(c.exchange_rate,1),0.0001)),0) as total_transcription,
        COALESCE(SUM(w.main_wallet          * GREATEST(COALESCE(c.exchange_rate,1),0.0001)),0) as total_main
    FROM wallets w
    JOIN users u ON u.id=w.user_id
    LEFT JOIN countries c ON c.name=u.country
");
$walletData = $walletResult ? $walletResult->fetch_assoc() : null;

$stats['total_referral_balance']       = floatval($walletData['total_referral']       ?? 0);
$stats['total_bonus_balance']          = floatval($walletData['total_bonus']          ?? 0);
$stats['total_video_balance']          = floatval($walletData['total_video']          ?? 0);
$stats['total_trivia_balance']         = floatval($walletData['total_trivia']         ?? 0);
$stats['total_survey_balance']         = floatval($walletData['total_survey']         ?? 0);
$stats['total_ads_balance']            = floatval($walletData['total_ads']            ?? 0);
$stats['total_spin_balance']           = floatval($walletData['total_spin']           ?? 0);
$stats['total_blog_balance']           = floatval($walletData['total_blog']           ?? 0);
$stats['total_meme_balance']           = floatval($walletData['total_meme']           ?? 0);
$stats['total_chat_balance']           = floatval($walletData['total_chat']           ?? 0);
$stats['total_transcription_balance']  = floatval($walletData['total_transcription']  ?? 0);
$stats['total_main_balance']           = floatval($walletData['total_main']           ?? 0);

$stats['total_wallet_balance'] =
    $stats['total_referral_balance'] + $stats['total_bonus_balance'] +
    $stats['total_video_balance']    + $stats['total_trivia_balance'] +
    $stats['total_survey_balance']   + $stats['total_ads_balance']    +
    $stats['total_spin_balance']     + $stats['total_blog_balance']   +
    $stats['total_meme_balance']     + $stats['total_chat_balance']   +
    $stats['total_transcription_balance'] + $stats['total_main_balance'];

// ── WITHDRAWAL STATS → KES ────────────────────────────────────────────────
$stats['pending_withdrawals']       = intval(safeQueryValue($conn,"SELECT COUNT(*) as count FROM withdrawals WHERE status='pending'"));
$stats['completed_withdrawals']     = intval(safeQueryValue($conn,"SELECT COUNT(*) as count FROM withdrawals WHERE status='completed'"));
$stats['rejected_withdrawals']      = intval(safeQueryValue($conn,"SELECT COUNT(*) as count FROM withdrawals WHERE status='rejected'"));
$stats['processing_withdrawals']    = intval(safeQueryValue($conn,"SELECT COUNT(*) as count FROM withdrawals WHERE status='processing'"));

// Withdrawal amounts → KES
$stats['pending_withdrawal_amount'] = floatval(safeQueryValue($conn,"
    SELECT COALESCE(SUM(
        w.amount * GREATEST(COALESCE(c.exchange_rate,1),0.0001)
    ),0) as total
    FROM withdrawals w
    JOIN users u ON u.id=w.user_id
    LEFT JOIN countries c ON c.name=u.country
    WHERE w.status='pending'
",'total'));

$stats['total_withdrawn'] = floatval(safeQueryValue($conn,"
    SELECT COALESCE(SUM(
        w.net_amount * GREATEST(COALESCE(c.exchange_rate,1),0.0001)
    ),0) as total
    FROM withdrawals w
    JOIN users u ON u.id=w.user_id
    LEFT JOIN countries c ON c.name=u.country
    WHERE w.status='completed'
",'total'));

// ── TASK STATS ────────────────────────────────────────────────────────────
$stats['total_tasks']           = intval(safeQueryValue($conn,"SELECT COUNT(*) as count FROM tasks"));
$stats['active_tasks']          = intval(safeQueryValue($conn,"SELECT COUNT(*) as count FROM tasks WHERE status='active'"));
$stats['inactive_tasks']        = intval(safeQueryValue($conn,"SELECT COUNT(*) as count FROM tasks WHERE status='inactive'"));
$stats['pending_submissions']   = intval(safeQueryValue($conn,"SELECT COUNT(*) as count FROM task_completions WHERE status='pending'"));
$stats['completed_submissions'] = intval(safeQueryValue($conn,"SELECT COUNT(*) as count FROM task_completions WHERE status='completed'"));
$stats['rejected_submissions']  = intval(safeQueryValue($conn,"SELECT COUNT(*) as count FROM task_completions WHERE status='rejected'"));
$stats['total_completions']     = $stats['completed_submissions'];
$stats['today_task_completions']= intval(safeQueryValue($conn,"SELECT COUNT(*) as count FROM task_completions WHERE status='completed' AND DATE(created_at)=CURDATE()"));

// Task earnings → KES
$stats['total_task_earnings'] = floatval(safeQueryValue($conn,"
    SELECT COALESCE(SUM(
        tc.reward_earned * GREATEST(COALESCE(c.exchange_rate,1),0.0001)
    ),0) as total
    FROM task_completions tc
    JOIN users u ON u.id=tc.user_id
    LEFT JOIN countries c ON c.name=u.country
    WHERE tc.status='completed'
",'total'));

// ── RECENT ACTIVITIES ─────────────────────────────────────────────────────
$recent_activations = $conn->query("
    SELECT u.id, u.username, u.email, u.country, u.activation_date,
        c.activation_fee,
        c.currency_symbol,
        -- Show fee in KES for admin
        (c.activation_fee * GREATEST(COALESCE(c.exchange_rate,1),0.0001)) as fee_kes
    FROM users u
    LEFT JOIN countries c ON u.country=c.name
    WHERE u.status='active' AND u.activation_date IS NOT NULL
    ORDER BY u.activation_date DESC LIMIT 10
");

$recent_transactions = $conn->query("
    SELECT t.*, u.username,
        -- Normalise to KES for display
        (t.amount * GREATEST(COALESCE(c.exchange_rate,1),0.0001)) as amount_kes
    FROM transactions t
    JOIN users u ON t.user_id=u.id
    LEFT JOIN countries c ON c.name=u.country
    WHERE t.status='completed'
    ORDER BY t.created_at DESC LIMIT 10
");

$recent_withdrawals = $conn->query("
    SELECT w.*, u.username,
        (w.amount * GREATEST(COALESCE(c.exchange_rate,1),0.0001)) as amount_kes
    FROM withdrawals w
    JOIN users u ON w.user_id=u.id
    LEFT JOIN countries c ON c.name=u.country
    WHERE w.status='pending'
    ORDER BY w.requested_at DESC LIMIT 5
");

$recent_task_submissions = $conn->query("
    SELECT tc.*, t.title as task_title, u.username
    FROM task_completions tc
    JOIN tasks t ON tc.task_id=t.id
    JOIN users u ON tc.user_id=u.id
    WHERE tc.status='pending'
    ORDER BY tc.created_at DESC LIMIT 10
");

// ── COUNTRY STATS ─────────────────────────────────────────────────────────
$countryStats = $conn->query("
    SELECT
        c.name as country,
        c.currency_symbol,
        c.exchange_rate,
        COUNT(u.id) as user_count,
        SUM(CASE WHEN u.status='active' THEN 1 ELSE 0 END) as active_count,
        SUM(CASE WHEN u.status='inactive' THEN 1 ELSE 0 END) as inactive_count,
        -- Revenue in KES
        SUM(CASE WHEN u.status='active'
            THEN c.activation_fee * GREATEST(COALESCE(c.exchange_rate,1),0.0001)
            ELSE 0 END) as total_revenue_kes
    FROM countries c
    LEFT JOIN users u ON u.country=c.name
    WHERE c.status='active'
    GROUP BY c.id, c.name, c.currency_symbol, c.exchange_rate
    ORDER BY user_count DESC
");

// ── ADMIN CURRENCY — ALWAYS KES ───────────────────────────────────────────
$defaultCurrency = 'Ksh'; // Admin always sees KES
$currencyCode    = 'KES';

// ── DERIVED STATS ─────────────────────────────────────────────────────────
$stats['avg_earnings_per_user']    = $stats['active_users'] > 0 ? ($stats['total_wallet_balance'] / $stats['active_users']) : 0;
$stats['withdrawal_ratio']         = $stats['total_wallet_balance'] > 0 ? (($stats['pending_withdrawal_amount'] / $stats['total_wallet_balance']) * 100) : 0;
$stats['platform_liquidity']       = $stats['total_admin_earnings'] - $stats['pending_withdrawal_amount'];

function safeTimeAgo($datetime) {
    if (empty($datetime)) return 'N/A';
    return timeAgo($datetime);
}
?>

<style>
.dashboard-container{padding:16px;max-width:1400px;margin:0 auto}
.page-header{margin-bottom:24px}
.page-title{font-size:24px;font-weight:900;color:var(--text-primary);margin-bottom:4px;display:flex;align-items:center;gap:10px}
.page-subtitle{font-size:13px;color:var(--text-secondary)}

/* KES badge — reminds admin everything is in KES */
.kes-badge{display:inline-flex;align-items:center;gap:5px;padding:3px 10px;border-radius:20px;font-size:10px;font-weight:700;background:rgba(16,185,129,.1);color:#10b981;border:1px solid rgba(16,185,129,.2);margin-left:8px}

.admin-earnings-card{background:linear-gradient(135deg,#667eea,#764ba2);border-radius:16px;padding:24px;margin-bottom:24px;box-shadow:0 10px 30px rgba(102,126,234,.3)}
.earnings-top{display:flex;align-items:center;gap:16px;margin-bottom:12px;flex-wrap:wrap}
.admin-earnings-icon{width:56px;height:56px;background:rgba(255,255,255,.2);border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0}
.admin-earnings-icon i{font-size:28px;color:white}
.earnings-info{flex:1;min-width:0}
.earnings-label{color:rgba(255,255,255,.9);font-size:13px;font-weight:600;text-transform:uppercase;letter-spacing:1px;margin-bottom:4px}
.admin-earnings-amount{color:white;font-size:42px;font-weight:900;line-height:1;word-break:break-all}
.admin-earnings-breakdown{display:flex;gap:24px;color:rgba(255,255,255,.95);font-size:13px;font-weight:500;flex-wrap:wrap}
.admin-earnings-breakdown>div{display:flex;align-items:center;gap:6px;white-space:nowrap}
.earnings-note{margin-top:12px;padding-top:12px;border-top:1px solid rgba(255,255,255,.2);font-size:11px;color:rgba(255,255,255,.8)}

.section-heading{font-size:15px;font-weight:800;color:var(--text-primary);margin:32px 0 16px;text-transform:uppercase;letter-spacing:1px}
.stats-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:24px}
.stat-card{background:var(--card-bg);border:1px solid var(--border-color);border-radius:14px;padding:18px;transition:all .3s;position:relative;overflow:hidden}
.stat-card:hover{transform:translateY(-2px);box-shadow:0 8px 24px rgba(0,0,0,.08)}
.stat-icon{width:44px;height:44px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:20px;color:white;margin-bottom:12px}
.stat-label{font-size:11px;color:var(--text-secondary);font-weight:600;margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px}
.stat-value{font-size:26px;font-weight:900;color:var(--text-primary);line-height:1.1;margin-bottom:8px;word-break:break-all}
.stat-footer{display:flex;align-items:center;gap:6px;font-size:11px;color:var(--text-secondary);flex-wrap:wrap}
.stat-change{display:inline-flex;align-items:center;gap:4px;padding:3px 8px;border-radius:6px;font-size:11px;font-weight:600}
.stat-change.positive{background:rgba(16,185,129,.1);color:#10b981}
.stat-change.negative{background:rgba(239,68,68,.1);color:#ef4444}

.dashboard-section{background:var(--card-bg);border:1px solid var(--border-color);border-radius:14px;padding:20px;margin-bottom:20px}
.section-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:18px;padding-bottom:14px;border-bottom:2px solid var(--border-color);gap:12px}
.section-title{font-size:17px;font-weight:800;color:var(--text-primary);display:flex;align-items:center;gap:10px;white-space:nowrap}
.section-link{color:var(--theme-color);text-decoration:none;font-size:13px;font-weight:600;display:flex;align-items:center;gap:6px;transition:all .3s;white-space:nowrap;flex-shrink:0}
.section-link:hover{gap:10px}
.table-wrapper{overflow-x:auto;-webkit-overflow-scrolling:touch;margin:0 -20px;padding:0 20px}
.table{width:100%;border-collapse:collapse;min-width:500px}
.table th{text-align:left;padding:12px;font-size:11px;font-weight:700;color:var(--text-secondary);text-transform:uppercase;border-bottom:2px solid var(--border-color);white-space:nowrap}
.table td{padding:14px 12px;border-bottom:1px solid var(--border-color);color:var(--text-primary);font-size:13px}
.table tbody tr:hover{background:var(--darker-bg)}

.badge{padding:5px 12px;border-radius:8px;font-size:11px;font-weight:700;text-transform:uppercase;display:inline-block;white-space:nowrap}
.badge-pending{background:rgba(245,158,11,.12);color:#f59e0b}
.badge-completed,.badge-approved{background:rgba(16,185,129,.12);color:#10b981}
.badge-active{background:rgba(59,130,246,.12);color:#3b82f6}
.badge-failed,.badge-rejected{background:rgba(239,68,68,.12);color:#ef4444}
.empty-state{text-align:center;padding:48px 20px;color:var(--text-secondary)}
.empty-state i{font-size:48px;opacity:.2;margin-bottom:16px;display:block}
.btn{padding:8px 16px;border-radius:8px;font-size:12px;font-weight:700;text-decoration:none;display:inline-flex;align-items:center;gap:6px;transition:all .3s;border:none;cursor:pointer;white-space:nowrap}
.btn-sm{padding:6px 12px;font-size:11px}
.btn-primary{background:var(--theme-color);color:white}
.btn-success{background:#10b981;color:white}
.btn-danger{background:#ef4444;color:white}
.two-column{display:grid;grid-template-columns:repeat(2,1fr);gap:20px}
.transaction-item{padding:12px;border-bottom:1px solid var(--border-color)}
.transaction-item:last-child{border-bottom:none}
.transaction-row{display:flex;justify-content:space-between;align-items:start;gap:12px;margin-bottom:6px}
.transaction-user{font-weight:700;font-size:13px;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.transaction-type{font-size:11px;color:var(--text-secondary);margin-top:2px}
.transaction-amount{font-weight:800;font-size:14px;text-align:right;white-space:nowrap}
.transaction-time{font-size:10px;color:var(--text-secondary);margin-top:2px;text-align:right}
.scrollable-list{max-height:400px;overflow-y:auto}
.scrollable-list::-webkit-scrollbar{width:4px}
.scrollable-list::-webkit-scrollbar-thumb{background:var(--border-color);border-radius:2px}
.withdrawal-actions{display:flex;gap:8px;flex-wrap:wrap}

@media(max-width:1024px){.stats-grid{grid-template-columns:repeat(3,1fr)}}
@media(max-width:768px){
    .dashboard-container{padding:12px}.page-title{font-size:20px}
    .admin-earnings-amount{font-size:32px}.admin-earnings-breakdown{flex-direction:column;gap:8px}
    .stats-grid{grid-template-columns:repeat(2,1fr);gap:12px}
    .stat-card{padding:14px}.stat-value{font-size:22px}
    .two-column{grid-template-columns:1fr;gap:16px}
    .table-wrapper{margin:0 -16px;padding:0 16px}
}
@media(max-width:480px){
    .dashboard-container{padding:10px}
    .stats-grid{grid-template-columns:repeat(2,1fr);gap:10px}
    .stat-card{padding:12px}.stat-value{font-size:18px}
    .admin-earnings-card{padding:16px;border-radius:12px}
    .admin-earnings-amount{font-size:26px}
}
@media(max-width:360px){
    .stats-grid{grid-template-columns:1fr}
    .stat-card{display:flex;align-items:center;gap:12px;padding:12px}
    .stat-icon{margin-bottom:0;flex-shrink:0}
    .stat-card .stat-value{font-size:20px;margin-bottom:2px}
}
</style>

<div class="dashboard-container">

<div class="page-header">
    <h1 class="page-title">
        <i class="fas fa-chart-line"></i> Dashboard
        <span class="kes-badge"><i class="fas fa-coins"></i> All figures in KES</span>
    </h1>
    <p class="page-subtitle">Platform performance — all monetary values automatically converted to Kenyan Shillings</p>
</div>

<!-- TODAY'S ADMIN EARNINGS -->
<div class="admin-earnings-card">
    <div class="earnings-top">
        <div class="admin-earnings-icon"><i class="fas fa-wallet"></i></div>
        <div class="earnings-info">
            <div class="earnings-label">💰 Today's Admin Earnings</div>
            <div class="admin-earnings-amount">Ksh <?= number_format($stats['today_admin_earnings'],2) ?></div>
        </div>
    </div>
    <div class="admin-earnings-breakdown">
        <div><i class="fas fa-arrow-up"></i> Revenue: Ksh <?= number_format($stats['today_activation_revenue'],2) ?></div>
        <div><i class="fas fa-minus-circle"></i> Commissions: Ksh <?= number_format($stats['today_total_commissions'],2) ?></div>
        <div><i class="fas fa-equals"></i> Earnings: Ksh <?= number_format($stats['today_admin_earnings'],2) ?></div>
    </div>
    <div class="earnings-note">
        <i class="fas fa-info-circle"></i>
        All amounts converted from local currencies using each country's exchange rate &nbsp;·&nbsp;
        Commission paid today: Ksh <?= number_format($stats['today_commission_paid'],2) ?>
    </div>
</div>

<!-- TODAY'S METRICS -->
<h3 class="section-heading">📊 Today's Performance</h3>
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-icon" style="background:linear-gradient(135deg,#10b981,#059669)"><i class="fas fa-user-check"></i></div>
        <div class="stat-label">Activated Today</div>
        <div class="stat-value"><?= number_format($stats['activated_today']) ?></div>
        <div class="stat-footer"><i class="fas fa-users"></i> New active members</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon" style="background:linear-gradient(135deg,#3b82f6,#2563eb)"><i class="fas fa-dollar-sign"></i></div>
        <div class="stat-label">Activation Fees (KES)</div>
        <div class="stat-value">Ksh <?= number_format($stats['today_activation_revenue'],0) ?></div>
        <div class="stat-footer"><i class="fas fa-arrow-up"></i> Total collected</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon" style="background:linear-gradient(135deg,#f59e0b,#d97706)"><i class="fas fa-hand-holding-usd"></i></div>
        <div class="stat-label">Commissions (KES)</div>
        <div class="stat-value">Ksh <?= number_format($stats['today_total_commissions'],0) ?></div>
        <div class="stat-footer"><i class="fas fa-users"></i> All levels</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon" style="background:linear-gradient(135deg,#10b981,#059669)"><i class="fas fa-chart-line"></i></div>
        <div class="stat-label">Your Earnings Today</div>
        <div class="stat-value">Ksh <?= number_format($stats['today_admin_earnings'],0) ?></div>
        <div class="stat-footer">
            <?php $margin = $stats['today_activation_revenue'] > 0 ? ($stats['today_admin_earnings']/$stats['today_activation_revenue']*100) : 0; ?>
            <i class="fas fa-percentage"></i> <?= number_format($margin,1) ?>% margin
        </div>
    </div>
</div>

<!-- ALL-TIME METRICS -->
<h3 class="section-heading">📈 All-Time Statistics</h3>
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-icon" style="background:linear-gradient(135deg,#667eea,#764ba2)"><i class="fas fa-users"></i></div>
        <div class="stat-label">Total Users</div>
        <div class="stat-value"><?= number_format($stats['total_users']) ?></div>
        <div class="stat-footer"><span class="stat-change positive"><i class="fas fa-plus"></i> <?= $stats['new_users_today'] ?> today</span></div>
    </div>
    <div class="stat-card">
        <div class="stat-icon" style="background:linear-gradient(135deg,#10b981,#059669)"><i class="fas fa-user-check"></i></div>
        <div class="stat-label">Active Users</div>
        <div class="stat-value"><?= number_format($stats['active_users']) ?></div>
        <div class="stat-footer"><i class="fas fa-percentage"></i> <?= $stats['total_users']>0?round(($stats['active_users']/$stats['total_users'])*100,1):0 ?>% activated</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon" style="background:linear-gradient(135deg,#ef4444,#dc2626)"><i class="fas fa-user-times"></i></div>
        <div class="stat-label">Inactive Users</div>
        <div class="stat-value"><?= number_format($stats['inactive_users']) ?></div>
        <div class="stat-footer"><i class="fas fa-clock"></i> Pending activation</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon" style="background:linear-gradient(135deg,#3b82f6,#2563eb)"><i class="fas fa-money-bill-wave"></i></div>
        <div class="stat-label">Total Revenue (KES)</div>
        <div class="stat-value">Ksh <?= number_format($stats['total_activation_revenue'],0) ?></div>
        <div class="stat-footer"><i class="fas fa-chart-bar"></i> All countries</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon" style="background:linear-gradient(135deg,#f59e0b,#d97706)"><i class="fas fa-users"></i></div>
        <div class="stat-label">Total Commissions (KES)</div>
        <div class="stat-value">Ksh <?= number_format($stats['total_commissions_owed'],0) ?></div>
        <div class="stat-footer"><i class="fas fa-hand-holding-usd"></i> All levels</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon" style="background:linear-gradient(135deg,#10b981,#059669)"><i class="fas fa-piggy-bank"></i></div>
        <div class="stat-label">Total Admin Earnings (KES)</div>
        <div class="stat-value">Ksh <?= number_format($stats['total_admin_earnings'],0) ?></div>
        <div class="stat-footer">
            <?php $tm=$stats['total_activation_revenue']>0?($stats['total_admin_earnings']/$stats['total_activation_revenue']*100):0;?>
            <i class="fas fa-percentage"></i> <?= number_format($tm,1) ?>% margin
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon" style="background:linear-gradient(135deg,#8b5cf6,#7c3aed)"><i class="fas fa-wallet"></i></div>
        <div class="stat-label">Total Referral Wallets (KES)</div>
        <div class="stat-value">Ksh <?= number_format($stats['total_referral_balance'],0) ?></div>
        <div class="stat-footer"><i class="fas fa-coins"></i> In referral wallets</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon" style="background:linear-gradient(135deg,#ec4899,#db2777)"><i class="fas fa-coins"></i></div>
        <div class="stat-label">All User Wallets (KES)</div>
        <div class="stat-value">Ksh <?= number_format($stats['total_wallet_balance'],0) ?></div>
        <div class="stat-footer"><i class="fas fa-layer-group"></i> Combined balance</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon" style="background:linear-gradient(135deg,#ec4899,#db2777)"><i class="fas fa-clock"></i></div>
        <div class="stat-label">Pending Withdrawals</div>
        <div class="stat-value"><?= number_format($stats['pending_withdrawals']) ?></div>
        <div class="stat-footer">
            <?php if($stats['pending_withdrawals']>0):?>
            <a href="withdrawals.php?status=pending" class="section-link">Ksh <?= number_format($stats['pending_withdrawal_amount'],0) ?> <i class="fas fa-arrow-right"></i></a>
            <?php else:?><span style="color:#10b981"><i class="fas fa-check"></i> All clear!</span><?php endif;?>
        </div>
    </div>
</div>

<!-- RECENT ACTIVATIONS -->
<div class="dashboard-section">
    <div class="section-header">
        <h2 class="section-title"><i class="fas fa-bolt"></i> Recent Activations</h2>
        <a href="users.php?status=active" class="section-link">View All <i class="fas fa-arrow-right"></i></a>
    </div>
    <?php if($recent_activations&&$recent_activations->num_rows>0):?>
    <div class="table-wrapper">
    <table class="table">
        <thead><tr><th>User</th><th>Country</th><th>Fee (Local)</th><th>Fee (KES)</th><th>Date</th></tr></thead>
        <tbody>
        <?php while($act=$recent_activations->fetch_assoc()):?>
        <tr>
            <td style="font-weight:700"><?= htmlspecialchars($act['username']??'N/A') ?></td>
            <td><?= htmlspecialchars($act['country']??'') ?></td>
            <td style="color:var(--text-secondary)"><?= htmlspecialchars($act['currency_symbol']??'') ?> <?= number_format(floatval($act['activation_fee']??0),0) ?></td>
            <td style="color:var(--theme-color);font-weight:700">Ksh <?= number_format(floatval($act['fee_kes']??0),0) ?></td>
            <td><?= safeTimeAgo($act['activation_date']??null) ?></td>
        </tr>
        <?php endwhile;?>
        </tbody>
    </table>
    </div>
    <?php else:?>
    <div class="empty-state"><i class="fas fa-user-check"></i><p>No activations yet</p></div>
    <?php endif;?>
</div>

<div class="two-column">
    <!-- RECENT TRANSACTIONS -->
    <div class="dashboard-section">
        <div class="section-header">
            <h2 class="section-title"><i class="fas fa-exchange-alt"></i> Recent Transactions</h2>
            <a href="transactions.php" class="section-link">View All <i class="fas fa-arrow-right"></i></a>
        </div>
        <?php if($recent_transactions&&$recent_transactions->num_rows>0):?>
        <div class="scrollable-list">
        <?php while($trans=$recent_transactions->fetch_assoc()):
            $isDebit=(stripos($trans['type']??'','debit')!==false||stripos($trans['type']??'','withdrawal')!==false);
            $amtColor=$isDebit?'#ef4444':'#10b981';
            $amtPrefix=$isDebit?'-':'+';
        ?>
        <div class="transaction-item">
            <div class="transaction-row">
                <div style="min-width:0;flex:1">
                    <div class="transaction-user"><?= htmlspecialchars($trans['username']??'Unknown') ?></div>
                    <div class="transaction-type"><?= str_replace('_',' ',ucwords($trans['type']??'')) ?></div>
                </div>
                <div style="flex-shrink:0">
                    <div class="transaction-amount" style="color:<?= $amtColor ?>">
                        <?= $amtPrefix ?>Ksh <?= number_format(floatval($trans['amount_kes']??0),2) ?>
                    </div>
                    <div class="transaction-time"><?= safeTimeAgo($trans['created_at']??null) ?></div>
                </div>
            </div>
        </div>
        <?php endwhile;?>
        </div>
        <?php else:?>
        <div class="empty-state"><i class="fas fa-exchange-alt"></i><p>No transactions yet</p></div>
        <?php endif;?>
    </div>

    <!-- PENDING WITHDRAWALS -->
    <div class="dashboard-section">
        <div class="section-header">
            <h2 class="section-title"><i class="fas fa-money-check-alt"></i> Pending Withdrawals</h2>
            <a href="withdrawals.php?status=pending" class="section-link">View All <i class="fas fa-arrow-right"></i></a>
        </div>
        <?php if($recent_withdrawals&&$recent_withdrawals->num_rows>0):?>
        <div class="scrollable-list">
        <?php while($with=$recent_withdrawals->fetch_assoc()):?>
        <div class="transaction-item">
            <div class="transaction-row" style="margin-bottom:8px">
                <div style="min-width:0;flex:1">
                    <div class="transaction-user"><?= htmlspecialchars($with['username']??'Unknown') ?></div>
                    <div class="transaction-type"><?= htmlspecialchars($with['phone_number']??'') ?></div>
                </div>
                <div style="flex-shrink:0">
                    <div class="transaction-amount" style="color:var(--theme-color)">Ksh <?= number_format(floatval($with['amount_kes']??0),2) ?></div>
                    <div class="transaction-time"><?= safeTimeAgo($with['requested_at']??null) ?></div>
                </div>
            </div>
            <div class="withdrawal-actions">
                <a href="withdrawals.php?action=approve&id=<?= intval($with['id']) ?>" class="btn btn-sm btn-success"><i class="fas fa-check"></i> Approve</a>
                <a href="withdrawals.php?action=reject&id=<?= intval($with['id']) ?>" class="btn btn-sm btn-danger"><i class="fas fa-times"></i> Reject</a>
            </div>
        </div>
        <?php endwhile;?>
        </div>
        <?php else:?>
        <div class="empty-state"><i class="fas fa-check-circle"></i><p>No pending withdrawals!</p></div>
        <?php endif;?>
    </div>
</div>

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