<?php
require_once '../connection/db.php';
requireLogin();

$user     = getCurrentUser();
$memberId = (int)$user['member_id'];
$db       = getDB();

$page   = max(1,(int)($_GET['page']??1));
$limit  = 20;
$offset = ($page-1)*$limit;

$totalQ = $db->prepare('SELECT COUNT(*) AS c FROM meddolic_user_level_income WHERE memberId=?');
$totalQ->execute([$memberId]);
$totalRows  = (int)($totalQ->fetch()['c']??0);
$totalPages = (int)ceil($totalRows/$limit);

$incQ = $db->prepare("
    SELECT li.*, ud.user_id AS child_user_id, pl.poolName
    FROM meddolic_user_level_income li
    LEFT JOIN meddolic_user_details ud ON ud.member_id=li.childId
    LEFT JOIN meddolic_config_pool_list pl ON pl.id=li.packageId
    WHERE li.memberId=?
    ORDER BY li.dateTime DESC LIMIT ? OFFSET ?
");
$incQ->execute([$memberId,$limit,$offset]);
$incomes = $incQ->fetchAll();

$totalIncome = getLevelIncomeTotal($memberId);

// Level-wise breakdown
$lvlQ = $db->prepare('SELECT level, COUNT(*) AS cnt, SUM(levelIncome) AS total
    FROM meddolic_user_level_income WHERE memberId=? GROUP BY level ORDER BY level');
$lvlQ->execute([$memberId]);
$lvlBreakdown = $lvlQ->fetchAll();

$pageTitle  = 'Level Income';
$activePage = 'level_income';
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> Level Income</div>
        <h3>Level Income</h3>
        <div class="subtitle">Income from your downline team across all levels</div>
      </div>

      <div class="stats-grid" style="margin-bottom:20px">
        <div class="stat-card">
          <div class="stat-icon"><i class="fas fa-chart-line"></i></div>
          <div class="stat-info"><p>Total Level Income</p><h5 class="gold"><?= fmtUSD($totalIncome) ?></h5></div>
        </div>
        <div class="stat-card">
          <div class="stat-icon"><i class="fas fa-list"></i></div>
          <div class="stat-info"><p>Total Records</p><h5><?= number_format($totalRows) ?></h5></div>
        </div>
      </div>

      <!-- Level breakdown -->
      <?php if (!empty($lvlBreakdown)): ?>
      <div class="card" style="margin-bottom:16px">
        <div class="card-title"><i class="fas fa-layer-group"></i> Level-wise Breakdown</div>
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:10px">
          <?php foreach ($lvlBreakdown as $lb): ?>
          <div style="background:var(--dark3);border:1px solid var(--border);border-radius:8px;padding:12px;text-align:center">
            <div style="font-size:10px;color:#555;margin-bottom:5px">Level <?= (int)$lb['level'] ?></div>
            <div style="font-family:'Orbitron',sans-serif;font-size:13px;color:#f19107;font-weight:700">
              $<?= number_format($lb['total'],2) ?>
            </div>
            <div style="font-size:11px;color:#555;margin-top:3px"><?= $lb['cnt'] ?> records</div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>
      <?php endif; ?>

      <div class="card">
        <div class="card-title"><i class="fas fa-chart-line"></i> Level Income Details</div>
        <div class="table-responsive">
          <table class="data-table">
            <thead>
              <tr><th>#</th><th>From (User ID)</th><th>Package</th><th>Package Price</th><th>Level</th><th>%</th><th>Income</th><th>Date</th></tr>
            </thead>
            <tbody>
              <?php if (empty($incomes)): ?>
                <tr class="empty-row"><td colspan="8"><i class="fas fa-inbox"></i> No level income yet</td></tr>
              <?php else: foreach ($incomes as $i => $inc): ?>
              <tr>
                <td><?= $offset+$i+1 ?></td>
                <td class="amount"><?= e($inc['child_user_id']??'—') ?></td>
                <td><span class="badge badge-blue"><?= e($inc['poolName']??'Pkg '.$inc['packageId']) ?></span></td>
                <td>$<?= number_format($inc['packagePrice'],3) ?></td>
                <td><span class="badge badge-gold">L<?= (int)$inc['level'] ?></span></td>
                <td><?= number_format($inc['levelPercent'],2) ?>%</td>
                <td class="amount">$<?= number_format($inc['levelIncome'],5) ?></td>
                <td style="font-size:12px;color:var(--text-muted)"><?= date('d M Y H:i',strtotime($inc['dateTime'])) ?></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++): ?>
            <a href="?page=<?= $p ?>" 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>
