<?php
/**
 * User/PoolIncome.php  v11
 * Shows global matrix pool income from meddolic_user_pool_income
 * poolLevel=0 → Per-join income (when someone joins under you)
 * poolLevel=1 → L1 completion bonus (3 direct filled)
 * poolLevel=2 → L2 completion bonus (9 total filled) + triggers re-entry
 */
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_pool_income WHERE memberId=?');
$totalQ->execute([$memberId]);
$totalRows  = (int)($totalQ->fetch()['c'] ?? 0);
$totalPages = (int)ceil($totalRows / $limit);

$incQ = $db->prepare("
    SELECT pi.*, mp.poolName, mp.poolPrice
    FROM meddolic_user_pool_income pi
    LEFT JOIN meddolic_config_matrix_package mp ON mp.matrixId = pi.poolId
    WHERE pi.memberId = ?
    ORDER BY pi.dateTime DESC
    LIMIT ? OFFSET ?
");
$incQ->execute([$memberId, $limit, $offset]);
$incomes = $incQ->fetchAll();

$totalIncome = getPoolIncomeTotal($memberId);

// Per-pool summary
$summaryQ = $db->prepare("
    SELECT pi.poolId, mp.poolName, mp.poolPrice,
           SUM(pi.poolIncome) AS total,
           COUNT(*) AS cnt
    FROM meddolic_user_pool_income pi
    LEFT JOIN meddolic_config_matrix_package mp ON mp.matrixId = pi.poolId
    WHERE pi.memberId = ?
    GROUP BY pi.poolId
    ORDER BY pi.poolId ASC
");
$summaryQ->execute([$memberId]);
$poolSummary = $summaryQ->fetchAll();

$pageTitle  = 'Pool Income';
$activePage = 'pool_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> Pool Income</div>
        <h3>Auto Pool Income</h3>
        <div class="subtitle">Income from global 3×3 matrix pools</div>
      </div>

      <!-- Summary -->
      <div class="stats-grid" style="margin-bottom:20px">
        <div class="stat-card">
          <div class="stat-icon"><i class="fas fa-swimming-pool"></i></div>
          <div class="stat-info">
            <p>Total Pool 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>

      <!-- Per-pool summary -->
      <?php if (!empty($poolSummary)): ?>
      <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px;margin-bottom:20px">
        <?php foreach ($poolSummary as $ps): ?>
        <div class="card" style="padding:14px">
          <div style="font-size:10px;letter-spacing:1px;text-transform:uppercase;color:#555;margin-bottom:4px">
            <?= e($ps['poolName'] ?? 'Pool '.$ps['poolId']) ?>
          </div>
          <div style="font-size:20px;font-weight:700;color:var(--gold);font-family:'Orbitron',sans-serif">
            $<?= number_format((float)$ps['total'], 2) ?>
          </div>
          <div style="font-size:10px;color:#444;margin-top:3px"><?= (int)$ps['cnt'] ?> payments</div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>

      <div class="card">
        <div class="card-title"><i class="fas fa-swimming-pool"></i> Pool Income Details</div>
        <div class="table-responsive">
          <table class="data-table">
            <thead>
              <tr>
                <th>#</th>
                <th>Pool</th>
                <th>Type</th>
                <th>Fill Count</th>
                <th class="g">Net Income</th>
                <th>Date</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($incomes)): ?>
                <tr class="empty-row"><td colspan="6"><i class="fas fa-inbox"></i> No pool income yet</td></tr>
              <?php else: foreach ($incomes as $i => $inc):
                $lvl = (int)$inc['poolLevel'];
                if ($lvl === 0) {
                    $typeLabel = 'Join Income';
                    $typeBadge = 'badge-blue';
                    $typeIcon  = 'fas fa-user-plus';
                } elseif ($lvl === 1) {
                    $typeLabel = 'L1 Bonus (3 fills)';
                    $typeBadge = 'badge-gold';
                    $typeIcon  = 'fas fa-star';
                } else {
                    $typeLabel = 'L2 Bonus (9 fills)';
                    $typeBadge = 'badge-green';
                    $typeIcon  = 'fas fa-trophy';
                }
              ?>
              <tr>
                <td><?= $offset + $i + 1 ?></td>
                <td>
                  <span class="badge badge-gold"><?= e($inc['poolName'] ?? 'Pool '.$inc['poolId']) ?></span>
                  <div style="font-size:10px;color:#555;margin-top:1px">
                    $<?= number_format((float)($inc['poolPrice'] ?? 0), 0) ?> pool
                  </div>
                </td>
                <td>
                  <span class="badge <?= $typeBadge ?>" style="font-size:10px">
                    <i class="<?= $typeIcon ?>"></i> <?= $typeLabel ?>
                  </span>
                </td>
                <td style="font-size:12px;color:#666">
                  <?= $lvl === 0 ? '1 member' : ($lvl === 1 ? '3 members' : '9 members') ?>
                </td>
                <td class="amount" style="color:var(--success);font-weight:700;font-size:14px">
                  $<?= number_format((float)$inc['poolIncome'], 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>
