<?php
require_once '../connection/db.php';
require_once '../connection/MatrixEngine.php';  // ← REQUIRED for MatrixEngine class
requireLogin();

$user = getCurrentUser();
$memberId = (int) $user['member_id'];
$userId = $user['user_id'] ?? '';
$wallet = $user['walletAddress'] ?? '';
$activDate = $user['activation_date'] ?? null;
$topupFlag = (int) ($user['topup_flag'] ?? 0);

$db = getDB();

// ── Safe income totals (fallback to 0 if function missing) ──────────────
$refIncome = function_exists('getReferralIncomeTotal') ? getReferralIncomeTotal($memberId) : 0;
$sponserIncome = function_exists('getsponsorIncomeTotal') ? getsponsorIncomeTotal($memberId) : 0;
$levelIncome = function_exists('getLevelIncomeTotal') ? getLevelIncomeTotal($memberId) : 0;
$poolIncome = function_exists('getPoolIncomeTotal') ? getPoolIncomeTotal($memberId) : 0;
$upgradeIncome = function_exists('getUpgradeIncomeTotal') ? getUpgradeIncomeTotal($memberId) : 0;
$totalIncome = $refIncome + $levelIncome + $poolIncome + $upgradeIncome + $sponserIncome;

$directCount = function_exists('getDirectCount') ? getDirectCount($memberId) : 0;
$teamCount = function_exists('getTeamCount') ? getTeamCount($memberId) : 0;

$curPkgId = (int) ($user['currentPackage'] ?? 0);
$curPkgRow = [];
if ($curPkgId > 0) {
  $ps = $db->prepare('SELECT * FROM meddolic_config_pool_list WHERE id=? LIMIT 1');
  $ps->execute([$curPkgId]);
  $curPkgRow = $ps->fetch() ?: [];
}

$normalPkgs = function_exists('getPoolList') ? getPoolList() : [];
$matrixPkgs = function_exists('getMatrixPackages') ? getMatrixPackages() : [];

