<?php
// BONUS MANAGEMENT — WEEKLY RESET SYSTEM
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'Bonus Management';
include 'side.php';
require_once 'admin_protect.php';

$conn = getConnection();

// ── Ensure week_key column exists (compatible with MySQL 5.7+ and MariaDB) ──
function ensureWeekKeyCol($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 ''");
    }
}
ensureWeekKeyCol($conn, 'user_bonus_claims');
ensureWeekKeyCol($conn, 'bonus_awards');
// Add unique key only if it doesn't already exist
$keyChk = $conn->query("SHOW INDEX FROM user_bonus_claims WHERE Key_name='user_tier_week'");
if ($keyChk && $keyChk->num_rows === 0) {
    $conn->query("ALTER TABLE user_bonus_claims ADD UNIQUE KEY user_tier_week (user_id, bonus_tier_id, week_key)");
}

// ── Week helpers ──────────────────────────────────────────────────────────
function currentWeekKey(){ return date('Y-\WW'); }
function weekStart($wk=null){
    if(!$wk)$wk=currentWeekKey();
    [$y,$w]=explode('-W',$wk);
    $dt=new DateTime();$dt->setISODate((int)$y,(int)$w,1);$dt->setTime(0,0,0);
    return $dt->format('Y-m-d H:i:s');
}
function weekEnd($wk=null){
    if(!$wk)$wk=currentWeekKey();
    [$y,$w]=explode('-W',$wk);
    $dt=new DateTime();$dt->setISODate((int)$y,(int)$w,7);$dt->setTime(23,59,59);
    return $dt->format('Y-m-d H:i:s');
}
function weekLabel($wk){
    return date('M j',strtotime(weekStart($wk))).' – '.date('M j',strtotime(weekEnd($wk)));
}

// ── Award helper ──────────────────────────────────────────────────────────
function awardBonus($conn,$userId,$amount,$bonusType,$reason,$adminId=null,$tierId=null,$notes=null){
    $wk=$_wk=currentWeekKey();
    $conn->begin_transaction();
    try{
        $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 IGNORE INTO user_bonus_claims(user_id,bonus_tier_id,week_key)VALUES(?,?,?)");
            $cs->bind_param("iis",$userId,$tierId,$wk);$cs->execute();
        }
        $conn->commit();return true;
    }catch(Exception $e){$conn->rollback();return false;}
}

// ── Check referral milestones (weekly) ────────────────────────────────────
function checkReferralMilestones($conn,$userId){
    $wk=currentWeekKey();$ws=weekStart($wk);$we=weekEnd($wk);
    $uS=$conn->prepare("SELECT country FROM users WHERE id=?");$uS->bind_param("i",$userId);$uS->execute();
    $u=$uS->get_result()->fetch_assoc();if(!$u)return 0;
    $cS=$conn->prepare("SELECT id FROM countries WHERE name=?");$cS->bind_param("s",$u['country']);$cS->execute();
    $cr=$cS->get_result()->fetch_assoc();$cid=$cr?$cr['id']:null;
    // Count THIS WEEK's referrals only
    $rc=$conn->prepare("SELECT COUNT(*) as c FROM users WHERE referred_by=? AND status='active' AND created_at>=? AND created_at<=?");
    $rc->bind_param("iss",$userId,$ws,$we);$rc->execute();
    $weekRefs=$rc->get_result()->fetch_assoc()['c'];
    $tQ=$conn->prepare("SELECT t.* FROM referral_bonus_tiers t WHERE t.status='active' AND t.referral_count<=? AND (t.country_id=? OR t.country_id IS NULL) AND t.id NOT IN (SELECT bonus_tier_id FROM user_bonus_claims WHERE user_id=? AND week_key=?) ORDER BY t.country_id DESC,t.referral_count ASC");
    $tQ->bind_param("iiis",$weekRefs,$cid,$userId,$wk);$tQ->execute();
    $tiers=$tQ->get_result();$awarded=0;$done=[];
    while($t=$tiers->fetch_assoc()){if(in_array($t['referral_count'],$done))continue;$done[]=$t['referral_count'];$reason="🎉 {$t['bonus_name']} — {$t['referral_count']} referrals this week!";if(awardBonus($conn,$userId,$t['bonus_amount'],'referral_milestone',$reason,null,$t['id']))$awarded++;}
    return $awarded;
}

