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

/* ── BACKEND — UNCHANGED ─────────────────────────────── */
$levelFilter  = isset($_GET['level'])  ? intval($_GET['level'])      : 0;
$statusFilter = isset($_GET['status']) ? sanitize($_GET['status'])   : 'all';
$searchQuery  = isset($_GET['search']) ? sanitize($_GET['search'])   : '';
$page         = isset($_GET['page'])   ? max(1,intval($_GET['page'])): 1;
$perPage=15; $offset=($page-1)*$perPage;

$uq=$conn->prepare("SELECT username,referral_code,country FROM users WHERE id=?");
$uq->bind_param("i",$userId);$uq->execute();
$currentUser=$uq->get_result()->fetch_assoc();

function getRefs($conn,$uid,$lvl,$status='all',$search='',$off=0,$pp=15){
    $refs=[];
    if($lvl==1){ $w="referred_by=$uid"; }
    elseif($lvl>1&&$lvl<=5){ $cur="SELECT id FROM users WHERE referred_by=$uid"; for($i=2;$i<=$lvl;$i++) $cur="SELECT id FROM users WHERE referred_by IN ($cur)"; $w="id IN ($cur)"; }
    else return $refs;
    if($status!='all') $w.=" AND status='$status'";
    if($search) $w.=" AND (username LIKE '%$search%' OR phone LIKE '%$search%')";
    $r=$conn->query("SELECT id,username,email,phone,country,status,created_at,(SELECT COUNT(*) FROM users WHERE referred_by=users.id) as refs FROM users WHERE $w ORDER BY created_at DESC LIMIT $off,$pp");
    while($row=$r->fetch_assoc()) $refs[]=$row;
    return $refs;
}
function cntRefs($conn,$uid,$lvl,$status='all',$search=''){
    if($lvl==1){ $w="referred_by=$uid"; }
    elseif($lvl>1&&$lvl<=5){ $cur="SELECT id FROM users WHERE referred_by=$uid"; for($i=2;$i<=$lvl;$i++) $cur="SELECT id FROM users WHERE referred_by IN ($cur)"; $w="id IN ($cur)"; }
    else return 0;
    if($status!='all') $w.=" AND status='$status'";
    if($search) $w.=" AND (username LIKE '%$search%' OR phone LIKE '%$search%')";
    return intval($conn->query("SELECT COUNT(*) as c FROM users WHERE $w")->fetch_assoc()['c']);
}

$stats=[];
for($i=1;$i<=5;$i++) $stats[$i]=['total'=>cntRefs($conn,$userId,$i),'active'=>cntRefs($conn,$userId,$i,'active'),'inactive'=>cntRefs($conn,$userId,$i,'inactive')];
$totAll=array_sum(array_column($stats,'total'));
$totAct=array_sum(array_column($stats,'active'));
$totInact=array_sum(array_column($stats,'inactive'));
$actRate=$totAll>0?round($totAct/$totAll*100):0;

if($levelFilter>0){
    $referrals=getRefs($conn,$userId,$levelFilter,$statusFilter,$searchQuery,$offset,$perPage);
    $totalCount=cntRefs($conn,$userId,$levelFilter,$statusFilter,$searchQuery);
} else {
    $all=[];
    for($i=1;$i<=5;$i++) foreach(getRefs($conn,$userId,$i,$statusFilter,$searchQuery,0,999) as $r){ $r['level']=$i; $all[]=$r; }
    $totalCount=count($all); $referrals=array_slice($all,$offset,$perPage);
}
$totalPages=max(1,ceil($totalCount/$perPage));
$refLink=SITE_URL."/register.php?ref=".$currentUser['referral_code'];
$lvlLabels=['1'=>'Direct','2'=>'Level 2','3'=>'Level 3','4'=>'Level 4','5'=>'Level 5'];
$lcColors=['1'=>'#6366f1','2'=>'#f59e0b','3'=>'#ec4899','4'=>'#06b6d4','5'=>'#84cc16'];
?>
<style>
/* ══════════════════════════════════════════════════
   NETWORK — Scorecard + compact list design
   Distinct from previous: full-width rate meter,
   horizontal level bar, compact 2-line member rows.
   Mobile-first, all containers equal width.
══════════════════════════════════════════════════ */
.nt { padding:12px 12px 90px; }
@media(max-width:480px){ .nt{padding:10px 10px 90px} }

