<?php
/* ============================================================================
   Admin → Wallet Management → Wallet History
   Per-user, in-detail wallet history across BOTH wallets (main + virtual).
   ============================================================================ */
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/wallet.php';

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

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

wallet_ensure_schema($db);

// UI permission map for the sidebar
$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']); }

/* ---- One-time backfill of old `transactions` rows into the ledger ---- */
if (isset($_POST['run_backfill'])) {
    $n = wallet_backfill_from_transactions($db);
    $_SESSION['flash_success'] = $n > 0
        ? "Imported $n old transaction(s) into the wallet ledger."
        : "Nothing to import — the ledger already has data.";
    redirect('wallet_history.php');
}

/* ---- Admin adjustment (add / deduct on either wallet) ---- */
if (isset($_POST['adjust_wallet'])) {
    $target = intval($_POST['target_user_id']);
    $wallet = ($_POST['adj_wallet'] ?? 'main') === 'virtual' ? WALLET_VIRTUAL : WALLET_MAIN;
    $dir    = ($_POST['adj_direction'] ?? 'credit') === 'debit' ? 'debit' : 'credit';
    $amt    = round((float)($_POST['adj_amount'] ?? 0), 2);
    $note   = sanitize($_POST['adj_note'] ?? '');

    if ($target <= 0 || $amt <= 0) {
        $_SESSION['flash_error'] = "Pick a user and enter an amount greater than zero.";
    } else {
        $desc = 'Admin adjustment' . ($note !== '' ? ' — ' . $note : '');
        if ($dir === 'credit') {
            wallet_credit($db, $target, $wallet, $amt, ['category' => 'admin', 'description' => $desc, 'created_by' => $user_id]);
            $_SESSION['flash_success'] = "Added ₹" . number_format($amt, 2) . " to the " . ($wallet === WALLET_VIRTUAL ? 'virtual' : 'main') . " wallet.";
        } else {
            $col = ($wallet === WALLET_VIRTUAL) ? 'bonus_wallet' : 'wallet_balance';
            $bal = wallet_balances($db, $target);
            $have = ($wallet === WALLET_VIRTUAL) ? $bal['virtual'] : $bal['main'];
            if ($have + 0.001 < $amt) {
                $_SESSION['flash_error'] = "That wallet only holds ₹" . number_format($have, 2) . ".";
            } else {
                $db->insert("UPDATE users SET `$col` = `$col` - ? WHERE id = ?", [$amt, $target]); // whitelisted
                $nb = wallet_balances($db, $target);
                wallet__ledger($db, $target, $wallet, 'debit', $amt,
                    ($wallet === WALLET_VIRTUAL) ? $nb['virtual'] : $nb['main'],
                    ['category' => 'admin', 'description' => $desc, 'created_by' => $user_id]);
                wallet__legacy($db, $target, 'debit', $amt, $desc);
                $_SESSION['flash_success'] = "Deducted ₹" . number_format($amt, 2) . ".";
            }
        }
    }
    redirect('wallet_history.php?uid=' . $target);
}

/* ---- Filters ---- */
$sel_uid   = isset($_GET['uid']) ? intval($_GET['uid']) : 0;
$f_search  = trim($_GET['q'] ?? '');
$f_wallet  = in_array(($_GET['w'] ?? ''), ['main','virtual'], true) ? $_GET['w'] : '';
$f_dir     = in_array(($_GET['d'] ?? ''), ['credit','debit'], true) ? $_GET['d'] : '';
$f_cat     = trim($_GET['c'] ?? '');
$f_from    = preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['from'] ?? '') ? $_GET['from'] : '';
$f_to      = preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['to'] ?? '') ? $_GET['to'] : '';
$f_type    = in_array(($_GET['t'] ?? ''), ['customer','seller','admin'], true) ? $_GET['t'] : '';