// ══════════════════════════════════════════════════════════════════════════
// POST ACTIONS
// ══════════════════════════════════════════════════════════════════════════
if($_SERVER['REQUEST_METHOD']==='POST'){
    $action=$_POST['action']??'';
    switch($action){
        case 'award_manual_bonus':
            $uid=intval($_POST['user_id']);$amt=floatval($_POST['amount']);
            $reason=sanitize($_POST['reason']);$notes=sanitize($_POST['notes']??'');
            $bt=sanitize($_POST['bonus_type']??'manual');
            if($uid<=0||$amt<=0||empty($reason)){setFlash('error','Invalid input.');redirect('bonuses.php');exit;}
            $cu=$conn->prepare("SELECT username FROM users WHERE id=?");$cu->bind_param("i",$uid);$cu->execute();
            $ud=$cu->get_result()->fetch_assoc();
            if(!$ud){setFlash('error','User not found.');redirect('bonuses.php');exit;}
            if(awardBonus($conn,$uid,$amt,$bt,$reason,$_SESSION['admin_id'],null,$notes)){
                logAdminAction('award_bonus',"Awarded {$amt} to {$ud['username']}",$uid);
                setFlash('success',"Awarded KSH ".number_format($amt,2)." to {$ud['username']}!");
            }else{setFlash('error','Failed.');}
            break;

        case 'save_tier':
            $tid=intval($_POST['tier_id']??0);$cid=!empty($_POST['country_id'])?intval($_POST['country_id']):null;
            $rc=intval($_POST['referral_count']);$ba=floatval($_POST['bonus_amount']);
            $bn=sanitize($_POST['bonus_name']);$desc=sanitize($_POST['description']??'');
            $st=sanitize($_POST['tier_status']);
            if($rc<=0||$ba<=0||empty($bn)){setFlash('error','Invalid input.');redirect('bonuses.php');exit;}
            if($tid>0){
                $s=$conn->prepare("UPDATE referral_bonus_tiers SET country_id=?,referral_count=?,bonus_amount=?,bonus_name=?,description=?,status=? WHERE id=?");
                $s->bind_param("iidsssi",$cid,$rc,$ba,$bn,$desc,$st,$tid);$s->execute();
                setFlash('success','Tier updated!');
            }else{
                $s=$conn->prepare("INSERT INTO referral_bonus_tiers(country_id,referral_count,bonus_amount,bonus_name,description,status)VALUES(?,?,?,?,?,?)");
                $s->bind_param("iidsss",$cid,$rc,$ba,$bn,$desc,$st);$s->execute();
                setFlash('success','Tier created!');
            }
            break;

        case 'delete_tier':
            $tid=intval($_POST['tier_id']);
            $ts=$conn->prepare("SELECT bonus_name FROM referral_bonus_tiers WHERE id=?");$ts->bind_param("i",$tid);$ts->execute();
            $t=$ts->get_result()->fetch_assoc();
            if($t){$conn->query("DELETE FROM referral_bonus_tiers WHERE id=$tid");setFlash('success','Tier deleted!');}
            else setFlash('error','Not found.');
            break;

        case 'check_all_milestones':
            $us=$conn->query("SELECT id FROM users WHERE status='active'");
            $tot=0;while($u=$us->fetch_assoc())$tot+=checkReferralMilestones($conn,$u['id']);
            setFlash('success',"Check complete! {$tot} bonuses awarded this week.");
            break;

        case 'check_user_milestones':
            $uid=intval($_POST['user_id']);$aw=checkReferralMilestones($conn,$uid);
            setFlash($aw>0?'success':'info',$aw>0?"Awarded {$aw} bonus(es)!":'No new bonuses for this user this week.');
            break;
    }
    redirect('bonuses.php');exit;
}

// ══════════════════════════════════════════════════════════════════════════
// LOAD DATA
// ══════════════════════════════════════════════════════════════════════════
$wk  = currentWeekKey();
$ws  = weekStart($wk);
$we  = weekEnd($wk);

