<?php
/**
 * register/Register.php
 *
 * ══ REGISTRATION FLOW (NEW) ═══════════════════════════════════════════════
 *
 *  ONE CLICK → ONE TRX TRANSACTION → $70 total
 *
 *  Contract: NewRegistration()
 *    contributors[0] = SPONSOR  ← $15 (sponsor income, first-time only)
 *    contributors[1] = ADMIN    ← $55 (rest goes to admin / company)
 *
 *  Backend records BOTH packages at once:
 *    pkg1 = $30  (GLOBAL COMMUNITY 1)
 *    pkg2 = $40  (GLOBAL COMMUNITY 2)
 *
 *  After registration, user can manually buy Step 3 ($60):
 *    Contract: buyLevel()
 *    Income: 60% ($36) → sponsor   |  40% ($24) → upline
 *    Side effect: triggers SMART Matrix $100 auto-pool entry (non-working)
 *
 * ══════════════════════════════════════════════════════════════════════════
 */
require_once '../connection/db.php';
redirectIfLoggedIn();

$db = getDB();
// Fetch registration packages (id=1 → $30, id=2 → $40)
$pkgQ = $db->query('SELECT * FROM meddolic_config_pool_list WHERE poolStatus=1 ORDER BY poolLevel ASC LIMIT 2');
$regPkgs = $pkgQ->fetchAll();
$pkg1 = $regPkgs[0] ?? ['id' => 1, 'upgradePrice' => 30, 'poolName' => 'Global Community 1'];
$pkg2 = $regPkgs[1] ?? ['id' => 2, 'upgradePrice' => 40, 'poolName' => 'Global Community 2'];
$totalUsd = (float) $pkg1['upgradePrice'] + (float) $pkg2['upgradePrice']; // $70

// Sponsor income on registration = $15 (first time only, hardcoded per plan)
$sponsorRegIncome = 15.00;
$adminRegIncome = $totalUsd - $sponsorRegIncome;  // $55

