<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'My Bonuses';
include 'side.php';
$conn = getConnection();

// ── Ensure week_key column exists (safe for MySQL 5.7+ and MariaDB) ─────────
function ensureWeekKeyColumn($conn, $table) {
    $db = $conn->query("SELECT DATABASE() as d")->fetch_assoc()['d'];
    $chk = $conn->prepare("SELECT COUNT(*) as c FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=? AND TABLE_NAME=? AND COLUMN_NAME='week_key'");
    $chk->bind_param("ss", $db, $table);
    $chk->execute();
    if ($chk->get_result()->fetch_assoc()['c'] == 0) {
        $conn->query("ALTER TABLE `$table` ADD COLUMN week_key VARCHAR(10) NOT NULL DEFAULT ''");
    }
}
ensureWeekKeyColumn($conn, 'user_bonus_claims');
ensureWeekKeyColumn($conn, 'bonus_awards');

// Also ensure unique key exists (ignore error if already there)
$conn->query("ALTER TABLE user_bonus_claims DROP INDEX IF EXISTS user_tier_week");
@$conn->query("ALTER TABLE user_bonus_claims ADD UNIQUE KEY user_tier_week (user_id, bonus_tier_id, week_key)");

// ── Week helpers ──────────────────────────────────────────────────────────
function currentWeekKey() {
    // ISO week: Monday = start, Sunday = end
    return date('Y-\WW');  // e.g. 2026-W18
}
function weekStart($weekKey = null) {
    // Returns Monday 00:00:00 of the given (or current) week
    if (!$weekKey) $weekKey = currentWeekKey();
    [$year, $week] = explode('-W', $weekKey);
    $dt = new DateTime();
    $dt->setISODate((int)$year, (int)$week, 1); // 1 = Monday
    $dt->setTime(0, 0, 0);
    return $dt->format('Y-m-d H:i:s');
}
function weekEnd($weekKey = null) {
    // Returns Sunday 23:59:59
    if (!$weekKey) $weekKey = currentWeekKey();
    [$year, $week] = explode('-W', $weekKey);
    $dt = new DateTime();
    $dt->setISODate((int)$year, (int)$week, 7); // 7 = Sunday
    $dt->setTime(23, 59, 59);
    return $dt->format('Y-m-d H:i:s');
}
function nextSundayCountdown() {
    $now     = new DateTime();
    $sunday  = clone $now;
    // Find next Sunday 23:59:59
    $dow = (int)$now->format('N'); // 1=Mon ... 7=Sun
    $daysToSun = 7 - $dow;
    if ($daysToSun === 0) $daysToSun = 0; // today is Sunday
    $sunday->modify("+{$daysToSun} days");
    $sunday->setTime(23, 59, 59);
    $diff = $sunday->getTimestamp() - time();
    if ($diff <= 0) return 'Resets tonight!';
    $d = floor($diff / 86400);
    $h = floor(($diff % 86400) / 3600);
    $m = floor(($diff % 3600) / 60);
    $parts = [];
    if ($d > 0) $parts[] = "{$d}d";
    if ($h > 0) $parts[] = "{$h}h";
    $parts[] = "{$m}m";
    return implode(' ', $parts);
}

// ── Helper functions ──────────────────────────────────────────────────────
if (!function_exists('isBonusTierClaimedThisWeek')) {
    function isBonusTierClaimedThisWeek($conn, $userId, $tierId) {
        $wk = currentWeekKey();
        $s  = $conn->prepare("SELECT id FROM user_bonus_claims WHERE user_id=? AND bonus_tier_id=? AND week_key=?");
        $s->bind_param("iis", $userId, $tierId, $wk);
        $s->execute();
        return $s->get_result()->num_rows > 0;
    }
}

if (!function_exists('awardBonusToUser')) {
    function awardBonusToUser($conn, $userId, $amount, $bonusType, $reason, $adminId=null, $tierId=null, $notes=null) {
        $wk = currentWeekKey();
        if ($tierId && isBonusTierClaimedThisWeek($conn, $userId, $tierId))
            return ['success'=>false, 'message'=>'Already claimed this week.'];
        $conn->begin_transaction();
        try {
            if ($tierId) {
                $lc = $conn->prepare("SELECT id FROM user_bonus_claims WHERE user_id=? AND bonus_tier_id=? AND week_key=? FOR UPDATE");
                $lc->bind_param("iis", $userId, $tierId, $wk); $lc->execute();
                if ($lc->get_result()->num_rows > 0) { $conn->rollback(); return ['success'=>false,'message'=>'Already claimed this week.']; }
            }
            $uw = $conn->prepare("UPDATE wallets SET bonus_wallet=bonus_wallet+? WHERE user_id=?");
            $uw->bind_param("di", $amount, $userId); $uw->execute();
            $ib = $conn->prepare("INSERT INTO bonus_awards(user_id,bonus_type,bonus_tier_id,amount,reason,notes,awarded_by,status,week_key)VALUES(?,?,?,?,?,?,?,'credited',?)");
            $ib->bind_param("isissiis", $userId, $bonusType, $tierId, $amount, $reason, $notes, $adminId, $wk);
            $ib->execute();
            if ($tierId) {
                $cs = $conn->prepare("INSERT INTO user_bonus_claims(user_id,bonus_tier_id,week_key)VALUES(?,?,?)");
                $cs->bind_param("iis", $userId, $tierId, $wk); $cs->execute();
            }
            $conn->commit();
            return ['success'=>true, 'message'=>'Bonus awarded!'];
        } catch (Exception $e) {
            $conn->rollback();
            return ['success'=>false, 'message'=>'Failed to claim. Try again.'];
        }
    }
}