/* ── SCORECARD ── */
.nt-score {
    background:var(--card);border:1px solid var(--bdr);
    border-radius:16px;padding:16px;margin-bottom:10px;
    transition:background .25s;
}
.nt-score-top {
    display:flex;align-items:center;justify-content:space-between;
    margin-bottom:14px;gap:10px;
}
.nt-score-title {
    font-size:13px;font-weight:800;color:var(--txt);
    display:flex;align-items:center;gap:7px;
}
.nt-score-title i { color:var(--P);font-size:14px }
.nt-share {
    display:flex;align-items:center;gap:6px;
    padding:7px 13px;border-radius:8px;
    background:var(--P);color:#fff;border:none;
    font-size:11px;font-weight:700;cursor:pointer;
    font-family:inherit;transition:.15s;white-space:nowrap;
}
.nt-share:hover { filter:brightness(1.1) }

/* 3 big numbers */
.nt-nums {
    display:grid;grid-template-columns:repeat(3,1fr);
    gap:0;margin-bottom:14px;
}
.nt-num {
    text-align:center;padding:10px 8px;
    border-right:1px solid var(--bdr);
}
.nt-num:last-child { border-right:none }
.nt-num-v {
    font-size:28px;font-weight:900;color:var(--txt);
    letter-spacing:-1px;line-height:1;
    font-variant-numeric:tabular-nums;
}
.nt-num-v.ok { color:var(--OK) }
.nt-num-v.dn { color:var(--DN) }
.nt-num-l {
    font-size:9px;font-weight:700;letter-spacing:1px;
    text-transform:uppercase;color:var(--txt2);margin-top:4px;
}

/* Rate meter bar */
.nt-meter-lbl {
    display:flex;justify-content:space-between;
    font-size:10px;color:var(--txt2);margin-bottom:5px;
    font-weight:600;
}
.nt-meter-lbl span:last-child { color:var(--OK);font-weight:800 }
.nt-meter-track {
    height:6px;background:var(--bg3);border-radius:4px;
    overflow:hidden;
}
.nt-meter-fill {
    height:100%;background:var(--P);border-radius:4px;
    transition:width 1s cubic-bezier(.22,1,.36,1);
}

