<?php
/* ============================================================================
   WBMCZ — ORDER TRACKING
   ----------------------------------------------------------------------------
   One order, its seven steps, everything that has been paid, and — while money
   is still outstanding — a way for the customer to clear it online instead of
   waiting for the visit.
   ============================================================================ */
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');
$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'];

$oid = isset($_GET['id']) ? (int)$_GET['id'] : 0;

/* the office and the seller on the order may look at it too */
$order = buy_order($db, $oid);
if (!$order) { redirect('orders.php'); }
$mine   = ((int)$order['user_id'] === $user_id);
$seller = ((int)($order['seller_id'] ?? 0) === $user_id);
if (!$mine && !$seller && $role !== 'admin') { redirect('orders.php'); }

$err = ''; $ok = '';

/* ---------- the customer clears the balance online ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['pay_due']) && $mine) {
    $due = round((float)$order['due_amount'], 2);
    if ($due <= 0) {
        $err = 'Nothing is outstanding on this order.';
    } else {
        $use_wallet = !empty($_POST['use_wallet']);
        $plan   = buy_wallet_plan($db, $user_id, $due, $use_wallet);
        $paid_ok = true; $ref = '';

        if ($plan['gateway'] > 0.009) {
            $pay_id = trim((string)($_POST['payment_id'] ?? ''));
            $paid_ok = false;
            if ($pay_id !== '' && $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)
                    && ((float)$d['amount'] / 100) + 0.009 >= $plan['gateway']) {
                    $paid_ok = true; $ref = $pay_id;
                }
            }
            if (!$paid_ok) { $err = 'We could not verify that payment. Nothing has been recorded.'; }
        }

        if ($paid_ok) {
            if ($plan['wallet'] > 0) {
                $sp = wallet_spend($db, $user_id, $plan['wallet'], [
                    'category' => 'purchase',
                    'description' => 'Balance on order ' . $order['order_code'],
                    'reference_type' => 'order', 'reference_id' => $oid,
                ]);
                if (!$sp['ok']) { $err = 'Your wallet balance changed. Please try again.'; }
            }
            if ($err === '') {
                if ($plan['gateway'] > 0) {
                    try {
                        $db->insert("INSERT INTO transactions (user_id, type, amount, description, status) VALUES (?, 'debit', ?, ?, 'Success')",
                            [$user_id, $plan['gateway'], "Paid online (ID: $ref) — balance on order " . $order['order_code']]);
                        wallet__ledger($db, $user_id, WALLET_MAIN, 'debit', $plan['gateway'], wallet_balances($db, $user_id)['main'], [
                            'category' => 'purchase', 'description' => "Paid online (ID: $ref) — order " . $order['order_code'],
                            'reference_type' => 'order', 'reference_id' => $oid,
                        ]);
                    } catch (\Throwable $e) {}
                }
                $res = buy_record_collection($db, $oid, [
                    'amount' => $due, 'mode' => 'company',
                    'reference' => $ref ?: 'wallet',
                    'note' => 'Paid online by the customer',
                    'auto' => true,
                ]);
                if (empty($res['ok'])) { $err = $res['error']; }
                else {
                    $_SESSION['flash_ok'] = 'Payment received. Nothing more is owed on this order.';
                    redirect('order.php?id=' . $oid);
                }
            }
        }
    }
}

/* ---------- the seller says what they collected ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['collect']) && ($seller || $role === 'admin')) {
    $res = buy_record_collection($db, $oid, [
        'amount' => (float)($_POST['amount'] ?? 0),
        'mode'   => (string)($_POST['mode'] ?? 'cash'),
        'reference' => trim((string)($_POST['reference'] ?? '')),
        'note'   => trim((string)($_POST['note'] ?? '')),
        'auto'   => ($role === 'admin'),
    ]);
    if (empty($res['ok'])) { $err = $res['error']; }
    else {
        $_SESSION['flash_ok'] = $role === 'admin'
            ? 'Recorded and verified.'
            : 'Recorded. The office will verify it shortly.';
        redirect('order.php?id=' . $oid);
    }
}

if (!empty($_SESSION['flash_ok'])) { $ok = $_SESSION['flash_ok']; unset($_SESSION['flash_ok']); }
$order = buy_order($db, $oid);          /* re-read, it may have moved */

$stages   = buy_stages();
$here     = buy_stage_index((string)$order['stage']);
$cancelled = ((string)$order['stage'] === 'cancelled');
$is_visit = ((string)$order['fulfilment'] === 'visit');
$due      = round((float)$order['due_amount'], 2);