$poolEntries = $db->prepare('SELECT ped.*, mp.poolName FROM meddolic_user_pool_entry_details ped
    LEFT JOIN meddolic_config_matrix_package mp ON mp.matrixId=ped.poolId
    WHERE ped.memberId=? ORDER BY ped.entryDate DESC LIMIT 5');
$poolEntries->execute([$memberId]);
$myPoolEntries = $poolEntries->fetchAll();

$refQ = $db->prepare('SELECT ud.user_id, ud.walletAddress, ud.activation_date, ud.topup_flag
    FROM meddolic_user_details ud WHERE ud.sponser_id=? ORDER BY ud.date_time DESC LIMIT 5');
$refQ->execute([$memberId]);
$recentReferrals = $refQ->fetchAll();

$walletBal = (float) ($user['wallet'] ?? 0);

// ── Matrix status ────────────────────────────────────────────────────────
$allEntriesQ2 = $db->prepare("SELECT DISTINCT poolId FROM meddolic_user_pool_entry_details WHERE memberId=?");
$allEntriesQ2->execute([$memberId]);
$enteredMatrices = array_column($allEntriesQ2->fetchAll(), 'poolId', 'poolId');

// Safe: use class constant if available, else empty array
$wTriggers = (class_exists('MatrixEngine') && defined('MatrixEngine::WORKING_TRIGGERS_GLOBAL'))
  ? MatrixEngine::WORKING_TRIGGERS_GLOBAL
  : [];
$matrixRequiresPkg = !empty($wTriggers) ? array_flip($wTriggers) : [];

$paidGlobalIds = [];
$gateBlocking = false;
try {
  $manualGlobalQ2 = $db->prepare(
    "SELECT DISTINCT package_id FROM gm_package_purchases
         WHERE member_id=? AND buy_type=3 AND trx_hash NOT LIKE 'AUTOOO_%' AND status=1"
  );
  $manualGlobalQ2->execute([$memberId]);
  $paidGlobalIds = array_column($manualGlobalQ2->fetchAll(), 'package_id', 'package_id');
  if (!empty($wTriggers) && isset($wTriggers[$curPkgId]) && !isset($paidGlobalIds[$wTriggers[$curPkgId]])) {
    $gateBlocking = true;
  }
} catch (\Exception $e) {
  $gateBlocking = false;
}

$totalUsersQ = $db->query("SELECT COUNT(*) AS c FROM meddolic_user_details WHERE topup_flag=1");
$totalUsers = (int) ($totalUsersQ->fetch()['c'] ?? 0);

$pageTitle = 'Dashboard';
$activePage = 'dashboard';

// ── Safe helper fallbacks ────────────────────────────────────────────────
if (!function_exists('fmtUSD')) {
  function fmtUSD(float $v): string
  {
    return '$' . number_format($v, 2);
  }
}
if (!function_exists('e')) {
  function e(string $v): string
  {
    return htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
  }
}
function xe(string $v): string
{
  return htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
}

require_once 'Include/header.php';
?>

<!-- ══ INLINE STYLES ══════════════════════════════════════════════════════ -->
<style>
  /* ── Package Section ──────────────────────────────────────────────────── */
  .pkg-section {
    margin-bottom: 28px;
  }

  .pkg-section-title {
    font-size: 11px;
    letter-spacing: 2px;
    text-transform: uppercase;
    color: #555;
    margin-bottom: 14px;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .pkg-section-title::after {
    content: '';
    flex: 1;
    height: 1px;
    background: linear-gradient(90deg, #2a2a2a, transparent);
  }

  /* ── Package Cards Grid ───────────────────────────────────────────────── */
  .pkg-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(min(200px, 100%), 1fr));
    gap: 10px;
  }

  /* ── Single Package Card ──────────────────────────────────────────────── */
  .pkg-card {
    background: var(--dark2, #111);
    border: 1px solid #1e1e1e;
    border-radius: 14px;
    padding: 14px 12px;
    position: relative;
    transition: transform .15s, box-shadow .15s, border-color .15s;
    overflow: hidden;
  }

  .pkg-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 2px;
    background: linear-gradient(90deg, transparent, #1e1e1e, transparent);
    transition: background .2s;
  }

  .pkg-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, .4);
  }

  .pkg-card.done {
    border-color: rgba(34, 197, 94, .25);
  }

  .pkg-card.done::before {
    background: linear-gradient(90deg, transparent, rgba(34, 197, 94, .4), transparent);
  }

  .pkg-card.next {
    border-color: rgba(241, 145, 7, .45);
  }

  .pkg-card.next::before {
    background: linear-gradient(90deg, transparent, rgba(241, 145, 7, .6), transparent);
  }

  .pkg-card.gated {
    opacity: .6;
    border-color: rgba(59, 130, 246, .25);
  }

  .pkg-card.locked {
    opacity: .28;
    pointer-events: none;
  }

  /* Matrix card accent */
  .pkg-card.mx-done {
    border-color: rgba(34, 197, 94, .25);
  }

  .pkg-card.mx-done::before {
    background: linear-gradient(90deg, transparent, rgba(34, 197, 94, .4), transparent);
  }

  .pkg-card.mx-next {
    border-color: rgba(234, 179, 8, .45);
  }

  .pkg-card.mx-next::before {
    background: linear-gradient(90deg, transparent, rgba(234, 179, 8, .6), transparent);
  }

  .pkg-card.mx-locked {
    opacity: .28;
    pointer-events: none;
  }

  .pkg-num {
    position: absolute;
    top: 10px;
    right: 12px;
    font-family: 'Orbitron', sans-serif;
    font-size: 9px;
    color: #2a2a2a;
    font-weight: 700;
  }

  .pkg-name {
    font-size: 13px;
    font-weight: 700;
    color: #ccc;
    margin-bottom: 4px;
    font-family: 'Orbitron', sans-serif;
    letter-spacing: .5px;
  }

  .pkg-name.gold {
    color: var(--gold, #f19107);
  }

  .pkg-name.green {
    color: #22c55e;
  }

  .pkg-name.amber {
    color: #eab308;
  }

  .pkg-price {
    font-size: 22px;
    font-weight: 900;
    line-height: 1;
    font-family: 'Orbitron', sans-serif;
    margin-bottom: 10px;
  }

  .pkg-price.gold {
    color: var(--gold, #f19107);
  }

  .pkg-price.green {
    color: #22c55e;
  }

  .pkg-price.amber {
    color: #eab308;
  }

  .pkg-meta {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
    margin-bottom: 12px;
  }

  .pkg-badge {
    font-size: 9px;
    font-weight: 700;
    padding: 2px 7px;
    border-radius: 4px;
    text-transform: uppercase;
    letter-spacing: .5px;
  }

  .pb-blue {
    background: rgba(59, 130, 246, .12);
    color: #60a5fa;
    border: 1px solid rgba(59, 130, 246, .25);
  }

  .pb-green {
    background: rgba(34, 197, 94, .1);
    color: #4ade80;
    border: 1px solid rgba(34, 197, 94, .25);
  }

  .pb-gold {
    background: rgba(241, 145, 7, .1);
    color: #f19107;
    border: 1px solid rgba(241, 145, 7, .25);
  }

  .pb-amber {
    background: rgba(234, 179, 8, .1);
    color: #eab308;
    border: 1px solid rgba(234, 179, 8, .25);
  }

  .pb-purple {
    background: rgba(168, 85, 247, .12);
    color: #c084fc;
    border: 1px solid rgba(168, 85, 247, .25);
  }

  /* 100% income highlight */
  .income-100 {
    background: linear-gradient(135deg, rgba(34, 197, 94, .12), rgba(16, 185, 129, .08));
    border: 1px solid rgba(34, 197, 94, .3);
    border-radius: 8px;
    padding: 6px 10px;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    gap: 6px;
  }

  .income-100-badge {
    font-family: 'Orbitron', sans-serif;
    font-size: 14px;
    font-weight: 900;
    color: #22c55e;
    line-height: 1;
  }

  .income-100-label {
    font-size: 10px;
    color: #4ade80;
    line-height: 1.3;
  }

  /* Auto-trigger note */
  .auto-trigger {
    font-size: 9px;
    color: #f59e0b;
    display: flex;
    align-items: center;
    gap: 4px;
    margin-bottom: 8px;
  }

  /* Action buttons */
  .btn-upgrade {
    width: 100%;
    padding: 9px 0;
    border-radius: 8px;
    border: none;
    font-size: 11px;
    font-weight: 700;
    letter-spacing: .5px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    transition: opacity .15s, transform .1s;
  }

  .btn-upgrade:hover {
    opacity: .88;
    transform: translateY(-1px);
  }

  .btn-upgrade:active {
    transform: scale(.97);
  }

  .btn-upgrade.gold-btn {
    background: linear-gradient(135deg, #f19107, #c97800);
    color: #000;
  }

  .btn-upgrade.amber-btn {
    background: linear-gradient(135deg, #eab308, #ca8a04);
    color: #000;
  }

  .btn-upgrade.done-btn {
    background: rgba(34, 197, 94, .08);
    color: #22c55e;
    border: 1px solid rgba(34, 197, 94, .3);
    cursor: default;
  }

  .btn-upgrade.done-btn:hover {
    opacity: 1;
    transform: none;
  }

  .btn-upgrade.lock-btn {
    background: rgba(255, 255, 255, .03);
    color: #333;
    border: 1px solid #1e1e1e;
    cursor: not-allowed;
  }

  .btn-upgrade.lock-btn:hover {
    opacity: 1;
    transform: none;
  }

  .btn-upgrade.gate-btn {
    background: rgba(59, 130, 246, .08);
    color: #60a5fa;
    border: 1px solid rgba(59, 130, 246, .2);
    cursor: not-allowed;
  }

  /* ── Confirm Modal ────────────────────────────────────────────────────── */
  .dash-modal-overlay {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, .7);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    padding: 16px;
    opacity: 0;
    pointer-events: none;
    transition: opacity .2s;
  }

  .dash-modal-overlay.open {
    opacity: 1;
    pointer-events: all;
  }

  .dash-modal {
    background: #111;
    border: 1px solid #2a2a2a;
    border-radius: 18px;
    padding: 24px;
    width: 100%;
    max-width: 380px;
    transform: translateY(20px) scale(.97);
    transition: transform .2s;
    position: relative;
  }

  .dash-modal-overlay.open .dash-modal {
    transform: translateY(0) scale(1);
  }

  .dash-modal-close {
    position: absolute;
    top: 14px;
    right: 16px;
    background: none;
    border: none;
    color: #555;
    font-size: 20px;
    cursor: pointer;
    line-height: 1;
  }

  .dash-modal-close:hover {
    color: #999;
  }

  .dm-type {
    font-size: 9px;
    letter-spacing: 2px;
    text-transform: uppercase;
    color: #555;
    margin-bottom: 6px;
  }

  .dm-name {
    font-family: 'Orbitron', sans-serif;
    font-size: 17px;
    font-weight: 700;
    margin-bottom: 16px;
  }

  .dm-name.gold {
    color: var(--gold, #f19107);
  }

  .dm-name.amber {
    color: #eab308;
  }

  .dm-divider {
    height: 1px;
    background: #1e1e1e;
    margin: 14px 0;
  }

  .dm-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    font-size: 12px;
  }

  .dm-row span:first-child {
    color: #555;
  }

  .dm-row span:last-child {
    font-weight: 700;
    color: #ccc;
  }

  .dm-row .gold {
    color: var(--gold, #f19107);
    font-family: 'Orbitron', sans-serif;
  }

  .dm-row .amber {
    color: #eab308;
    font-family: 'Orbitron', sans-serif;
  }

  .dm-income-box {
    background: linear-gradient(135deg, rgba(34, 197, 94, .1), rgba(16, 185, 129, .06));
    border: 1px solid rgba(34, 197, 94, .3);
    border-radius: 10px;
    padding: 12px 14px;
    margin: 14px 0;
    text-align: center;
  }

  .dm-income-pct {
    font-family: 'Orbitron', sans-serif;
    font-size: 28px;
    font-weight: 900;
    color: #22c55e;
    line-height: 1;
  }

  .dm-income-lbl {
    font-size: 10px;
    color: #4ade80;
    margin-top: 4px;
  }

  .dm-confirm-btn {
    width: 100%;
    padding: 12px;
    border-radius: 10px;
    border: none;
    font-size: 13px;
    font-weight: 700;
    letter-spacing: .5px;
    cursor: pointer;
    margin-top: 8px;
    transition: opacity .15s;
  }

  .dm-confirm-btn:hover {
    opacity: .88;
  }

  .dm-confirm-btn.gold-btn {
    background: linear-gradient(135deg, #f19107, #c97800);
    color: #000;
  }

  .dm-confirm-btn.amber-btn {
    background: linear-gradient(135deg, #eab308, #ca8a04);
    color: #000;
  }

  .dm-loader {
    display: none;
    text-align: center;
    padding: 10px;
    color: #555;
    font-size: 12px;
  }

  /* ── Stat cards scroll on mobile ──────────────────────────────────────── */
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(min(180px, 100%), 1fr));
    gap: 10px;
    margin-bottom: 20px;
  }

  @media(max-width:600px) {
    .pkg-grid {
      grid-template-columns: repeat(2, 1fr);
    }

    .pkg-price {
      font-size: 18px;
    }
  }

  @media(max-width:380px) {
    .pkg-grid {
      grid-template-columns: 1fr;
    }
  }
</style>

<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> Dashboard</div>
        <h3>Dashboard</h3>
        <div class="subtitle">
          Welcome, <span><?= xe($userId) ?></span>
          &nbsp;|&nbsp; Wallet: <span style="font-family:monospace;font-size:12px;color:#555">
            <?= xe(substr($wallet, 0, 12)) . '…' . xe(substr($wallet, -6)) ?>
          </span>
          &nbsp;|&nbsp;
          <?php if ($topupFlag): ?>
            <span class="badge badge-green"><i class="fas fa-check-circle"></i> Active</span>
          <?php else: ?>
            <span class="badge badge-red"><i class="fas fa-times-circle"></i> Inactive</span>
          <?php endif; ?>
        </div>
      </div>

      <?php if (!$topupFlag): ?>
        <div class="alert alert-gold">
          <i class="fas fa-exclamation-triangle"></i>
          Your account is not yet active.
          <a href="../register/Register.php" style="margin-left:10px;font-weight:700">Complete Registration</a>
        </div>
      <?php endif; ?>

      <!-- ── Stat Cards ──────────────────────────────────────────────────── -->
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon"><i class="fas fa-user-check"></i></div>
          <div class="stat-info">
            <p>Activation Date</p>
            <h5><?= $activDate ? date('d M Y', strtotime($activDate)) : 'Pending' ?></h5>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon"><i class="fas fa-layer-group"></i></div>
          <div class="stat-info">
            <p>Current Package</p>
            <h5 class="gold"><?= $curPkgRow ? xe($curPkgRow['poolName']) : 'None' ?></h5>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon"><i class="fas fa-user-plus"></i></div>
          <div class="stat-info">
            <p>Direct Referrals</p>
            <h5><?= number_format($directCount) ?></h5>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon"><i class="fas fa-users"></i></div>
          <div class="stat-info">
            <p>Total Team</p>
            <h5><?= number_format($teamCount) ?></h5>
          </div>
        </div>
        <a href="ReferralIncome.php" class="stat-card" style="text-decoration:none">
          <div class="stat-icon"><i class="fas fa-coins"></i></div>
          <div class="stat-info">
            <p>Referral Income</p>
            <h5 class="gold"><?= fmtUSD($refIncome) ?></h5>
          </div>
        </a>
        <a href="SponserIncome.php" class="stat-card" style="text-decoration:none">
          <div class="stat-icon"><i class="fas fa-coins"></i></div>
          <div class="stat-info">
            <p>Sponsor Income</p>
            <h5 class="gold"><?= fmtUSD($sponserIncome) ?></h5>
          </div>
        </a>
        <a href="LevelIncome.php" class="stat-card" style="text-decoration:none">
          <div class="stat-icon"><i class="fas fa-chart-line"></i></div>
          <div class="stat-info">
            <p>Level Income</p>
            <h5 class="gold"><?= fmtUSD($levelIncome) ?></h5>
          </div>
        </a>
        <a href="PoolIncome.php" class="stat-card" style="text-decoration:none">
          <div class="stat-icon"><i class="fas fa-swimming-pool"></i></div>
          <div class="stat-info">
            <p>Matrix Income</p>
            <h5 class="gold"><?= fmtUSD($poolIncome) ?></h5>
          </div>
        </a>
        <a href="UpgradeIncome.php" class="stat-card" style="text-decoration:none">
          <div class="stat-icon"><i class="fas fa-arrow-up"></i></div>
          <div class="stat-info">
            <p>Placement Upline Income</p>
            <h5 class="gold"><?= fmtUSD($upgradeIncome) ?></h5>
          </div>
        </a>
        <div class="stat-card" style="border-color:rgba(241,145,7,.4)">
          <div class="stat-icon" style="background:rgba(241,145,7,.2)"><i class="fas fa-trophy"></i></div>
          <div class="stat-info">
            <p>Total Earnings</p>
            <h5 class="gold" style="font-size:17px"><?= fmtUSD($totalIncome) ?></h5>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon"><i class="fas fa-wallet"></i></div>
          <div class="stat-info">
            <p>Wallet Balance</p>
            <h5 class="gold"><?= fmtUSD($walletBal) ?></h5>
          </div>
        </div>
        <div class="stat-card" style="text-align:center">
          <div class="stat-icon"><i class="fas fa-globe"></i></div>
          <div class="stat-info">
            <p>Active Members</p>
            <h5 class="gold"><?= number_format($totalUsers) ?></h5>
          </div>
        </div>
      </div>

      <!-- ══════════════════════════════════════════════════════════════════
           NORMAL PACKAGES — Inline Cards
           ══════════════════════════════════════════════════════════════════ -->
      <div class="pkg-section">
        <div class="pkg-section-title">
          <i class="fas fa-layer-group" style="color:var(--gold)"></i>
          Normal Package Plan — Upgrade Levels
        </div>

        <div class="pkg-grid">
          <?php foreach ($normalPkgs as $i => $p):
            $pid = (int) $p['id'];

            if ($curPkgId >= $pid)
              $nStatus = 'done';
            elseif ($curPkgId + 1 === $pid)
              $nStatus = $gateBlocking ? 'gated' : 'next';
            else
              $nStatus = 'locked';

            // What global matrix auto-triggers after this pkg
            $trigGlobalId = $wTriggers[$pid] ?? null;
            $trigGlobalPkg = null;
            if ($trigGlobalId) {
              $tQ = $db->prepare('SELECT * FROM meddolic_config_matrix_package WHERE matrixId=? LIMIT 1');
              $tQ->execute([$trigGlobalId]);
              $trigGlobalPkg = $tQ->fetch();
            }
            ?>
            <div class="pkg-card <?= $nStatus ?>">
              <div class="pkg-num">#<?= $i + 1 ?></div>

              <div class="pkg-name gold"><?= xe($p['poolName']) ?></div>

              <div class="pkg-price gold">$<?= number_format((float) $p['upgradePrice'], 0) ?></div>

              <div class="pkg-meta">
                <span class="pkg-badge pb-blue">Direct <?= $p['directPercent'] ?>%</span>
                <span class="pkg-badge pb-gold">Upline <?= $p['uplinePercent'] ?>%</span>
              </div>

              <?php if ($trigGlobalPkg && $nStatus !== 'done'): ?>
                <div class="auto-trigger">
                  <i class="fas fa-bolt"></i>
                  Auto unlocks <strong><?= xe($trigGlobalPkg['poolName']) ?></strong>
                </div>
              <?php endif; ?>

              <?php if ($nStatus === 'done'): ?>
                <button class="btn-upgrade done-btn">
                  <i class="fas fa-check-circle"></i> Completed
                </button>

              <?php elseif ($nStatus === 'next'): ?>
                <button class="btn-upgrade gold-btn"
                  onclick="openWorkingModal(<?= $pid ?>, <?= (float) $p['upgradePrice'] ?>, '<?= xe($p['poolName']) ?>', <?= $p['directPercent'] ?>, <?= $p['uplinePercent'] ?>, <?= $trigGlobalPkg ? 1 : 0 ?>, '<?= $trigGlobalPkg ? xe($trigGlobalPkg['poolName']) : '' ?>')">
                  <i class="fas fa-bolt"></i> Upgrade — $<?= number_format((float) $p['upgradePrice'], 0) ?>
                </button>

              <?php elseif ($nStatus === 'gated'): ?>
                <button class="btn-upgrade gate-btn">
                  <i class="fas fa-lock"></i> Buy Matrix First
                </button>

              <?php else: ?>
                <button class="btn-upgrade lock-btn">
                  <i class="fas fa-lock"></i> Locked
                </button>
              <?php endif; ?>
            </div>
          <?php endforeach; ?>
        </div>
      </div>

      <!-- ══════════════════════════════════════════════════════════════════
           GLOBAL MATRIX PACKAGES — Inline Cards with 100% Income Badge
           ══════════════════════════════════════════════════════════════════ -->
      <div class="pkg-section">
        <div class="pkg-section-title">
          <i class="fas fa-th" style="color:#eab308"></i>
          Global Matrix Pool — Auto Pool Plan
        </div>

        <div class="pkg-grid">
          <?php
          $dirReqArr = [1 => 0, 2 => 2, 3 => 2, 4 => 2, 5 => 2, 6 => 2];

          foreach ($matrixPkgs as $i => $mp):
            $mid = (int) $mp['matrixId'];
            $reqWrkPkg = $matrixRequiresPkg[$mid] ?? 0;
            $isLocked = ($reqWrkPkg > 0 && $curPkgId < $reqWrkPkg);
            $isEntered = isset($enteredMatrices[$mid]);
            $dirReq = $dirReqArr[$mid] ?? 0;

            $aeQ = $db->prepare("SELECT poolStatus FROM meddolic_user_pool_entry_details WHERE memberId=? AND poolId=? ORDER BY entryId DESC LIMIT 1");
            $aeQ->execute([$memberId, $mid]);
            $aeRow = $aeQ->fetch();
            $isActive = $aeRow && (int) $aeRow['poolStatus'] === 1;

            // Re-entry count
            $reEntryQ = $db->prepare("SELECT COUNT(*) FROM meddolic_user_pool_entry_details WHERE memberId=? AND poolId=?");
            $reEntryQ->execute([$memberId, $mid]);
            $reEntryCount = (int) $reEntryQ->fetchColumn();

            if ($isActive)
              $mxStatus = 'mx-done';
            elseif ($isLocked)
              $mxStatus = 'mx-locked';
            else
              $mxStatus = 'mx-next';
            ?>
            <div class="pkg-card <?= $mxStatus ?>">
              <div class="pkg-num">#<?= $i + 1 ?></div>

              <div class="pkg-name amber"><?= xe($mp['poolName']) ?></div>

              <div class="pkg-price amber">$<?= number_format((float) $mp['poolPrice'], 0) ?></div>

              <!-- 100% Income Highlight — shown on Upgrade cards -->
              <?php if (!$isActive && !$isLocked): ?>
                <div class="income-100">
                  <div>
                    <div class="income-100-badge">100%</div>
                  </div>
                  <div class="income-100-label">
                    First join income<br>goes <strong>100% to you</strong>
                  </div>
                </div>
              <?php endif; ?>

              <div class="pkg-meta">
                <?php if ($dirReq > 0): ?>
                  <span class="pkg-badge pb-amber"><?= $dirReq ?> actives req.</span>
                <?php else: ?>
                  <span class="pkg-badge pb-green">No direct req.</span>
                <?php endif; ?>
                <?php if ($reEntryCount > 0): ?>
                  <span class="pkg-badge pb-purple">↻ <?= $reEntryCount ?> entries</span>
                <?php endif; ?>
                <?php if ($reqWrkPkg > 0): ?>
                  <span class="pkg-badge pb-blue">Slot <?= $reqWrkPkg ?> req.</span>
                <?php endif; ?>
              </div>

              <?php if ($isActive): ?>
                <button class="btn-upgrade done-btn">
                  <i class="fas fa-circle" style="font-size:7px"></i> Active &amp; Running
                </button>
                <?php if ($reEntryCount > 0): ?>
                  <button class="btn-upgrade amber-btn" style="margin-top:6px"
                    onclick="openMatrixModal(<?= $mid ?>, <?= (float) $mp['poolPrice'] ?>, '<?= xe($mp['poolName']) ?>', <?= $dirReq ?>, true)">
                    <i class="fas fa-plus"></i> Extra Slot
                  </button>
                <?php endif; ?>

              <?php elseif ($isLocked): ?>
                <button class="btn-upgrade lock-btn">
                  <i class="fas fa-lock"></i> Upgrade Slot <?= $reqWrkPkg ?> First
                </button>

              <?php else: ?>
                <button class="btn-upgrade amber-btn"
                  onclick="openMatrixModal(<?= $mid ?>, <?= (float) $mp['poolPrice'] ?>, '<?= xe($mp['poolName']) ?>', <?= $dirReq ?>, <?= $isEntered ? 'true' : 'false' ?>)">
                  <i class="fas fa-plus-circle"></i>
                  <?= $isEntered ? 'Buy Extra Slot' : 'Buy $' . number_format((float) $mp['poolPrice'], 0) ?>
                </button>
              <?php endif; ?>
            </div>
          <?php endforeach; ?>
        </div>
      </div>

      <!-- ── Recent Referrals + Pool Entries ─────────────────────────── -->
      <div class="two-col" style="margin-bottom:20px">
        <div class="card">
          <div class="card-title"><i class="fas fa-user-plus"></i> Recent Referrals</div>
          <div class="table-responsive">
            <table class="data-table">
              <thead>
                <tr>
                  <th>#</th>
                  <th>User ID</th>
                  <th>Wallet</th>
                  <th>Active Date</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($recentReferrals)): ?>
                  <tr class="empty-row">
                    <td colspan="5"><i class="fas fa-inbox"></i> No referrals yet</td>
                  </tr>
                <?php else:
                  foreach ($recentReferrals as $i => $r): ?>
                    <tr>
                      <td><?= $i + 1 ?></td>
                      <td class="amount"><?= xe($r['user_id']) ?></td>
                      <td style="font-family:monospace;font-size:11px;color:#555">
                        <?= xe(substr($r['walletAddress'], 0, 10)) ?>…
                      </td>
                      <td style="font-size:12px;color:var(--text-muted)">
                        <?= $r['activation_date'] ? date('d M Y', strtotime($r['activation_date'])) : '—' ?>
                      </td>
                      <td>
                        <?= (int) $r['topup_flag'] ? '<span class="badge badge-green">Active</span>' : '<span class="badge badge-red">Pending</span>' ?>
                      </td>
                    </tr>
                  <?php endforeach; endif; ?>
              </tbody>
            </table>
          </div>
          <a href="MyReferrals.php" style="font-size:12px;margin-top:10px;display:block;color:var(--gold)">View all
            referrals →</a>
        </div>

        <div class="card">
          <div class="card-title"><i class="fas fa-swimming-pool"></i> My Matrix Pool Entries</div>
          <div class="table-responsive">
            <table class="data-table">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Pool</th>
                  <th>Level</th>
                  <th>Re-entry</th>
                  <th>Date</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($myPoolEntries)): ?>
                  <tr class="empty-row">
                    <td colspan="6"><i class="fas fa-inbox"></i> No pool entries yet</td>
                  </tr>
                <?php else:
                  foreach ($myPoolEntries as $i => $pe): ?>
                    <tr>
                      <td><?= $i + 1 ?></td>
                      <td><span class="badge badge-gold"><?= xe($pe['poolName'] ?? 'Pool ' . $pe['poolId']) ?></span></td>
                      <td><?= (int) $pe['poolLevel'] ?></td>
                      <td><?= (int) $pe['reEntryCount'] ?></td>
                      <td style="font-size:12px;color:var(--text-muted)"><?= date('d M Y', strtotime($pe['entryDate'])) ?>
                      </td>
                      <td>
                        <?= (int) $pe['poolStatus'] ? '<span class="badge badge-green">Running</span>' : '<span class="badge badge-red">Finished</span>' ?>
                      </td>
                    </tr>
                  <?php endforeach; endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- ── Referral Link ─────────────────────────────────────────────── -->
      <div class="referral-card">
        <div class="card-title"><i class="fas fa-share-alt"></i> Your Referral Link</div>
        <div class="ref-input-group">
          <input class="ref-input" id="refLinkInput" readonly
            value="<?= xe('http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . dirname(dirname($_SERVER['SCRIPT_NAME'])) . '/register/Register.php?ref=' . $wallet) ?>">
          <button class="btn-copy" onclick="copyText('refLinkInput')">
            <i class="fas fa-copy"></i> Copy
          </button>
        </div>
      </div>

    </div><!-- /page-content -->
    <?php require_once 'Include/footer.php'; ?>
  </div>
</div>

<!-- ══ WORKING PACKAGE CONFIRM MODAL ════════════════════════════════════ -->
<div class="dash-modal-overlay" id="workingModal">
  <div class="dash-modal">
    <button class="dash-modal-close" onclick="closeModal('workingModal')">×</button>
    <div class="dm-type"><i class="fas fa-arrow-up"></i>&nbsp; Normal Package Upgrade</div>
    <div class="dm-name gold" id="wm-name">—</div>
    <div class="dm-divider"></div>

    <div class="dm-row">
      <span>Package Price</span>
      <span class="gold" id="wm-usd">$0</span>
    </div>
    <div class="dm-row">
      <span>≈ TRX Amount</span>
      <span id="wm-trx" style="color:#60a5fa;font-family:'Orbitron',sans-serif">0 TRX</span>
    </div>
    <div class="dm-row">
      <span>Direct Referral %</span>
      <span id="wm-direct" style="color:#4ade80">—</span>
    </div>
    <div class="dm-row">
      <span>Upline Placement %</span>
      <span id="wm-upline" style="color:#818cf8">—</span>
    </div>

    <div id="wm-trigger-box" style="display:none; margin-top:10px">
      <div
        style="background:rgba(245,158,11,.08);border:1px solid rgba(245,158,11,.25);border-radius:8px;padding:8px 12px;font-size:11px;color:#f59e0b;display:flex;align-items:center;gap:6px">
        <i class="fas fa-bolt"></i>
        Auto-unlocks Global Matrix: <strong id="wm-trigger-name" style="margin-left:4px"></strong>
      </div>
    </div>

    <div class="dm-divider"></div>
    <div id="wm-loader" class="dm-loader"><i class="fas fa-spinner fa-spin"></i> Processing…</div>
    <button class="dm-confirm-btn gold-btn" id="wm-confirm-btn" onclick="confirmWorking()">
      <i class="fas fa-bolt"></i> Confirm Upgrade
    </button>
    <div style="font-size:10px;color:#333;text-align:center;margin-top:8px">Transaction will be sent from your connected
      wallet</div>
  </div>
</div>

<!-- ══ MATRIX PACKAGE CONFIRM MODAL ════════════════════════════════════= -->
<div class="dash-modal-overlay" id="matrixModal">
  <div class="dash-modal">
    <button class="dash-modal-close" onclick="closeModal('matrixModal')">×</button>
    <div class="dm-type"><i class="fas fa-th"></i>&nbsp; Global Matrix Pool</div>
    <div class="dm-name amber" id="mm-name">—</div>
    <div class="dm-divider"></div>

    <!-- 100% Income highlight -->
    <div class="dm-income-box" id="mm-income-box">
      <div class="dm-income-pct">100%</div>
      <div class="dm-income-lbl">First join income goes 100% to you<br><span style="color:#555;font-size:9px">2nd &amp;
          3rd slots → 50%+50% split</span></div>
    </div>

    <div class="dm-row">
      <span>Pool Price</span>
      <span class="amber" id="mm-usd">$0</span>
    </div>
    <div class="dm-row">
      <span>≈ TRX Amount</span>
      <span id="mm-trx" style="color:#60a5fa;font-family:'Orbitron',sans-serif">0 TRX</span>
    </div>
    <div class="dm-row" id="mm-dir-row">
      <span>Min. Direct Required</span>
      <span id="mm-dir" style="color:#f59e0b">—</span>
    </div>

    <div class="dm-divider"></div>
    <div id="mm-loader" class="dm-loader"><i class="fas fa-spinner fa-spin"></i> Processing…</div>
    <button class="dm-confirm-btn amber-btn" id="mm-confirm-btn" onclick="confirmMatrix()">
      <i class="fas fa-plus-circle"></i> Confirm Purchase
    </button>
    <div style="font-size:10px;color:#333;text-align:center;margin-top:8px">Transaction will be sent from your connected
      wallet</div>
  </div>
</div>

<!-- ══ SCRIPTS ══════════════════════════════════════════════════════════ -->
<script>
  const CONTRACT_ADDR = '<?= CONTRACT_ADDRESS ?>';
  const ADMIN_WALLET = '<?= ADMIN_WALLET ?>';
  const MY_USER_ID = '<?= xe($user['user_id'] ?? '') ?>';
  const SPONSOR_ADDR = '<?php
  $sqD = $db->prepare("SELECT walletAddress FROM meddolic_user_details WHERE member_id=? LIMIT 1");
  $sqD->execute([$user['sponser_id'] ?? 0]);
  echo xe($sqD->fetchColumn() ?: ADMIN_WALLET);
  ?>';

  let TRX_PRICE = 3.48;
  fetch('ajaxCalls/getTrxPrice.php').then(r => r.json()).then(d => { if (d.price) TRX_PRICE = parseFloat(d.price); updateTrxAmounts(); });

  function usdToSun(usd) { return Math.ceil((usd / TRX_PRICE) * 1_000_000); }
  function usdToTrx(usd) { return Math.ceil(usd / TRX_PRICE); }

  function updateTrxAmounts() {
    if (window._wm_usd) document.getElementById('wm-trx').textContent = usdToTrx(window._wm_usd) + ' TRX';
    if (window._mm_usd) document.getElementById('mm-trx').textContent = usdToTrx(window._mm_usd) + ' TRX';
  }

  /* ── Modal helpers ───────────────────────────────────────────────────── */
  function openModal(id) { document.getElementById(id).classList.add('open'); }
  function closeModal(id) { document.getElementById(id).classList.remove('open'); }
  document.querySelectorAll('.dash-modal-overlay').forEach(function (el) {
    el.addEventListener('click', function (e) { if (e.target === el) el.classList.remove('open'); });
  });

  /* ── Working (Normal) Package Modal ─────────────────────────────────── */
  var _wpId, _wpUsd, _wpName;
  function openWorkingModal(pkgId, usdAmt, pkgName, directPct, uplinePct, hasTrigger, triggerName) {
    _wpId = pkgId; _wpUsd = usdAmt; _wpName = pkgName;
    window._wm_usd = usdAmt;
    document.getElementById('wm-name').textContent = pkgName;
    document.getElementById('wm-usd').textContent = '$' + usdAmt.toLocaleString();
    document.getElementById('wm-trx').textContent = usdToTrx(usdAmt) + ' TRX';
    document.getElementById('wm-direct').textContent = directPct + '%';
    document.getElementById('wm-upline').textContent = uplinePct + '%';
    var tb = document.getElementById('wm-trigger-box');
    if (hasTrigger && triggerName) {
      document.getElementById('wm-trigger-name').textContent = triggerName;
      tb.style.display = 'block';
    } else { tb.style.display = 'none'; }
    document.getElementById('wm-loader').style.display = 'none';
    document.getElementById('wm-confirm-btn').style.display = 'block';
    openModal('workingModal');
  }

  async function confirmWorking() {
    document.getElementById('wm-loader').style.display = 'block';
    document.getElementById('wm-confirm-btn').style.display = 'none';
    try {
      // Replace this block with real TronLink contract call:
      const result = { txHash: 'DEMO_W_' + _wpId + '_' + Date.now(), myWallet: SPONSOR_ADDR };

      const fd = new FormData();
      fd.append('pkg_id', _wpId);
      fd.append('pkg_price', _wpUsd);
      fd.append('trx_amount', usdToTrx(_wpUsd));
      fd.append('trx_hash', result.txHash);
      fd.append('wallet', result.myWallet);
      fd.append('trx_price', TRX_PRICE);

      const r = await fetch('ajaxCalls/buyNormalPackage.php', { method: 'POST', body: fd });
      const d = await r.json();
      if (d.status === 'ok') {
        closeModal('workingModal');
        showSuccessToast('✅ Upgraded to ' + _wpName + '!');
        setTimeout(() => location.reload(), 1800);
      } else {
        showSuccessToast('❌ ' + d.message);
        document.getElementById('wm-loader').style.display = 'none';
        document.getElementById('wm-confirm-btn').style.display = 'block';
      }
    } catch (err) {
      showSuccessToast('Error: ' + err.message);
      document.getElementById('wm-loader').style.display = 'none';
      document.getElementById('wm-confirm-btn').style.display = 'block';
    }
  }

  /* ── Matrix Package Modal ────────────────────────────────────────────── */
  var _mmId, _mmUsd, _mmName, _mmIsExtra;
  function openMatrixModal(matrixId, usdAmt, name, dirReq, isExtra) {
    _mmId = matrixId; _mmUsd = usdAmt; _mmName = name; _mmIsExtra = isExtra;
    window._mm_usd = usdAmt;
    document.getElementById('mm-name').textContent = name + (isExtra ? ' — Extra Slot' : '');
    document.getElementById('mm-usd').textContent = '$' + usdAmt.toLocaleString();
    document.getElementById('mm-trx').textContent = usdToTrx(usdAmt) + ' TRX';

    // 100% income box: hide on extra slot
    document.getElementById('mm-income-box').style.display = isExtra ? 'none' : 'block';

    var dirRow = document.getElementById('mm-dir-row');
    if (dirReq > 0) {
      document.getElementById('mm-dir').textContent = dirReq + ' active directs';
      dirRow.style.display = 'flex';
    } else { dirRow.style.display = 'none'; }

    document.getElementById('mm-confirm-btn').textContent =
      (isExtra ? '⊕ Buy Extra Slot' : '✚ Confirm Purchase') + ' — $' + usdAmt.toLocaleString();
    document.getElementById('mm-loader').style.display = 'none';
    document.getElementById('mm-confirm-btn').style.display = 'block';
    openModal('matrixModal');
  }

  async function confirmMatrix() {
    document.getElementById('mm-loader').style.display = 'block';
    document.getElementById('mm-confirm-btn').style.display = 'none';
    try {
      // Replace with real TronLink call:
      const result = { txHash: 'DEMO_M_' + _mmId + '_' + Date.now(), myWallet: SPONSOR_ADDR };

      const fd = new FormData();
      fd.append('matrix_id', _mmId);
      fd.append('pkg_price', _mmUsd);
      fd.append('trx_amount', usdToTrx(_mmUsd));
      fd.append('trx_hash', result.txHash);
      fd.append('wallet', result.myWallet);
      fd.append('trx_price', TRX_PRICE);

      const r = await fetch('ajaxCalls/buyMatrixPackage.php', { method: 'POST', body: fd });
      const d = await r.json();
      if (d.status === 'ok') {
        closeModal('matrixModal');
        showSuccessToast('✅ Joined ' + _mmName + '!');
        setTimeout(() => location.reload(), 1800);
      } else {
        showSuccessToast('❌ ' + d.message);
        document.getElementById('mm-loader').style.display = 'none';
        document.getElementById('mm-confirm-btn').style.display = 'block';
      }
    } catch (err) {
      showSuccessToast('Error: ' + err.message);
      document.getElementById('mm-loader').style.display = 'none';
      document.getElementById('mm-confirm-btn').style.display = 'block';
    }
  }

  /* ── Success toast ───────────────────────────────────────────────────── */
  function showSuccessToast(msg) {
    var t = document.createElement('div');
    t.textContent = msg;
    Object.assign(t.style, {
      position: 'fixed', bottom: '24px', left: '50%', transform: 'translateX(-50%)',
      background: '#22c55e', color: '#000', padding: '12px 24px', borderRadius: '10px',
      fontWeight: '700', fontSize: '13px', zIndex: '99999',
      boxShadow: '0 4px 20px rgba(34,197,94,.4)', transition: 'opacity .4s'
    });
    document.body.appendChild(t);
    setTimeout(() => { t.style.opacity = '0'; setTimeout(() => t.remove(), 400); }, 1400);
  }

  /* ── Copy referral link ──────────────────────────────────────────────── */
  function copyText(id) {
    const el = document.getElementById(id);
    el.select(); document.execCommand('copy');
    showSuccessToast('Referral link copied!');
  }
</script>