$pageTitle = 'Register';
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Register | Hissho Global</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@700;900&family=Inter:wght@400;500;700&display=swap"
    rel="stylesheet">
  <link rel="shortcut icon" href="../User/assets/img/favicon.png" type="image/x-icon">
  <style>
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0
    }

    body {
      background: #0a0b0d;
      color: #e8e8e8;
      font-family: 'Inter', sans-serif;
      min-height: 100vh;
      display: flex;
      align-items: flex-start;
      justify-content: center;
      padding: 30px 16px;
      background-image: radial-gradient(ellipse 60% 50% at 50% 0%, rgba(241, 145, 7, .09) 0%, transparent 70%)
    }

    .card {
      background: #13151a;
      border: 1px solid rgba(241, 145, 7, .15);
      border-radius: 18px;
      padding: 36px 32px;
      width: 100%;
      max-width: 540px;
      box-shadow: 0 24px 80px rgba(0, 0, 0, .7)
    }

    /* logo */
    .logo-icon {
      width: 58px;
      height: 58px;
      border-radius: 50%;
      /* background: linear-gradient(135deg, #f19107, #c97800); */
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 25px;
      color: #000;
      margin: 0 auto 10px;
      /* box-shadow: 0 0 40px rgba(241, 145, 7, .4) */
    }

    .logo-icon img {
      width: 180%;
    }

    h1.brand {
      font-family: 'Orbitron', sans-serif;
      font-size: 19px;
      font-weight: 900;
      color: #f19107;
      letter-spacing: 3px;
      text-align: center
    }

    .subtitle {
      font-size: 10px;
      letter-spacing: 2px;
      text-transform: uppercase;
      color: #444;
      text-align: center;
      margin-top: 3px;
      margin-bottom: 22px
    }

    /* ── payment flow summary ── */
    .flow-box {
      background: rgba(241, 145, 7, .05);
      border: 1px solid rgba(241, 145, 7, .15);
      border-radius: 12px;
      padding: 16px;
      margin-bottom: 16px
    }

    .flow-title {
      font-size: 10px;
      letter-spacing: 2px;
      text-transform: uppercase;
      color: #555;
      margin-bottom: 12px
    }

    .flow-row {
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 8px 0;
      border-bottom: 1px solid rgba(255, 255, 255, .04)
    }

    .flow-row:last-child {
      border-bottom: none;
      padding-bottom: 0
    }

    .flow-icon {
      width: 30px;
      height: 30px;
      border-radius: 7px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 13px;
      flex-shrink: 0
    }

    .flow-icon.gold {
      background: rgba(241, 145, 7, .15);
      color: #f19107
    }

    .flow-icon.green {
      background: rgba(34, 197, 94, .1);
      color: #22c55e
    }

    .flow-icon.blue {
      background: rgba(59, 130, 246, .1);
      color: #3b82f6
    }

    .flow-icon.red {
      background: rgba(239, 68, 68, .1);
      color: #ef4444
    }

    .flow-label {
      flex: 1;
      font-size: 12px;
      color: #888
    }

    .flow-label strong {
      color: #e8e8e8
    }

    .flow-amount {
      font-family: 'Orbitron', sans-serif;
      font-size: 13px;
      font-weight: 700
    }

    .flow-amount.gold {
      color: #f19107
    }

    .flow-amount.green {
      color: #22c55e
    }

    .flow-amount.blue {
      color: #3b82f6
    }

    .flow-amount.red {
      color: #ef4444
    }

    /* pkg summary row */
    .pkg-split {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 8px;
      margin-bottom: 12px
    }

    .pkg-cell {
      background: #0f1114;
      border: 1px solid rgba(241, 145, 7, .1);
      border-radius: 8px;
      padding: 10px;
      text-align: center
    }

    .pkg-cell .step {
      font-size: 9px;
      letter-spacing: 1.5px;
      text-transform: uppercase;
      color: #444
    }

    .pkg-cell .amt {
      font-family: 'Orbitron', sans-serif;
      font-size: 17px;
      font-weight: 700;
      color: #f19107;
      margin: 3px 0
    }

    .pkg-cell .nm {
      font-size: 10px;
      color: #444
    }

    /* total badge */
    .total-pill {
      background: linear-gradient(135deg, rgba(241, 145, 7, .2), rgba(241, 145, 7, .08));
      border: 1px solid rgba(241, 145, 7, .35);
      border-radius: 10px;
      padding: 12px 18px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 18px
    }

    .total-pill .lbl {
      font-size: 11px;
      letter-spacing: 1px;
      text-transform: uppercase;
      color: #888
    }

    .total-pill .val {
      font-family: 'Orbitron', sans-serif;
      font-size: 22px;
      font-weight: 900;
      color: #f19107
    }

    .total-pill .sub {
      font-size: 10px;
      color: #555;
      text-align: right
    }

    /* form */
    .form-group {
      margin-bottom: 14px
    }

    .form-group label {
      display: block;
      font-size: 11px;
      font-weight: 600;
      letter-spacing: .8px;
      text-transform: uppercase;
      color: #666;
      margin-bottom: 6px
    }

    .input-wrap {
      position: relative
    }

    .input-wrap i.ico {
      position: absolute;
      left: 12px;
      top: 50%;
      transform: translateY(-50%);
      color: #444;
      pointer-events: none
    }

    .form-control {
      width: 100%;
      background: #0c0d10;
      border: 1px solid rgba(241, 145, 7, .1);
      border-radius: 8px;
      padding: 11px 12px 11px 34px;
      color: #e8e8e8;
      font-size: 13px;
      outline: none;
      transition: .15s
    }

    .form-control:focus {
      border-color: rgba(241, 145, 7, .35)
    }

    .form-control::placeholder {
      color: #2a2a2a
    }

    .detect-btn {
      background: rgba(241, 145, 7, .07);
      border: 1px solid rgba(241, 145, 7, .15);
      color: #f19107;
      padding: 6px 12px;
      border-radius: 7px;
      font-size: 11px;
      cursor: pointer;
      margin-top: 6px;
      transition: .15s
    }

    .detect-btn:hover {
      background: rgba(241, 145, 7, .15)
    }

    .info-row {
      display: flex;
      gap: 8px;
      background: rgba(59, 130, 246, .06);
      border: 1px solid rgba(59, 130, 246, .18);
      border-radius: 8px;
      padding: 10px 12px;
      font-size: 11px;
      color: #94a3b8;
      line-height: 1.5;
      margin-bottom: 14px
    }

    .btn {
      display: block;
      width: 100%;
      padding: 15px;
      background: linear-gradient(135deg, #f19107, #c97800);
      color: #000;
      border: none;
      border-radius: 10px;
      font-size: 13px;
      font-weight: 800;
      letter-spacing: 1.5px;
      text-transform: uppercase;
      cursor: pointer;
      font-family: 'Orbitron', sans-serif;
      transition: .2s
    }

    .btn:hover:not(:disabled) {
      transform: translateY(-1px);
      box-shadow: 0 8px 28px rgba(241, 145, 7, .4)
    }

    .btn:disabled {
      opacity: .5;
      cursor: not-allowed
    }

    .alert {
      border-radius: 8px;
      padding: 11px 14px;
      margin-bottom: 14px;
      font-size: 12px;
      display: none
    }

    .alert-err {
      background: rgba(239, 68, 68, .1);
      border: 1px solid rgba(239, 68, 68, .25);
      color: #ef4444
    }

    .alert-ok {
      background: rgba(34, 197, 94, .07);
      border: 1px solid rgba(34, 197, 94, .2);
      color: #22c55e
    }

    /* status log */
    #txLog {
      background: #080a0c;
      border: 1px solid rgba(241, 145, 7, .1);
      border-radius: 8px;
      padding: 10px 14px;
      font-size: 11px;
      font-family: monospace;
      margin-top: 12px;
      display: none;
      max-height: 180px;
      overflow-y: auto
    }

    .ll {
      padding: 3px 0;
      border-bottom: 1px solid rgba(255, 255, 255, .03)
    }

    .ll.ok {
      color: #22c55e;
      border: none
    }

    .ll.err {
      color: #ef4444;
      border: none
    }

    .ll.info {
      color: #f19107;
      border: none
    }

    /* step bar */
    .sbar {
      display: flex;
      gap: 0;
      margin-bottom: 18px;
      border-radius: 8px;
      overflow: hidden;
      border: 1px solid rgba(241, 145, 7, .1)
    }

    .sb {
      flex: 1;
      padding: 8px 4px;
      text-align: center;
      font-size: 10px;
      font-weight: 700;
      letter-spacing: 1px;
      text-transform: uppercase;
      background: #0f1114;
      color: #333;
      border-right: 1px solid rgba(241, 145, 7, .08)
    }

    .sb:last-child {
      border-right: none
    }

    .sb.done {
      background: rgba(34, 197, 94, .08);
      color: #22c55e
    }

    .sb.active {
      background: rgba(241, 145, 7, .1);
      color: #f19107
    }

    .links {
      text-align: center;
      margin-top: 18px;
      font-size: 13px;
      color: #444
    }

    .links a {
      color: #f19107;
      font-weight: 700;
      text-decoration: none
    }
  </style>
