<?php
/* ============================================================================
   Admin → Wallet Management → Bank Requests / Transaction Update
   Tabs:  #bank_requests   #transactions   #settings
   ============================================================================ */
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/bank.php';

if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }
if (!hasPermission('manage_transactions')) { die("Access Denied: You do not have permission to manage withdrawals."); }

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

bank_ensure_schema($db);

$can_users = hasPermission('manage_users');
$can_sellers = hasPermission('manage_sellers');
$can_staff = hasPermission('manage_staff_roles');
$can_services = hasPermission('manage_services');
$can_orders = hasPermission('manage_orders');
$can_transactions = hasPermission('manage_transactions');
$can_tickets = hasPermission('manage_tickets');
$can_settings = hasPermission('manage_settings');

$success_msg = ''; $error_msg = '';
if (isset($_SESSION['flash_success'])) { $success_msg = $_SESSION['flash_success']; unset($_SESSION['flash_success']); }
if (isset($_SESSION['flash_error']))   { $error_msg   = $_SESSION['flash_error'];   unset($_SESSION['flash_error']); }

$me_row = $db->select("SELECT id, name FROM users WHERE id = ?", [$user_id]);
$me = !empty($me_row) ? $me_row[0] : ['id' => $user_id, 'name' => 'Admin'];

