<?php
/**
 * pay.php  — Communeglobal Publication Fee Payment
 * Entry:  pay.php?tracking_code=CIJSS-XXXXXX
 * Reads from: submissions, submission_authors, affiliations, journals, manuscript_info
 * Writes to:  payments (new unified table — see migration.sql)
 */

ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logs/payment.log');
error_reporting(E_ALL);

require_once __DIR__ . '/config/db.php';     // provides db()
require_once __DIR__ . '/inc/payment_helpers.php';

// Start session safely — works whether or not db.php defines startSession()
if (function_exists('startSession')) {
    startSession();
} elseif (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ── 1. Validate tracking code ────────────────────────────────────────────────
$tracking_code = trim($_GET['tracking_code'] ?? '');
if (!$tracking_code) {
    renderError('Invalid request. A tracking code is required.'); exit;
}

// ── 2. Load submission ───────────────────────────────────────────────────────
try {
    $stmt = db()->prepare("
        SELECT
            s.submission_id,
            s.user_id,
            s.journal_id,
            s.tracking_code,
            s.submission_status,
            s.preliminary_fee_chf,
            mi.article_title,
            j.name AS journal_name,
            -- Email: corresponding author first, then first author
            COALESCE(ca.email, fa.email) AS email,
            COALESCE(ca.first_name, fa.first_name) AS author_first_name,
            COALESCE(ca.last_name,  fa.last_name)  AS author_last_name,
            -- Country priority:
            -- 1. submission_payment.country_region (filled during submission billing step)
            -- 2. users.country (set in profile)
            -- 3. NULL → default USD
            COALESCE(
                NULLIF(TRIM(sp.country_region), ''),
                NULLIF(TRIM(u.country), '')
            ) AS country
        FROM submissions s
        LEFT JOIN journals j             ON j.journal_id      = s.journal_id
        LEFT JOIN manuscript_info mi     ON mi.submission_id  = s.submission_id
        -- Billing step country (most accurate — author filled during submission)
        LEFT JOIN submission_payment sp  ON sp.submission_id  = s.submission_id
        -- Logged-in user profile country (fallback)
        LEFT JOIN users u                ON u.user_id         = s.user_id
        -- Corresponding author (for email/name only)
        LEFT JOIN submission_authors ca
            ON ca.submission_id = s.submission_id AND ca.is_corresponding = 1
        -- First author fallback (for email/name only)
        LEFT JOIN submission_authors fa
            ON fa.submission_id = s.submission_id AND fa.author_order = 1
        WHERE s.tracking_code = ?
        LIMIT 1
    ");
    $stmt->execute([$tracking_code]);
    $submission = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    logPaymentError('DB fetch error: ' . $e->getMessage(), $tracking_code);
    renderError('Database error. Please try again later.'); exit;
}

if (!$submission) {
    renderError('Tracking code not found. Please check your email and try again.'); exit;
}

// ── 3. Check if already paid ─────────────────────────────────────────────────
try {
    $chk = db()->prepare("
        SELECT payment_id FROM payments
        WHERE submission_id = ? AND status = 'COMPLETED'
        LIMIT 1
    ");
    $chk->execute([$submission['submission_id']]);
    if ($chk->fetch()) {
        renderError('This submission has already been paid. Contact support if this is unexpected.'); exit;
    }
} catch (PDOException $e) {
    // Table may not exist yet — continue (migration needed)
}

// ── 4. Resolve pricing ───────────────────────────────────────────────────────
$country      = normalizeCountry($submission['country'] ?? '');
$journal_name = $submission['journal_name'] ?? '';
$pricing      = resolvePricing($country, $journal_name);

$amount       = $pricing['amount'];
$currency     = $pricing['currency'];
$sym          = $pricing['symbol'];
$paypal_amount = $pricing['paypal_amount'];

// Gateway visibility
$show_paypal   = $pricing['show_paypal'];
$show_razorpay = $pricing['show_razorpay'];
$show_stripe   = $pricing['show_stripe'];
$show_ngn_bank = ($country === 'nigeria');
$show_gcash    = ($country === 'philippines');

$invoice_no    = 'CGBL-' . $tracking_code;
$author_name   = trim(($submission['author_first_name'] ?? '') . ' ' . ($submission['author_last_name'] ?? ''));
$author_email  = $submission['email'] ?? '';
$article_title = $submission['article_title'] ?? '(Untitled)';

// ── 5. Log for debugging ──────────────────────────────────────────────────────
logPaymentError(
    "LOAD | tracking=$tracking_code | country=$country | amount=$amount $currency | paypal=$paypal_amount",
    $tracking_code,
    'debug'
);

// ── 6. Render ─────────────────────────────────────────────────────────────────
$pageTitle  = 'Pay Publication Fee';
$activePage = 'payment';

// _layout.php lives in the same author/ folder (same level as dashboard.php)
$_layout = file_exists(__DIR__ . '/_layout.php')
    ? __DIR__ . '/_layout.php'
    : (file_exists(__DIR__ . '/../_layout.php') ? __DIR__ . '/../_layout.php' : null);

if ($_layout) {
    require_once $_layout;
} else {
    echo '<!doctype html><html lang="en"><head><meta charset="utf-8">'
       . '<meta name="viewport" content="width=device-width,initial-scale=1">'
       . '<title>' . htmlspecialchars($pageTitle) . '</title>'
       . '<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">'
       . '<style>'
       . ':root{--white:#fff;--border:#e2e8f0;--muted:#64748b;--teal:#14b8a6;--teal-dk:#0f9488;--font:"Inter",sans-serif}'
       . '*{box-sizing:border-box;margin:0;padding:0}'
       . 'body{font-family:var(--font);background:#f8fafc;color:#1e293b;min-height:100vh}'
       . '.au-main{max-width:920px;margin:0 auto;padding:30px 20px}'
       . '</style></head><body><div class="au-main">';
}
?>

<style>
/* ── Payment page styles ─────────────────────────────────────── */
.pay-wrap     { max-width: 860px; margin: 0 auto; }
.pay-card     { background: var(--white); border: 1px solid var(--border); border-radius: 10px; padding: 24px; margin-bottom: 20px; }
.pay-card-hdr { font-size: 15px; font-weight: 700; margin-bottom: 16px; display: flex; align-items: center; gap: 8px; color: #1e293b; }
.pay-card-hdr svg { flex-shrink: 0; }

/* Submission info grid */
.info-grid    { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; }
@media(max-width: 600px) { .info-grid { grid-template-columns: 1fr 1fr; } }
.info-item strong { display: block; font-size: 11px; text-transform: uppercase; letter-spacing: .5px; color: var(--muted); margin-bottom: 3px; }
.info-item span   { font-weight: 600; font-size: 13.5px; color: #1e293b; }
.article-title-row { margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--border); font-size: 13px; color: #334155; }
.article-title-row strong { color: var(--muted); font-size: 11px; text-transform: uppercase; display: block; margin-bottom: 3px; }

/* Amount display */
.amount-box { background: #eff6ff; border: 2px dashed #93c5fd; border-radius: 10px; text-align: center; padding: 18px; margin-bottom: 20px; }
.amount-box .amount-val { font-size: 2rem; font-weight: 800; color: #1d4ed8; letter-spacing: -0.5px; }
.amount-box .amount-sub { font-size: 12px; color: #64748b; margin-top: 4px; }

/* Notice */
.pay-notice { background: #fffbeb; border-left: 4px solid #f59e0b; border-radius: 8px; padding: 12px 16px; font-size: 13px; color: #78350f; line-height: 1.6; margin-bottom: 20px; }

/* Method grid */
.method-grid  { display: grid; grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); gap: 12px; }
.method-card  { border: 2px solid var(--border); border-radius: 8px; padding: 14px; cursor: pointer; transition: all .18s; background: #fafafa; display: flex; align-items: center; gap: 12px; position: relative; }
.method-card:hover { border-color: var(--teal); background: #f0fdfa; }
.method-card.selected { border-color: var(--teal); background: #f0fdfa; box-shadow: 0 0 0 3px rgba(20,184,166,.15); }
.method-card input[type=radio] { position: absolute; opacity: 0; pointer-events: none; }
.method-icon  { font-size: 1.6rem; flex-shrink: 0; width: 36px; text-align: center; }
.method-title { font-size: 13.5px; font-weight: 700; color: #1e293b; }
.method-sub   { font-size: 12px; color: var(--muted); margin-top: 2px; }

/* Pay button */
.btn-pay { width: 100%; background: var(--teal); color: #fff; border: none; border-radius: 8px; padding: 14px; font-size: 15px; font-weight: 700; cursor: pointer; margin-top: 16px; font-family: var(--font); transition: background .18s; display: flex; align-items: center; justify-content: center; gap: 8px; }
.btn-pay:hover:not(:disabled) { background: var(--teal-dk); }
.btn-pay:disabled { opacity: .65; cursor: not-allowed; }

/* PayPal container */
#paypalContainer { margin-top: 16px; display: none; }

/* Bank details panel */
.bank-panel { background: #f8fafc; border: 1px solid var(--border); border-radius: 8px; padding: 18px; margin-top: 16px; display: none; font-size: 13px; line-height: 1.8; }
.bank-panel.show { display: block; }
.bank-panel h4   { font-size: 13.5px; font-weight: 700; margin-bottom: 12px; color: #1e293b; }
.bank-panel p    { margin: 4px 0; }
.bank-panel .bank-note { background: #dbeafe; border-left: 4px solid var(--teal); border-radius: 6px; padding: 10px 14px; margin-top: 12px; color: #1e3a5f; font-size: 12.5px; }
.bank-panel .bank-note ol, .bank-panel .bank-note ul { padding-left: 18px; margin: 6px 0; }
.bank-panel .bank-note li { margin: 3px 0; }

/* Result */
#result { margin-top: 16px; padding: 12px 16px; border-radius: 8px; display: none; font-size: 13px; font-weight: 500; }
#result.success { background: #dcfce7; color: #15803d; border: 1px solid #86efac; }
#result.error   { background: #fee2e2; color: #dc2626; border: 1px solid #fca5a5; }
</style>

<div class="pay-wrap">

  <!-- ── Submission info ──────────────────────────────────────── -->
  <div class="pay-card">
    <div class="pay-card-hdr">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
      Submission Details
    </div>
    <div class="info-grid">
      <div class="info-item">
        <strong>Tracking Code</strong>
        <span><?= htmlspecialchars($tracking_code) ?></span>
      </div>
      <div class="info-item">
        <strong>Invoice No.</strong>
        <span><?= htmlspecialchars($invoice_no) ?></span>
      </div>
      <div class="info-item">
        <strong>Journal</strong>
        <span><?= htmlspecialchars($journal_name ?: '—') ?></span>
      </div>
    </div>
    <?php if ($article_title && $article_title !== '(Untitled)'): ?>
    <div class="article-title-row">
      <strong>Article Title</strong>
      <?= htmlspecialchars($article_title) ?>
    </div>
    <?php endif; ?>
  </div>

  <!-- ── Amount ───────────────────────────────────────────────── -->
  <div class="amount-box">
    <div class="amount-val"><?= $sym . number_format((float)$amount, 2) . ' ' . $currency ?></div>
    <div class="amount-sub">Article Processing Charge (APC)</div>
  </div>

  <!-- ── Important notice ─────────────────────────────────────── -->
  <div class="pay-notice">
    <strong>⚠ Important:</strong> After successful payment, upload your Author Declaration, Final Paper, and Payment Proof via the Final Submission System.
  </div>

  <!-- ── Payment methods ──────────────────────────────────────── -->
  <div class="pay-card">
    <div class="pay-card-hdr">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="1" y="4" width="22" height="16" rx="2" ry="2"/><line x1="1" y1="10" x2="23" y2="10"/></svg>
      Select Payment Method
    </div>

    <div class="method-grid">

      <?php if ($show_ngn_bank): ?>
      <label class="method-card selected" data-method="ngn_bank">
        <input type="radio" name="payment_method" value="ngn_bank" checked>
        <div class="method-icon">🏦</div>
        <div>
          <div class="method-title">Bank Transfer (NGN)</div>
          <div class="method-sub">Local Nigeria — Recommended</div>
        </div>
      </label>
      <?php endif; ?>

      <?php if ($show_paypal): ?>
      <label class="method-card" data-method="paypal">
        <input type="radio" name="payment_method" value="paypal">
        <div class="method-icon">🅿</div>
        <div>
          <div class="method-title">PayPal</div>
          <div class="method-sub">$<?= $paypal_amount ?> USD</div>
        </div>
      </label>
      <?php endif; ?>

      <?php if ($show_stripe): ?>
      <label class="method-card <?= (!$show_paypal && !$show_ngn_bank) ? 'selected' : '' ?>" data-method="stripe">
        <input type="radio" name="payment_method" value="stripe" <?= (!$show_paypal && !$show_ngn_bank) ? 'checked' : '' ?>>
        <div class="method-icon">💳</div>
        <div>
          <div class="method-title">Card (Stripe)</div>
          <div class="method-sub"><?= $sym . $amount . ' ' . $currency ?></div>
        </div>
      </label>
      <?php endif; ?>

      <?php if ($show_razorpay): ?>
      <label class="method-card <?= (!$show_paypal && !$show_stripe && !$show_ngn_bank) ? 'selected' : '' ?>" data-method="razorpay">
        <input type="radio" name="payment_method" value="razorpay" <?= (!$show_paypal && !$show_stripe && !$show_ngn_bank) ? 'checked' : '' ?>>
        <div class="method-icon">⚡</div>
        <div>
          <div class="method-title">Razorpay</div>
          <div class="method-sub"><?= $sym . $amount . ' ' . $currency ?></div>
        </div>
      </label>
      <?php endif; ?>

      <?php if ($show_gcash): ?>
      <label class="method-card" data-method="gcash">
        <input type="radio" name="payment_method" value="gcash">
        <div class="method-icon">📱</div>
        <div>
          <div class="method-title">GCash</div>
          <div class="method-sub">Mobile wallet / card</div>
        </div>
      </label>
      <?php endif; ?>

      <label class="method-card" data-method="bank">
        <input type="radio" name="payment_method" value="bank">
        <div class="method-icon">🏛</div>
        <div>
          <div class="method-title">Bank Transfer</div>
          <div class="method-sub"><?= (strtolower($country) === 'india') ? 'UPI / Net Banking' : 'International Wire' ?></div>
        </div>
      </label>

    </div><!-- /method-grid -->

    <button id="payNowBtn" class="btn-pay">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
      Pay Now
    </button>

    <div id="paypalContainer"></div>

    <!-- ── Standard bank details ─────────────────────────────── -->
    <div id="bankPanel" class="bank-panel">
      <h4>🏛 Bank Transfer Details — Communeglobal</h4>
      <p><strong>Bank Name:</strong> Axis Bank</p>
      <p><strong>Account Name:</strong> CIJSS</p>
      <p><strong>Account Number:</strong> 922020064564426</p>
      <p><strong>SWIFT Code:</strong> AXISINBBXXX</p>
      <p><strong>IFSC Code:</strong> UTIB0005029</p>
      <p><strong>UPI ID:</strong> rsisinter@ybl</p>
      <p><strong>Bank Address:</strong> Axis Bank, Emerald Plaza, Sector 65, Gurgaon, Haryana 122018, India</p>

      <div class="bank-note">
        <?php if (strtolower($country) === 'india'): ?>
        <strong>India Payments:</strong>
        <ul>
          <li>Pay via UPI ID: <strong>rsisinter@ybl</strong> or Net Banking.</li>
          <li>Payments can be made by family, friends, or colleagues.</li>
          <li>Email: <strong>editorialoffice@communeglobal.com</strong> for assistance.</li>
        </ul>
        <?php else: ?>
        <strong>International Wire Instructions:</strong>
        <ol>
          <li>Provide our bank details including the SWIFT code <strong>AXISINBBXXX</strong>.</li>
          <li>Set Beneficiary Name exactly as <strong>"CIJSS"</strong>.</li>
          <li>Set Payment Purpose as <strong>"Online Publication Fees CIJSS"</strong>.</li>
          <li>After transfer, save your receipt and upload it in the Final Submission System.</li>
        </ol>
        <?php endif; ?>
      </div>
    </div>

    <!-- ── GCash details ─────────────────────────────────────── -->
    <div id="gcashPanel" class="bank-panel">
      <h4>📱 GCash — Philippines</h4>
      <p>Transfer directly to our Indian bank account via GCash International Transfer.</p>
      <div class="bank-note">
        <strong>Steps:</strong>
        <ul>
          <li>Open GCash → International Payment / Bank Transfer.</li>
          <li>Select <strong>India</strong> as destination country.</li>
          <li>Beneficiary: <strong>CIJSS</strong></li>
          <li>Account No: <strong>922020064564426</strong></li>
          <li>SWIFT: <strong>AXISINBBXXX</strong></li>
          <li>Purpose: <strong>Online Publication Fees CIJSS</strong></li>
          <li>Upload receipt in Final Submission System.</li>
        </ul>
      </div>
    </div>

    <!-- ── NGN bank details ──────────────────────────────────── -->
    <div id="ngnBankPanel" class="bank-panel <?= $show_ngn_bank ? 'show' : '' ?>">
      <h4>🏦 Local Bank Transfer — Nigeria (NGN)</h4>
      <p><strong>Account Name:</strong> Raenest / CIJSS</p>
      <p><strong>Bank Name:</strong> Kredi Money Microfinance Bank</p>
      <p><strong>Account Number:</strong> 1861994002</p>
      <div class="bank-note">
        <strong>Steps:</strong>
        <ol>
          <li>Open your banking app → Bank Transfer.</li>
          <li>Enter the account details above.</li>
          <li>Enter amount in <strong>Naira (₦)</strong>.</li>
          <li>Add Reference: <strong>UMI</strong></li>
          <li>Complete payment and save receipt.</li>
          <li>Upload proof in Final Submission System.</li>
        </ol>
      </div>
    </div>

    <div id="result"></div>

  </div><!-- /pay-card -->

</div><!-- /pay-wrap -->

<!-- ── JS ──────────────────────────────────────────────────────── -->
<script src="https://js.stripe.com/v3/"></script>
<?php if ($show_paypal): ?>
<script src="https://www.paypal.com/sdk/js?client-id=AfTKIvUFjaDpt8BpDfGekGy_rcxvtPyicc9Elxt0xHZFtvRwRrj26HhDDzIop163ryHdswo72eJk9GPe&currency=USD"></script>
<?php endif; ?>
<?php if ($show_razorpay): ?>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<?php endif; ?>

<script>
const TC        = <?= json_encode($tracking_code) ?>;
const AMOUNT    = <?= json_encode($amount) ?>;
const CURRENCY  = <?= json_encode($currency) ?>;
const PP_AMOUNT = <?= json_encode($paypal_amount) ?>;
const EMAIL     = <?= json_encode($author_email) ?>;
const NAME      = <?= json_encode($author_name) ?>;
const COUNTRY   = <?= json_encode($country) ?>;

const payNowBtn     = document.getElementById('payNowBtn');
const paypalCont    = document.getElementById('paypalContainer');
const bankPanel     = document.getElementById('bankPanel');
const gcashPanel    = document.getElementById('gcashPanel');
const ngnBankPanel  = document.getElementById('ngnBankPanel');
const resultEl      = document.getElementById('result');
let ppRendered = false;

// ── Card selection ────────────────────────────────────────────────
document.querySelectorAll('.method-card').forEach(card => {
  card.addEventListener('click', function () {
    document.querySelectorAll('.method-card').forEach(c => c.classList.remove('selected'));
    this.classList.add('selected');
    this.querySelector('input').checked = true;
    resetUI();
    const m = this.dataset.method;
    if (m === 'bank')     bankPanel.classList.add('show');
    if (m === 'gcash')    gcashPanel.classList.add('show');
    if (m === 'ngn_bank') ngnBankPanel.classList.add('show');
  });
});

function resetUI() {
  bankPanel.classList.remove('show');
  gcashPanel.classList.remove('show');
  ngnBankPanel.classList.remove('show');
  paypalCont.style.display = 'none';
  paypalCont.innerHTML = '';
  payNowBtn.style.display = 'flex';
  payNowBtn.disabled = false;
  payNowBtn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg> Pay Now';
  resultEl.style.display = 'none';
  ppRendered = false;
}

function showResult(msg, ok) {
  resultEl.className = ok ? 'success' : 'error';
  resultEl.innerHTML = msg;
  resultEl.style.display = 'block';
  resultEl.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

// ── Pay Now click ─────────────────────────────────────────────────
payNowBtn.addEventListener('click', () => {
  const method = document.querySelector('input[name="payment_method"]:checked')?.value;
  if (!method) { showResult('Please select a payment method.', false); return; }

  if (method === 'paypal')   startPayPal();
  else if (method === 'stripe')   startStripe();
  else if (method === 'razorpay') startRazorpay();
  else showResult('Please follow the bank details above and email your receipt to <strong>editorialoffice@communeglobal.com</strong>', true);
});

// ── PayPal ────────────────────────────────────────────────────────
function startPayPal() {
  if (ppRendered) return;
  ppRendered = true;
  payNowBtn.style.display = 'none';
  paypalCont.style.display = 'block';
  paypal.Buttons({
    style: { layout: 'vertical', color: 'blue', shape: 'rect', label: 'paypal', height: 44 },
    createOrder: () =>
      post('ajax/payment_paypal_create.php', { tracking_code: TC, amount: PP_AMOUNT, currency: 'USD' })
        .then(d => d.order_id),
    onApprove: data =>
      post('ajax/payment_paypal_capture.php', { tracking_code: TC, orderID: data.orderID })
        .then(r => {
          if (r.success) redirect(data.orderID, 'paypal');
          else showResult('Payment capture failed. Contact support.', false);
        }),
    onError: () => { showResult('PayPal error. Please try another method.', false); resetUI(); }
  }).render('#paypalContainer');
}

// ── Stripe ────────────────────────────────────────────────────────
const stripe = Stripe('<?= STRIPE_PUBLIC_KEY ?>');
function startStripe() {
  setBusy('Redirecting to Stripe…');
  post('ajax/payment_stripe_create.php', { tracking_code: TC, amount: AMOUNT, currency: CURRENCY })
    .then(d => {
      if (d.session_id) stripe.redirectToCheckout({ sessionId: d.session_id });
      else { resetUI(); showResult('Could not create Stripe session.', false); }
    })
    .catch(() => { resetUI(); showResult('Network error.', false); });
}

// ── Razorpay ──────────────────────────────────────────────────────
function startRazorpay() {
  setBusy('Creating order…');
  post('ajax/payment_razorpay_create.php', { tracking_code: TC, amount: AMOUNT, currency: CURRENCY })
    .then(data => {
      resetUI();
      if (!data.success) { showResult('Could not create Razorpay order.', false); return; }
      new Razorpay({
        key:         '<?= RAZORPAY_KEY_ID ?>',
        amount:      data.amount,
        currency:    data.currency,
        name:        'Communeglobal',
        description: 'Publication Fee — ' + TC,
        order_id:    data.order_id,
        prefill:     { email: EMAIL, name: NAME },
        theme:       { color: '#14b8a6' },
        handler: resp =>
          post('ajax/payment_razorpay_capture.php', {
            tracking_code:        TC,
            razorpay_payment_id:  resp.razorpay_payment_id,
            razorpay_order_id:    resp.razorpay_order_id,
            razorpay_signature:   resp.razorpay_signature
          }).then(r => {
            if (r.success) redirect(resp.razorpay_payment_id, 'razorpay');
            else showResult('Payment verification failed.', false);
          }),
        modal: { ondismiss: resetUI }
      }).open();
    })
    .catch(() => { resetUI(); showResult('Network error.', false); });
}

// ── Helpers ───────────────────────────────────────────────────────
function post(url, body) {
  return fetch(url, {
    method:  'POST',
    headers: { 'Content-Type': 'application/json' },
    body:    JSON.stringify(body)
  }).then(r => r.json());
}
function redirect(sessionId, method) {
  window.location.href = `payment_success.php?session_id=${encodeURIComponent(sessionId)}&tracking_code=${encodeURIComponent(TC)}&method=${method}`;
}
function setBusy(label) {
  payNowBtn.disabled = true;
  payNowBtn.innerHTML = `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" style="animation:spin 1s linear infinite"><path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/></svg> ${label}`;
}
</script>
<style>@keyframes spin{to{transform:rotate(360deg)}}</style>

<?php
if (function_exists('layoutEnd')) {
    layoutEnd();
} else {
    echo '</div></body></html>';
}
?>