<?php
/**
 * User/MatrixPackages.php  v8
 *
 * BOTH:
 *   (a) Shows auto-entry status (system enters you when you buy the trigger pkg)
 *   (b) Allows EXTRA MANUAL PURCHASE of additional slots in the same global pool
 *       (separate TX via buyNewMatrix contract call)
 *
 * Pool states:
 *   'locked'    → triggering working pkg not yet bought
 *   'available' → trigger pkg bought → can buy manually (AND already auto-entered)
 *   'active'    → currently running in this pool
 *   'completed' → pool filled, re-entered
 */
require_once '../connection/db.php';
require_once '../connection/MatrixEngine.php';
requireLogin();

$user = getCurrentUser();
$memberId = (int) $user['member_id'];
$db = getDB();
$curWrkPkg = (int) ($user['currentPackage'] ?? 0);

$matrixPkgs = getMatrixPackages();
$poolIncomes = $db->query('SELECT * FROM meddolic_config_pool_income ORDER BY matrixId, poolLevel')->fetchAll();

// All my pool entries indexed by matrixId
$myEntriesQ = $db->prepare(
  "SELECT ped.*, mp.poolName, mp.poolPrice
     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.poolId ASC, ped.entryDate DESC"
);
$myEntriesQ->execute([$memberId]);
$allMyEntries = $myEntriesQ->fetchAll();

// Latest entry per matrixId
$entryByMatrix = [];
foreach ($allMyEntries as $e) {
  $mid = (int) $e['poolId'];
  if (!isset($entryByMatrix[$mid]))
    $entryByMatrix[$mid] = $e;
}

// Trigger map: matrixId → required working pkgId
$triggerMap = MatrixEngine::WORKING_TRIGGERS_GLOBAL; // pkgId => matrixId
$matrixRequiresPkg = array_flip($triggerMap);         // matrixId => pkgId

$pageTitle = 'Matrix Packages';
$activePage = 'matrix';
require_once 'Include/header.php';

