<?php
// ─────────────────────────────────────────────────────────────
//  checkout.php — Dedicated Stripe checkout page for plans
// ─────────────────────────────────────────────────────────────
require_once __DIR__ . '/lib.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"/>
<title>Checkout</title>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/>
<link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=Syne:wght@600;700;800&family=DM+Sans:opsz,wght@9..40,300;9..40,400;9..40,500;9..40,600&display=swap" rel="stylesheet"/>
<style>
*{box-sizing:border-box;margin:0;padding:0}
:root{--bg:#f4f5f7;--surface:#fff;--border:#e8eaed;--border-hi:#d1d5db;--accent:#e09500;--accent-hi:#f5a623;--accent-d:#b87800;--accent-pale:#fff8eb;--text:#111827;--text-2:#4b5563;--text-3:#9ca3af;--red:#dc2626;--red-pale:#fef2f2;--red-border:#fecaca;--font-display:'Syne',sans-serif;--font-body:'DM Sans',sans-serif;--font-mono:'DM Mono',monospace}
body{font-family:var(--font-body);background:var(--bg);color:var(--text);min-height:100vh;padding-bottom:env(safe-area-inset-bottom,0)}
.wrap{max-width:640px;margin:0 auto;padding:24px 16px 40px}
.back{display:inline-flex;align-items:center;gap:6px;font-size:13px;color:var(--text-2);margin-bottom:14px}
.card{background:var(--surface);border:1px solid var(--border);border-radius:16px;overflow:hidden}
.hdr{padding:22px;background:linear-gradient(135deg,var(--accent-hi),var(--accent-d));color:#fff}
.hdr h1{font-family:var(--font-display);font-size:22px}
.hdr p{opacity:.9;font-size:13px;margin-top:4px}
.body{padding:20px}
.plan{padding:12px;border:1px solid var(--border);border-radius:10px;background:#fff;margin-bottom:16px}
.plan-name{font-family:var(--font-display);font-size:16px}
.plan-meta{font-size:12px;color:var(--text-2);margin-top:3px}
.plan-price{font-family:var(--font-display);font-size:26px;color:var(--accent);margin-top:6px}
.fg{margin-bottom:14px}
.fg label{display:block;font-size:11px;font-weight:600;color:var(--text-2);text-transform:uppercase;letter-spacing:.07em;margin-bottom:6px}
.fg input{width:100%;background:var(--bg);border:1.5px solid var(--border-hi);border-radius:9px;padding:10px 13px;font-size:13px;color:var(--text);outline:none}
.fg input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-pale)}
.err{display:none;font-size:12px;color:var(--red);background:var(--red-pale);border:1px solid var(--red-border);padding:8px;border-radius:8px;margin-bottom:10px}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;width:100%;padding:11px 16px;border-radius:9px;font-size:14px;font-weight:700;border:none;cursor:pointer;background:linear-gradient(135deg,var(--accent-hi),var(--accent-d));color:#fff}
.btn[disabled]{opacity:.7;cursor:default}
.muted{font-size:12px;color:var(--text-3);margin-top:10px;text-align:center}
.loading{font-size:13px;color:var(--text-2)}
</style>
</head>
<body>
<div class="wrap">
  <a class="back" href="<?= APP_URL ?>/plans.php">← Back to plans</a>
  <div class="card">
    <div class="hdr">
      <h1>Checkout</h1>
      <p>Complete your membership purchase securely with Stripe.</p>
    </div>
    <div class="body">
      <div id="loading" class="loading">Loading plan…</div>
      <div id="content" style="display:none">
        <div class="plan">
          <div class="plan-name" id="plan-name"></div>
          <div class="plan-meta" id="plan-meta"></div>
          <div class="plan-price" id="plan-price"></div>
        </div>
        <div class="fg"><label>Your name</label><input id="name" type="text" placeholder="Full name"/></div>
        <div class="fg"><label>Email address</label><input id="email" type="email" placeholder="you@example.com"/></div>
        <div id="err" class="err"></div>
        <button id="payBtn" class="btn">Continue to Stripe →</button>
        <div class="muted">Secured by Stripe. Card details are never stored on this server.</div>
      </div>
    </div>
  </div>
</div>
<script>
const BASE = <?= json_encode(APP_URL, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>;
const API = BASE + '/api/booking';
const params = new URLSearchParams(location.search);
const planId = parseInt(params.get('plan_id') || '0', 10);
let plan = null;

function money(n){ const v = parseFloat(n||0); return `$${(v%1===0)?v.toFixed(0):v.toFixed(2)}`; }
function showErr(m){ const e=document.getElementById('err'); e.textContent=m; e.style.display='block'; }

async function load() {
  if (!planId) { showErr('Missing plan_id'); return; }
  const res = await fetch(API + '/plans').then(r=>r.json()).catch(()=>({ok:false}));
  if (!res.ok) { showErr('Could not load plans.'); return; }
  plan = (res.plans||[]).find(p => Number(p.id) === Number(planId));
  if (!plan) { showErr('Plan not found.'); return; }
  document.getElementById('plan-name').textContent = plan.name || 'Membership';
  document.getElementById('plan-meta').textContent = `${plan.duration_days} days access`;
  document.getElementById('plan-price').textContent = money(plan.price);
  document.getElementById('loading').style.display = 'none';
  document.getElementById('content').style.display = '';
}

async function checkout() {
  const name = document.getElementById('name').value.trim();
  const email = document.getElementById('email').value.trim();
  if (!name) return showErr('Please enter your name.');
  if (!email || !email.includes('@')) return showErr('Please enter a valid email.');
  document.getElementById('err').style.display = 'none';
  const btn = document.getElementById('payBtn');
  btn.disabled = true;
  btn.textContent = 'Redirecting...';
  const body = {
    plan_id: planId,
    email, name,
    success_url: BASE + '/plans.php?success=1',
    cancel_url: location.href
  };
  const res = await fetch(API + '/stripe/checkout', {
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body: JSON.stringify(body)
  }).then(r=>r.json()).catch(()=>({ok:false,error:'Network error'}));
  btn.disabled = false;
  btn.textContent = 'Continue to Stripe →';
  if (res.ok && res.checkout_url) {
    location.href = res.checkout_url;
  } else {
    showErr(res.error || 'Could not start checkout.');
  }
}

document.getElementById('payBtn').addEventListener('click', checkout);
load();
</script>
</body>
</html>
