<?php
/**
 * User/NormalPackages.php  v8
 *
 * UNLOCK SEQUENCE (exact):
 *   Register ($30+$40)
 *     → Step3 ($60): NEXT (unlocked)
 *
 *   Buy Step3 ($60)
 *     → SMART GLOBAL $100: AUTO-ENTERED immediately (free, system places you)
 *     → SMART GLOBAL $100: also UNLOCKED for extra manual purchase
 *     → Step4 ($200): NEXT  ← unlocked because SMART entry now exists in DB
 *
 *   Buy Step4 ($200)
 *     → Step5 ($500): NEXT
 *
 *   Buy Step5 ($500)
 *     → SILVER GLOBAL $500: AUTO-ENTERED + UNLOCKED for extra buy
 *     → Step6 ($4000): NEXT
 *
 *   … and so on.
 *
 * PACKAGE STATUS:
 *   'done'    = already purchased (curPkgId >= pid)
 *   'next'    = available to buy NOW (curPkgId+1 === pid AND global gate satisfied)
 *   'gated'   = sequential turn BUT waiting for global pool entry first
 *   'locked'  = not yet turn
 */
require_once '../connection/db.php';
require_once '../connection/MatrixEngine.php';
requireLogin();

$user = getCurrentUser();

$memberId = (int) $user['member_id'];
// echo "DEBUG: Fetched user from DB, memberId $memberId<br>";
$db = getDB();
$misc = getMiscSetting();
$adminPct = (float) $misc['adminCharge'];
$packages = getPoolList();
$curPkgId = (int) ($user['currentPackage'] ?? 0);

// Global trigger map (from MatrixEngine constant)
$workingTriggersGlobal = MatrixEngine::WORKING_TRIGGERS_GLOBAL; // [pkgId => matrixId]

// Which global pools has user MANUALLY PURCHASED (paid TX — not just auto-entered free)?
// Auto-entry trx_hash starts with 'AUTO_' — those do NOT satisfy the gate.
// Gate is only satisfied when user pays $100/$500/etc manually.
$manualGlobalQ = $db->prepare(
  "SELECT DISTINCT package_id FROM gm_package_purchases
     WHERE member_id=? AND buy_type=3
       AND trx_hash NOT LIKE 'TUTO_%'
       AND status=1"
);
$manualGlobalQ->execute([$memberId]);
// echo "DEBUG: Fetched manual global purchases, count " . $manualGlobalQ->rowCount() . "<br>";
$manuallBoughtGlobal = array_column($manualGlobalQ->fetchAll(), 'package_id', 'package_id');

// $manuallBoughtGlobal[$matrixId] = $matrixId  when manually paid

// All entered globals (auto OR manual) — for display badges
$allEnteredQ = $db->prepare(
  "SELECT DISTINCT poolId FROM meddolic_user_pool_entry_details WHERE memberId=?"
);
$allEnteredQ->execute([$memberId]);
$enteredGlobals = array_column($allEnteredQ->fetchAll(), 'poolId', 'poolId');

// Gate check: is the NEXT working pkg blocked?
// pkg(N+1) is LOCKED if pkg(N) triggered a global that user has NOT manually paid yet
$gateBlocking = false;
$gatingGlobalPkgInfo = null;
if (isset($workingTriggersGlobal[$curPkgId])) {

  $requiredGlobalId = $workingTriggersGlobal[$curPkgId];

  if (!isset($manuallBoughtGlobal[$requiredGlobalId])) {
    $gateBlocking = true;
    // Fetch info about the blocking global pool
    $ggQ = $db->prepare(
      'SELECT * FROM meddolic_config_matrix_package WHERE matrixId=? LIMIT 1'
    );
    $ggQ->execute([$requiredGlobalId]);
    $gatingGlobalPkgInfo = $ggQ->fetch();
  }
}

// Sponsor wallet for contract
$sponsorQ = $db->prepare('SELECT walletAddress FROM meddolic_user_details WHERE member_id=? LIMIT 1');
$sponsorQ->execute([$user['sponser_id'] ?? 0]);
$sponsorWallet = $sponsorQ->fetchColumn() ?: ADMIN_WALLET;

// Upline wallet
$uplineQ = $db->prepare(
  "SELECT ud2.walletAddress FROM meddolic_user_details ud1
     JOIN meddolic_user_details ud2 ON ud2.member_id = ud1.sponser_id
     WHERE ud1.member_id = ? LIMIT 1"
);
$uplineQ->execute([$user['sponser_id'] ?? 0]);
$uplineWallet = $uplineQ->fetchColumn() ?: ADMIN_WALLET;

