<?php
/**
 * User/UpgradeIncome.php  v11
 * Shows upline income from meddolic_user_upgrade_income
 * Pkg3: 40% to A2 (2nd upline from buyer)
 * Pkg4: 40% to A3 (3rd upline from buyer)
 * Pkg5+: 4% per level (10 levels) + 30% placement to A(n)
 */
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_upgrade_income WHERE memberId=?');
$totalQ->execute([$memberId]);
$totalRows = (int) ($totalQ->fetch()['c'] ?? 0);
$totalPages = (int) ceil($totalRows / $limit);

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

$totalIncome = getUpgradeIncomeTotal($memberId);

$pageTitle = 'Upline Income';
$activePage = 'upgrade_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> Upline Income</div>
        <h3>Upline Income</h3>
        <div class="subtitle">Income received as upline when your downline buys packages</div>
      </div>

      <!-- Summary -->
      <div class="stats-grid" style="margin-bottom:20px">
        <div class="stat-card">
          <div class="stat-icon"><i class="fas fa-arrow-up"></i></div>
          <div class="stat-info">
            <p>Total Upline 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 class="stat-card" style="grid-column:span 2">
          <div class="stat-icon"><i class="fas fa-info-circle"></i></div>
          <div class="stat-info">
            <p>Income Rules</p>
            <h5 style="font-size:10px;color:#888;line-height:1.6">
              Pkg3 ($60): 40% to A2 &nbsp;|&nbsp;
              Pkg4 ($200): 40% to A3 &nbsp;|&nbsp;
              Pkg5+ : 4% per level (10 levels) + 30% placement
            </h5>
          </div>
        </div> -->
      </div>

      <div class="card">
        <div class="card-title"><i class="fas fa-arrow-up"></i> Upline Income Details</div>
        <div class="table-responsive">
          <table class="data-table">
            <thead>
              <tr>
                <th>#</th>
                <th>From (User)</th>
                <th>Package</th>
                <th>Pkg Price</th>
                <th>Type</th>
                <th>Level</th>
                <th>%</th>
                <th>Gross</th>
                <th>Admin</th>
                <th class="g">Net</th>
                <th>Date</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($incomes)): ?>
                <tr class="empty-row">
                  <td colspan="11"><i class="fas fa-inbox"></i> No upline income yet</td>
                </tr>
              <?php else:
                foreach ($incomes as $i => $inc):
                  $lvl = (int) $inc['level'];
                  $pct = (float) $inc['upgradePercent'];
                  $pkgId = (int) $inc['packageId'];

                  if ($pct >= 30.0 && $lvl > 0) {
                    $typeLabel = 'Placement';
                    $typeBadge = 'badge-gold';
                  } elseif ($pkgId <= 4) {
                    $typeLabel = 'Upline ' . ($pkgId === 3 ? 'A2' : 'A3');
                    $typeBadge = 'badge-blue';
                  } else {
                    $typeLabel = 'Level Dist.';
                    $typeBadge = 'badge-blue';
                  }
                  ?>
                  <tr>
                    <td><?= $offset + $i + 1 ?></td>
                    <td>
                      <span class="amount"><?= e($inc['child_uid'] ?? '—') ?></span>
                      <?php if ($inc['child_wallet']): ?>
                        <div style="font-family:monospace;font-size:10px;color:#444;margin-top:1px">
                          <?= e(substr($inc['child_wallet'], 0, 10)) ?>…
                        </div>
                      <?php endif; ?>
                    </td>
                    <td>
                      <span class="badge badge-blue"><?= e($inc['poolName'] ?? 'Pkg ' . $pkgId) ?></span>
                    </td>
                    <td>$<?= number_format((float) ($inc['packagePrice'] ?? 0), 0) ?></td>
                    <td>
                      <span class="badge <?= $typeBadge ?>" style="font-size:10px"><?= $typeLabel ?></span>
                    </td>
                    <td>
                      <?php if ($lvl > 0): ?>
                        <span class="badge badge-gold" style="font-size:10px">L<?= $lvl ?></span>
                      <?php else: ?>
                        <span style="color:#333">—</span>
                      <?php endif; ?>
                    </td>
                    <td><?= number_format($pct, 0) ?>%</td>
                    <td>$<?= number_format((float) $inc['upgradeIncome'], 2) ?></td>
                    <td style="color:var(--danger)">$<?= number_format((float) $inc['adminCharge'], 2) ?></td>
                    <td class="amount" style="color:var(--success);font-weight:700">
                      $<?= number_format((float) $inc['netIncome'], 2) ?>
                    </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>