// Stats
$stats = [];
$stats['total_awarded']     = $conn->query("SELECT COALESCE(SUM(amount),0) as t FROM bonus_awards WHERE status='credited'")->fetch_assoc()['t'];
$stats['week_awarded']      = $conn->query("SELECT COALESCE(SUM(amount),0) as t FROM bonus_awards WHERE status='credited' AND week_key='$wk'")->fetch_assoc()['t'];
$stats['week_claims']       = $conn->query("SELECT COUNT(*) as c FROM user_bonus_claims WHERE week_key='$wk'")->fetch_assoc()['c'];
$stats['total_recipients']  = $conn->query("SELECT COUNT(DISTINCT user_id) as c FROM bonus_awards WHERE status='credited'")->fetch_assoc()['c'];
$stats['active_tiers']      = $conn->query("SELECT COUNT(*) as c FROM referral_bonus_tiers WHERE status='active'")->fetch_assoc()['c'];

// Tiers
$tiers = $conn->query("SELECT t.*,c.name as country_name,c.currency_symbol,(SELECT COUNT(*) FROM user_bonus_claims WHERE bonus_tier_id=t.id AND week_key='$wk') as week_claimed,(SELECT COUNT(*) FROM user_bonus_claims WHERE bonus_tier_id=t.id) as times_claimed FROM referral_bonus_tiers t LEFT JOIN countries c ON t.country_id=c.id ORDER BY t.country_id IS NULL,c.name,t.referral_count ASC");

// Recent awards
$recentBonuses = $conn->query("SELECT ba.*,u.username,u.email,a.username as admin_username,t.bonus_name as tier_name FROM bonus_awards ba JOIN users u ON ba.user_id=u.id LEFT JOIN admins a ON ba.awarded_by=a.id LEFT JOIN referral_bonus_tiers t ON ba.bonus_tier_id=t.id ORDER BY ba.created_at DESC LIMIT 50");

// Weekly leaderboard — top referrers this week
$weekLeaders = $conn->query("SELECT u.id,u.username,u.country,COUNT(r.id) as week_refs,(SELECT COALESCE(SUM(amount),0) FROM bonus_awards WHERE user_id=u.id AND week_key='$wk' AND status='credited') as week_bonus FROM users u LEFT JOIN users r ON r.referred_by=u.id AND r.status='active' AND r.created_at>='$ws' AND r.created_at<='$we' WHERE u.status='active' GROUP BY u.id HAVING week_refs>0 ORDER BY week_refs DESC LIMIT 20");

// Users for dropdown
$users = $conn->query("SELECT id,username,email FROM users WHERE status='active' ORDER BY username ASC");
$countries = $conn->query("SELECT id,name,currency_symbol FROM countries WHERE status='active' ORDER BY name ASC");

$flash = getFlash();
?>

