<?php
require_once __DIR__ . '/config.php';

$errors = [];
$old = ['full_name' => '', 'email' => '', 'email_confirm' => '', 'phone' => '', 'device_model' => '', 'quantity' => 1];
$canceled = isset($_GET['canceled']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $old['full_name']      = trim($_POST['full_name'] ?? '');
    $old['email']          = strtolower(trim($_POST['email'] ?? ''));
    $old['email_confirm']  = strtolower(trim($_POST['email_confirm'] ?? ''));
    $old['phone']          = trim($_POST['phone'] ?? '');
    $old['device_model']   = trim($_POST['device_model'] ?? '');
    $qty                   = (int)($_POST['quantity'] ?? 1);
    $planId                = $_POST['plan_id'] ?? '';
    $token                 = $_POST['csrf_token'] ?? '';
    $honeypot              = trim($_POST['website'] ?? '');

    if (!hash_equals($_SESSION['esim_csrf'] ?? '', $token)) {
        $errors[] = 'Your session expired. Please try again.';
    }
    if ($honeypot !== '') {
        $errors[] = 'Submission rejected.';
    }
    if (!isset($ESIM_PLANS[$planId])) {
        $errors[] = 'Please choose a valid plan.';
    }
    if (mb_strlen($old['full_name']) < 2 || mb_strlen($old['full_name']) > 80) {
        $errors[] = 'Please enter your full name.';
    }
    if (!filter_var($old['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please enter a valid email address — this is where your eSIM QR code will be sent.';
    }
    if ($old['email'] !== $old['email_confirm']) {
        $errors[] = 'Email addresses do not match.';
    }
    if ($old['phone'] !== '' && !preg_match('/^[0-9+\s().-]{6,20}$/', $old['phone'])) {
        $errors[] = 'Please enter a valid phone number or leave it empty.';
    }
    if (mb_strlen($old['device_model']) > 100) {
        $errors[] = 'Device name is too long.';
    }
    $qty = max(1, min(5, $qty));

    if (!$errors && empty($_SESSION['esim_csrf'])) {
        $errors[] = 'Your session expired. Please reload the page and try again.';
    }

    if (!$errors) {
        $plan = $ESIM_PLANS[$planId];
        $orderRef = esimNewOrderRef();
        $totalCents = $plan['unit_amount'] * $qty;

        $stmt = esimDb()->prepare("
            INSERT INTO esim_orders
                (order_ref, plan_id, plan_name, name, email, phone, device_model, quantity, amount_total_cents, currency)
            VALUES
                (:ref, :pid, :pname, :name, :email, :phone, :device, :qty, :amount, :currency)
        ");
        $stmt->execute([
            ':ref'      => $orderRef,
            ':pid'      => $planId,
            ':pname'    => $plan['name'],
            ':name'     => $old['full_name'],
            ':email'    => $old['email'],
            ':phone'    => $old['phone'],
            ':device'   => $old['device_model'],
            ':qty'      => $qty,
            ':amount'   => $totalCents,
            ':currency' => $plan['currency'],
        ]);

        list($ok, $resp) = esimCreateCheckoutSession($plan, $qty, $orderRef, $old['email']);

        if ($ok) {
            $upd = esimDb()->prepare("UPDATE esim_orders SET stripe_session_id = :sid WHERE order_ref = :ref");
            $upd->execute([':sid' => $resp['id'], ':ref' => $orderRef]);
            unset($_SESSION['esim_csrf']);
            header('Location: ' . $resp['url']);
            exit;
        }

        $errMsg = $resp['error']['message'] ?? 'Unknown error';
        $upd = esimDb()->prepare("UPDATE esim_orders SET last_error = :err WHERE order_ref = :ref");
        $upd->execute([':err' => substr($errMsg, 0, 500), ':ref' => $orderRef]);
        $errors[] = 'We could not start the checkout. Please try again in a moment.';
    }
}

$_SESSION['esim_csrf'] = bin2hex(random_bytes(32));
$plan = reset($ESIM_PLANS);
$planKey = key($ESIM_PLANS);
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="noindex">
    <title>Order Your Egypt eSIM – Instant Delivery | Doktorly.Life</title>
    <meta name="description" content="Order your Egypt tourist eSIM. 3GB high-speed data, 15 days validity, instant QR delivery by email. Secure payment via Stripe.">

    <link rel="apple-touch-icon" sizes="180x180" href="static/img/favicon_io/apple-touch-icon.png" />
    <link rel="icon" type="image/png" sizes="32x32" href="static/img/favicon_io/favicon-32x32.png" />
    <link rel="icon" type="image/png" sizes="16x16" href="static/img/favicon_io/favicon-16x16.png" />
    <link rel="manifest" href="static/img/favicon_io/site.webmanifest" />
    <link href="https://fonts.googleapis.com/css2?family=Work+Sans:wght@300;400;500;600;700;800&family=Manrope:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">

    <style>
        :root {
            --teal: #115e59;
            --teal-dark: #0b4c47;
            --teal-hover: #0f6b65;
            --teal-shadow: rgba(17,94,89,0.2);
            --navy: #0a0f26;
            --cream: #F3F1E7;
            --cream-dark: #E6E4DC;
            --text-primary: #0a0f26;
            --text-secondary: #6b7280;
            --text-muted: #9ca3af;
            --border: rgba(10,15,38,0.1);
            --border-light: rgba(10,15,38,0.06);
            --radius: 1rem;
            --radius-lg: 1.25rem;
            --radius-xl: 1.5rem;
            --danger: #dc2626;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        html { scroll-behavior: smooth; }
        body { background: var(--cream); color: var(--text-primary); font-family: 'Manrope', sans-serif; min-height: 100vh; display: flex; flex-direction: column; }
        ::selection { background: var(--navy); color: #fff; }
        .hd { font-family: 'Work Sans', sans-serif; }
        .cn { width: 100%; max-width: 1100px; margin: 0 auto; padding-left: 1.5rem; padding-right: 1.5rem; }
        .text-sm { font-size: 0.875rem; }
        .text-xs { font-size: 0.75rem; }
        .semibold { font-weight: 600; }
        .bold { font-weight: 700; }

        nav.top { padding: 1.25rem 0; }
        nav.top .cn { display: flex; align-items: center; justify-content: space-between; gap: 1rem; }
        .logo-svg { width: 7rem; height: auto; }
        .back-link { font-size: 0.875rem; font-weight: 500; color: var(--text-secondary); text-decoration: none; display: inline-flex; align-items: center; gap: 0.375rem; transition: color 0.2s; }
        .back-link:hover { color: var(--text-primary); }

        .layout { display: grid; grid-template-columns: 1fr; gap: 2rem; align-items: start; padding: 2rem 0 4rem; flex: 1; }
        @media(min-width:900px){ .layout{grid-template-columns: 1fr 420px; gap: 3rem;} }

        .panel {
            background: rgba(255,255,255,0.7); backdrop-filter: blur(12px);
            border: 1px solid var(--border); border-radius: var(--radius-xl); padding: 2rem;
        }
        @media(max-width:600px){ .panel{padding:1.25rem} }

        .badge { display: inline-flex; align-items: center; gap: 0.5rem; background: rgba(255,255,255,0.6); border: 1px solid var(--border); border-radius: 9999px; padding: 0.375rem 1rem; margin-bottom: 1rem; }
        .badge-dot { width: 0.5rem; height: 0.5rem; background: #22c55e; border-radius: 50%; animation: pulse 2s infinite; }
        @keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.5} }

        h1.hd { font-size: 1.875rem; font-weight: 600; line-height: 1.15; letter-spacing: -0.02em; margin-bottom: 0.5rem; }
        @media(min-width:1024px){ h1.hd{font-size:2.25rem} }
        .sub { color: var(--text-secondary); line-height: 1.6; margin-bottom: 1.75rem; }

        .alert-error { background: rgba(220,38,38,0.08); border: 1px solid rgba(220,38,38,0.3); color: var(--danger); border-radius: var(--radius); padding: 0.875rem 1.125rem; font-size: 0.875rem; margin-bottom: 1.25rem; }
        .alert-info { background: rgba(245,158,11,0.08); border: 1px solid rgba(245,158,11,0.35); color: #b45309; border-radius: var(--radius); padding: 0.875rem 1.125rem; font-size: 0.875rem; margin-bottom: 1.25rem; }
        .alert-error p + p { margin-top: 0.25rem; }

        .field { margin-bottom: 1.25rem; }
        label { display: block; font-size: 0.8125rem; font-weight: 600; margin-bottom: 0.375rem; }
        label .opt { font-weight: 400; color: var(--text-muted); }
        .input, select.input {
            width: 100%; padding: 0.75rem 1rem; border-radius: var(--radius);
            border: 1px solid var(--border); background: #fff; font-family: inherit;
            font-size: 0.9375rem; color: var(--text-primary); outline: none;
            transition: border-color 0.2s, box-shadow 0.2s;
        }
        .input:focus { border-color: var(--teal); box-shadow: 0 0 0 3px rgba(17,94,89,0.15); }
        .hint { font-size: 0.75rem; color: var(--text-muted); margin-top: 0.3rem; }
        .row-2 { display: grid; grid-template-columns: 1fr; gap: 1.25rem; }
        @media(min-width:520px){ .row-2{grid-template-columns:1fr 1fr} }

        .consent { display: flex; align-items: flex-start; gap: 0.625rem; margin: 1.5rem 0; font-size: 0.8125rem; color: var(--text-secondary); line-height: 1.5; cursor: pointer; }
        .consent input { margin-top: 0.2rem; accent-color: var(--teal); }
        .consent a { color: var(--teal); }

        .btn {
            display: inline-flex; align-items: center; justify-content: center; gap: 0.625rem;
            font-family: 'Work Sans', sans-serif; font-weight: 600; font-size: 1rem;
            padding: 1rem 2rem; border-radius: var(--radius-lg); border: none;
            cursor: pointer; text-decoration: none; position: relative; overflow: hidden;
            transition: opacity 0.2s, background 0.2s;
        }
        .btn-teal { background: var(--teal); color: #fff; box-shadow: 0 10px 15px -3px var(--teal-shadow); width: 100%; }
        .btn-teal:hover { background: var(--teal-hover); }
        .btn-teal[disabled] { opacity: 0.6; cursor: wait; }

        .secure-note { display: flex; align-items: center; justify-content: center; gap: 0.5rem; font-size: 0.75rem; color: var(--text-muted); margin-top: 0.875rem; text-align: center; }

        aside.summary { position: sticky; top: 1.5rem; }
        .summary-card { background: var(--navy); color: #fff; border-radius: var(--radius-xl); padding: 2rem; box-shadow: 0 20px 25px -5px rgba(10,15,38,0.2); }
        .summary-plan { font-family: 'Work Sans', sans-serif; font-weight: 600; font-size: 1.125rem; margin-bottom: 0.25rem; }
        .summary-tag { display: inline-flex; align-items: center; gap: 0.375rem; background: rgba(255,255,255,0.08); border-radius: 9999px; padding: 0.25rem 0.75rem; font-size: 0.6875rem; font-weight: 600; letter-spacing: 0.08em; text-transform: uppercase; color: rgba(255,255,255,0.7); margin-bottom: 1.25rem; }
        .srow { display: flex; justify-content: space-between; align-items: center; font-size: 0.875rem; padding: 0.625rem 0; }
        .srow .lbl { color: rgba(255,255,255,0.6); }
        .srow .val { font-weight: 600; }
        .sdiv { border: none; border-top: 1px solid rgba(255,255,255,0.1); margin: 0.75rem 0; }
        .stotal { display: flex; justify-content: space-between; align-items: baseline; }
        .stotal .lbl { font-size: 0.875rem; color: rgba(255,255,255,0.6); }
        .stotal .val { font-size: 2rem; font-weight: 700; font-family: 'Work Sans', sans-serif; }
        .per-unit { font-size: 0.75rem; color: rgba(255,255,255,0.5); text-align: right; }

        .guar { margin-top: 1.25rem; display: flex; flex-direction: column; gap: 0.5rem; }
        .guar-item { display: flex; align-items: center; gap: 0.5rem; font-size: 0.75rem; color: rgba(255,255,255,0.65); }
        .chk { width: 0.875rem; height: 0.875rem; color: #22c55e; flex-shrink: 0; }

        footer.ft { background: var(--teal-dark); padding: 1.25rem 0; text-align: center; }
        footer.ft span { font-size: 0.75rem; color: rgba(255,255,255,0.4); }
        footer.ft a { color: rgba(255,255,255,0.55); text-decoration: none; }
        footer.ft a:hover { color: #fff; }
    </style>
</head>
<body>
    <nav class="top">
        <div class="cn">
            <a href="index.html"><img class="logo-svg" src="static/img/logo_esim.svg" alt="Doktorly.Life eSIM"></a>
            <a href="index.html" class="back-link">← Back to overview</a>
        </div>
    </nav>

    <main class="cn layout">
        <section class="panel">
            <?php if ($canceled): ?>
                <div class="alert-info">Your previous payment was canceled — no charge was made. You can safely complete your order below.</div>
            <?php endif; ?>
            <?php if ($errors): ?>
                <div class="alert-error">
                    <?php foreach ($errors as $e): ?><p><?= htmlspecialchars($e) ?></p><?php endforeach; ?>
                </div>
            <?php endif; ?>

            <div class="badge">
                <span class="badge-dot"></span>
                <span class="text-xs semibold" style="letter-spacing:0.1em;text-transform:uppercase;color:var(--text-muted);">Instant email delivery</span>
            </div>
            <h1 class="hd">Complete Your eSIM Order</h1>
            <p class="sub text-sm">Tell us where to send your eSIM. You'll be redirected to a secure Stripe payment page.</p>

            <form method="post" action="" id="orderForm" novalidate>
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['esim_csrf']) ?>">
                <input type="hidden" name="plan_id" value="<?= htmlspecialchars($planKey) ?>">
                <input type="text" name="website" value="" style="position:absolute;left:-9999px;" tabindex="-1" autocomplete="off" aria-hidden="true">

                <div class="field">
                    <label for="full_name">Full name</label>
                    <input class="input" type="text" id="full_name" name="full_name" required maxlength="80"
                           placeholder="As shown on your passport" value="<?= htmlspecialchars($old['full_name']) ?>">
                </div>

                <div class="field">
                    <label for="email">Email address</label>
                    <input class="input" type="email" id="email" name="email" required maxlength="120"
                           placeholder="you@example.com" value="<?= htmlspecialchars($old['email']) ?>">
                    <p class="hint">Your eSIM QR code and setup guide are delivered to this address within minutes of payment.</p>
                </div>

                <div class="field">
                    <label for="email_confirm">Confirm email</label>
                    <input class="input" type="email" id="email_confirm" name="email_confirm" required maxlength="120"
                           placeholder="Re-enter your email" value="<?= htmlspecialchars($old['email_confirm']) ?>">
                </div>

                <div class="row-2">
                    <div class="field">
                        <label for="phone">WhatsApp / phone <span class="opt">(optional)</span></label>
                        <input class="input" type="tel" id="phone" name="phone" maxlength="20"
                               placeholder="+49 …" value="<?= htmlspecialchars($old['phone']) ?>">
                        <p class="hint">For faster support if you need help activating.</p>
                    </div>
                    <div class="field">
                        <label for="device_model">Device model <span class="opt">(optional)</span></label>
                        <input class="input" type="text" id="device_model" name="device_model" maxlength="100"
                               list="device-options" placeholder="e.g. iPhone 15 Pro" value="<?= htmlspecialchars($old['device_model']) ?>">
                        <datalist id="device-options"></datalist>
                        <p class="hint">We'll double-check compatibility before sending your QR code.</p>
                    </div>
                </div>

                <div class="field">
                    <label for="quantity">Number of eSIMs</label>
                    <select class="input" id="quantity" name="quantity">
                        <?php for ($i = 1; $i <= 5; $i++): ?>
                            <option value="<?= $i ?>" <?= (int)$old['quantity'] === $i ? 'selected' : '' ?>><?= $i ?> × <?= htmlspecialchars($plan['name']) ?></option>
                        <?php endfor; ?>
                    </select>
                </div>

                <label class="consent">
                    <input type="checkbox" name="consent" required value="1">
                    <span>I understand this is a data-only eSIM for unlocked, eSIM-compatible devices, and I accept the
                    <a href="terms.html" target="_blank">Terms</a>, <a href="refund.html" target="_blank">Refund Policy</a> and
                    <a href="privacy-policy.html" target="_blank">Privacy Policy</a>.</span>
                </label>

                <button type="submit" class="btn btn-teal" id="payBtn">
                    <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/></svg>
                    <span id="payLabel">Pay securely with card</span>
                </button>
                <p class="secure-note">
                    <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/></svg>
                    Redirects to Stripe's encrypted checkout · Visa, Mastercard, Amex, Apple&nbsp;Pay &amp; Google&nbsp;Pay
                </p>
            </form>
        </section>

        <aside class="summary">
            <div class="summary-card">
                <div class="summary-tag">
                    <svg width="12" height="12" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a2 2 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                    Egypt
                </div>
                <div class="summary-plan"><?= htmlspecialchars($plan['name']) ?></div>
                <div class="text-xs" style="color:rgba(255,255,255,0.6);margin-bottom:1.25rem;"><?= htmlspecialchars($plan['data']) ?> · <?= htmlspecialchars($plan['validity']) ?></div>

                <div class="srow"><span class="lbl">Price per eSIM</span><span class="val">$<?= number_format($plan['unit_amount'] / 100, 2) ?></span></div>
                <div class="srow"><span class="lbl">Quantity</span><span class="val" id="sumQty">1</span></div>
                <hr class="sdiv">
                <div class="stotal">
                    <span class="lbl">Total</span>
                    <span class="val" id="sumTotal">$<?= number_format($plan['unit_amount'] / 100, 2) ?></span>
                </div>
                <div class="per-unit" id="perUnitNote">One-time payment · No hidden fees · No roaming charges</div>

                <div class="guar">
                    <span class="guar-item"><svg class="chk" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>Instant QR delivery by email</span>
                    <span class="guar-item"><svg class="chk" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>30-day money-back guarantee</span>
                    <span class="guar-item"><svg class="chk" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>Keeps your WhatsApp &amp; home number active</span>
                </div>
            </div>
        </aside>
    </main>

    <footer class="ft">
        <div class="cn">
            <span>© <?= date('Y') ?> Doktorly.Life · <a href="terms.html">Terms</a> · <a href="privacy-policy.html">Privacy</a> · <a href="refund.html">Refunds</a></span>
        </div>
    </footer>

    <script>
        const UNIT_CENTS = <?= (int)$plan['unit_amount'] ?>;
        const fmt = c => '$' + (c / 100).toFixed(2);

        const qtySel = document.getElementById('quantity');
        qtySel.addEventListener('change', () => {
            const q = parseInt(qtySel.value, 10);
            document.getElementById('sumQty').textContent = q;
            document.getElementById('sumTotal').textContent = fmt(UNIT_CENTS * q);
        });

        const form = document.getElementById('orderForm');
        form.addEventListener('submit', function(e) {
            if (!this.reportValidity()) return;
            const btn = document.getElementById('payBtn');
            btn.disabled = true;
            document.getElementById('payLabel').textContent = 'Redirecting to secure payment…';
        });

        fetch('esim-check.php?list=')
            .then(r => (r.ok ? r.text() : ''))
            .then(html => { document.getElementById('device-options').innerHTML = html; })
            .catch(() => {});
    </script>

    <script>
      var _paq = window._paq = window._paq || [];
      _paq.push(['trackPageView']);
      _paq.push(['enableLinkTracking']);
      (function() {
        var u="//doktorly.de/analytics/";
        _paq.push(['setTrackerUrl', u+'matomo.php']);
        _paq.push(['setSiteId', '2']);
        var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
        g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
      })();
    </script>
</body>
</html>
