<?php
/* ============================================================================
   WBMCZ — PRODUCT PAGE
   ----------------------------------------------------------------------------
   One product, everything about it on a single screen: what it costs a regular
   customer, what it costs a member, how it is delivered, and — for the people
   who run the shop — what the seller earns and what the company keeps.

   Two ways out of this page:
     Add to Cart  puts it in the basket and stays here
     Buy Now      goes straight to checkout with only this product
   ============================================================================ */
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';

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

$lang         = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id      = (int)$_SESSION['user_id'];
$role         = (string)($_SESSION['user_type'] ?? 'user');

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');

$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'];

/* ---------- which product ---------- */
$pid  = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$svc  = $pid > 0 ? shares_get_service($db, $pid) : null;
if (!$svc) { redirect('dashboard.php'); }
if ((int)($svc['status'] ?? 1) !== 1) { redirect('dashboard.php'); }

$stype = $svc['__type'] ?? 'seller';
$cat_id = shares_service_category($db, $svc);
$cat = $cat_id ? $db->select("SELECT * FROM service_categories WHERE id = ?", [$cat_id]) : [];
$cat = !empty($cat) ? $cat[0] : null;

/* ---------- price, split and delivery, all in one call ---------- */
$q    = buy_quote($db, $svc, $user_id);
$gate = product_purchase_gate($db, $svc, $user_id);
$gate_payload = $gate['ok'] ? null : product_gate_payload($db, $svc, $user_id, $gate);
$gate_msg     = $gate['ok'] ? '' : product_gate_message($gate_payload);

/* Only the service area stops a purchase now. Missing KYC does not — those
   boxes are put in front of the buyer on the checkout page instead. */
$gate_area_ok = !empty($gate['area']['ok']);
$gate_collect = !empty($gate['collect']);
$can_buy      = ($gate['ok'] || $gate_collect);

$is_visit = ($q['fulfilment'] === 'visit');

/* Has this customer already bought it? */
$owned = [];
try {
    $owned = $db->select(
        "SELECT id, status, stage, order_code FROM orders
          WHERE user_id = ? AND service_name = ? AND status <> 'Cancelled'
          ORDER BY id DESC LIMIT 1", [$user_id, $svc['title']]);
} catch (\Throwable $e) {}
$already = !empty($owned) ? $owned[0] : null;

/* The seller behind the product */
$seller = null;
if (!empty($svc['seller_id'])) {
    $sr = $db->select("SELECT id, name, mobile FROM users WHERE id = ?", [(int)$svc['seller_id']]);
    if (!empty($sr)) { $seller = $sr[0]; }
}

/* ---------------------------------------------------------------------------
   Who may see the money side — the seller's payout and the company's profit.

   The office and the seller who owns the product always see it. Whether the
   CUSTOMER does is a business decision rather than a code decision, so it is a
   setting: `show_payout_public`, which offmigration.php creates and sets to 1.

   It is on because that is what the reference design shows. The argument for
   turning it off is worth knowing: a customer who can see the seller earns
   ₹2,200 and the company keeps ₹600 has been handed the case for dealing with
   that seller directly next time. Set it to 0 in Website Settings and the two
   rows disappear for customers only — nothing else changes.
   --------------------------------------------------------------------------- */
$sees_money = ((string)getSetting('show_payout_public', '1') === '1')
           || ($role === 'admin')
           || ($role === 'seller' && (int)($svc['seller_id'] ?? 0) === $user_id);

/* ---------- actions ---------- */
$flash = ''; $flash_kind = 'ok';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_to_cart'])) {
        if (!$q['allow_cart']) { $flash = 'This product has to be bought on its own.'; $flash_kind = 'no'; }
        elseif (!$can_buy)      { $flash = $gate_msg; $flash_kind = 'no'; }
        else {
            cart_add($db, $user_id, (int)$svc['id'], $stype, 1);
            $_SESSION['flash_ok'] = htmlspecialchars($svc['title']) . ' has been added to your cart.';
            redirect('product.php?id=' . (int)$svc['id']);
        }
    }
    if (isset($_POST['buy_now'])) {
        if (!$can_buy) { $flash = $gate_msg; $flash_kind = 'no'; }
        else { redirect('checkout.php?id=' . (int)$svc['id']); }
    }
}
if (!empty($_SESSION['flash_ok'])) { $flash = $_SESSION['flash_ok']; $flash_kind = 'ok'; unset($_SESSION['flash_ok']); }

