<?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;


/* ------------------------------
   Level Distribution
------------------------------*/
$lvlDistQ = $db->prepare("
SELECT level, COUNT(*) cnt
FROM meddolic_user_child_ids
WHERE member_id = ?
GROUP BY level
ORDER BY level ASC
");

$lvlDistQ->execute([$memberId]);
$lvlDist = $lvlDistQ->fetchAll();


/* ------------------------------
   Total Rows for Pagination
------------------------------*/
if ($filterLevel > 0) {

  $tQ = $db->prepare("
    SELECT COUNT(*) c
    FROM meddolic_user_pool_entry_details
    WHERE memberId = ?
    AND poolLevel = ?
    AND poolStatus = 1
    ");

  $tQ->execute([$memberId, $filterLevel]);

} else {

  $tQ = $db->prepare("
    SELECT COUNT(*) c
    FROM meddolic_user_pool_entry_details
    WHERE memberId = ?
    AND poolStatus = 1
    ");

  $tQ->execute([$memberId]);

}

$totalRows = (int) $tQ->fetch()['c'];
$totalPages = ceil($totalRows / $limit);


/* ------------------------------
   Pool Entries Query
------------------------------*/
$sql = "
SELECT 
a.entryId,
a.poolId,
a.poolLevel,
a.entryDate,
b.user_id,
b.name
FROM meddolic_user_pool_entry_details a
JOIN meddolic_user_details b 
ON a.memberId = b.member_id
JOIN meddolic_config_pool_list c 
ON a.poolId = c.poolId
WHERE a.memberId = ?
AND a.poolStatus = 1
";

$params = [$memberId];

if ($filterLevel > 0) {
  $sql .= " AND a.poolLevel = ?";
  $params[] = $filterLevel;
}

$sql .= " ORDER BY a.entryId ASC LIMIT ? OFFSET ?";
$params[] = $limit;
$params[] = $offset;

$teamQ = $db->prepare($sql);
$teamQ->execute($params);
$team = $teamQ->fetchAll();


/* ------------------------------
   Total Investment Function
------------------------------*/
function totalInvest($db, $memberId)
{
  $q = $db->prepare("
    SELECT SUM(investAmount) total
    FROM meddolic_user_activation_details
    WHERE memberId = ?
    ");

  $q->execute([$memberId]);
  $r = $q->fetch();

  return $r['total'] ?? 0;
}


$pageTitle = 'Auto Pool Status';
$activePage = 'poolstatus';

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> Auto Pool Status
        </div>

        <h3>Pool Status</h3>

        <div class="subtitle">
          All pool entries of your account
        </div>
      </div>


      <!-- LEVEL STATS -->
      <div class="stats-grid" style="margin-bottom:16px">

        <?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="?"
          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
        </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>


      <!-- TABLE -->
      <div class="card">

        <div class="card-title">
          <i class="fas fa-layer-group"></i>
          Pool Entries
        </div>

        <div class="table-responsive">

          <table class="data-table">

            <thead>
              <tr>
                <th>#</th>
                <th>User ID</th>
                <th>Pool No.</th>
                <th>Entry Date</th>
                <th>Action</th>
              </tr>
            </thead>

            <tbody>

              <?php if (empty($team)): ?>

                <tr class="empty-row">
                  <td colspan="5">
                    <i class="fas fa-inbox"></i>
                    No pool entries yet
                  </td>
                </tr>

              <?php else: ?>

                <?php foreach ($team as $i => $t): ?>

                  <tr>

                    <td><?= $offset + $i + 1 ?></td>

                    <td class="amount">
                      <?= e($t['user_id'] ?? '—') ?>
                    </td>

                    <td>
                      <span class="badge badge-gold">
                        Pool <?= (int) $t['poolId'] ?>
                      </span>
                    </td>

                    <td style="font-size:12px;color:var(--text-muted)">
                      <?= date('d M Y', strtotime($t['entryDate'])) ?>
                    </td>

                    <td>
                      <a href="myPoolTeamStatus.php?userId=<?= $memberId ?>&entryId=<?= $t['entryId'] ?>&poolId=<?= $t['poolId'] ?>"
                        class="btn btn-primary btn-sm">
                        More
                      </a>
                    </td>

                  </tr>

                <?php endforeach; ?>

              <?php endif; ?>

            </tbody>

          </table>

        </div>


        <!-- PAGINATION -->
        <?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>