if (!function_exists('claimMilestoneBonus')) {
    function claimMilestoneBonus($conn, $userId, $tierId) {
        if (isBonusTierClaimedThisWeek($conn, $userId, $tierId))
            return ['success'=>false, 'message'=>'Already claimed this week.'];
        $ts = $conn->prepare("SELECT * FROM referral_bonus_tiers WHERE id=? AND status='active'");
        $ts->bind_param("i", $tierId); $ts->execute();
        $tier = $ts->get_result()->fetch_assoc();
        if (!$tier) return ['success'=>false, 'message'=>'Invalid or inactive tier.'];

        // Count referrals made THIS WEEK only
        $wStart = weekStart();
        $cs = $conn->prepare("SELECT COUNT(*) as c FROM users WHERE referred_by=? AND status='active' AND created_at >= ?");
        $cs->bind_param("is", $userId, $wStart); $cs->execute();
        $weeklyRefs = $cs->get_result()->fetch_assoc()['c'];

        if ($weeklyRefs < $tier['referral_count']) {
            $rem = $tier['referral_count'] - $weeklyRefs;
            return ['success'=>false, 'message'=>"Need {$rem} more referrals this week."];
        }
        $reason = "🎉 {$tier['bonus_name']} - {$tier['referral_count']} referrals this week!";
        $r = awardBonusToUser($conn, $userId, $tier['bonus_amount'], 'referral_milestone', $reason, null, $tierId);
        if ($r['success']) { $r['amount'] = $tier['bonus_amount']; $r['tier_name'] = $tier['bonus_name']; }
        return $r;
    }
}

// ── Handle claim POST ─────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['claim_tier'])) {
    $tid = intval($_POST['claim_tier']);
    $r   = claimMilestoneBonus($conn, $userId, $tid);
    $csym = $userData['currency_symbol'] ?? 'KSh';
    if ($r['success']) $_SESSION['bsuccess'] = "🎉 {$r['tier_name']} bonus of $csym ".number_format($r['amount'],2)." claimed!";
    else               $_SESSION['berror']   = $r['message'];
    header("Location: bonus.php"); exit;
}

// ── Load data ─────────────────────────────────────────────────────────────
$uStmt = $conn->prepare("SELECT country FROM users WHERE id=?");
$uStmt->bind_param("i", $userId); $uStmt->execute();
$uInfo = $uStmt->get_result()->fetch_assoc();
$countryId = null;
if ($uInfo) {
    $cStmt = $conn->prepare("SELECT id FROM countries WHERE name=?");
    $cStmt->bind_param("s", $uInfo['country']); $cStmt->execute();
    $cr = $cStmt->get_result()->fetch_assoc();
    $countryId = $cr ? $cr['id'] : null;
}

// ── Weekly referral count (this week only) ────────────────────────────────
$wStart   = weekStart();
$wEnd     = weekEnd();
$weekKey  = currentWeekKey();

$wrStmt = $conn->prepare("SELECT COUNT(*) as c FROM users WHERE referred_by=? AND status='active' AND created_at >= ? AND created_at <= ?");
$wrStmt->bind_param("iss", $userId, $wStart, $wEnd); $wrStmt->execute();
$weeklyRefs = $wrStmt->get_result()->fetch_assoc()['c'];

// Also get all-time for display
$arStmt = $conn->prepare("SELECT COUNT(*) as c FROM users WHERE referred_by=? AND status='active'");
$arStmt->bind_param("i", $userId); $arStmt->execute();
$allTimeRefs = $arStmt->get_result()->fetch_assoc()['c'];

// ── Wallet + history ─────────────────────────────────────────────────────
$bwStmt = $conn->prepare("SELECT COALESCE(bonus_wallet,0) as bal FROM wallets WHERE user_id=?");
$bwStmt->bind_param("i", $userId); $bwStmt->execute();
$bonusBal = $bwStmt->get_result()->fetch_assoc()['bal'] ?? 0;

