<?php
require_once '../connection/db.php';
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();

// ── Income totals from database ──────────────────────────────────────────────
$refIncome = getReferralIncomeTotal($memberId);
$sponserIncome = getsponsorIncomeTotal($memberId);
$levelIncome = getLevelIncomeTotal($memberId);
$poolIncome = getPoolIncomeTotal($memberId);
$upgradeIncome = getUpgradeIncomeTotal($memberId);
$totalIncome = $refIncome + $levelIncome + $poolIncome + $upgradeIncome;

// ── Team stats from database ─────────────────────────────────────────────────
$directCount = getDirectCount($memberId);
$teamCount = getTeamCount($memberId);

// ── Current package ─────────────────────────────────────────────────────────
$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() ?: [];
}

// ── Packages from DB: manual (normal) ────────────────────────────────────────
$normalPkgs = getPoolList();

// ── Matrix packages from DB ───────────────────────────────────────────────────
$matrixPkgs = getMatrixPackages();

// ── Current matrix pool entries ───────────────────────────────────────────────
$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();

// ── Recent referrals ─────────────────────────────────────────────────────────
$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();

// ── Wallet balance ────────────────────────────────────────────────────────────
$walletBal = (float) ($user['wallet'] ?? 0);

$pageTitle = 'Dashboard';
$activePage = 'dashboard';
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> Dashboard</div>
        <h3>Dashboard</h3>
        <div class="subtitle">
          Welcome, <span><?= e($userId) ?></span>
          &nbsp;|&nbsp; Wallet: <span style="font-family:monospace;font-size:12px;color:#555">
            <?= e(substr($wallet, 0, 12)) . '…' . e(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. Please complete registration payment.
          <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 ? e($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>

      <!-- ── Two columns: Normal Packages + Matrix Packages ──────────────── -->
      <div class="two-col" style="margin-bottom:20px">

        <!-- Normal Packages — with inline Buy buttons -->
        <!-- <div class="card">
          <div class="card-title"><i class="fas fa-layer-group"></i> Normal Package Plan (Manual Purchase)</div>
          <?php
          // Gate check: is next working pkg blocked by needing to buy global?
          $manualGlobalQ2 = $db->prepare(
            "SELECT DISTINCT package_id FROM gm_package_purchases
               WHERE member_id=? AND buy_type=3 AND trx_hash NOT LIKE 'AUTO_%' AND status=1"
          );
          $manualGlobalQ2->execute([$memberId]);
          $paidGlobalIds = array_column($manualGlobalQ2->fetchAll(), 'package_id', 'package_id');
          $wTriggers = MatrixEngine::WORKING_TRIGGERS_GLOBAL;
          $gateBlocking = false;
          if (isset($wTriggers[$curPkgId]) && !isset($paidGlobalIds[$wTriggers[$curPkgId]])) {
            $gateBlocking = true;
          }
          ?>
          <div class="table-responsive">
            <table class="data-table">
              <thead>
                <tr><th>#</th><th>Pool Name</th><th>Package ($)</th><th>Direct%</th><th>Upline%</th><th>Status / Action</th></tr>
              </thead>
              <tbody>
                <?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 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();
                  }
                  ?>
                <tr style="<?= $nStatus === 'locked' ? 'opacity:.4' : ($nStatus === 'gated' ? 'opacity:.7' : '') ?>">
                  <td><?= $i + 1 ?></td>
                  <td>
                    <span class="badge badge-blue"><?= e($p['poolName']) ?></span>
                    <?php if ($trigGlobalPkg && $nStatus !== 'done'): ?>
                      <div style="font-size:9px;color:#f59e0b;margin-top:2px">⚡ AUTO <?= e($trigGlobalPkg['poolName']) ?></div>
                    <?php endif; ?>
                  </td>
                  <td class="amount gold" style="font-weight:700">$<?= number_format($p['upgradePrice'], 0) ?></td>
                  <td><?= $p['directPercent'] ?>%</td>
                  <td><?= $p['uplinePercent'] ?>%</td>
                  <td>
                    <?php if ($nStatus === 'done'): ?>
                      <span class="badge badge-green"><i class="fas fa-check"></i> Done</span>
                    <?php elseif ($nStatus === 'next'): ?>
                      <button class="btn-gold" style="padding:5px 14px;font-size:11px"
                        onclick="dashBuyWorking(<?= $pid ?>,<?= $p['upgradePrice'] ?>,'<?= e($p['poolName']) ?>')">
                        <i class="fas fa-bolt"></i> Upgrade
                      </button>
                    <?php elseif ($nStatus === 'gated'): ?>
                      <span class="badge" style="background:rgba(59,130,246,.12);color:#60a5fa;border:1px solid rgba(59,130,246,.3);font-size:9px">
                        <i class="fas fa-lock"></i> Buy Matrix First
                      </span>
                    <?php else: ?>
                      <span class="badge" style="background:rgba(255,255,255,.04);color:#333;font-size:9px">
                        <i class="fas fa-lock"></i> Locked
                      </span>
                    <?php endif; ?>
                  </td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div> -->

        <!-- Matrix Packages — with inline Buy buttons -->
        <div class="card">
          <div class="card-title"><i class="fas fa-th"></i> Matrix Package Plan (Auto Pool)</div>
          <?php
          // Build matrix status map
          $allEntriesQ2 = $db->prepare("SELECT DISTINCT poolId FROM meddolic_user_pool_entry_details WHERE memberId=?");
          $allEntriesQ2->execute([$memberId]);
          $enteredMatrices = array_column($allEntriesQ2->fetchAll(), 'poolId', 'poolId');
          $matrixRequiresPkg2 = array_flip($wTriggers); // matrixId => required working pkg
          ?>
          <div class="table-responsive">
            <table class="data-table">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Pool Name</th>
                  <th>Price ($)</th>
                  <th>Direct Req</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($matrixPkgs as $i => $mp):
                  $mid = (int) $mp['matrixId'];
                  $reqWrkPkg = $matrixRequiresPkg2[$mid] ?? 0;
                  $isLocked = ($reqWrkPkg > 0 && $curPkgId < $reqWrkPkg);
                  $isEntered = isset($enteredMatrices[$mid]);
                  $dirReqArr = [1 => 0, 2 => 2, 3 => 2, 4 => 2, 5 => 2, 6 => 2];
                  $dirReq = $dirReqArr[$mid] ?? 0;

                  // Check active entry
                  $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;

                  // Check manually paid
                  $mpChk = $db->prepare("SELECT id FROM gm_package_purchases WHERE member_id=? AND package_id=? AND buy_type=3 AND trx_hash NOT LIKE 'AUTO_%' LIMIT 1");
                  $mpChk->execute([$memberId, $mid]);
                  $manuallyPaid = (bool) $mpChk->fetch();
                  ?>
                  <tr style="<?= $isLocked ? 'opacity:.35' : '' ?>">
                    <td><?= $i + 1 ?></td>
                    <td><span class="badge badge-gold"><?= e($mp['poolName']) ?></span></td>
                    <td class="amount">$<?= number_format($mp['poolPrice'], 0) ?></td>
                    <td style="font-size:11px;color:<?= $dirReq > 0 ? '#f59e0b' : '#555' ?>">
                      <?= $dirReq > 0 ? $dirReq . ' actives' : 'None' ?>
                    </td>
                    <td>
                      <?php if ($isActive): ?>
                        <span class="badge badge-green"><i class="fas fa-circle" style="font-size:7px"></i> Active</span>
                      <?php elseif ($isLocked): ?>
                        <span class="badge" style="background:rgba(255,255,255,.04);color:#333;font-size:9px">
                          <i class="fas fa-lock"></i> Locked
                        </span>
                      <?php else: ?>
                        <button class="btn-gold" style="padding:5px 12px;font-size:11px"
                          onclick="dashBuyMatrix(<?= $mid ?>,<?= $mp['poolPrice'] ?>,'<?= e($mp['poolName']) ?>')">
                          <i class="fas fa-plus"></i>
                          <?= $isEntered ? 'Extra Slot' : 'Buy $' . number_format($mp['poolPrice'], 0) ?>
                        </button>
                      <?php endif; ?>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- ── Buy buttons panel (Upgrade Level + Buy Matrix) ──────────────── -->
      <?php
      // Next working package (for "Upgrade Level" button)
      $nextWorkingPkg = null;
      if ($curPkgId > 0) {
        $nwQ = $db->prepare('SELECT * FROM meddolic_config_pool_list WHERE id=? LIMIT 1');
        $nwQ->execute([$curPkgId + 1]);
        $nextWorkingPkg = $nwQ->fetch();
      }
      // Next matrix pool (for "Buy Matrix" button)
      $nextMatrixPkg = null;
      foreach ($matrixPkgs as $mpp) {
        $mid2 = (int) $mpp['matrixId'];
        $reqW = $matrixRequiresPkg2[$mid2] ?? 0;
        if ($curPkgId >= $reqW && !isset($enteredMatrices[$mid2])) {
          // Find manually paid status
          $mpC = $db->prepare("SELECT id FROM gm_package_purchases WHERE member_id=? AND package_id=? AND buy_type=3 AND trx_hash NOT LIKE 'AUTO_%' LIMIT 1");
          $mpC->execute([$memberId, $mid2]);
          if (!$mpC->fetch()) {
            $nextMatrixPkg = $mpp;
            break;
          }
        }
      }
      ?>
      <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:14px;margin-bottom:24px">
        <?php if ($nextWorkingPkg && !$gateBlocking): ?>
          <div class="card" style="border-color:rgba(241,145,7,.4);padding:18px">
            <div style="font-size:10px;letter-spacing:1.5px;text-transform:uppercase;color:#555;margin-bottom:6px">Upgrade
              Level</div>
            <div
              style="font-family:'Orbitron',sans-serif;font-size:18px;font-weight:700;color:#f19107;margin-bottom:12px">
              Upgrade Level <?= (int) $nextWorkingPkg['poolLevel'] ?>
              ($<?= number_format($nextWorkingPkg['upgradePrice'], 0) ?>)
            </div>
            <button class="btn-gold"
              onclick="dashBuyWorking(<?= (int) $nextWorkingPkg['id'] ?>,<?= $nextWorkingPkg['upgradePrice'] ?>,'<?= e($nextWorkingPkg['poolName']) ?>')">
              <i class="fas fa-arrow-up"></i> Upgrade Now
            </button>
          </div>
        <?php endif; ?>

        <?php if ($nextMatrixPkg): ?>
          <div class="card" style="border-color:rgba(245,158,11,.4);padding:18px">
            <div style="font-size:10px;letter-spacing:1.5px;text-transform:uppercase;color:#555;margin-bottom:6px">Buy
              Matrix</div>
            <div
              style="font-family:'Orbitron',sans-serif;font-size:18px;font-weight:700;color:#eab308;margin-bottom:12px">
              Buy Matrix : $<?= number_format($nextMatrixPkg['poolPrice'], 0) ?>
            </div>
            <button class="btn-gold"
              onclick="dashBuyMatrix(<?= (int) $nextMatrixPkg['matrixId'] ?>,<?= $nextMatrixPkg['poolPrice'] ?>,'<?= e($nextMatrixPkg['poolName']) ?>')"
              style="background:linear-gradient(135deg,#eab308,#ca8a04)">
              <i class="fas fa-plus-circle"></i> Buy Matrix
            </button>
          </div>
        <?php endif; ?>

        <div class="card" style="padding:18px">
          <div style="font-size:10px;letter-spacing:1.5px;text-transform:uppercase;color:#555;margin-bottom:6px">Pending
            Matrix</div>
          <?php
          $pendQ = $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=? AND ped.poolStatus=1 LIMIT 3");
          $pendQ->execute([$memberId]);
          $pendMatrices = $pendQ->fetchAll();
          ?>
          <?php if (empty($pendMatrices)): ?>
            <div style="font-size:12px;color:#444;text-align:center;padding:10px"><i class="fas fa-inbox"></i> No active
              pools</div>
          <?php else: ?>
            <table style="width:100%;font-size:12px;border-collapse:collapse">
              <tr style="color:#444;font-size:10px;border-bottom:1px solid rgba(255,255,255,.05)">
                <td style="padding:4px 0">#</td>
                <td>Date</td>
                <td>Matrix</td>
              </tr>
              <?php foreach ($pendMatrices as $pi => $pm): ?>
                <tr>
                  <td style="padding:4px 0;color:#555"><?= $pi + 1 ?></td>
                  <td style="color:#666"><?= date('d M', strtotime($pm['entryDate'])) ?></td>
                  <td><span class="badge badge-gold"
                      style="font-size:9px"><?= e($pm['poolName'] ?? 'Pool ' . $pm['poolId']) ?></span></td>
                </tr>
              <?php endforeach; ?>
            </table>
          <?php endif; ?>
        </div>

        <div class="card" style="padding:18px;text-align:center">
          <div style="font-size:10px;letter-spacing:1.5px;text-transform:uppercase;color:#555;margin-bottom:8px">Total
            Users</div>
          <?php
          $totalUsersQ = $db->query("SELECT COUNT(*) AS c FROM meddolic_user_details WHERE topup_flag=1");
          $totalUsers = (int) ($totalUsersQ->fetch()['c'] ?? 0);
          ?>
          <div style="font-size:32px;font-weight:900;color:#f19107;font-family:'Orbitron',sans-serif">
            <?= number_format($totalUsers) ?>
          </div>
          <div style="font-size:11px;color:#444;margin-top:4px">Active Members</div>
        </div>
      </div>

      <!-- ── Recent Referrals ─────────────────────────────────────────────── -->
      <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"><?= e($r['user_id']) ?></td>
                      <td style="font-family:monospace;font-size:11px;color:#555">
                        <?= e(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>

        <!-- My Pool Entries -->
        <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"><?= e($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="<?= e('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>

<script>
  const CONTRACT_ADDR = '<?= CONTRACT_ADDRESS ?>';
  const ADMIN_WALLET = '<?= ADMIN_WALLET ?>';
  const MY_USER_ID = '<?= e($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 e($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); });

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

  // ── Buy Working Package directly from Dashboard ───────────────────────
  async function dashBuyWorking(pkgId, usdAmt, pkgName) {
    if (!confirm('⬆ UPGRADE\n\n' + pkgName + '\n$' + usdAmt + ' ≈ ' + Math.ceil(usdAmt / TRX_PRICE) + ' TRX\n\nConfirm?')) return;

    // DEMO — replace with real contract call
    const result = { txHash: 'DEMO_W_' + pkgId + '_' + Date.now(), myWallet: SPONSOR_ADDR };

    const fd = new FormData();
    fd.append('pkg_id', pkgId); fd.append('pkg_price', usdAmt);
    fd.append('trx_amount', Math.ceil(usdAmt / TRX_PRICE)); 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') { alert('✅ Upgraded to ' + pkgName); location.reload(); }
    else alert('❌ ' + d.message);
  }

  // ── Buy Matrix Package directly from Dashboard ────────────────────────
  async function dashBuyMatrix(matrixId, usdAmt, name) {
    if (!confirm('🌐 BUY MATRIX\n\n' + name + '\n$' + usdAmt + ' ≈ ' + Math.ceil(usdAmt / TRX_PRICE) + ' TRX\n\n1st join → 100% income to you\n2nd/3rd → 50%+50% split\n\nConfirm?')) return;

    // DEMO — replace with real contract call
    const result = { txHash: 'DEMO_M_' + matrixId + '_' + Date.now(), myWallet: SPONSOR_ADDR };

    const fd = new FormData();
    fd.append('matrix_id', matrixId); fd.append('pkg_price', usdAmt);
    fd.append('trx_amount', Math.ceil(usdAmt / TRX_PRICE)); 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') { alert('✅ Joined ' + name + '!'); location.reload(); }
    else alert('❌ ' + d.message);
  }

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