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

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

/* Pagination & Level Filter */
$filterLevel = (int) ($_GET['level'] ?? 0);
$page = max(1, (int) ($_GET['page'] ?? 1));
$limit = 25;
$offset = ($page - 1) * $limit;

/* GET Filters for Specific Entry */
$entryIdFilter = isset($_GET['entryId']) ? (int) $_GET['entryId'] : 0;
$poolIdFilter = isset($_GET['poolId']) ? (int) $_GET['poolId'] : 0;

/* Total Child Rows */
$tWhere = $filterLevel > 0 ? 'AND level=?' : '';
$tParams = $filterLevel > 0 ? [$memberId, $filterLevel] : [$memberId];
$tQ = $db->prepare("SELECT COUNT(*) AS c FROM meddolic_user_child_ids WHERE member_id=? $tWhere");
$tQ->execute($tParams);
$totalRows = (int) ($tQ->fetch(PDO::FETCH_ASSOC)['c'] ?? 0);
$totalPages = (int) ceil($totalRows / $limit);

/* Fetch Level Distribution */
$lvlDistQ = $db->prepare("SELECT level, COUNT(*) AS cnt FROM meddolic_user_child_ids WHERE member_id=? GROUP BY level ORDER BY level ASC");
$lvlDistQ->execute([$memberId]);
$lvlDist = $lvlDistQ->fetchAll(PDO::FETCH_ASSOC);