$cart_n = cart_count($db, $user_id);
$unread_notifs = $db->select("SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5", [$user_id]);

/* ---------- little helpers for the view ---------- */
function pr($n) { return '₹' . number_format((float)$n, 2); }
function pr0($n) { return '₹' . number_format((float)$n, ($n == floor($n)) ? 0 : 2); }

/* The picture, exactly the way the category page resolves it. */
$thumb = buy_thumb($svc);
$img   = $thumb['img'];
$icon  = $thumb['icon'] ?: 'fa-file-lines';
$color = $svc['color_class'] ?: 'color-1';
$tones = ['color-1' => '#ef4444', 'color-2' => '#3b82f6', 'color-3' => '#10b981',
          'color-4' => '#f59e0b', 'color-5' => '#8b5cf6'];
$tone = $tones[$color] ?? '#1e3a5f';

/* the documents this product needs, as friendly words */
$need_docs = [];
if (function_exists('product_required_kyc') && function_exists('product_kyc_labels')) {
    $need_docs = product_kyc_labels(product_required_kyc($svc, $role));
}
?>
<!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><?php echo esc($svc['title']); ?> - <?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>
    <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@300;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; }

        .pd-hero { background: linear-gradient(135deg, #0b1220 0%, #1e293b 100%); }
        .pd-card { background: #fff; border: 1px solid #e8edf5; border-radius: 18px;
                   box-shadow: 0 10px 30px -22px rgba(15,23,42,.55); }
        .pd-ico  { width: 104px; height: 104px; border-radius: 26px; display: flex;
                   align-items: center; justify-content: center; font-size: 2.6rem;
                   background: #fff; box-shadow: 0 12px 26px -14px rgba(15,23,42,.6); }
        .pd-ico img { width: 100%; height: 100%; object-fit: contain; padding: 10px; }

        .chip { display: inline-flex; align-items: center; gap: 6px; padding: 6px 11px;
                border-radius: 999px; font-size: .7rem; font-weight: 700; white-space: nowrap; }
        .chip-gold  { background: #fff7e6; color: #b45309; border: 1px solid #fde3af; }
        .chip-blue  { background: #eff6ff; color: #1d4ed8; border: 1px solid #dbeafe; }
        .chip-green { background: #ecfdf5; color: #047857; border: 1px solid #d1fae5; }
        .chip-slate { background: #f1f5f9; color: #475569; border: 1px solid #e2e8f0; }

        .price-now { font-size: 2.1rem; font-weight: 800; letter-spacing: -.02em; }
        .price-was { text-decoration: line-through; color: #94a3b8; font-weight: 600; }
        .save-pill { background: #dcfce7; color: #15803d; font-weight: 800; font-size: .72rem;
                     padding: 4px 10px; border-radius: 999px; }

        .plan { border: 1.5px solid #e8edf5; border-radius: 14px; padding: 14px; background: #fff; }
        .plan.is-you { border-color: #C8901B; background: linear-gradient(180deg,#fffdf7,#fff); }
        .plan-tag { font-size: .6rem; font-weight: 800; letter-spacing: .08em; text-transform: uppercase; }

        .row { display: flex; align-items: center; justify-content: space-between;
               padding: 9px 0; border-bottom: 1px dashed #eef2f7; font-size: .85rem; }
        .row:last-child { border-bottom: 0; }

        .btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px;
               font-weight: 800; border-radius: 13px; padding: 14px 18px; font-size: .9rem;
               transition: transform .18s ease, box-shadow .18s ease; width: 100%; }
        .btn:hover { transform: translateY(-2px); }
        .btn-buy   { background: linear-gradient(135deg,#C8901B,#e0a92c); color: #14202f;
                     box-shadow: 0 12px 26px -14px rgba(200,144,27,.95); }
        .btn-cart  { background: #0b1220; color: #fff; box-shadow: 0 12px 26px -16px rgba(11,18,32,.9); }
        .btn-off   { background: #e2e8f0; color: #64748b; cursor: not-allowed; }
        .btn-off:hover { transform: none; }

        .money-box { background: linear-gradient(135deg,#0b1220,#1e293b); color: #fff; border-radius: 18px; }
        .money-row { display:flex; align-items:center; justify-content:space-between; padding: 10px 0;
                     border-bottom: 1px solid rgba(255,255,255,.08); font-size: .85rem; }
        .money-row:last-child { border-bottom: 0; }

        .steps { counter-reset: s; }
        .step { display: flex; gap: 12px; padding: 10px 0; }
        .step-n { width: 26px; height: 26px; border-radius: 50%; background: #0b1220; color: #fff;
                  font-size: .72rem; font-weight: 800; display: flex; align-items: center;
                  justify-content: center; flex-shrink: 0; }
        @media (max-width: 640px) { .price-now { font-size: 1.75rem; } .pd-ico { width: 84px; height: 84px; font-size: 2rem; } }
    </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'  => $svc['title'],
    'active' => 'services',
    '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">
  <div class="max-w-6xl mx-auto">

    <!-- breadcrumb -->
    <div class="flex items-center gap-2 text-[12px] text-slate-500 font-semibold mb-4">
        <a href="dashboard.php" class="hover:text-slate-800">Home</a>
        <i class="fas fa-angle-right text-[9px]"></i>
        <?php if ($cat): ?>
            <a href="category.php?id=<?php echo (int)$cat['id']; ?>" class="hover:text-slate-800"><?php echo esc($cat['title']); ?></a>
            <i class="fas fa-angle-right text-[9px]"></i>
        <?php endif; ?>
        <span class="text-slate-800"><?php echo esc($svc['title']); ?></span>
    </div>

    <?php if ($flash): ?>
        <div class="mb-4 px-4 py-3 rounded-xl text-sm font-semibold flex items-center gap-2
             <?php echo $flash_kind === 'ok' ? 'bg-emerald-50 text-emerald-800 border border-emerald-200' : 'bg-rose-50 text-rose-800 border border-rose-200'; ?>">
            <i class="fas <?php echo $flash_kind === 'ok' ? 'fa-circle-check' : 'fa-circle-exclamation'; ?>"></i>
            <span><?php echo $flash; ?></span>
            <?php if ($flash_kind === 'ok'): ?>
                <a href="cart.php" class="ml-auto underline">View cart</a>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-5">

      <!-- ============ LEFT: the product ============ -->
      <div class="lg:col-span-2 space-y-5">

        <div class="pd-card overflow-hidden">
            <div class="pd-hero p-5 sm:p-7 flex items-center gap-5">
                <div class="pd-ico" style="color: <?php echo $tone; ?>">
                    <?php if ($img): ?><img src="<?php echo esc($img); ?>" alt="">
                    <?php else: ?><i class="fas <?php echo esc($icon); ?>"></i><?php endif; ?>
                </div>
                <div class="min-w-0">
                    <h1 class="font-poppins text-white text-xl sm:text-2xl font-bold leading-tight"><?php echo esc($svc['title']); ?></h1>
                    <div class="flex flex-wrap items-center gap-2 mt-3">
                        <?php if ($cat): ?><span class="chip chip-slate" style="background:rgba(255,255,255,.12);color:#e2e8f0;border-color:rgba(255,255,255,.18)"><i class="fas <?php echo esc($cat['icon_class'] ?: 'fa-layer-group'); ?>"></i><?php echo esc($cat['title']); ?></span><?php endif; ?>
                        <?php if ($is_visit): ?>
                            <span class="chip chip-gold"><i class="fas fa-person-walking"></i> Visit &amp; complete</span>
                        <?php else: ?>
                            <span class="chip chip-green"><i class="fas fa-bolt"></i> Online, right away</span>
                        <?php endif; ?>
                        <?php if ($seller): ?>
                            <span class="chip chip-slate" style="background:rgba(255,255,255,.12);color:#e2e8f0;border-color:rgba(255,255,255,.18)"><i class="fas fa-store"></i> <?php echo esc($seller['name']); ?></span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <?php if (!empty($svc['description'])): ?>
            <div class="p-5 sm:p-7 border-b border-slate-100" x-data="{ more: false }">
                <p class="text-[13px] leading-relaxed text-slate-600 whitespace-pre-line"
                   :class="more ? '' : 'line-clamp-4'"><?php echo esc($svc['description']); ?></p>
                <button @click="more = !more" class="mt-2 text-[12px] font-bold text-[#C8901B]">
                    <span x-text="more ? 'Show less' : 'Read more'"></span>
                </button>
            </div>
            <?php endif; ?>

            <?php if ($need_docs): ?>
            <div class="p-5 sm:p-7 border-b border-slate-100">
                <p class="text-[11px] font-extrabold uppercase tracking-wider text-slate-400 mb-3">Documents needed</p>
                <div class="flex flex-wrap gap-2">
                    <?php foreach ($need_docs as $d): ?>
                        <span class="chip chip-blue"><i class="fas fa-file-lines"></i> <?php echo esc($d); ?></span>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- how this one is delivered -->
            <div class="p-5 sm:p-7">
                <p class="text-[11px] font-extrabold uppercase tracking-wider text-slate-400 mb-3">How it works</p>
                <div class="steps">
                <?php if ($is_visit): ?>
                    <div class="step"><span class="step-n">1</span><div>
                        <p class="text-[13px] font-bold text-slate-800">Pay <?php echo pr($q['advance']); ?> to book it</p>
                        <p class="text-[12px] text-slate-500">This is the booking amount. You can use your wallet for part or all of it.</p></div></div>
                    <div class="step"><span class="step-n">2</span><div>
                        <p class="text-[13px] font-bold text-slate-800">Our person comes to you</p>
                        <p class="text-[12px] text-slate-500"><?php echo $q['visit_note'] !== '' ? esc($q['visit_note']) : 'The seller visits your address, checks the papers and finishes the work.'; ?></p></div></div>
                    <div class="step"><span class="step-n">3</span><div>
                        <p class="text-[13px] font-bold text-slate-800">Pay the remaining <?php echo pr($q['due']); ?> at the visit</p>
                        <p class="text-[12px] text-slate-500">In cash, or online — whichever suits you. You get a receipt against your order.</p></div></div>
                    <div class="step"><span class="step-n">4</span><div>
                        <p class="text-[13px] font-bold text-slate-800">Service handed over</p>
                        <p class="text-[12px] text-slate-500">The order closes only once everything is done and paid.</p></div></div>
                <?php else: ?>
                    <div class="step"><span class="step-n">1</span><div>
                        <p class="text-[13px] font-bold text-slate-800">Pay <?php echo pr($q['payable']); ?> online</p>
                        <p class="text-[12px] text-slate-500">Wallet, UPI, card — whatever you prefer.</p></div></div>
                    <div class="step"><span class="step-n">2</span><div>
                        <p class="text-[13px] font-bold text-slate-800">We take it from there</p>
                        <p class="text-[12px] text-slate-500">The work starts as soon as the payment lands.</p></div></div>
                    <div class="step"><span class="step-n">3</span><div>
                        <p class="text-[13px] font-bold text-slate-800">Track it from Order History</p>
                        <p class="text-[12px] text-slate-500">Every step shows up there until it is completed.</p></div></div>
                <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- what both kinds of customer pay -->
        <div class="pd-card p-5 sm:p-7">
            <p class="text-[11px] font-extrabold uppercase tracking-wider text-slate-400 mb-4">Price for you</p>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div class="plan <?php echo $q['is_subscribed'] ? '' : 'is-you'; ?>">
                    <div class="flex items-center justify-between">
                        <span class="plan-tag text-slate-400">Regular customer</span>
                        <?php if (!$q['is_subscribed']): ?><span class="chip chip-gold" style="padding:2px 8px">You</span><?php endif; ?>
                    </div>
                    <p class="text-xl font-extrabold text-slate-800 mt-1.5"><?php echo pr($q['regular']); ?></p>
                    <?php if ($sees_money): ?>
                        <p class="text-[11px] text-slate-500 mt-1">Seller <?php echo pr0($q['payout_regular']); ?> · Company <?php echo pr0($q['profit_regular']); ?></p>
                    <?php endif; ?>
                </div>
                <div class="plan <?php echo $q['is_subscribed'] ? 'is-you' : ''; ?>">
                    <div class="flex items-center justify-between">
                        <span class="plan-tag text-[#C8901B]"><i class="fas fa-crown"></i> Subscriber</span>
                        <?php if ($q['is_subscribed']): ?><span class="chip chip-gold" style="padding:2px 8px">You</span><?php endif; ?>
                    </div>
                    <p class="text-xl font-extrabold text-slate-800 mt-1.5"><?php echo pr($q['member']); ?></p>
                    <?php if ($sees_money): ?>
                        <p class="text-[11px] text-slate-500 mt-1">Seller <?php echo pr0($q['payout_member']); ?> · Company <?php echo pr0($q['profit_member']); ?></p>
                    <?php endif; ?>
                </div>
            </div>
            <?php if (!$q['is_subscribed'] && $q['member_off'] > 0): ?>
                <a href="subscription.php" class="mt-3 flex items-center gap-2 px-4 py-3 rounded-xl bg-amber-50 border border-amber-200 text-[12px] font-bold text-amber-800">
                    <i class="fas fa-crown"></i>
                    Members pay <?php echo pr($q['member']); ?> for this — you would save <?php echo pr($q['member_off']); ?>.
                    <span class="ml-auto underline whitespace-nowrap">See plans</span>
                </a>
            <?php endif; ?>
        </div>

        <?php if ($sees_money): ?>
        <!-- the money side, for the office and the seller who owns it -->
        <div class="money-box p-5 sm:p-7">
            <div class="flex items-center gap-2 mb-3">
                <i class="fas fa-lock text-[#C8901B]"></i>
                <p class="text-[11px] font-extrabold uppercase tracking-wider text-white/60">Internal — not shown to customers</p>
            </div>
            <div class="money-row"><span class="text-white/70">Selling price (this customer)</span><span class="font-extrabold"><?php echo pr($q['payable']); ?></span></div>
            <div class="money-row"><span class="text-white/70">Seller earns</span><span class="font-extrabold text-emerald-300"><?php echo pr($q['seller_payout']); ?></span></div>
            <div class="money-row"><span class="text-white/70">Company keeps</span><span class="font-extrabold text-[#e6bb5f]"><?php echo pr($q['company_profit']); ?></span></div>
            <?php if ($is_visit): ?>
            <div class="money-row"><span class="text-white/70">Taken online now</span><span class="font-extrabold"><?php echo pr($q['advance']); ?></span></div>
            <div class="money-row"><span class="text-white/70">Collected at the visit</span><span class="font-extrabold"><?php echo pr($q['due']); ?></span></div>
            <p class="text-[11.5px] text-white/50 leading-relaxed mt-3">
                <?php if (abs($q['advance'] - $q['company_profit']) < 0.01): ?>
                    The booking amount is exactly the company's share, so the seller keeps what they collect and nothing has to be handed over afterwards.
                <?php elseif ($q['advance'] > $q['company_profit']): ?>
                    The booking amount is <?php echo pr($q['advance'] - $q['company_profit']); ?> more than the company's share, so the company owes the seller that much after the visit.
                <?php else: ?>
                    The seller will be holding <?php echo pr($q['company_profit'] - $q['advance']); ?> of the company's money after the visit — it shows on the Seller Dues screen until it is handed in.
                <?php endif; ?>
            </p>
            <?php endif; ?>
        </div>
        <?php endif; ?>
      </div>

      <!-- ============ RIGHT: the buy box ============ -->
      <div class="lg:col-span-1">
        <div class="pd-card p-5 sm:p-6 lg:sticky lg:top-4">

            <div class="flex items-end gap-3 flex-wrap">
                <span class="price-now" style="color: <?php echo $tone; ?>"><?php echo pr($q['payable']); ?></span>
                <?php if ($q['mrp'] > $q['payable']): ?>
                    <span class="price-was text-sm mb-1.5"><?php echo pr($q['mrp']); ?></span>
                    <span class="save-pill mb-1.5">Save <?php echo pr0($q['mrp'] - $q['payable']); ?></span>
                <?php endif; ?>
            </div>
            <p class="text-[11.5px] text-slate-400 font-semibold mt-1">
                <?php echo $q['is_subscribed'] ? 'Subscriber price — your discount is already applied.' : 'Price inclusive of all charges.'; ?>
            </p>

            <?php if ($is_visit): ?>
            <div class="mt-4 rounded-xl border border-amber-200 bg-amber-50 p-4">
                <p class="text-[11px] font-extrabold uppercase tracking-wider text-amber-700 mb-2">
                    <i class="fas fa-person-walking"></i> Pay in two parts
                </p>
                <div class="row" style="border-color:#fde3af">
                    <span class="text-amber-900 font-semibold">Pay now to book</span>
                    <span class="font-extrabold text-amber-900"><?php echo pr($q['advance']); ?></span>
                </div>
                <div class="row" style="border-color:#fde3af">
                    <span class="text-amber-900 font-semibold">Pay at the visit</span>
                    <span class="font-extrabold text-amber-900"><?php echo pr($q['due']); ?></span>
                </div>
                <p class="text-[11.5px] text-amber-800/80 mt-2 leading-snug">
                    Cash or online at the visit — your choice. Nothing more than <?php echo pr($q['payable']); ?> in total.
                </p>
            </div>
            <?php endif; ?>

            <!-- wallet -->
            <?php $plan = buy_wallet_plan($db, $user_id, $is_visit ? $q['advance'] : $q['payable'], true); ?>
            <div class="mt-4 rounded-xl border border-slate-200 p-4">
                <div class="row">
                    <span class="text-slate-500 font-semibold"><i class="fas fa-wallet text-slate-400 mr-1"></i> Wallet balance</span>
                    <span class="font-extrabold text-slate-800"><?php echo pr($wal['total']); ?></span>
                </div>
                <?php if ($plan['wallet'] > 0): ?>
                <div class="row">
                    <span class="text-slate-500 font-semibold">From wallet</span>
                    <span class="font-extrabold text-emerald-600">− <?php echo pr($plan['wallet']); ?></span>
                </div>
                <div class="row">
                    <span class="text-slate-800 font-bold"><?php echo $plan['gateway'] > 0 ? 'You still pay' : 'Nothing left to pay'; ?></span>
                    <span class="font-extrabold" style="color: <?php echo $tone; ?>"><?php echo pr($plan['gateway']); ?></span>
                </div>
                <?php if ($plan['covered']): ?>
                    <p class="text-[11.5px] text-emerald-700 font-semibold mt-2"><i class="fas fa-circle-check"></i> Your wallet covers this fully — no card needed.</p>
                <?php endif; ?>
                <?php else: ?>
                    <p class="text-[11.5px] text-slate-400 mt-1">Your wallet is empty, so the full amount will be taken online. <a href="wallet.php#add_money" class="text-[#C8901B] font-bold underline">Add money</a></p>
                <?php endif; ?>
            </div>

            <!-- buttons -->
            <div class="mt-5 space-y-2.5">
            <?php if (!$gate_area_ok): ?>
                <button type="button" class="btn btn-off" disabled><i class="fas fa-lock"></i> Not available in your area</button>
                <div class="rounded-xl bg-rose-50 border border-rose-200 p-3.5">
                    <p class="text-[12px] text-rose-800 font-semibold leading-snug"><?php echo esc($gate_msg); ?></p>
                </div>
            <?php else: ?>
                <?php if ($gate_collect): ?>
                <div class="rounded-xl bg-amber-50 border border-amber-200 p-3.5">
                    <p class="text-[12px] text-amber-900 font-semibold leading-snug">
                        <i class="fas fa-id-card mr-1"></i>
                        This service asks for a few verification details. You will fill them in on the
                        checkout page — once saved they cannot be changed.
                    </p>
                </div>
                <?php endif; ?>
                <form method="POST" class="space-y-2.5">
                    <button type="submit" name="buy_now" value="1" class="btn btn-buy">
                        <i class="fas fa-bolt"></i> <?php echo $is_visit ? 'Book for ' . pr($q['advance']) : 'Buy Now'; ?>
                    </button>
                    <?php if ($q['allow_cart']): ?>
                        <button type="submit" name="add_to_cart" value="1" class="btn btn-cart">
                            <i class="fas fa-cart-plus"></i> Add to Cart
                        </button>
                    <?php else: ?>
                        <p class="text-center text-[11.5px] text-slate-400 font-semibold">This one is bought on its own — it cannot go in the cart.</p>
                    <?php endif; ?>
                </form>
            <?php endif; ?>
            </div>

            <?php if ($already): ?>
                <a href="order.php?id=<?php echo (int)$already['id']; ?>" class="mt-4 flex items-center gap-2 px-4 py-3 rounded-xl bg-slate-50 border border-slate-200 text-[12px] font-bold text-slate-700">
                    <i class="fas fa-box"></i>
                    You ordered this before — <?php echo esc($already['order_code'] ?: ('#' . $already['id'])); ?>
                    <span class="ml-auto underline">Track</span>
                </a>
            <?php endif; ?>

            <?php if ($cart_n > 0): ?>
                <a href="cart.php" class="mt-3 flex items-center justify-center gap-2 text-[12.5px] font-bold text-slate-500 hover:text-slate-800">
                    <i class="fas fa-basket-shopping"></i> <?php echo $cart_n; ?> item<?php echo $cart_n > 1 ? 's' : ''; ?> in your cart
                </a>
            <?php endif; ?>

            <div class="mt-5 pt-4 border-t border-slate-100 grid grid-cols-3 gap-2 text-center">
                <div><i class="fas fa-shield-halved text-slate-300"></i><p class="text-[10.5px] font-bold text-slate-500 mt-1">Secure<br>payment</p></div>
                <div><i class="fas fa-headset text-slate-300"></i><p class="text-[10.5px] font-bold text-slate-500 mt-1">Support<br>on call</p></div>
                <div><i class="fas fa-receipt text-slate-300"></i><p class="text-[10.5px] font-bold text-slate-500 mt-1">Full<br>tracking</p></div>
            </div>
        </div>
      </div>

    </div>
  </div>
</main>
<?php theme_close(); ?>
</html>
