<?php
/* ============================================================================
   WBMCZ — Wallet to Bank + Wallet History UI

   Rendered inside wallet.php (member) and seller/wallet.php.
   Fully responsive: cards stack on mobile, tables turn into stacked rows.
   ============================================================================ */

require_once __DIR__ . '/bank.php';

if (!function_exists('bank_handle_post')) {

/**
 * Handles both POST actions. Call BEFORE any HTML output.
 * $rel = '' from the site root, '../' from /seller.
 */
function bank_handle_post($db, $user_id, $rel = '', $redirect = 'wallet.php#to_bank') {
    bank_ensure_schema($db);

    if (isset($_POST['save_bank_account'])) {
        $file = bank_handle_upload('passbook', $rel . 'uploads/bank/');
        $res  = bank_submit_account($db, $user_id, $_POST, $file);
        if ($res['ok']) $_SESSION['flash_success'] = "Bank details submitted. Admin will verify them shortly.";
        else            $_SESSION['flash_error']   = $res['error'];
        redirect($redirect);
    }

    if (isset($_POST['request_withdrawal'])) {
        $res = bank_request_withdrawal($db, $user_id, $_POST['wd_amount'] ?? 0);
        if ($res['ok']) $_SESSION['flash_success'] = "Withdrawal request {$res['ref']} submitted. It is now pending admin approval.";
        else            $_SESSION['flash_error']   = $res['error'];
        redirect($redirect);
    }
}

/**
 * Everything both tabs need.
 */
function bank_page_data($db, $user_id) {
    bank_ensure_schema($db);
    return [
        'settings'  => bank_settings($db),
        'account'   => bank_get_account($db, $user_id),
        'prefill'   => bank_prefill($db, $user_id),
        'latest'    => bank_latest_withdrawal($db, $user_id),
        'history'   => bank_withdrawals($db, $user_id, 100),
        'totals'    => bank_withdraw_totals($db, $user_id),
        'balances'  => wallet_balances($db, $user_id),
    ];
}

/* ===========================================================================
   TAB 1 — WALLET TO BANK
   =========================================================================== */
function bank_render_to_bank($d, $opts = []) {
    $rel    = $opts['rel'] ?? '';
    $accent = $opts['accent'] ?? 'indigo';

    $acc      = $d['account'];
    $pre      = $d['prefill'];
    $s        = $d['settings'];
    $bal      = $d['balances'];
    $approved = $acc && (int)$acc['status'] === BANK_APPROVED;
    $enabled  = ($s['withdraw_enabled'] ?? '1') === '1';

    ob_start(); ?>

<div x-data="bankTab()">

    <div class="mb-5">
        <h2 class="text-xl sm:text-2xl font-bold text-gray-800"><i class="fas fa-building-columns text-<?php echo $accent; ?>-600 mr-2"></i>Wallet to Bank</h2>
        <p class="text-gray-500 text-xs sm:text-sm mt-0.5">Move money from your main wallet to your bank account.</p>
    </div>

    <!-- ===== STEP RAIL ===== -->
    <div class="bk-steps mb-5">
        <?php
            $step = !$acc ? 1 : ((int)$acc['status'] === BANK_APPROVED ? 3 : 2);
            $steps = [
                [1, 'Add Bank', 'fa-building-columns'],
                [2, 'Admin Verify', 'fa-user-shield'],
                [3, 'Withdraw', 'fa-money-bill-transfer'],
            ];
            foreach ($steps as $i => $st):
                $done = $step > $st[0]; $cur = $step === $st[0];
        ?>
            <div class="bk-step <?php echo $done ? 'is-done' : ($cur ? 'is-cur' : ''); ?>">
                <span class="bk-dot"><i class="fas <?php echo $done ? 'fa-check' : $st[2]; ?>"></i></span>
                <span class="bk-lbl"><?php echo $st[1]; ?></span>
            </div>
            <?php if ($i < 2): ?><div class="bk-bar <?php echo $step > $st[0] ? 'is-done' : ''; ?>"></div><?php endif; ?>
        <?php endforeach; ?>
    </div>

    <!-- ===== BALANCE STRIP ===== -->
    <div class="grid grid-cols-2 lg:grid-cols-4 gap-2.5 mb-5">
        <div class="bk-card">
            <p class="bk-k">Withdrawable</p>
            <p class="text-lg sm:text-xl font-black text-emerald-600">₹<?php echo number_format($bal['main'], 2); ?></p>
            <p class="bk-sub">Main wallet only</p>
        </div>
        <div class="bk-card">
            <p class="bk-k">Locked</p>
            <p class="text-lg sm:text-xl font-black text-amber-500">₹<?php echo number_format($bal['virtual'], 2); ?></p>
            <p class="bk-sub">Virtual — not withdrawable</p>
        </div>
        <div class="bk-card">
            <p class="bk-k">In Process</p>
            <p class="text-lg sm:text-xl font-black text-blue-600">₹<?php echo number_format($d['totals']['pending'], 2); ?></p>
            <p class="bk-sub">Awaiting approval</p>
        </div>
        <div class="bk-card">
            <p class="bk-k">Withdrawn</p>
            <p class="text-lg sm:text-xl font-black text-slate-800">₹<?php echo number_format($d['totals']['approved'], 2); ?></p>
            <p class="bk-sub">Successfully sent</p>
        </div>
    </div>

    <?php if (!$enabled): ?>
        <div class="bk-note bk-note-amber mb-5">
            <i class="fas fa-triangle-exclamation"></i>
            <div><b>Withdrawals are temporarily disabled.</b><br>Please check back later or contact support.</div>
        </div>
    <?php endif; ?>

    <div class="grid lg:grid-cols-[minmax(0,1fr),340px] gap-4 items-start">

        <!-- ================= LEFT ================= -->
        <div class="space-y-4 min-w-0">

            <?php if (!$acc): ?>
                <!-- ---------- NO BANK YET ---------- -->
                <div class="bk-panel text-center py-10 px-5">
                    <div class="w-16 h-16 rounded-2xl bg-<?php echo $accent; ?>-50 text-<?php echo $accent; ?>-600 flex items-center justify-center text-2xl mx-auto mb-4 border border-<?php echo $accent; ?>-100">
                        <i class="fas fa-building-columns"></i>
                    </div>
                    <h3 class="text-lg font-extrabold text-slate-800 mb-1">Add your bank account</h3>
                    <p class="text-xs text-slate-500 max-w-sm mx-auto mb-5 leading-relaxed">
                        <?php if ($pre['source'] === 'kyc'): ?>
                            We found bank details in your KYC — the form is already filled in. Just check them and submit.
                        <?php else: ?>
                            Enter your bank details once. After admin verification you can withdraw any time.
                        <?php endif; ?>
                    </p>
                    <button type="button" @click="openForm()" class="bk-btn bk-btn-primary">
                        <i class="fas fa-plus"></i> <?php echo $pre['source'] === 'kyc' ? 'Review &amp; Submit Bank Details' : 'Add Bank Account'; ?>
                    </button>
                    <?php if ($pre['source'] === 'kyc'): ?>
                        <p class="text-[10px] text-emerald-600 font-bold mt-3"><i class="fas fa-wand-magic-sparkles mr-1"></i>Auto-filled from your KYC</p>
                    <?php endif; ?>
                </div>

            <?php else: ?>
                <!-- ---------- BANK CARD ---------- -->
                <?php $m = bank_account_status_meta($acc['status']); ?>
                <div class="bk-bank">
                    <div class="bk-bank-glow"></div>
                    <div class="relative z-10">
                        <div class="flex items-start justify-between gap-3 mb-5">
                            <div class="min-w-0">
                                <p class="text-[9px] font-extrabold uppercase tracking-[.2em] text-white/45 mb-1">Linked Bank Account</p>
                                <p class="text-base sm:text-lg font-extrabold truncate"><?php echo htmlspecialchars($acc['bank_name']); ?></p>
                            </div>
                            <span class="bk-chip bk-chip-<?php echo $m[1]; ?>"><i class="fas <?php echo $m[2]; ?> mr-1"></i><?php echo $m[0]; ?></span>
                        </div>

                        <p class="font-mono text-lg sm:text-2xl tracking-[.18em] mb-5 break-all"><?php echo htmlspecialchars(bank_mask_account($acc['account_number'])); ?></p>

                        <div class="grid grid-cols-2 gap-3 text-[11px]">
                            <div>
                                <p class="text-white/40 uppercase tracking-wider text-[9px] font-bold mb-0.5">Holder</p>
                                <p class="font-bold truncate"><?php echo htmlspecialchars($acc['holder_name']); ?></p>
                            </div>
                            <div>
                                <p class="text-white/40 uppercase tracking-wider text-[9px] font-bold mb-0.5">IFSC</p>
                                <p class="font-bold font-mono"><?php echo htmlspecialchars($acc['ifsc_code']); ?></p>
                            </div>
                            <div>
                                <p class="text-white/40 uppercase tracking-wider text-[9px] font-bold mb-0.5">Branch</p>
                                <p class="font-bold truncate"><?php echo htmlspecialchars($acc['branch_name']); ?></p>
                            </div>
                            <div>
                                <p class="text-white/40 uppercase tracking-wider text-[9px] font-bold mb-0.5">Type</p>
                                <p class="font-bold capitalize"><?php echo htmlspecialchars($acc['account_type']); ?></p>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if ((int)$acc['status'] === BANK_PENDING): ?>
                    <div class="bk-note bk-note-amber">
                        <i class="fas fa-clock"></i>
                        <div><b>Waiting for admin verification.</b><br>
                        You'll be able to withdraw as soon as your account is approved. This usually takes a few hours.</div>
                    </div>
                <?php elseif ((int)$acc['status'] === BANK_REJECTED): ?>
                    <div class="bk-note bk-note-rose">
                        <i class="fas fa-circle-xmark"></i>
                        <div>
                            <b>Your bank details were rejected.</b>
                            <?php if (!empty($acc['admin_remark'])): ?><br><span class="opacity-90">Reason: <?php echo htmlspecialchars($acc['admin_remark']); ?></span><?php endif; ?>
                            <br><button type="button" @click="openForm()" class="underline font-bold mt-1">Correct and resubmit</button>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endif; ?>

            <!-- ---------- WITHDRAW FORM ---------- -->
            <?php if ($approved && $enabled): ?>
            <div class="bk-panel p-4 sm:p-5">
                <p class="text-sm font-bold text-slate-800 mb-4"><i class="fas fa-money-bill-transfer mr-2 text-<?php echo $accent; ?>-500"></i>Request a withdrawal</p>

                <form method="POST" class="space-y-4" @submit="if (!valid()) { $event.preventDefault(); }">
                    <div>
                        <label class="bk-l">Bank account</label>
                        <label class="bk-radio">
                            <input type="radio" name="bank_pick" value="<?php echo (int)$acc['id']; ?>" checked class="sr-only peer">
                            <div class="bk-radio-box">
                                <div class="w-9 h-9 rounded-xl bg-slate-100 flex items-center justify-center text-slate-500 flex-shrink-0">
                                    <i class="fas fa-building-columns"></i>
                                </div>
                                <div class="min-w-0 flex-1">
                                    <p class="text-xs font-extrabold text-slate-800 truncate"><?php echo htmlspecialchars($acc['bank_name']); ?></p>
                                    <p class="text-[10px] text-slate-400 font-mono"><?php echo htmlspecialchars(bank_mask_account($acc['account_number'])); ?> · <?php echo htmlspecialchars($acc['ifsc_code']); ?></p>
                                </div>
                                <i class="fas fa-circle-check text-emerald-500"></i>
                            </div>
                        </label>
                    </div>

                    <div>
                        <label class="bk-l">Amount (₹)</label>
                        <div class="relative">
                            <span class="absolute left-0 top-0 bottom-0 w-11 flex items-center justify-center text-slate-400 font-bold text-lg pointer-events-none">₹</span>
                            <input type="number" step="0.01" min="<?php echo (float)$s['withdraw_min']; ?>" name="wd_amount"
                                   x-model.number="amt" required inputmode="decimal" placeholder="0.00"
                                   class="bk-f pl-11 text-lg font-black" :class="err && 'border-rose-400 bg-rose-50'">
                        </div>

                        <div class="flex flex-wrap gap-1.5 mt-2">
                            <?php foreach ([500, 1000, 2000, 5000] as $q): if ($q <= $bal['main']): ?>
                                <button type="button" @click="amt = <?php echo $q; ?>" class="bk-quick">₹<?php echo number_format($q); ?></button>
                            <?php endif; endforeach; ?>
                            <?php if ($bal['main'] >= (float)$s['withdraw_min']): ?>
                                <button type="button" @click="amt = max" class="bk-quick bk-quick-max">All ₹<?php echo number_format($bal['main'], 2); ?></button>
                            <?php endif; ?>
                        </div>

                        <p x-show="err" x-cloak class="text-[11px] font-bold text-rose-600 mt-2"><i class="fas fa-circle-exclamation mr-1"></i><span x-text="err"></span></p>
                    </div>

                    <!-- live breakdown -->
                    <div x-show="amt > 0" x-cloak class="bk-calc">
                        <div class="bk-calc-row"><span>Requested</span><b>₹<span x-text="fmt(amt)"></span></b></div>
                        <div class="bk-calc-row" x-show="charge() > 0"><span>Service charge (<?php echo bank_charge_label($s); ?>)</span><b class="text-rose-500">−₹<span x-text="fmt(charge())"></span></b></div>
                        <div class="bk-calc-row bk-calc-total"><span>You will receive</span><b class="text-emerald-600">₹<span x-text="fmt(net())"></span></b></div>
                        <div class="bk-calc-row"><span>Wallet after this</span><b>₹<span x-text="fmt(Math.max(0, max - amt))"></span></b></div>
                    </div>

                    <button type="submit" name="request_withdrawal" class="bk-btn bk-btn-primary w-full py-3.5" :disabled="!!err || !amt">
                        <i class="fas fa-paper-plane"></i> Submit Withdrawal Request
                    </button>

                    <p class="text-[10px] text-slate-400 text-center leading-relaxed">
                        Min ₹<?php echo number_format((float)$s['withdraw_min'], 2); ?>
                        <?php if ((float)$s['withdraw_max'] > 0): ?> · Max ₹<?php echo number_format((float)$s['withdraw_max'], 2); ?> per request<?php endif; ?>
                        · <?php echo bank_charge_label($s); ?><br>
                        <?php echo htmlspecialchars($s['withdraw_note']); ?>
                    </p>
                </form>
            </div>
            <?php endif; ?>
        </div>

        <!-- ================= RIGHT: LATEST STATUS ================= -->
        <div class="space-y-4">
            <?php if (!empty($d['latest'])): $w = $d['latest']; $sm = bank_status_meta($w['status']); ?>
            <div class="bk-panel overflow-hidden">
                <div class="px-4 py-3 border-b border-slate-100 bg-slate-50/70">
                    <p class="text-[11px] font-extrabold uppercase tracking-wider text-slate-500">Transaction Status</p>
                </div>
                <div class="p-4 text-center">
                    <div class="w-14 h-14 rounded-2xl mx-auto mb-3 flex items-center justify-center text-xl bk-st-<?php echo $sm[1]; ?>">
                        <i class="fas <?php echo $sm[2]; ?> <?php echo $w['status'] === 'processing' ? 'fa-spin' : ''; ?>"></i>
                    </div>
                    <p class="text-sm font-extrabold text-slate-800 leading-snug"><?php echo $sm[0]; ?></p>
                    <p class="text-2xl font-black text-slate-900 mt-2">₹<?php echo number_format((float)$w['net_amount'], 2); ?></p>
                    <p class="text-[10px] font-mono text-slate-400 mt-1"><?php echo htmlspecialchars($w['reference_no']); ?></p>

                    <div class="mt-4 space-y-1.5 text-left">
                        <div class="bk-mini"><span>Requested</span><b><?php echo date('d M Y, h:i A', strtotime($w['created_at'])); ?></b></div>
                        <?php if ((float)$w['charge'] > 0): ?>
                            <div class="bk-mini"><span>Charge</span><b class="text-rose-500">₹<?php echo number_format((float)$w['charge'], 2); ?></b></div>
                        <?php endif; ?>
                        <div class="bk-mini"><span>Bank</span><b class="truncate"><?php echo htmlspecialchars($w['bank_name']); ?></b></div>
                        <?php if (!empty($w['utr_number'])): ?>
                            <div class="bk-mini"><span>UTR</span><b class="font-mono text-[10px]"><?php echo htmlspecialchars($w['utr_number']); ?></b></div>
                        <?php endif; ?>
                        <?php if (!empty($w['reviewed_at'])): ?>
                            <div class="bk-mini"><span>Updated</span><b><?php echo date('d M, h:i A', strtotime($w['reviewed_at'])); ?></b></div>
                        <?php endif; ?>
                    </div>

                    <?php if ($w['status'] === 'approved'): ?>
                        <div class="mt-3 bk-note bk-note-emerald text-left">
                            <i class="fas fa-circle-check"></i>
                            <div>Money sent to your bank successfully. It may take a few hours to reflect.</div>
                        </div>
                    <?php elseif ($w['status'] === 'rejected'): ?>
                        <div class="mt-3 bk-note bk-note-rose text-left">
                            <i class="fas fa-rotate-left"></i>
                            <div>₹<?php echo number_format((float)$w['amount'], 2); ?> refunded to your wallet.
                            <?php if (!empty($w['admin_remark'])): ?><br><span class="opacity-90"><?php echo htmlspecialchars($w['admin_remark']); ?></span><?php endif; ?></div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

            <div class="bk-panel p-4">
                <p class="text-[11px] font-extrabold uppercase tracking-wider text-slate-500 mb-2.5">Good to know</p>
                <ul class="space-y-2 text-[11px] text-slate-500 leading-relaxed">
                    <li><i class="fas fa-circle-check text-emerald-500 mr-1.5"></i>Only your <b>main wallet</b> can be withdrawn.</li>
                    <li><i class="fas fa-lock text-amber-500 mr-1.5"></i>The <b>virtual wallet</b> is for purchases only.</li>
                    <li><i class="fas fa-shield-halved text-blue-500 mr-1.5"></i>Rejected requests are <b>refunded in full</b>.</li>
                    <li><i class="fas fa-clock text-slate-400 mr-1.5"></i><?php echo htmlspecialchars($s['withdraw_note']); ?></li>
                </ul>
            </div>
        </div>
    </div>

    <!-- ================= WITHDRAWAL HISTORY ================= -->
    <div class="bk-panel overflow-hidden mt-5">
        <div class="px-4 sm:px-5 py-3 border-b border-slate-100 bg-slate-50/70 flex items-center justify-between gap-2">
            <p class="text-sm font-bold text-slate-700"><i class="fas fa-clock-rotate-left mr-2 text-<?php echo $accent; ?>-500"></i>Transaction History</p>
            <span class="text-[11px] font-bold text-slate-400"><?php echo count($d['history']); ?> request(s)</span>
        </div>

        <?php if (empty($d['history'])): ?>
            <div class="p-12 text-center text-slate-400">
                <i class="fas fa-receipt text-3xl mb-3 block text-slate-300"></i>
                <p class="text-sm font-semibold text-slate-500">No withdrawals yet</p>
            </div>
        <?php else: ?>
            <!-- desktop table -->
            <div class="hidden md:block overflow-x-auto">
                <table class="w-full text-left text-xs">
                    <thead>
                        <tr class="bg-slate-50 text-[10px] uppercase text-slate-500 tracking-wider">
                            <th class="p-3 pl-5 font-semibold">Date</th>
                            <th class="p-3 font-semibold">Reference</th>
                            <th class="p-3 font-semibold">Bank</th>
                            <th class="p-3 font-semibold text-right">Amount</th>
                            <th class="p-3 font-semibold text-right">Received</th>
                            <th class="p-3 pr-5 font-semibold text-center">Status</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100">
                    <?php foreach ($d['history'] as $w): $sm = bank_status_meta($w['status']); ?>
                        <tr class="hover:bg-slate-50/60">
                            <td class="p-3 pl-5 whitespace-nowrap">
                                <p class="font-bold text-slate-700"><?php echo date('d M Y', strtotime($w['created_at'])); ?></p>
                                <p class="text-[10px] text-slate-400"><?php echo date('h:i A', strtotime($w['created_at'])); ?></p>
                            </td>
                            <td class="p-3 font-mono text-[10px] text-slate-500"><?php echo htmlspecialchars($w['reference_no']); ?>
                                <?php if (!empty($w['utr_number'])): ?><p class="text-emerald-600 font-bold mt-0.5">UTR <?php echo htmlspecialchars($w['utr_number']); ?></p><?php endif; ?>
                            </td>
                            <td class="p-3 text-slate-600">
                                <p class="font-semibold truncate max-w-[160px]"><?php echo htmlspecialchars($w['bank_name']); ?></p>
                                <p class="text-[10px] text-slate-400 font-mono"><?php echo htmlspecialchars(bank_mask_account($w['account_number'])); ?></p>
                            </td>
                            <td class="p-3 text-right font-bold text-slate-700 whitespace-nowrap">₹<?php echo number_format((float)$w['amount'], 2); ?>
                                <?php if ((float)$w['charge'] > 0): ?><p class="text-[10px] text-rose-400 font-normal">−₹<?php echo number_format((float)$w['charge'], 2); ?> fee</p><?php endif; ?>
                            </td>
                            <td class="p-3 text-right font-black text-emerald-600 whitespace-nowrap">₹<?php echo number_format((float)$w['net_amount'], 2); ?></td>
                            <td class="p-3 pr-5 text-center"><span class="bk-badge bk-badge-<?php echo $sm[1]; ?>"><?php echo $sm[0]; ?></span></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- mobile cards -->
            <div class="md:hidden divide-y divide-slate-100">
                <?php foreach ($d['history'] as $w): $sm = bank_status_meta($w['status']); ?>
                <div class="p-4">
                    <div class="flex items-start justify-between gap-3 mb-2">
                        <div class="min-w-0">
                            <p class="text-base font-black text-slate-800">₹<?php echo number_format((float)$w['net_amount'], 2); ?></p>
                            <p class="text-[10px] font-mono text-slate-400"><?php echo htmlspecialchars($w['reference_no']); ?></p>
                        </div>
                        <span class="bk-badge bk-badge-<?php echo $sm[1]; ?> flex-shrink-0"><?php echo $sm[0]; ?></span>
                    </div>
                    <div class="flex flex-wrap gap-x-4 gap-y-1 text-[11px] text-slate-500">
                        <span><i class="fas fa-calendar mr-1 text-slate-300"></i><?php echo date('d M Y, h:i A', strtotime($w['created_at'])); ?></span>
                        <span><i class="fas fa-building-columns mr-1 text-slate-300"></i><?php echo htmlspecialchars($w['bank_name']); ?></span>
                        <?php if ((float)$w['charge'] > 0): ?><span class="text-rose-400">Fee ₹<?php echo number_format((float)$w['charge'], 2); ?></span><?php endif; ?>
                        <?php if (!empty($w['utr_number'])): ?><span class="text-emerald-600 font-bold">UTR <?php echo htmlspecialchars($w['utr_number']); ?></span><?php endif; ?>
                    </div>
                    <?php if (!empty($w['admin_remark'])): ?>
                        <p class="text-[10px] text-slate-400 mt-1.5 italic"><?php echo htmlspecialchars($w['admin_remark']); ?></p>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- ================= BANK FORM POPUP ================= -->
    <div x-show="form" x-cloak x-transition.opacity class="fixed inset-0 z-[300] flex items-end sm:items-center justify-center sm:p-4">
        <div class="absolute inset-0 bg-slate-900/65 backdrop-blur-sm" @click="form = false"></div>
        <div class="relative w-full sm:max-w-lg bg-white rounded-t-3xl sm:rounded-2xl shadow-2xl overflow-hidden max-h-[92vh] flex flex-col">
            <div class="px-5 py-4 flex items-center justify-between flex-shrink-0" style="background:linear-gradient(135deg,#1e293b,#334155);">
                <div class="min-w-0">
                    <h3 class="text-white font-bold text-base sm:text-lg"><i class="fas fa-building-columns mr-2"></i>Bank Account Details</h3>
                    <p class="text-white/60 text-[11px]">All fields are required · verified by admin</p>
                </div>
                <button @click="form = false" class="text-white/70 hover:text-white text-3xl leading-none">&times;</button>
            </div>

            <form method="POST" enctype="multipart/form-data" class="flex flex-col overflow-hidden">
                <div class="p-5 overflow-y-auto space-y-3.5">
                    <?php if ($pre['source'] === 'kyc'): ?>
                        <div class="bk-note bk-note-emerald">
                            <i class="fas fa-wand-magic-sparkles"></i>
                            <div>Filled in from your <b>KYC bank details</b>. Please check everything before submitting.</div>
                        </div>
                    <?php endif; ?>

                    <div>
                        <label class="bk-l">Account Holder Name <span class="text-rose-500">*</span></label>
                        <input name="holder_name" required value="<?php echo htmlspecialchars($pre['holder_name']); ?>" placeholder="Exactly as printed in the passbook" class="bk-f">
                    </div>

                    <div class="grid sm:grid-cols-2 gap-3">
                        <div>
                            <label class="bk-l">Bank Name <span class="text-rose-500">*</span></label>
                            <input name="bank_name" required value="<?php echo htmlspecialchars($pre['bank_name']); ?>" placeholder="State Bank of India" class="bk-f">
                        </div>
                        <div>
                            <label class="bk-l">Branch Name <span class="text-rose-500">*</span></label>
                            <input name="branch_name" required value="<?php echo htmlspecialchars($pre['branch_name']); ?>" placeholder="Kolkata Main" class="bk-f">
                        </div>
                    </div>

                    <div>
                        <label class="bk-l">Account Number <span class="text-rose-500">*</span></label>
                        <input name="account_number" required inputmode="numeric" pattern="\d{9,18}" maxlength="18"
                               x-model="a1" value="<?php echo htmlspecialchars($pre['account_number']); ?>"
                               placeholder="9 to 18 digits" class="bk-f font-mono">
                    </div>

                    <div>
                        <label class="bk-l">Re-enter Account Number <span class="text-rose-500">*</span></label>
                        <input name="confirm_account" required inputmode="numeric" maxlength="18" x-model="a2"
                               placeholder="Type it again" class="bk-f font-mono"
                               :class="a2 && a1 !== a2 ? 'border-rose-400 bg-rose-50' : (a2 && a1 === a2 ? 'border-emerald-400 bg-emerald-50' : '')">
                        <p x-show="a2 && a1 !== a2" x-cloak class="text-[11px] font-bold text-rose-600 mt-1"><i class="fas fa-circle-exclamation mr-1"></i>Account numbers do not match</p>
                        <p x-show="a2 && a1 === a2" x-cloak class="text-[11px] font-bold text-emerald-600 mt-1"><i class="fas fa-circle-check mr-1"></i>Matched</p>
                    </div>

                    <div class="grid sm:grid-cols-2 gap-3">
                        <div>
                            <label class="bk-l">IFSC Code <span class="text-rose-500">*</span></label>
                            <input name="ifsc_code" required maxlength="11" style="text-transform:uppercase"
                                   value="<?php echo htmlspecialchars($pre['ifsc_code']); ?>" placeholder="SBIN0001234" class="bk-f font-mono">
                        </div>
                        <div>
                            <label class="bk-l">Account Type <span class="text-rose-500">*</span></label>
                            <select name="account_type" required class="bk-f">
                                <option value="savings" <?php echo $pre['account_type'] === 'savings' ? 'selected' : ''; ?>>Savings</option>
                                <option value="current" <?php echo $pre['account_type'] === 'current' ? 'selected' : ''; ?>>Current</option>
                            </select>
                        </div>
                    </div>

                    <div class="grid sm:grid-cols-2 gap-3">
                        <div>
                            <label class="bk-l">Registered Mobile <span class="text-rose-500">*</span></label>
                            <input name="mobile" required inputmode="numeric" pattern="\d{10}" maxlength="10"
                                   value="<?php echo htmlspecialchars($pre['mobile']); ?>" placeholder="10 digits" class="bk-f font-mono">
                        </div>
                        <div>
                            <label class="bk-l">UPI ID <span class="text-slate-400 font-normal normal-case">(optional)</span></label>
                            <input name="upi_id" value="<?php echo htmlspecialchars($pre['upi_id']); ?>" placeholder="name@bank" class="bk-f">
                        </div>
                    </div>

                    <div>
                        <label class="bk-l">Passbook / Cancelled Cheque <span class="text-slate-400 font-normal normal-case">(jpg, png, pdf)</span></label>
                        <input type="file" name="passbook" accept="image/*,.pdf"
                               class="w-full text-xs text-slate-600 file:mr-2 file:py-2.5 file:px-3 file:rounded-xl file:border-0 file:bg-slate-100 file:text-slate-700 file:font-bold file:text-xs">
                        <?php if ($acc && !empty($acc['passbook'])): ?>
                            <p class="text-[10px] text-emerald-600 font-bold mt-1"><i class="fas fa-check mr-1"></i>A document is already on file — upload again only to replace it.</p>
                        <?php endif; ?>
                    </div>

                    <div class="bk-note bk-note-slate">
                        <i class="fas fa-shield-halved"></i>
                        <div>Make sure every detail matches your passbook. Wrong details can cause failed or lost transfers.</div>
                    </div>
                </div>

                <div class="flex gap-2 px-5 py-4 border-t bg-slate-50 flex-shrink-0">
                    <button type="button" @click="form = false" class="bk-btn bk-btn-ghost flex-1">Cancel</button>
                    <button type="submit" name="save_bank_account" class="bk-btn bk-btn-primary flex-[2]" :disabled="!!a2 && a1 !== a2">
                        <i class="fas fa-paper-plane"></i> Submit for Verification
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php echo bank_styles(); ?>
<script>
function bankTab() {
    return {
        form: false,
        a1: <?php echo json_encode((string)$pre['account_number']); ?>,
        a2: '',
        amt: null,
        max: <?php echo (float)$bal['main']; ?>,
        min: <?php echo (float)$s['withdraw_min']; ?>,
        cap: <?php echo (float)$s['withdraw_max']; ?>,
        chargeType: <?php echo json_encode((string)$s['withdraw_charge_type']); ?>,
        chargeVal: <?php echo (float)$s['withdraw_charge_value']; ?>,
        openForm() { this.form = true; this.a2 = ''; },
        fmt(n) { return (Number(n) || 0).toFixed(2); },
        charge() {
            const a = Number(this.amt) || 0;
            if (this.chargeType === 'percent') return Math.min(a, (a * this.chargeVal) / 100);
            if (this.chargeType === 'fixed')   return Math.min(a, this.chargeVal);
            return 0;
        },
        net() { return Math.max(0, (Number(this.amt) || 0) - this.charge()); },
        get err() {
            const a = Number(this.amt) || 0;
            if (!this.amt) return '';
            if (a < this.min) return 'Minimum withdrawal is ₹' + this.min.toFixed(2);
            if (this.cap > 0 && a > this.cap) return 'Maximum ₹' + this.cap.toFixed(2) + ' per request';
            if (a > this.max) return 'Your main wallet has only ₹' + this.max.toFixed(2);
            return '';
        },
        valid() { return !this.err && Number(this.amt) > 0; }
    }
}
</script>
<?php
    return ob_get_clean();
}

/* ===========================================================================
   TAB 2 — WALLET HISTORY (both wallets, from the ledger)
   =========================================================================== */
function bank_render_history($db, $user_id, $opts = []) {
    $accent = $opts['accent'] ?? 'indigo';
    $self   = $opts['self'] ?? 'wallet.php';

    $f_wallet = in_array(($_GET['hw'] ?? ''), ['main','virtual'], true) ? $_GET['hw'] : '';
    $f_dir    = in_array(($_GET['hd'] ?? ''), ['credit','debit'], true) ? $_GET['hd'] : '';
    $f_cat    = trim($_GET['hc'] ?? '');
    $f_from   = preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['hf'] ?? '') ? $_GET['hf'] : '';
    $f_to     = preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['ht'] ?? '') ? $_GET['ht'] : '';

    $rows = wallet_history($db, $user_id, [
        'wallet' => $f_wallet, 'direction' => $f_dir, 'category' => $f_cat,
        'from' => $f_from, 'to' => $f_to, 'limit' => 500,
    ]);
    $sum  = wallet_summary($db, $user_id, $f_from, $f_to);
    $bal  = wallet_balances($db, $user_id);
    $cats = wallet_categories();

    $in  = ($sum['main_in'] ?? 0) + ($sum['virtual_in'] ?? 0);
    $out = ($sum['main_out'] ?? 0) + ($sum['virtual_out'] ?? 0);

    ob_start(); ?>