$poolColors = [
  'SMART MATRIX' => '#f59e0b',
  'SILVER MATRIX' => '#94a3b8',
  'GOLD MATRIX' => '#eab308',
  'ROYAL MATRIX' => '#8b5cf6',
  'DIAMOND MATRIX' => '#06b6d4',
  'CROWN MATRIX' => '#f43f5e',
];
$poolEmojis = [
  'SMART MATRIX' => '🥉',
  'SILVER MATRIX' => '🥈',
  'GOLD MATRIX' => '🥇',
  'ROYAL MATRIX' => '👑',
  'DIAMOND MATRIX' => '💎',
  'CROWN MATRIX' => '🌟',
];
?>
<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> Global Matrix</div>
        <h3>Global Matrix Plan</h3>
        <div class="subtitle">3×3 Auto-Pool — Auto-Entered + Manual Extra Slots Available</div>
      </div>

      <!-- How it works -->


      <!-- Pool Cards -->
      <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(270px,1fr));
                  gap:16px;margin-bottom:24px">
        <?php foreach ($matrixPkgs as $mp):
          $mid = (int) $mp['matrixId'];
          $poolPrice = (float) $mp['poolPrice'];
          $color = $poolColors[$mp['poolName']] ?? '#f19107';
          $emoji = $poolEmojis[$mp['poolName']] ?? '⭐';

          $entry = $entryByMatrix[$mid] ?? null;
          $isActive = $entry && (int) $entry['poolStatus'] === 1;
          $isComplete = $entry && (int) $entry['poolStatus'] === 0;

          // Re-entry count across all entries in this pool
          $reQ = $db->prepare(
            "SELECT COALESCE(SUM(reEntryCount),0) AS t
               FROM meddolic_user_pool_entry_details WHERE memberId=? AND poolId=?"
          );
          $reQ->execute([$memberId, $mid]);
          $reEntries = (int) ($reQ->fetch()['t'] ?? 0);

          // Slot counts for active entry
          $directCount = 0;
          $grandCount = 0;
          if ($entry) {
            $eid = (int) $entry['entryId'];
            $dcQ = $db->prepare("SELECT COUNT(*) AS c FROM meddolic_user_pool_entry_details WHERE parent1EntryId=? AND poolId=?");
            $dcQ->execute([$eid, $mid]);
            $directCount = (int) ($dcQ->fetch()['c'] ?? 0);
            $gcQ = $db->prepare("SELECT COUNT(*) AS c FROM meddolic_user_pool_entry_details WHERE parent1EntryId IN (SELECT entryId FROM meddolic_user_pool_entry_details WHERE parent1EntryId=? AND poolId=?) AND poolId=?");
            $gcQ->execute([$eid, $mid, $mid]);
            $grandCount = (int) ($gcQ->fetch()['c'] ?? 0);
          }

          // My total earned in this pool
          $earnQ = $db->prepare("SELECT COALESCE(SUM(poolIncome),0) AS t FROM meddolic_user_pool_income WHERE memberId=? AND poolId=?");
          $earnQ->execute([$memberId, $mid]);
          $earned = (float) ($earnQ->fetch()['t'] ?? 0);

          // Is this pool unlocked? (trigger pkg purchased = working step done)
          $requiredPkgId = $matrixRequiresPkg[$mid] ?? 0;
          $reqPkg = null;
          if ($requiredPkgId) {
            $rQ = $db->prepare('SELECT * FROM meddolic_config_pool_list WHERE id=? LIMIT 1');
            $rQ->execute([$requiredPkgId]);
            $reqPkg = $rQ->fetch();
          }
          // Pool is unlocked as soon as user has bought the triggering working step
          $isUnlocked = ($curWrkPkg >= $requiredPkgId && $requiredPkgId > 0);
          $isLocked = !$isUnlocked;

          // Has user manually paid for this global pool (real TX, not just auto-entry)?
          $manualPaidQ = $db->prepare(
            "SELECT id FROM gm_package_purchases
               WHERE member_id=? AND package_id=? AND buy_type=3
                 AND trx_hash NOT LIKE 'AUTO_%' AND status=1 LIMIT 1"
          );
          $manualPaidQ->execute([$memberId, $mid]);
          $hasManuallPaid = (bool) $manualPaidQ->fetch();

          // Has user been auto-entered (free slot from working pkg trigger)?
          $autoEnteredQ = $db->prepare(
            "SELECT id FROM gm_package_purchases
               WHERE member_id=? AND package_id=? AND buy_type=3
                 AND trx_hash LIKE 'AUTO_%' LIMIT 1"
          );
          $autoEnteredQ->execute([$memberId, $mid]);
          $hasAutoEntry = (bool) $autoEnteredQ->fetch();

          // Income config rows for this pool
          $incRows = array_values(array_filter($poolIncomes, fn($r) => (int) $r['matrixId'] === $mid));
          ?>
          <div class="card" style="position:relative;
          border-color:<?= $isActive ? 'rgba(34,197,94,.4)' : ($isLocked ? 'rgba(255,255,255,.05)' : 'rgba(241,145,7,.15)') ?>;
          <?= $isLocked ? 'opacity:.4' : '' ?>">

            <!-- Status badge -->
            <div style="position:absolute;top:12px;right:12px">
              <?php if ($isActive): ?>
                <span class="badge badge-green"><i class="fas fa-circle" style="font-size:8px"></i> Active</span>
              <?php elseif ($isComplete && $reEntries > 0): ?>
                <span class="badge badge-blue">↻ Re-entered ×<?= $reEntries ?></span>
              <?php elseif ($isUnlocked): ?>
                <span class="badge badge-gold">🔓 Unlocked</span>
              <?php else: ?>
                <span class="badge" style="background:rgba(255,255,255,.04);color:#333;
                    border:1px solid rgba(255,255,255,.06)"><i class="fas fa-lock"></i> Locked</span>
              <?php endif; ?>
            </div>

            <!-- Auto-entry status badge -->
            <?php if ($isUnlocked): ?>
              <div style="position:absolute;top:40px;right:12px">
                <?php if ($hasAutoEntry): ?>
                  <span style="background:rgba(34,197,94,.08);border:1px solid rgba(34,197,94,.25);
                             border-radius:4px;padding:2px 7px;font-size:9px;color:#22c55e">
                    ✓ Auto-slot active
                  </span>
                <?php else: ?>
                  <span style="background:rgba(245,158,11,.08);border:1px solid rgba(245,158,11,.3);
                             border-radius:4px;padding:2px 7px;font-size:9px;color:#f59e0b">
                    ⚡ Buy to enter
                  </span>
                <?php endif; ?>
              </div>
            <?php endif; ?>

            <!-- Header -->
            <div style="display:flex;align-items:center;gap:12px;margin-bottom:16px">
              <div style="width:48px;height:48px;border-radius:12px;
                        background:<?= $color ?>22;border:1px solid <?= $color ?>44;
                        display:flex;align-items:center;justify-content:center;
                        font-size:22px;flex-shrink:0"><?= $emoji ?></div>
              <div>
                <div style="font-family:'Orbitron',sans-serif;font-size:18px;font-weight:700;
                          color:<?= $color ?>">$<?= number_format($poolPrice, 0) ?></div>
                <div style="font-size:12px;color:var(--text-muted);margin-top:2px">
                  <?= e($mp['poolName']) ?>
                </div>
              </div>
            </div>

            <!-- Trigger info -->
            <?php if ($reqPkg): ?>
              <div style="font-size:11px;color:#555;margin-bottom:10px">
                <i class="fas fa-bolt" style="color:<?= $color ?>"></i>
                Auto-entered when you buy
                <strong style="color:<?= $color ?>">
                  Step <?= (int) $reqPkg['poolLevel'] ?> ($<?= number_format((float) $reqPkg['upgradePrice'], 0) ?>)
                </strong>
              </div>
            <?php endif; ?>

            <!-- Pool progress (if entered) -->
            <?php if ($entry): ?>
              <div style="background:var(--dark3);border-radius:8px;padding:10px 12px;margin-bottom:12px">
                <div style="font-size:10px;letter-spacing:1px;text-transform:uppercase;
                          color:#444;margin-bottom:8px">Pool Progress</div>
                <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:6px;text-align:center">
                  <div>
                    <div style="font-size:20px;font-weight:700;color:<?= $color ?>"><?= $directCount ?>/3</div>
                    <div style="font-size:9px;color:#555">L1 Direct</div>
                    <div style="font-size:9px;color:#888;margin-top:2px">
                      <?= $directCount < 1 ? '1st→100% to you' : ($directCount < 3 ? '2nd/3rd→50%+50%' : '✓ Full') ?>
                    </div>
                  </div>
                  <div>
                    <div style="font-size:20px;font-weight:700;color:<?= $color ?>"><?= $grandCount ?>/6</div>
                    <div style="font-size:9px;color:#555">L2 Grand</div>
                    <div style="font-size:9px;color:#888;margin-top:2px">50%+50% split</div>
                  </div>
                  <div>
                    <div style="font-size:20px;font-weight:700;color:#22c55e"><?= $reEntries ?></div>
                    <div style="font-size:9px;color:#555">Re-entries</div>
                    <div style="font-size:9px;color:#888;margin-top:2px">auto after fill</div>
                  </div>
                </div>
                <div style="margin-top:10px;height:5px;background:rgba(255,255,255,.06);border-radius:3px">
                  <div style="height:5px;border-radius:3px;background:linear-gradient(90deg,<?= $color ?>,<?= $color ?>88);
                            width:<?= min(100, round(($directCount + $grandCount) / 9 * 100)) ?>%;transition:.3s">
                  </div>
                </div>
                <div style="font-size:10px;color:#444;margin-top:4px;text-align:right">
                  <?= $directCount + $grandCount ?>/9 filled
                </div>
              </div>
            <?php endif; ?>

            <!-- Income structure -->
            <div style="background:var(--dark3);border-radius:8px;padding:10px 12px;margin-bottom:12px">
              <div style="font-size:10px;letter-spacing:1px;text-transform:uppercase;color:#444;margin-bottom:6px">
                Income Structure
              </div>
              <?php foreach ($incRows as $ir): ?>
                <div style="display:flex;justify-content:space-between;margin-bottom:4px">
                  <span style="font-size:12px;color:var(--text-muted)">
                    L<?= $ir['poolLevel'] ?> bonus (<?= $ir['userNeed'] ?> fill)
                  </span>
                  <span style="font-size:12px;font-weight:700;color:<?= $color ?>">
                    $<?= number_format($ir['userIncome'], 0) ?>
                  </span>
                </div>
              <?php endforeach; ?>
              <?php if ($earned > 0): ?>
                <div style="border-top:1px solid rgba(255,255,255,.06);margin-top:8px;
                          padding-top:8px;display:flex;justify-content:space-between">
                  <span style="font-size:11px;color:#555">Total Earned</span>
                  <span style="font-size:12px;font-weight:700;color:#22c55e">
                    $<?= number_format($earned, 2) ?>
                  </span>
                </div>
              <?php endif; ?>
            </div>

            <!-- Action -->
            <?php if ($isLocked): ?>
              <div style="background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.06);
                        border-radius:8px;padding:10px;font-size:11px;color:#333;text-align:center">
                <i class="fas fa-lock"></i>
                Buy <strong>Step <?= (int) ($reqPkg['poolLevel'] ?? '?') ?></strong>
                ($<?= number_format((float) ($reqPkg['upgradePrice'] ?? 0), 0) ?>) in Working Plan to unlock
              </div>

            <?php elseif ($isUnlocked && !$hasManuallPaid && !$isActive): ?>
              <!-- Unlocked and NOT yet manually purchased → PRIMARY BUY button -->
              <?php if ($hasAutoEntry): ?>
                <div style="background:rgba(34,197,94,.06);border:1px solid rgba(34,197,94,.15);
                          border-radius:7px;padding:8px 10px;font-size:11px;color:#22c55e;
                          margin-bottom:8px;line-height:1.5">
                  <i class="fas fa-check-circle"></i>
                  Free <strong>auto-slot</strong> is active. Buy this for an <strong>extra paid slot</strong>.
                </div>
              <?php else: ?>
                <div style="background:rgba(245,158,11,.06);border:1px solid rgba(245,158,11,.2);
                          border-radius:7px;padding:8px 10px;font-size:11px;color:#b8860b;
                          margin-bottom:8px;line-height:1.5">
                  <i class="fas fa-bolt"></i>
                  <strong>Unlocked!</strong> Buy to enter and earn income.<br>
                  <span style="color:#555;font-size:10px">Required to unlock next working step.</span>
                </div>
              <?php endif; ?>
              <button class="btn-gold" onclick="buyGlobalSlot(<?= $mid ?>,<?= $poolPrice ?>,'<?= e($mp['poolName']) ?>')"
                style="background:linear-gradient(135deg,<?= $color ?>,<?= $color ?>cc);font-size:13px;font-weight:700">
                <i class="fas fa-plus-circle"></i>
                Buy <?= e($mp['poolName']) ?> — $<?= number_format($poolPrice, 0) ?>
              </button>

            <?php elseif ($isActive): ?>
              <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
                <a href="MatrixTree.php?pool=<?= $mid ?>" style="display:block;text-align:center;padding:9px;
                        background:<?= $color ?>18;border:1px solid <?= $color ?>44;
                        border-radius:8px;color:<?= $color ?>;font-size:12px;
                        text-decoration:none;font-weight:600">
                  <i class="fas fa-sitemap"></i> View Tree
                </a>
                <button class="btn-gold" onclick="buyGlobalSlot(<?= $mid ?>,<?= $poolPrice ?>,'<?= e($mp['poolName']) ?>')"
                  style="font-size:11px">
                  <i class="fas fa-plus"></i> Extra Slot
                </button>
              </div>

            <?php else: ?>
              <!-- Paid + completed → extra slot -->
              <button class="btn-gold" onclick="buyGlobalSlot(<?= $mid ?>,<?= $poolPrice ?>,'<?= e($mp['poolName']) ?>')"
                style="background:linear-gradient(135deg,<?= $color ?>,<?= $color ?>cc)">
                <i class="fas fa-redo"></i> Buy Extra Slot — $<?= number_format($poolPrice, 0) ?>
              </button>
            <?php endif; ?>

          </div>
        <?php endforeach; ?>
      </div>

      <!-- Entry History -->
      <div class="card">
        <div class="card-title"><i class="fas fa-history"></i> My Pool Entry History</div>
        <?php
        $fullQ = $db->prepare("
            SELECT ped.*, mp.poolName, mp.poolPrice
            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
        ");
        $fullQ->execute([$memberId]);
        $fullHist = $fullQ->fetchAll();
        ?>
        <div class="table-responsive">
          <table class="data-table">
            <thead>
              <tr>
                <th>#</th>
                <th>Pool</th>
                <th>Price</th>
                <th>L1/L2</th>
                <th>Re-entries</th>
                <th>Entered</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($fullHist)): ?>
                <tr class="empty-row">
                  <td colspan="7">
                    <i class="fas fa-inbox"></i>
                    No entries yet. Buy Step 3 in Working Plan to auto-enter SMART pool!
                  </td>
                </tr>
              <?php else:
                foreach ($fullHist as $i => $ph):
                  $eid2 = (int) $ph['entryId'];
                  $dcQ3 = $db->prepare("SELECT COUNT(*) AS c FROM meddolic_user_pool_entry_details WHERE parent1EntryId=? AND poolId=?");
                  $dcQ3->execute([$eid2, $ph['poolId']]);
                  $dc3 = (int) ($dcQ3->fetch()['c'] ?? 0);
                  $gcQ3 = $db->prepare("SELECT COUNT(*) AS c FROM meddolic_user_pool_entry_details WHERE parent1EntryId IN (SELECT entryId FROM meddolic_user_pool_entry_details WHERE parent1EntryId=? AND poolId=?) AND poolId=?");
                  $gcQ3->execute([$eid2, $ph['poolId'], $ph['poolId']]);
                  $gc3 = (int) ($gcQ3->fetch()['c'] ?? 0);
                  ?>
                  <tr>
                    <td><?= $i + 1 ?></td>
                    <td><span class="badge badge-gold"><?= e($ph['poolName'] ?? 'Pool ' . $ph['poolId']) ?></span></td>
                    <td class="amount">$<?= number_format((float) ($ph['poolPrice'] ?? 0), 0) ?></td>
                    <td><?= $dc3 ?>/3 · <?= $gc3 ?>/6</td>
                    <td><?= (int) $ph['reEntryCount'] ?>×</td>
                    <td style="font-size:12px;color:var(--text-muted)">
                      <?= date('d M Y H:i', strtotime($ph['entryDate'])) ?>
                    </td>
                    <td>
                      <?= (int) $ph['poolStatus']
                        ? '<span class="badge badge-green">Running</span>'
                        : '<span class="badge badge-blue">Completed</span>' ?>
                    </td>
                  </tr>
                <?php endforeach; endif; ?>
            </tbody>
          </table>
        </div>
      </div>

    </div>
    <?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'] ?? '') ?>';
  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); }

  async function buyGlobalSlot(matrixId, usdAmt, name) {
    const trxNeeded = Math.ceil(usdAmt / TRX_PRICE);

    if (!confirm(
      '══ EXTRA SLOT — GLOBAL MATRIX ══\n\n' +
      '🌐 Pool: ' + name + '\n' +
      '💰 $' + usdAmt + ' ≈ ' + trxNeeded + ' TRX\n\n' +
      'This buys an EXTRA slot in the global pool.\n' +
      '(System already auto-entered you if eligible.)\n\n' +
      'Income per join:\n' +
      '  1st person under you → 100% to you\n' +
      '  2nd & 3rd → 50% you + 50% your upline\n\n' +
      'Pool fills (9 members) → bonus paid + re-entry\n\n' +
      'Confirm purchase?'
    )) return;

    const tw = window.tronLink?.tronWeb || window.tronWeb;
    if (!tw?.defaultAddress?.base58) { showToast('error', 'TronLink not connected.'); return; }
    const myWallet = tw.defaultAddress.base58;

    try {
      const totalSun = usdToSun(usdAmt);

      const fd = new FormData();
      const randomHash = 'AUTO_' + Math.random().toString(36).substring(2, 10).toUpperCase() + '_' + Date.now();

      fd.append('matrix_id', matrixId);
      fd.append('pkg_price', usdAmt);
      fd.append('trx_amount', Math.ceil(usdAmt / TRX_PRICE));
      fd.append('trx_hash', randomHash);
      fd.append('wallet', 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('✅ Extra slot purchased in ' + name + '!\n\n' +
          'You will earn income as members join under your new slot.\n' +
          'When 9 fill → bonus paid + re-entry.');
        location.reload();
      } else {
        alert('❌ ' + d.message);
      }
    } catch (err) {
      alert('❌ Transaction failed:\n' + err.message);
    }
  }
