<?php
/* ============================================================================
   WBMCZ — CHECKOUT
   ----------------------------------------------------------------------------
   Three steps on one page:
     1  Where we are coming to, and who to call
     2  How you want to pay
     3  Confirm, and the money is taken

   Works for the whole cart, or for one product when it arrives as ?id=123
   (the Buy Now button on the product page).

   The price is never taken from the form. Everything is recalculated here from
   the product row, so a tampered field changes nothing.
   ============================================================================ */
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/Language.php';
require_once __DIR__ . '/includes/shares.php';
require_once __DIR__ . '/includes/wallet.php';
require_once __DIR__ . '/includes/purchase.php';
require_once __DIR__ . '/includes/kyc.php';
require_once __DIR__ . '/includes/kyc_fields.php';
require_once __DIR__ . '/includes/kyc_checkout.php';

if (!isLoggedIn()) { redirect('login.php'); }

$lang         = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id      = (int)$_SESSION['user_id'];

wallet_ensure_schema($db);
shares_ensure_schema($db);
buy_ensure_schema($db);

$company_name = getSetting('company_name', 'WBMCZ');
$company_logo = getSetting('company_logo', 'assets/images/logo.png');
$rzp_key      = getSetting('razorpay_key_id', '');
$rzp_secret   = getSetting('razorpay_key_secret', '');

$u    = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($u) ? $u[0] : ['name' => 'User', 'mobile' => ''];
$wal  = wallet_balances($db, $user_id);
$wallet_balance = $wal['main'];

/* ---------- what are we buying ---------- */
$single = isset($_GET['id']) ? (int)$_GET['id'] : (isset($_POST['single_id']) ? (int)$_POST['single_id'] : 0);
$lines  = [];
if ($single > 0) {
    $svc = shares_get_service($db, $single);
    if ($svc && (int)($svc['status'] ?? 1) === 1) {
        $q = buy_quote($db, $svc, $user_id);
        $q['qty'] = 1; $q['cart_id'] = 0; $q['svc'] = $svc;
        $lines[] = $q;
    }
} else {
    $lines = cart_items($db, $user_id);
}
if (empty($lines)) { redirect('cart.php'); }

/* ---------------------------------------------------------------------------
   VERIFICATION DETAILS (KYC) ASKED FOR RIGHT HERE
   ---------------------------------------------------------------------------
   Nothing on the storefront says "KYC Required" any more. Whatever this basket
   needs is asked for on this page like an address form, saved to the buyer's
   KYC record the moment the order is placed, and locked from then on.
   It has to happen BEFORE the gates below are read, so a basket that was
   blocked a second ago passes as soon as the form is filled in.
   --------------------------------------------------------------------------- */
kyc_ensure_schema($db);
kycf_ensure_schema($db);
$kyc_keys = kycx_required_for_lines($db, $lines, $user_id);
$kyc_err  = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['place_order']) && !empty($kyc_keys)) {
    $__r = kycx_save($db, $user_id, $kyc_keys, __DIR__);
    if (empty($__r['ok'])) { $kyc_err = $__r['error']; }
}
$kyc_block = kycx_render($db, $user_id, $kyc_keys);

/* every line must pass its own gate */
$blocked = [];
foreach ($lines as $l) {
    $g = product_purchase_gate($db, $l['svc'], $user_id);
    /* KYC we can still take on this page is not a block — the form above does it. */
    if (!$g['ok'] && empty($g['collect'])) {
        $blocked[] = ['title' => $l['title'], 'msg' => product_gate_message(product_gate_payload($db, $l['svc'], $user_id, $g))];
    }
}

$t = cart_totals($lines);

/* ---------- which ways of paying are open on this basket ---------- */
$allow_code = true;
foreach ($lines as $l) { if (!$l['allow_code']) { $allow_code = false; break; } }

$modes = [];
$modes['full'] = ['Pay the full amount now', 'fa-circle-check', $t['payable'], 0.0,
                  'Everything is settled today — nothing to pay later.'];