/* what the seller has claimed but the office has not looked at */
$waiting = buy_collections($db, ['order_id' => $oid]);

$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); }
function dt($s) { return $s ? date('d M Y, g:i A', strtotime($s)) : ''; }
$plan_due = $due > 0 ? buy_wallet_plan($db, $user_id, $due, true) : ['wallet' => 0, 'gateway' => 0, 'covered' => false];
?>
<!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>Order <?php echo esc($order['order_code']); ?> - <?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; }
        .o-card { background:#fff; border:1px solid #e8edf5; border-radius:18px; box-shadow:0 10px 30px -22px rgba(15,23,42,.55); }
        .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; }

        /* the seven steps */
        .track { position:relative; padding-left:40px; }
        .track:before { content:''; position:absolute; left:15px; top:12px; bottom:12px; width:2px; background:#e8edf5; }
        .tstep { position:relative; padding:12px 0; }
        .tdot { position:absolute; left:-40px; top:10px; width:31px; height:31px; border-radius:50%;
                background:#fff; border:2px solid #e2e8f0; color:#cbd5e1; display:flex; align-items:center;
                justify-content:center; font-size:.72rem; z-index:1; }
        .tstep.done .tdot { background:#0b1220; border-color:#0b1220; color:#fff; }
        .tstep.now  .tdot { background:linear-gradient(135deg,#C8901B,#e0a92c); border-color:#C8901B; color:#14202f;
                            box-shadow:0 0 0 5px rgba(200,144,27,.16); }
        .tstep.done .tname, .tstep.now .tname { color:#0f172a; }
        .tname { font-weight:800; font-size:.86rem; color:#94a3b8; }
        .tnote { font-size:.75rem; color:#94a3b8; margin-top:1px; }

        .badge { display:inline-flex; align-items:center; gap:5px; padding:4px 11px; border-radius:999px;
                 font-size:.68rem; font-weight:800; }
        .b-gold { background:#fff7e6; color:#b45309; border:1px solid #fde3af; }
        .b-green{ background:#ecfdf5; color:#047857; border:1px solid #d1fae5; }
        .b-red  { background:#fef2f2; color:#b91c1c; border:1px solid #fecaca; }
        .b-slate{ background:#f1f5f9; color:#475569; border:1px solid #e2e8f0; }

        .btn { display:inline-flex; align-items:center; justify-content:center; gap:8px; width:100%;
               font-weight:800; border-radius:13px; padding:13px 18px; font-size:.88rem; 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; }
        .fld { width:100%; border:1.5px solid #e8edf5; border-radius:12px; padding:10px 12px; font-size:.85rem; }
        .fld:focus { outline:none; border-color:#C8901B; box-shadow:0 0 0 3px rgba(200,144,27,.12); }
        .lbl { font-size:.68rem; font-weight:800; text-transform:uppercase; letter-spacing:.05em; color:#94a3b8; margin-bottom:4px; display:block; }
        .code-box { background:linear-gradient(135deg,#0b1220,#1e293b); color:#fff; border-radius:16px; padding:18px; text-align:center; }
        .code-box b { font-family:'Poppins',sans-serif; font-size:1.7rem; letter-spacing:.18em; color:#e6bb5f; }
    </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' => 'Order ' . $order['order_code'], 'active' => 'orders',
    '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-5xl mx-auto">

    <?php if (isset($_GET['new'])): ?>
        <div class="mb-4 px-5 py-4 rounded-2xl bg-emerald-50 border border-emerald-200">
            <p class="font-poppins font-bold text-emerald-900"><i class="fas fa-circle-check"></i> Your order is placed</p>
            <p class="text-[13px] text-emerald-800 mt-0.5">
                <?php if ((string)$order['payment_code_status'] === 'pending'): ?>
                    Keep the payment code below — it is how we match your money to this order.
                <?php elseif ($due > 0): ?>
                    <?php echo pr($due); ?> is still to be paid, at the visit or online from this page.
                <?php else: ?>
                    Everything is paid. We will take it from here.
                <?php endif; ?>
            </p>
        </div>
    <?php endif; ?>
    <?php if ($ok): ?><div class="mb-4 px-4 py-3 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-800 text-sm font-semibold"><i class="fas fa-circle-check mr-1"></i> <?php echo esc($ok); ?></div><?php endif; ?>
    <?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 esc($err); ?></div><?php endif; ?>

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

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

        <div class="o-card p-5 sm:p-6">
            <div class="flex flex-wrap items-start justify-between gap-3">
                <div>
                    <p class="text-[11px] font-extrabold uppercase tracking-wider text-slate-400">Order</p>
                    <h1 class="font-poppins text-xl font-bold text-slate-900"><?php echo esc($order['order_code']); ?></h1>
                    <p class="text-[12.5px] text-slate-500 mt-0.5">Placed <?php echo dt($order['created_at']); ?></p>
                </div>
                <div class="flex flex-wrap gap-2">
                    <?php if ($cancelled): ?><span class="badge b-red"><i class="fas fa-ban"></i> Cancelled</span>
                    <?php elseif ((string)$order['stage'] === 'completed'): ?><span class="badge b-green"><i class="fas fa-flag-checkered"></i> Completed</span>
                    <?php else: ?><span class="badge b-gold"><i class="fas fa-clock"></i> <?php echo esc(buy_stage_meta($order['stage'])[0]); ?></span><?php endif; ?>
                    <?php if ($is_visit): ?><span class="badge b-slate"><i class="fas fa-person-walking"></i> Visit</span><?php endif; ?>
                </div>
            </div>

            <div class="mt-5 rounded-xl border border-slate-200 divide-y divide-slate-100">
                <?php foreach ($order['items'] as $it): ?>
                <?php
                /* the product's own picture, when the product is still there */
                $__svc = (int)$it['service_id'] > 0 ? shares_get_service($db, (int)$it['service_id']) : null;
                $th    = $__svc ? buy_thumb($__svc) : ['img' => '', 'icon' => 'fa-file-lines'];
                ?>
                <div class="flex items-center gap-3 p-3.5">
                    <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">
                        <a href="product.php?id=<?php echo (int)$it['service_id']; ?>" class="font-bold text-[13.5px] text-slate-800 hover:text-[#C8901B] truncate block"><?php echo esc($it['title']); ?></a>
                        <p class="text-[11.5px] text-slate-500">
                            <?php echo $it['fulfilment'] === 'visit' ? 'Visit &amp; complete' : 'Online'; ?>
                            <?php if ((int)$it['qty'] > 1): ?> · &times;<?php echo (int)$it['qty']; ?><?php endif; ?>
                            <?php if (!empty($it['seller_name'])): ?> · <?php echo esc($it['seller_name']); ?><?php endif; ?>
                        </p>
                    </div>
                    <span class="font-extrabold text-slate-800 text-[13.5px]"><?php echo pr($it['amount']); ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- the seven steps -->
        <div class="o-card p-5 sm:p-6">
            <h2 class="font-poppins font-bold text-slate-800 mb-4">Where it has got to</h2>
            <div class="track">
                <?php $i = 0; foreach ($stages as $key => $s): $i++;
                    /* an online order never has a visit or a collection step */
                    if (!$is_visit && in_array($key, ['visit', 'collected'], true)) { continue; }
                    $idx  = buy_stage_index($key);
                    $done = (!$cancelled && $idx < $here);
                    $now  = (!$cancelled && $idx === $here);
                ?>
                <div class="tstep <?php echo $done ? 'done' : ($now ? 'now' : ''); ?>">
                    <div class="tdot"><i class="fas <?php echo $done ? 'fa-check' : $s[1]; ?>"></i></div>
                    <p class="tname"><?php echo esc($s[0]); ?></p>
                    <p class="tnote"><?php echo esc($s[2]); ?></p>
                </div>
                <?php endforeach; ?>
                <?php if ($cancelled): ?>
                <div class="tstep now">
                    <div class="tdot" style="background:#fef2f2;border-color:#fecaca;color:#b91c1c"><i class="fas fa-ban"></i></div>
                    <p class="tname" style="color:#b91c1c">Cancelled</p>
                    <p class="tnote">This order was cancelled.</p>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- what actually happened, line by line -->
        <div class="o-card p-5 sm:p-6">
            <h2 class="font-poppins font-bold text-slate-800 mb-3">History</h2>
            <div class="space-y-2.5">
            <?php foreach (array_reverse($order['timeline']) as $tl): ?>
                <div class="flex gap-3 items-start">
                    <div class="w-7 h-7 rounded-full bg-slate-50 border border-slate-200 flex items-center justify-center text-[10px] text-slate-400 flex-shrink-0 mt-0.5">
                        <i class="fas <?php echo esc(buy_stage_meta($tl['stage'])[1]); ?>"></i>
                    </div>
                    <div class="flex-1 min-w-0">
                        <p class="text-[13px] font-bold text-slate-800">
                            <?php echo esc($tl['title']); ?>
                            <?php if ($tl['amount'] !== null && (float)$tl['amount'] > 0): ?>
                                <span class="text-[#C8901B]">· <?php echo pr($tl['amount']); ?></span>
                            <?php endif; ?>
                        </p>
                        <?php if (!empty($tl['note'])): ?><p class="text-[12px] text-slate-500"><?php echo esc($tl['note']); ?></p><?php endif; ?>
                        <p class="text-[11px] text-slate-400 mt-0.5">
                            <?php echo dt($tl['created_at']); ?>
                            <?php if (!empty($tl['actor_name'])): ?> · <?php echo esc($tl['actor_name']); ?><?php endif; ?>
                        </p>
                    </div>
                </div>
            <?php endforeach; ?>
            </div>
        </div>
      </div>

      <!-- right -->
      <div class="lg:col-span-1 space-y-5">

        <?php if ((string)$order['payment_code_status'] === 'pending' && !empty($order['payment_code'])): ?>
        <div class="code-box">
            <p class="text-[10.5px] font-extrabold uppercase tracking-widest text-white/50">Your payment code</p>
            <b><?php echo esc($order['payment_code']); ?></b>
            <p class="text-[12px] text-white/70 mt-2 leading-snug">
                Pay <?php echo pr($order['due_amount']); ?> at the office or to our person and give them this code.
            </p>
        </div>
        <?php endif; ?>

        <div class="o-card p-5">
            <h3 class="font-poppins font-bold text-slate-800 mb-3">Payment</h3>
            <div class="row"><span class="text-slate-500">Order total</span><span class="font-bold text-slate-800"><?php echo pr($order['amount']); ?></span></div>
            <?php if ((float)$order['discount_amount'] > 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($order['discount_amount']); ?></span></div>
            <?php endif; ?>
            <?php if ((float)$order['wallet_used'] > 0): ?>
                <div class="row"><span class="text-slate-500">From wallet</span><span class="font-bold text-emerald-600"><?php echo pr($order['wallet_used']); ?></span></div>
            <?php endif; ?>
            <?php if ((float)$order['gateway_used'] > 0): ?>
                <div class="row"><span class="text-slate-500">Paid online</span><span class="font-bold text-slate-800"><?php echo pr($order['gateway_used']); ?></span></div>
            <?php endif; ?>
            <?php if ((float)$order['collected_amount'] > 0): ?>
                <div class="row"><span class="text-slate-500">Collected <?php echo $order['collected_mode'] ? '(' . esc(buy_mode_label($order['collected_mode'])) . ')' : ''; ?></span><span class="font-bold text-slate-800"><?php echo pr($order['collected_amount']); ?></span></div>
            <?php endif; ?>
            <div class="row"><span class="text-slate-800 font-bold">Paid so far</span><span class="font-extrabold text-emerald-600"><?php echo pr($order['paid_amount']); ?></span></div>
            <?php if ($due > 0): ?>
                <div class="row"><span class="text-amber-800 font-bold">Still to pay</span><span class="font-extrabold text-amber-700 text-base"><?php echo pr($due); ?></span></div>
            <?php endif; ?>
        </div>

        <?php if ($due > 0 && $mine && !$cancelled): ?>
        <div class="o-card p-5" x-data="{ useWallet: true, busy: false }">
            <h3 class="font-poppins font-bold text-slate-800 mb-1">Clear it now?</h3>
            <p class="text-[12.5px] text-slate-500 mb-3">
                You can pay the remaining <?php echo pr($due); ?> here instead of waiting for the visit.
            </p>
            <form method="POST" id="dueForm">
                <input type="hidden" name="pay_due" value="1">
                <input type="hidden" name="payment_id" id="due_payment_id">
                <input type="hidden" name="use_wallet" :value="useWallet ? 1 : ''">

                <?php if ($plan_due['wallet'] > 0): ?>
                <label class="flex items-center gap-2.5 mb-3 cursor-pointer">
                    <input type="checkbox" x-model="useWallet" class="accent-[#C8901B]">
                    <span class="text-[12.5px] text-slate-600 font-semibold">
                        Use <?php echo pr($plan_due['wallet']); ?> from my wallet
                    </span>
                </label>
                <?php endif; ?>

                <button type="button" class="btn btn-go" :disabled="busy" :class="busy && 'opacity-50 pointer-events-none'"
                        @click="payDue($el, useWallet)">
                    <i class="fas fa-lock"></i> Pay <?php echo pr($due); ?>
                </button>
            </form>
            <p class="text-[11px] text-slate-400 mt-2 leading-snug">
                Paid this way, the money reaches the company directly — the seller does not have to carry it.
            </p>
        </div>
        <?php endif; ?>

        <?php if (($seller || $role === 'admin') && $due > 0 && !$cancelled): ?>
        <div class="o-card p-5">
            <h3 class="font-poppins font-bold text-slate-800 mb-1">Record what you collected</h3>
            <p class="text-[12.5px] text-slate-500 mb-3">
                <?php echo $role === 'admin'
                    ? 'Anything entered here is verified straight away.'
                    : 'The office verifies this before it counts against your dues.'; ?>
            </p>
            <form method="POST" class="space-y-3">
                <input type="hidden" name="collect" value="1">
                <div>
                    <label class="lbl">Amount</label>
                    <input class="fld" type="number" step="0.01" min="0.01" max="<?php echo $due; ?>" name="amount" value="<?php echo $due; ?>" required>
                </div>
                <div>
                    <label class="lbl">How it was taken</label>
                    <select class="fld" name="mode">
                        <?php foreach (buy_collection_modes() as $k => $m): ?>
                            <option value="<?php echo $k; ?>"><?php echo esc($m[0]); ?> — <?php echo esc($m[3]); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="lbl">Reference (optional)</label>
                    <input class="fld" name="reference" maxlength="120" placeholder="UPI id, receipt number…">
                </div>
                <button class="btn btn-dark"><i class="fas fa-sack-dollar"></i> Record <?php echo pr($due); ?></button>
            </form>
        </div>
        <?php endif; ?>

        <?php if (!empty($waiting) && ($seller || $role === 'admin' || $mine)): ?>
        <div class="o-card p-5">
            <h3 class="font-poppins font-bold text-slate-800 mb-3">Collections on this order</h3>
            <div class="space-y-2">
            <?php foreach ($waiting as $c): ?>
                <div class="flex items-center gap-2.5 text-[12.5px]">
                    <span class="badge <?php echo $c['status'] === 'approved' ? 'b-green' : ($c['status'] === 'rejected' ? 'b-red' : 'b-gold'); ?>">
                        <?php echo ucfirst($c['status']); ?>
                    </span>
                    <span class="font-bold text-slate-800"><?php echo pr($c['amount']); ?></span>
                    <span class="text-slate-400"><?php echo esc(buy_mode_label($c['mode'])); ?></span>
                    <span class="ml-auto text-[11px] text-slate-400"><?php echo dt($c['created_at']); ?></span>
                </div>
            <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <?php if (!empty($order['address'])): ?>
        <div class="o-card p-5">
            <h3 class="font-poppins font-bold text-slate-800 mb-2"><?php echo $is_visit ? 'Visit address' : 'Contact'; ?></h3>
            <p class="text-[13px] font-bold text-slate-700"><?php echo esc($order['customer_name']); ?></p>
            <p class="text-[12.5px] text-slate-500"><?php echo esc($order['customer_mobile']); ?></p>
            <p class="text-[12.5px] text-slate-500 mt-1 leading-snug"><?php echo nl2br(esc($order['address'])); ?></p>
            <?php if (!empty($order['note'])): ?>
                <p class="text-[12px] text-slate-400 mt-2"><i class="fas fa-note-sticky"></i> <?php echo esc($order['note']); ?></p>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <a href="orders.php" class="block text-center text-[12.5px] font-bold text-slate-400 hover:text-slate-700">
            <i class="fas fa-arrow-left"></i> All my orders
        </a>
      </div>
    </div>
  </div>
</main>

<script>
var DUE_GATEWAY = <?php echo json_encode((float)($plan_due['gateway'] ?? 0)); ?>;
var DUE_WALLET  = <?php echo json_encode((float)($plan_due['wallet'] ?? 0)); ?>;
var DUE_TOTAL   = <?php echo json_encode((float)$due); ?>;
var RZP_KEY     = <?php echo json_encode($rzp_key); ?>;
var BRAND       = <?php echo json_encode($company_name); ?>;

function payDue(btn, useWallet) {
    var f = document.getElementById('dueForm');
    var gateway = useWallet ? DUE_GATEWAY : DUE_TOTAL;
    if (gateway <= 0) { f.submit(); return; }
    if (!RZP_KEY) { alert('Online payment is not set up yet. Please contact support.'); return; }
    var rzp = new Razorpay({
        key: RZP_KEY,
        amount: Math.round(gateway * 100),
        currency: 'INR',
        name: BRAND,
        description: 'Balance on order <?php echo esc($order['order_code']); ?>',
        handler: function (res) {
            document.getElementById('due_payment_id').value = res.razorpay_payment_id;
            f.submit();
        }
    });
    rzp.open();
}
</script>
<?php theme_close(); ?>
</html>