</script> -->
<script>

  const CONTRACT_ADDR = '<?= CONTRACT_ADDRESS ?>';
  const ADMIN_WALLET = '<?= ADMIN_WALLET ?>';
  const MY_USER_ID = '<?= e($user['user_id'] ?? '') ?>';

  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) * 1000000);
  }

  // Buy extra slot in a global pool
  async function buyGlobalSlot(matrixId, usdAmt, name) {

    const trxNeeded = Math.ceil(usdAmt / TRX_PRICE);

    const confirmBox = await Swal.fire({
      title: '🌐 EXTRA SLOT',
      html:
        '<div style="font-size:13px;text-align:left ;">' +
        '<b>Pool:</b> ' + name + '<br>' +
        '<b>Amount:</b> $' + usdAmt + ' ≈ ' + trxNeeded + ' TRX<br><br>' +

        'Buy <b>extra slot</b> in global pool.<br><br>' +

        '<b>Income</b><br>' +
        '1st → 100% you<br>' +
        '2nd & 3rd → 50% you + 50% upline<br><br>' +

        '9 members → bonus + re-entry' +
        '</div>',

      icon: 'question',
      width: '340px',
      padding: '14px',
      background: '#111214',
      border: '1px solid #ffffff40',
      color: '#fff',
      showCancelButton: true,
      confirmButtonText: 'Buy Slot',
      cancelButtonText: 'Cancel',
      confirmButtonColor: '#16a34a',
      cancelButtonColor: '#ef4444'
    });

    if (!confirmBox.isConfirmed) return;

    const tw = window.tronLink?.tronWeb || window.tronWeb;

    if (!tw?.defaultAddress?.base58) {
      showToast('error', 'TronLink not connected');
      return;
    }

    const myWallet = tw.defaultAddress.base58;

    try {

      const totalSun = usdToSun(usdAmt);

      const fd = new FormData();
      const randomHash = 'AUTO_' + Math.random().toString(36).substring(2, 10).toUpperCase() + '_' + Date.now();

      fd.append('matrix_id', matrixId);
      fd.append('pkg_price', usdAmt);
      fd.append('trx_amount', Math.ceil(usdAmt / TRX_PRICE));
      fd.append('trx_hash', randomHash);
      fd.append('wallet', 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') {

        showToast(
          'success',
          'Extra slot purchased in ' + name + '!'
        );

        setTimeout(() => {
          location.reload();
        }, 2000);

      } else {

        showToast('error', d.message);

      }

    } catch (err) {

      showToast(
        'error',
        'Transaction failed: ' + err.message
      );

    }
  }

</script>