if ($t['has_visit'] && $t['advance'] < $t['payable']) {
    $modes['advance'] = ['Book with an advance', 'fa-person-walking', $t['advance'], $t['due'],
                         'Pay the rest at the visit, in cash or online.'];
}
if ($allow_code) {
    $modes['code'] = ['Get a payment code', 'fa-barcode', 0.0, $t['payable'],
                      'Pay at the office or to our person, and give them this code.'];
}
$default_mode = isset($modes['advance']) ? 'advance' : 'full';

/* ---------- the order gets placed here ---------- */
$err = '';
$done = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['place_order'])) {

    if ($kyc_err !== '') {
        $err = $kyc_err;
    } elseif (!empty($blocked)) {
        $err = 'One of the items is not ready to be bought yet.';
    } else {
        $mode = (string)($_POST['pay_mode'] ?? $default_mode);
        if (!isset($modes[$mode])) { $mode = $default_mode; }
        $use_wallet = !empty($_POST['use_wallet']);
        $ref        = '';

        /* how much has to reach us right now */
        $payNow = $mode === 'code' ? 0.0 : ($mode === 'advance' ? $t['advance'] : $t['payable']);
        $plan   = buy_wallet_plan($db, $user_id, $payNow, $use_wallet);

        /* a gateway payment has to be verified against Razorpay before we
           believe a single rupee of it */
        if ($plan['gateway'] > 0.009) {
            $pay_id = trim((string)($_POST['payment_id'] ?? ''));
            if ($pay_id === '') {
                $err = 'The online payment did not complete. Nothing has been charged.';
            } else {
                $ok = false; $paid = 0.0;
                if ($rzp_key !== '' && $rzp_secret !== '') {
                    $ch = curl_init("https://api.razorpay.com/v1/payments/" . rawurlencode($pay_id));
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
                    curl_setopt($ch, CURLOPT_USERPWD, $rzp_key . ':' . $rzp_secret);
                    $resp = curl_exec($ch);
                    curl_close($ch);
                    $d = json_decode((string)$resp, true);
                    if (isset($d['status']) && in_array($d['status'], ['authorized', 'captured'], true)) {
                        $paid = (float)$d['amount'] / 100;
                        $ok   = ($paid + 0.009 >= $plan['gateway']);
                    }
                }
                if (!$ok) { $err = 'We could not verify that payment. If money has left your account it will come back — please contact support with the payment id ' . esc($pay_id) . '.'; }
                else { $ref = $pay_id; }
            }
        }

        if ($err === '') {
            $res = buy_place_order($db, $user_id, $lines, [
                'payment_mode' => $mode,
                'use_wallet'   => $use_wallet,
                'gateway_ref'  => $ref,
                'address'      => trim((string)($_POST['address'] ?? '')),
                'note'         => trim((string)($_POST['note'] ?? '')),
                /* fixed at registration — the form cannot change these */
                'name'         => trim((string)($user['name'] ?? '')),
                'mobile'       => trim((string)($user['mobile'] ?? '')),
            ]);
            if (empty($res['ok'])) { $err = $res['error'] ?: 'The order could not be placed.'; }
            else { redirect('order.php?id=' . (int)$res['order_id'] . '&new=1'); }
        }
    }
}

$unread_notifs = $db->select("SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5", [$user_id]);
function pr($n) { return '₹' . number_format((float)$n, 2); }