<div class="mb-5">
    <h2 class="text-xl sm:text-2xl font-bold text-gray-800"><i class="fas fa-clock-rotate-left text-<?php echo $accent; ?>-600 mr-2"></i>Wallet History</h2>
    <p class="text-gray-500 text-xs sm:text-sm mt-0.5">Every rupee that moved through your main and virtual wallets.</p>
</div>

<div class="grid grid-cols-2 lg:grid-cols-4 gap-2.5 mb-5">
    <div class="bk-card"><p class="bk-k">Total Balance</p><p class="text-lg sm:text-xl font-black text-emerald-600">₹<?php echo number_format($bal['total'], 2); ?></p><p class="bk-sub">Main + Virtual</p></div>
    <div class="bk-card"><p class="bk-k">Money In</p><p class="text-lg sm:text-xl font-black text-emerald-600">+₹<?php echo number_format($in, 2); ?></p><p class="bk-sub">Credits</p></div>
    <div class="bk-card"><p class="bk-k">Money Out</p><p class="text-lg sm:text-xl font-black text-rose-500">−₹<?php echo number_format($out, 2); ?></p><p class="bk-sub">Debits</p></div>
    <div class="bk-card"><p class="bk-k">Entries</p><p class="text-lg sm:text-xl font-black text-slate-800"><?php echo number_format($sum['count'] ?? 0); ?></p><p class="bk-sub">In this range</p></div>
