<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'Analytics Dashboard';
include 'side.php'; // sets $userId, $conn, $userData, $siteName, $adminPrimary etc.
$isVerified = ($userData['verified'] ?? 0) == 1;

// ── Wallet ────────────────────────────────────────────────────────────────
$stmt = $conn->prepare("SELECT * FROM wallets WHERE user_id=? LIMIT 1");
$stmt->bind_param("i",$userId); $stmt->execute();
$uw = $stmt->get_result()->fetch_assoc();
if (!$uw) {
    $ins = $conn->prepare("INSERT INTO wallets(user_id,main_wallet,referral_wallet,bonus_wallet,video_wallet,trivia_wallet,survey_wallet,ads_wallet,spin_wallet,blog_wallet,meme_wallet,chat_wallet,transcription_wallet,created_at,updated_at)VALUES(?,0,0,0,0,0,0,0,0,0,0,0,0,NOW(),NOW())");
    $ins->bind_param("i",$userId); $ins->execute();
    $stmt = $conn->prepare("SELECT * FROM wallets WHERE user_id=? LIMIT 1");
    $stmt->bind_param("i",$userId); $stmt->execute();
    $uw = $stmt->get_result()->fetch_assoc();
}
$wRef  = floatval($uw['referral_wallet']      ?? 0);
$wMain = floatval($uw['main_wallet']          ?? 0);
$wBonus= floatval($uw['bonus_wallet']         ?? 0);
$wVid  = floatval($uw['video_wallet']         ?? 0);
$wTri  = floatval($uw['trivia_wallet']        ?? 0);
$wSur  = floatval($uw['survey_wallet']        ?? 0);
$wAds  = floatval($uw['ads_wallet']           ?? 0);
$wSpin = floatval($uw['spin_wallet']          ?? 0);
$wBlog = floatval($uw['blog_wallet']          ?? 0);
$wMeme = floatval($uw['meme_wallet']          ?? 0);
$wChat = floatval($uw['chat_wallet']          ?? 0);
$wTran = floatval($uw['transcription_wallet'] ?? 0);
$totalWallets = $wRef+$wMain+$wBonus+$wVid+$wTri+$wSur+$wAds+$wSpin+$wBlog+$wMeme+$wChat+$wTran;

// ── Withdrawn (local currency) ────────────────────────────────────────────
$stmt = $conn->prepare("SELECT COALESCE(SUM(net_amount),0) as tw FROM withdrawals WHERE user_id=? AND (status IN('completed','approved') OR hashback_status='SENT')");
$stmt->bind_param("i",$userId); $stmt->execute();
$withdrawn = floatval($stmt->get_result()->fetch_assoc()['tw']);

// ── Country / Currency ────────────────────────────────────────────────────
$stmt = $conn->prepare("SELECT activation_fee, currency_symbol, currency_code, exchange_rate FROM countries WHERE name=?");
$stmt->bind_param("s",$userData['country']); $stmt->execute();
$cd  = $stmt->get_result()->fetch_assoc();
$fee = floatval($cd['activation_fee']  ?? 200);
$cs  = $cd['currency_symbol']          ?? 'Ksh';
$cc  = $cd['currency_code']            ?? 'KES';
$er  = max(0.000001, floatval($cd['exchange_rate'] ?? 1));

// ── USD rate ──────────────────────────────────────────────────────────────
$kesPerUsd = floatval(getSetting('kes_usd_rate', '130'));
if ($kesPerUsd <= 0) $kesPerUsd = 130;
$usdRate = $kesPerUsd / $er;

// ── Network ───────────────────────────────────────────────────────────────
$stmt = $conn->prepare("SELECT COUNT(*) as c FROM users WHERE referred_by=?");
$stmt->bind_param("i",$userId); $stmt->execute();
$netTot = intval($stmt->get_result()->fetch_assoc()['c']);

$stmt = $conn->prepare("SELECT COUNT(*) as c FROM users WHERE referred_by=? AND status='active'");
$stmt->bind_param("i",$userId); $stmt->execute();
$netAct = intval($stmt->get_result()->fetch_assoc()['c']);

$netPending = max(0, $netTot - $netAct);

$stmt = $conn->prepare("SELECT COUNT(*) as c FROM users WHERE referred_by=? AND status='active' AND DATE(activation_date)=CURDATE()");
$stmt->bind_param("i",$userId); $stmt->execute();
$todayNewMembers = intval($stmt->get_result()->fetch_assoc()['c']);

$stmt = $conn->prepare("SELECT COUNT(*) as c FROM users WHERE referred_by=? AND status='active' AND activation_date >= DATE_SUB(NOW(),INTERVAL 7 DAY)");
$stmt->bind_param("i",$userId); $stmt->execute();
$weeklyRefs = intval($stmt->get_result()->fetch_assoc()['c']);

// ── Today earnings (local currency) ──────────────────────────────────────
$todayRaw = 0.0;
$q1 = $conn->prepare("SELECT COALESCE(SUM(amount),0) AS te FROM transactions WHERE user_id=? AND type='credit' AND status='completed' AND DATE(created_at)=CURDATE()");
if ($q1) { $q1->bind_param("i",$userId); $q1->execute(); $todayRaw += floatval($q1->get_result()->fetch_assoc()['te'] ?? 0); }
$q2 = $conn->prepare("SELECT COALESCE(SUM(amount),0) AS te FROM transactions WHERE user_id=? AND type='' AND status='completed' AND amount>0 AND (description LIKE '%referral bonus%' OR reference LIKE 'REF_%' OR reference LIKE 'PCOMM%') AND DATE(created_at)=CURDATE()");
if ($q2) { $q2->bind_param("i",$userId); $q2->execute(); $todayRaw += floatval($q2->get_result()->fetch_assoc()['te'] ?? 0); }
$q3 = $conn->prepare("SELECT COALESCE(SUM(reward_earned),0) as te FROM task_completions WHERE user_id=? AND status='completed' AND DATE(created_at)=CURDATE()");
if ($q3) { $q3->bind_param("i",$userId); $q3->execute(); $todayRaw += floatval($q3->get_result()->fetch_assoc()['te'] ?? 0); }

// ── 7-day daily chart data ────────────────────────────────────────────────
$dailyEarnings = []; $dailyRefs = [];
for ($i = 6; $i >= 0; $i--) {
    $ds = $conn->prepare("SELECT COALESCE(SUM(amount),0) as de FROM transactions WHERE user_id=? AND type='credit' AND status='completed' AND DATE(created_at)=DATE_SUB(CURDATE(),INTERVAL ? DAY)");
    $ds->bind_param("ii",$userId,$i); $ds->execute();
    $dailyEarnings[] = round(floatval($ds->get_result()->fetch_assoc()['de'] ?? 0), 2);

    $dr = $conn->prepare("SELECT COUNT(*) as cnt FROM users WHERE referred_by=? AND status='active' AND DATE(activation_date)=DATE_SUB(CURDATE(),INTERVAL ? DAY)");
    $dr->bind_param("ii",$userId,$i); $dr->execute();
    $dailyRefs[] = intval($dr->get_result()->fetch_assoc()['cnt'] ?? 0);
}

// ── Products & commissions ────────────────────────────────────────────────
$totOwned = 0;
$pq = $conn->prepare("SELECT status FROM product_purchases WHERE user_id=?");
$pq->bind_param("i",$userId); $pq->execute();
$pr = $pq->get_result();
while ($p = $pr->fetch_assoc()) { if ($p['status'] === 'completed') $totOwned++; }

$comEarned = 0;
$cq = $conn->query("SELECT COALESCE(SUM(commission_amount),0) as t FROM product_commissions WHERE recipient_id={$userId}");
if ($cq) $comEarned = floatval($cq->fetch_assoc()['t'] ?? 0);

// ── Tournament Rank (weekly) ──────────────────────────────────────────────
$tournamentRank = 0;
$tournamentActive = 0;
$now = new DateTime('now', new DateTimeZone('Africa/Nairobi'));
$dayOfWeek = intval($now->format('N'));
$weekStart = clone $now;
$weekStart->modify('-' . ($dayOfWeek - 1) . ' days')->setTime(0, 0, 0);
$weekEnd = clone $weekStart;
$weekEnd->modify('+6 days')->setTime(23, 59, 59);
$wsStr = $weekStart->format('Y-m-d H:i:s');
$weStr = $weekEnd->format('Y-m-d H:i:s');