/* Fetch Pool Entries */
if ($entryIdFilter && $poolIdFilter) {
    // Specific entry from GET
    $teamQ = $db->prepare("
        SELECT entryId, poolId, poolLevel, entryDate
        FROM meddolic_user_pool_entry_details
        WHERE memberId = ? AND poolId = ? AND entryId = ? AND poolStatus = 1
        ORDER BY entryId ASC
        LIMIT ? OFFSET ?
    ");
    $teamQ->bindValue(1, $memberId, PDO::PARAM_INT);
    $teamQ->bindValue(2, $poolIdFilter, PDO::PARAM_INT);
    $teamQ->bindValue(3, $entryIdFilter, PDO::PARAM_INT);
    $teamQ->bindValue(4, $limit, PDO::PARAM_INT);
    $teamQ->bindValue(5, $offset, PDO::PARAM_INT);
} else {
    // All pool entries
    $teamQ = $db->prepare("
        SELECT entryId, poolId, poolLevel, entryDate
        FROM meddolic_user_pool_entry_details
        WHERE memberId = ? AND poolStatus = 1
        ORDER BY entryId ASC
        LIMIT ? OFFSET ?
    ");
    $teamQ->bindValue(1, $memberId, PDO::PARAM_INT);
    $teamQ->bindValue(2, $limit, PDO::PARAM_INT);
    $teamQ->bindValue(3, $offset, PDO::PARAM_INT);
}

$teamQ->execute();
$team = $teamQ->fetchAll(PDO::FETCH_ASSOC);

/* Helper Functions */
function poolStatusPDO(PDO $db, int $memberId, int $poolId, int $poolLevel): string
{
    $stmt = $db->prepare("SELECT COUNT(1) AS c FROM meddolic_user_pool_income WHERE memberId=? AND poolId=? AND poolLevel=?");
    $stmt->execute([$memberId, $poolId, $poolLevel]);
    return ($stmt->fetch(PDO::FETCH_ASSOC)['c'] ?? 0) > 0
        ? "<span class='badge badge-success'>ACHIEVED</span>"
        : "<span class='badge badge-warning'>PROCESSING</span>";
}

function achiveDatePDO(PDO $db, int $memberId, int $poolId, int $poolLevel): string
{
    $stmt = $db->prepare("SELECT dateTime FROM meddolic_user_pool_income WHERE memberId=? AND poolId=? AND poolLevel=? ORDER BY dateTime ASC LIMIT 1");
    $stmt->execute([$memberId, $poolId, $poolLevel]);
    $dt = $stmt->fetch(PDO::FETCH_ASSOC)['dateTime'] ?? '';
    return $dt ? "<i class='fa fa-clock-o'></i> " . date("d-m-Y H:i:s", strtotime($dt)) : '';
}

function countMembersPDO(PDO $db, int $memberId, int $poolId, int $poolLevel, int $entryId): int
{
    $stmt = $db->prepare("SELECT COUNT(1) AS totalMembers FROM meddolic_user_pool_placeholder_details WHERE member_id=? AND poolId=? AND parentEntryId=?");
    $stmt->execute([$memberId, $poolId, $entryId]);
    $totalMembers = (int) ($stmt->fetch(PDO::FETCH_ASSOC)['totalMembers'] ?? 0);

    $limit = pow(4, $poolLevel);
    $cumulativeLimit = 0;
    for ($i = 1; $i < $poolLevel; $i++)
        $cumulativeLimit += pow(4, $i);

    return $poolLevel > 1
        ? max(0, min($totalMembers - $cumulativeLimit, $limit))
        : min($totalMembers, $limit);
}

/* Page Header */
$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">

            <!-- Page Header -->
            <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 downline members across all levels</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>

            <div style="display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap">
                <?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>

            <!-- Pool Entries 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>Wallet Address</th>
                                <th>User Need</th>
                                <th>Pool No</th>
                                <th>Pool Level</th>
                                <th>Pool Income</th>
                                <th>Pool Status</th>
                                <th>Achieved Date</th>
                            </tr>
                        </thead>
                        <tbody>

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

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

                            <?php else: ?>

                                <?php
                                /* Fetch ALL pool configuration once */
                                $configQ = $db->prepare("
SELECT poolLevel, userNeed, matrixId, userIncome
FROM meddolic_config_pool_income
ORDER BY matrixId, poolLevel
");
                                $configQ->execute();
                                $poolConfigs = $configQ->fetchAll(PDO::FETCH_ASSOC);

                                /* Convert to indexed array */
                                $configMap = [];
                                foreach ($poolConfigs as $cfg) {
                                    $configMap[$cfg['matrixId']][] = $cfg;
                                }
                                ?>

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

                                    <?php
                                    $poolId = $t['poolId'];
                                    $entryId = $t['entryId'];

                                    /* get config for this pool */
                                    $levels = $configMap[$poolId] ?? [];
                                    ?>

                                    <?php foreach ($levels as $valPool):

                                        $currentPoolId = $valPool['matrixId'];

                                        $memberCount = countMembersPDO(
                                            $db,
                                            $memberId,
                                            $currentPoolId,
                                            $valPool['poolLevel'],
                                            $entryId
                                        );

                                        $poolStatus = poolStatusPDO(
                                            $db,
                                            $memberId,
                                            $currentPoolId,
                                            $valPool['poolLevel']
                                        );

                                        $achieveDate = achiveDatePDO(
                                            $db,
                                            $memberId,
                                            $currentPoolId,
                                            $valPool['poolLevel']
                                        );
                                        ?>

                                        <tr>

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

                                            <td><?= e($user['user_id']) ?></td>

                                            <td><?= e($user['walletAddress'] ?? '—') ?></td>

                                            <td>
                                                <?= $memberCount ?> /
                                                <?= $valPool['userNeed'] ?>
                                            </td>

                                            <td>
                                                Pool <?= $currentPoolId ?>
                                            </td>

                                            <td>
                                                Level <?= $valPool['poolLevel'] ?>
                                            </td>

                                            <td>
                                                <span class="badge badge-success">
                                                    $<?= number_format($valPool['userIncome'], 2) ?>
                                                </span>
                                            </td>

                                            <td>
                                                <?= $poolStatus ?>
                                            </td>

                                            <td>
                                                <?= $achieveDate ?>
                                            </td>

                                        </tr>

                                    <?php endforeach; ?>

                                <?php endforeach; ?>

                            <?php endif; ?>

                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if (!$entryIdFilter && $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>