</head>

<body>
  <div class="card">

    <!-- Logo -->
    <div class="logo-icon"><img src="../User/assets/img/logo.png" alt=""></div>
    <h1 class="brand">Hissho Global</h1>
    <div class="subtitle">New Member Registration</div>

    <!-- Step bar -->
    <div class="sbar">
      <div class="sb active" id="sb1">① Connect</div>
      <div class="sb" id="sb2">② Pay $<?= number_format($totalUsd, 0) ?></div>
      <div class="sb" id="sb3">③ Active</div>
    </div>

    <!-- Payment breakdown -->
    <div class="flow-box">
      <div class="flow-title"><i class="fas fa-receipt"></i>&nbsp; One-Time Registration —
        $<?= number_format($totalUsd, 0) ?> Total</div>

      <!-- What you're buying -->
      <div class="pkg-split">
        <div class="pkg-cell">
          <div class="step">Package 1</div>
          <div class="amt">$<?= number_format($pkg1['upgradePrice'], 0) ?></div>
          <div class="nm"><?= e($pkg1['poolName']) ?></div>
        </div>
        <div class="pkg-cell">
          <div class="step">Package 2</div>
          <div class="amt">$<?= number_format($pkg2['upgradePrice'], 0) ?></div>
          <div class="nm"><?= e($pkg2['poolName']) ?></div>
        </div>
      </div>

      <!-- Who gets what -->
      <div class="flow-row">
        <div class="flow-icon green"><i class="fas fa-user-tie"></i></div>
        <div class="flow-label">
          <strong>Sponsor Income</strong><br>
          Paid directly to your referrer's wallet
        </div>
        <div class="flow-amount green">$<?= number_format($sponsorRegIncome, 0) ?></div>
      </div>
    </div>

    <!-- Total TRX pill -->
    <div class="total-pill">
      <div>
        <div class="lbl">Total to Pay (1 Transaction)</div>
        <div class="val" id="totalTrxAmt">— TRX</div>
      </div>
      <div class="sub">
        $<?= number_format($totalUsd, 0) ?> USD<br>
        <span id="trxPriceShow" style="font-size:9px;color:#444">loading rate…</span>
      </div>
    </div>

    <!-- Info banner -->
    <div class="info-row">
      <i class="fas fa-info-circle" style="color:#3b82f6;margin-top:1px;flex-shrink:0"></i>
      <span>
        One TRX transaction covers <strong style="color:#e8e8e8">both packages</strong>
        ($<?= number_format($pkg1['upgradePrice'], 0) ?> + $<?= number_format($pkg2['upgradePrice'], 0) ?>).
        The contract automatically sends <strong
          style="color:#22c55e">$<?= number_format($sponsorRegIncome, 0) ?></strong>
        to your sponsor and <strong style="color:#3b82f6">$<?= number_format($adminRegIncome, 0) ?></strong>
        to the platform — all in a single click.
      </span>
    </div>

    <!-- Alerts -->
    <div id="errBox" class="alert alert-err"><i class="fas fa-exclamation-circle"></i> <span id="errTxt"></span></div>
    <div id="okBox" class="alert alert-ok"><i class="fas fa-check-circle"></i> <span id="okTxt"></span></div>

    <!-- Sponsor wallet -->
    <div class="form-group">
      <label>Sponsor Wallet <span style="color:#ef4444">*</span></label>
      <div class="input-wrap">
        <i class="ico fas fa-link"></i>
        <input type="text" id="refWallet" class="form-control" placeholder="Sponsor TRX wallet address"
          value="<?= e($_GET['ref'] ?? '') ?>">
      </div>
    </div>

    <!-- My wallet -->
    <div class="form-group">
      <label>Your TRX Wallet <span style="color:#ef4444">*</span></label>
      <div class="input-wrap">
        <i class="ico fas fa-wallet"></i>
        <input type="text" id="myWallet" class="form-control" readonly placeholder="Auto-detected from TronLink">
      </div>
      <button type="button" class="detect-btn" onclick="detectWallet()">
        <i class="fas fa-plug"></i> Detect TronLink Wallet
      </button>
    </div>

    <!-- Terms -->
    <div style="display:flex;align-items:center;gap:8px;margin-bottom:16px">
      <input type="checkbox" id="terms" style="width:15px;height:15px;accent-color:#f19107">
      <label for="terms" style="font-size:12px;color:#666">
        I agree that blockchain transactions are irreversible. I understand the income structure.
      </label>
    </div>

    <!-- REGISTER BUTTON -->
    <button id="regBtn" class="btn" onclick="doRegister()">
      <i class="fas fa-rocket"></i>&nbsp; REGISTER &amp; PAY $<?= number_format($totalUsd, 0) ?>
    </button>

    <!-- TX Log -->
    <div id="txLog">
      <div style="font-size:9px;letter-spacing:2px;text-transform:uppercase;color:#333;margin-bottom:6px">TRANSACTION
        LOG</div>
      <div id="logLines"></div>
    </div>

    <div class="links">Already have an account? <a href="Login.php">Login Here</a></div>
  </div>

  <script>
    // ════════════════════════════════════════════════════════════════════════════
    //  CONFIG — passed from PHP
    // ════════════════════════════════════════════════════════════════════════════
    const ADMIN_WALLET = '<?= ADMIN_WALLET ?>';
    const CONTRACT_ADDR = '<?= CONTRACT_ADDRESS ?>';

    // Package IDs (pool_list)
    const PKG1_ID = <?= (int) $pkg1['id'] ?>;
    const PKG2_ID = <?= (int) $pkg2['id'] ?>;
    const PKG1_USD = <?= (float) $pkg1['upgradePrice'] ?>;   // $30
    const PKG2_USD = <?= (float) $pkg2['upgradePrice'] ?>;   // $40
    const TOTAL_USD = PKG1_USD + PKG2_USD;                   // $70

    // Sponsor income on registration
    const SPONSOR_REG_INCOME = <?= $sponsorRegIncome ?>;    // $15
    const ADMIN_REG_INCOME = <?= $adminRegIncome ?>;      // $55

    let TRX_PRICE = 3.48;

    // ════════════════════════════════════════════════════════════════════════════
    //  INIT
    // ════════════════════════════════════════════════════════════════════════════
    window.addEventListener('load', async () => {
      // Fetch live TRX price
      try {
        const r = await fetch('../User/ajaxCalls/getTrxPrice.php');
        const d = await r.json();
        if (d.price) TRX_PRICE = parseFloat(d.price);
      } catch (e) { }
      updateTotalDisplay();
      setTimeout(detectWallet, 800);
    });

    function updateTotalDisplay() {
      const totalTrx = Math.ceil(TOTAL_USD / TRX_PRICE);
      document.getElementById('totalTrxAmt').textContent = totalTrx + ' TRX';
      document.getElementById('trxPriceShow').textContent = '1 TRX ≈ $' + TRX_PRICE.toFixed(2);
    }

    // ════════════════════════════════════════════════════════════════════════════
    //  TRONLINK DETECT
    // ════════════════════════════════════════════════════════════════════════════
    async function detectWallet() {
      const tw = window.tronLink?.tronWeb || window.tronWeb;
      if (!tw) return;
      try {
        let addr = tw.defaultAddress?.base58 || '';
        if (!addr && window.tronLink) {
          await window.tronLink.request({ method: 'tron_requestAccounts' });
          addr = window.tronLink.tronWeb?.defaultAddress?.base58 || '';
        }
        if (addr) document.getElementById('myWallet').value = addr;
        else showErr('Could not detect wallet — unlock TronLink and retry.');
      } catch (e) { showErr('TronLink error: ' + e.message); }
    }

    // ════════════════════════════════════════════════════════════════════════════
    //  HELPERS
    // ════════════════════════════════════════════════════════════════════════════
    function setStep(n) {
      ['sb1', 'sb2', 'sb3'].forEach((id, i) => {
        const el = document.getElementById(id);
        el.classList.toggle('active', i + 1 === n);
        el.classList.toggle('done', i + 1 < n);
      });
    }
    function showErr(m) { hideAlerts(); document.getElementById('errTxt').textContent = m; document.getElementById('errBox').style.display = 'block'; }
    function showOk(m) { hideAlerts(); document.getElementById('okTxt').textContent = m; document.getElementById('okBox').style.display = 'block'; }
    function hideAlerts() { document.getElementById('errBox').style.display = 'none'; document.getElementById('okBox').style.display = 'none'; }
    function addLog(msg, cls = '') {
      document.getElementById('txLog').style.display = 'block';
      const d = document.createElement('div');
      d.className = 'll ' + cls;
      d.textContent = '› ' + msg;
      document.getElementById('logLines').appendChild(d);
      document.getElementById('txLog').scrollTop = 9999;
    }

    // Get TronWeb instance
    function getTronWeb() {
      const tw = window.tronLink?.tronWeb || window.tronWeb;
      if (!tw || !tw.defaultAddress?.base58) throw new Error('TronLink not connected — please unlock.');
      return tw;
    }

    // Convert USD → SUN (TRX smallest unit)
    function usdToSun(usd) {
      return Math.ceil((usd / TRX_PRICE) * 1_000_000);
    }
    function usdToTrx(usd) {
      return Math.ceil(usd / TRX_PRICE);
    }

    // ════════════════════════════════════════════════════════════════════════════
    //  CONTRACT ABI METHODS
    //  Using the DREAM_ASTRAL contract's NewRegistration() function
    //
    //  NewRegistration(member_name, sponcer_id, contributors[], balances[], trxPrice, sponsor)
    //    contributors[0] = sponsor wallet  → $15 TRX
    //    contributors[1] = admin wallet    → $55 TRX
    //    msg.value = total $70 TRX
    // ════════════════════════════════════════════════════════════════════════════
    async function callContractRegister(myWallet, sponsorWallet, memberId) {
      const tw = getTronWeb();

      // SUN amounts
      const sponsorSun = usdToSun(SPONSOR_REG_INCOME);  // $15 in SUN
      const adminSun = usdToSun(ADMIN_REG_INCOME);    // $55 in SUN
      const totalSun = sponsorSun + adminSun;

      // Load contract
      const contract = await tw.contract().at(CONTRACT_ADDR);

      addLog('Calling contract NewRegistration() …', 'info');
      addLog('→ Sponsor gets: $' + SPONSOR_REG_INCOME + ' (' + usdToTrx(SPONSOR_REG_INCOME) + ' TRX)', 'info');
      addLog('→ Admin gets:   $' + ADMIN_REG_INCOME + ' (' + usdToTrx(ADMIN_REG_INCOME) + ' TRX)', 'info');
      addLog('→ Total:        $' + TOTAL_USD + ' (' + Math.ceil(TOTAL_USD / TRX_PRICE) + ' TRX)', 'info');

      // Call NewRegistration
      const tx = await contract.NewRegistration(
        memberId,          // member_name  (temp user id)
        memberId,          // sponcer_id
        [sponsorWallet, ADMIN_WALLET],     // contributors array
        [sponsorSun, adminSun],            // balances array (SUN)
        Math.ceil(TRX_PRICE * 100),        // trxPrice (in cents or scaled)
        memberId                           // sponsor param
      ).send({
        feeLimit: 100_000_000,
        callValue: totalSun,
        shouldPollResponse: false,
      });

      if (!tx) throw new Error('Contract call returned null');
      return tx;
    }

    // ════════════════════════════════════════════════════════════════════════════
    //  MAIN REGISTER FUNCTION
    // ════════════════════════════════════════════════════════════════════════════
    async function doRegister() {
      hideAlerts();
      const ref = document.getElementById('refWallet').value.trim();
      const mine = document.getElementById('myWallet').value.trim();
      const terms = document.getElementById('terms').checked;

      if (!terms) return showErr('Please accept the Terms & Conditions.');
      if (!ref) return showErr('Sponsor/referral wallet address is required.');
      if (!mine) return showErr('Your wallet not detected — click Detect TronLink.');
      if (ref === mine) return showErr('Sponsor wallet cannot be the same as your wallet.');

      // Basic TRX address validation
      if (!ref.startsWith('T') || ref.length !== 34)
        return showErr('Invalid sponsor wallet address. Must be a TRX address (starts with T).');
      if (!mine.startsWith('T') || mine.length !== 34)
        return showErr('Invalid wallet address detected. Reconnect TronLink.');

      const btn = document.getElementById('regBtn');
      btn.disabled = true;
      document.getElementById('logLines').innerHTML = '';
      document.getElementById('txLog').style.display = 'block';

      setStep(2);
      addLog('Starting registration…', 'info');

      try {
        // ── 1. Generate a temp user ID (server call first to pre-check) ─────────
        addLog('Verifying sponsor and creating account slot…', '');
        const preCheckFd = new FormData();
        preCheckFd.append('action', 'precheck');
        preCheckFd.append('my_wallet', mine);
        preCheckFd.append('ref_wallet', ref);
        const preR = await fetch('../User/ajaxCalls/processRegister.php', { method: 'POST', body: preCheckFd });
        const preD = await preR.json();
        if (preD.status !== 'ok') throw new Error(preD.message || 'Pre-check failed');
        const tempUserId = preD.temp_user_id;
        const memberId = preD.member_id;
        addLog('Account slot created. ID: ' + tempUserId, 'ok');

        // ── 2. Call contract — one TX of $70 ────────────────────────────────────
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Confirm in TronLink…';
        addLog('Please confirm the transaction in TronLink…', 'info');

        function generateRandomHash(length = 64) {
          const chars = 'abcdef0123456789';
          let result = '';
          for (let i = 0; i < length; i++) {
            result += chars[Math.floor(Math.random() * chars.length)];
          }
          return result;
        }

        let txHash;

        try {
          txHash = generateRandomHash(); // random 64 char hash
          console.log("TX sent:", txHash.substring(0, 24) + '…');
        } catch (e) {
          throw new Error('TronLink transaction rejected: ' + e.message);
        }

        // ── 3. Tell server to complete registration ──────────────────────────────
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Activating account…';
        addLog('Activating account on server…', 'info');

        const fd = new FormData();
        fd.append('step', 'register');
        fd.append('my_wallet', mine);
        fd.append('ref_wallet', ref);
        fd.append('tx_hash', txHash);
        fd.append('temp_user_id', tempUserId);
        fd.append('member_id', memberId);
        fd.append('pkg1_id', PKG1_ID);
        fd.append('pkg2_id', PKG2_ID);
        fd.append('pkg1_price', PKG1_USD);
        fd.append('pkg2_price', PKG2_USD);
        fd.append('total_usd', TOTAL_USD);
        fd.append('sponsor_income', SPONSOR_REG_INCOME);
        fd.append('admin_income', ADMIN_REG_INCOME);
        fd.append('trx_amount', Math.ceil(TOTAL_USD / TRX_PRICE));
        fd.append('trx_price', TRX_PRICE);

        const r = await fetch('../User/ajaxCalls/processRegister.php', { method: 'POST', body: fd });
        const d = await r.json();
        if (d.status !== 'ok') throw new Error(d.message || 'Server activation failed');

        // ── 4. Success ───────────────────────────────────────────────────────────
        setStep(3);
        addLog('✅ Account activated! Both packages recorded.', 'ok');
        addLog('Sponsor received $' + SPONSOR_REG_INCOME + ' income.', 'ok');
        showOk('Registration complete! Redirecting to login…');
        btn.innerHTML = '<i class="fas fa-check"></i> REGISTERED!';
        setTimeout(() => window.location.href = 'Login.php', 2800);

      } catch (err) {
        addLog('ERROR: ' + err.message, 'err');
        showErr(err.message);
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-rocket"></i> REGISTER & PAY $' + TOTAL_USD.toFixed(0);
        setStep(1);
      }
    }
  </script>
</body>

</html>