</div>

<form method="GET" class="bk-panel p-4 mb-4 grid grid-cols-2 lg:grid-cols-6 gap-2 items-end">
    <input type="hidden" name="tab" value="history">
    <div><label class="bk-l">Wallet</label>
        <select name="hw" class="bk-f">
            <option value="">Both</option>
            <option value="main" <?php echo $f_wallet==='main'?'selected':''; ?>>Main</option>
            <option value="virtual" <?php echo $f_wallet==='virtual'?'selected':''; ?>>Virtual</option>
        </select></div>
    <div><label class="bk-l">Type</label>
        <select name="hd" class="bk-f">
            <option value="">All</option>
            <option value="credit" <?php echo $f_dir==='credit'?'selected':''; ?>>Credit</option>
            <option value="debit" <?php echo $f_dir==='debit'?'selected':''; ?>>Debit</option>
        </select></div>
    <div class="col-span-2 lg:col-span-1"><label class="bk-l">Category</label>
        <select name="hc" class="bk-f">
            <option value="">All</option>
            <?php foreach ($cats as $ck => $cv): ?>
                <option value="<?php echo $ck; ?>" <?php echo $f_cat===$ck?'selected':''; ?>><?php echo $cv[0]; ?></option>
            <?php endforeach; ?>
        </select></div>
    <div><label class="bk-l">From</label><input type="date" name="hf" value="<?php echo htmlspecialchars($f_from); ?>" class="bk-f"></div>
    <div><label class="bk-l">To</label><input type="date" name="ht" value="<?php echo htmlspecialchars($f_to); ?>" class="bk-f"></div>
    <div class="col-span-2 lg:col-span-1 flex gap-2">
        <button class="bk-btn bk-btn-dark flex-1 py-2.5">Apply</button>
        <a href="<?php echo $self; ?>#history" class="bk-btn bk-btn-ghost px-3 py-2.5">Reset</a>
    </div>