/* ============================================================
   AJAX — full detail of one bank account / one withdrawal
   ============================================================ */
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    $id = intval($_GET['id'] ?? 0);
    if ($_GET['ajax'] === 'bank') {
        $r = $db->select("SELECT b.*, u.name AS user_name, u.mobile AS user_mobile, u.email AS user_email, u.user_type,
                                 k.full_name AS kyc_name, k.account_number AS kyc_account, k.ifsc_code AS kyc_ifsc,
                                 k.bank_name AS kyc_bank, k.status AS kyc_status,
                                 COALESCE(u.wallet_balance,0) AS wallet_balance, COALESCE(u.bonus_wallet,0) AS bonus_wallet
                          FROM bank_accounts b
                          LEFT JOIN users u ON b.user_id = u.id
                          LEFT JOIN kyc_details k ON b.user_id = k.user_id
                          WHERE b.id = ?", [$id]);
        echo json_encode(!empty($r) ? $r[0] : null);
    } elseif ($_GET['ajax'] === 'wd') {
        $r = $db->select("SELECT w.*, u.name AS user_name, u.mobile AS user_mobile, u.email AS user_email,
                                 COALESCE(u.wallet_balance,0) AS wallet_balance,
                                 b.branch_name, b.account_type, b.upi_id, b.passbook, b.mobile AS bank_mobile
                          FROM withdrawal_requests w
                          LEFT JOIN users u ON w.user_id = u.id
                          LEFT JOIN bank_accounts b ON w.bank_account_id = b.id
                          WHERE w.id = ?", [$id]);
        echo json_encode(!empty($r) ? $r[0] : null);
    } else { echo json_encode(['error' => 'unknown']); }
    exit;
}

/* ============================================================
   POST HANDLERS
   ============================================================ */
if (isset($_POST['review_bank'])) {
    $bid     = intval($_POST['bank_id']);
    $approve = ($_POST['review_bank'] === 'approve');
    $remark  = trim(sanitize($_POST['bank_remark'] ?? ''));
    if (!$approve && $remark === '') {
        $_SESSION['flash_error'] = "Please write a reason so the user knows what to correct.";
    } else {
        bank_review_account($db, $bid, $approve, $remark, $me);
        $_SESSION['flash_success'] = $approve
            ? "Bank account verified. Wallet to Bank is now active for this user."
            : "Bank account rejected. The user can correct and resubmit.";
    }
    redirect('withdrawals.php#bank_requests');
}

if (isset($_POST['review_wd'])) {
    $wid    = intval($_POST['wd_id']);
    $action = $_POST['review_wd'];
    $utr    = trim(sanitize($_POST['utr_number'] ?? ''));
    $remark = trim(sanitize($_POST['wd_remark'] ?? ''));

    if ($action === 'approve' && $utr === '') {
        $_SESSION['flash_error'] = "Please enter the UTR / reference number of the transfer.";
    } elseif ($action === 'reject' && $remark === '') {
        $_SESSION['flash_error'] = "Please write a reason — the amount will be refunded to the user.";
    } else {
        $res = bank_review_withdrawal($db, $wid, $action, $utr, $remark, $me);
        if ($res['ok']) {
            $_SESSION['flash_success'] = $action === 'approve'
                ? "Marked as sent successfully. The user has been notified."
                : ($action === 'processing' ? "Marked as processing." : "Rejected — the full amount has been refunded to the user's wallet.");
        } else { $_SESSION['flash_error'] = $res['error']; }
    }
    redirect('withdrawals.php#transactions');
}

if (isset($_POST['save_settings'])) {
    foreach (bank_default_settings() as $k => $_) {
        if (isset($_POST[$k])) bank_save_setting($db, $k, sanitize($_POST[$k]));
    }
    $_SESSION['flash_success'] = "Withdrawal settings saved.";
    redirect('withdrawals.php#settings');
}

/* ============================================================
   DATA
   ============================================================ */
$bs = isset($_GET['bs']) && in_array($_GET['bs'], ['0','1','2'], true) ? (int)$_GET['bs'] : 0;
$ws = isset($_GET['ws']) && in_array($_GET['ws'], ['pending','processing','approved','rejected'], true) ? $_GET['ws'] : 'pending';
$q  = trim($_GET['q'] ?? '');

$bq = "SELECT b.*, u.name AS user_name, u.mobile AS user_mobile, u.user_type
       FROM bank_accounts b LEFT JOIN users u ON b.user_id = u.id WHERE b.status = ?";
$bp = [$bs];
if ($q !== '') { $bq .= " AND (u.name LIKE ? OR u.mobile LIKE ? OR b.account_number LIKE ? OR b.bank_name LIKE ?)";
                 $l = "%$q%"; array_push($bp, $l, $l, $l, $l); }
$bq .= " ORDER BY b.updated_at DESC, b.created_at DESC LIMIT 300";
$bank_rows = $db->select($bq, $bp);

$wq = "SELECT w.*, u.name AS user_name, u.mobile AS user_mobile
       FROM withdrawal_requests w LEFT JOIN users u ON w.user_id = u.id WHERE w.status = ?";
$wp = [$ws];
if ($q !== '') { $wq .= " AND (u.name LIKE ? OR u.mobile LIKE ? OR w.reference_no LIKE ? OR w.account_number LIKE ?)";
                 $l = "%$q%"; array_push($wp, $l, $l, $l, $l); }
$wq .= " ORDER BY w.created_at DESC LIMIT 300";
$wd_rows = $db->select($wq, $wp);

/* Counters */
$bc = ['0' => 0, '1' => 0, '2' => 0];
try { foreach ($db->select("SELECT status, COUNT(*) n FROM bank_accounts GROUP BY status") as $r) { $bc[(string)(int)$r['status']] = (int)$r['n']; } } catch (\Throwable $e) {}
$wc = ['pending' => 0, 'processing' => 0, 'approved' => 0, 'rejected' => 0];
$wsum = ['pending' => 0.0, 'approved' => 0.0];
try {
    foreach ($db->select("SELECT status, COUNT(*) n, COALESCE(SUM(amount),0) t FROM withdrawal_requests GROUP BY status") as $r) {
        $wc[$r['status']] = (int)$r['n'];
        if (isset($wsum[$r['status']])) $wsum[$r['status']] = (float)$r['t'];
    }
} catch (\Throwable $e) {}

$settings = bank_settings($db);

$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;
$company_logo = getSetting('company_logo', '../assets/images/logo.png');
$company_name = getSetting('company_name', 'WBMCZ');
$profile_image_url = !empty($user['profile_pic']) ? '../uploads/profiles/' . $user['profile_pic'] : null;

$init_tab = 'bank_requests';
?>
<!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>Withdrawals - Admin Panel</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=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style> body { font-family: 'Inter', sans-serif; } .hide-scrollbar::-webkit-scrollbar { display: none; } </style>
</head>
<body class="bg-gray-50" x-data="{ sidebarOpen: window.innerWidth >= 768, profileOpen: false, tab: (window.location.hash ? window.location.hash.substring(1) : 'bank_requests') }">

    <div class="flex h-screen overflow-hidden">
        
        <?php include __DIR__ . '/includes/sidebar.php'; ?>
        <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">
            
            <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 lg:px-8 shadow-sm border-b border-gray-200 z-40 relative">
                <div class="flex items-center">
                    <button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-emerald-600 focus:outline-none rounded-lg hover:bg-gray-100 transition-colors">
                        <i class="fas fa-bars text-xl"></i>
                    </button>
                    <h2 class="text-xl font-bold hidden md:block text-slate-800">Withdrawals</h2>
                </div>

                <div class="flex items-center space-x-3 sm:space-x-5 ml-auto">
                    <div class="relative">
                        <button @click="profileOpen = !profileOpen" @click.away="profileOpen = false" class="flex items-center focus:outline-none">
                            <?php if(!empty($profile_image_url) && file_exists($profile_image_url)): ?>
                                <img src="<?php echo $profile_image_url; ?>" class="w-10 h-10 rounded-full border-2 border-emerald-100 shadow-sm object-cover">
                            <?php else: ?>
                                <div class="w-10 h-10 rounded-full bg-emerald-100 border-2 border-emerald-200 text-emerald-600 flex items-center justify-center text-lg font-bold shadow-sm">
                                    <?php echo strtoupper(substr($user['name'], 0, 1)); ?>
                                </div>
                            <?php endif; ?>
                            <i class="fas fa-chevron-down text-xs ml-2 text-slate-400 hidden sm:block"></i>
                        </button>
                        
                        <div x-show="profileOpen" x-transition class="absolute right-0 mt-3 w-56 bg-white rounded-xl shadow-2xl py-2 border border-gray-100 z-50" style="display: none;">
                            <div class="px-4 py-3 border-b border-gray-100">
                                <p class="text-sm text-gray-500">Signed in as Admin</p>
                                <p class="text-sm font-bold text-gray-900 truncate"><?php echo htmlspecialchars($user['name'], ENT_QUOTES, 'UTF-8', false); ?></p>
                            </div>
                            <a href="profile.php" class="block px-4 py-2 text-sm text-gray-700 hover:bg-emerald-50 hover:text-emerald-600 transition-colors"><i class="fas fa-user mr-2 w-4"></i> My Profile</a>
                            <div class="border-t border-gray-100 mt-2 pt-2">
                                <a href="../logout.php" onclick="return confirm('Are you sure you want to logout?');" class="block px-4 py-2 text-sm text-rose-600 hover:bg-rose-50 transition-colors"><i class="fas fa-sign-out-alt mr-2 w-4"></i> Logout</a>
                            </div>
                        </div>
                    </div>
                </div>
            </header>

            <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8"
                  @hashchange.window="tab = window.location.hash.substring(1) || 'bank_requests'"
                  x-data="wdPage()">

                <?php if ($success_msg): ?>
                <div class="mb-5 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
                    <i class="fas fa-check-circle text-xl mr-3"></i><span class="font-medium"><?php echo $success_msg; ?></span>
                </div>
                <?php endif; ?>
                <?php if ($error_msg): ?>
                <div class="mb-5 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
                    <i class="fas fa-exclamation-circle text-xl mr-3"></i><span class="font-medium"><?php echo $error_msg; ?></span>
                </div>
                <?php endif; ?>

                <div class="mb-5">
                    <h2 class="text-xl sm:text-2xl font-bold text-slate-800 mb-1">Withdrawal Management</h2>
                    <p class="text-gray-500 text-xs sm:text-sm">Verify bank accounts, then approve or reject the money transfers.</p>
                </div>

                <!-- ===== SUMMARY ===== -->
                <div class="grid grid-cols-2 lg:grid-cols-4 gap-2.5 mb-5">
                    <div class="wd-card"><p class="wd-k">Bank Requests</p><p class="text-xl font-black text-amber-600"><?php echo $bc['0']; ?></p><p class="wd-sub">Awaiting verification</p></div>
                    <div class="wd-card"><p class="wd-k">Verified Banks</p><p class="text-xl font-black text-emerald-600"><?php echo $bc['1']; ?></p><p class="wd-sub">Can withdraw</p></div>
                    <div class="wd-card"><p class="wd-k">Pending Payouts</p><p class="text-xl font-black text-blue-600">₹<?php echo number_format($wsum['pending'], 2); ?></p><p class="wd-sub"><?php echo $wc['pending'] + $wc['processing']; ?> request(s)</p></div>
                    <div class="wd-card"><p class="wd-k">Total Paid</p><p class="text-xl font-black text-slate-800">₹<?php echo number_format($wsum['approved'], 2); ?></p><p class="wd-sub"><?php echo $wc['approved']; ?> completed</p></div>
                </div>

                <!-- ===== TABS ===== -->
                <div class="flex gap-1 mb-5 border-b border-gray-200 overflow-x-auto hide-scrollbar">
                    <a href="withdrawals.php#bank_requests" @click="tab='bank_requests'" :class="tab==='bank_requests' ? 'border-emerald-600 text-emerald-700' : 'border-transparent text-slate-500'" class="px-4 py-3 text-xs sm:text-sm font-bold border-b-2 whitespace-nowrap transition-colors">
                        <i class="fas fa-building-columns mr-1.5"></i>Bank Request Pending
                        <?php if ($bc['0'] > 0): ?><span class="ml-1 px-1.5 py-0.5 rounded-full text-[10px] bg-amber-100 text-amber-700"><?php echo $bc['0']; ?></span><?php endif; ?>
                    </a>
                    <a href="withdrawals.php#transactions" @click="tab='transactions'" :class="tab==='transactions' ? 'border-emerald-600 text-emerald-700' : 'border-transparent text-slate-500'" class="px-4 py-3 text-xs sm:text-sm font-bold border-b-2 whitespace-nowrap transition-colors">
                        <i class="fas fa-money-bill-transfer mr-1.5"></i>Transaction Update
                        <?php if ($wc['pending'] > 0): ?><span class="ml-1 px-1.5 py-0.5 rounded-full text-[10px] bg-blue-100 text-blue-700"><?php echo $wc['pending']; ?></span><?php endif; ?>
                    </a>
                    <a href="withdrawals.php#settings" @click="tab='settings'" :class="tab==='settings' ? 'border-emerald-600 text-emerald-700' : 'border-transparent text-slate-500'" class="px-4 py-3 text-xs sm:text-sm font-bold border-b-2 whitespace-nowrap transition-colors">
                        <i class="fas fa-sliders mr-1.5"></i>Settings
                    </a>
                </div>

                <!-- ================= TAB 1: BANK REQUESTS ================= -->
                <div x-show="tab==='bank_requests'" x-cloak>
                    <form method="GET" class="wd-panel p-3 mb-4 flex flex-wrap gap-2 items-center">
                        <input type="hidden" name="tab" value="bank_requests">
                        <div class="relative flex-1 min-w-[180px]">
                            <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
                            <input name="q" value="<?php echo htmlspecialchars($q); ?>" placeholder="Name, mobile, account or bank" class="wd-f pl-9">
                        </div>
                        <select name="bs" class="wd-f w-auto">
                            <option value="0" <?php echo $bs===0?'selected':''; ?>>Pending (<?php echo $bc['0']; ?>)</option>
                            <option value="1" <?php echo $bs===1?'selected':''; ?>>Verified (<?php echo $bc['1']; ?>)</option>
                            <option value="2" <?php echo $bs===2?'selected':''; ?>>Rejected (<?php echo $bc['2']; ?>)</option>
                        </select>
                        <button class="wd-btn wd-btn-dark">Filter</button>
                        <a href="withdrawals.php#bank_requests" class="wd-btn wd-btn-ghost">Reset</a>
                    </form>

                    <?php if (empty($bank_rows)): ?>
                        <div class="wd-panel p-14 text-center text-slate-400">
                            <i class="fas fa-building-columns text-3xl mb-3 block text-slate-300"></i>
                            <p class="text-base font-bold text-slate-600">No bank requests here</p>
                            <p class="text-xs mt-1">Nothing is waiting for your verification.</p>
                        </div>
                    <?php else: ?>
                        <div class="space-y-3">
                        <?php foreach ($bank_rows as $b): $m = bank_account_status_meta($b['status']); ?>
                            <div class="wd-panel p-4">
                                <div class="flex flex-col lg:flex-row lg:items-center gap-4">
                                    <div class="flex items-start gap-3 flex-1 min-w-0">
                                        <div class="w-11 h-11 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">
                                            <div class="flex flex-wrap items-center gap-2 mb-0.5">
                                                <p class="font-extrabold text-slate-800 text-sm truncate"><?php echo htmlspecialchars($b['user_name'] ?: '—'); ?></p>
                                                <span class="wd-badge wd-badge-<?php echo $m[1]; ?>"><?php echo $m[0]; ?></span>
                                                <span class="wd-badge wd-badge-slate uppercase"><?php echo htmlspecialchars($b['user_type']); ?></span>
                                            </div>
                                            <p class="text-[11px] text-slate-500"><?php echo htmlspecialchars($b['user_mobile']); ?> · ID <?php echo (int)$b['user_id']; ?></p>
                                            <p class="text-[11px] text-slate-600 mt-1">
                                                <b><?php echo htmlspecialchars($b['bank_name']); ?></b> ·
                                                <span class="font-mono"><?php echo htmlspecialchars(bank_mask_account($b['account_number'])); ?></span> ·
                                                <span class="font-mono"><?php echo htmlspecialchars($b['ifsc_code']); ?></span>
                                            </p>
                                        </div>
                                    </div>
                                    <div class="flex flex-wrap gap-2 flex-shrink-0">
                                        <button type="button" @click="openBank(<?php echo (int)$b['id']; ?>)" class="wd-btn wd-btn-ghost"><i class="fas fa-eye"></i> Details</button>
                                        <?php if ((int)$b['status'] !== BANK_APPROVED): ?>
                                        <form method="POST" class="inline" onsubmit="return confirm('Verify this bank account? The user will be able to withdraw.');">
                                            <input type="hidden" name="bank_id" value="<?php echo (int)$b['id']; ?>">
                                            <button type="submit" name="review_bank" value="approve" class="wd-btn wd-btn-green"><i class="fas fa-check"></i> Approve</button>
                                        </form>
                                        <?php endif; ?>
                                        <?php if ((int)$b['status'] !== BANK_REJECTED): ?>
                                        <button type="button" @click="openReject(<?php echo (int)$b['id']; ?>, '<?php echo htmlspecialchars(addslashes($b['user_name']), ENT_QUOTES); ?>')" class="wd-btn wd-btn-red"><i class="fas fa-xmark"></i> Reject</button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php if (!empty($b['admin_remark'])): ?>
                                    <div class="mt-3 bg-rose-50 border border-rose-200 rounded-xl px-3 py-2 text-[11px] text-rose-700">
                                        <b>Remark:</b> <?php echo htmlspecialchars($b['admin_remark']); ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- ================= TAB 2: TRANSACTION UPDATE ================= -->
                <div x-show="tab==='transactions'" x-cloak>
                    <form method="GET" class="wd-panel p-3 mb-4 flex flex-wrap gap-2 items-center">
                        <input type="hidden" name="tab" value="transactions">
                        <div class="relative flex-1 min-w-[180px]">
                            <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
                            <input name="q" value="<?php echo htmlspecialchars($q); ?>" placeholder="Name, mobile, reference or account" class="wd-f pl-9">
                        </div>
                        <select name="ws" class="wd-f w-auto">
                            <option value="pending"    <?php echo $ws==='pending'?'selected':''; ?>>Pending (<?php echo $wc['pending']; ?>)</option>
                            <option value="processing" <?php echo $ws==='processing'?'selected':''; ?>>Processing (<?php echo $wc['processing']; ?>)</option>
                            <option value="approved"   <?php echo $ws==='approved'?'selected':''; ?>>Approved (<?php echo $wc['approved']; ?>)</option>
                            <option value="rejected"   <?php echo $ws==='rejected'?'selected':''; ?>>Rejected (<?php echo $wc['rejected']; ?>)</option>
                        </select>
                        <button class="wd-btn wd-btn-dark">Filter</button>
                        <a href="withdrawals.php#transactions" class="wd-btn wd-btn-ghost">Reset</a>
                    </form>

                    <?php if (empty($wd_rows)): ?>
                        <div class="wd-panel p-14 text-center text-slate-400">
                            <i class="fas fa-money-bill-transfer text-3xl mb-3 block text-slate-300"></i>
                            <p class="text-base font-bold text-slate-600">No <?php echo htmlspecialchars($ws); ?> withdrawals</p>
                        </div>
                    <?php else: ?>
                        <div class="space-y-3">
                        <?php foreach ($wd_rows as $w): $sm = bank_status_meta($w['status']); ?>
                            <div class="wd-panel p-4">
                                <div class="flex flex-col lg:flex-row lg:items-center gap-4">
                                    <div class="flex-1 min-w-0">
                                        <div class="flex flex-wrap items-center gap-2 mb-1">
                                            <span class="font-mono text-[10px] font-bold text-slate-400"><?php echo htmlspecialchars($w['reference_no']); ?></span>
                                            <span class="wd-badge wd-badge-<?php echo $sm[1]; ?>"><?php echo $sm[0]; ?></span>
                                        </div>
                                        <p class="font-extrabold text-slate-800 text-sm truncate"><?php echo htmlspecialchars($w['user_name'] ?: '—'); ?>
                                            <span class="font-normal text-[11px] text-slate-400">· <?php echo htmlspecialchars($w['user_mobile']); ?></span></p>
                                        <p class="text-[11px] text-slate-600 mt-1">
                                            <b><?php echo htmlspecialchars($w['bank_name']); ?></b> ·
                                            <span class="font-mono"><?php echo htmlspecialchars(bank_mask_account($w['account_number'])); ?></span> ·
                                            <span class="font-mono"><?php echo htmlspecialchars($w['ifsc_code']); ?></span>
                                        </p>
                                        <p class="text-[10px] text-slate-400 mt-0.5"><i class="fas fa-clock mr-1"></i><?php echo date('d M Y, h:i A', strtotime($w['created_at'])); ?>
                                            <?php if (!empty($w['utr_number'])): ?> · <span class="text-emerald-600 font-bold">UTR <?php echo htmlspecialchars($w['utr_number']); ?></span><?php endif; ?></p>
                                    </div>

                                    <div class="text-left lg:text-right flex-shrink-0">
                                        <p class="text-xl font-black text-slate-900">₹<?php echo number_format((float)$w['net_amount'], 2); ?></p>
                                        <p class="text-[10px] text-slate-400">
                                            Requested ₹<?php echo number_format((float)$w['amount'], 2); ?>
                                            <?php if ((float)$w['charge'] > 0): ?> · fee ₹<?php echo number_format((float)$w['charge'], 2); ?><?php endif; ?>
                                        </p>
                                    </div>

                                    <div class="flex flex-wrap gap-2 flex-shrink-0">
                                        <button type="button" @click="openWd(<?php echo (int)$w['id']; ?>)" class="wd-btn wd-btn-ghost"><i class="fas fa-eye"></i> Details</button>
                                        <?php if (in_array($w['status'], ['pending','processing'], true)): ?>
                                            <button type="button" @click="openApprove(<?php echo (int)$w['id']; ?>, '<?php echo htmlspecialchars(addslashes($w['reference_no']), ENT_QUOTES); ?>', <?php echo (float)$w['net_amount']; ?>)" class="wd-btn wd-btn-green"><i class="fas fa-check"></i> Update</button>
                                            <button type="button" @click="openWdReject(<?php echo (int)$w['id']; ?>, '<?php echo htmlspecialchars(addslashes($w['reference_no']), ENT_QUOTES); ?>', <?php echo (float)$w['amount']; ?>)" class="wd-btn wd-btn-red"><i class="fas fa-xmark"></i> Reject</button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php if (!empty($w['admin_remark'])): ?>
                                    <div class="mt-3 bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-[11px] text-slate-600">
                                        <b>Remark:</b> <?php echo htmlspecialchars($w['admin_remark']); ?>
                                        <?php if (!empty($w['reviewed_by_name'])): ?> <span class="text-slate-400">— <?php echo htmlspecialchars($w['reviewed_by_name']); ?></span><?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- ================= TAB 3: SETTINGS ================= -->
                <div x-show="tab==='settings'" x-cloak>
                    <form method="POST" class="wd-panel p-5 max-w-2xl">
                        <p class="text-sm font-bold text-slate-800 mb-4"><i class="fas fa-sliders mr-2 text-emerald-600"></i>Withdrawal Settings</p>

                        <div class="space-y-4">
                            <label class="flex items-center justify-between gap-4 p-3 rounded-xl border border-slate-200 cursor-pointer">
                                <div>
                                    <p class="text-xs font-bold text-slate-700">Enable withdrawals</p>
                                    <p class="text-[11px] text-slate-400">Turn off to temporarily stop all new requests.</p>
                                </div>
                                <select name="withdraw_enabled" class="wd-f w-auto">
                                    <option value="1" <?php echo $settings['withdraw_enabled']==='1'?'selected':''; ?>>Enabled</option>
                                    <option value="0" <?php echo $settings['withdraw_enabled']==='0'?'selected':''; ?>>Disabled</option>
                                </select>
                            </label>

                            <div class="grid sm:grid-cols-2 gap-3">
                                <div>
                                    <label class="wd-l">Minimum amount (₹)</label>
                                    <input type="number" step="1" min="1" name="withdraw_min" value="<?php echo htmlspecialchars($settings['withdraw_min']); ?>" class="wd-f">
                                </div>
                                <div>
                                    <label class="wd-l">Maximum per request (₹)</label>
                                    <input type="number" step="1" min="0" name="withdraw_max" value="<?php echo htmlspecialchars($settings['withdraw_max']); ?>" class="wd-f">
                                    <p class="text-[10px] text-slate-400 mt-1">0 = no limit</p>
                                </div>
                            </div>

                            <div class="grid sm:grid-cols-2 gap-3">
                                <div>
                                    <label class="wd-l">Service charge type</label>
                                    <select name="withdraw_charge_type" class="wd-f">
                                        <option value="none"    <?php echo $settings['withdraw_charge_type']==='none'?'selected':''; ?>>No charge</option>
                                        <option value="percent" <?php echo $settings['withdraw_charge_type']==='percent'?'selected':''; ?>>Percentage of amount</option>
                                        <option value="fixed"   <?php echo $settings['withdraw_charge_type']==='fixed'?'selected':''; ?>>Fixed amount</option>
                                    </select>
                                </div>
                                <div>
                                    <label class="wd-l">Charge value</label>
                                    <input type="number" step="0.01" min="0" name="withdraw_charge_value" value="<?php echo htmlspecialchars($settings['withdraw_charge_value']); ?>" class="wd-f">
                                    <p class="text-[10px] text-slate-400 mt-1">Percent → e.g. 2 means 2%. Fixed → e.g. 10 means ₹10.</p>
                                </div>
                            </div>

                            <div>
                                <label class="wd-l">Note shown to users</label>
                                <input name="withdraw_note" value="<?php echo htmlspecialchars($settings['withdraw_note']); ?>" class="wd-f">
                            </div>

                            <div class="bg-slate-50 border border-slate-200 rounded-xl p-3 text-[11px] text-slate-600">
                                <b>Current rule:</b> minimum ₹<?php echo number_format((float)$settings['withdraw_min'], 2); ?>,
                                <?php echo (float)$settings['withdraw_max'] > 0 ? 'maximum ₹' . number_format((float)$settings['withdraw_max'], 2) : 'no maximum'; ?>,
                                charge <?php echo bank_charge_label($settings); ?>.
                                <br>Example: on a ₹1,000 withdrawal the user receives
                                <b>₹<?php echo number_format(1000 - bank_charge_for($settings, 1000), 2); ?></b>.
                            </div>
                        </div>

                        <button type="submit" name="save_settings" class="wd-btn wd-btn-green mt-5 w-full sm:w-auto px-8 py-3"><i class="fas fa-save"></i> Save Settings</button>
                    </form>
                </div>

                <!-- ================= MODALS ================= -->
                <div x-show="modal" 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="close()"></div>

                    <!-- detail -->
                    <div x-show="modal==='detail'" 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);">
                            <h3 class="text-white font-bold text-base"><i class="fas fa-circle-info mr-2"></i><span x-text="detailTitle"></span></h3>
                            <button @click="close()" class="text-white/70 hover:text-white text-3xl leading-none">&times;</button>
                        </div>
                        <div class="p-5 overflow-y-auto">
                            <template x-if="loading"><p class="text-center text-slate-400 py-8"><i class="fas fa-spinner fa-spin mr-2"></i>Loading…</p></template>
                            <div x-show="!loading" class="space-y-1.5">
                                <template x-for="row in detailRows" :key="row[0]">
                                    <div class="flex justify-between gap-4 py-2 border-b border-slate-100 text-xs">
                                        <span class="text-slate-400 font-bold uppercase text-[10px] tracking-wide flex-shrink-0" x-text="row[0]"></span>
                                        <span class="font-bold text-slate-800 text-right break-all" x-text="row[1]"></span>
                                    </div>
                                </template>
                                <template x-if="d.passbook">
                                    <a :href="'../' + d.passbook" target="_blank" class="wd-btn wd-btn-ghost w-full mt-3"><i class="fas fa-file-lines"></i> View passbook / cheque</a>
                                </template>
                            </div>
                        </div>
                    </div>

                    <!-- bank reject -->
                    <div x-show="modal==='bankReject'" class="relative w-full sm:max-w-md bg-white rounded-t-3xl sm:rounded-2xl shadow-2xl overflow-hidden">
                        <div class="px-5 py-4 flex items-center gap-3" style="background:linear-gradient(135deg,#e11d48,#be123c);">
                            <i class="fas fa-triangle-exclamation text-white text-lg"></i>
                            <div class="min-w-0"><h3 class="text-white font-bold text-base">Reject Bank Account</h3>
                            <p class="text-white/70 text-[11px] truncate" x-text="curName"></p></div>
                        </div>
                        <form method="POST" class="p-5 space-y-3">
                            <input type="hidden" name="bank_id" :value="curId">
                            <p class="text-xs text-slate-500">The user will see your reason and can correct their details and resubmit.</p>
                            <div><label class="wd-l">Reason <span class="text-rose-500">*</span></label>
                                <textarea name="bank_remark" rows="3" required x-model="reason" placeholder="e.g. The name on the account does not match your KYC." class="wd-f resize-y"></textarea></div>
                            <div class="flex flex-wrap gap-1.5">
                                <template x-for="r in bankReasons" :key="r">
                                    <button type="button" @click="reason = reason ? reason + ' ' + r : r" class="wd-quick" x-text="r"></button>
                                </template>
                            </div>
                            <div class="flex gap-2 pt-1">
                                <button type="button" @click="close()" class="wd-btn wd-btn-ghost flex-1">Cancel</button>
                                <button type="submit" name="review_bank" value="reject" class="wd-btn wd-btn-red flex-1" :disabled="!reason.trim()">Reject</button>
                            </div>
                        </form>
                    </div>

                    <!-- withdrawal approve -->
                    <div x-show="modal==='wdApprove'" class="relative w-full sm:max-w-md bg-white rounded-t-3xl sm:rounded-2xl shadow-2xl overflow-hidden">
                        <div class="px-5 py-4 flex items-center gap-3" style="background:linear-gradient(135deg,#059669,#047857);">
                            <i class="fas fa-circle-check text-white text-lg"></i>
                            <div class="min-w-0"><h3 class="text-white font-bold text-base">Mark as Sent</h3>
                            <p class="text-white/70 text-[11px] font-mono truncate" x-text="curName"></p></div>
                        </div>
                        <form method="POST" class="p-5 space-y-3">
                            <input type="hidden" name="wd_id" :value="curId">
                            <div class="bg-emerald-50 border border-emerald-200 rounded-xl p-3 text-center">
                                <p class="text-[10px] font-bold uppercase tracking-wider text-emerald-500">Amount to transfer</p>
                                <p class="text-2xl font-black text-emerald-700">₹<span x-text="curAmt.toFixed(2)"></span></p>
                            </div>
                            <p class="text-xs text-slate-500">Transfer the money from your bank first, then enter the UTR / reference number here. The user is notified as <b>Approved &amp; Sent Successfully</b>.</p>
                            <div><label class="wd-l">UTR / Reference No. <span class="text-rose-500">*</span></label>
                                <input name="utr_number" required x-model="utr" placeholder="e.g. N123456789012345" class="wd-f font-mono"></div>
                            <div><label class="wd-l">Note <span class="text-slate-400 font-normal normal-case">(optional)</span></label>
                                <input name="wd_remark" placeholder="Anything the user should know" class="wd-f"></div>
                            <div class="flex gap-2 pt-1">
                                <button type="button" @click="close()" class="wd-btn wd-btn-ghost flex-1">Cancel</button>
                                <button type="submit" name="review_wd" value="processing" class="wd-btn wd-btn-blue">Processing</button>
                                <button type="submit" name="review_wd" value="approve" class="wd-btn wd-btn-green flex-1" :disabled="!utr.trim()">Mark Sent</button>
                            </div>
                        </form>
                    </div>

                    <!-- withdrawal reject -->
                    <div x-show="modal==='wdReject'" class="relative w-full sm:max-w-md bg-white rounded-t-3xl sm:rounded-2xl shadow-2xl overflow-hidden">
                        <div class="px-5 py-4 flex items-center gap-3" style="background:linear-gradient(135deg,#e11d48,#be123c);">
                            <i class="fas fa-rotate-left text-white text-lg"></i>
                            <div class="min-w-0"><h3 class="text-white font-bold text-base">Reject &amp; Refund</h3>
                            <p class="text-white/70 text-[11px] font-mono truncate" x-text="curName"></p></div>
                        </div>
                        <form method="POST" class="p-5 space-y-3">
                            <input type="hidden" name="wd_id" :value="curId">
                            <div class="bg-rose-50 border border-rose-200 rounded-xl p-3 text-center">
                                <p class="text-[10px] font-bold uppercase tracking-wider text-rose-500">Will be refunded to the wallet</p>
                                <p class="text-2xl font-black text-rose-700">₹<span x-text="curAmt.toFixed(2)"></span></p>
                            </div>
                            <div><label class="wd-l">Reason <span class="text-rose-500">*</span></label>
                                <textarea name="wd_remark" rows="3" required x-model="reason" placeholder="e.g. Bank details could not be verified." class="wd-f resize-y"></textarea></div>
                            <div class="flex flex-wrap gap-1.5">
                                <template x-for="r in wdReasons" :key="r">
                                    <button type="button" @click="reason = reason ? reason + ' ' + r : r" class="wd-quick" x-text="r"></button>
                                </template>
                            </div>
                            <div class="flex gap-2 pt-1">
                                <button type="button" @click="close()" class="wd-btn wd-btn-ghost flex-1">Cancel</button>
                                <button type="submit" name="review_wd" value="reject" class="wd-btn wd-btn-red flex-1" :disabled="!reason.trim()">Reject &amp; Refund</button>
                            </div>
                        </form>
                    </div>
                </div>

                <style>
                    [x-cloak] { display:none !important; }
                    .wd-panel { background:#fff; border:1px solid #e2e8f0; border-radius:1rem; box-shadow:0 1px 3px rgba(15,23,42,.05); }
                    .wd-card  { background:#fff; border:1px solid #e2e8f0; border-radius:1rem; padding:.85rem 1rem; }
                    .wd-k     { font-size:9px; font-weight:800; text-transform:uppercase; letter-spacing:.08em; color:#94a3b8; margin-bottom:.15rem; }
                    .wd-sub   { font-size:9.5px; color:#cbd5e1; margin-top:.15rem; font-weight:600; }
                    .wd-l     { display:block; font-size:10px; font-weight:800; color:#475569; margin-bottom:.3rem; text-transform:uppercase; letter-spacing:.05em; }
                    .wd-f     { width:100%; padding:.65rem .8rem; background:#fff; border:1.5px solid #cbd5e1; border-radius:.75rem; font-size:.78rem; outline:none; }
                    .wd-f:focus { border-color:#10b981; box-shadow:0 0 0 3px rgba(16,185,129,.15); }
                    .wd-btn { display:inline-flex; align-items:center; justify-content:center; gap:.4rem; padding:.6rem 1rem;
                              border-radius:.7rem; font-weight:800; font-size:.72rem; border:0; cursor:pointer; transition:.15s; white-space:nowrap; }
                    .wd-btn:disabled { opacity:.4; cursor:not-allowed; }
                    .wd-btn-green { background:#059669; color:#fff; } .wd-btn-green:not(:disabled):hover { background:#047857; }
                    .wd-btn-red   { background:#e11d48; color:#fff; } .wd-btn-red:not(:disabled):hover { background:#be123c; }
                    .wd-btn-blue  { background:#2563eb; color:#fff; }
                    .wd-btn-dark  { background:#0f172a; color:#fff; }
                    .wd-btn-ghost { background:#f1f5f9; color:#475569; }
                    .wd-badge { display:inline-block; font-size:9px; font-weight:900; padding:.22rem .5rem; border-radius:.4rem; white-space:nowrap; }
                    .wd-badge-emerald { background:#d1fae5; color:#047857; }
                    .wd-badge-amber   { background:#fef3c7; color:#b45309; }
                    .wd-badge-rose    { background:#ffe4e6; color:#be123c; }
                    .wd-badge-blue    { background:#dbeafe; color:#1d4ed8; }
                    .wd-badge-slate   { background:#f1f5f9; color:#475569; }
                    .wd-quick { padding:.3rem .6rem; border-radius:.5rem; background:#f1f5f9; color:#475569; font-size:10.5px; font-weight:700; border:0; cursor:pointer; text-align:left; }
                    .wd-quick:hover { background:#e2e8f0; }
                </style>

                <script>
                function wdPage() {
                    return {
                        modal: null, loading: false, curId: null, curName: '', curAmt: 0,
                        reason: '', utr: '', d: {}, detailRows: [], detailTitle: '',
                        bankReasons: ['Name does not match KYC.','Account number is wrong.','IFSC code is invalid.','Passbook image is unclear.','Please upload a cancelled cheque.'],
                        wdReasons: ['Bank details could not be verified.','Suspicious activity on the account.','Duplicate request.','Please contact support.'],
                        close() { this.modal = null; this.reason = ''; this.utr = ''; },
                        openReject(id, name)  { this.curId = id; this.curName = name; this.reason = ''; this.modal = 'bankReject'; },
                        openApprove(id, ref, amt) { this.curId = id; this.curName = ref; this.curAmt = amt; this.utr = ''; this.modal = 'wdApprove'; },
                        openWdReject(id, ref, amt) { this.curId = id; this.curName = ref; this.curAmt = amt; this.reason = ''; this.modal = 'wdReject'; },
                        money(v) { return '₹' + (Number(v) || 0).toFixed(2); },
                        openBank(id) {
                            this.detailTitle = 'Bank Account'; this.modal = 'detail'; this.loading = true; this.d = {}; this.detailRows = [];
                            fetch('withdrawals.php?ajax=bank&id=' + id).then(r => r.json()).then(d => {
                                this.d = d || {};
                                this.detailRows = [
                                    ['User', (d.user_name || '') + ' (ID ' + d.user_id + ')'],
                                    ['Mobile', d.user_mobile || '—'], ['Email', d.user_email || '—'],
                                    ['Holder Name', d.holder_name], ['Bank', d.bank_name], ['Branch', d.branch_name],
                                    ['Account No.', d.account_number], ['IFSC', d.ifsc_code],
                                    ['Type', d.account_type], ['Bank Mobile', d.mobile || '—'], ['UPI', d.upi_id || '—'],
                                    ['KYC Status', d.kyc_status || 'not submitted'],
                                    ['KYC Name', d.kyc_name || '—'],
                                    ['KYC Account', d.kyc_account || '—'],
                                    ['Match with KYC', (d.kyc_account && d.kyc_account === d.account_number) ? 'YES — matches' : 'Check manually'],
                                    ['Main Wallet', this.money(d.wallet_balance)],
                                    ['Virtual Wallet', this.money(d.bonus_wallet)],
                                    ['Submitted', d.created_at],
                                ];
                            }).catch(() => {}).finally(() => { this.loading = false; });
                        },
                        openWd(id) {
                            this.detailTitle = 'Withdrawal Request'; this.modal = 'detail'; this.loading = true; this.d = {}; this.detailRows = [];
                            fetch('withdrawals.php?ajax=wd&id=' + id).then(r => r.json()).then(d => {
                                this.d = d || {};
                                this.detailRows = [
                                    ['Reference', d.reference_no], ['Status', d.status],
                                    ['User', (d.user_name || '') + ' (ID ' + d.user_id + ')'],
                                    ['Mobile', d.user_mobile || '—'], ['Email', d.user_email || '—'],
                                    ['Requested', this.money(d.amount)], ['Charge', this.money(d.charge)],
                                    ['Payable', this.money(d.net_amount)],
                                    ['Holder Name', d.holder_name], ['Bank', d.bank_name], ['Branch', d.branch_name || '—'],
                                    ['Account No.', d.account_number], ['IFSC', d.ifsc_code],
                                    ['Type', d.account_type || '—'], ['UPI', d.upi_id || '—'],
                                    ['Wallet Now', this.money(d.wallet_balance)],
                                    ['Requested On', d.created_at],
                                    ['UTR', d.utr_number || '—'],
                                    ['Reviewed By', d.reviewed_by_name || '—'],
                                ];
                            }).catch(() => {}).finally(() => { this.loading = false; });
                        }
                    }
                }
                </script>
            </main>
        </div>
    </div>
</body>
</html>