$pageTitle = 'Working Plan';
$activePage = 'normal';
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">

      <div class="page-header">
        <div class="breadcrumb"><i class="fas fa-home"></i> <i class="fas fa-chevron-right"></i> Working Plan</div>
        <h3>Working Matrix Plan</h3>
        <div class="subtitle">3×3 Manual Purchase — Buy Steps Sequentially</div>
      </div>

      <!-- Info Banner -->


      <!-- Package Cards -->
      <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));
                  gap:14px;margin-bottom:24px">
        <?php foreach ($packages as $p):
          $pid = (int) $p['id'];
          $price = (float) $p['upgradePrice'];
          $dPct = (float) $p['directPercent'];
          $uPct = (float) $p['uplinePercent'];
          $dNet = round($price * $dPct / 100 * (1 - $adminPct / 100), 2);
          $uNet = round($price * $uPct / 100 * (1 - $adminPct / 100), 2);
          $adminAmt = round($price * ($dPct + $uPct) / 100 * $adminPct / 100, 2);

          // Determine status
          if ($curPkgId >= $pid) {
            $status = 'done';
          } elseif ($curPkgId + 1 === $pid) {
            // Sequential next — but is it gated by a global?
            $status = $gateBlocking ? 'gated' : 'next';
          } else {
            $status = 'locked';
          }

          // Auto-global this step triggers (if any)
          $autoGlobalMatrixId = $workingTriggersGlobal[$pid] ?? null;
          $autoGlobalPkg = null;
          if ($autoGlobalMatrixId) {
            $gQ = $db->prepare('SELECT * FROM meddolic_config_matrix_package WHERE matrixId=? LIMIT 1');
            $gQ->execute([$autoGlobalMatrixId]);
            $autoGlobalPkg = $gQ->fetch();
          }
          $alreadyInGlobal = $autoGlobalMatrixId && isset($enteredGlobals[$autoGlobalMatrixId]);

          // Gating info: what global is blocking the NEXT step (for locked cards)
          // i.e. if THIS pkg triggers a global and user hasn't entered, NEXT pkg shows gated
          $gatingGlobalId = $workingTriggersGlobal[$pid] ?? null;
          $gatingGlobalPkg = null;
          if ($gatingGlobalId && !isset($enteredGlobals[$gatingGlobalId])) {
            $ggQ = $db->prepare('SELECT * FROM meddolic_config_matrix_package WHERE matrixId=? LIMIT 1');
            $ggQ->execute([$gatingGlobalId]);
            $gatingGlobalPkg = $ggQ->fetch();
          }

          $cardOpacity = match ($status) {
            'done' => 'opacity:.5',
            'gated' => 'opacity:.7',
            'locked' => 'opacity:.3',
            default => '',
          };
          $cardBorder = match ($status) {
            'next' => 'border-color:rgba(241,145,7,.5);box-shadow:0 0 24px rgba(241,145,7,.1)',
            'gated' => 'border-color:rgba(59,130,246,.3)',
            default => '',
          };
          ?>
          <div class="card" style="position:relative;transition:.2s;<?= $cardOpacity ?>;<?= $cardBorder ?>">

            <!-- Status badge -->
            <div style="position:absolute;top:12px;right:12px">
              <?php if ($status === 'done'): ?>
                <span class="badge badge-green"><i class="fas fa-check"></i> Done</span>
              <?php elseif ($status === 'next'): ?>
                <span class="badge badge-gold">▶ Next</span>
              <?php elseif ($status === 'gated'): ?>
                <span class="badge" style="background:rgba(59,130,246,.12);color:#60a5fa;
                    border:1px solid rgba(59,130,246,.3)">
                  <i class="fas fa-clock"></i> Gated
                </span>
              <?php else: ?>
                <span class="badge" style="background:rgba(255,255,255,.04);color:#333;
                    border:1px solid rgba(255,255,255,.07)">
                  <i class="fas fa-lock"></i> Locked
                </span>
              <?php endif; ?>
            </div>

            <!-- Auto-global badge (what this step triggers) -->
            <?php if ($autoGlobalPkg): ?>
              <div style="position:absolute;top:40px;right:12px">
                <?php if ($alreadyInGlobal): ?>
                  <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">
                    ✓ <?= e($autoGlobalPkg['poolName']) ?> entered
                  </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">
                    ⚡ AUTO <?= e($autoGlobalPkg['poolName']) ?>
                  </span>
                <?php endif; ?>
              </div>
            <?php endif; ?>

            <!-- Step + Price -->
            <div style="margin-bottom:14px;padding-right:75px">
              <div style="font-size:9px;letter-spacing:2px;text-transform:uppercase;color:#444;margin-bottom:4px">
                Step <?= (int) $p['poolLevel'] ?>
              </div>
              <div style="font-family:'Orbitron',sans-serif;font-size:26px;font-weight:900;color:#f19107">
                $<?= number_format($price, 0) ?>
              </div>
              <div style="font-size:12px;color:var(--text-muted);margin-top:3px"><?= e($p['poolName']) ?></div>
            </div>

            <!-- Income boxes -->
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:10px">
              <div style="background:rgba(34,197,94,.06);border:1px solid rgba(34,197,94,.15);
                        border-radius:7px;padding:9px;text-align:center">
                <div style="font-size:9px;color:#555;margin-bottom:3px">Sponsor</div>
                <div style="font-size:15px;font-weight:700;color:#22c55e"><?= $dPct ?>%</div>
                <div style="font-size:10px;color:#555">= $<?= number_format($dNet, 2) ?></div>
              </div>
              <div style="background:rgba(59,130,246,.06);border:1px solid rgba(59,130,246,.15);
                        border-radius:7px;padding:9px;text-align:center">
                <div style="font-size:9px;color:#555;margin-bottom:3px">Upline</div>
                <div style="font-size:15px;font-weight:700;color:#3b82f6"><?= $uPct ?>%</div>
                <div style="font-size:10px;color:#555">= $<?= number_format($uNet, 2) ?></div>
              </div>
            </div>
            <div style="font-size:10px;color:#333;margin-bottom:12px;text-align:center">
              Admin <?= $adminPct ?>% = $<?= number_format($adminAmt, 2) ?>
            </div>

            <!-- Auto-global description (for 'next' status only) -->
            <?php if ($status === 'next' && $autoGlobalPkg && !$alreadyInGlobal): ?>
              <div style="background:rgba(245,158,11,.06);border:1px solid rgba(245,158,11,.2);
                        border-radius:8px;padding:8px 10px;margin-bottom:10px;font-size:11px;
                        color:#b8860b;line-height:1.5">
                <i class="fas fa-bolt"></i>
                Buying this step will <strong>auto-enter</strong> you into
                <strong><?= e($autoGlobalPkg['poolName']) ?></strong>
                ($<?= number_format((float) $autoGlobalPkg['poolPrice'], 0) ?>).
                You can also buy extra slots in that pool manually.
              </div>
            <?php endif; ?>

            <!-- Gated card: tell user which global pool they must pay first -->
            <?php if ($status === 'gated'): ?>
              <div style="background:rgba(59,130,246,.06);border:1px solid rgba(59,130,246,.2);
                        border-radius:8px;padding:10px;font-size:11px;color:#60a5fa;
                        line-height:1.5;margin-bottom:10px">
                <i class="fas fa-info-circle"></i>
                <?php if ($gatingGlobalPkgInfo): ?>
                  Purchase <strong><?= e($gatingGlobalPkgInfo['poolName']) ?></strong>
                  ($<?= number_format((float) $gatingGlobalPkgInfo['poolPrice'], 0) ?>) in
                  <a href="MatrixPackages.php" style="color:#60a5fa;font-weight:700;text-decoration:none">
                    <i class="fas fa-th"></i> Matrix Packages
                  </a>
                  to unlock this step.
                <?php else: ?>
                  Complete the required global pool purchase to unlock this step.
                <?php endif; ?>
              </div>
            <?php endif; ?>

            <!-- Action Button -->
            <?php if ($status === 'done'): ?>
              <button disabled class="btn-gold" style="opacity:.4;font-size:11px">
                <i class="fas fa-check"></i> Completed
              </button>
            <?php elseif ($status === 'locked'): ?>
              <button disabled class="btn-gold" style="opacity:.2;font-size:11px">
                <i class="fas fa-lock"></i> Locked
              </button>
            <?php elseif ($status === 'gated'): ?>
              <button disabled class="btn-gold"
                style="background:linear-gradient(135deg,#1e40af,#1e3a8a);opacity:.8;font-size:11px">
                <i class="fas fa-lock"></i>
                Buy <?= e($gatingGlobalPkgInfo['poolName'] ?? 'Global Pool') ?> First
              </button>
            <?php else: ?>
              <button class="btn-gold"
                onclick="buyPackage(<?= $pid ?>,<?= $price ?>,'<?= e($p['poolName']) ?>',<?= $dPct ?>,<?= $uPct ?>)">
                <i class="fas fa-bolt"></i>
                Upgrade Now — $<?= number_format($price, 0) ?>
              </button>
            <?php endif; ?>

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

      <!-- Purchase History -->
      <div class="card">
        <div class="card-title"><i class="fas fa-history"></i> Purchase History</div>
        <?php
        $histQ = $db->prepare("
            SELECT pp.*, pl.poolName, pl.poolLevel
            FROM gm_package_purchases pp
            LEFT JOIN meddolic_config_pool_list pl ON pl.id = pp.package_id
            WHERE pp.member_id = ? ORDER BY pp.purchase_date DESC LIMIT 50
        ");
        $histQ->execute([$memberId]);
        $hist = $histQ->fetchAll();
        $buyTypes = ['1' => 'Register', '2' => 'Upgrade', '3' => 'Auto Pool', '4' => 'Auto Upgrade'];
        ?>
        <div class="table-responsive">
          <table class="data-table">
            <thead>
              <tr>
                <th>#</th>
                <th>Package</th>
                <th>Price</th>
                <th>TX Hash</th>
                <th>Type</th>
                <th>Date</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($hist)): ?>
                <tr class="empty-row">
                  <td colspan="6">
                    <i class="fas fa-inbox"></i> No purchases yet
                  </td>
                </tr>
              <?php else:
                foreach ($hist as $i => $h): ?>
                  <tr>
                    <td><?= $i + 1 ?></td>
                    <td><span class="badge badge-blue">
                        Step <?= $h['poolLevel'] ?? '?' ?> — <?= e($h['poolName'] ?? 'Pkg ' . $h['package_id']) ?>
                      </span></td>
                    <td class="amount gold">$<?= number_format($h['package_price'], 0) ?></td>
                    <td style="font-family:monospace;font-size:11px;color:#444">
                      <?= $h['trx_hash'] ? e(substr($h['trx_hash'], 0, 16)) . '…' : '—' ?>
                    </td>
                    <td><span class="badge badge-gold"><?= $buyTypes[(string) $h['buy_type']] ?? '—' ?></span></td>
                    <td style="font-size:12px;color:var(--text-muted)">
                      <?= date('d M Y H:i', strtotime($h['purchase_date'])) ?>
                    </td>
                  </tr>
                <?php endforeach; endif; ?>
            </tbody>
          </table>
        </div>
      </div>

    </div>
    <?php require_once 'Include/footer.php'; ?>
  </div>