/* ---- CSV export of the selected user's history ---- */
if (isset($_GET['export']) && $sel_uid > 0) {
    $rows = wallet_history($db, $sel_uid, ['wallet'=>$f_wallet,'direction'=>$f_dir,'category'=>$f_cat,'from'=>$f_from,'to'=>$f_to,'limit'=>5000]);
    $u = $db->select("SELECT name FROM users WHERE id = ?", [$sel_uid]);
    $nm = !empty($u) ? preg_replace('/[^A-Za-z0-9]+/', '_', $u[0]['name']) : 'user';
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="wallet_history_' . $nm . '_' . date('Ymd_His') . '.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Date', 'Wallet', 'Direction', 'Amount', 'Balance After', 'Category', 'Description', 'Reference']);
    foreach ($rows as $r) {
        fputcsv($out, [
            $r['created_at'],
            $r['wallet'] === 'virtual' ? 'Virtual' : 'Main',
            ucfirst($r['direction']),
            number_format((float)$r['amount'], 2, '.', ''),
            number_format((float)$r['balance_after'], 2, '.', ''),
            wallet_cat_label($r['category']),
            $r['description'],
            trim(($r['reference_type'] ?? '') . ' ' . ($r['reference_id'] ?? '')),
        ]);
    }
    fclose($out);
    exit;
}

/* ---- User list (left panel) ---- */
$uq = "SELECT id, name, mobile, email, user_type, profile_pic,
              COALESCE(wallet_balance,0) AS wallet_balance, COALESCE(bonus_wallet,0) AS bonus_wallet
       FROM users WHERE 1=1";
$up = [];
if ($f_search !== '') {
    $uq .= " AND (name LIKE ? OR mobile LIKE ? OR email LIKE ? OR id = ?)";
    $like = '%' . $f_search . '%';
    array_push($up, $like, $like, $like, (int)$f_search);
}
if ($f_type !== '') { $uq .= " AND user_type = ?"; $up[] = $f_type; }
$uq .= " ORDER BY (COALESCE(wallet_balance,0) + COALESCE(bonus_wallet,0)) DESC, name ASC LIMIT 300";
$user_rows = $db->select($uq, $up);

/* ---- Selected user's detail ---- */
$sel = null; $sel_bal = ['main'=>0,'virtual'=>0,'total'=>0]; $sel_sum = []; $sel_rows = []; $sel_src = [];
if ($sel_uid > 0) {
    $r = $db->select("SELECT u.*, s.business_name FROM users u LEFT JOIN sellers s ON u.id = s.user_id WHERE u.id = ?", [$sel_uid]);
    if (!empty($r)) {
        $sel     = $r[0];
        $sel_bal = wallet_balances($db, $sel_uid);
        $sel_sum = wallet_summary($db, $sel_uid, $f_from, $f_to);
        $sel_rows= wallet_history($db, $sel_uid, ['wallet'=>$f_wallet,'direction'=>$f_dir,'category'=>$f_cat,'from'=>$f_from,'to'=>$f_to,'limit'=>1000]);
        $sel_src = earning_by_source($db, $sel_uid);
    }
}

/* ---- Platform-wide totals for the header cards ---- */
$tot = ['main'=>0.0,'virtual'=>0.0,'users'=>0,'rows'=>0];
try {
    $t = $db->select("SELECT COALESCE(SUM(wallet_balance),0) m, COALESCE(SUM(bonus_wallet),0) v, COUNT(*) n FROM users");
    if (!empty($t)) { $tot['main'] = (float)$t[0]['m']; $tot['virtual'] = (float)$t[0]['v']; $tot['users'] = (int)$t[0]['n']; }
    $t2 = $db->select("SELECT COUNT(*) n FROM wallet_ledger");
    if (!empty($t2)) { $tot['rows'] = (int)$t2[0]['n']; }
} catch (\Throwable $e) {}

$cat_map = wallet_categories();