$lbQuery = $conn->prepare("
    SELECT r.id, COUNT(DISTINCT u.id) AS active_referrals
    FROM users r
    INNER JOIN users u ON u.referred_by = r.id AND u.status = 'active' AND u.activation_date >= ? AND u.activation_date <= ?
    GROUP BY r.id
    ORDER BY active_referrals DESC
");
$lbQuery->bind_param("ss", $wsStr, $weStr);
$lbQuery->execute();
$leaderboard = $lbQuery->get_result()->fetch_all(MYSQLI_ASSOC);

foreach($leaderboard as $idx => $row) {
    if ($row['id'] == $userId) {
        $tournamentRank = $idx + 1;
        $tournamentActive = intval($row['active_referrals']);
        break;
    }
}

// ── Derived analytics ─────────────────────────────────────────────────────
$activationRate = $netTot > 0 ? round(($netAct/$netTot)*100) : 0;
$earningRate    = $netTot > 0 ? round(($netAct/$netTot)*100) : 0;

// ── Site Logo ─────────────────────────────────────────────────────────────
$siteLogo = '';
// First try getSetting function
if (function_exists('getSetting')) {
    $siteLogo = getSetting('site_logo', '');
}
// If empty, try direct database query
if (empty($siteLogo)) {
    $logoQuery = $conn->query("SELECT setting_value FROM site_settings WHERE setting_key='site_logo' LIMIT 1");
    if ($logoQuery && $logoQuery->num_rows > 0) {
        $siteLogo = $logoQuery->fetch_assoc()['setting_value'];
    }
}
// Build full logo path if we have a logo
$logoPath = '';
if (!empty($siteLogo)) {
    // Check common upload directories
    $possiblePaths = [
        '../uploads/logos/' . $siteLogo,
        '../assets/images/' . $siteLogo,
        '../images/' . $siteLogo,
        $siteLogo // Could be full path already
    ];
    foreach ($possiblePaths as $path) {
        if (file_exists($path)) {
            $logoPath = str_replace('../', '/', $path);
            break;
        }
    }
}

// ── Notification ──────────────────────────────────────────────────────────
$notifTxt = 'Maximize your earnings — share your invite link today!';
$notifOn  = true;
$nq = $conn->query("SELECT setting_key,setting_value FROM site_settings WHERE setting_key IN('dashboard_notification','dashboard_notification_enabled')");
if ($nq && $nq->num_rows > 0) {
    while ($r = $nq->fetch_assoc()) {
        if ($r['setting_key'] === 'dashboard_notification') $notifTxt = str_replace(['{SITE_NAME}','{siteName}'], $siteName, $r['setting_value']);
        if ($r['setting_key'] === 'dashboard_notification_enabled') $notifOn = $r['setting_value'] === '1';
    }
}
$flash = getFlash();
?>
<!-- Force light mode as default (runs before paint to avoid flash) -->
<script>
(function(){
    try {
        var saved = localStorage.getItem('ev_theme');
        var theme = saved || 'light';
        document.documentElement.setAttribute('data-theme', theme);
        if (!saved) localStorage.setItem('ev_theme', 'light');
    } catch(e) {
        document.documentElement.setAttribute('data-theme', 'light');
    }
})();
</script>

<style>
/* ════════════════════════════════════════════════════════════════════════
   EARNOVIX ANALYTICS DASHBOARD — ENHANCED WITH GLASSMORPHISM
   Admin Color Injection · Light/Dark Mode · Gradient Backgrounds
════════════════════════════════════════════════════════════════════════ */

/* ── LIGHT MODE PURPLE THEME (MATCHING SCREENSHOT) ── */
[data-theme="light"] {
    --bg1:  #1a0f2e !important;
    --bg2:  #2d1b4e !important;
    --bg3:  #3d2659 !important;
    --bdr:  rgba(255,255,255,0.12) !important;
    --bdr-p:rgba(var(--Pr),0.35) !important;
    --txt:  rgba(255,255,255,0.95) !important;
    --txt2: rgba(255,255,255,0.75) !important;
    --txt3: rgba(255,255,255,0.50) !important;
    --P-bg: rgba(var(--Pr),0.15) !important;
    --S-bg: rgba(var(--Sr),0.15) !important;
    --OK-bg:rgba(34,197,94,0.12) !important;
    --WN-bg:rgba(255,184,0,0.12) !important;
    --DN-bg:rgba(255,79,139,0.15) !important;
    --hdr-bg: rgba(26,15,46,0.95) !important;
    --sb-bg:  #2d1b4e !important;
    --card:   #2d1b4e !important;
    --card2:  #3d2659 !important;
    --shadow: 0 4px 24px rgba(0,0,0,0.4) !important;
    --scroll-thumb: rgba(var(--Pr),0.30) !important;
}

.pg{max-width:100%;overflow-x:hidden}
.db-body{padding:14px 14px 90px}
@media(min-width:1024px){.db-body{padding:18px 20px 90px}}
@media(max-width:1023px) and (min-width:769px){.db-body{padding:16px 14px 90px}}

.sec-lbl{font-size:9px;font-weight:700;letter-spacing:2px;text-transform:uppercase;color:var(--P);opacity:.7;margin:16px 0 8px;display:flex;align-items:center;gap:8px}
.sec-lbl::after{content:'';flex:1;height:1px;background:linear-gradient(90deg,var(--P-bg),transparent)}

/* ── PRELOADER ── FULL PAGE COVERAGE ── */
#pagePreloader{
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background:linear-gradient(135deg,rgba(var(--Pr),.25),rgba(var(--Sr),.10),rgba(0,0,0,.95));
    z-index:99999;
    display:flex;
    align-items:center;
    justify-content:center;
    transition:opacity .6s ease,visibility .6s ease;
    backdrop-filter:blur(10px);
    -webkit-backdrop-filter:blur(10px);
}
[data-theme="light"] #pagePreloader{
    background:linear-gradient(135deg,#2d1b4e,#1a0f2e,#0f0820);
}
#pagePreloader.hidden{
    opacity:0;
    visibility:hidden;
}
.preloader-content{
    display:flex;
    flex-direction:column;
    align-items:center;
    gap:20px;
}

/* Circular Spinner */
.spinner-circle{
    width:80px;
    height:80px;
    position:relative;
    animation:smoothPulse 2s ease-in-out infinite;
}
@keyframes smoothPulse{
    0%,100%{transform:scale(1)}
    50%{transform:scale(1.05)}
}

.spinner-ring{
    position:absolute;
    width:100%;
    height:100%;
    border-radius:50%;
    border:3px solid transparent;
    border-top-color:var(--P);
    border-right-color:var(--P);
    animation:spinSmooth 1.2s cubic-bezier(.55,.15,.45,.85) infinite;
}
@keyframes spinSmooth{
    0%{transform:rotate(0deg)}
    100%{transform:rotate(360deg)}
}

.spinner-ring:nth-child(2){
    width:90%;
    height:90%;
    top:5%;
    left:5%;
    border-top-color:var(--S);
    border-right-color:var(--S);
    animation:spinSmooth 1.5s cubic-bezier(.55,.15,.45,.85) infinite reverse;
}

.spinner-ring:nth-child(3){
    width:80%;
    height:80%;
    top:10%;
    left:10%;
    border-top-color:var(--OK);
    border-right-color:var(--OK);
    animation:spinSmooth 1.8s cubic-bezier(.55,.15,.45,.85) infinite;
    opacity:.7;
}

.spinner-center{
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    width:40px;
    height:40px;
    border-radius:50%;
    background:linear-gradient(135deg,var(--P),var(--S));
    display:flex;
    align-items:center;
    justify-content:center;
    color:#fff;
    font-size:18px;
    box-shadow:0 4px 20px rgba(var(--Pr),.4);
    animation:centerGlow 2s ease-in-out infinite;
}
@keyframes centerGlow{
    0%,100%{box-shadow:0 4px 20px rgba(var(--Pr),.4)}
    50%{box-shadow:0 6px 30px rgba(var(--Pr),.6)}
}

.spinner-logo{
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    width:52px;
    height:52px;
    border-radius:50%;
    background:#ffffff;
    display:flex;
    align-items:center;
    justify-content:center;
    box-shadow:0 4px 20px rgba(var(--Pr),.4);
    animation:centerGlow 2s ease-in-out infinite;
    overflow:hidden;
    padding:10px;
}
[data-theme="light"] .spinner-logo{
    background:#ffffff;
    box-shadow:0 4px 20px rgba(var(--Pr),.3);
}
.spinner-logo .logo-img{
    width:100%;
    height:100%;
    object-fit:contain;
    animation:logoFloat 3s ease-in-out infinite;
}
@keyframes logoFloat{
    0%,100%{transform:scale(1)}
    50%{transform:scale(1.08)}
}
.spinner-logo .logo-text{
    font-size:18px;
    font-weight:900;
    background:linear-gradient(135deg,var(--P),var(--S));
    -webkit-background-clip:text;
    -webkit-text-fill-color:transparent;
    background-clip:text;
    letter-spacing:-1px;
}

.preloader-text{
    font-size:14px;
    font-weight:700;
    color:#ffffff;
    letter-spacing:1.2px;
    animation:textFade 1.5s ease-in-out infinite;
}
@keyframes textFade{
    0%,100%{opacity:.4}
    50%{opacity:1}
}

.preloader-subtext{
    font-size:11px;
    font-weight:600;
    color:rgba(255,255,255,.75);
    letter-spacing:.5px;
    margin-top:-8px;
}

/* Loading dots animation */
.loading-dots{
    display:inline-flex;
    gap:4px;
    margin-left:4px;
}
.loading-dots span{
    width:4px;
    height:4px;
    background:var(--P);
    border-radius:50%;
    animation:dotBounce 1.4s ease-in-out infinite;
}
.loading-dots span:nth-child(2){animation-delay:.2s}
.loading-dots span:nth-child(3){animation-delay:.4s}
@keyframes dotBounce{
    0%,60%,100%{transform:translateY(0)}
    30%{transform:translateY(-8px)}
}

