<?php

require_once '../connection/db.php';
require_once '../connection/MatrixEngine.php';
requireLogin();




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


// Working tree
$workingTree = $engine->getWorkingMatrixTree($memberId);

// Global matrix trees
$matrixPkgs = getMatrixPackages();
$globalTrees = [];
foreach ($matrixPkgs as $mp) {
  $globalTrees[(int) $mp['matrixId']] = $engine->getGlobalMatrixTree($memberId, (int) $mp['matrixId']);
}

// Team counts for auto-upgrade progress
$stL1 = $db->prepare("SELECT COUNT(*) FROM meddolic_user_set_placeholder_details WHERE member_id=? AND level=1");
$stL1->execute([$memberId]);
$l1cnt = (int) $stL1->fetchColumn();

$stL2 = $db->prepare("SELECT COUNT(*) FROM meddolic_user_set_placeholder_details WHERE member_id=? AND level BETWEEN 1 AND 2");
$stL2->execute([$memberId]);
$l2cnt = (int) $stL2->fetchColumn();

$stL3 = $db->prepare("
    SELECT COUNT(*) FROM meddolic_user_set_placeholder_details p
    JOIN meddolic_user_details ud ON p.child_id = ud.member_id
    WHERE p.member_id=? AND p.level BETWEEN 1 AND 3 AND ud.topup_flag=1
");
$stL3->execute([$memberId]);
$l3cnt = (int) $stL3->fetchColumn();

$curPkgId = (int) ($user['currentPackage'] ?? 0);
$allPkgs = getPoolList();

$incPrev = [];
foreach ($allPkgs as $p) {
  $incPrev[(int) $p['id']] = $engine->calculateIncomePreview((int) $p['id'], (float) $p['upgradePrice']);
}

$auQ = $db->prepare("
    SELECT au.*, p1.poolName AS from_name, p1.upgradePrice AS from_price,
           p2.poolName AS to_name, p2.upgradePrice AS to_price
    FROM gm_auto_upgrades au
    LEFT JOIN meddolic_config_pool_list p1 ON p1.id = au.from_pkg_id
    LEFT JOIN meddolic_config_pool_list p2 ON p2.id = au.to_pkg_id
    WHERE au.member_id=? ORDER BY au.created_at DESC
");
$auQ->execute([$memberId]);
$autoUpgrades = $auQ->fetchAll();

$poolIncomes = [];
foreach ($matrixPkgs as $mp) {
  $piQ = $db->prepare("SELECT * FROM meddolic_user_pool_income WHERE memberId=? AND poolId=? ORDER BY dateTime ASC");
  $piQ->execute([$memberId, $mp['matrixId']]);
  $poolIncomes[(int) $mp['matrixId']] = $piQ->fetchAll();
}

$pageTitle = 'Matrix Tree';
$activePage = 'tree';
require_once 'Include/header.php';

// ── Helper: recursively build tree HTML with connecting lines ─────────────
function renderTreeNode(array $nodeData, array $allNodes, int $depth = 0): string
{
  $uid = htmlspecialchars($nodeData['user_id'] ?? '');
  $active = (int) ($nodeData['topup_flag'] ?? 0);
  $pkg = (int) ($nodeData['currentPackage'] ?? 0);
  $mid = (int) ($nodeData['member_id'] ?? 0);

  // Get children of this node from allNodes, sorted by leg_pos
  $myChildren = [];
  foreach ($allNodes as $nid => $n) {
    if ((int) $n['parent_id'] === $mid) {
      $myChildren[$n['leg_pos']] = $n;
    }
  }
  ksort($myChildren);

  $nodeClass = $active ? 'tnode-v active' : 'tnode-v pending';
  $statusIcon = $active ? '✅' : '⏳';
  $depthColor = $depth === 0 ? '#22c55e' : ($depth === 1 ? '#3b82f6' : ($depth === 2 ? '#a855f7' : '#6b7280'));

  $childrenHtml = '';
  if (!empty($myChildren)) {
    $childrenHtml = '<div class="tree-children">';
    foreach ($myChildren as $leg => $child) {
      $childrenHtml .= '<div class="tree-child-wrap">';
      $childrenHtml .= renderTreeNode($child, $allNodes, $depth + 1);
      $childrenHtml .= '</div>';
    }
    $childrenHtml .= '</div>';
  }

  $pkgLabel = $pkg > 0 ? "S{$pkg}" : '';

  return "
    <div class='tree-node-wrap'>
      <div class='{$nodeClass}' style='border-color:{$depthColor}44'>
        <div class='tnode-avatar' style='background:{$depthColor}22;border:2px solid {$depthColor}66'>
          <i class='fas fa-user' style='color:{$depthColor};font-size:14px'></i>
        </div>
        <div class='tnode-uid'>{$uid}</div>
        <div class='tnode-status'>{$statusIcon} " . ($active ? 'Active' : 'Inactive') . "</div>
        " . ($pkgLabel ? "<div class='tnode-pkg' style='color:{$depthColor}'>{$pkgLabel}</div>" : '') . "
      </div>
      {$childrenHtml}
    </div>";
}
?>

<style>
  /* ── Base ─────────────────────────────────────────── */
  .tree-wrap {
    overflow-x: auto;
    overflow-y: visible;
    padding: 16px 8px;
    min-width: 300px
  }

  .tree-scroll {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch
  }

  /* ── Tree node cards ──────────────────────────────── */
  .tnode-v {
    background: var(--dark3);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 10px 12px;
    text-align: center;
    min-width: 80px;
    max-width: 100px;
    font-size: 11px;
    transition: .15s;
    position: relative;
    display: inline-block
  }

  .tnode-v.active {
    background: rgba(34, 197, 94, .05)
  }

  .tnode-v.pending {
    opacity: .6
  }

  .tnode-root-v {
    background: rgba(241, 145, 7, .1);
    border: 2px solid rgba(241, 145, 7, .6);
    border-radius: 12px;
    padding: 12px 20px;
    text-align: center;
    display: inline-block
  }

  .tnode-root-v .root-uid {
    font-family: 'Orbitron', sans-serif;
    font-size: 13px;
    font-weight: 700;
    color: var(--gold)
  }

  .tnode-root-v .root-sub {
    font-size: 10px;
    color: #888;
    margin-top: 3px
  }

  .tnode-avatar {
    width: 34px;
    height: 34px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 6px
  }

  .tnode-uid {
    font-family: 'Orbitron', sans-serif;
    font-size: 10px;
    color: var(--gold);
    font-weight: 700;
    word-break: break-all
  }

  .tnode-status {
    font-size: 9px;
    color: var(--text-muted);
    margin-top: 3px
  }

  .tnode-pkg {
    font-size: 9px;
    font-weight: 700;
    margin-top: 2px
  }

  /* ── Tree layout (CSS flexbox tree with connectors) ──────────────────── */
  .tree-root-row {
    display: flex;
    justify-content: center;
    margin-bottom: 0
  }

  .tree-node-wrap {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative
  }

  /* Vertical line down from node to children bar */
  .tree-node-wrap>.tree-children::before {
    content: '';
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 2px;
    height: 20px;
    background: #333
  }

  .tree-children {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    justify-content: center;
    gap: 0;
    position: relative;
    margin-top: 0;
    padding-top: 20px
  }

  /* Horizontal bar connecting siblings */
  .tree-children::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 2px;
    background: #333;
    /* Only draw between first and last child */
    margin: 0 calc(50px + 6px)
  }

  .tree-child-wrap {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    padding: 0 6px
  }

  /* Vertical drop line from bar to each child */
  .tree-child-wrap::before {
    content: '';
    position: absolute;
    top: -20px;
    left: 50%;
    transform: translateX(-50%);
    width: 2px;
    height: 20px;
    background: #333
  }

  /* Stem from root node down */
  .tree-stem {
    width: 2px;
    height: 24px;
    background: #333;
    margin: 0 auto
  }

  /* ── Level badges ─────────────────────────────────── */
  .lvl-badge {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    font-size: 10px;
    letter-spacing: 1.5px;
    text-transform: uppercase;
    color: #555;
    background: var(--dark3);
    border: 1px solid var(--border);
    border-radius: 20px;
    padding: 4px 14px;
    margin: 12px auto;
    white-space: nowrap
  }

  .lvl-badge .cnt {
    color: var(--gold);
    font-weight: 700;
    font-family: 'Orbitron', sans-serif
  }

  /* ── Progress bars ────────────────────────────────── */
  .pbar-bg {
    background: var(--dark3);
    border-radius: 6px;
    height: 7px;
    overflow: hidden;
    margin-top: 5px
  }

  .pbar {
    height: 100%;
    border-radius: 6px;
    background: linear-gradient(90deg, #f19107, #c97800);
    transition: width .5s
  }

  /* ── Pool cards ───────────────────────────────────── */
  .pool-card {
    background: var(--dark3);
    border-radius: 12px;
    padding: 16px;
    border: 1px solid var(--border)
  }

  .pool-card.enrolled {
    border-color: var(--border-glow)
  }

  .slot {
    flex: 1;
    border-radius: 6px;
    padding: 5px 4px;
    text-align: center;
    font-size: 10px;
    border: 1px solid rgba(255, 255, 255, .06);
    background: rgba(255, 255, 255, .02)
  }

  .slot.fill {
    background: rgba(34, 197, 94, .09);
    border-color: rgba(34, 197, 94, .3)
  }

  .slot.fill2 {
    background: rgba(59, 130, 246, .09);
    border-color: rgba(59, 130, 246, .28)
  }

  /* ── Income table ─────────────────────────────────── */
  .ict th,
  .ict td {
    padding: 9px 12px;
    font-size: 12px
  }

  .ict .g {
    color: var(--success)
  }

  .ict .b {
    color: #3b82f6
  }

  .ict .r {
    color: var(--danger)
  }

  .trigger-badge {
    background: rgba(59, 130, 246, .14);
    color: #3b82f6;
    border-radius: 4px;
    padding: 2px 7px;
    font-size: 10px;
    font-weight: 700
  }

  /* ── Empty state ──────────────────────────────────── */
  .tree-empty {
    text-align: center;
    padding: 32px 16px;
    color: #444;
    font-size: 13px
  }

  .tree-empty i {
    font-size: 32px;
    color: #2a2a2a;
    margin-bottom: 12px;
    display: block
  }

  /* ── Depth color legend ───────────────────────────── */
  .depth-legend {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    margin-bottom: 14px;
    font-size: 11px
  }

  .dl-item {
    display: flex;
    align-items: center;
    gap: 5px
  }

  .dl-dot {
    width: 10px;
    height: 10px;
    border-radius: 50%
  }

  @media (max-width:768px) {
    .tnode-v {
      min-width: 65px;
      max-width: 80px;
      padding: 7px 8px
    }

    .tnode-uid {
      font-size: 9px
    }

    .tree-children {
      gap: 0
    }

    .tree-child-wrap {
      padding: 0 3px
    }
  }

  .pslot-l2 {
    width: 32px;
    font-size: 8px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>

<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> Matrix Tree</div>
        <h3>Matrix Tree &amp; Pool Status</h3>
        <div class="subtitle">Working 3×3 plan · Global auto-pools · Income calculator</div>
      </div>

      <!-- ══ AUTO-UPGRADE PROGRESS ═══════════════════════════════════ -->
      <div class="card" style="margin-bottom:16px">
        <div class="card-title"><i class="fas fa-bolt"></i> Auto-Upgrade Progress (Working Plan)</div>
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(185px,1fr));gap:12px">

          <?php
          $tiers = [
            ['label' => '3 Directs (L1)', 'count' => $l1cnt, 'need' => 3, 'note' => '3rd direct → Next step auto-purchased'],
            ['label' => '9 Team (L1+L2)', 'count' => $l2cnt, 'need' => 9, 'note' => '3×3 filled → Next step auto-purchased'],
            ['label' => '27 Team (L1-L3)', 'count' => $l3cnt, 'need' => 27, 'note' => '3×3×3 full → Next step auto-purchased'],
          ];
          foreach ($tiers as $t):
            $pct = min(100, $t['need'] > 0 ? round($t['count'] / $t['need'] * 100) : 0);
            $done = $t['count'] >= $t['need'];
            ?>
              <div style="background:var(--dark3);border-radius:10px;padding:14px;
                      border:1px solid <?= $done ? 'rgba(34,197,94,.25)' : 'var(--border)' ?>">
                <div style="font-size:10px;letter-spacing:1px;text-transform:uppercase;color:#555;margin-bottom:5px">
                  <?= $t['label'] ?>
                </div>
                <div style="font-size:22px;font-weight:700;font-family:'Orbitron',sans-serif;
                        color:<?= $done ? 'var(--success)' : 'var(--gold)' ?>">
                  <?= $t['count'] ?><span style="font-size:13px;color:#555"> / <?= $t['need'] ?></span>
                  <?= $done ? ' ✅' : '' ?>
                </div>
                <div class="pbar-bg">
                  <div class="pbar" style="width:<?= $pct ?>%"></div>
                </div>
                <div style="font-size:10px;color:#444;margin-top:6px"><?= $t['note'] ?></div>
              </div>
          <?php endforeach; ?>

          <?php
          $cp = null;
          $np = null;
          foreach ($allPkgs as $p) {
            if ((int) $p['id'] === $curPkgId)
              $cp = $p;
            if ((int) $p['id'] === $curPkgId + 1)
              $np = $p;
          }
          ?>
          <div
            style="background:rgba(241,145,7,.06);border:1px solid rgba(241,145,7,.2);border-radius:10px;padding:14px">
            <div style="font-size:10px;letter-spacing:1px;text-transform:uppercase;color:#555;margin-bottom:5px">Current
              Step</div>
            <div style="font-family:'Orbitron',sans-serif;font-size:20px;font-weight:700;color:var(--gold)">
              <?= $cp ? '$' . number_format($cp['upgradePrice'], 0) : 'None' ?>
            </div>
            <div style="font-size:11px;color:#888;margin-top:3px"><?= $cp ? e($cp['poolName']) : 'Not started' ?></div>
            <?php if ($np): ?>
                <div
                  style="font-size:10px;color:#555;margin-top:6px;border-top:1px solid rgba(255,255,255,.05);padding-top:6px">
                  Next: $<?= number_format($np['upgradePrice'], 0) ?>
                </div>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <!-- ══ WORKING MATRIX TREE ═══════════════════════════════════════ -->
      <div class="card" style="margin-bottom:16px">
        <div class="card-title">
          <i class="fas fa-sitemap"></i> Working Matrix Tree
          <span style="font-size:11px;color:#555;font-weight:400;margin-left:8px">
            — 3×3 BFS structure · <?= $workingTree['total'] ?? 0 ?> total members
          </span>
        </div>

        <!-- Depth color legend -->
        <div class="depth-legend">
          <div class="dl-item">
            <div class="dl-dot" style="background:#f19107"></div><span style="color:#888">YOU</span>
          </div>
          <div class="dl-item">
            <div class="dl-dot" style="background:#22c55e"></div><span style="color:#888">Level 1 (Direct)</span>
          </div>
          <div class="dl-item">
            <div class="dl-dot" style="background:#3b82f6"></div><span style="color:#888">Level 2</span>
          </div>
          <div class="dl-item">
            <div class="dl-dot" style="background:#a855f7"></div><span style="color:#888">Level 3</span>
          </div>
          <div class="dl-item">
            <div class="dl-dot" style="background:#6b7280"></div><span style="color:#888">Level 4+</span>
          </div>
        </div>

        <div class="tree-scroll">
          <div class="tree-wrap">

            <?php
            $treeNodes = $workingTree['tree'] ?? [];
            $allNodes = $workingTree['nodes'] ?? [];
            $totalMembers = $workingTree['total'] ?? 0;
            ?>

            <!-- ROOT NODE -->
            <div class="tree-root-row">
              <div class="tnode-root-v">
                <div style="width:42px;height:42px;border-radius:50%;background:rgba(241,145,7,.2);
                          border:2px solid rgba(241,145,7,.6);display:flex;align-items:center;
                          justify-content:center;margin:0 auto 8px">
                  <i class="fas fa-user" style="color:var(--gold);font-size:16px"></i>
                </div>
                <div class="root-uid"><?= e($user['user_id'] ?? 'YOU') ?></div>
                <div class="root-sub">YOU · <?= $totalMembers ?> downline</div>
              </div>
            </div>

            <?php if (empty($treeNodes)): ?>
                <div class="tree-empty">
                  <i class="fas fa-users"></i>
                  No team members yet.<br>
                  <span style="font-size:11px;color:#333">Share your referral link to start building your matrix.</span>
                </div>
            <?php else: ?>

                <!-- Stem line from root to L1 -->
                <div class="tree-stem"></div>

                <!-- LEVEL 1 LABEL -->
                <div style="text-align:center">
                  <span class="lvl-badge">
                    Level 1 (Direct)
                    <span class="cnt"><?= count(array_filter($treeNodes)) ?></span> / 3
                  </span>
                </div>

                <!-- RECURSIVE TREE starting from L1 children -->
                <div style="overflow-x:auto; padding-bottom:16px">
                  <div class="tree-children" style="padding-top:16px;margin-top:0">
                    <?php foreach ($treeNodes as $leg => $childNode): ?>
                        <div class="tree-child-wrap">
                          <?= renderTreeNode($childNode, $allNodes, 0) ?>
                        </div>
                    <?php endforeach; ?>

                    <!-- Show empty L1 slots if < 3 directs -->
                    <?php for ($emptyLeg = count($treeNodes) + 1; $emptyLeg <= 3; $emptyLeg++): ?>
                        <div class="tree-child-wrap">
                          <div class="tnode-v pending" style="opacity:.2;min-width:80px">
                            <div class="tnode-avatar" style="background:rgba(255,255,255,.03);border:2px dashed #333">
                              <i class="fas fa-plus" style="color:#333;font-size:12px"></i>
                            </div>
                            <div style="font-size:9px;color:#333;margin-top:4px">Empty</div>
                          </div>
                        </div>
                    <?php endfor; ?>
                  </div>
                </div>

                <!-- Level summary stats below tree -->
                <?php
                $levelMap = $workingTree['levelMap'] ?? [];
                if (!empty($levelMap)):
                  ?>
                    <div style="border-top:1px solid var(--border);margin-top:16px;padding-top:14px">
                      <div
                        style="font-size:10px;letter-spacing:1px;text-transform:uppercase;color:#444;margin-bottom:10px;text-align:center">
                        Level Summary
                      </div>
                      <div style="display:flex;gap:8px;flex-wrap:wrap;justify-content:center">
                        <?php foreach ($levelMap as $lvl => $memberIds): ?>
                            <div style="background:var(--dark3);border:1px solid var(--border);border-radius:8px;
                            padding:8px 14px;text-align:center;min-width:70px">
                              <div style="font-size:9px;color:#555;text-transform:uppercase;letter-spacing:1px">L<?= $lvl ?></div>
                              <div style="font-size:18px;font-weight:700;font-family:'Orbitron',sans-serif;
                              color:var(--gold);margin:2px 0"><?= count($memberIds) ?></div>
                              <div style="font-size:9px;color:#333">of <?= (int) pow(3, $lvl) ?></div>
                              <div class="pbar-bg" style="margin-top:4px">
                                <div class="pbar"
                                  style="width:<?= min(100, round(count($memberIds) / pow(3, $lvl) * 100)) ?>%;
                      <?= count($memberIds) >= pow(3, $lvl) ? 'background:linear-gradient(90deg,#22c55e,#15803d)' : '' ?>">
                                </div>
                              </div>
                            </div>
                        <?php endforeach; ?>
                      </div>
                    </div>
                <?php endif; ?>

            <?php endif; // end if treeNodes not empty ?>

          </div><!-- /tree-wrap -->
        </div><!-- /tree-scroll -->
      </div>

      <!-- ══ GLOBAL MATRIX POOLS ════════════════════════════════════════ -->
      <div class="card" style="margin-bottom:16px">
        <div class="card-title"><i class="fas fa-th"></i> Global Matrix Pools (3×3 BFS — Auto-Pool &amp; Re-Entry)</div>

        <style>
          /* Pool grid */
          .pool-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(310px, 1fr));
            gap: 16px
          }

          /* Pool card */
          .pool-card {
            background: var(--dark3);
            border-radius: 14px;
            padding: 18px;
            border: 1px solid var(--border);
            transition: .2s
          }

          .pool-card.enrolled {
            border-color: var(--border-glow)
          }

          /* 3-level pool tree */
          .pool-tree {
            margin: 12px 0 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 0
          }

          /* Level label row */
          .ptree-label {
            font-size: 9px;
            letter-spacing: 1.5px;
            text-transform: uppercase;
            color: #444;
            margin-bottom: 5px;
            text-align: center
          }

          /* Each row of slots */
          .ptree-row {
            display: flex;
            gap: 4px;
            justify-content: center;
            position: relative;
            margin-bottom: 0
          }

          /* Connector lines between rows */
          .ptree-connector {
            width: 2px;
            height: 14px;
            background: #2a2a2a;
            margin: 0 auto
          }

          .ptree-connector-row {
            display: flex;
            justify-content: center;
            gap: 0;
            position: relative;
            height: 14px;
            margin: 0 auto;
          }

          .ptree-connector-row::before {
            content: '';
            position: absolute;
            top: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 2px;
            height: 100%;
            background: #2a2a2a
          }

          /* Individual slot */
          .pslot {
            border-radius: 6px;
            padding: 4px 3px;
            text-align: center;
            font-size: 9px;
            font-family: 'Orbitron', sans-serif;
            font-weight: 600;
            border: 1px solid #1a1a1a;
            background: rgba(255, 255, 255, .02);
            color: #2a2a2a;
            min-width: 0;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            transition: .15s
          }

          /* L1 slots — wider */
          .pslot-l1 {
            width: 88px;
            font-size: 10px;
            padding: 6px 4px
          }

          /* L2 slots — medium */
          .pslot-l2 {
            width: 28px
          }

          /* L3 slots — tiny dot */
          .pslot-l3 {
            width: 8px;
            height: 8px;
            padding: 0;
            border-radius: 50%;
            font-size: 0
          }

          /* Filled states */
          .pslot.f1 {
            background: rgba(34, 197, 94, .12);
            border-color: rgba(34, 197, 94, .35);
            color: #22c55e
          }

          .pslot.f2 {
            background: rgba(59, 130, 246, .12);
            border-color: rgba(59, 130, 246, .30);
            color: #3b82f6
          }

          .pslot.f3 {
            background: rgba(168, 85, 247, .15);
            border-color: rgba(168, 85, 247, .35);
            color: #a855f7
          }

          /* Income summary */
          .pool-income-row {
            display: flex;
            justify-content: space-between;
            font-size: 11px;
            margin-bottom: 3px;
            padding: 2px 0
          }

          .pool-income-total {
            display: flex;
            justify-content: space-between;
            font-size: 12px;
            font-weight: 700;
            border-top: 1px solid rgba(255, 255, 255, .06);
            margin-top: 6px;
            padding-top: 6px
          }

          /* Progress mini bar */
          .mini-prog {
            display: flex;
            gap: 3px;
            margin-top: 10px
          }

          .mini-prog-item {
            flex: 1;
            text-align: center;
            font-size: 9px
          }

          .mini-prog-bar {
            height: 4px;
            border-radius: 4px;
            background: #1a1a1a;
            margin-top: 3px;
            overflow: hidden
          }

          .mini-prog-fill {
            height: 100%;
            border-radius: 4px;
            transition: width .4s
          }
        </style>

        <?php $poolColors = [1 => '#f59e0b', 2 => '#94a3b8', 3 => '#eab308', 4 => '#8b5cf6', 5 => '#06b6d4', 6 => '#64748b', 7 => '#f43f5e', 8 => '#10b981']; ?>
        <div class="pool-grid">
          <?php foreach ($matrixPkgs as $mp):
            $mid = (int) $mp['matrixId'];
            $gt = $globalTrees[$mid] ?? ['entry' => null, 'levels' => [], 're_entries' => 0];
            $enrolled = $gt['entry'] !== null;
            $l1nodes = array_values($gt['levels'][1] ?? []);
            $l2nodes = array_values($gt['levels'][2] ?? []);
            $l3nodes = array_values($gt['levels'][3] ?? []);
            $color = $poolColors[$mid] ?? '#f19107';
            $incPaid = $poolIncomes[$mid] ?? [];

            // Separate by poolLevel: 0=join income, 1=L1bonus, 2=L2bonus, 3=L3bonus
            $joinIncome = array_filter($incPaid, fn($r) => (int) $r['poolLevel'] === 0);
            $l1Bonus = array_filter($incPaid, fn($r) => (int) $r['poolLevel'] === 1);
            $l2Bonus = array_filter($incPaid, fn($r) => (int) $r['poolLevel'] === 2);
            $l3Bonus = array_filter($incPaid, fn($r) => (int) $r['poolLevel'] === 3);
            $joinTotal = array_sum(array_column(array_values($joinIncome), 'poolIncome'));
            $l1BonusAmt = array_sum(array_column(array_values($l1Bonus), 'poolIncome'));
            $l2BonusAmt = array_sum(array_column(array_values($l2Bonus), 'poolIncome'));
            $l3BonusAmt = array_sum(array_column(array_values($l3Bonus), 'poolIncome'));
            $totalEarned = $joinTotal + $l1BonusAmt + $l2BonusAmt + $l3BonusAmt;

            $l1count = count($l1nodes);
            $l2count = count($l2nodes);
            $l3count = count($l3nodes);
            ?>
              <div class="pool-card <?= $enrolled ? 'enrolled' : '' ?>"
                style="<?= $enrolled ? "border-color:{$color}33" : '' ?>">

                <!-- Header -->
                <div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:10px">
                  <div>
                    <div style="font-family:'Orbitron',sans-serif;font-size:13px;font-weight:700;color:<?= $color ?>">
                      <?= e($mp['poolName'] ?? '') ?>
                    </div>
                    <div style="font-size:11px;color:#555;margin-top:2px">
                      $<?= number_format((float) ($mp['poolPrice'] ?? 0), 0) ?>
                      <?php if ($gt['re_entries'] > 0): ?>
                          &nbsp;<span style="color:#3b82f6;font-size:10px;background:rgba(59,130,246,.1);
                    border-radius:4px;padding:1px 6px">↻ <?= $gt['re_entries'] ?> re-entries</span>
                      <?php endif; ?>
                    </div>
                  </div>
                  <?php if ($enrolled): ?>
                      <span class="badge badge-green" style="font-size:10px">ACTIVE</span>
                  <?php else: ?>
                      <span style="font-size:10px;color:#2a2a2a;background:#111;border-radius:4px;padding:2px 8px">Not
                        enrolled</span>
                  <?php endif; ?>
                </div>

                <?php if ($enrolled): ?>

                    <!-- ── 3-LEVEL VISUAL POOL TREE ──────────────────────────── -->
                    <div class="pool-tree" style="width:100%;overflow:hidden">

                      <!-- YOU root -->
                      <div style="text-align:center;margin-bottom:4px">
                        <span style="background:rgba(241,145,7,.15);border:2px solid rgba(241,145,7,.5);
                 border-radius:8px;padding:4px 18px;font-family:'Orbitron',sans-serif;
                 font-size:11px;font-weight:700;color:var(--gold);display:inline-block">YOU</span>
                      </div>
                      <div style="width:2px;height:10px;background:#2a2a2a;margin:0 auto"></div>

                      <!-- LEVEL 1 — 3 slots -->
                      <div class="ptree-label">Level 1 &nbsp;<span
                          style="color:#22c55e;font-weight:700"><?= $l1count ?></span>/3</div>
                      <?php
                      $l1byLeg = [];
                      foreach ($l1nodes as $n)
                        $l1byLeg[(int) $n['legPos']] = $n;
                      ?>
                      <div style="display:flex;gap:4px;justify-content:center">
                        <?php for ($s = 1; $s <= 3; $s++):
                          $n = $l1byLeg[$s] ?? null;
                          $uid = $n ? htmlspecialchars(substr($n['user_id'] ?? '', 0, 7)) : '';
                          ?>
                            <div class="pslot pslot-l1 <?= $n ? 'f1' : '' ?>"
                              style="flex:1;max-width:90px;min-width:0;overflow:hidden;text-overflow:ellipsis"
                              title="<?= $n ? htmlspecialchars($n['user_id'] ?? '') : 'Empty' ?>">
                              <?= $n ? $uid : '<span style="color:#1e1e1e">─</span>' ?>
                            </div>
                        <?php endfor; ?>
                      </div>

                      <div style="width:2px;height:10px;background:#2a2a2a;margin:0 auto"></div>

                      <!-- LEVEL 2 — 9 slots in 3 groups of 3 -->
                      <div class="ptree-label">Level 2 &nbsp;<span
                          style="color:#3b82f6;font-weight:700"><?= $l2count ?></span>/9</div>
                      <?php $l2arr = array_values($l2nodes); ?>
                      <div style="display:flex;justify-content:center;gap:12px;width:100%">
                        <?php for ($g = 0; $g < 3; $g++): ?>
                            <div style="display:flex;flex-direction:column;align-items:center;gap:2px">
                              <div style="display:flex;gap:3px">
                                <?php for ($s = 0; $s < 3; $s++):
                                  $n = $l2arr[$g * 3 + $s] ?? null;
                                  $uid = $n ? htmlspecialchars(substr($n['user_id'] ?? '', 0, 4)) : '';
                                  ?>
                                    <div style="width:28px;min-width:28px;height:22px;border-radius:5px;
                  display:flex;align-items:center;justify-content:center;
                  font-family:'Orbitron',sans-serif;font-size:7px;font-weight:600;
                  border:1px solid <?= $n ? 'rgba(59,130,246,.4)' : '#1a1a1a' ?>;
                  background:<?= $n ? 'rgba(59,130,246,.12)' : 'rgba(255,255,255,.02)' ?>;
                  color:<?= $n ? '#3b82f6' : '#222' ?>;overflow:hidden;text-overflow:ellipsis"
                                      title="<?= $n ? htmlspecialchars($n['user_id'] ?? '') : 'Empty' ?>">
                                      <?= $n ? $uid : '─' ?>
                                    </div>
                                <?php endfor; ?>
                              </div>
                            </div>
                        <?php endfor; ?>
                      </div>

                      <div style="width:2px;height:10px;background:#2a2a2a;margin:0 auto"></div>

                      <!-- LEVEL 3 — 27 dots in 3 main groups of 9 (3×3) -->
                      <div class="ptree-label">Level 3 &nbsp;<span
                          style="color:#a855f7;font-weight:700"><?= $l3count ?></span>/27</div>
                      <?php $l3arr = array_values($l3nodes); ?>
                      <div style="display:flex;justify-content:center;gap:10px">
                        <?php for ($mg = 0; $mg < 3; $mg++): // 3 main groups (one per L1) ?>
                            <div style="display:flex;flex-direction:column;gap:3px">
                              <?php for ($rg = 0; $rg < 3; $rg++): // 3 rows of 3 dots each ?>
                                  <div style="display:flex;gap:3px">
                                    <?php for ($s = 0; $s < 3; $s++):
                                      $idx = $mg * 9 + $rg * 3 + $s;
                                      $n = $l3arr[$idx] ?? null;
                                      ?>
                                        <div style="width:9px;height:9px;border-radius:50%;
                  border:1px solid <?= $n ? 'rgba(168,85,247,.7)' : '#252525' ?>;
                  background:<?= $n ? 'rgba(168,85,247,.5)' : 'rgba(255,255,255,.02)' ?>"
                                          title="<?= $n ? htmlspecialchars($n['user_id'] ?? '') : 'Empty' ?>">
                                        </div>
                                    <?php endfor; ?>
                                  </div>
                              <?php endfor; ?>
                            </div>
                        <?php endfor; ?>
                      </div>

                    </div><!-- /pool-tree -->

                    <!-- Mini progress bars L1/L2/L3 -->
                    <div class="mini-prog" style="margin-top:12px">
                      <div class="mini-prog-item">
                        <div style="color:#22c55e;font-weight:700"><?= $l1count ?>/3</div>
                        <div class="mini-prog-bar">
                          <div class="mini-prog-fill"
                            style="width:<?= min(100, round($l1count / 3 * 100)) ?>%;background:#22c55e">
                          </div>
                        </div>
                        <div style="color:#333;margin-top:2px">L1</div>
                      </div>
                      <div class="mini-prog-item">
                        <div style="color:#3b82f6;font-weight:700"><?= $l2count ?>/9</div>
                        <div class="mini-prog-bar">
                          <div class="mini-prog-fill"
                            style="width:<?= min(100, round($l2count / 9 * 100)) ?>%;background:#3b82f6">
                          </div>
                        </div>
                        <div style="color:#333;margin-top:2px">L2</div>
                      </div>
                      <div class="mini-prog-item">
                        <div style="color:#a855f7;font-weight:700"><?= $l3count ?>/27</div>
                        <div class="mini-prog-bar">
                          <div class="mini-prog-fill"
                            style="width:<?= min(100, round($l3count / 27 * 100)) ?>%;background:#a855f7">
                          </div>
                        </div>
                        <div style="color:#333;margin-top:2px">L3</div>
                      </div>
                    </div>

                    <!-- Income breakdown -->
                    <?php if ($totalEarned > 0): ?>
                        <div style="border-top:1px solid rgba(255,255,255,.05);margin-top:12px;padding-top:10px">
                          <?php if ($joinTotal > 0): ?>
                              <div class="pool-income-row">
                                <span style="color:#555">Join Income</span>
                                <span style="color:<?= $color ?>;font-weight:700">$<?= number_format($joinTotal, 2) ?></span>
                              </div>
                          <?php endif; ?>
                          <?php if ($l1BonusAmt > 0): ?>
                              <div class="pool-income-row">
                                <span style="color:#22c55e">L1 Bonus <span style="color:#555;font-size:10px">(3 direct)</span></span>
                                <span style="color:#22c55e;font-weight:700">$<?= number_format($l1BonusAmt, 2) ?></span>
                              </div>
                          <?php endif; ?>
                          <?php if ($l2BonusAmt > 0): ?>
                              <div class="pool-income-row">
                                <span style="color:#3b82f6">L2 Bonus <span style="color:#555;font-size:10px">(9 filled)</span></span>
                                <span style="color:#3b82f6;font-weight:700">$<?= number_format($l2BonusAmt, 2) ?></span>
                              </div>
                          <?php endif; ?>
                          <?php if ($l3BonusAmt > 0): ?>
                              <div class="pool-income-row">
                                <span style="color:#a855f7">L3 Bonus <span style="color:#555;font-size:10px">(27 filled →
                                    re-entry)</span></span>
                                <span style="color:#a855f7;font-weight:700">$<?= number_format($l3BonusAmt, 2) ?></span>
                              </div>
                          <?php endif; ?>
                          <div class="pool-income-total">
                            <span style="color:#888">Total Earned</span>
                            <span style="color:var(--success)">$<?= number_format($totalEarned, 2) ?></span>
                          </div>
                        </div>
                    <?php endif; ?>

                <?php else: ?>
                    <!-- Not enrolled state -->
                    <div style="padding:20px 0;text-align:center">
                      <div style="font-size:28px;margin-bottom:8px;opacity:.15">◎</div>
                      <div style="font-size:11px;color:#2a2a2a;line-height:1.6">
                        Auto-entered when you reach the<br>required working step
                      </div>
                    </div>
                <?php endif; ?>

              </div><!-- /pool-card -->
          <?php endforeach; ?>
        </div><!-- /pool-grid -->
      </div>

      <!-- ══ INCOME TABLE ═══════════════════════════════════════════════ -->
      <div class="card" style="margin-bottom:16px">
        <div class="card-title"><i class="fas fa-calculator"></i> Income Calculation Per Step</div>
        <div class="table-responsive">
          <table class="data-table ict">
            <thead>
              <tr>
                <th>Step</th>
                <th>Package</th>
                <th>Price</th>
                <th>Direct%</th>
                <th class="g">Sponsor Net</th>
                <th>Upline%</th>
                <th class="b">Upline Net</th>
                <th class="r">Admin Fee</th>
                <th>Triggers Pool</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($allPkgs as $p):
                $pid = (int) $p['id'];
                $prev = $incPrev[$pid] ?? [];
                $done = $curPkgId > $pid;
                $active = $curPkgId === $pid;
                ?>
                  <tr style="<?= $active ? 'background:rgba(241,145,7,.05)' : '' ?>">
                    <td style="font-family:'Orbitron',sans-serif;font-size:11px;color:var(--gold)">
                      S<?= (int) $p['poolLevel'] ?></td>
                    <td><?= e($p['poolName']) ?></td>
                    <td class="amount gold">$<?= number_format((float) $p['upgradePrice'], 0) ?></td>
                    <td class="g"><?= $p['directPercent'] ?>%</td>
                    <td class="g amount">$<?= number_format($prev['direct_net'] ?? 0, 2) ?></td>
                    <td class="b"><?= $p['uplinePercent'] ?>%</td>
                    <td class="b amount">$<?= number_format($prev['upline_net'] ?? 0, 2) ?></td>
                    <td class="r amount">$<?= number_format($prev['total_admin'] ?? 0, 2) ?></td>
                    <td>
                      <?php if (!empty($prev['triggers_pool'])): ?>
                          <span class="trigger-badge">⚡
                            <?= e($prev['triggers_matrix']['poolName'] ?? 'Pool ' . $prev['triggers_pool']) ?></span>
                      <?php else: ?>
                          <span style="color:#2a2a2a">—</span>
                      <?php endif; ?>
                    </td>
                    <td>
                      <?php if ($done): ?>
                          <span class="badge badge-green">✓ Done</span>
                      <?php elseif ($active): ?>
                          <span class="badge badge-gold">● Current</span>
                      <?php else: ?>
                          <span style="color:#333;font-size:11px">Locked</span>
                      <?php endif; ?>
                    </td>
                  </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>