<?php
/**
 * User/ReferralIncome.php  v11
 * Shows referral income (direct sponsor income from meddolic_user_referral_income)
 * Pkg3: 60% of $60 = $36 to A1 (sponsor)
 * Pkg4: 60% of $200 = $120 to A1
 * Pkg5+: 30% of price to A1
 * Registration: $15 flat to sponsor
 */
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_referral_income WHERE memberId=? AND incomeType=2');
$totalQ->execute([$memberId]);
$totalRows = (int) ($totalQ->fetch()['c'] ?? 0);
$totalPages = (int) ceil($totalRows / $limit);

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

$totalIncome = getsponsorIncomeTotal($memberId);
$totalCount = $totalRows;

$pageTitle = 'Sponser Income';
$activePage = 'sponser_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> Sponsor Income</div>
        <h3>Sponsor Income</h3>
        <div class="subtitle"> sponsor income earned when your downline upgrades</div>
      </div>

      <!-- Summary cards -->
      <div class="stats-grid" style="margin-bottom:20px">
        <div class="stat-card">
          <div class="stat-icon"><i class="fas fa-coins"></i></div>
          <div class="stat-info">
            <p>Total Sponsor 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($totalCount) ?></h5>
          </div>
        </div>

      </div>

      <div class="card">
        <div class="card-title"><i class="fas fa-coins"></i> Sponsor 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>My % Rule</th>
                <th>Gross</th>
                <th>Admin Fee</th>
                <th class="g">Net Income</th>
                <th>Date</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($incomes)): ?>
                <tr class="empty-row">
                  <td colspan="9"><i class="fas fa-inbox"></i> No Sponsor income yet</td>
                </tr>
              <?php else:
                foreach ($incomes as $i => $inc):
                  $pkgId = (int) $inc['packageId'];
                  // Determine rule label
                  if ($pkgId <= 2)
                    $ruleLabel = 'Reg $15 flat';
                  elseif ($pkgId === 3)
                    $ruleLabel = '60% of $60';
                  elseif ($pkgId === 4)
                    $ruleLabel = '60% of $200';
                  else
                    $ruleLabel = '30% of $' . number_format((float) ($inc['pkg_price'] ?? 0), 0);
                  ?>
                  <tr>
                    <td><?= $offset + $i + 1 ?></td>
                    <td>
                      <span class="amount"><?= e($inc['child_user_id'] ?? '—') ?></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 badge-gold" style="font-size:10px"><?= $ruleLabel ?></span>
                    </td>
                    <td>$<?= number_format((float) $inc['referralIncome'], 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>