/* ── HERO ── DARK SOLID BACKGROUNDS WITH CONCENTRATED COLORS ── */
.hero-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:9px;margin-bottom:12px}
.hero-grid .full{grid-column:1/-1}
.hstat{
    border:1px solid var(--bdr);
    border-radius:14px;
    padding:13px 14px;
    position:relative;
    overflow:hidden;
    transition:border-color .2s,background .25s,box-shadow .2s,transform .2s;
}
.hstat:hover{
    box-shadow:0 8px 24px rgba(0,0,0,.3);
    transform:translateY(-2px);
}
.hstat::before{
    content:'';
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    opacity:0.15;
    pointer-events:none;
    transition:opacity .3s;
}
.hstat:hover::before{opacity:0.22}

/* Portfolio - Primary gradient DARK CONCENTRATED */
.hstat.prime{
    border-color:rgba(var(--Pr),.75);
    background:linear-gradient(135deg,rgba(var(--Pr),.75),rgba(var(--Pr),.58));
}
.hstat.prime::before{background:linear-gradient(135deg,var(--P),transparent)}

/* Withdrawn - Red VIBRANT gradient */
.hstat.red-c{
    border-color:rgba(239,68,68,.80);
    background:linear-gradient(135deg,rgba(239,68,68,.72),rgba(220,38,38,.58));
}
.hstat.red-c::before{background:linear-gradient(135deg,#ef4444,#dc2626)}

/* Today - Blue VIBRANT gradient */
.hstat.blue-c{
    border-color:rgba(59,130,246,.80);
    background:linear-gradient(135deg,rgba(59,130,246,.72),rgba(37,99,235,.58));
}
.hstat.blue-c::before{background:linear-gradient(135deg,#3b82f6,#2563eb)}

/* Balance - Green VIBRANT gradient */
.hstat.green-c{
    border-color:rgba(34,197,94,.80);
    background:linear-gradient(135deg,rgba(34,197,94,.72),rgba(22,163,74,.58));
}
.hstat.green-c::before{background:linear-gradient(135deg,#22c55e,#16a34a)}

/* Tournament - Purple/Gold VIBRANT gradient */
.hstat.purple-c{
    border-color:rgba(168,85,247,.80);
    background:linear-gradient(135deg,rgba(168,85,247,.72),rgba(251,191,36,.58));
}
.hstat.purple-c::before{background:linear-gradient(135deg,#a855f7,#fbbf24)}

.hstat-top{display:flex;align-items:center;justify-content:space-between;margin-bottom:5px}
.hstat-lbl{font-size:9px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;color:rgba(255,255,255,.85)}
.hstat-ico{
    width:22px;
    height:22px;
    border-radius:6px;
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:10px;
}
.hstat-ico.c{background:rgba(var(--Pr),.55);color:var(--P)}
.hstat-ico.s{background:rgba(var(--Sr),.55);color:var(--S)}
.hstat-ico.ok{background:rgba(34,197,94,.55);color:var(--OK)}
.hstat-ico.wn{background:rgba(251,191,36,.55);color:var(--WN)}
.hstat-ico.dn{background:rgba(239,68,68,.55);color:var(--DN)}
.hstat-ico.red{background:rgba(239,68,68,.60);color:#ef4444}
.hstat-ico.blue{background:rgba(59,130,246,.60);color:#3b82f6}
.hstat-ico.green{background:rgba(34,197,94,.60);color:#22c55e}
.hstat-ico.purple{
    background:linear-gradient(135deg,rgba(168,85,247,.65),rgba(251,191,36,.55));
    color:#a855f7;
}
[data-theme="light"] .hstat-ico.purple{color:#7c3aed}

.hstat-val{font-size:22px;font-weight:800;letter-spacing:-.6px;color:#ffffff;line-height:1;font-variant-numeric:tabular-nums}
.hstat-val.sm{font-size:17px}
.hstat-val.red-v{color:#ffffff}
.hstat-val.blue-v{color:#ffffff}
.hstat-val.green-v{color:#ffffff}
.hstat-val.purple-v{color:#ffffff}
[data-theme="light"] .hstat-val.purple-v{
    background:linear-gradient(135deg,#7c3aed,#d97706);
    -webkit-background-clip:text;
    -webkit-text-fill-color:transparent;
    background-clip:text;
}

.hstat-sub{font-size:10px;color:rgba(255,255,255,.75);margin-top:5px;display:flex;align-items:center;gap:5px;flex-wrap:wrap}
.badge-up{background:var(--OK-bg);color:var(--OK);padding:1px 6px;border-radius:3px;font-size:9px;font-weight:700}
.badge-dn{background:var(--DN-bg);color:var(--DN);padding:1px 6px;border-radius:3px;font-size:9px;font-weight:700}
.badge-prize{
    background:linear-gradient(135deg,rgba(251,191,36,.25),rgba(168,85,247,.20));
    color:#fbbf24;
    padding:1px 6px;
    border-radius:3px;
    font-size:9px;
    font-weight:700;
    border:1px solid rgba(251,191,36,.3);
}
[data-theme="light"] .badge-prize{
    background:linear-gradient(135deg,rgba(251,191,36,.30),rgba(168,85,247,.25));
    color:#d97706;
    border-color:rgba(251,191,36,.4);
}

/* Currency toggle */
.cur-row{display:flex;gap:5px;margin-top:12px}
.cur-btn{
    flex:1;
    padding:8px 0;
    border-radius:9px;
    border:1px solid var(--bdr);
    cursor:pointer;
    font-size:11px;
    font-weight:700;
    font-family:inherit;
    transition:all .18s;
    background:rgba(var(--Pr),.32);
    color:rgba(255,255,255,.75);
}
[data-theme="light"] .cur-btn{
    background:var(--bg3);
}
.cur-btn.on{
    background:var(--P);
    color:#fff;
    border-color:transparent;
    box-shadow:0 2px 8px rgba(var(--Pr),.4);
}
[data-theme="light"] .cur-btn.on{color:#fff}

/* ── CHART CARD ── DARK SOLID CONCENTRATED ── */
.chart-card{
    background:linear-gradient(135deg,rgba(var(--Pr),.18),rgba(0,0,0,.38));
    border:1px solid var(--bdr);
    border-radius:14px;
    padding:14px;
    margin-bottom:10px;
    transition:background .25s,border-color .25s,transform .2s;
}
.chart-card:hover{transform:translateY(-1px)}
.card-hdr{display:flex;align-items:flex-start;justify-content:space-between;gap:8px;margin-bottom:12px;flex-wrap:wrap}
.card-title{font-size:13px;font-weight:700;color:#ffffff}
.card-sub{font-size:10px;color:rgba(255,255,255,.75);margin-top:2px}
.chip-row{display:flex;gap:4px;flex-shrink:0}
.chip{
    padding:3px 9px;
    border-radius:20px;
    font-size:9px;
    font-weight:700;
    cursor:pointer;
    border:1px solid var(--bdr);
    color:rgba(255,255,255,.75);
    background:rgba(var(--Pr),.22);
    font-family:inherit;
    letter-spacing:.5px;
    transition:all .15s;
}
[data-theme="light"] .chip{
    background:rgba(var(--Pr),.30);
    color:#ffffff;
}
.chip.on{border-color:var(--P);color:var(--P);background:rgba(var(--Pr),.40)}
[data-theme="light"] .chip.on{background:rgba(var(--Pr),.50);color:#ffffff}
.chart-legend{display:flex;gap:14px;margin-top:10px;font-size:10px;color:rgba(255,255,255,.75);flex-wrap:wrap}
.chart-legend span{display:flex;align-items:center;gap:5px}

/* ── WALLET GRID ── VIBRANT ── */
.wallet-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin-bottom:10px}
.wcard{
    background:linear-gradient(135deg,rgba(var(--Pr),.38),rgba(var(--Pr),.25));
    border:1px solid var(--bdr);
    border-radius:12px;
    padding:12px;
    position:relative;
    overflow:hidden;
    transition:border-color .2s,background .25s,transform .2s,box-shadow .2s;
}
.wcard:hover{
    border-color:rgba(var(--Pr),.45);
    transform:translateY(-1px);
    box-shadow:0 4px 16px rgba(0,0,0,.38);
}
[data-theme="light"] .wcard:hover{
    box-shadow:0 4px 16px rgba(var(--Pr),.25);
}
.wcard::before{content:'';position:absolute;top:0;left:0;right:0;height:2.5px;border-radius:12px 12px 0 0}
.wc-1::before{background:linear-gradient(90deg,var(--P),var(--S))}
.wc-2::before{background:linear-gradient(90deg,var(--S),var(--OK))}
.wc-3::before{background:linear-gradient(90deg,var(--OK),#10b981)}
.wc-4::before{background:linear-gradient(90deg,var(--DN),#dc2626)}
.wc-5::before{background:linear-gradient(90deg,var(--WN),#f59e0b)}
.wc-6::before{background:linear-gradient(90deg,#06b6d4,#0891b2)}
.wc-7::before{background:linear-gradient(90deg,#10b981,#059669)}
.wc-8::before{background:linear-gradient(90deg,#a78bfa,#8b5cf6)}
.wc-9::before{background:linear-gradient(90deg,#f97316,#ea580c)}
.wc-10::before{background:linear-gradient(90deg,#38bdf8,#0ea5e9)}
.wc-11::before{background:linear-gradient(90deg,#34d399,#10b981)}
.wc-12::before{background:linear-gradient(90deg,#e879f9,#d946ef)}
.wc-13::before{background:linear-gradient(90deg,#84cc16,#65a30d)}
.wcard-lbl{font-size:9px;font-weight:700;letter-spacing:1.2px;text-transform:uppercase;color:rgba(255,255,255,.85);margin-bottom:7px}
.wcard-amt{font-size:17px;font-weight:800;color:#ffffff;letter-spacing:-.3px;font-variant-numeric:tabular-nums}
.wcard-type{font-size:9px;color:rgba(255,255,255,.65);margin-top:3px;font-weight:600}
.wbar-wrap{height:3px;background:var(--bg3);border-radius:2px;margin-top:9px;overflow:hidden}
.wbar{height:100%;border-radius:2px;transition:width .9s cubic-bezier(.22,1,.36,1)}

/* ── NETWORK ── DARK SOLID ── */
.net-card{
    background:linear-gradient(135deg,rgba(var(--Pr),.18),rgba(0,0,0,.38));
    border:1px solid var(--bdr);
    border-radius:14px;
    padding:14px;
    margin-bottom:10px;
    transition:background .25s,border-color .25s,transform .2s;
}
.net-card:hover{transform:translateY(-1px)}
.net-stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin-bottom:14px}
.nstat{
    background:rgba(var(--Pr),.35);
    border-radius:10px;
    padding:10px;
    text-align:center;
    transition:background .25s,transform .2s;
    border:1px solid rgba(var(--Pr),.25);
}
.nstat:hover{transform:translateY(-1px);background:rgba(var(--Pr),.32)}
[data-theme="light"] .nstat:hover{
    background:rgba(var(--Pr),.42);
}
.nstat-num{font-size:20px;font-weight:800;color:#ffffff;letter-spacing:-.4px}
.nstat-lbl{font-size:9px;color:rgba(255,255,255,.75);font-weight:600;text-transform:uppercase;letter-spacing:1px;margin-top:2px}

/* ── Network Stat Colors: Blue (Invited), Green (Active), Red (Pending) ── */
.nstat-blue{
    background:linear-gradient(135deg,rgba(59,130,246,.68),rgba(37,99,235,.52))!important;
    border:1px solid rgba(59,130,246,.75)!important;
}
.nstat-blue:hover{
    transform:translateY(-1px);
    background:linear-gradient(135deg,rgba(59,130,246,.75),rgba(37,99,235,.60))!important;
    box-shadow:0 4px 16px rgba(59,130,246,.35);
}
.nstat-blue .nstat-num{color:#ffffff!important}
.nstat-blue .nstat-lbl{color:rgba(255,255,255,.90)!important}

.nstat-green{
    background:linear-gradient(135deg,rgba(34,197,94,.68),rgba(22,163,74,.52))!important;
    border:1px solid rgba(34,197,94,.75)!important;
}
.nstat-green:hover{
    transform:translateY(-1px);
    background:linear-gradient(135deg,rgba(34,197,94,.75),rgba(22,163,74,.60))!important;
    box-shadow:0 4px 16px rgba(34,197,94,.35);
}
.nstat-green .nstat-num{color:#ffffff!important}
.nstat-green .nstat-lbl{color:rgba(255,255,255,.90)!important}

.nstat-red{
    background:linear-gradient(135deg,rgba(239,68,68,.68),rgba(220,38,38,.52))!important;
    border:1px solid rgba(239,68,68,.75)!important;
}
.nstat-red:hover{
    transform:translateY(-1px);
    background:linear-gradient(135deg,rgba(239,68,68,.75),rgba(220,38,38,.60))!important;
    box-shadow:0 4px 16px rgba(239,68,68,.35);
}
.nstat-red .nstat-num{color:#ffffff!important}
.nstat-red .nstat-lbl{color:rgba(255,255,255,.90)!important}

/* Light mode - same vibrant colors */
[data-theme="light"] .nstat-blue{
    background:linear-gradient(135deg,rgba(59,130,246,.68),rgba(37,99,235,.52))!important;
    border:1px solid rgba(59,130,246,.75)!important;
}
[data-theme="light"] .nstat-green{
    background:linear-gradient(135deg,rgba(34,197,94,.68),rgba(22,163,74,.52))!important;
    border:1px solid rgba(34,197,94,.75)!important;
}
[data-theme="light"] .nstat-red{
    background:linear-gradient(135deg,rgba(239,68,68,.68),rgba(220,38,38,.52))!important;
    border:1px solid rgba(239,68,68,.75)!important;
}

.bar-rows{display:flex;flex-direction:column;gap:8px}
.brow{display:flex;align-items:center;gap:8px}
.brow-lbl{font-size:10px;color:rgba(255,255,255,.75);width:70px;flex-shrink:0}
.brow-track{flex:1;height:5px;background:rgba(var(--Pr),.32);border-radius:3px;overflow:hidden;border:1px solid rgba(var(--Pr),.22)}
[data-theme="light"] .brow-track{
    background:rgba(var(--Pr),.30);
    border-color:rgba(var(--Pr),.40);
}
.brow-fill{height:100%;border-radius:3px;transition:width 1s ease}
.brow-val{font-size:10px;font-weight:700;color:#ffffff;width:32px;text-align:right;flex-shrink:0}

/* ── GREETING CONTAINER ── */
.greeting-container{
    display:flex;
    align-items:center;
    gap:12px;
    padding:16px 14px;
    border-radius:14px;
    margin-bottom:12px;
    position:relative;
    overflow:hidden;
    transition:transform .2s,box-shadow .2s;
    animation:fadeUp .4s ease both;
    animation-delay:.02s;
}
.greeting-container:hover{
    transform:translateY(-1px);
    box-shadow:0 6px 24px rgba(0,0,0,.38);
}
[data-theme="light"] .greeting-container:hover{
    box-shadow:0 6px 24px rgba(0,0,0,.12);
}

/* Time-based gradient backgrounds - CONCENTRATED */
.greeting-container.morning{
    background:linear-gradient(135deg,rgba(251,191,36,.45),rgba(251,146,60,.32),rgba(0,0,0,.20));
    border:1.5px solid rgba(251,191,36,.55);
}
[data-theme="light"] .greeting-container.morning{
    background:linear-gradient(135deg,rgba(251,191,36,.35),rgba(251,146,60,.22));
    border-color:rgba(251,191,36,.48);
}

.greeting-container.afternoon{
    background:linear-gradient(135deg,rgba(59,130,246,.45),rgba(37,99,235,.32),rgba(0,0,0,.20));
    border:1.5px solid rgba(59,130,246,.55);
}
[data-theme="light"] .greeting-container.afternoon{
    background:linear-gradient(135deg,rgba(59,130,246,.35),rgba(37,99,235,.22));
    border-color:rgba(59,130,246,.48);
}

.greeting-container.evening{
    background:linear-gradient(135deg,rgba(168,85,247,.45),rgba(126,34,206,.32),rgba(0,0,0,.20));
    border:1.5px solid rgba(168,85,247,.55);
}
[data-theme="light"] .greeting-container.evening{
    background:linear-gradient(135deg,rgba(168,85,247,.35),rgba(126,34,206,.22));
    border-color:rgba(168,85,247,.48);
}

.greeting-container.night{
    background:linear-gradient(135deg,rgba(79,70,229,.45),rgba(99,102,241,.32),rgba(0,0,0,.20));
    border:1.5px solid rgba(79,70,229,.55);
}
[data-theme="light"] .greeting-container.night{
    background:linear-gradient(135deg,rgba(79,70,229,.35),rgba(99,102,241,.22));
    border-color:rgba(79,70,229,.48);
}

.greeting-icon{
    width:48px;
    height:48px;
    flex-shrink:0;
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:26px;
    border-radius:12px;
    background:rgba(255,255,255,.10);
    backdrop-filter:blur(10px);
    -webkit-backdrop-filter:blur(10px);
    animation:iconFloat 3s ease-in-out infinite;
}
[data-theme="light"] .greeting-icon{
    background:rgba(0,0,0,.05);
}
@keyframes iconFloat{
    0%,100%{transform:translateY(0)}
    50%{transform:translateY(-4px)}
}

.greeting-content{
    flex:1;
    min-width:0;
}

.greeting-text{
    font-size:16px;
    font-weight:800;
    color:#ffffff;
    letter-spacing:-.3px;
    margin-bottom:3px;
    line-height:1.2;
}
    color:#ffffff;
}

.greeting-name{
    background:linear-gradient(135deg,var(--P),var(--S));
    -webkit-background-clip:text;
    -webkit-text-fill-color:transparent;
    background-clip:text;
    font-weight:900;
}

.greeting-sub{
    font-size:11px;
    color:rgba(255,255,255,.75);
    line-height:1.4;
}
    color:rgba(255,255,255,.75);
}

.greeting-time{
    text-align:right;
    flex-shrink:0;
    min-width:80px;
}

.time-display{
    font-size:18px;
    font-weight:900;
    color:#ffffff;
    letter-spacing:-.5px;
    line-height:1;
    margin-bottom:3px;
    font-variant-numeric:tabular-nums;
}
    color:#ffffff;
}

.date-display{
    font-size:9px;
    font-weight:700;
    color:rgba(255,255,255,.75);
    text-transform:uppercase;
    letter-spacing:.5px;
}
    color:rgba(255,255,255,.75);
}

/* Responsive greeting */
@media(max-width:480px){
    .greeting-container{padding:13px 12px;gap:10px}
    .greeting-icon{width:42px;height:42px;font-size:22px}
    .greeting-text{font-size:14px}
    .greeting-sub{font-size:10px}
    .time-display{font-size:16px}
    .greeting-time{min-width:70px}
}
@media(max-width:360px){
    .greeting-time{display:none}
}
.act-bar{
    background:linear-gradient(135deg,rgba(251,191,36,.20),rgba(251,191,36,.10));
    border:1px solid rgba(251,191,36,.35);
    border-radius:12px;
    padding:11px 13px;
    display:flex;
    align-items:center;
    gap:10px;
    margin-bottom:10px;
    flex-wrap:wrap;
}
[data-theme="light"] .act-bar{
    background:var(--WN-bg);
    border-color:rgba(255,184,0,.25);
}
.act-ico{font-size:20px;flex-shrink:0}
.act-t{font-size:12px;font-weight:700;color:var(--WN)}
.act-s{font-size:10px;color:rgba(255,255,255,.75);margin-top:1px}
.act-btn{margin-left:auto;background:var(--WN);color:#07060f;border:none;border-radius:8px;padding:7px 13px;font-size:11px;font-weight:800;cursor:pointer;white-space:nowrap;font-family:inherit;text-decoration:none;flex-shrink:0}

.congrats{
    background:linear-gradient(135deg,rgba(var(--Pr),.35),rgba(var(--Pr),.10));
    border:1px solid rgba(var(--Pr),.40);
    border-radius:12px;
    padding:11px 13px;
    display:flex;
    align-items:center;
    gap:10px;
    margin-bottom:10px;
    flex-wrap:wrap;
}
[data-theme="light"] .congrats{
    background:var(--P-bg);
    border-color:rgba(var(--Pr),.28);
}
.cg-t{font-size:13px;font-weight:800;color:var(--P)}
.cg-s{font-size:11px;color:rgba(255,255,255,.75);margin-top:2px}
.cg-btn{margin-left:auto;background:var(--P);color:#fff;border:none;border-radius:7px;padding:6px 12px;font-size:11px;font-weight:800;cursor:pointer;text-decoration:none;font-family:inherit;flex-shrink:0}

.notif-bar{
    background:linear-gradient(135deg,rgba(var(--Pr),.25),rgba(var(--Pr),.18));
    border-left:3px solid var(--P);
    border-radius:0 10px 10px 0;
    padding:9px 12px;
    display:flex;
    align-items:flex-start;
    gap:8px;
    margin-bottom:10px;
    font-size:11px;
    color:rgba(255,255,255,.75);
    line-height:1.6;
    border-top:1px solid rgba(var(--Pr),.35);
    border-right:1px solid rgba(var(--Pr),.35);
    border-bottom:1px solid rgba(var(--Pr),.35);
}
[data-theme="light"] .notif-bar{
    background:var(--P-bg);
    border-top-color:rgba(var(--Pr),.22);
    border-right-color:rgba(var(--Pr),.22);
    border-bottom-color:rgba(var(--Pr),.22);
}
.notif-bar i{color:var(--P);flex-shrink:0;font-size:11px;margin-top:1px}

/* ── INVITE ── DARK SOLID ── */
.invite-card{
    background:linear-gradient(135deg,rgba(var(--Pr),.18),rgba(0,0,0,.38));
    border:1px solid var(--bdr);
    border-radius:14px;
    padding:14px;
    margin-bottom:10px;
    transition:background .25s,border-color .25s,transform .2s;
}
.invite-card:hover{transform:translateY(-1px)}
.invite-stats{display:flex;gap:16px;margin-bottom:12px;flex-wrap:wrap}
.istat-n{font-size:18px;font-weight:800;color:#ffffff}
[data-theme="light"] .istat-n{color:#ffffff}
.istat-l{font-size:9px;color:rgba(255,255,255,.75);font-weight:700;text-transform:uppercase;letter-spacing:1px;margin-top:1px}
[data-theme="light"] .istat-l{color:rgba(255,255,255,.75)}
.link-strip{
    display:flex;
    height:40px;
    background:rgba(var(--Pr),.35);
    border:1px solid rgba(var(--Pr),.25);
    border-radius:8px;
    overflow:hidden;
    margin-bottom:10px;
    transition:background .25s;
}
[data-theme="light"] .link-strip{
    background:var(--bg3);
    border-color:var(--bdr);
}
.link-pfx{
    padding:0 10px;
    background:rgba(var(--Pr),.35);
    border-right:1px solid rgba(var(--Pr),.25);
    font-size:9px;
    font-weight:700;
    color:var(--P);
    display:flex;
    align-items:center;
    letter-spacing:.5px;
    white-space:nowrap;
    flex-shrink:0;
}
[data-theme="light"] .link-pfx{
    background:var(--P-bg);
    border-right-color:rgba(var(--Pr),.18);
}
.link-url{flex:1;padding:0 10px;font-size:10px;font-family:monospace;color:rgba(255,255,255,.75);display:flex;align-items:center;overflow:hidden}
.link-url span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.copy-btn{
    width:100%;
    height:42px;
    background:var(--P);
    color:#fff;
    border:none;
    border-radius:9px;
    font-size:14px;
    font-weight:800;
    cursor:pointer;
    display:flex;
    align-items:center;
    justify-content:center;
    gap:7px;
    font-family:inherit;
    transition:all .2s;
    letter-spacing:.2px;
}
[data-theme="light"] .copy-btn{color:#fff}
.copy-btn:hover{filter:brightness(1.1);transform:translateY(-1px);box-shadow:0 4px 16px rgba(var(--Pr),.35)}
.alt-toggle{background:none;border:none;width:100%;text-align:left;padding:9px 0;font-size:11px;font-weight:600;color:var(--P);cursor:pointer;font-family:inherit;display:flex;align-items:center;justify-content:space-between;border-top:1px solid var(--bdr);margin-top:4px}
.share-row{display:flex;align-items:center;gap:8px;margin-top:10px;flex-wrap:wrap}
.share-lbl{font-size:10px;color:rgba(255,255,255,.65);font-weight:600}
.sico-sm{width:32px;height:32px;display:flex;align-items:center;justify-content:center;font-size:13px;color:#fff;text-decoration:none;transition:transform .15s;border:none;cursor:pointer}
.sico-sm:hover{transform:scale(1.1)}
.s-wa{border-radius:12px 4px 12px 4px;background:#25D366}
.s-tw{border-radius:50%;background:#1DA1F2}
.s-fb{border-radius:10px;background:#1877F2}
.s-em{border-radius:4px 14px 4px 14px;background:#EA4335}

/* ── USER DETAILS ── DARK SOLID ── */
.ud-card{
    background:linear-gradient(135deg,rgba(var(--Pr),.18),rgba(0,0,0,.38));
    border:1px solid var(--bdr);
    border-radius:14px;
    overflow:hidden;
    transition:background .25s,border-color .25s,transform .2s;
}
.ud-card:hover{transform:translateY(-1px)}
.ud-toggle{width:100%;background:none;border:none;padding:13px 14px;display:flex;align-items:center;justify-content:space-between;font-size:13px;font-weight:700;color:#ffffff;cursor:pointer;font-family:inherit}
.ud-body{padding:0 14px 12px;display:none}
.ud-body.open{display:block}
.ud-row{display:flex;justify-content:space-between;align-items:center;padding:7px 0;border-top:1px solid var(--bdr);font-size:11px;flex-wrap:wrap;gap:4px}
.ud-k{color:rgba(255,255,255,.75);font-weight:600;font-size:10px;letter-spacing:.5px;text-transform:uppercase}
.ud-v{font-weight:700;color:#ffffff;font-size:11px}

/* ── TOAST ── */
.db-toast{position:fixed;top:-80px;left:50%;transform:translateX(-50%);min-width:260px;max-width:calc(100vw - 32px);background:var(--card2);border:1px solid rgba(var(--Pr),.30);border-left:3px solid var(--P);border-radius:10px;padding:10px 36px 10px 12px;z-index:9999;display:flex;align-items:center;gap:9px;transition:top .4s cubic-bezier(.34,1.56,.64,1);box-shadow:0 8px 32px rgba(0,0,0,.3)}
.db-toast.show{top:calc(var(--hh) + 10px)}
.t-dot{width:20px;height:20px;border-radius:50%;background:var(--P);display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:800;color:#fff;flex-shrink:0}
[data-theme="light"] .t-dot{color:#fff}
.t-txt{font-size:12px;font-weight:600;color:#ffffff;flex:1}
.t-cls{position:absolute;right:9px;top:50%;transform:translateY(-50%);background:none;border:none;font-size:17px;color:rgba(255,255,255,.65);cursor:pointer}

/* ── ANIMATIONS ── */
@keyframes fadeUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:none}}
.hero-grid,.chart-card,.wallet-grid,.net-card,.invite-card,.ud-card{animation:fadeUp .4s ease both}
.chart-card{animation-delay:.05s}.wallet-grid{animation-delay:.1s}.net-card{animation-delay:.14s}
.invite-card{animation-delay:.18s}.ud-card{animation-delay:.22s}

/* ── RESPONSIVE ── */
@media(max-width:400px){.db-body{padding:10px 10px 80px}.hero-grid{gap:7px}.wallet-grid{gap:7px}.hstat-val{font-size:19px}.hstat-val.sm{font-size:16px}}
@media(max-width:320px){.wallet-grid{grid-template-columns:1fr}.hero-grid{grid-template-columns:1fr}.hero-grid .full{grid-column:1}.net-stats{grid-template-columns:repeat(3,1fr)}}
@media(min-width:560px){.wallet-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.hero-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.hero-grid .full{grid-column:1/-1}.db-body{padding:16px 16px 90px}}
@media(min-width:900px){.wallet-grid{grid-template-columns:repeat(4,minmax(0,1fr))}.hero-grid{grid-template-columns:repeat(4,minmax(0,1fr))}.db-body{padding:18px 20px 90px;max-width:1200px}}
@media(min-width:1200px){.db-body{max-width:1100px}.hero-grid{grid-template-columns:repeat(4,minmax(0,1fr))}}

/* ── LIGHT MODE TEXT COLOR OVERRIDES (PURPLE THEME USES WHITE TEXT) ── */
/* Light mode is now purple theme, so it uses same white text as dark mode */
/* Only keep special overrides for specific elements */

[data-theme="light"] .chip{
    background:rgba(var(--Pr),.30);
    color:#ffffff;
}

[data-theme="light"] .chip.on{
    background:rgba(var(--Pr),.50);
    color:#ffffff;
}

[data-theme="light"] .wcard:hover{
    box-shadow:0 4px 16px rgba(var(--Pr),.25);
}

[data-theme="light"] .nstat:hover{
    background:rgba(var(--Pr),.42);
}

[data-theme="light"] .greeting-icon{
    background:rgba(255,255,255,.15);
}

[data-theme="light"] .hstat-ico.purple{color:#a855f7}

[data-theme="light"] .hstat-val.purple-v{
    background:linear-gradient(135deg,#a855f7,#fbbf24);
    -webkit-background-clip:text;
    -webkit-text-fill-color:transparent;
    background-clip:text;
}

[data-theme="light"] .preloader-text{color:#ffffff!important}

[data-theme="light"] .preloader-subtext{color:rgba(255,255,255,.85)!important}
</style>

<div class="pg">

<!-- ══════════════════════════════════════════════════════════════════════
     PRELOADER - Full Page with Circular Spinner & Site Logo
══════════════════════════════════════════════════════════════════════ -->
<div id="pagePreloader">
    <div class="preloader-content">
        <div class="spinner-circle">
            <div class="spinner-ring"></div>
            <div class="spinner-ring"></div>
            <div class="spinner-ring"></div>
            <div class="spinner-logo">
                <?php if (!empty($logoPath)): ?>
                    <img src="<?= htmlspecialchars($logoPath) ?>" alt="<?= htmlspecialchars($siteName) ?>" class="logo-img" />
                <?php else: ?>
                    <span class="logo-text"><?= htmlspecialchars(strtoupper(substr($siteName, 0, 2))) ?></span>
                <?php endif; ?>
            </div>
        </div>
        <div class="preloader-text">
            Loading Dashboard
            <span class="loading-dots">
                <span></span>
                <span></span>
                <span></span>
            </span>
        </div>
        <div class="preloader-subtext">Please wait</div>
    </div>
</div>

<div class="db-body">

<?php if ($userData['status'] === 'inactive'): ?>
<div class="act-bar">
    <div class="act-ico">&#128275;</div>
    <div>
        <div class="act-t">Account not activated</div>
        <div class="act-s">One payment unlocks all earnings.</div>
    </div>
    <a href="activate.php" class="act-btn">Activate <?= htmlspecialchars($cs) ?> <?= number_format($fee, 0) ?></a>
</div>
<?php endif; ?>

<?php if ($todayNewMembers > 0): ?>
<div class="congrats">
    <div style="font-size:22px;flex-shrink:0">&#127919;</div>
    <div>
        <div class="cg-t">+<?= $todayNewMembers ?> New Member<?= $todayNewMembers > 1 ? 's' : '' ?> Today</div>
        <div class="cg-s">Keep sharing your invite link</div>
    </div>
    <a href="downlines.php" class="cg-btn">View</a>
</div>
<?php endif; ?>

<?php if ($notifOn): ?>
<div class="notif-bar">
    <i class="fa-solid fa-satellite-dish"></i>
    <span><?= htmlspecialchars($notifTxt) ?></span>
</div>
<?php endif; ?>

<!-- ── GREETING CONTAINER ── -->
<?php
// Get current hour to determine greeting
$currentHour = intval(date('G')); // 24-hour format
if ($currentHour >= 5 && $currentHour < 12) {
    $greeting = 'Good Morning';
    $greetIcon = '🌅';
    $greetClass = 'morning';
} elseif ($currentHour >= 12 && $currentHour < 17) {
    $greeting = 'Good Afternoon';
    $greetIcon = '☀️';
    $greetClass = 'afternoon';
} elseif ($currentHour >= 17 && $currentHour < 21) {
    $greeting = 'Good Evening';
    $greetIcon = '🌆';
    $greetClass = 'evening';
} else {
    $greeting = 'Good Night';
    $greetIcon = '🌙';
    $greetClass = 'night';
}
$firstName = explode(' ', $userData['full_name'] ?? $username)[0];
?>
<div class="greeting-container <?= $greetClass ?>">
    <div class="greeting-icon"><?= $greetIcon ?></div>
    <div class="greeting-content">
        <div class="greeting-text"><?= $greeting ?>, <span class="greeting-name"><?= htmlspecialchars($firstName) ?></span></div>
        <div class="greeting-sub">Welcome back! Ready to earn today?</div>
    </div>
    <div class="greeting-time">
        <div class="time-display" id="currentTime"><?= date('h:i A') ?></div>
        <div class="date-display"><?= date('M j, Y') ?></div>
    </div>
</div>

<!-- ── HERO STATS ── -->
<div class="hero-grid">

    <div class="hstat prime full">
        <div class="hstat-top">
            <span class="hstat-lbl">Total Portfolio</span>
            <span class="hstat-ico c"><i class="fa-solid fa-chart-line" style="font-size:9px"></i></span>
        </div>
        <div class="hstat-val" id="heroNum" data-local="<?= $totalWallets ?>"><?= htmlspecialchars($cs) ?> <?= number_format($totalWallets, 2) ?></div>
        <div class="hstat-sub">All wallets combined <span class="badge-up">+<?= $netAct ?> active</span></div>
        <div class="cur-row">
            <button class="cur-btn on" id="btnLOC" onclick="setCur('loc')"><?= htmlspecialchars($cs) ?></button>
            <button class="cur-btn" id="btnUSD" onclick="setCur('usd')">$ USD</button>
        </div>
    </div>

    <!-- WITHDRAWN — RED -->
    <div class="hstat red-c">
        <div class="hstat-top"><span class="hstat-lbl">Withdrawn</span><span class="hstat-ico red"><i class="fa-solid fa-paper-plane" style="font-size:9px"></i></span></div>
        <div class="hstat-val sm red-v money-val" data-local="<?= $withdrawn ?>"><?= htmlspecialchars($cs) ?> <?= number_format($withdrawn, 2) ?></div>
        <div class="hstat-sub">Lifetime payouts</div>
    </div>

    <!-- TODAY — BLUE -->
    <div class="hstat blue-c">
        <div class="hstat-top"><span class="hstat-lbl">Today</span><span class="hstat-ico blue"><i class="fa-solid fa-fire-flame-curved" style="font-size:9px"></i></span></div>
        <div class="hstat-val sm blue-v money-val" data-local="<?= $todayRaw ?>"><?= htmlspecialchars($cs) ?> <?= number_format($todayRaw, 2) ?></div>
        <div class="hstat-sub">Resets <span id="midnight-cd" style="color:#3b82f6;font-weight:700">—</span></div>
    </div>

    <!-- BALANCE — GREEN -->
    <div class="hstat green-c">
        <div class="hstat-top"><span class="hstat-lbl">Balance</span><span class="hstat-ico green"><i class="fa-solid fa-sack-dollar" style="font-size:9px"></i></span></div>
        <div class="hstat-val sm green-v money-val" data-local="<?= $wMain ?>"><?= htmlspecialchars($cs) ?> <?= number_format($wMain, 2) ?></div>
        <div class="hstat-sub">Available now</div>
    </div>

    <!-- TOURNAMENT RANK — PURPLE/GOLD GRADIENT -->
    <div class="hstat purple-c">
        <div class="hstat-top"><span class="hstat-lbl">Tournament</span><span class="hstat-ico purple"><i class="fa-solid fa-trophy" style="font-size:9px"></i></span></div>
        <div class="hstat-val sm purple-v"><?= $tournamentRank > 0 ? '#' . $tournamentRank : 'Unranked' ?></div>
        <div class="hstat-sub">
            <?php if($tournamentRank > 0 && $tournamentRank <= 3): ?>
                Prize position <span class="badge-prize">🏆 Top 3</span>
            <?php elseif($tournamentRank > 0): ?>
                <?= $tournamentActive ?> active this week
            <?php else: ?>
                Join this week
            <?php endif; ?>
        </div>
    </div>

</div>



<!-- ── NETWORK ANALYTICS ── -->
<div class="net-card">
    <div class="card-hdr">
        <div>
            <div class="card-title">Team Network Analytics</div>
            <div class="card-sub">Referral performance metrics</div>
        </div>
        <?php if ($todayNewMembers > 0): ?>
        <span style="font-size:10px;color:var(--P);background:var(--P-bg);padding:3px 9px;border-radius:4px;border:1px solid rgba(var(--Pr),.22);font-weight:700">+<?= $todayNewMembers ?> today</span>
        <?php endif; ?>
    </div>
    <div class="net-stats">
        <div class="nstat nstat-blue">
            <div class="nstat-num" style="color:#3b82f6"><?= $netTot ?></div>
            <div class="nstat-lbl">Invited</div>
        </div>
        <div class="nstat nstat-green">
            <div class="nstat-num" style="color:#22c55e"><?= $netAct ?></div>
            <div class="nstat-lbl">Active</div>
        </div>
        <div class="nstat nstat-red">
            <div class="nstat-num" style="color:#ef4444"><?= $netPending ?></div>
            <div class="nstat-lbl">Pending</div>
        </div>
    </div>
    <div class="bar-rows">
        <div class="brow"><span class="brow-lbl">Activation</span><div class="brow-track"><div class="brow-fill" style="width:0%;background:var(--P)" data-w="<?= $activationRate ?>"></div></div><span class="brow-val"><?= $activationRate ?>%</span></div>
        <div class="brow"><span class="brow-lbl">This week</span><div class="brow-track"><div class="brow-fill" style="width:0%;background:var(--OK)" data-w="<?= min($weeklyRefs*10,100) ?>"></div></div><span class="brow-val"><?= $weeklyRefs ?></span></div>
        <div class="brow"><span class="brow-lbl">Earning</span><div class="brow-track"><div class="brow-fill" style="width:0%;background:var(--S)" data-w="<?= $earningRate ?>"></div></div><span class="brow-val"><?= $netAct ?></span></div>
        <div class="brow"><span class="brow-lbl">Products</span><div class="brow-track"><div class="brow-fill" style="width:0%;background:var(--WN)" data-w="<?= min($totOwned*20,100) ?>"></div></div><span class="brow-val"><?= $totOwned ?></span></div>
    </div>
</div>

<!-- ── AFFILIATE LINK ── -->
<div class="sec-lbl">Affiliate Link</div>
<div class="invite-card">
    <div class="card-hdr">
        <div><div class="card-title">Your Invite Link</div><div class="card-sub">Earn per activation</div></div>
        <span style="font-size:9px;font-weight:700;color:var(--WN);background:var(--WN-bg);padding:3px 9px;border-radius:4px;border:1px solid rgba(255,184,0,.22)"><?= htmlspecialchars($cs) ?>/join</span>
    </div>
    <div class="invite-stats">
        <div><div class="istat-n" style="color:var(--P)"><?= $netTot ?></div><div class="istat-l">Invited</div></div>
        <div><div class="istat-n" style="color:var(--OK)"><?= $netAct ?></div><div class="istat-l">Active</div></div>
        <div><div class="istat-n money-val" style="color:var(--WN)" data-local="<?= $wRef ?>"><?= htmlspecialchars($cs) ?> <?= number_format($wRef, 0) ?></div><div class="istat-l">Earned</div></div>
    </div>
    <div class="link-strip">
        <div class="link-pfx">&#9670; INVITE</div>
        <div class="link-url"><span id="affLink"><?= SITE_URL ?>/register.php?ref=<?= htmlspecialchars($userData['referral_code']) ?></span></div>
    </div>
    <button class="copy-btn" onclick="copyLink()"><i class="fa-solid fa-link"></i> Copy Invite Link</button>
    <button class="alt-toggle" onclick="var s=this.nextElementSibling;s.style.display=s.style.display==='block'?'none':'block';this.querySelector('i').className=s.style.display==='block'?'fa-solid fa-angle-up':'fa-solid fa-angle-down'">
        Alternative link <i class="fa-solid fa-angle-down" style="font-size:10px"></i>
    </button>
    <div style="display:none;padding:9px 0">
        <div class="link-strip">
            <div class="link-pfx">&#9670; ALT</div>
            <div class="link-url"><span><?= SITE_URL ?>/join/<?= htmlspecialchars($userData['referral_code']) ?></span></div>
        </div>
    </div>
    <div class="share-row">
        <span class="share-lbl">Share:</span>
        <a href="https://wa.me/?text=<?= urlencode('Join me on '.$siteName.'! '.SITE_URL.'/register.php?ref='.$userData['referral_code']) ?>" target="_blank" class="sico-sm s-wa"><i class="fa-brands fa-whatsapp"></i></a>
        <a href="https://twitter.com/intent/tweet?url=<?= urlencode(SITE_URL.'/register.php?ref='.$userData['referral_code']) ?>" target="_blank" class="sico-sm s-tw"><i class="fa-brands fa-x-twitter"></i></a>
        <a href="https://www.facebook.com/sharer/sharer.php?u=<?= urlencode(SITE_URL.'/register.php?ref='.$userData['referral_code']) ?>" target="_blank" class="sico-sm s-fb"><i class="fa-brands fa-facebook-f"></i></a>
        <a href="mailto:?subject=<?= urlencode('Join '.$siteName) ?>&body=<?= urlencode('Join me: '.SITE_URL.'/register.php?ref='.$userData['referral_code']) ?>" class="sico-sm s-em"><i class="fa-solid fa-at"></i></a>
    </div>
</div>

<!-- ── ACCOUNT DETAILS ── -->
<div class="ud-card" style="margin-top:10px">
    <button class="ud-toggle" onclick="var b=this.nextElementSibling;b.classList.toggle('open');this.querySelector('span').textContent=b.classList.contains('open')?'▲':'▼'">
        Account Details <span style="font-size:10px;color:rgba(255,255,255,.65)">▼</span>
    </button>
    <div class="ud-body">
        <div class="ud-row"><span class="ud-k">Username</span><span class="ud-v"><?= htmlspecialchars($username) ?></span></div>
        <div class="ud-row"><span class="ud-k">Status</span><span class="ud-v" style="color:<?= $userData['status']==='active'?'var(--OK)':'var(--DN)' ?>"><?= ucfirst($userData['status']) ?> <?= $userData['status']==='active'?'✓':'' ?></span></div>
        <div class="ud-row"><span class="ud-k">Country</span><span class="ud-v"><?= htmlspecialchars($userData['country']) ?></span></div>
        <div class="ud-row"><span class="ud-k">Currency</span><span class="ud-v"><?= htmlspecialchars($cs) ?> (<?= htmlspecialchars($cc) ?>)</span></div>
        <div class="ud-row"><span class="ud-k">Ref Code</span><span class="ud-v" style="font-family:monospace;color:var(--P);font-size:11px"><?= htmlspecialchars($userData['referral_code']) ?></span></div>
        <div class="ud-row"><span class="ud-k">Verified</span><span class="ud-v"><?= $isVerified ? 'Yes ✓' : 'No' ?></span></div>
        <div class="ud-row"><span class="ud-k">Products</span><span class="ud-v"><?= $totOwned ?> owned</span></div>
        <div class="ud-row"><span class="ud-k">Commissions</span><span class="ud-v money-val" data-local="<?= $comEarned ?>"><?= htmlspecialchars($cs) ?> <?= number_format($comEarned, 2) ?></span></div>
        <?php if($tournamentRank > 0): ?>
        <div class="ud-row"><span class="ud-k">Tournament Rank</span><span class="ud-v" style="color:#a855f7">#{<?= $tournamentRank ?>} (<?= $tournamentActive ?> active)</span></div>
        <?php endif; ?>
    </div>
</div>

</div><!-- /db-body -->
</div><!-- /pg -->

<!-- TOAST -->
<div class="db-toast" id="db-toast">
    <div class="t-dot" id="t-dot">✓</div>
    <span class="t-txt" id="t-txt"></span>
    <button class="t-cls" onclick="document.getElementById('db-toast').classList.remove('show')">×</button>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.js"></script>
<script>
(function(){

// ── Preloader - Hide after page loads ────────────────────────────────────
window.addEventListener('load', function() {
    setTimeout(function() {
        var preloader = document.getElementById('pagePreloader');
        if (preloader) {
            preloader.classList.add('hidden');
            setTimeout(function() {
                preloader.style.display = 'none';
            }, 600); // Match transition duration
        }
    }, 800); // Show for at least 800ms for smooth experience
});

// ── Currency values from PHP ──────────────────────────────────────────────
var LOCAL_SYM  = '<?= addslashes($cs) ?>';
var USD_RATE   = <?= $usdRate ?>;
var curMode = 'loc';

// ── Admin theme colors ─────────────────────────────────────────────────────
var ADMIN_P  = '<?= addslashes($adminPrimary)   ?>';
var ADMIN_S  = '<?= addslashes($adminSecondary) ?>';
var ADMIN_OK = '<?= addslashes($adminSuccess)   ?>';
var ADMIN_WN = '<?= addslashes($adminWarning)   ?>';
var ADMIN_DN = '<?= addslashes($adminDanger)    ?>';

function hexRgba(hex, a) {
    hex = hex.replace('#','');
    if (hex.length === 3) hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
    var r=parseInt(hex.slice(0,2),16), g=parseInt(hex.slice(2,4),16), b=parseInt(hex.slice(4,6),16);
    return 'rgba('+r+','+g+','+b+','+a+')';
}
function isDark() { return document.documentElement.getAttribute('data-theme') === 'dark'; }
function getChartColors() {
    var dark = isDark();
    return {
        gridColor:    dark ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.06)',
        tickColor:    dark ? 'rgba(255,255,255,0.35)' : 'rgba(0,0,0,0.4)',
        tooltipBg:    dark ? '#141228' : '#ffffff',
        tooltipBorder:dark ? hexRgba(ADMIN_P,.25) : 'rgba(0,0,0,0.1)',
        tooltipTitle: dark ? '#fff' : '#111',
        tooltipBody:  dark ? 'rgba(255,255,255,.7)' : 'rgba(0,0,0,.65)',
    };
}

// ── Count-up animation ────────────────────────────────────────────────────
var hn = document.getElementById('heroNum');
if (hn) {
    var tgt = <?= (float)$totalWallets ?>, t0 = null;
    (function cu(ts) {
        if (!t0) t0 = ts;
        var p = Math.min((ts-t0)/1500, 1), e = p===1 ? 1 : 1-Math.pow(2,-10*p);
        hn.textContent = LOCAL_SYM+' '+(tgt*e).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g,',');
        if (p < 1) requestAnimationFrame(cu);
    })(performance.now());
}

// ── Currency toggle ───────────────────────────────────────────────────────
function fmt(localVal, mode) {
    var n = parseFloat(localVal) || 0;
    if (mode === 'usd') {
        return '$ ' + (n / USD_RATE).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g,',');
    }
    return LOCAL_SYM + ' ' + n.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g,',');
}

function refreshMoney(mode) {
    document.querySelectorAll('.money-val').forEach(function(el) {
        el.textContent = fmt(el.getAttribute('data-local'), mode);
    });
    var h2 = document.getElementById('heroNum');
    if (h2) h2.textContent = fmt(h2.getAttribute('data-local'), mode);
}

window.setCur = function(m) {
    curMode = m;
    document.getElementById('btnLOC').classList.toggle('on', m === 'loc');
    document.getElementById('btnUSD').classList.toggle('on', m === 'usd');
    refreshMoney(m);
};

// ── Midnight countdown ────────────────────────────────────────────────────
var cdEl = document.getElementById('midnight-cd');
function ms2mid() { var n=new Date(), nx=new Date(n.getFullYear(),n.getMonth(),n.getDate()+1); return nx-n; }
function fmtCD(ms) { var s=Math.floor(ms/1000),h=Math.floor(s/3600),m=Math.floor((s%3600)/60),sc=s%60; return h+'h '+m+'m '+sc+'s'; }
(function tick() {
    var ms = ms2mid();
    if (ms <= 500) { location.reload(); return; }
    if (cdEl) cdEl.textContent = fmtCD(ms);
    setTimeout(tick, 1000);
})();

// ── Live Clock Update ─────────────────────────────────────────────────────
var timeEl = document.getElementById('currentTime');
if (timeEl) {
    (function updateClock() {
        var now = new Date();
        var hours = now.getHours();
        var minutes = now.getMinutes();
        var ampm = hours >= 12 ? 'PM' : 'AM';
        hours = hours % 12;
        hours = hours ? hours : 12; // 0 = 12
        minutes = minutes < 10 ? '0' + minutes : minutes;
        timeEl.textContent = hours + ':' + minutes + ' ' + ampm;
        setTimeout(updateClock, 1000);
    })();
}

// ── Toast ─────────────────────────────────────────────────────────────────
var tmr = null;
function showToast(msg, type) {
    var t=document.getElementById('db-toast'), d=document.getElementById('t-dot'), x=document.getElementById('t-txt');
    clearTimeout(tmr); t.className='db-toast show';
    d.innerHTML = type==='error' ? '✗' : '✓';
    t.style.borderLeftColor = type==='error' ? ADMIN_DN : ADMIN_P;
    d.style.background      = type==='error' ? ADMIN_DN : ADMIN_P;
    x.textContent = msg;
    tmr = setTimeout(function(){ t.classList.remove('show'); }, 5000);
}

// ── Copy invite link ──────────────────────────────────────────────────────
window.copyLink = function() {
    var l = document.getElementById('affLink').textContent.trim();
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(l).then(function(){ showToast('Link copied!','success'); }).catch(fb);
    } else { fb(); }
    function fb() {
        var ta = document.createElement('textarea'); ta.value=l; ta.style.cssText='position:fixed;left:-9999px';
        document.body.appendChild(ta); ta.select();
        try { document.execCommand('copy'); showToast('Copied!','success'); }
        catch(e) { showToast('Copy failed','error'); }
        document.body.removeChild(ta);
    }
};

// ── Wallet progress bars ──────────────────────────────────────────────────
setTimeout(function() {
    var barColors = ['wc-1','wc-2','wc-3','wc-4','wc-5','wc-6','wc-7','wc-8','wc-9','wc-10','wc-11','wc-12','wc-13'];
    var colors    = [ADMIN_P,ADMIN_S,ADMIN_OK,ADMIN_DN,ADMIN_WN,'#06b6d4','#10b981','#a78bfa','#f97316','#38bdf8','#34d399','#e879f9','#84cc16'];
    barColors.forEach(function(cls,i) {
        var card = document.querySelector('.'+cls); if (!card) return;
        var bar  = card.querySelector('.wbar');     if (!bar)  return;
        bar.style.background = colors[i];
        bar.style.width = bar.getAttribute('data-pct') + '%';
    });
}, 300);

// ── Network bars ──────────────────────────────────────────────────────────
setTimeout(function() {
    document.querySelectorAll('.brow-fill').forEach(function(b){ b.style.width = b.getAttribute('data-w') + '%'; });
}, 400);

// ── 7-day chart data from PHP ─────────────────────────────────────────────
var realEarnings = <?= json_encode($dailyEarnings) ?>;
var realRefs     = <?= json_encode($dailyRefs) ?>;
var labels7 = (function() {
    var out=[], d=new Date();
    for (var i=6; i>=0; i--) { var x=new Date(d); x.setDate(d.getDate()-i); out.push(['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][x.getDay()]); }
    return out;
})();

var chartData = {
    '7d': { labels:labels7, earn:realEarnings, ref:realRefs },
    '30d':{ labels:['W1','W2','W3','W4'], earn:[0,0,0,0], ref:[0,0,0,0] },
    '90d':{ labels:['M1','M2','M3'], earn:[0,0,0], ref:[0,0,0] },
};

function buildChartOptions() {
    var c = getChartColors();
    return {
        responsive:true, maintainAspectRatio:false,
        plugins:{
            legend:{display:false},
            tooltip:{backgroundColor:c.tooltipBg,borderColor:c.tooltipBorder,borderWidth:1,titleColor:c.tooltipTitle,bodyColor:c.tooltipBody,padding:10,
                callbacks:{label:function(ctx){ return ' '+LOCAL_SYM+' '+ctx.parsed.y.toFixed(2); }}}
        },
        scales:{
            x:{ticks:{color:c.tickColor,font:{size:10}},grid:{color:c.gridColor},border:{color:'transparent'}},
            y:{ticks:{color:c.tickColor,font:{size:10},callback:function(v){ return LOCAL_SYM+' '+Math.round(v); }},grid:{color:c.gridColor},border:{color:'transparent'}}
        }
    };
}

window.addEventListener('storage', function(e){ if (e.key==='ev_theme') location.reload(); });

// ── Flash messages ────────────────────────────────────────────────────────
<?php if ($flash): ?>showToast(<?= json_encode($flash['message']) ?>, <?= json_encode($flash['type']) ?>);<?php endif; ?>
var p = new URLSearchParams(window.location.search);
if (p.get('activated')==='1'||p.get('activated')==='success') {
    history.replaceState({},'',location.pathname);
    showToast('Account activated! Welcome aboard.','success');
}

})();
</script>
<?php include 'footer.php'; ?>