$teStmt = $conn->prepare("SELECT COALESCE(SUM(amount),0) as tot FROM bonus_awards WHERE user_id=? AND status='credited'");
$teStmt->bind_param("i", $userId); $teStmt->execute();
$totalEarned = $teStmt->get_result()->fetch_assoc()['tot'];

// This week's earnings
$twStmt = $conn->prepare("SELECT COALESCE(SUM(amount),0) as tot FROM bonus_awards WHERE user_id=? AND status='credited' AND week_key=?");
$twStmt->bind_param("is", $userId, $weekKey); $twStmt->execute();
$weekEarned = $twStmt->get_result()->fetch_assoc()['tot'];

// Claims this week
$cmStmt = $conn->prepare("SELECT COUNT(*) as c FROM user_bonus_claims WHERE user_id=? AND week_key=?");
$cmStmt->bind_param("is", $userId, $weekKey); $cmStmt->execute();
$weekClaims = $cmStmt->get_result()->fetch_assoc()['c'];

// ── Milestones ────────────────────────────────────────────────────────────
$tStmt = $conn->prepare("
    SELECT t.*,c.currency_symbol,c.name as country_name,
        (SELECT id FROM user_bonus_claims WHERE user_id=? AND bonus_tier_id=t.id AND week_key=?) as claimed_id
    FROM referral_bonus_tiers t
    LEFT JOIN countries c ON t.country_id=c.id
    WHERE t.status='active' AND (t.country_id=? OR t.country_id IS NULL)
    ORDER BY t.referral_count ASC
");
$tStmt->bind_param("isi", $userId, $weekKey, $countryId);
$tStmt->execute();
$tRes = $tStmt->get_result();

$milestones = []; $done = [];
while ($t = $tRes->fetch_assoc()) {
    if (in_array($t['referral_count'], $done)) continue;
    $done[] = $t['referral_count'];
    $t['is_claimed']   = !empty($t['claimed_id']);
    $t['is_claimable'] = !$t['is_claimed'] && $weeklyRefs >= $t['referral_count'];
    $t['progress_pct'] = min(100, round(($weeklyRefs / $t['referral_count']) * 100));
    $t['remaining']    = max(0, $t['referral_count'] - $weeklyRefs);
    $milestones[]      = $t;
}

// ── History ───────────────────────────────────────────────────────────────
$hStmt = $conn->prepare("SELECT ba.*,t.bonus_name as tier_name FROM bonus_awards ba LEFT JOIN referral_bonus_tiers t ON ba.bonus_tier_id=t.id WHERE ba.user_id=? ORDER BY ba.created_at DESC LIMIT 20");
$hStmt->bind_param("i", $userId); $hStmt->execute();
$history = $hStmt->get_result();

$cs       = $userData['currency_symbol'] ?? 'KSh';
$bsuccess = $_SESSION['bsuccess'] ?? null; unset($_SESSION['bsuccess']);
$berror   = $_SESSION['berror']   ?? null; unset($_SESSION['berror']);

$nextMilestone = null;
foreach ($milestones as $m) {
    if (!$m['is_claimed'] && !$m['is_claimable']) { $nextMilestone = $m; break; }
}

$countdown = nextSundayCountdown();
?>
<style>
*,*::before,*::after { box-sizing:border-box; }
.pg { padding:0; overflow-x:hidden; width:100%; max-width:100%; }

.fl {
    display:flex; align-items:center; gap:8px;
    padding:9px 13px; border-radius:10px;
    font-size:12px; font-weight:600;
    margin:10px 13px 0; border-left:3px solid;
    animation:fadeUp .3s ease both;
}
.fl.success { background:var(--OK-bg); border-color:var(--OK); color:var(--OK); }
.fl.error   { background:var(--DN-bg); border-color:var(--DN); color:var(--DN); }

/* ── WEEK BANNER ── */
.week-banner{
    display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;
    padding:9px 13px;margin:10px 13px 0;
    background:rgba(var(--Pr),.07);border:1px solid rgba(var(--Pr),.18);
    border-radius:11px;font-size:11.5px;
}
.week-banner-left{display:flex;align-items:center;gap:7px;font-weight:600;color:var(--txt)}
.week-banner-left i{color:var(--P);font-size:11px}
.week-badge{padding:2px 9px;border-radius:20px;font-size:9.5px;font-weight:800;background:var(--P-bg);color:var(--P);border:1px solid rgba(var(--Pr),.18)}
.week-countdown{font-size:10.5px;font-weight:700;color:var(--WN);display:flex;align-items:center;gap:4px}
.week-countdown i{font-size:9px}

.bonus-hero {
    position:relative; overflow:hidden;
    padding:22px 16px 18px;
    background:var(--bg2);
    border-bottom:1px solid var(--bdr);
}
[data-theme="dark"] .bonus-hero {
    background: linear-gradient(150deg, #07060f 0%, #0e0c1a 45%, #141228 100%);
}
.bonus-hero::before {
    content:''; position:absolute; inset:0; pointer-events:none;
    background:
        radial-gradient(ellipse 55% 55% at 15% 25%, rgba(var(--Pr),.18) 0%, transparent 65%),
        radial-gradient(ellipse 45% 55% at 85% 75%, rgba(var(--Pr),.10) 0%, transparent 65%);
}
[data-theme="light"] .bonus-hero::before { opacity:.6; }
.bonus-hero-glow {
    position:absolute; bottom:0; left:0; right:0; height:1px;
    background:linear-gradient(90deg, transparent, rgba(var(--Pr),.5) 50%, transparent);
}
.bonus-hero-inner {
    position:relative; z-index:2;
    display:flex; align-items:center; gap:14px;
}
.hero-counter {
    flex-shrink:0; width:60px; height:60px; border-radius:50%;
    border:2.5px solid var(--P);
    display:flex; align-items:center; justify-content:center;
    animation:ringSpín 8s linear infinite;
    box-shadow:0 0 16px rgba(var(--Pr),.35);
    position:relative; z-index:1;
}
@keyframes ringSpín { to { filter: hue-rotate(360deg); } }
.hero-counter-inner {
    width:calc(100% - 8px); height:calc(100% - 8px); border-radius:50%;
    background:var(--bg2);
    display:flex; flex-direction:column; align-items:center; justify-content:center;
}
[data-theme="dark"] .hero-counter-inner { background:#0e0c1a; }
.hero-counter-num { font-size:18px; font-weight:900; line-height:1; color:var(--P); font-variant-numeric:tabular-nums; }
.hero-counter-lbl { font-size:8px; font-weight:700; color:var(--txt2); letter-spacing:.5px; text-transform:uppercase; }
.hero-text { flex:1; min-width:0; }
.hero-text-title {
    font-size:15px; font-weight:900; color:var(--txt);
    letter-spacing:-.2px; margin-bottom:3px;
    display:flex; align-items:center; gap:6px; flex-wrap:wrap;
}
[data-theme="dark"] .hero-text-title { color:#fff; }
.hero-text-sub { font-size:11px; color:var(--txt2); line-height:1.5; margin-bottom:7px; }
.hero-stats { display:flex; gap:12px; flex-wrap:wrap; }
.hstat-b   { display:flex; flex-direction:column; }
.hstat-num { font-size:13px; font-weight:900; color:var(--txt); letter-spacing:-.3px; line-height:1; }
[data-theme="dark"] .hstat-num { color:#fff; }
.hstat-lbl { font-size:9px; color:var(--txt2); text-transform:uppercase; letter-spacing:.5px; font-weight:600; margin-top:1px; }
.hstat-div { width:1px; background:var(--bdr); align-self:stretch; margin:0 2px; }
.claimed-badge {
    font-size:9px; padding:2px 8px; border-radius:20px; font-weight:700;
    background:var(--OK-bg); color:var(--OK); border:1px solid rgba(34,197,94,.2);
}
.week-earned-badge{
    font-size:9px;padding:2px 8px;border-radius:20px;font-weight:700;
    background:rgba(245,158,11,.12);color:var(--WN);border:1px solid rgba(245,158,11,.2);
}
.hero-progress {
    display:flex; align-items:center; gap:8px; margin-top:12px;
    padding:8px 11px; border-radius:9px;
    background:var(--bg3); border:1px solid var(--bdr);
    position:relative; z-index:2;
}
.hp-label { font-size:10.5px; color:var(--txt2); font-weight:600; white-space:nowrap; }
.hp-bar   { flex:1; height:5px; background:var(--bg2); border-radius:3px; overflow:hidden; border:1px solid var(--bdr); }
.hp-fill  { height:100%; border-radius:3px; background:var(--P); transition:width .6s ease; }
.hp-pct   { font-size:10.5px; font-weight:800; color:var(--P); white-space:nowrap; }

.roadmap { padding:16px 14px; position:relative; }
.roadmap-line {
    position:absolute; left:37px; top:0; bottom:0; width:2px;
    background:linear-gradient(180deg, rgba(var(--Pr),.35), rgba(var(--Pr),.15), var(--bdr));
    z-index:0;
}
.roadmap-sec {
    font-size:9px; font-weight:700; letter-spacing:2px; text-transform:uppercase;
    color:var(--P); opacity:.7; margin-bottom:12px;
    display:flex; align-items:center; gap:8px;
    position:relative; z-index:1;
}
.roadmap-sec::after {
    content:''; flex:1; height:1px;
    background:linear-gradient(90deg, rgba(var(--Pr),.3), transparent);
}
.milestone {
    position:relative; z-index:1;
    display:flex; gap:12px; margin-bottom:12px;
}
.milestone:last-child { margin-bottom:0; }
.ms-bubble {
    width:46px; height:46px; flex-shrink:0; border-radius:50%;
    display:flex; align-items:center; justify-content:center;
    font-size:16px; font-weight:900;
    position:relative; z-index:2;
    transition:transform .2s; border:2.5px solid transparent;
}
.ms-bubble.locked   { background:var(--bg3); border-color:var(--bdr); color:var(--txt3); font-size:13px; }
.ms-bubble.claimable{ background:var(--WN); border-color:rgba(245,158,11,.5); color:#fff; box-shadow:0 0 18px rgba(245,158,11,.45),0 0 36px rgba(245,158,11,.2); animation:claimPulse 2s ease-in-out infinite; }
@keyframes claimPulse { 0%,100%{box-shadow:0 0 18px rgba(245,158,11,.45)} 50%{box-shadow:0 0 28px rgba(245,158,11,.75),0 0 48px rgba(245,158,11,.3)} }
.ms-bubble.claimed  { background:var(--OK); border-color:rgba(34,197,94,.4); color:#fff; box-shadow:0 4px 14px rgba(34,197,94,.35); }
.ms-card {
    flex:1; min-width:0; border-radius:13px; padding:12px 13px;
    background:var(--card); border:1px solid var(--bdr);
    transition:border-color .2s, background .2s, box-shadow .2s;
    position:relative; overflow:hidden;
}
.ms-card:hover { border-color:rgba(var(--Pr),.25); box-shadow:var(--shadow); }
.ms-card::before { content:''; position:absolute; left:0; top:0; bottom:0; width:3px; border-radius:0 2px 2px 0; opacity:0; transition:opacity .2s; }
.ms-card.claimable::before { background:var(--WN); opacity:1; }
.ms-card.claimed::before   { background:var(--OK); opacity:1; }
.ms-card.claimable { border-color:rgba(245,158,11,.28); background:var(--WN-bg); }
.ms-card.claimed   { border-color:rgba(34,197,94,.22); background:var(--OK-bg); opacity:.8; }
.ms-top { display:flex; align-items:flex-start; justify-content:space-between; gap:8px; margin-bottom:6px; flex-wrap:wrap; }
.ms-name { font-size:12.5px; font-weight:700; color:var(--txt); letter-spacing:-.2px; line-height:1.2; }
.ms-req  { font-size:10px; color:var(--txt2); margin-top:2px; display:flex; align-items:center; gap:4px; flex-wrap:wrap; }
.ms-req i { font-size:9px; }
.ms-amount-wrap { text-align:right; flex-shrink:0; }
.ms-amount { font-size:16px; font-weight:900; line-height:1; letter-spacing:-.4px; font-variant-numeric:tabular-nums; }
.ms-amount.ok  { color:var(--OK); }
.ms-amount.wn  { color:var(--WN); }
.ms-amount.dim { color:var(--txt3); }
.ms-currency   { font-size:9px; color:var(--txt3); text-transform:uppercase; letter-spacing:.4px; font-weight:700; }
.ms-pbar  { height:4px; background:var(--bg3); border-radius:3px; overflow:hidden; margin:8px 0 4px; }
.ms-pfill { height:100%; border-radius:3px; transition:width .6s cubic-bezier(.22,1,.36,1); }
.ms-pfill.ok  { background:var(--OK); }
.ms-pfill.wn  { background:var(--WN); }
.ms-pfill.dim { background:var(--txt3); }
.ms-pinfo { display:flex; justify-content:space-between; font-size:9.5px; }
.ms-pinfo span   { color:var(--txt3); }
.ms-pinfo strong { color:var(--txt2); }
.ms-btn {
    width:100%; height:36px; border:none; border-radius:9px; margin-top:9px;
    font-size:12px; font-weight:700; cursor:pointer; font-family:inherit;
    display:flex; align-items:center; justify-content:center; gap:6px; transition:.18s;
}
.ms-btn.claim { background:var(--WN); color:#fff; box-shadow:0 3px 12px rgba(245,158,11,.35); }
.ms-btn.claim:hover { filter:brightness(1.1); transform:translateY(-1px); }
.ms-btn.done  { background:var(--OK-bg); color:var(--OK); cursor:default; border:1px solid rgba(34,197,94,.2); }
.ms-btn.need  { background:var(--bg3); color:var(--txt3); cursor:not-allowed; border:1px solid var(--bdr); font-size:11px; }

/* Week label on claimed */
.ms-week-lbl{font-size:9px;color:var(--txt3);margin-top:4px;text-align:right}

.history-section { padding:0 14px 16px; }
.history-sec {
    font-size:9px; font-weight:700; letter-spacing:2px; text-transform:uppercase;
    color:var(--P); opacity:.7; margin-bottom:10px;
    display:flex; align-items:center; gap:8px;
}
.history-sec::after { content:''; flex:1; height:1px; background:linear-gradient(90deg, rgba(var(--Pr),.3), transparent); }
.history-sec-count { font-size:9px; padding:2px 8px; border-radius:20px; font-weight:800; background:var(--P-bg); color:var(--P); opacity:1; border:1px solid rgba(var(--Pr),.18); }
.history-scroll { display:flex; gap:8px; overflow-x:auto; padding-bottom:6px; -webkit-overflow-scrolling:touch; scrollbar-width:none; }
.history-scroll::-webkit-scrollbar { display:none; }
.hcard { flex-shrink:0; width:160px; border-radius:12px; padding:11px 12px; background:var(--card); border:1px solid var(--bdr); position:relative; overflow:hidden; transition:border-color .2s, box-shadow .2s; }
.hcard:hover { border-color:rgba(var(--Pr),.25); box-shadow:var(--shadow); }
.hcard::before { content:''; position:absolute; top:0; left:0; right:0; height:2.5px; border-radius:12px 12px 0 0; background:var(--hc-color, var(--P)); }
.hcard-ico { width:30px; height:30px; border-radius:8px; display:flex; align-items:center; justify-content:center; font-size:12px; color:#fff; margin-bottom:8px; }
.hcard-type  { font-size:8.5px; font-weight:800; text-transform:uppercase; letter-spacing:.5px; margin-bottom:3px; }
.hcard-name  { font-size:11px; font-weight:700; color:var(--txt); margin-bottom:2px; line-height:1.3; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.hcard-amt   { font-size:16px; font-weight:900; color:var(--OK); letter-spacing:-.4px; font-variant-numeric:tabular-nums; }
.hcard-date  { font-size:9.5px; color:var(--txt3); margin-top:2px; }
.hcard-week  { font-size:9px; color:var(--txt3); margin-top:1px; }
.history-empty { text-align:center; padding:20px 16px; background:var(--card); border:1px solid var(--bdr); border-radius:12px; font-size:12px; color:var(--txt2); }
.miles-empty { text-align:center; padding:28px 16px; position:relative; z-index:1; background:var(--card); border:1px solid var(--bdr); border-radius:12px; }
.miles-empty-ico { font-size:32px; margin-bottom:8px; opacity:.4; }
.miles-empty-t   { font-size:13px; font-weight:700; color:var(--txt); }
.miles-empty-s   { font-size:12px; color:var(--txt2); margin-top:3px; }
.confetti-container { position:fixed; inset:0; pointer-events:none; z-index:9999; overflow:hidden; }
@keyframes confetti-fall { to { transform:translateY(100vh) rotate(720deg); opacity:0; } }
@keyframes fadeUp { from{opacity:0;transform:translateY(10px)} to{opacity:1;transform:translateY(0)} }
.bonus-hero     { animation:fadeUp .4s ease both .03s; }
.roadmap        { animation:fadeUp .4s ease both .07s; }
.history-section{ animation:fadeUp .4s ease both .14s; }
.milestone:nth-child(1) { animation:fadeUp .3s ease .05s both; }
.milestone:nth-child(2) { animation:fadeUp .3s ease .09s both; }
.milestone:nth-child(3) { animation:fadeUp .3s ease .13s both; }
.milestone:nth-child(n+4){ animation:fadeUp .3s ease .17s both; }
@media(max-width:360px) {
    .roadmap-line{left:29px}.ms-bubble{width:38px;height:38px;font-size:12px;border-width:2px}
    .ms-card{padding:10px 11px}.ms-name{font-size:12px}.ms-amount{font-size:15px}
    .hero-counter{width:52px;height:52px}.hero-counter-num{font-size:16px}
}
@media(min-width:600px) {
    .roadmap-line{left:43px}.ms-bubble{width:50px;height:50px;font-size:18px}
    .hero-counter{width:70px;height:70px}.hero-counter-num{font-size:22px}
    .roadmap{padding:18px 20px}.history-section{padding:0 20px 20px}
}
</style>

<div class="pg">

<?php if ($bsuccess): ?>
<div class="fl success"><i class="fa-solid fa-circle-check"></i><?= htmlspecialchars($bsuccess) ?></div>
<?php endif; ?>
<?php if ($berror): ?>
<div class="fl error"><i class="fa-solid fa-circle-xmark"></i><?= htmlspecialchars($berror) ?></div>
<?php endif; ?>

<!-- ── WEEK BANNER ── -->
<div class="week-banner">
    <div class="week-banner-left">
        <i class="fa-solid fa-calendar-week"></i>
        <span>Week <?= $weekKey ?> &nbsp;·&nbsp; <?= date('M j', strtotime(weekStart())) ?> – <?= date('M j', strtotime(weekEnd())) ?></span>
        <span class="week-badge"><?= $weeklyRefs ?> refs this week</span>
    </div>
    <div class="week-countdown">
        <i class="fa-solid fa-rotate"></i>
        Resets in <?= htmlspecialchars($countdown) ?>
    </div>
</div>

<!-- ═══ HERO ═══ -->
<div class="bonus-hero">
    <div class="bonus-hero-glow"></div>
    <div class="bonus-hero-inner">

        <!-- Weekly referral count -->
        <div class="hero-counter">
            <div class="hero-counter-inner">
                <div class="hero-counter-num"><?= number_format($weeklyRefs) ?></div>
                <div class="hero-counter-lbl">This Week</div>
            </div>
        </div>

        <div class="hero-text">
            <div class="hero-text-title">
                Bonus Rewards
                <?php if ($weekClaims > 0): ?>
                <span class="claimed-badge"><?= $weekClaims ?> this week</span>
                <?php endif; ?>
                <?php if ($weekEarned > 0): ?>
                <span class="week-earned-badge">+<?= $cs ?> <?= number_format($weekEarned,0) ?></span>
                <?php endif; ?>
            </div>
            <div class="hero-text-sub">Get referrals each week to unlock cash bonuses. Resets every Sunday!</div>
            <div class="hero-stats">
                <div class="hstat-b">
                    <div class="hstat-num"><?= $cs.' '.number_format($bonusBal,0) ?></div>
                    <div class="hstat-lbl">Balance</div>
                </div>
                <div class="hstat-div"></div>
                <div class="hstat-b">
                    <div class="hstat-num"><?= number_format($weeklyRefs) ?></div>
                    <div class="hstat-lbl">Week Sales</div>
                </div>
                <div class="hstat-div"></div>
                <div class="hstat-b">
                    <div class="hstat-num"><?= number_format($allTimeRefs) ?></div>
                    <div class="hstat-lbl">All Time</div>
                </div>
                <div class="hstat-div"></div>
                <div class="hstat-b">
                    <div class="hstat-num"><?= count($milestones) ?></div>
                    <div class="hstat-lbl">Tiers</div>
                </div>
            </div>
        </div>
    </div>

    <?php if ($nextMilestone): ?>
    <div class="hero-progress">
        <span class="hp-label">Next: <?= htmlspecialchars($nextMilestone['bonus_name']) ?></span>
        <div class="hp-bar"><div class="hp-fill" style="width:<?= $nextMilestone['progress_pct'] ?>%"></div></div>
        <span class="hp-pct"><?= $nextMilestone['progress_pct'] ?>%</span>
    </div>
    <?php endif; ?>
</div>

<!-- ═══ MILESTONE ROADMAP ═══ -->
<div class="roadmap">
    <div class="roadmap-line"></div>
    <div class="roadmap-sec"><i class="fa-solid fa-road" style="font-size:9px"></i>This Week's Milestones</div>

    <?php if (empty($milestones)): ?>
    <div class="miles-empty">
        <div class="miles-empty-ico">🏅</div>
        <div class="miles-empty-t">No Milestones Available</div>
        <div class="miles-empty-s">Check back later!</div>
    </div>
    <?php else: foreach ($milestones as $idx => $m):
        $state    = $m['is_claimed'] ? 'claimed' : ($m['is_claimable'] ? 'claimable' : 'locked');
        $amtClass = $m['is_claimed'] ? 'ok'  : ($m['is_claimable'] ? 'wn' : 'dim');
        $fillCls  = $m['is_claimed'] ? 'ok'  : ($m['is_claimable'] ? 'wn' : 'dim');
        if ($m['is_claimed'])       $bubCont = '<i class="fa-solid fa-check"></i>';
        elseif ($m['is_claimable']) $bubCont = '<i class="fa-solid fa-gift"></i>';
        else $bubCont = ($idx + 1);
    ?>
    <div class="milestone">
        <div class="ms-bubble <?= $state ?>"><?= $bubCont ?></div>
        <div class="ms-card <?= $state ?>">
            <div class="ms-top">
                <div>
                    <div class="ms-name"><?= htmlspecialchars($m['bonus_name']) ?></div>
                    <div class="ms-req">
                        <i class="fa-solid fa-users"></i>
                        <?= number_format($m['referral_count']) ?> refs this week
                        <?php if ($m['remaining'] > 0): ?>
                        &nbsp;·&nbsp;
                        <span style="color:<?= $m['is_claimable']?'var(--OK)':'var(--WN)' ?>;font-weight:700"><?= $m['remaining'] ?> to go</span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="ms-amount-wrap">
                    <div class="ms-amount <?= $amtClass ?>"><?= number_format($m['bonus_amount'],0) ?></div>
                    <div class="ms-currency"><?= $cs ?> Bonus</div>
                </div>
            </div>

            <?php if (!$m['is_claimed']): ?>
            <div class="ms-pbar">
                <div class="ms-pfill <?= $fillCls ?>" style="width:<?= $m['progress_pct'] ?>%"></div>
            </div>
            <div class="ms-pinfo">
                <span><?= $weeklyRefs ?> / <?= $m['referral_count'] ?> this week</span>
                <strong><?= $m['progress_pct'] ?>%</strong>
            </div>
            <?php else: ?>
            <div class="ms-week-lbl">Claimed <?= $weekKey ?></div>
            <?php endif; ?>

            <?php if ($m['is_claimed']): ?>
            <button class="ms-btn done" disabled>
                <i class="fa-solid fa-circle-check"></i> Claimed This Week
            </button>
            <?php elseif ($m['is_claimable']): ?>
            <form method="POST">
                <input type="hidden" name="claim_tier" value="<?= $m['id'] ?>">
                <button type="submit" class="ms-btn claim"
                    onclick="return confirm('Claim <?= htmlspecialchars($m['bonus_name']) ?> — <?= $cs ?> <?= number_format($m['bonus_amount'],0) ?>?')">
                    <i class="fa-solid fa-gift"></i> Claim <?= $cs.' '.number_format($m['bonus_amount'],0) ?>
                </button>
            </form>
            <?php else: ?>
            <button class="ms-btn need" disabled>
                <i class="fa-solid fa-lock"></i> Need <?= $m['remaining'] ?> more this week
            </button>
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; endif; ?>
</div>

<!-- ═══ HISTORY ═══ -->
<?php
$histRows = [];
while ($h = $history->fetch_assoc()) $histRows[] = $h;
$typeColor = [
    'referral_milestone' => ['color'=>'var(--WN)',  'ico'=>'fa-trophy',              'bg'=>'var(--WN)'],
    'manual'             => ['color'=>'var(--P)',    'ico'=>'fa-hand-holding-dollar', 'bg'=>'var(--P)'],
    'promotion'          => ['color'=>'#a78bfa',     'ico'=>'fa-bullhorn',            'bg'=>'#a78bfa'],
    'welcome'            => ['color'=>'var(--OK)',   'ico'=>'fa-star',                'bg'=>'var(--OK)'],
];
?>
<div class="history-section">
    <div class="history-sec">
        <i class="fa-solid fa-clock-rotate-left" style="font-size:9px"></i>Bonus History
        <?php if (!empty($histRows)): ?>
        <span class="history-sec-count"><?= count($histRows) ?></span>
        <?php endif; ?>
    </div>
    <?php if (empty($histRows)): ?>
    <div class="history-empty">
        <i class="fa-solid fa-gift" style="font-size:24px;display:block;margin-bottom:6px;color:var(--txt3)"></i>
        No bonuses claimed yet — start referring!
    </div>
    <?php else: ?>
    <div class="history-scroll">
        <?php foreach ($histRows as $b):
            $bt = $b['bonus_type'] ?? 'manual';
            $tc = $typeColor[$bt] ?? ['color'=>'var(--P)','ico'=>'fa-coins','bg'=>'var(--P)'];
            $blbl = ($bt==='referral_milestone') ? 'Milestone' : ucfirst(str_replace('_',' ',$bt));
            $bWeek = $b['week_key'] ?? '';
        ?>
        <div class="hcard" style="--hc-color:<?= $tc['color'] ?>">
            <div class="hcard-ico" style="background:<?= $tc['bg'] ?>">
                <i class="fa-solid <?= $tc['ico'] ?>"></i>
            </div>
            <div class="hcard-type" style="color:<?= $tc['color'] ?>"><?= $blbl ?></div>
            <div class="hcard-name"><?= htmlspecialchars($b['tier_name']??'Bonus') ?></div>
            <div class="hcard-amt">+<?= $cs.' '.number_format($b['amount'],0) ?></div>
            <div class="hcard-date"><?= date('M j, Y',strtotime($b['created_at'])) ?></div>
            <?php if ($bWeek): ?><div class="hcard-week"><?= htmlspecialchars($bWeek) ?></div><?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

</div><!-- /.pg -->

<?php if ($bsuccess): ?>
<div class="confetti-container" id="cc"></div>
<script>
(function(){
    var c   = document.getElementById('cc');
    var col = '<?= addslashes($adminPrimary ?? '#6d28d9') ?>';
    var palette = [col,'#22c55e','#f59e0b','#ef4444','#a78bfa','#f97316'];
    for (var i=0; i<80; i++) {
        (function(i){ setTimeout(function(){
            var d = document.createElement('div');
            d.style.cssText = 'position:absolute;width:9px;height:9px;background:'+palette[Math.floor(Math.random()*palette.length)]+';left:'+Math.random()*100+'%;top:-10px;border-radius:'+(Math.random()>.5?'50%':'2px')+';animation:confetti-fall '+(2+Math.random()*2)+'s linear forwards';
            c.appendChild(d);
            setTimeout(function(){ d.remove(); }, 4000);
        }, i*25); })(i);
    }
    setTimeout(function(){ if(c.parentNode) c.remove(); }, 5000);
})();
</script>
<?php endif; ?>

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