/* ── INVITE STRIP ── */
.nt-invite {
    background:var(--card);border:1px solid var(--bdr);
    border-radius:12px;padding:11px 13px;margin-bottom:10px;
    display:flex;align-items:center;gap:8px;
    transition:background .25s;
}
.nt-invite-ic {
    width:32px;height:32px;border-radius:8px;
    background:var(--P-bg);color:var(--P);
    border:1px solid rgba(var(--Pr),.2);
    display:flex;align-items:center;justify-content:center;
    font-size:13px;flex-shrink:0;
}
.nt-invite-url {
    flex:1;min-width:0;font-family:monospace;font-size:10.5px;
    color:var(--txt2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
}
.nt-invite-copy {
    padding:6px 13px;background:var(--P);color:#fff;
    border:none;border-radius:7px;font-size:11px;font-weight:700;
    cursor:pointer;font-family:inherit;transition:.15s;flex-shrink:0;
    white-space:nowrap;
}
.nt-invite-copy:hover { filter:brightness(1.1) }

/* ── LEVEL BAR ── */
.nt-lvlbar {
    display:grid;grid-template-columns:repeat(5,1fr);
    gap:6px;margin-bottom:10px;
}
.nt-lv {
    background:var(--card);border:1px solid var(--bdr);
    border-radius:10px;padding:9px 8px 8px;
    text-align:center;text-decoration:none;
    transition:all .15s;cursor:pointer;
    border-top:3px solid var(--lc,var(--bdr));
    position:relative;
}
.nt-lv:hover { transform:translateY(-2px);border-color:var(--lc,var(--P)) }
.nt-lv.on {
    background:var(--P-bg);
    border-color:var(--P);border-top-color:var(--P);
}
.nt-lv-n {
    font-size:17px;font-weight:900;color:var(--txt);
    line-height:1;letter-spacing:-.3px;
}
.nt-lv-l {
    font-size:8px;font-weight:700;letter-spacing:.5px;
    text-transform:uppercase;color:var(--txt2);margin-top:3px;
}
.nt-lv-a {
    font-size:8px;color:var(--OK);font-weight:600;margin-top:2px;
}
@media(max-width:360px) {
    .nt-lvlbar { gap:4px }
    .nt-lv { padding:7px 4px 6px }
    .nt-lv-n { font-size:14px }
    .nt-lv-l { font-size:7px }
}

/* ── FILTER STRIP ── */
.nt-filters {
    display:flex;align-items:center;gap:6px;
    margin-bottom:10px;flex-wrap:wrap;
}
.nt-filters form { display:contents }
.nt-sel {
    height:36px;padding:0 24px 0 10px;
    background:var(--card);border:1px solid var(--bdr);
    border-radius:8px;color:var(--txt);font-size:12px;
    font-family:inherit;outline:none;cursor:pointer;
    appearance:none;-webkit-appearance:none;
    background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6'%3E%3Cpath d='M0 0l5 6 5-6z' fill='%236b7280'/%3E%3C/svg%3E");
    background-repeat:no-repeat;background-position:right 8px center;
    flex-shrink:0;min-width:0;
    transition:border-color .15s;
    /* Shrink on small screens */
    max-width:calc(50% - 3px);
}
[data-theme="dark"] .nt-sel {
    background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6'%3E%3Cpath d='M0 0l5 6 5-6z' fill='rgba(255,255,255,.4)'/%3E%3C/svg%3E");
}
.nt-sel option { background:var(--card);color:var(--txt) }
.nt-sel:focus { border-color:rgba(var(--Pr),.4) }
.nt-inp {
    flex:1;height:36px;padding:0 10px;min-width:80px;
    background:var(--card);border:1px solid var(--bdr);
    border-radius:8px;color:var(--txt);font-size:12px;
    font-family:inherit;outline:none;transition:border-color .15s;
    box-sizing:border-box;
}
.nt-inp::placeholder { color:var(--txt3) }
.nt-inp:focus { border-color:rgba(var(--Pr),.4) }
.nt-sbtn {
    width:36px;height:36px;border-radius:8px;flex-shrink:0;
    background:var(--P);color:#fff;border:none;
    font-size:12px;cursor:pointer;
    display:flex;align-items:center;justify-content:center;
    transition:.15s;
}
.nt-sbtn:hover { filter:brightness(1.1) }
.nt-clr {
    height:36px;padding:0 11px;flex-shrink:0;
    background:none;border:1px solid var(--DN-bg);
    border-radius:8px;color:var(--DN);font-size:11px;font-weight:600;
    display:flex;align-items:center;gap:4px;
    cursor:pointer;font-family:inherit;transition:.15s;white-space:nowrap;
    text-decoration:none;
}
.nt-clr:hover { background:var(--DN-bg) }
.nt-filters-r {
    margin-left:auto;font-size:11px;color:var(--txt2);
    white-space:nowrap;flex-shrink:0;
}

/* ── MEMBER LIST ── */
.nt-list {
    background:var(--card);border:1px solid var(--bdr);
    border-radius:14px;overflow:hidden;
    transition:background .25s;
    width:100%;box-sizing:border-box;
}
.nt-list-hdr {
    display:flex;align-items:center;justify-content:space-between;
    padding:11px 14px;border-bottom:1px solid var(--bdr);
    background:var(--bg3);
}
.nt-list-title {
    font-size:12.5px;font-weight:700;color:var(--txt);
    display:flex;align-items:center;gap:7px;
}
.nt-list-badge {
    font-size:10px;font-weight:700;padding:2px 8px;
    border-radius:10px;background:var(--P-bg);
    color:var(--P);border:1px solid rgba(var(--Pr),.2);
}

/* Member row — compact 2-line design */
.nt-member {
    display:flex;align-items:center;gap:10px;
    padding:10px 14px;border-bottom:1px solid var(--bdr);
    transition:background .12s;position:relative;
}
.nt-member:last-child { border-bottom:none }
.nt-member:hover { background:var(--P-bg) }

/* Left accent stripe on hover */
.nt-member::before {
    content:'';position:absolute;left:0;top:0;bottom:0;
    width:0;background:var(--P);transition:width .15s;
}
.nt-member:hover::before { width:3px }

/* Avatar with status indicator */
.nt-mav {
    width:38px;height:38px;border-radius:10px;flex-shrink:0;
    display:flex;align-items:center;justify-content:center;
    font-size:14px;font-weight:800;color:#fff;
    position:relative;
}
.nt-mav-dot {
    position:absolute;bottom:-2px;right:-2px;
    width:10px;height:10px;border-radius:50%;
    border:2px solid var(--card);
}
.nt-mav-dot.on  { background:var(--OK) }
.nt-mav-dot.off { background:var(--DN) }

/* Info — two lines */
.nt-minfo { flex:1;min-width:0 }
.nt-mname {
    font-size:12.5px;font-weight:700;color:var(--txt);
    white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
    display:flex;align-items:center;gap:6px;margin-bottom:3px;
}
.nt-mlvl {
    font-size:8px;font-weight:800;padding:1px 6px;
    border-radius:4px;color:#fff;flex-shrink:0;
    text-transform:uppercase;letter-spacing:.4px;
}
.nt-mmeta {
    font-size:10.5px;color:var(--txt2);
    display:flex;align-items:center;gap:8px;flex-wrap:wrap;
}
.nt-mmeta span { display:flex;align-items:center;gap:3px }
.nt-mmeta i    { font-size:8px;color:var(--txt3) }

/* Right — status + refs count */
.nt-mright { text-align:right;flex-shrink:0 }
.nt-mstatus {
    font-size:9px;font-weight:700;padding:2px 8px;
    border-radius:10px;text-transform:uppercase;
    letter-spacing:.3px;display:inline-block;margin-bottom:3px;
}
.nt-mstatus.active   { background:var(--OK-bg);color:var(--OK) }
.nt-mstatus.inactive { background:var(--DN-bg);color:var(--DN) }
.nt-mrefs {
    font-size:10px;color:var(--txt3);
    display:flex;align-items:center;gap:3px;justify-content:flex-end;
}

/* ── EMPTY ── */
.nt-empty { text-align:center;padding:44px 20px }
.nt-empty-ic {
    width:56px;height:56px;border-radius:14px;
    background:var(--bg3);border:1px solid var(--bdr);
    display:flex;align-items:center;justify-content:center;
    font-size:22px;color:var(--txt3);margin:0 auto 12px;
}
.nt-empty-t { font-size:14px;font-weight:700;color:var(--txt);margin-bottom:4px }
.nt-empty-s { font-size:12px;color:var(--txt2);line-height:1.6 }
.nt-empty-btn {
    display:inline-flex;align-items:center;gap:6px;
    margin-top:13px;padding:9px 18px;border-radius:9px;
    background:var(--P);color:#fff;font-size:12px;font-weight:700;
    border:none;cursor:pointer;font-family:inherit;text-decoration:none;
    transition:.15s;
}
.nt-empty-btn:hover { filter:brightness(1.1) }

/* ── PAGINATION ── */
.nt-pag {
    display:flex;justify-content:center;align-items:center;
    gap:5px;padding:11px 14px;border-top:1px solid var(--bdr);
}
.nt-pb {
    min-width:32px;height:32px;border-radius:7px;
    display:flex;align-items:center;justify-content:center;
    background:var(--card);border:1px solid var(--bdr);
    color:var(--txt2);font-size:12px;font-weight:600;
    text-decoration:none;transition:.15s;padding:0 7px;
}
.nt-pb:hover { border-color:rgba(var(--Pr),.3);color:var(--P);background:var(--P-bg) }
.nt-pb.on    { background:var(--P);color:#fff;border-color:transparent;font-weight:800 }
.nt-pd       { color:var(--txt3);padding:0 3px;font-size:12px }

/* ── TOAST ── */
.nt-toast {
    position:fixed;top:-80px;left:50%;transform:translateX(-50%);
    min-width:230px;max-width:calc(100vw - 28px);
    background:var(--card);border:1px solid var(--bdr);
    border-left:4px solid var(--P);border-radius:11px;
    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 28px rgba(0,0,0,.2);
}
.nt-toast.show { top:calc(var(--hh,52px) + 10px) }
.nt-toast-ic {
    width:24px;height:24px;border-radius:7px;background:var(--P);
    display:flex;align-items:center;justify-content:center;
    font-size:11px;color:#fff;flex-shrink:0;
}
.nt-toast span { font-size:12px;font-weight:600;color:var(--txt);flex:1 }
.nt-toast-x {
    position:absolute;right:9px;top:50%;transform:translateY(-50%);
    background:none;border:none;font-size:17px;color:var(--txt3);cursor:pointer;
}

@keyframes ntIn { from{opacity:0;transform:translateY(8px)} to{opacity:1;transform:none} }
.nt-score  { animation:ntIn .3s ease both }
.nt-invite { animation:ntIn .3s ease .04s both }
.nt-lvlbar { animation:ntIn .3s ease .07s both }
.nt-list   { animation:ntIn .3s ease .12s both }
</style>

<div class="nt">

    <!-- ── SCORECARD ── -->
    <div class="nt-score">
        <div class="nt-score-top">
            <div class="nt-score-title">
                <i class="fa-solid fa-diagram-project"></i>
                <?= htmlspecialchars($currentUser['username']) ?>'s Network
            </div>
            <button class="nt-share" onclick="ntCopy()">
                <i class="fa-solid fa-share-nodes"></i> Share
            </button>
        </div>

        <!-- 3 big numbers -->
        <div class="nt-nums">
            <div class="nt-num">
                <div class="nt-num-v"><?= number_format($totAll) ?></div>
                <div class="nt-num-l">Total</div>
            </div>
            <div class="nt-num">
                <div class="nt-num-v ok"><?= number_format($totAct) ?></div>
                <div class="nt-num-l">Active</div>
            </div>
            <div class="nt-num">
                <div class="nt-num-v dn"><?= number_format($totInact) ?></div>
                <div class="nt-num-l">Inactive</div>
            </div>
        </div>

        <!-- Rate meter -->
        <div class="nt-meter-lbl">
            <span>Activation Rate</span>
            <span><?= $actRate ?>%</span>
        </div>
        <div class="nt-meter-track">
            <div class="nt-meter-fill" id="ntMeter" style="width:0%"></div>
        </div>
    </div>

    <!-- ── INVITE STRIP ── -->
    <div class="nt-invite">
        <div class="nt-invite-ic"><i class="fa-solid fa-link"></i></div>
        <div class="nt-invite-url" id="ntRefLink"><?= htmlspecialchars($refLink) ?></div>
        <button class="nt-invite-copy" onclick="ntCopy()">Copy Link</button>
    </div>

    <!-- ── LEVEL BAR ── -->
    <div class="nt-lvlbar">
        <?php for($i=1;$i<=5;$i++): $lc=$lcColors[$i]; ?>
        <a href="?level=<?= $i ?>&status=<?= $statusFilter ?>&search=<?= urlencode($searchQuery) ?>"
           class="nt-lv <?= $levelFilter==$i?'on':'' ?>"
           style="--lc:<?= $lc ?>">
            <div class="nt-lv-n"><?= number_format($stats[$i]['total']) ?></div>
            <div class="nt-lv-l">L<?= $i ?></div>
            <div class="nt-lv-a"><?= $stats[$i]['active'] ?> ✓</div>
        </a>
        <?php endfor; ?>
    </div>

    <!-- ── FILTER STRIP ── -->
    <div class="nt-filters">
        <form method="GET">
            <select name="level" class="nt-sel" onchange="this.form.submit()">
                <option value="0" <?= $levelFilter==0?'selected':'' ?>>All</option>
                <option value="1" <?= $levelFilter==1?'selected':'' ?>>L1 Direct</option>
                <option value="2" <?= $levelFilter==2?'selected':'' ?>>L2</option>
                <option value="3" <?= $levelFilter==3?'selected':'' ?>>L3</option>
                <option value="4" <?= $levelFilter==4?'selected':'' ?>>L4</option>
                <option value="5" <?= $levelFilter==5?'selected':'' ?>>L5</option>
            </select>
            <select name="status" class="nt-sel" onchange="this.form.submit()">
                <option value="all"      <?= $statusFilter=='all'     ?'selected':'' ?>>All Status</option>
                <option value="active"   <?= $statusFilter=='active'  ?'selected':'' ?>>Active</option>
                <option value="inactive" <?= $statusFilter=='inactive'?'selected':'' ?>>Inactive</option>
            </select>
            <input type="text" name="search" class="nt-inp"
                   placeholder="Search..."
                   value="<?= htmlspecialchars($searchQuery) ?>">
            <button type="submit" class="nt-sbtn">
                <i class="fa-solid fa-magnifying-glass"></i>
            </button>
        </form>
        <?php if($searchQuery||$statusFilter!='all'||$levelFilter>0): ?>
        <a href="downlines.php" class="nt-clr"><i class="fa-solid fa-xmark"></i></a>
        <?php endif; ?>
        <span class="nt-filters-r"><?= number_format($totalCount) ?> found</span>
    </div>

    <!-- ── MEMBER LIST ── -->
    <div class="nt-list">
        <div class="nt-list-hdr">
            <div class="nt-list-title">
                <i class="fa-solid fa-users" style="color:var(--P);font-size:12px"></i>
                <?= $levelFilter>0 ? $lvlLabels[$levelFilter] : 'All Members' ?>
            </div>
            <span class="nt-list-badge"><?= number_format($totalCount) ?></span>
        </div>

        <?php if(empty($referrals)): ?>
        <div class="nt-empty">
            <div class="nt-empty-ic"><i class="fa-solid fa-user-plus"></i></div>
            <div class="nt-empty-t">No members yet</div>
            <div class="nt-empty-s">
                <?= $totAll==0
                    ? 'Share your invite link to grow your network.'
                    : 'No members match your filters.' ?>
            </div>
            <?php if($totAll==0): ?>
            <button class="nt-empty-btn" onclick="ntCopy()">
                <i class="fa-solid fa-share-nodes"></i> Copy Invite Link
            </button>
            <?php endif; ?>
        </div>

        <?php else:
            $avColors=['#6366f1','#06b6d4','#ec4899','#f59e0b','#10b981','#8b5cf6','#ef4444','#84cc16','#f97316','#0ea5e9'];
            foreach($referrals as $ref):
                $lvl   = isset($ref['level']) ? $ref['level'] : $levelFilter;
                $lc    = $lcColors[min($lvl,5)];
                $avCol = $avColors[ord(strtoupper($ref['username'][0])) % count($avColors)];
                $init  = strtoupper(substr($ref['username'],0,1));
                $isAct = $ref['status']==='active';
        ?>
        <div class="nt-member">
            <div class="nt-mav" style="background:<?= $avCol ?>">
                <?= $init ?>
                <span class="nt-mav-dot <?= $isAct?'on':'off' ?>"></span>
            </div>
            <div class="nt-minfo">
                <div class="nt-mname">
                    <?= htmlspecialchars($ref['username']) ?>
                    <?php if($levelFilter==0): ?>
                    <span class="nt-mlvl" style="background:<?= $lc ?>">L<?= $lvl ?></span>
                    <?php endif; ?>
                </div>
                <div class="nt-mmeta">
                    <?php if(!empty($ref['phone'])): ?>
                    <span><i class="fa-solid fa-phone"></i><?= htmlspecialchars($ref['phone']) ?></span>
                    <?php endif; ?>
                    <?php if(!empty($ref['country'])): ?>
                    <span><i class="fa-solid fa-location-dot"></i><?= htmlspecialchars($ref['country']) ?></span>
                    <?php endif; ?>
                    <span><i class="fa-regular fa-clock"></i><?= date('M j, Y', strtotime($ref['created_at'])) ?></span>
                </div>
            </div>
            <div class="nt-mright">
                <div class="nt-mstatus <?= $ref['status'] ?>"><?= ucfirst($ref['status']) ?></div>
                <div class="nt-mrefs">
                    <i class="fa-solid fa-sitemap" style="font-size:7px"></i>
                    <?= $ref['refs'] ?>
                </div>
            </div>
        </div>
        <?php endforeach; endif; ?>

        <!-- Pagination -->
        <?php if($totalPages>1): ?>
        <div class="nt-pag">
            <?php if($page>1): ?>
            <a href="?level=<?= $levelFilter ?>&status=<?= $statusFilter ?>&search=<?= urlencode($searchQuery) ?>&page=<?= $page-1 ?>" class="nt-pb">
                <i class="fa-solid fa-chevron-left" style="font-size:9px"></i>
            </a>
            <?php endif; ?>
            <?php
            $s=max(1,$page-2);$e=min($totalPages,$page+2);
            if($s>1){echo '<a href="?level='.$levelFilter.'&status='.$statusFilter.'&search='.urlencode($searchQuery).'&page=1" class="nt-pb">1</a>';if($s>2)echo '<span class="nt-pd">…</span>';}
            for($i=$s;$i<=$e;$i++) echo '<a href="?level='.$levelFilter.'&status='.$statusFilter.'&search='.urlencode($searchQuery).'&page='.$i.'" class="nt-pb '.($i===$page?'on':'').'">'.$i.'</a>';
            if($e<$totalPages){if($e<$totalPages-1)echo '<span class="nt-pd">…</span>';echo '<a href="?level='.$levelFilter.'&status='.$statusFilter.'&search='.urlencode($searchQuery).'&page='.$totalPages.'" class="nt-pb">'.$totalPages.'</a>';}
            ?>
            <?php if($page<$totalPages): ?>
            <a href="?level=<?= $levelFilter ?>&status=<?= $statusFilter ?>&search=<?= urlencode($searchQuery) ?>&page=<?= $page+1 ?>" class="nt-pb">
                <i class="fa-solid fa-chevron-right" style="font-size:9px"></i>
            </a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>

</div><!-- /.nt -->

<!-- Toast -->
<div class="nt-toast" id="ntToast">
    <div class="nt-toast-ic"><i class="fa-solid fa-check"></i></div>
    <span id="ntToastMsg">Link copied!</span>
    <button class="nt-toast-x" onclick="document.getElementById('ntToast').classList.remove('show')">×</button>
</div>

<script>
(function(){
    /* Animate meter on load */
    setTimeout(function(){
        var m = document.getElementById('ntMeter');
        if(m) m.style.width = '<?= $actRate ?>%';
    }, 300);

    var _t = null;
    function ntShowToast(msg) {
        var el = document.getElementById('ntToast');
        var tm = document.getElementById('ntToastMsg');
        clearTimeout(_t);
        tm.textContent = msg;
        el.classList.add('show');
        _t = setTimeout(function(){ el.classList.remove('show'); }, 3000);
    }

    window.ntCopy = function() {
        var url = document.getElementById('ntRefLink').textContent.trim();
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(url).then(function(){
                ntShowToast('Invite link copied!');
            }).catch(fb);
        } else { fb(); }
        function fb() {
            var a = document.createElement('textarea');
            a.value = url; a.style.cssText = 'position:fixed;left:-9999px';
            document.body.appendChild(a); a.select();
            try { document.execCommand('copy'); ntShowToast('Copied!'); } catch(e){}
            document.body.removeChild(a);
        }
    };
})();
</script>
<?php include 'footer.php'; ?>