<style>
.page-header{margin-bottom:24px}
.page-title{font-size:24px;font-weight:900;color:var(--text-primary);display:flex;align-items:center;gap:12px;margin-bottom:4px}
.page-title i{background:linear-gradient(135deg,#f59e0b,#ef4444);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}
.page-subtitle{font-size:13px;color:var(--text-secondary);font-weight:500}

/* Week badge */
.week-chip{display:inline-flex;align-items:center;gap:6px;padding:4px 12px;border-radius:20px;font-size:11px;font-weight:700;background:rgba(245,158,11,.1);color:#f59e0b;border:1px solid rgba(245,158,11,.2);margin-bottom:16px}
.week-chip i{font-size:10px}

.header-actions{display:flex;gap:10px;margin-top:16px;flex-wrap:wrap}
.btn-ah{padding:10px 18px;background:linear-gradient(135deg,var(--theme-color),#ec4899);color:#fff;border:none;border-radius:10px;font-size:13px;font-weight:600;cursor:pointer;transition:all .3s;display:flex;align-items:center;gap:7px}
.btn-ah:hover{transform:translateY(-2px);box-shadow:0 4px 12px rgba(var(--theme-rgb),.4)}
.btn-ah.sec{background:var(--card-bg);color:var(--text-primary);border:1px solid var(--border-color)}
.btn-ah.sec:hover{background:var(--darker-bg)}

.stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:14px;margin-bottom:22px}
.stat-card{background:var(--card-bg);border:1px solid var(--border-color);border-radius:14px;padding:18px;position:relative;overflow:hidden}
.stat-card::before{content:'';position:absolute;top:0;left:0;right:0;height:2px}
.stat-card.amber::before{background:linear-gradient(90deg,#f59e0b,#fbbf24)}
.stat-card.green::before{background:linear-gradient(90deg,#10b981,#34d399)}
.stat-card.blue::before{background:linear-gradient(90deg,#6366f1,#818cf8)}
.stat-card.purple::before{background:linear-gradient(90deg,#8b5cf6,#a78bfa)}
.stat-ico{width:40px;height:40px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:18px;color:#fff;margin-bottom:10px}
.stat-ico.amber{background:linear-gradient(135deg,#f59e0b,#ef4444)}
.stat-ico.green{background:linear-gradient(135deg,#10b981,#059669)}
.stat-ico.blue {background:linear-gradient(135deg,#6366f1,#4f46e5)}
.stat-ico.purple{background:linear-gradient(135deg,#8b5cf6,#7c3aed)}
.stat-lbl{font-size:11px;color:var(--text-secondary);font-weight:700;text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px}
.stat-val{font-size:24px;font-weight:900;color:var(--text-primary)}
.stat-sub{font-size:10px;color:var(--text-secondary);margin-top:2px}

.content-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px}
@media(max-width:900px){.content-grid{grid-template-columns:1fr}}

.card{background:var(--card-bg);border:1px solid var(--border-color);border-radius:14px;overflow:hidden}
.card-header{padding:16px 20px;border-bottom:1px solid var(--border-color);display:flex;justify-content:space-between;align-items:center}
.card-title{font-size:15px;font-weight:800;color:var(--text-primary);display:flex;align-items:center;gap:8px}
.card-body{padding:18px}

.form-group{margin-bottom:14px}
.form-label{display:block;font-size:11.5px;font-weight:600;color:var(--text-secondary);margin-bottom:5px;text-transform:uppercase;letter-spacing:.5px}
.form-control{width:100%;padding:10px 13px;font-size:13px;border:1px solid var(--border-color);border-radius:9px;background:var(--darker-bg);color:var(--text-primary);transition:.2s}
.form-control:focus{outline:none;border-color:var(--theme-color)}
.form-row{display:grid;grid-template-columns:1fr 1fr;gap:10px}
@media(max-width:500px){.form-row{grid-template-columns:1fr}}
.btn-primary{width:100%;padding:12px;background:linear-gradient(135deg,#f59e0b,#ef4444);color:#fff;border:none;border-radius:9px;font-size:13px;font-weight:700;cursor:pointer;transition:.3s;display:flex;align-items:center;justify-content:center;gap:7px}
.btn-primary:hover{transform:translateY(-2px);box-shadow:0 6px 20px rgba(245,158,11,.4)}
.btn-sm{padding:6px 12px;font-size:11.5px;border-radius:7px;border:none;cursor:pointer;transition:.2s;display:inline-flex;align-items:center;gap:5px;font-weight:700}
.btn-edit{background:rgba(139,92,246,.15);color:#8b5cf6}.btn-edit:hover{background:#8b5cf6;color:#fff}
.btn-delete{background:rgba(239,68,68,.15);color:#ef4444}.btn-delete:hover{background:#ef4444;color:#fff}
.btn-award{background:rgba(16,185,129,.15);color:#10b981}.btn-award:hover{background:#10b981;color:#fff}

.tier-card{background:var(--darker-bg);border:1px solid var(--border-color);border-radius:10px;padding:14px;margin-bottom:10px;transition:border-color .2s}
.tier-card:hover{border-color:rgba(var(--theme-rgb),.3)}
.tier-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;flex-wrap:wrap;gap:6px}
.tier-name{font-size:14px;font-weight:700;color:var(--text-primary)}
.tier-amount{font-size:17px;font-weight:900;color:#10b981}
.tier-details{display:flex;gap:12px;font-size:12px;color:var(--text-secondary);flex-wrap:wrap}
.tier-detail{display:flex;align-items:center;gap:5px}
.tier-actions{display:flex;gap:7px;margin-top:10px}

/* Week stats on tier */
.tier-week-stat{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:20px;font-size:10px;font-weight:700;background:rgba(245,158,11,.1);color:#f59e0b;border:1px solid rgba(245,158,11,.2)}

.tbl-wrap{overflow-x:auto;max-height:480px;overflow-y:auto}
.data-table{width:100%;border-collapse:collapse}
.data-table th{padding:11px 14px;text-align:left;font-size:10.5px;font-weight:700;color:var(--text-secondary);text-transform:uppercase;letter-spacing:.5px;background:var(--darker-bg);border-bottom:1px solid var(--border-color);position:sticky;top:0;z-index:10}
.data-table td{padding:11px 14px;font-size:13px;color:var(--text-primary);border-bottom:1px solid var(--border-color);font-weight:500}
.data-table tbody tr:hover{background:var(--darker-bg)}

.badge{padding:3px 9px;border-radius:6px;font-size:10.5px;font-weight:700;text-transform:uppercase}
.badge-active{background:rgba(16,185,129,.15);color:#10b981}
.badge-inactive{background:rgba(239,68,68,.15);color:#ef4444}
.badge-manual{background:rgba(59,130,246,.15);color:#3b82f6}
.badge-milestone{background:rgba(245,158,11,.15);color:#f59e0b}
.badge-promotion{background:rgba(139,92,246,.15);color:#8b5cf6}
.badge-global{background:rgba(99,102,241,.15);color:#6366f1}
.badge-week{background:rgba(245,158,11,.12);color:#f59e0b;font-size:9.5px;padding:2px 7px}

.modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.7);backdrop-filter:blur(4px);z-index:10000;align-items:center;justify-content:center;padding:20px}
.modal.active{display:flex}
.modal-content{background:var(--card-bg);border:1px solid var(--border-color);border-radius:16px;padding:24px;max-width:480px;width:100%;max-height:90vh;overflow-y:auto}
.modal-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:18px;padding-bottom:14px;border-bottom:1px solid var(--border-color)}
.modal-title{font-size:18px;font-weight:800;color:var(--text-primary)}
.modal-close{width:30px;height:30px;background:var(--darker-bg);border:1px solid var(--border-color);border-radius:8px;color:var(--text-secondary);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:.2s}
.modal-close:hover{background:var(--card-bg);color:var(--text-primary)}

.leader-card{background:var(--darker-bg);border-radius:10px;padding:11px 13px;margin-bottom:8px;display:flex;align-items:center;justify-content:space-between;gap:10px}
.leader-av{width:36px;height:36px;border-radius:9px;background:linear-gradient(135deg,#f59e0b,#ef4444);display:flex;align-items:center;justify-content:center;font-weight:700;color:#fff;font-size:14px;flex-shrink:0}
.leader-name{font-size:13px;font-weight:700;color:var(--text-primary)}
.leader-sub{font-size:11px;color:var(--text-secondary)}
.leader-count{font-size:22px;font-weight:900;color:#f59e0b;text-align:right;flex-shrink:0}
.leader-lbl{font-size:10px;color:var(--text-secondary);text-transform:uppercase;text-align:right}
.leader-bonus{font-size:11px;font-weight:700;color:#10b981;text-align:right}
</style>

<!-- Page header -->
<div class="page-header">
    <h1 class="page-title"><i class="fas fa-gift"></i> Bonus Management</h1>
    <p class="page-subtitle">Weekly referral milestones — resets every Sunday midnight</p>
    <div class="week-chip">
        <i class="fa-solid fa-calendar-week"></i>
        Week <?= $wk ?> &nbsp;·&nbsp; <?= weekLabel($wk) ?>
    </div>
    <div class="header-actions">
        <button class="btn-ah" onclick="openModal('awardModal')"><i class="fas fa-plus"></i> Award Manual Bonus</button>
        <button class="btn-ah sec" onclick="openModal('tierModal')"><i class="fas fa-layer-group"></i> Add Tier</button>
        <form method="POST" style="display:inline">
            <input type="hidden" name="action" value="check_all_milestones">
            <button type="submit" class="btn-ah sec" onclick="return confirm('Check all users for this week&apos;s milestone bonuses?')"><i class="fas fa-sync"></i> Check This Week</button>
        </form>
    </div>
</div>

<!-- Stats -->
<div class="stats-grid">
    <div class="stat-card amber">
        <div class="stat-ico amber"><i class="fas fa-coins"></i></div>
        <div class="stat-lbl">This Week</div>
        <div class="stat-val">KSH <?= number_format($stats['week_awarded'],0) ?></div>
        <div class="stat-sub"><?= number_format($stats['week_claims']) ?> claims</div>
    </div>
    <div class="stat-card green">
        <div class="stat-ico green"><i class="fas fa-chart-line"></i></div>
        <div class="stat-lbl">All-Time Total</div>
        <div class="stat-val">KSH <?= number_format($stats['total_awarded'],0) ?></div>
    </div>
    <div class="stat-card blue">
        <div class="stat-ico blue"><i class="fas fa-users"></i></div>
        <div class="stat-lbl">Total Recipients</div>
        <div class="stat-val"><?= number_format($stats['total_recipients']) ?></div>
    </div>
    <div class="stat-card purple">
        <div class="stat-ico purple"><i class="fas fa-layer-group"></i></div>
        <div class="stat-lbl">Active Tiers</div>
        <div class="stat-val"><?= number_format($stats['active_tiers']) ?></div>
    </div>
</div>

<div class="content-grid">
    <!-- Bonus Tiers -->
    <div class="card">
        <div class="card-header">
            <div class="card-title"><i class="fas fa-medal" style="color:#f59e0b"></i> Referral Bonus Tiers</div>
            <button class="btn-sm btn-award" onclick="openModal('tierModal')"><i class="fas fa-plus"></i> Add</button>
        </div>
        <div class="card-body">
            <?php if ($tiers && $tiers->num_rows > 0): while ($t=$tiers->fetch_assoc()): ?>
            <div class="tier-card">
                <div class="tier-header">
                    <div>
                        <span class="tier-name"><?= htmlspecialchars($t['bonus_name']) ?></span>
                        <?php if ($t['country_id']): ?>
                        <span class="badge badge-active" style="margin-left:6px"><?= htmlspecialchars($t['country_name']) ?></span>
                        <?php else: ?>
                        <span class="badge badge-global" style="margin-left:6px">Global</span>
                        <?php endif; ?>
                    </div>
                    <span class="tier-amount"><?= $t['currency_symbol']??'KSH' ?> <?= number_format($t['bonus_amount'],0) ?></span>
                </div>
                <div class="tier-details">
                    <span class="tier-detail"><i class="fas fa-users"></i> <?= $t['referral_count'] ?> refs/week</span>
                    <span class="tier-week-stat"><i class="fas fa-calendar-week"></i> <?= $t['week_claimed'] ?> this week</span>
                    <span class="tier-detail"><i class="fas fa-check-circle"></i> <?= $t['times_claimed'] ?> all-time</span>
                    <span class="badge badge-<?= $t['status'] ?>"><?= ucfirst($t['status']) ?></span>
                </div>
                <div class="tier-actions">
                    <button class="btn-sm btn-edit" onclick="editTier(<?= htmlspecialchars(json_encode($t)) ?>)"><i class="fas fa-edit"></i> Edit</button>
                    <form method="POST" style="display:inline" onsubmit="return confirm('Delete this tier?')">
                        <input type="hidden" name="action" value="delete_tier">
                        <input type="hidden" name="tier_id" value="<?= $t['id'] ?>">
                        <button type="submit" class="btn-sm btn-delete"><i class="fas fa-trash"></i> Delete</button>
                    </form>
                </div>
            </div>
            <?php endwhile; else: ?>
            <p style="text-align:center;color:var(--text-secondary);padding:30px">No tiers yet.</p>
            <?php endif; ?>
        </div>
    </div>

    <!-- This week's leaderboard -->
    <div class="card">
        <div class="card-header">
            <div class="card-title"><i class="fas fa-trophy" style="color:#f59e0b"></i> This Week's Top Referrers</div>
            <span class="badge badge-week"><?= weekLabel($wk) ?></span>
        </div>
        <div class="card-body" style="padding:14px">
            <?php if ($weekLeaders && $weekLeaders->num_rows > 0): while($r=$weekLeaders->fetch_assoc()): ?>
            <div class="leader-card">
                <div style="display:flex;align-items:center;gap:10px;flex:1;min-width:0">
                    <div class="leader-av"><?= strtoupper(substr($r['username'],0,1)) ?></div>
                    <div>
                        <div class="leader-name"><?= htmlspecialchars($r['username']) ?></div>
                        <div class="leader-sub"><?= htmlspecialchars($r['country']??'') ?></div>
                        <?php if ($r['week_bonus']>0): ?>
                        <div class="leader-bonus">+KSH <?= number_format($r['week_bonus'],0) ?></div>
                        <?php endif; ?>
                    </div>
                </div>
                <div>
                    <div class="leader-count"><?= $r['week_refs'] ?></div>
                    <div class="leader-lbl">refs</div>
                </div>
            </div>
            <?php endwhile; else: ?>
            <p style="text-align:center;color:var(--text-secondary);padding:30px">No referrals this week yet.</p>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Recent Bonus Awards -->
<div class="card">
    <div class="card-header">
        <div class="card-title"><i class="fas fa-history" style="color:var(--theme-color)"></i> Recent Bonus Awards</div>
    </div>
    <div class="tbl-wrap">
    <table class="data-table">
        <thead><tr><th>#</th><th>User</th><th>Type</th><th>Amount</th><th>Week</th><th>Reason</th><th>By</th><th>Date</th></tr></thead>
        <tbody>
        <?php if ($recentBonuses && $recentBonuses->num_rows>0): while($b=$recentBonuses->fetch_assoc()): ?>
        <tr>
            <td><strong>#<?= $b['id'] ?></strong></td>
            <td><strong><?= htmlspecialchars($b['username']) ?></strong><br><small style="color:var(--text-secondary)"><?= htmlspecialchars($b['email']) ?></small></td>
            <td><span class="badge badge-<?= $b['bonus_type']==='referral_milestone'?'milestone':($b['bonus_type']==='manual'?'manual':'promotion') ?>"><?= ucfirst(str_replace('_',' ',$b['bonus_type'])) ?></span></td>
            <td style="font-weight:700;color:#10b981">KSH <?= number_format($b['amount'],2) ?></td>
            <td><?php if($b['week_key']??''): ?><span class="badge badge-week"><?= htmlspecialchars($b['week_key']) ?></span><?php endif; ?></td>
            <td style="max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?= htmlspecialchars($b['reason']) ?></td>
            <td><?= $b['admin_username'] ? htmlspecialchars($b['admin_username']) : '<span style="color:var(--text-secondary)">System</span>' ?></td>
            <td style="white-space:nowrap"><?= date('M j, H:i',strtotime($b['created_at'])) ?></td>
        </tr>
        <?php endwhile; else: ?>
        <tr><td colspan="8" style="text-align:center;padding:30px;color:var(--text-secondary)">No bonuses yet.</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
    </div>
</div>

<!-- Award Manual Bonus Modal -->
<div class="modal" id="awardModal">
<div class="modal-content">
    <div class="modal-header">
        <div class="modal-title"><i class="fas fa-gift"></i> Award Manual Bonus</div>
        <button class="modal-close" onclick="closeModal('awardModal')"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="award_manual_bonus">
        <div class="form-group">
            <label class="form-label">User *</label>
            <select name="user_id" class="form-control" required>
                <option value="">-- Select User --</option>
                <?php $users->data_seek(0); while($u=$users->fetch_assoc()): ?>
                <option value="<?= $u['id'] ?>"><?= htmlspecialchars($u['username']) ?> (<?= htmlspecialchars($u['email']) ?>)</option>
                <?php endwhile; ?>
            </select>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label class="form-label">Amount (KSH) *</label>
                <input type="number" name="amount" class="form-control" step="1" min="1" required placeholder="100">
            </div>
            <div class="form-group">
                <label class="form-label">Type</label>
                <select name="bonus_type" class="form-control">
                    <option value="manual">Manual</option>
                    <option value="promotion">Promotion</option>
                    <option value="achievement">Achievement</option>
                    <option value="welcome">Welcome</option>
                    <option value="other">Other</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="form-label">Reason *</label>
            <input type="text" name="reason" class="form-control" required placeholder="e.g. Contest winner">
        </div>
        <div class="form-group">
            <label class="form-label">Notes (optional)</label>
            <textarea name="notes" class="form-control" rows="2" placeholder="Internal notes…"></textarea>
        </div>
        <button type="submit" class="btn-primary"><i class="fas fa-gift"></i> Award Bonus</button>
    </form>
</div>
</div>

<!-- Add/Edit Tier Modal -->
<div class="modal" id="tierModal">
<div class="modal-content">
    <div class="modal-header">
        <div class="modal-title" id="tierModalTitle"><i class="fas fa-layer-group"></i> Add Bonus Tier</div>
        <button class="modal-close" onclick="closeModal('tierModal')"><i class="fas fa-times"></i></button>
    </div>
    <div style="background:rgba(245,158,11,.08);border:1px solid rgba(245,158,11,.2);border-radius:9px;padding:9px 12px;margin-bottom:14px;font-size:11.5px;color:#f59e0b">
        <i class="fas fa-info-circle"></i>
        <strong>Referral count = referrals needed within a single week</strong> to claim this tier.
        Tiers reset every Sunday — users can claim each tier once per week.
    </div>
    <form method="POST" id="tierForm">
        <input type="hidden" name="action" value="save_tier">
        <input type="hidden" name="tier_id" id="tierIdField" value="0">
        <div class="form-group">
            <label class="form-label">Tier Name *</label>
            <input type="text" name="bonus_name" id="tierName" class="form-control" required placeholder="e.g. 5-Referral Star">
        </div>
        <div class="form-row">
            <div class="form-group">
                <label class="form-label">Referrals / Week *</label>
                <input type="number" name="referral_count" id="tierRefCount" class="form-control" min="1" required placeholder="5">
            </div>
            <div class="form-group">
                <label class="form-label">Bonus Amount (KSH) *</label>
                <input type="number" name="bonus_amount" id="tierAmount" class="form-control" step="1" min="1" required placeholder="500">
            </div>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label class="form-label">Country (optional)</label>
                <select name="country_id" id="tierCountry" class="form-control">
                    <option value="">Global</option>
                    <?php $countries->data_seek(0); while($c=$countries->fetch_assoc()): ?>
                    <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['name']) ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="form-group">
                <label class="form-label">Status</label>
                <select name="tier_status" id="tierStatus" class="form-control">
                    <option value="active">Active</option>
                    <option value="inactive">Inactive</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="form-label">Description (optional)</label>
            <textarea name="description" id="tierDesc" class="form-control" rows="2" placeholder="Bonus description…"></textarea>
        </div>
        <button type="submit" class="btn-primary" id="tierSubmitBtn"><i class="fas fa-save"></i> Save Tier</button>
    </form>
</div>
</div>

<script>
function openModal(id){document.getElementById(id).classList.add('active')}
function closeModal(id){
    document.getElementById(id).classList.remove('active');
    if(id==='tierModal'){document.getElementById('tierForm').reset();document.getElementById('tierIdField').value='0';document.getElementById('tierModalTitle').innerHTML='<i class="fas fa-layer-group"></i> Add Bonus Tier';document.getElementById('tierSubmitBtn').innerHTML='<i class="fas fa-save"></i> Save Tier';}
}
function editTier(t){
    document.getElementById('tierIdField').value=t.id;
    document.getElementById('tierName').value=t.bonus_name;
    document.getElementById('tierRefCount').value=t.referral_count;
    document.getElementById('tierAmount').value=t.bonus_amount;
    document.getElementById('tierCountry').value=t.country_id||'';
    document.getElementById('tierStatus').value=t.status;
    document.getElementById('tierDesc').value=t.description||'';
    document.getElementById('tierModalTitle').innerHTML='<i class="fas fa-edit"></i> Edit Bonus Tier';
    document.getElementById('tierSubmitBtn').innerHTML='<i class="fas fa-save"></i> Update Tier';
    openModal('tierModal');
}
document.querySelectorAll('.modal').forEach(function(m){m.addEventListener('click',function(e){if(e.target===this)this.classList.remove('active');});});
</script>
<?php include 'footer.php'; ?>