</form>

<div class="bk-panel overflow-hidden">
    <div class="px-4 sm:px-5 py-3 border-b border-slate-100 bg-slate-50/70 flex items-center justify-between gap-2">
        <p class="text-sm font-bold text-slate-700"><i class="fas fa-list mr-2 text-<?php echo $accent; ?>-500"></i>All transactions</p>
        <span class="text-[11px] font-bold text-slate-400"><?php echo count($rows); ?> row(s)</span>
    </div>

    <?php if (empty($rows)): ?>
        <div class="p-12 text-center text-slate-400">
            <i class="fas fa-receipt text-3xl mb-3 block text-slate-300"></i>
            <p class="text-sm font-semibold text-slate-500">No transactions for this filter</p>
        </div>
    <?php else: ?>
        <!-- desktop -->
        <div class="hidden md:block overflow-x-auto">
            <table class="w-full text-left text-xs">
                <thead>
                    <tr class="bg-slate-50 text-[10px] uppercase text-slate-500 tracking-wider">
                        <th class="p-3 pl-5 font-semibold">Date &amp; Time</th>
                        <th class="p-3 font-semibold">Wallet</th>
                        <th class="p-3 font-semibold">Category</th>
                        <th class="p-3 font-semibold">Description</th>
                        <th class="p-3 font-semibold text-right">Amount</th>
                        <th class="p-3 pr-5 font-semibold text-right">Balance</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                <?php foreach ($rows as $r): $cr = ($r['direction']==='credit'); $isv = ($r['wallet']==='virtual'); ?>
                    <tr class="hover:bg-slate-50/60">
                        <td class="p-3 pl-5 whitespace-nowrap">
                            <p class="font-bold text-slate-700"><?php echo date('d M Y', strtotime($r['created_at'])); ?></p>
                            <p class="text-[10px] text-slate-400"><?php echo date('h:i A', strtotime($r['created_at'])); ?></p>
                        </td>
                        <td class="p-3"><span class="bk-badge <?php echo $isv ? 'bk-badge-amber' : 'bk-badge-slate'; ?>"><?php echo $isv ? 'Virtual' : 'Main'; ?></span></td>
                        <td class="p-3"><span class="text-[10px] font-bold text-slate-600 whitespace-nowrap"><i class="fas <?php echo wallet_cat_icon($r['category']); ?> mr-1 text-slate-400"></i><?php echo wallet_cat_label($r['category']); ?></span></td>
                        <td class="p-3 text-slate-600 max-w-[320px]"><p class="break-words"><?php echo htmlspecialchars($r['description'] ?: '—'); ?></p></td>
                        <td class="p-3 text-right whitespace-nowrap"><span class="font-black text-sm <?php echo $cr ? 'text-emerald-600' : 'text-rose-600'; ?>"><?php echo $cr ? '+' : '−'; ?>₹<?php echo number_format((float)$r['amount'], 2); ?></span></td>
                        <td class="p-3 pr-5 text-right font-bold text-slate-500 whitespace-nowrap">₹<?php echo number_format((float)$r['balance_after'], 2); ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- mobile -->
        <div class="md:hidden divide-y divide-slate-100">
            <?php foreach ($rows as $r): $cr = ($r['direction']==='credit'); $isv = ($r['wallet']==='virtual'); ?>
            <div class="p-4 flex items-start gap-3">
                <div class="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 <?php echo $cr ? 'bg-emerald-50 text-emerald-600' : 'bg-rose-50 text-rose-600'; ?>">
                    <i class="fas <?php echo wallet_cat_icon($r['category']); ?> text-xs"></i>
                </div>
                <div class="min-w-0 flex-1">
                    <div class="flex items-start justify-between gap-2">
                        <p class="text-xs font-bold text-slate-800 leading-snug break-words"><?php echo htmlspecialchars($r['description'] ?: wallet_cat_label($r['category'])); ?></p>
                        <span class="font-black text-sm whitespace-nowrap <?php echo $cr ? 'text-emerald-600' : 'text-rose-600'; ?>"><?php echo $cr ? '+' : '−'; ?>₹<?php echo number_format((float)$r['amount'], 2); ?></span>
                    </div>
                    <div class="flex flex-wrap items-center gap-x-2 gap-y-1 mt-1.5">
                        <span class="bk-badge <?php echo $isv ? 'bk-badge-amber' : 'bk-badge-slate'; ?>"><?php echo $isv ? 'Virtual' : 'Main'; ?></span>
                        <span class="text-[10px] text-slate-400"><?php echo date('d M Y, h:i A', strtotime($r['created_at'])); ?></span>
                        <span class="text-[10px] text-slate-400">Bal ₹<?php echo number_format((float)$r['balance_after'], 2); ?></span>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<?php echo bank_styles(); ?>