</div>

<script>
  function showToast(icon, title) {

    const Toast = Swal.mixin({
      toast: true,
      position: "top-end",
      showConfirmButton: false,
      timer: 2500,
      timerProgressBar: true,
      width: '280px',
      padding: '10px'
    });

    Toast.fire({
      icon: icon,
      title: title
    });
  }
  // ════════════════════════════════════════════════════════════════
  const CONTRACT_ADDR = '<?= CONTRACT_ADDRESS ?>';
  const ADMIN_WALLET = '<?= ADMIN_WALLET ?>';
  const SPONSOR_WALLET = '<?= $sponsorWallet ?>';
  const UPLINE_WALLET = '<?= $uplineWallet ?>';
  const MY_USER_ID = '<?= e($user['user_id'] ?? '') ?>';
  const ADMIN_PCT = <?= $adminPct ?>;

  // Auto-global data for confirm dialog
  const AUTO_GLOBAL_MAP = <?= json_encode(
    array_reduce(
      array_keys(MatrixEngine::WORKING_TRIGGERS_GLOBAL),
      function ($carry, $pkgId) use ($db) {
    $matrixId = MatrixEngine::WORKING_TRIGGERS_GLOBAL[$pkgId];
    $r = $db->prepare('SELECT * FROM meddolic_config_matrix_package WHERE matrixId=? LIMIT 1');
    $r->execute([$matrixId]);
    $row = $r->fetch();
    $carry[$pkgId] = $row ? [
      'name' => $row['poolName'],
      'price' => (float) $row['poolPrice'],
    ] : null;
    return $carry;
  },
      []
    ),
    JSON_UNESCAPED_UNICODE
  ) ?>;

  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); }
  function usdToTrx(usd) { return Math.ceil(usd / TRX_PRICE); }

  // ════════════════════════════════════════════════════════════════
  //  BUY PACKAGE
  // ════════════════════════════════════════════════════════════════
  async function buyPackage(pkgId, usdAmt, pkgName, directPct, uplinePct) {
    let preview = {};
    try {
      const pr = await fetch('ajaxCalls/getIncomeCalc.php?pkg_id=' + pkgId);
      preview = (await pr.json()).preview || {};
    } catch (e) { }

    const trxNeeded = usdToTrx(usdAmt);
    const dNet = preview.direct_net ?? (usdAmt * directPct / 100 * (1 - ADMIN_PCT / 100)).toFixed(2);
    const uNet = preview.upline_net ?? (usdAmt * uplinePct / 100 * (1 - ADMIN_PCT / 100)).toFixed(2);
    const autoG = AUTO_GLOBAL_MAP[pkgId] ?? null;

    let msg = '══════════════════════════\n';
    msg += '   WORKING PLAN UPGRADE\n';
    msg += '══════════════════════════\n';
    msg += '📦 ' + pkgName + '\n';
    msg += '💰 $' + usdAmt + ' ≈ ' + trxNeeded + ' TRX\n\n';
    msg += '💵 Income Distribution:\n';
    msg += '  Sponsor → $' + dNet + ' (' + directPct + '% − admin)\n';
    msg += '  Upline  → $' + uNet + ' (' + uplinePct + '% − admin)\n';
    if (autoG) {
      msg += '\n⚡ AUTO-ENTRY INCLUDED:\n';
      msg += '  System will place you in ' + autoG.name + '\n';
      msg += '  ($' + parseInt(autoG.price).toLocaleString() + ') automatically.\n';
      msg += '  You can also buy extra slots there manually.\n';
    }
    msg += '\n─ Auto-Upgrade Rules ─\n';
    msg += '  3 directs → next step auto\n';
    msg += '  9 team    → next step auto\n';
    msg += '  27 team   → next step auto\n';
    msg += '\nConfirm purchase?';

    const confirmBox = await Swal.fire({
      title: 'WORKING PLAN UPGRADE',
      html: '<pre style="text-align:left;font-size:13px">' + msg + '</pre>',
      icon: 'question',
      width: '360px',
      padding: '15px',
      background: '#111214',
      border: '1px solid #ffffff40',
      color: '#fff',
      showCancelButton: true,
      confirmButtonText: 'Confirm Purchase',
      cancelButtonText: 'Cancel',
      confirmButtonColor: '#16a34a',
      cancelButtonColor: '#f53d3d'

    });

    if (!confirmBox.isConfirmed) return;
    document.querySelectorAll('.btn-gold').forEach(b => b.disabled = true);

    try {
      const totalSun = usdToSun(usdAmt);
      const sponsorSun = usdToSun(usdAmt * directPct / 100 * (1 - ADMIN_PCT / 100));
      const uplineSun = usdToSun(usdAmt * uplinePct / 100 * (1 - ADMIN_PCT / 100));
      const adminSun = Math.max(0, totalSun - sponsorSun - uplineSun);

      // ── LIVE CONTRACT CALL (uncomment when deploying) ──────────────
      // const tw = window.tronLink?.tronWeb || window.tronWeb;
      // if (!tw?.defaultAddress?.base58) throw new Error('TronLink not connected');
      // const myWallet = tw.defaultAddress.base58;
      // const contract = await tw.contract().at(CONTRACT_ADDR);
      // const tx = await contract.buyLevel(
      //   MY_USER_ID, Math.round(usdAmt), pkgId, MY_USER_ID,
      //   [SPONSOR_WALLET, UPLINE_WALLET, ADMIN_WALLET],
      //   [sponsorSun, uplineSun, adminSun],
      //   Math.ceil(TRX_PRICE * 100)
      // ).send({ feeLimit:100_000_000, callValue:totalSun, shouldPollResponse:false });
      // if (!tx) throw new Error('No TX returned');
      // const result = { txHash: tx, myWallet };

      // DEMO MODE (remove when live):
      const result = { txHash: 'DEMO_' + pkgId + '_' + Date.now(), myWallet: SPONSOR_WALLET };

      const fd = new FormData();
      fd.append('pkg_id', pkgId);
      fd.append('pkg_price', usdAmt);
      fd.append('trx_amount', usdToTrx(usdAmt));
      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') {
        let ok = '✅ Upgrade successful!\n\n';
        ok += '💵 Sponsor received: $' + (d.income?.sponsor_net ?? dNet) + '\n';
        ok += '💵 Upline received:  $' + (d.income?.upline_net ?? uNet) + '\n';
        if (d.auto_global) {
          ok += '\n⚡ Auto-entered: ' + d.auto_global.poolName +
            ' ($' + parseInt(d.auto_global.poolPrice).toLocaleString() + ')\n';
          ok += '   You can also buy extra slots in Matrix Packages.';
        }
        showToast('success', 'Upgrade Successful!');

        setTimeout(() => {
          location.reload();
        }, 2000);
      } else {
        showToast('error', d.message);
        document.querySelectorAll('.btn-gold').forEach(b => b.disabled = false);
      }
    } catch (err) {
      showToast('error', err.message);
      document.querySelectorAll('.btn-gold').forEach(b => b.disabled = false);
    }
  }
</script>