// General details for the shell
$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;
?>
<!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>Wallet History - 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 }">

    <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">Wallet History</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" x-data="{ adjust: false }">

                <?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-6">
                    <h2 class="text-2xl font-bold text-slate-800 mb-1">Wallet History</h2>
                    <p class="text-gray-500 text-sm">Pick a user on the left to see every rupee that moved through both of their wallets.</p>
                </div>

                <!-- ===== PLATFORM TOTALS ===== -->
                <div class="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-6">
                    <div class="bg-white rounded-2xl border border-gray-200 shadow-sm p-4">
                        <p class="wh-k">Main Wallets</p>
                        <p class="text-2xl font-black text-slate-800">₹<?php echo number_format($tot['main'], 2); ?></p>
                        <p class="text-[10px] text-slate-400 mt-0.5">Deposited &amp; withdrawable</p>
                    </div>
                    <div class="bg-white rounded-2xl border border-amber-200 shadow-sm p-4">
                        <p class="wh-k text-amber-500">Virtual Wallets</p>
                        <p class="text-2xl font-black text-amber-600">₹<?php echo number_format($tot['virtual'], 2); ?></p>
                        <p class="text-[10px] text-amber-400 mt-0.5">Referral earnings — not withdrawable</p>
                    </div>
                    <div class="bg-white rounded-2xl border border-gray-200 shadow-sm p-4">
                        <p class="wh-k">Total Liability</p>
                        <p class="text-2xl font-black text-emerald-600">₹<?php echo number_format($tot['main'] + $tot['virtual'], 2); ?></p>
                        <p class="text-[10px] text-slate-400 mt-0.5"><?php echo number_format($tot['users']); ?> accounts</p>
                    </div>
                    <div class="bg-white rounded-2xl border border-gray-200 shadow-sm p-4">
                        <p class="wh-k">Ledger Entries</p>
                        <p class="text-2xl font-black text-indigo-600"><?php echo number_format($tot['rows']); ?></p>
                        <?php if ($tot['rows'] === 0): ?>
                            <form method="POST" class="mt-1">
                                <button type="submit" name="run_backfill" class="text-[10px] font-bold text-indigo-600 hover:underline">
                                    <i class="fas fa-download mr-1"></i>Import old transactions
                                </button>
                            </form>
                        <?php else: ?>
                            <p class="text-[10px] text-slate-400 mt-0.5">Across both wallets</p>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="grid lg:grid-cols-[320px,1fr] gap-5 items-start">

                    <!-- ===== LEFT: USER PICKER ===== -->
                    <div class="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden lg:sticky lg:top-0">
                        <div class="p-4 border-b border-gray-100 bg-slate-50/60">
                            <form method="GET" class="space-y-2">
                                <div class="relative">
                                    <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($f_search); ?>" placeholder="Name, mobile, email or ID"
                                           class="w-full pl-9 pr-3 py-2.5 bg-white border border-slate-300 rounded-xl text-xs outline-none focus:ring-2 focus:ring-emerald-400">
                                </div>
                                <div class="flex gap-2">
                                    <select name="t" class="flex-1 px-3 py-2 bg-white border border-slate-300 rounded-xl text-xs outline-none">
                                        <option value="">All types</option>
                                        <option value="customer" <?php echo $f_type==='customer'?'selected':''; ?>>Customer</option>
                                        <option value="seller"   <?php echo $f_type==='seller'?'selected':''; ?>>Seller</option>
                                        <option value="admin"    <?php echo $f_type==='admin'?'selected':''; ?>>Staff / Admin</option>
                                    </select>
                                    <button class="px-4 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl text-xs font-bold"><i class="fas fa-filter"></i></button>
                                </div>
                            </form>
                        </div>
                        <div class="max-h-[70vh] overflow-y-auto divide-y divide-gray-100">
                            <?php if (!empty($user_rows)): foreach ($user_rows as $u):
                                $tot_u = (float)$u['wallet_balance'] + (float)$u['bonus_wallet'];
                                $active = ($sel_uid === (int)$u['id']);
                                $qs = ['uid' => $u['id']];
                                if ($f_search !== '') $qs['q'] = $f_search;
                                if ($f_type !== '')   $qs['t'] = $f_type;
                            ?>
                            <a href="wallet_history.php?<?php echo http_build_query($qs); ?>"
                               class="flex items-center gap-3 p-3 transition-colors <?php echo $active ? 'bg-emerald-50 border-l-4 border-emerald-500' : 'hover:bg-slate-50 border-l-4 border-transparent'; ?>">
                                <div class="w-9 h-9 rounded-full bg-slate-100 flex items-center justify-center text-[11px] font-black text-slate-500 flex-shrink-0 overflow-hidden">
                                    <?php if (!empty($u['profile_pic'])): ?>
                                        <img src="../uploads/profiles/<?php echo htmlspecialchars($u['profile_pic']); ?>" class="w-full h-full object-cover" alt="">
                                    <?php else: ?>
                                        <?php echo strtoupper(substr($u['name'], 0, 2)); ?>
                                    <?php endif; ?>
                                </div>
                                <div class="min-w-0 flex-1">
                                    <p class="text-xs font-bold text-slate-800 truncate"><?php echo htmlspecialchars($u['name']); ?></p>
                                    <p class="text-[10px] text-slate-400"><?php echo htmlspecialchars($u['mobile']); ?> • <?php echo ucfirst($u['user_type']); ?></p>
                                </div>
                                <div class="text-right flex-shrink-0">
                                    <p class="text-xs font-black text-slate-700">₹<?php echo number_format($tot_u, 2); ?></p>
                                    <?php if ((float)$u['bonus_wallet'] > 0): ?>
                                        <p class="text-[9px] font-bold text-amber-500">₹<?php echo number_format((float)$u['bonus_wallet'], 2); ?> virtual</p>
                                    <?php endif; ?>
                                </div>
                            </a>
                            <?php endforeach; else: ?>
                                <p class="p-8 text-center text-xs text-slate-400">No users match that search.</p>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- ===== RIGHT: DETAIL ===== -->
                    <div>
                    <?php if (!$sel): ?>
                        <div class="bg-white rounded-2xl border border-gray-200 shadow-sm p-20 text-center">
                            <div class="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-4 text-slate-300 text-2xl border border-slate-100">
                                <i class="fas fa-hand-pointer"></i>
                            </div>
                            <p class="text-lg font-bold text-slate-700 mb-1">Select a user</p>
                            <p class="text-sm text-slate-500">Their full wallet history will open here.</p>
                        </div>
                    <?php else: ?>

                        <!-- user header -->
                        <div class="bg-gradient-to-r from-slate-800 to-slate-900 rounded-2xl shadow-lg p-5 mb-4 text-white">
                            <div class="flex flex-col sm:flex-row sm:items-center gap-4">
                                <div class="w-14 h-14 rounded-2xl bg-white/10 flex items-center justify-center text-lg font-black flex-shrink-0 overflow-hidden">
                                    <?php if (!empty($sel['profile_pic'])): ?>
                                        <img src="../uploads/profiles/<?php echo htmlspecialchars($sel['profile_pic']); ?>" class="w-full h-full object-cover" alt="">
                                    <?php else: ?><?php echo strtoupper(substr($sel['name'], 0, 2)); ?><?php endif; ?>
                                </div>
                                <div class="min-w-0 flex-1">
                                    <p class="font-extrabold text-lg leading-tight truncate"><?php echo htmlspecialchars($sel['name']); ?></p>
                                    <p class="text-white/60 text-xs">
                                        ID <?php echo (int)$sel['id']; ?> • <?php echo htmlspecialchars($sel['mobile']); ?> •
                                        <span class="uppercase font-bold"><?php echo htmlspecialchars($sel['user_type']); ?></span>
                                        <?php if (!empty($sel['business_name'])): ?> • <?php echo htmlspecialchars($sel['business_name']); ?><?php endif; ?>
                                    </p>
                                </div>
                                <div class="flex gap-2 flex-shrink-0">
                                    <button type="button" @click="adjust = true" class="px-4 py-2.5 rounded-xl bg-white/10 hover:bg-white/20 text-xs font-bold"><i class="fas fa-sliders mr-1.5"></i>Adjust</button>
                                    <a href="wallet_history.php?<?php echo http_build_query(array_filter(['uid'=>$sel_uid,'w'=>$f_wallet,'d'=>$f_dir,'c'=>$f_cat,'from'=>$f_from,'to'=>$f_to,'export'=>1])); ?>"
                                       class="px-4 py-2.5 rounded-xl bg-emerald-500 hover:bg-emerald-600 text-xs font-bold"><i class="fas fa-file-csv mr-1.5"></i>CSV</a>
                                </div>
                            </div>
                        </div>

                        <!-- balances -->
                        <div class="grid sm:grid-cols-3 gap-3 mb-4">
                            <div class="bg-white rounded-2xl border-2 border-slate-200 p-4">
                                <p class="wh-k"><i class="fas fa-wallet mr-1"></i>Main Wallet</p>
                                <p class="text-2xl font-black text-slate-800">₹<?php echo number_format($sel_bal['main'], 2); ?></p>
                                <p class="text-[10px] text-emerald-600 font-bold mt-1">+₹<?php echo number_format($sel_sum['main_in'] ?? 0, 2); ?> in &nbsp;•&nbsp; <span class="text-rose-500">−₹<?php echo number_format($sel_sum['main_out'] ?? 0, 2); ?> out</span></p>
                            </div>
                            <div class="bg-amber-50 rounded-2xl border-2 border-amber-200 p-4">
                                <p class="wh-k text-amber-500"><i class="fas fa-gift mr-1"></i>Virtual Wallet</p>
                                <p class="text-2xl font-black text-amber-600">₹<?php echo number_format($sel_bal['virtual'], 2); ?></p>
                                <p class="text-[10px] text-amber-500 font-bold mt-1">+₹<?php echo number_format($sel_sum['virtual_in'] ?? 0, 2); ?> in &nbsp;•&nbsp; −₹<?php echo number_format($sel_sum['virtual_out'] ?? 0, 2); ?> out</p>
                            </div>
                            <div class="bg-white rounded-2xl border-2 border-emerald-200 p-4">
                                <p class="wh-k text-emerald-500"><i class="fas fa-coins mr-1"></i>Total</p>
                                <p class="text-2xl font-black text-emerald-600">₹<?php echo number_format($sel_bal['total'], 2); ?></p>
                                <p class="text-[10px] text-slate-400 mt-1"><?php echo number_format($sel_sum['count'] ?? 0); ?> ledger entries</p>
                            </div>
                        </div>

                        <!-- earning sources -->
                        <div class="bg-white rounded-2xl border border-gray-200 shadow-sm p-4 mb-4">
                            <p class="wh-k mb-3">Lifetime earnings by source</p>
                            <div class="grid grid-cols-2 sm:grid-cols-4 gap-2">
                                <?php foreach ($sel_src as $k => $v): ?>
                                    <div class="rounded-xl border border-slate-200 p-3">
                                        <p class="text-[10px] font-bold text-slate-400 uppercase truncate"><i class="fas <?php echo wallet_cat_icon($k); ?> mr-1"></i><?php echo wallet_cat_label($k); ?></p>
                                        <p class="text-base font-black text-slate-800">₹<?php echo number_format($v['total'], 2); ?></p>
                                        <p class="text-[10px] text-slate-400"><?php echo (int)$v['count']; ?> entries</p>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- filters -->
                        <form method="GET" class="bg-white rounded-2xl border border-gray-200 shadow-sm p-4 mb-4 grid sm:grid-cols-2 lg:grid-cols-6 gap-2 items-end">
                            <input type="hidden" name="uid" value="<?php echo $sel_uid; ?>">
                            <input type="hidden" name="q" value="<?php echo htmlspecialchars($f_search); ?>">
                            <input type="hidden" name="t" value="<?php echo htmlspecialchars($f_type); ?>">
                            <div><label class="wh-l">Wallet</label>
                                <select name="w" class="wh-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="wh-l">Direction</label>
                                <select name="d" class="wh-f">
                                    <option value="">All</option>
                                    <option value="credit" <?php echo $f_dir==='credit'?'selected':''; ?>>Credit (in)</option>
                                    <option value="debit"  <?php echo $f_dir==='debit'?'selected':''; ?>>Debit (out)</option>
                                </select></div>
                            <div><label class="wh-l">Category</label>
                                <select name="c" class="wh-f">
                                    <option value="">All</option>
                                    <?php foreach ($cat_map 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="wh-l">From</label><input type="date" name="from" value="<?php echo htmlspecialchars($f_from); ?>" class="wh-f"></div>
                            <div><label class="wh-l">To</label><input type="date" name="to" value="<?php echo htmlspecialchars($f_to); ?>" class="wh-f"></div>
                            <div class="flex gap-2">
                                <button class="flex-1 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl text-xs font-bold">Apply</button>
                                <a href="wallet_history.php?uid=<?php echo $sel_uid; ?>" class="px-3 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-600 rounded-xl text-xs font-bold flex items-center">Reset</a>
                            </div>
                        </form>

                        <!-- ledger -->
                        <div class="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden">
                            <div class="px-5 py-3 border-b border-gray-100 bg-slate-50/60 flex items-center justify-between">
                                <p class="text-sm font-bold text-slate-700"><i class="fas fa-list mr-2 text-emerald-600"></i>Transaction detail</p>
                                <span class="text-[11px] font-bold text-slate-400"><?php echo count($sel_rows); ?> row(s)</span>
                            </div>
                            <div class="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 After</th>
                                        </tr>
                                    </thead>
                                    <tbody class="divide-y divide-gray-100">
                                    <?php if (!empty($sel_rows)): foreach ($sel_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="px-2 py-1 rounded-lg text-[10px] font-bold <?php echo $isv ? 'bg-amber-100 text-amber-700' : 'bg-slate-100 text-slate-600'; ?>">
                                                    <i class="fas <?php echo $isv ? 'fa-gift' : 'fa-wallet'; ?> mr-1"></i><?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>
                                                <?php if (!empty($r['reference_type'])): ?>
                                                    <p class="text-[10px] text-slate-400 mt-0.5"><?php echo htmlspecialchars($r['reference_type']); ?> #<?php echo (int)$r['reference_id']; ?></p>
                                                <?php endif; ?>
                                            </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 whitespace-nowrap font-bold text-slate-500">
                                                ₹<?php echo number_format((float)$r['balance_after'], 2); ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; else: ?>
                                        <tr><td colspan="6" class="p-12 text-center text-slate-400">
                                            <i class="fas fa-receipt text-2xl mb-2 block"></i>
                                            No wallet activity for this filter.
                                        </td></tr>
                                    <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <!-- adjust modal -->
                        <div x-show="adjust" x-cloak x-transition.opacity class="fixed inset-0 z-[200] flex items-center justify-center p-4">
                            <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="adjust = false"></div>
                            <div class="relative w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden">
                                <div class="bg-gradient-to-r from-slate-700 to-slate-900 px-5 py-4 flex items-center justify-between">
                                    <h3 class="text-white font-bold text-lg"><i class="fas fa-sliders mr-2"></i>Adjust Wallet</h3>
                                    <button @click="adjust = false" class="text-white/70 hover:text-white text-2xl leading-none">&times;</button>
                                </div>
                                <form method="POST" class="p-5 space-y-3">
                                    <input type="hidden" name="target_user_id" value="<?php echo $sel_uid; ?>">
                                    <p class="text-xs text-slate-500">Manually add or deduct money for <b><?php echo htmlspecialchars($sel['name']); ?></b>. Every adjustment is logged.</p>
                                    <div class="grid grid-cols-2 gap-3">
                                        <div><label class="wh-l">Wallet</label>
                                            <select name="adj_wallet" class="wh-f">
                                                <option value="main">Main (withdrawable)</option>
                                                <option value="virtual">Virtual (not withdrawable)</option>
                                            </select></div>
                                        <div><label class="wh-l">Action</label>
                                            <select name="adj_direction" class="wh-f">
                                                <option value="credit">Add money</option>
                                                <option value="debit">Deduct money</option>
                                            </select></div>
                                    </div>
                                    <div><label class="wh-l">Amount (₹)</label><input type="number" step="0.01" min="0.01" name="adj_amount" required class="wh-f"></div>
                                    <div><label class="wh-l">Note (shown in history)</label><input name="adj_note" placeholder="e.g. Manual refund for order #123" class="wh-f"></div>
                                    <div class="flex justify-end gap-2 pt-1">
                                        <button type="button" @click="adjust = false" class="px-4 py-2.5 text-sm font-semibold text-slate-600 hover:bg-slate-100 rounded-xl">Cancel</button>
                                        <button type="submit" name="adjust_wallet" class="px-5 py-2.5 text-sm font-bold text-white bg-slate-800 hover:bg-slate-900 rounded-xl shadow">Apply</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    <?php endif; ?>
                    </div>
                </div>

                <style>
                    [x-cloak] { display:none !important; }
                    .wh-k { font-size:10px; font-weight:800; text-transform:uppercase; letter-spacing:.06em; color:#94a3b8; margin-bottom:.25rem; }
                    .wh-l { display:block; font-size:10px; font-weight:700; color:#64748b; margin-bottom:.2rem; text-transform:uppercase; letter-spacing:.04em; }
                    .wh-f { width:100%; padding:.6rem .7rem; background:#fff; border:1px solid #cbd5e1; border-radius:.75rem; font-size:.75rem; outline:none; }
                    .wh-f:focus { box-shadow:0 0 0 2px rgba(16,185,129,.35); border-color:#10b981; }
                </style>
            </main>
        </div>
    </div>


</body>
</html>