<?php
    return ob_get_clean();
}

/* ---------------------------------------------------------------------------
   Shared styles — printed once per page
   --------------------------------------------------------------------------- */
function bank_styles() {
    static $done = false;
    if ($done) return '';
    $done = true;
    ob_start(); ?>
<style>
    [x-cloak] { display:none !important; }

    .bk-panel { background:#fff; border:1px solid #e2e8f0; border-radius:1rem; box-shadow:0 1px 3px rgba(15,23,42,.05); }
    .bk-card  { background:#fff; border:1px solid #e2e8f0; border-radius:1rem; padding:.85rem 1rem; }
    .bk-k     { font-size:9px; font-weight:800; text-transform:uppercase; letter-spacing:.08em; color:#94a3b8; margin-bottom:.15rem; }
    .bk-sub   { font-size:9.5px; color:#cbd5e1; margin-top:.15rem; font-weight:600; }
    .bk-l     { display:block; font-size:10px; font-weight:800; color:#475569; margin-bottom:.3rem; text-transform:uppercase; letter-spacing:.05em; }
    .bk-f     { width:100%; padding:.7rem .85rem; background:#fff; border:1.5px solid #cbd5e1; border-radius:.8rem; font-size:.82rem; outline:none; transition:.15s; color:#0f172a; }
    .bk-f:focus { border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,.14); }

    .bk-btn { display:inline-flex; align-items:center; justify-content:center; gap:.5rem; padding:.7rem 1.2rem;
              border-radius:.8rem; font-weight:800; font-size:.78rem; border:0; cursor:pointer; transition:.15s; }
    .bk-btn:disabled { opacity:.4; cursor:not-allowed; }
    .bk-btn-primary { background:linear-gradient(135deg,#4f46e5,#7c3aed); color:#fff; box-shadow:0 8px 18px -8px rgba(79,70,229,.7); }
    .bk-btn-primary:not(:disabled):hover { transform:translateY(-1px); }
    .bk-btn-dark  { background:#0f172a; color:#fff; }
    .bk-btn-ghost { background:#f1f5f9; color:#475569; }

    .bk-quick { padding:.35rem .7rem; border-radius:.6rem; background:#f1f5f9; color:#475569; font-size:11px; font-weight:800; border:0; cursor:pointer; }
    .bk-quick:hover { background:#e2e8f0; }
    .bk-quick-max { background:#dcfce7; color:#15803d; }

    /* premium bank card */
    .bk-bank { position:relative; border-radius:1.25rem; padding:1.25rem; color:#fff; overflow:hidden;
               background:linear-gradient(140deg,#0b1220 0%,#1e293b 52%,#0b1220 100%);
               box-shadow:0 18px 40px -18px rgba(2,6,23,.65); }
    .bk-bank-glow { position:absolute; right:-70px; top:-70px; width:220px; height:220px; border-radius:50%;
                    background:radial-gradient(circle,rgba(99,102,241,.42) 0%,transparent 68%); }

    .bk-chip { font-size:9px; font-weight:900; padding:.28rem .6rem; border-radius:999px; white-space:nowrap; letter-spacing:.03em; }
    .bk-chip-emerald { background:rgba(16,185,129,.2); color:#6ee7b7; border:1px solid rgba(16,185,129,.35); }
    .bk-chip-amber   { background:rgba(245,158,11,.2); color:#fcd34d; border:1px solid rgba(245,158,11,.35); }
    .bk-chip-rose    { background:rgba(244,63,94,.2);  color:#fda4af; border:1px solid rgba(244,63,94,.35); }

    .bk-badge { display:inline-block; font-size:9px; font-weight:900; padding:.25rem .55rem; border-radius:.45rem; white-space:nowrap; }
    .bk-badge-emerald { background:#d1fae5; color:#047857; }
    .bk-badge-amber   { background:#fef3c7; color:#b45309; }
    .bk-badge-rose    { background:#ffe4e6; color:#be123c; }
    .bk-badge-blue    { background:#dbeafe; color:#1d4ed8; }
    .bk-badge-slate   { background:#f1f5f9; color:#475569; }

    .bk-st-emerald { background:#d1fae5; color:#059669; }
    .bk-st-amber   { background:#fef3c7; color:#d97706; }
    .bk-st-rose    { background:#ffe4e6; color:#e11d48; }
    .bk-st-blue    { background:#dbeafe; color:#2563eb; }

    .bk-note { display:flex; gap:.7rem; align-items:flex-start; padding:.8rem 1rem; border-radius:.85rem; font-size:11.5px; line-height:1.6; }
    .bk-note i { margin-top:.15rem; flex-shrink:0; }
    .bk-note-amber   { background:#fffbeb; border:1px solid #fde68a; color:#92400e; }
    .bk-note-rose    { background:#fff1f2; border:1px solid #fecdd3; color:#9f1239; }
    .bk-note-emerald { background:#ecfdf5; border:1px solid #a7f3d0; color:#065f46; }
    .bk-note-slate   { background:#f8fafc; border:1px solid #e2e8f0; color:#475569; }

    .bk-radio-box { display:flex; align-items:center; gap:.75rem; padding:.8rem; border:2px solid #e2e8f0; border-radius:.9rem; cursor:pointer; transition:.15s; }
    .bk-radio input:checked + .bk-radio-box { border-color:#6366f1; background:#eef2ff; }

    .bk-calc { background:#f8fafc; border:1px solid #e2e8f0; border-radius:.9rem; padding:.85rem 1rem; }
    .bk-calc-row { display:flex; justify-content:space-between; align-items:center; gap:1rem; font-size:11.5px; color:#64748b; padding:.22rem 0; }
    .bk-calc-row b { color:#0f172a; font-weight:800; }
    .bk-calc-total { border-top:1px dashed #cbd5e1; margin-top:.35rem; padding-top:.5rem; font-size:12.5px; }

    .bk-mini { display:flex; justify-content:space-between; align-items:center; gap:.75rem; font-size:10.5px; color:#94a3b8;
               background:#f8fafc; border-radius:.5rem; padding:.4rem .6rem; }
    .bk-mini b { color:#334155; font-weight:800; }

    /* step rail */
    .bk-steps { display:flex; align-items:center; gap:.4rem; }
    .bk-step  { display:flex; flex-direction:column; align-items:center; gap:.35rem; flex-shrink:0; }
    .bk-dot   { width:34px; height:34px; border-radius:50%; display:flex; align-items:center; justify-content:center;
                background:#f1f5f9; color:#cbd5e1; font-size:12px; border:2px solid #e2e8f0; transition:.25s; }
    .bk-lbl   { font-size:9.5px; font-weight:800; color:#94a3b8; text-transform:uppercase; letter-spacing:.04em; white-space:nowrap; }
    .bk-step.is-cur  .bk-dot { background:#eef2ff; color:#4f46e5; border-color:#a5b4fc; box-shadow:0 0 0 4px rgba(99,102,241,.12); }
    .bk-step.is-cur  .bk-lbl { color:#4f46e5; }
    .bk-step.is-done .bk-dot { background:#10b981; color:#fff; border-color:#10b981; }
    .bk-step.is-done .bk-lbl { color:#059669; }
    .bk-bar { flex:1; height:2.5px; background:#e2e8f0; border-radius:2px; min-width:14px; }
    .bk-bar.is-done { background:#10b981; }

    @media (max-width:400px) { .bk-lbl { font-size:8.5px; } .bk-dot { width:30px; height:30px; } }
</style>
<?php
    return ob_get_clean();
}

} // end function_exists guard
