<?php
require_once '../connection/db.php';
requireLogin();
$user=getCurrentUser();$memberId=(int)$user['member_id'];$db=getDB();
$filterLevel=(int)($_GET['level']??0);
$page=max(1,(int)($_GET['page']??1));$limit=25;$offset=($page-1)*$limit;

$where=$filterLevel>0?'AND ci.level=?':'';
$params=$filterLevel>0?[$memberId,$filterLevel,$limit,$offset]:[$memberId,$limit,$offset];
$tWhere=$filterLevel>0?'AND level=?':'';
$tParams=$filterLevel>0?[$memberId,$filterLevel]:[$memberId];

$tQ=$db->prepare("SELECT COUNT(*) AS c FROM meddolic_user_child_ids WHERE member_id=? $tWhere");
$tQ->execute($tParams);$totalRows=(int)($tQ->fetch()['c']??0);$totalPages=(int)ceil($totalRows/$limit);

$teamQ=$db->prepare("SELECT ci.child_id, ci.level, ci.date_time, ci.topup_status, ci.topup_date,
    ud.user_id, ud.walletAddress, ud.activation_date, ud.currentPackage, pl.poolName
    FROM meddolic_user_child_ids ci
    LEFT JOIN meddolic_user_details ud ON ud.member_id=ci.child_id
    LEFT JOIN meddolic_config_pool_list pl ON pl.id=ud.currentPackage
    WHERE ci.member_id=? $where ORDER BY ci.level ASC, ci.date_time DESC LIMIT ? OFFSET ?");
$teamQ->execute($params);$team=$teamQ->fetchAll();

// Level distribution
$lvlDistQ=$db->prepare('SELECT level,COUNT(*) AS cnt FROM meddolic_user_child_ids WHERE member_id=? GROUP BY level ORDER BY level');
$lvlDistQ->execute([$memberId]);$lvlDist=$lvlDistQ->fetchAll();

$pageTitle='My Team';$activePage='team';require_once 'Include/header.php';
?>
<div class="layout"><?php require_once 'Include/menu.php';?>
<div class="main-content"><?php require_once 'Include/topbar.php';?>
<div class="page-content">
<div class="page-header">
  <div class="breadcrumb"><i class="fas fa-home"></i> <i class="fas fa-chevron-right"></i> My Team</div>
  <h3>My Team</h3><div class="subtitle">All downline members across all levels</div>
</div>
<div class="stats-grid" style="margin-bottom:16px">
  <div class="stat-card"><div class="stat-icon"><i class="fas fa-users"></i></div>
    <div class="stat-info"><p>Total Team</p><h5><?=number_format(array_sum(array_column($lvlDist,'cnt')))?></h5></div></div>
  <?php foreach($lvlDist as $ld):?>
  <div class="stat-card" onclick="window.location='?level=<?=(int)$ld['level']?>'" style="cursor:pointer">
    <div class="stat-icon"><i class="fas fa-layer-group"></i></div>
    <div class="stat-info"><p>Level <?=(int)$ld['level']?></p><h5><?=number_format($ld['cnt'])?></h5></div>
  </div>
  <?php endforeach;?>
</div>

<!-- Level filter -->
<div style="display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap">
  <a href="MyTeam.php" style="padding:7px 16px;border-radius:8px;font-size:12px;font-weight:700;text-decoration:none;background:<?=$filterLevel===0?'rgba(241,145,7,.2)':'var(--dark3)'?>;border:1px solid <?=$filterLevel===0?'rgba(241,145,7,.4)':'var(--border)'?>;color:<?=$filterLevel===0?'var(--gold)':'var(--text-muted)'?>">All Levels</a>
  <?php foreach($lvlDist as $ld):?>
  <a href="?level=<?=$ld['level']?>" style="padding:7px 16px;border-radius:8px;font-size:12px;font-weight:700;text-decoration:none;background:<?=$filterLevel==(int)$ld['level']?'rgba(241,145,7,.2)':'var(--dark3)'?>;border:1px solid <?=$filterLevel==(int)$ld['level']?'rgba(241,145,7,.4)':'var(--border)'?>;color:<?=$filterLevel==(int)$ld['level']?'var(--gold)':'var(--text-muted)'?>">
    Level <?=$ld['level']?>
  </a>
  <?php endforeach;?>
</div>

<div class="card">
  <div class="card-title"><i class="fas fa-users"></i> Team Members <?=$filterLevel?'(Level '.$filterLevel.')':''?></div>
  <div class="table-responsive"><table class="data-table">
    <thead><tr><th>#</th><th>User ID</th><th>Wallet</th><th>Level</th><th>Package</th><th>Join Date</th><th>Active Date</th><th>Status</th></tr></thead>
    <tbody>
    <?php if(empty($team)):?><tr class="empty-row"><td colspan="8"><i class="fas fa-inbox"></i> No team members yet</td></tr>
    <?php else:foreach($team as $i=>$t):?>
    <tr>
      <td><?=$offset+$i+1?></td>
      <td class="amount"><?=e($t['user_id']??'—')?></td>
      <td style="font-family:monospace;font-size:11px;color:#555"><?=e(substr($t['walletAddress']??'',0,12))?>…</td>
      <td><span class="badge badge-gold">L<?=(int)$t['level']?></span></td>
      <td><?=$t['poolName']?'<span class="badge badge-blue">'.e($t['poolName']).'</span>':'<span style="color:#444">—</span>'?></td>
      <td style="font-size:12px;color:var(--text-muted)"><?=date('d M Y',strtotime($t['date_time']))?></td>
      <td style="font-size:12px;color:var(--text-muted)"><?=$t['activation_date']?date('d M Y',strtotime($t['activation_date'])):'—'?></td>
      <td><?=(int)$t['topup_status']?'<span class="badge badge-green">Active</span>':'<span class="badge badge-red">Inactive</span>'?></td>
    </tr>
    <?php endforeach;endif;?>
    </tbody>
  </table></div>
  <?php if($totalPages>1):?><div style="display:flex;justify-content:center;gap:8px;margin-top:16px;flex-wrap:wrap">
    <?php for($p=1;$p<=$totalPages;$p++):$qs=$filterLevel?'&level='.$filterLevel:'';?><a href="?page=<?=$p.$qs?>" style="padding:6px 14px;border-radius:6px;font-size:13px;background:<?=$p==$page?'rgba(241,145,7,.2)':'var(--dark3)'?>;border:1px solid <?=$p==$page?'rgba(241,145,7,.4)':'var(--border)'?>;color:<?=$p==$page?'var(--gold)':'var(--text-muted)'?>;text-decoration:none"><?=$p?></a><?php endfor;?>
  </div><?php endif;?>
</div>
</div><?php require_once 'Include/footer.php';?></div></div>