/* what the Alpine state needs to know, so the figures move as options change */
$js = [
    'payable'   => (float)$t['payable'],
    'advance'   => (float)$t['advance'],
    'due'       => (float)$t['due'],
    'spendable' => (float)wallet_spendable($db, $user_id),
    'rzpKey'    => $rzp_key,
    'brand'     => $company_name,
    'modes'     => [],
];
foreach ($modes as $k => $m) { $js['modes'][$k] = ['now' => (float)$m[2], 'later' => (float)$m[3]]; }
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkout - <?php echo esc($company_name); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
    <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=Poppins:wght@400;600;700&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body { font-family:'Inter',sans-serif; }
        .font-poppins { font-family:'Poppins',sans-serif; }
        [x-cloak] { display:none !important; }
        .k-card { background:#fff; border:1px solid #e8edf5; border-radius:18px; box-shadow:0 10px 30px -22px rgba(15,23,42,.55); }
        .stepbar { display:flex; align-items:center; gap:10px; }
        .sdot { width:30px; height:30px; border-radius:50%; display:flex; align-items:center; justify-content:center;
                font-size:.78rem; font-weight:800; background:#e2e8f0; color:#94a3b8; flex-shrink:0; transition:.2s; }
        .sdot.on   { background:linear-gradient(135deg,#C8901B,#e0a92c); color:#14202f; box-shadow:0 6px 16px -8px rgba(200,144,27,.9); }
        .sdot.done { background:#0b1220; color:#fff; }
        .sline { flex:1; height:2px; background:#e2e8f0; border-radius:2px; }
        .sline.on { background:#0b1220; }
        .slab { font-size:.66rem; font-weight:800; text-transform:uppercase; letter-spacing:.06em; color:#94a3b8; }
        .slab.on { color:#0b1220; }
        .opt { display:block; border:1.5px solid #e8edf5; border-radius:14px; padding:14px; cursor:pointer; transition:.18s; background:#fff; }
        .opt:hover { border-color:#cbd5e1; }
        .opt.sel { border-color:#C8901B; background:linear-gradient(180deg,#fffdf7,#fff); box-shadow:0 8px 20px -16px rgba(200,144,27,.9); }
        .fld { width:100%; border:1.5px solid #e8edf5; border-radius:12px; padding:11px 13px; font-size:.86rem; }
        .fld:focus { outline:none; border-color:#C8901B; box-shadow:0 0 0 3px rgba(200,144,27,.12); }
        .lbl { font-size:.7rem; font-weight:800; text-transform:uppercase; letter-spacing:.05em; color:#94a3b8; margin-bottom:5px; display:block; }
        .row { display:flex; align-items:center; justify-content:space-between; padding:9px 0; border-bottom:1px dashed #eef2f7; font-size:.86rem; }
        .row:last-child { border-bottom:0; }
        .btn { display:inline-flex; align-items:center; justify-content:center; gap:8px; width:100%; font-weight:800;
               border-radius:13px; padding:14px 18px; font-size:.9rem; transition:transform .18s ease; }
        .btn:hover { transform:translateY(-2px); }
        .btn-go   { background:linear-gradient(135deg,#C8901B,#e0a92c); color:#14202f; box-shadow:0 12px 26px -14px rgba(200,144,27,.95); }
        .btn-dark { background:#0b1220; color:#fff; }
        .btn-ghost{ background:#f1f5f9; color:#475569; }
        .toggle { position:relative; width:44px; height:25px; border-radius:999px; background:#e2e8f0; transition:.2s; flex-shrink:0; }
        .toggle.on { background:#C8901B; }
        .toggle span { position:absolute; top:3px; left:3px; width:19px; height:19px; border-radius:50%; background:#fff; transition:.2s; box-shadow:0 1px 3px rgba(0,0,0,.2); }
        .toggle.on span { left:22px; }
    </style>
</head>
<?php
require_once __DIR__ . '/includes/theme.php';
$__cats = $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
$__subs = [1 => [], 5 => []];
foreach ($db->select("SELECT id, category_id, title, icon_class FROM agency_sub_categories WHERE category_id IN (1,5) AND status = 1 ORDER BY category_id, id") as $__r) {
    $__subs[$__r['category_id']][] = $__r;
}
theme_open([
    'panel' => 'user', 'base' => '', 'title' => 'Checkout', 'active' => 'cart',
    'user' => $user, 'wallet' => $wallet_balance, 'notifs' => $unread_notifs,
    'logo' => $company_logo, 'brand' => $company_name,
    'menu' => theme_user_menu($__subs, $__cats),
]);
?>
<main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8"
      x-data="checkout(<?php echo htmlspecialchars(json_encode($js), ENT_QUOTES); ?>)">
  <div class="max-w-5xl mx-auto">

    <!-- steps -->
    <div class="k-card p-5 mb-5">
        <div class="stepbar">
            <div class="flex flex-col items-center gap-1.5">
                <div class="sdot" :class="step > 1 ? 'done' : 'on'"><span x-text="step > 1 ? '✓' : '1'"></span></div>
                <span class="slab" :class="step >= 1 && 'on'">Details</span>
            </div>
            <div class="sline" :class="step > 1 && 'on'"></div>
            <div class="flex flex-col items-center gap-1.5">
                <div class="sdot" :class="step > 2 ? 'done' : (step === 2 ? 'on' : '')"><span x-text="step > 2 ? '✓' : '2'"></span></div>
                <span class="slab" :class="step >= 2 && 'on'">Payment</span>
            </div>
            <div class="sline" :class="step > 2 && 'on'"></div>
            <div class="flex flex-col items-center gap-1.5">
                <div class="sdot" :class="step === 3 ? 'on' : ''">3</div>
                <span class="slab" :class="step >= 3 && 'on'">Confirm</span>
            </div>
        </div>
    </div>

    <?php if ($err): ?>
        <div class="mb-4 px-4 py-3 rounded-xl bg-rose-50 border border-rose-200 text-rose-800 text-sm font-semibold">
            <i class="fas fa-circle-exclamation mr-1"></i> <?php echo $err; ?>
        </div>
    <?php endif; ?>

    <?php if (!empty($blocked)): ?>
        <div class="mb-4 px-4 py-3 rounded-xl bg-rose-50 border border-rose-200">
            <p class="text-sm font-bold text-rose-800 mb-1">These cannot be bought yet</p>
            <?php foreach ($blocked as $b): ?>
                <p class="text-[12px] text-rose-700"><b><?php echo esc($b['title']); ?></b> — <?php echo esc($b['msg']); ?></p>
            <?php endforeach; ?>
            <a href="cart.php" class="inline-block mt-2 text-[12px] font-bold text-rose-800 underline">Back to cart</a>
        </div>
    <?php endif; ?>

    <form method="POST" id="orderForm" enctype="multipart/form-data">
    <input type="hidden" name="place_order" value="1">
    <input type="hidden" name="single_id" value="<?php echo (int)$single; ?>">
    <input type="hidden" name="payment_id" id="payment_id" value="">
    <input type="hidden" name="pay_mode" :value="mode">
    <input type="hidden" name="use_wallet" :value="useWallet ? 1 : ''">

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-5">
      <div class="lg:col-span-2 space-y-5">

        <!-- ===== STEP 1 ===== -->
        <div class="k-card p-5 sm:p-6" x-show="step === 1" x-cloak>
            <h2 class="font-poppins font-bold text-slate-800 mb-1">Who should we contact?</h2>
            <p class="text-[12.5px] text-slate-500 mb-4">
                <?php echo $t['has_visit']
                    ? 'Somebody is coming to this address, so please get it right.'
                    : 'We only use this if we need to reach you about the order.'; ?>
            </p>
            <div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <div>
                    <label class="lbl">Name <span class="normal-case tracking-normal text-emerald-600 font-black"><i class="fas fa-lock"></i></span></label>
                    <input class="fld bg-slate-50 text-slate-500" value="<?php echo esc($user['name'] ?? ''); ?>" disabled>
                </div>
                <div>
                    <label class="lbl">Mobile <span class="normal-case tracking-normal text-emerald-600 font-black"><i class="fas fa-lock"></i></span></label>
                    <input class="fld bg-slate-50 text-slate-500" value="<?php echo esc($user['mobile'] ?? ''); ?>" disabled>
                </div>
                <div>
                    <label class="lbl">Email <span class="normal-case tracking-normal text-emerald-600 font-black"><i class="fas fa-lock"></i></span></label>
                    <input class="fld bg-slate-50 text-slate-500" value="<?php echo esc($user['email'] ?? ''); ?>" disabled>
                </div>
            </div>
            <p class="text-[11.5px] text-slate-400 mt-2 leading-snug">
                <i class="fas fa-circle-info"></i>
                Name, mobile and email are the ones you registered with and cannot be changed on an order.
                Contact support if any of them is wrong.
            </p>
            <div class="mt-3">
                <label class="lbl"><?php echo $t['has_visit'] ? 'Full address for the visit' : 'Address (optional)'; ?></label>
                <textarea class="fld" name="address" rows="3" <?php echo $t['has_visit'] ? 'required' : ''; ?>
                    placeholder="House / street, area, town, district, PIN"><?php echo esc($user['address'] ?? ''); ?></textarea>
            </div>
            <div class="mt-3">
                <label class="lbl">Anything we should know? (optional)</label>
                <input class="fld" name="note" maxlength="200" placeholder="Landmark, best time to come, and so on">
            </div>
            <?php echo $kyc_block; ?>

            <button type="button" class="btn btn-dark mt-5" @click="next()">Continue to payment <i class="fas fa-arrow-right"></i></button>
        </div>

        <!-- ===== STEP 2 ===== -->
        <div class="k-card p-5 sm:p-6" x-show="step === 2" x-cloak>
            <h2 class="font-poppins font-bold text-slate-800 mb-1">How would you like to pay?</h2>
            <p class="text-[12.5px] text-slate-500 mb-4">Your wallet is used first on whichever you pick.</p>

            <div class="space-y-2.5">
            <?php foreach ($modes as $k => $m): ?>
                <label class="opt" :class="mode === '<?php echo $k; ?>' && 'sel'">
                    <div class="flex items-start gap-3">
                        <input type="radio" name="__mode" value="<?php echo $k; ?>" class="mt-1 accent-[#C8901B]"
                               <?php echo $k === $default_mode ? 'checked' : ''; ?> @change="mode = '<?php echo $k; ?>'">
                        <div class="flex-1 min-w-0">
                            <p class="font-bold text-[14px] text-slate-800"><i class="fas <?php echo $m[1]; ?> mr-1.5 text-slate-400"></i><?php echo $m[0]; ?></p>
                            <p class="text-[12px] text-slate-500 mt-0.5"><?php echo $m[4]; ?></p>
                        </div>
                        <div class="text-right flex-shrink-0">
                            <p class="font-extrabold text-slate-900"><?php echo pr($m[2]); ?></p>
                            <?php if ($m[3] > 0): ?><p class="text-[11px] text-amber-700 font-bold">+ <?php echo pr($m[3]); ?> later</p><?php endif; ?>
                        </div>
                    </div>
                </label>
            <?php endforeach; ?>
            </div>

            <!-- wallet toggle -->
            <div class="mt-4 rounded-xl border border-slate-200 p-4 flex items-center gap-3"
                 :class="mode === 'code' && 'opacity-50 pointer-events-none'">
                <div class="toggle" :class="useWallet && 'on'" @click="useWallet = !useWallet"><span></span></div>
                <div class="flex-1 min-w-0">
                    <p class="font-bold text-[13.5px] text-slate-800">Use my wallet first</p>
                    <p class="text-[12px] text-slate-500">
                        <?php echo pr($wal['total']); ?> available
                        <?php if ($wal['virtual'] > 0): ?>(<?php echo pr($wal['virtual']); ?> of it is virtual, and is spent first)<?php endif; ?>
                    </p>
                </div>
                <span class="font-extrabold text-emerald-600 text-sm" x-text="'− ' + money(walletPart)"></span>
            </div>

            <div class="flex gap-2.5 mt-5">
                <button type="button" class="btn btn-ghost" style="width:auto;padding-inline:22px" @click="step = 1"><i class="fas fa-arrow-left"></i></button>
                <button type="button" class="btn btn-dark" @click="step = 3">Review order <i class="fas fa-arrow-right"></i></button>
            </div>
        </div>

        <!-- ===== STEP 3 ===== -->
        <div class="k-card p-5 sm:p-6" x-show="step === 3" x-cloak>
            <h2 class="font-poppins font-bold text-slate-800 mb-1">One last look</h2>
            <p class="text-[12.5px] text-slate-500 mb-4">Nothing is charged until you press the button.</p>

            <div class="rounded-xl border border-slate-200 divide-y divide-slate-100">
                <?php foreach ($lines as $l): ?>
                <div class="flex items-center gap-3 p-3.5">
                    <?php $th = buy_thumb($l['svc']); ?>
                    <div class="w-10 h-10 rounded-xl bg-slate-50 flex items-center justify-center text-slate-400 flex-shrink-0 overflow-hidden">
                        <?php if ($th['img']): ?><img src="<?php echo esc($th['img']); ?>" alt="" class="w-full h-full object-contain p-1">
                        <?php else: ?><i class="fas <?php echo esc($th['icon']); ?>"></i><?php endif; ?>
                    </div>
                    <div class="flex-1 min-w-0">
                        <p class="font-bold text-[13.5px] text-slate-800 truncate"><?php echo esc($l['title']); ?></p>
                        <p class="text-[11.5px] text-slate-500">
                            <?php echo $l['fulfilment'] === 'visit' ? 'Visit &amp; complete' : 'Online'; ?>
                            <?php if ((int)$l['qty'] > 1): ?> · &times;<?php echo (int)$l['qty']; ?><?php endif; ?>
                        </p>
                    </div>
                    <span class="font-extrabold text-slate-800 text-[13.5px]"><?php echo pr($l['payable'] * $l['qty']); ?></span>
                </div>
                <?php endforeach; ?>
            </div>

            <div class="mt-4 rounded-xl bg-slate-50 border border-slate-200 p-4">
                <div class="row"><span class="text-slate-500">Order total</span><span class="font-bold text-slate-800"><?php echo pr($t['payable']); ?></span></div>
                <div class="row"><span class="text-slate-500">Paying now</span><span class="font-bold text-slate-800" x-text="money(payNow)"></span></div>
                <div class="row" x-show="walletPart > 0"><span class="text-slate-500">From wallet</span><span class="font-bold text-emerald-600" x-text="'− ' + money(walletPart)"></span></div>
                <div class="row"><span class="text-slate-800 font-bold" x-text="mode === 'code' ? 'To pay against the code' : 'Payable online'"></span>
                     <span class="font-extrabold text-[#C8901B] text-base" x-text="money(mode === 'code' ? payLater : gatewayPart)"></span></div>
                <div class="row" x-show="mode !== 'code' && payLater > 0">
                     <span class="text-amber-700 font-semibold">At the visit</span>
                     <span class="font-extrabold text-amber-700" x-text="money(payLater)"></span></div>
            </div>

            <label class="flex items-start gap-2.5 mt-4 cursor-pointer">
                <input type="checkbox" x-model="agree" class="mt-0.5 accent-[#C8901B]">
                <span class="text-[12px] text-slate-500 leading-snug">
                    I have checked the details above and I understand
                    <span x-show="payLater > 0">that <b x-text="money(payLater)"></b> is still to be paid</span>
                    <span x-show="payLater <= 0">that this pays for the order in full</span>.
                </span>
            </label>

            <div class="flex gap-2.5 mt-4">
                <button type="button" class="btn btn-ghost" style="width:auto;padding-inline:22px" @click="step = 2"><i class="fas fa-arrow-left"></i></button>
                <button type="button" class="btn btn-go" :disabled="!agree || busy" :class="(!agree || busy) && 'opacity-50 pointer-events-none'"
                        @click="pay()">
                    <i class="fas" :class="busy ? 'fa-spinner fa-spin' : 'fa-lock'"></i>
                    <span x-text="busy ? 'Please wait…' : (gatewayPart > 0 ? 'Pay ' + money(gatewayPart) : (mode === 'code' ? 'Get my payment code' : 'Place the order'))"></span>
                </button>
            </div>
        </div>
      </div>

      <!-- ===== the running summary, always visible ===== -->
      <div class="lg:col-span-1">
        <div class="k-card p-5 lg:sticky lg:top-4">
            <h3 class="font-poppins font-bold text-slate-800 mb-3">Summary</h3>
            <div class="row"><span class="text-slate-500"><?php echo (int)$t['items']; ?> item<?php echo $t['items'] > 1 ? 's' : ''; ?></span><span class="font-bold text-slate-800"><?php echo pr($t['payable']); ?></span></div>
            <?php if ($t['discount'] > 0): ?>
                <div class="row"><span class="text-amber-700 font-semibold"><i class="fas fa-crown"></i> Subscriber saving</span><span class="font-bold text-amber-700">− <?php echo pr($t['discount']); ?></span></div>
            <?php endif; ?>
            <div class="row"><span class="text-slate-500">Paying now</span><span class="font-bold text-slate-800" x-text="money(payNow)"></span></div>
            <div class="row" x-show="walletPart > 0"><span class="text-slate-500">Wallet covers</span><span class="font-bold text-emerald-600" x-text="'− ' + money(walletPart)"></span></div>
            <div class="row"><span class="text-slate-800 font-bold">Online now</span><span class="font-extrabold text-[#C8901B] text-base" x-text="money(gatewayPart)"></span></div>
            <div class="row" x-show="payLater > 0"><span class="text-amber-700 font-semibold" x-text="mode === 'code' ? 'Against the code' : 'At the visit'"></span><span class="font-extrabold text-amber-700" x-text="money(payLater)"></span></div>

            <p class="text-[11.5px] text-slate-400 leading-snug mt-3">
                <i class="fas fa-shield-halved"></i> Prices are worked out on our server when the order is placed, so nothing here can be tampered with.
            </p>
            <a href="cart.php" class="block text-center mt-3 text-[12.5px] font-bold text-slate-400 hover:text-slate-700"><i class="fas fa-arrow-left"></i> Back to cart</a>
        </div>
      </div>

    </div>
    </form>
  </div>
</main>

<script>
function checkout(cfg) {
    return {
        cfg: cfg,
        step: 1,
        mode: '<?php echo $default_mode; ?>',
        useWallet: true,
        agree: false,
        busy: false,

        get payNow()  { var m = this.cfg.modes[this.mode]; return m ? m.now : 0; },
        get payLater(){ var m = this.cfg.modes[this.mode]; return m ? m.later : 0; },
        get walletPart() {
            if (this.mode === 'code' || !this.useWallet) return 0;
            return Math.min(this.cfg.spendable, this.payNow);
        },
        get gatewayPart() {
            if (this.mode === 'code') return 0;
            return Math.max(0, Math.round((this.payNow - this.walletPart) * 100) / 100);
        },

        money(n) {
            return '₹' + Number(n || 0).toLocaleString('en-IN', {minimumFractionDigits: 2, maximumFractionDigits: 2});
        },

        next() {
            var f = document.getElementById('orderForm');
            var need = f.querySelectorAll('[required]');
            for (var i = 0; i < need.length; i++) {
                if (!need[i].value.trim()) { need[i].focus(); need[i].reportValidity(); return; }
            }
            this.step = 2;
        },

        pay() {
            if (this.busy) return;
            var f = document.getElementById('orderForm');

            /* nothing to collect online — the wallet covers it, or it is a code */
            if (this.gatewayPart <= 0) { this.busy = true; f.submit(); return; }

            if (!this.cfg.rzpKey) {
                alert('Online payment is not set up yet. Please contact support.');
                return;
            }

            var self = this;
            self.busy = true;
            var rzp = new Razorpay({
                key: self.cfg.rzpKey,
                amount: Math.round(self.gatewayPart * 100),
                currency: 'INR',
                name: self.cfg.brand,
                description: 'Order payment',
                handler: function (res) {
                    document.getElementById('payment_id').value = res.razorpay_payment_id;
                    f.submit();
                },
                modal: { ondismiss: function () { self.busy = false; } }
            });
            rzp.on('payment.failed', function () { self.busy = false; alert('The payment did not go through. Nothing has been charged.'); });
            rzp.open();
        }
    };
}
</script>
<?php theme_close(); ?>
</html>
