<?php
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';
require_once __DIR__ . '/../includes/admin_list.php';
require_once __DIR__ . '/../includes/notify.php';
require_once __DIR__ . '/../includes/kyc.php';

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

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

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

// --- Auto-create required tables/columns if missing (no manual migration needed) ---
$__conn = $db->getConnection();
$__ddl = [
    "CREATE TABLE IF NOT EXISTS user_notes (
        id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, title VARCHAR(255) NOT NULL,
        description TEXT NULL, created_by INT NULL, created_by_name VARCHAR(120) NULL,
        created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
    "CREATE TABLE IF NOT EXISTS user_update_history (
        id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, field_label VARCHAR(120) NOT NULL,
        old_value TEXT NULL, new_value TEXT NULL, updated_by INT NULL, updated_by_name VARCHAR(120) NULL,
        updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
];
foreach ($__ddl as $__q) { try { $__conn->query($__q); } catch (\Throwable $e) { /* ignore */ } }
$__cols = ['village' => 'VARCHAR(150)', 'post_office' => 'VARCHAR(150)', 'block_city' => 'VARCHAR(150)', 'landmark' => 'VARCHAR(255)'];
foreach ($__cols as $__c => $__type) {
    try {
        $__r = $__conn->query("SHOW COLUMNS FROM users LIKE '$__c'");
        if ($__r && $__r->num_rows === 0) { $__conn->query("ALTER TABLE users ADD COLUMN `$__c` $__type NULL"); }
    } catch (\Throwable $e) { /* ignore */ }
}
kyc_ensure_schema($db); // create kyc_details table if missing

// Current logged-in admin/staff (used for "created by" / "updated by" logging)
$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 (JSON) ENDPOINTS  — must run before any HTML output
   ============================================================ */
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    $uid = intval($_GET['uid'] ?? 0);
    if ($_GET['ajax'] === 'notes') {
        echo json_encode($db->select("SELECT * FROM user_notes WHERE user_id = ? ORDER BY created_at DESC", [$uid]));
    } elseif ($_GET['ajax'] === 'history') {
        echo json_encode($db->select("SELECT * FROM user_update_history WHERE user_id = ? ORDER BY updated_at DESC", [$uid]));
    } elseif ($_GET['ajax'] === 'user') {
        $r = $db->select("SELECT id,name,mobile,call_number,whatsapp_number,email,gender,state,district,pincode,village,post_office,block_city,landmark,profile_pic FROM users WHERE id = ?", [$uid]);
        echo json_encode(!empty($r) ? $r[0] : null);
    } elseif ($_GET['ajax'] === 'kyc') {
        $r = $db->select("SELECT * FROM kyc_details WHERE user_id = ?", [$uid]);
        echo json_encode(!empty($r) ? $r[0] : null);
    } elseif ($_GET['ajax'] === 'adminkyc') {
        echo json_encode(kyc_get_data($db, $uid)); // full KYC (prefilled if none yet)
    } else {
        echo json_encode(['error' => 'unknown']);
    }
    exit;
}

/* ============================================================
   POST HANDLERS  (only features that the current system supports)
   ============================================================ */

// --- Add a note against a user ---
if (isset($_POST['add_note'])) {
    $tid   = intval($_POST['target_user_id']);
    $title = sanitize($_POST['note_title'] ?? '');
    $desc  = sanitize($_POST['note_description'] ?? '');
    if ($tid > 0 && $title !== '') {
        $db->insert("INSERT INTO user_notes (user_id, title, description, created_by, created_by_name) VALUES (?, ?, ?, ?, ?)",
            [$tid, $title, $desc, $me['id'], $me['name']]);
        $_SESSION['flash_success'] = "Note added successfully!";
    } else {
        $_SESSION['flash_error'] = "Note title is required.";
    }
    redirect('user_list.php');
}

// --- Admin: save full KYC details for a user (from the Update modal) ---
if (isset($_POST['admin_kyc_save'])) {
    $tid = intval($_POST['target_user_id']);
    if ($tid > 0) {
        kyc_admin_save($db, $tid, '../uploads/kyc/', $me);
        $_SESSION['flash_success'] = "KYC details updated successfully!";
    }
    redirect('user_list.php');
}

// --- KYC approve / reject (logged to update history) ---
if (isset($_POST['kyc_action'])) {
    $tid    = intval($_POST['target_user_id']);
    $act    = $_POST['kyc_action']; // 'approved' or 'rejected'
    $remark = sanitize($_POST['kyc_remark'] ?? '');
    if (in_array($act, ['approved', 'rejected'])) {
        $db->insert("UPDATE kyc_details SET status = ?, admin_remark = ? WHERE user_id = ?", [$act, $remark, $tid]);
        $db->insert("INSERT INTO user_update_history (user_id, field_label, old_value, new_value, updated_by, updated_by_name) VALUES (?, 'KYC Status', 'pending', ?, ?, ?)",
            [$tid, ucfirst($act) . ($remark ? " ($remark)" : ''), $me['id'], $me['name']]);
        $_SESSION['flash_success'] = "KYC " . ucfirst($act) . " successfully!";
    }
    redirect('user_list.php');
}

// --- Update user details (logs every changed field to update history) ---
if (isset($_POST['update_user'])) {
    $tid = intval($_POST['target_user_id']);
    $old_row = $db->select("SELECT * FROM users WHERE id = ?", [$tid]);
    if (!empty($old_row)) {
        $old = $old_row[0];
        $fields = [
            'name' => 'Name', 'mobile' => 'Mobile', 'call_number' => 'Call Number',
            'whatsapp_number' => 'WhatsApp Number', 'email' => 'Email', 'gender' => 'Gender',
            'state' => 'State', 'district' => 'District', 'pincode' => 'Pincode',
            'village' => 'Village', 'post_office' => 'Post Office', 'block_city' => 'Block/City', 'landmark' => 'Landmark',
        ];
        $changed = 0;
        foreach ($fields as $col => $label) {
            if (!isset($_POST[$col])) continue;
            $newv = sanitize($_POST[$col]);
            $oldv = isset($old[$col]) ? (string)$old[$col] : '';
            if ($oldv !== (string)$newv) {
                $db->insert("UPDATE users SET `$col` = ? WHERE id = ?", [$newv, $tid]); // $col is from fixed whitelist
                $db->insert("INSERT INTO user_update_history (user_id, field_label, old_value, new_value, updated_by, updated_by_name) VALUES (?, ?, ?, ?, ?, ?)",
                    [$tid, $label, $oldv, $newv, $me['id'], $me['name']]);
                $changed++;
            }
        }
        // Optional profile picture change
        if (!empty($_FILES['profile_pic']['name']) && is_uploaded_file($_FILES['profile_pic']['tmp_name'])) {
            $ext = strtolower(pathinfo($_FILES['profile_pic']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg', 'jpeg', 'png', 'webp', 'gif'])) {
                $fname = 'user_' . $tid . '_' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES['profile_pic']['tmp_name'], '../uploads/profiles/' . $fname)) {
                    $db->insert("UPDATE users SET profile_pic = ? WHERE id = ?", [$fname, $tid]);
                    $db->insert("INSERT INTO user_update_history (user_id, field_label, old_value, new_value, updated_by, updated_by_name) VALUES (?, 'Profile Picture', ?, ?, ?, ?)",
                        [$tid, $old['profile_pic'] ?? '', $fname, $me['id'], $me['name']]);
                    $changed++;
                }
            }
        }
        $_SESSION['flash_success'] = $changed > 0 ? "User updated ($changed field" . ($changed > 1 ? 's' : '') . " changed)." : "No changes were made.";
    }
    redirect('user_list.php');
}

// --- Activate / Suspend user (existing capability: users.status) ---
if (isset($_POST['toggle_status'])) {
    $tid = sanitize($_POST['target_user_id']);
    $cur = sanitize($_POST['current_status']);
    $new = ($cur == 1) ? 0 : 1;
    $db->insert("UPDATE users SET status = ? WHERE id = ?", [$new, $tid]);
    $_SESSION['flash_success'] = 'Status updated successfully!';
    redirect('user_list.php');
}

// --- Change role: Customer / Seller (existing capability in users.php) ---
if (isset($_POST['change_role'])) {
    $tid = sanitize($_POST['target_user_id']);
    $new_role = sanitize($_POST['new_role']); // 'customer' or 'seller'
    if (in_array($new_role, ['customer', 'seller'])) {
        $db->insert("UPDATE users SET user_type = ? WHERE id = ?", [$new_role, $tid]);
        if ($new_role == 'seller') {
            $check = $db->select("SELECT id FROM sellers WHERE user_id = ?", [$tid]);
            if (empty($check)) {
                $u = $db->select("SELECT * FROM users WHERE id = ?", [$tid])[0];
                $db->insert("INSERT INTO sellers (user_id, name, phone, email, business_name, status) VALUES (?, ?, ?, ?, ?, 1)",
                    [$tid, $u['name'], $u['mobile'], $u['email'], $u['name'] . ' Business']);
            } else {
                $db->insert("UPDATE sellers SET status = 1 WHERE user_id = ?", [$tid]);
            }
        }
        $_SESSION['flash_success'] = "User type changed to " . ucfirst($new_role) . " successfully!";
        redirect('user_list.php');
    }
}

// --- Wallet credit / debit with a mandatory reason ---
if (isset($_POST['wallet_transfer'])) {
    $tid     = intval($_POST['target_user_id']);
    $amount  = round(floatval($_POST['transfer_amount']), 2);
    $action  = ($_POST['transfer_action'] ?? 'credit') === 'debit' ? 'debit' : 'credit';
    $wallet  = ($_POST['transfer_wallet'] ?? 'main') === 'virtual' ? WALLET_VIRTUAL : WALLET_MAIN;
    $reason  = trim(sanitize($_POST['transfer_reason'] ?? ''));
    $note    = trim(sanitize($_POST['transfer_note'] ?? ''));

    $full_reason = $reason . ($note !== '' ? ' — ' . $note : '');

    if ($tid <= 0 || $amount <= 0) {
        $_SESSION['flash_error'] = "Please enter a valid amount.";
    } elseif ($reason === '') {
        $_SESSION['flash_error'] = "A reason is required for every credit or debit.";
    } elseif ($action === 'credit') {
        wallet_credit($db, $tid, $wallet, $amount, [
            'category'    => 'admin',
            'description' => 'Admin credit — ' . $full_reason,
            'created_by'  => $user_id,
        ]);
        try {
            $db->insert("INSERT INTO user_update_history (user_id, field_label, old_value, new_value, updated_by, updated_by_name) VALUES (?, 'Wallet Credit', '', ?, ?, ?)",
                [$tid, '₹' . number_format($amount, 2) . ' (' . ($wallet === WALLET_VIRTUAL ? 'virtual' : 'main') . ') — ' . $full_reason, $user_id, $me['name'] ?? 'Admin']);
        } catch (\Throwable $e) {}
        if (function_exists('notify_send')) {
            notify_send($db, $tid, 'Wallet credited',
                '₹' . number_format($amount, 2) . ' has been added to your ' . ($wallet === WALLET_VIRTUAL ? 'virtual' : 'main') . ' wallet. Reason: ' . $full_reason,
                'wallet', 'wallet.php#wallet_history', $user_id);
        }
        $_SESSION['flash_success'] = "₹" . number_format($amount, 2) . " credited. Reason: " . htmlspecialchars($full_reason);
    } else {
        $bal  = wallet_balances($db, $tid);
        $have = ($wallet === WALLET_VIRTUAL) ? $bal['virtual'] : $bal['main'];
        if ($have + 0.001 < $amount) {
            $_SESSION['flash_error'] = "That wallet only holds ₹" . number_format($have, 2) . ".";
        } else {
            $col = ($wallet === WALLET_VIRTUAL) ? 'bonus_wallet' : 'wallet_balance';
            $db->insert("UPDATE users SET `$col` = `$col` - ? WHERE id = ?", [$amount, $tid]); // whitelisted
            $nb = wallet_balances($db, $tid);
            wallet__ledger($db, $tid, $wallet, 'debit', $amount,
                ($wallet === WALLET_VIRTUAL) ? $nb['virtual'] : $nb['main'],
                ['category' => 'admin', 'description' => 'Admin debit — ' . $full_reason, 'created_by' => $user_id]);
            wallet__legacy($db, $tid, 'debit', $amount, 'Admin debit — ' . $full_reason);
            try {
                $db->insert("INSERT INTO user_update_history (user_id, field_label, old_value, new_value, updated_by, updated_by_name) VALUES (?, 'Wallet Debit', '', ?, ?, ?)",
                    [$tid, '₹' . number_format($amount, 2) . ' (' . ($wallet === WALLET_VIRTUAL ? 'virtual' : 'main') . ') — ' . $full_reason, $user_id, $me['name'] ?? 'Admin']);
            } catch (\Throwable $e) {}
            if (function_exists('notify_send')) {
                notify_send($db, $tid, 'Wallet debited',
                    '₹' . number_format($amount, 2) . ' has been deducted from your ' . ($wallet === WALLET_VIRTUAL ? 'virtual' : 'main') . ' wallet. Reason: ' . $full_reason,
                    'wallet', 'wallet.php#wallet_history', $user_id);
            }
            $_SESSION['flash_success'] = "₹" . number_format($amount, 2) . " debited. Reason: " . htmlspecialchars($full_reason);
        }
    }
    redirect('user_list.php');
}

// --- Reset Password: admin enters a new password (logged to update history) ---
if (isset($_POST['reset_password'])) {
    $tid = intval($_POST['target_user_id']);
    $newpass = $_POST['new_password'] ?? '';
    if (strlen($newpass) >= 4) {
        $hashed = password_hash($newpass, PASSWORD_DEFAULT);
        $db->insert("UPDATE users SET password = ? WHERE id = ?", [$hashed, $tid]);
        $db->insert("INSERT INTO user_update_history (user_id, field_label, old_value, new_value, updated_by, updated_by_name) VALUES (?, 'Password', '••••••••', 'Password was reset', ?, ?)",
            [$tid, $me['id'], $me['name']]);
        $_SESSION['flash_success'] = "Password updated successfully!";
    } else {
        $_SESSION['flash_error'] = "Password must be at least 4 characters.";
    }
    redirect('user_list.php');
}

/* ============================================================
   FETCH DATA
   ============================================================ */
$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;
if (!$user) { session_destroy(); redirect('../login.php'); }

/* ---------------- STICKY FILTERS ---------------- */
$UL_DEFAULTS = ['search' => '', 'kyc' => '', 'sub' => '', 'status' => '', 'joined' => '', 'wallet' => '', 'types' => 'customer,seller,admin'];
$UL = alist_filters('users', $UL_DEFAULTS);

$search_query = $UL['search'];

// User-type filter (Customer / Seller / Staff). Staff = user_type 'admin'.
$allowed_types = ['customer', 'seller', 'admin'];
$type_labels   = ['customer' => 'Customer', 'seller' => 'Seller', 'admin' => 'Staff'];
$selected_types = array_values(array_intersect(array_filter(explode(',', (string)$UL['types'])), $allowed_types));
if (empty($selected_types)) $selected_types = $allowed_types;

$type_ph = implode(',', array_fill(0, count($selected_types), '?'));
$where_clause = "u.user_type IN ($type_ph)";
$params = $selected_types;

if ($search_query !== '') {
    $where_clause .= " AND (u.id = ? OR u.name LIKE ? OR u.mobile LIKE ? OR u.email LIKE ?)";
    $like = "%$search_query%";
    $params[] = intval(str_replace(['#', 'WBMCZ'], '', $search_query));
    $params[] = $like; $params[] = $like; $params[] = $like;
}
if ($UL['kyc'] === 'approved')      { $where_clause .= " AND k.status = 'approved'"; }
elseif ($UL['kyc'] === 'pending')   { $where_clause .= " AND k.status = 'pending'"; }
elseif ($UL['kyc'] === 'rejected')  { $where_clause .= " AND k.status = 'rejected'"; }
elseif ($UL['kyc'] === 'none')      { $where_clause .= " AND k.id IS NULL"; }

if ($UL['sub'] === 'yes')      { $where_clause .= " AND u.is_subscribed = 1"; }
elseif ($UL['sub'] === 'no')   { $where_clause .= " AND (u.is_subscribed = 0 OR u.is_subscribed IS NULL)"; }

if ($UL['status'] === '1')     { $where_clause .= " AND u.status = 1"; }
elseif ($UL['status'] === '0') { $where_clause .= " AND u.status = 0"; }

if ($UL['joined'] === 'today')     { $where_clause .= " AND DATE(u.created_at) = CURDATE()"; }
elseif ($UL['joined'] === '7')     { $where_clause .= " AND u.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"; }
elseif ($UL['joined'] === '30')    { $where_clause .= " AND u.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)"; }
elseif ($UL['joined'] === 'month') { $where_clause .= " AND u.created_at >= DATE_FORMAT(NOW(), '%Y-%m-01')"; }

if ($UL['wallet'] === 'zero')       { $where_clause .= " AND COALESCE(u.wallet_balance,0) = 0"; }
elseif ($UL['wallet'] === 'nonzero'){ $where_clause .= " AND COALESCE(u.wallet_balance,0) > 0"; }

/* ---------------- STATS ---------------- */
$ULS = ['total'=>0,'customer'=>0,'seller'=>0,'staff'=>0,'today'=>0,'week'=>0,'sub'=>0,
        'kyc_pending'=>0,'kyc_approved'=>0,'kyc_none'=>0,'wallet'=>0,'virtual'=>0,'blocked'=>0];
try {
    $r = $db->select("SELECT COUNT(*) t,
        SUM(user_type='customer') c, SUM(user_type='seller') s, SUM(user_type='admin') a,
        SUM(DATE(created_at)=CURDATE()) td, SUM(created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)) wk,
        SUM(COALESCE(is_subscribed,0)=1) sb, SUM(COALESCE(status,1)=0) bl,
        COALESCE(SUM(wallet_balance),0) wl, COALESCE(SUM(bonus_wallet),0) vw FROM users");
    if (!empty($r)) { $x=$r[0];
        $ULS['total']=(int)$x['t']; $ULS['customer']=(int)$x['c']; $ULS['seller']=(int)$x['s'];
        $ULS['staff']=(int)$x['a']; $ULS['today']=(int)$x['td']; $ULS['week']=(int)$x['wk'];
        $ULS['sub']=(int)$x['sb']; $ULS['blocked']=(int)$x['bl'];
        $ULS['wallet']=(float)$x['wl']; $ULS['virtual']=(float)$x['vw'];
    }
    $r = $db->select("SELECT SUM(status='pending') p, SUM(status='approved') a FROM kyc_details");
    if (!empty($r)) { $ULS['kyc_pending']=(int)$r[0]['p']; $ULS['kyc_approved']=(int)$r[0]['a']; }
    $r = $db->select("SELECT COUNT(*) n FROM users u LEFT JOIN kyc_details k ON k.user_id=u.id WHERE k.id IS NULL");
    if (!empty($r)) { $ULS['kyc_none']=(int)$r[0]['n']; }
} catch (\Throwable $e) {}
// LEFT JOIN self (referrer = "Created By") and kyc_details (status + address source)
/* ---------------- CSV EXPORT ---------------- */
if (isset($_GET['export'])) {
    $ex = $db->select(
        "SELECT u.*, r.name AS ref_name, k.status AS kyc_status
         FROM users u
         LEFT JOIN users r ON u.referred_by = r.id
         LEFT JOIN kyc_details k ON k.user_id = u.id
         WHERE $where_clause ORDER BY u.id DESC LIMIT 10000", $params);
    alist_export_csv('user_list', [
        'ID' => 'id',
        'Code' => function ($r) { return 'WBMCZ' . str_pad($r['id'], 4, '0', STR_PAD_LEFT); },
        'Name' => 'name', 'Mobile' => 'mobile', 'Email' => 'email',
        'Type' => function ($r) { return $r['user_type'] === 'admin' ? 'Staff' : ucfirst($r['user_type']); },
        'Status' => function ($r) { return ((int)($r['status'] ?? 1) === 1) ? 'Active' : 'Blocked'; },
        'KYC' => function ($r) { return $r['kyc_status'] ?: 'not submitted'; },
        'Subscribed' => function ($r) { return !empty($r['is_subscribed']) ? 'Yes' : 'No'; },
        'Main Wallet' => function ($r) { return number_format((float)($r['wallet_balance'] ?? 0), 2, '.', ''); },
        'Virtual Wallet' => function ($r) { return number_format((float)($r['bonus_wallet'] ?? 0), 2, '.', ''); },
        'State' => 'state', 'District' => 'district', 'Pincode' => 'pincode',
        'Referred By' => 'ref_name',
        'Joined' => 'created_at',
    ], $ex);
}

$customers = $db->select(
    "SELECT u.*, r.name AS ref_name, r.id AS ref_id,
            k.id AS kyc_id, k.status AS kyc_status,
            k.village AS k_village, k.post_office AS k_post_office, k.block_city AS k_block_city,
            k.landmark AS k_landmark, k.district AS k_district, k.state AS k_state, k.pincode AS k_pincode
     FROM users u
     LEFT JOIN users r ON u.referred_by = r.id
     LEFT JOIN kyc_details k ON k.user_id = u.id
     WHERE $where_clause ORDER BY u.id DESC", $params);

$raw_logo = getSetting('company_logo', 'assets/images/logo.png');
$company_logo = (strpos($raw_logo, 'http') === 0) ? $raw_logo : '../' . ltrim($raw_logo, '/');
$company_name = getSetting('company_name', 'WBMCZ');
$profile_image_url = !empty($user['profile_pic']) ? '../uploads/profiles/' . $user['profile_pic'] : null;

// Helper: build the WBMCZ user code (matches refer.php convention)
function userCode($id) { return 'WBMCZ' . str_pad($id, 4, '0', STR_PAD_LEFT); }

// The "admin created by" label — using the logged-in admin as a stand-in.
// # PENDING: there is no `created_by` column in the users table (see report).
$created_by_code = userCode($user['id']);
$created_by_name = strtoupper($user['name']);
?>
<!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>User List - <?php echo $company_name; ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=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; }
        /* PDF-style compact cell buttons */
        .cell-btn { display:block; width:100%; text-align:center; font-size:10px; font-weight:700; padding:3px 6px; border-radius:4px; color:#fff; white-space:nowrap; }
        .pending-tag { display:inline-block; font-size:9px; font-weight:700; color:#b45309; background:#fef3c7; border:1px dashed #f59e0b; padding:1px 6px; border-radius:9999px; }
        table.ul td { vertical-align: top; }
        /* Full gridlines around every cell (PDF-style) */
        table.ul { border: 2px solid #cbd5e1; }
        table.ul th, table.ul td { border: 1px solid #e2e8f0; }
        .fld { width:100%; border:1px solid #cbd5e1; border-radius:0.5rem; padding:0.5rem 0.75rem; font-size:0.875rem; outline:none; }
        .fld:focus { box-shadow:0 0 0 2px rgba(16,185,129,0.4); border-color:#10b981; }
        .lbl { display:block; font-size:0.7rem; font-weight:700; color:#475569; text-transform:uppercase; letter-spacing:0.03em; margin-bottom:0.25rem; }
        .filein { width:100%; font-size:0.7rem; color:#64748b; }
        .filein::file-selector-button { margin-right:0.5rem; padding:0.25rem 0.5rem; border-radius:0.375rem; border:0; background:#ecfdf5; color:#047857; font-weight:600; font-size:0.7rem; }
    </style>
</head>
<body class="bg-gray-50" x-data="userListApp()">
<div class="flex h-screen overflow-hidden">

    <!-- ================= SIDEBAR ================= -->
    <aside :class="sidebarOpen ? 'w-64' : 'w-20'" class="flex-shrink-0 bg-gradient-to-b from-slate-800 to-slate-900 text-white transition-all duration-300 flex flex-col shadow-2xl z-50 overflow-x-hidden relative">
        <div class="flex items-center h-20 px-4 border-b border-white/10" :class="sidebarOpen ? 'justify-between' : 'justify-center'">
            <a href="../index.php" class="flex items-center">
                <img src="<?php echo $company_logo; ?>" alt="Logo" class="h-10 w-10 bg-white rounded p-1 flex-shrink-0 object-contain">
                <span x-show="sidebarOpen" class="ml-3 text-xl font-bold tracking-wider whitespace-nowrap text-emerald-400">ADMIN</span>
            </a>
        </div>
        <nav class="flex-1 px-3 py-6 space-y-1.5 overflow-y-auto hide-scrollbar text-sm font-medium">
            <a href="index.php" class="flex items-center px-3 py-3 text-gray-300 hover:bg-white/5 hover:text-white rounded-xl transition-all" :class="sidebarOpen ? '' : 'justify-center'">
                <i class="fas fa-chart-line flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-xl'"></i>
                <span x-show="sidebarOpen" class="ml-3 font-semibold">Dashboard</span>
            </a>
            <div x-data="{ userMenuOpen: false }">
                <button @click="userMenuOpen = !userMenuOpen" class="w-full flex items-center justify-between px-3 py-3 text-gray-300 hover:bg-white/5 hover:text-white rounded-xl transition-all" :class="sidebarOpen ? '' : 'justify-center'">
                    <div class="flex items-center">
                        <i class="fas fa-users-cog flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-xl'"></i>
                        <span x-show="sidebarOpen" class="ml-3 font-semibold">User Management</span>
                    </div>
                    <i x-show="sidebarOpen" class="fas fa-chevron-down text-xs transition-transform" :class="userMenuOpen ? 'rotate-180' : ''"></i>
                </button>
                <div x-show="userMenuOpen && sidebarOpen" x-transition class="pl-10 pr-3 py-2 space-y-1">
                    <a href="user_list.php" class="block py-2 text-sm text-emerald-400 font-semibold transition-colors">User List</a>
                    <a href="kyc_pending.php" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">KYC Pending</a>
                    <a href="users.php" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Customer</a>
            <a href="notifications.php" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Notifications</a>
                    <a href="sellers.php" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Seller</a>
                    <a href="staff.php" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Staff</a>
                    <a href="roles.php" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Custom Role</a>
                    <a href="upgrade_requests.php" class="block py-2 text-sm text-amber-400 hover:text-amber-300 font-semibold transition-colors">Upgrade Requests</a>
                </div>
            </div>
            <a href="services.php" class="flex items-center px-3 py-3 text-gray-300 hover:bg-white/5 hover:text-white rounded-xl transition-all" :class="sidebarOpen ? '' : 'justify-center'">
                <i class="fas fa-layer-group flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-xl'"></i>
                <span x-show="sidebarOpen" class="ml-3 font-semibold">Services</span>
            </a>
            <a href="wallet.php" class="flex items-center px-3 py-3 text-gray-300 hover:bg-white/5 hover:text-white rounded-xl transition-all" :class="sidebarOpen ? '' : 'justify-center'">
                <i class="fas fa-wallet flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-xl'"></i>
                <span x-show="sidebarOpen" class="ml-3 font-semibold">Wallet</span>
            </a>
            <a href="settings.php" class="flex items-center px-3 py-3 text-gray-300 hover:bg-white/5 hover:text-white rounded-xl transition-all" :class="sidebarOpen ? '' : 'justify-center'">
                <i class="fas fa-cogs flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-xl'"></i>
                <span x-show="sidebarOpen" class="ml-3 font-semibold">Settings</span>
            </a>
            <div class="pt-6 mt-6 border-t border-white/10">
                <a href="../logout.php" onclick="return confirm('Are you sure you want to logout?');" class="flex items-center px-3 py-3 text-rose-400 hover:bg-rose-500/20 hover:text-rose-300 rounded-xl transition-all" :class="sidebarOpen ? '' : 'justify-center'">
                    <i class="fas fa-sign-out-alt flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-xl'"></i>
                    <span x-show="sidebarOpen" class="ml-3">Logout</span>
                </a>
            </div>
        </nav>
    </aside>

    <!-- ================= MAIN ================= -->
    <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 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">User List</h2>
            </div>
            <div class="flex items-center space-x-4 ml-auto">
                <a href="../index.php" target="_blank" class="hidden sm:flex items-center text-sm font-semibold text-gray-500 hover:text-emerald-600 transition-colors">
                    <i class="fas fa-external-link-alt mr-2"></i> Visit Site
                </a>
                <?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 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"><?php echo strtoupper(substr($user['name'],0,1)); ?></div>
                <?php endif; ?>
            </div>
        </header>

        <main class="flex-1 overflow-y-auto p-4 md:p-6 relative">
            <div class="mb-5">
                <h2 class="text-2xl font-bold text-slate-800 mb-1">User List Management</h2>
                <p class="text-gray-500 text-sm">All users — customers, sellers &amp; staff — with profile, address, subscription, wallet &amp; quick actions.</p>
            </div>

            <!-- ===== REPORT CARDS ===== -->
            <?php echo alist_stats([
                ['label'=>'Total Users','value'=>number_format($ULS['total']),'sub'=>$ULS['customer'].' customers','colour'=>'indigo','icon'=>'fa-users'],
                ['label'=>'Sellers','value'=>number_format($ULS['seller']),'sub'=>$ULS['staff'].' staff','colour'=>'emerald','icon'=>'fa-store'],
                ['label'=>'Joined Today','value'=>number_format($ULS['today']),'sub'=>$ULS['week'].' this week','colour'=>'blue','icon'=>'fa-user-plus'],
                ['label'=>'KYC Pending','value'=>number_format($ULS['kyc_pending']),'sub'=>$ULS['kyc_approved'].' approved','colour'=>'amber','icon'=>'fa-id-card'],
                ['label'=>'No KYC Yet','value'=>number_format($ULS['kyc_none']),'sub'=>'Never submitted','colour'=>'rose','icon'=>'fa-user-slash'],
                ['label'=>'Subscribed','value'=>number_format($ULS['sub']),'sub'=>$ULS['blocked'].' blocked','colour'=>'violet','icon'=>'fa-crown'],
            ]); ?>
            <div class="grid grid-cols-2 gap-2.5 mb-5">
                <div class="al-stat"><div class="al-stat-ico bg-slate-50 text-slate-600 border-slate-100"><i class="fas fa-wallet"></i></div>
                    <div><p class="al-stat-k">Total Main Wallet</p><p class="al-stat-v text-slate-700">₹<?php echo number_format($ULS['wallet'], 2); ?></p></div></div>
                <div class="al-stat"><div class="al-stat-ico bg-amber-50 text-amber-600 border-amber-100"><i class="fas fa-gift"></i></div>
                    <div><p class="al-stat-k">Total Virtual Wallet</p><p class="al-stat-v text-amber-600">₹<?php echo number_format($ULS['virtual'], 2); ?></p></div></div>
            </div>

            <?php echo alist_banner('user_list.php', 'users', $UL, $UL_DEFAULTS, [
                'search'=>'Search','kyc'=>'KYC','sub'=>'Subscription','status'=>'Status',
                'joined'=>'Joined','wallet'=>'Wallet','types'=>'User type']); ?>

            <!-- ===== FILTERS ===== -->
            <form method="GET" class="al-panel p-3 mb-5">
                <input type="hidden" name="f" value="users">
                <div class="grid grid-cols-2 lg:grid-cols-4 xl:grid-cols-7 gap-2 items-end">
                    <div class="col-span-2">
                        <label class="al-l">Search</label>
                        <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="search" value="<?php echo htmlspecialchars($UL['search']); ?>" placeholder="ID, code, name, phone or email" class="al-f pl-9">
                        </div>
                    </div>
                    <div><label class="al-l">User Type</label>
                        <select name="types" class="al-f">
                            <option value="customer,seller,admin" <?php echo $UL['types']==='customer,seller,admin'?'selected':''; ?>>All types</option>
                            <option value="customer" <?php echo $UL['types']==='customer'?'selected':''; ?>>Customers only</option>
                            <option value="seller"   <?php echo $UL['types']==='seller'?'selected':''; ?>>Sellers only</option>
                            <option value="admin"    <?php echo $UL['types']==='admin'?'selected':''; ?>>Staff only</option>
                        </select></div>
                    <div><label class="al-l">KYC</label>
                        <select name="kyc" class="al-f">
                            <option value="">Any</option>
                            <option value="pending"  <?php echo $UL['kyc']==='pending'?'selected':''; ?>>Pending</option>
                            <option value="approved" <?php echo $UL['kyc']==='approved'?'selected':''; ?>>Approved</option>
                            <option value="rejected" <?php echo $UL['kyc']==='rejected'?'selected':''; ?>>Rejected</option>
                            <option value="none"     <?php echo $UL['kyc']==='none'?'selected':''; ?>>Not submitted</option>
                        </select></div>
                    <div><label class="al-l">Subscription</label>
                        <select name="sub" class="al-f">
                            <option value="">Any</option>
                            <option value="yes" <?php echo $UL['sub']==='yes'?'selected':''; ?>>Subscribed</option>
                            <option value="no"  <?php echo $UL['sub']==='no'?'selected':''; ?>>Not subscribed</option>
                        </select></div>
                    <div><label class="al-l">Account</label>
                        <select name="status" class="al-f">
                            <option value="">Any</option>
                            <option value="1" <?php echo $UL['status']==='1'?'selected':''; ?>>Active</option>
                            <option value="0" <?php echo $UL['status']==='0'?'selected':''; ?>>Blocked</option>
                        </select></div>
                    <div><label class="al-l">Joined</label>
                        <select name="joined" class="al-f">
                            <option value="">Any time</option>
                            <option value="today" <?php echo $UL['joined']==='today'?'selected':''; ?>>Today</option>
                            <option value="7"     <?php echo $UL['joined']==='7'?'selected':''; ?>>Last 7 days</option>
                            <option value="30"    <?php echo $UL['joined']==='30'?'selected':''; ?>>Last 30 days</option>
                            <option value="month" <?php echo $UL['joined']==='month'?'selected':''; ?>>This month</option>
                        </select></div>
                    <div><label class="al-l">Wallet</label>
                        <select name="wallet" class="al-f">
                            <option value="">Any</option>
                            <option value="nonzero" <?php echo $UL['wallet']==='nonzero'?'selected':''; ?>>Has balance</option>
                            <option value="zero"    <?php echo $UL['wallet']==='zero'?'selected':''; ?>>Zero balance</option>
                        </select></div>
                    <div class="col-span-2 lg:col-span-1 flex gap-2">
                        <button class="al-btn al-btn-apply flex-1"><i class="fas fa-filter"></i> Apply</button>
                        <a href="user_list.php?reset=1" class="al-btn al-btn-ghost">Reset</a>
                    </div>
                    <div class="col-span-2 lg:col-span-1">
                        <a href="<?php echo alist_url('user_list.php','users',$UL,['export'=>1]); ?>" class="al-btn al-btn-csv w-full"><i class="fas fa-file-csv"></i> Export CSV</a>
                    </div>
                </div>
                <p class="text-[11px] text-slate-400 mt-2">
                    Showing <b class="text-slate-600"><?php echo count($customers); ?></b> user(s).
                    Filters stay applied until you press Reset.
                </p>
            </form>

            <?php if ($success_msg): ?>
                <div class="mb-4 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-4 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; ?>

            <?php echo alist_styles(); ?>
            <!-- ===== DESKTOP TABLE ===== -->
            <div class="hidden lg:block bg-white rounded-2xl shadow-sm border-2 border-slate-300 overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="ul w-full text-left border-collapse text-xs">
                        <thead>
                            <tr class="bg-slate-50 text-[10px] uppercase text-slate-500 tracking-wider">
                                <th class="p-3 font-semibold border-b border-gray-200">Profile</th>
                                <th class="p-3 font-semibold border-b border-gray-200">User Details</th>
                                <th class="p-3 font-semibold border-b border-gray-200">Village / Locality<br>Post Office<br>Block / City / Municipality<br>Landmark</th>
                                <th class="p-3 font-semibold border-b border-gray-200">State, District,<br>Pin Code</th>
                                <th class="p-3 font-semibold border-b border-gray-200">User Type,<br>Date &amp; Time</th>
                                <th class="p-3 font-semibold border-b border-gray-200">Created By</th>
                                <th class="p-3 font-semibold border-b border-gray-200">KYC Status</th>
                                <th class="p-3 font-semibold border-b border-gray-200">Subscription</th>
                                <th class="p-3 font-semibold border-b border-gray-200">Balance</th>
                                <th class="p-3 font-semibold border-b border-gray-200 min-w-[140px]">Transfer</th>
                                <th class="p-3 font-semibold border-b border-gray-200 min-w-[110px]">Quick Response</th>
                                <th class="p-3 font-semibold border-b border-gray-200 min-w-[110px]">Notes</th>
                                <th class="p-3 font-semibold border-b border-gray-200 min-w-[120px]">Update</th>
                                <th class="p-3 font-semibold border-b border-gray-200 min-w-[130px]">Action</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100">
                        <?php if(!empty($customers)): foreach($customers as $c):
                            $code = userCode($c['id']);
                            $call = !empty($c['call_number']) ? $c['call_number'] : $c['mobile'];
                            $wa   = !empty($c['whatsapp_number']) ? $c['whatsapp_number'] : $c['mobile'];
                            // Address: prefer KYC-submitted address, else registration data
                            $has_kyc   = !empty($c['kyc_id']);
                            $pick = function($kkey, $ukey) use ($c, $has_kyc) {
                                if ($has_kyc && !empty($c[$kkey])) return $c[$kkey];
                                return $c[$ukey] ?? '';
                            };
                            $a_village = $pick('k_village', 'village');
                            $a_post    = $pick('k_post_office', 'post_office');
                            $a_block   = $pick('k_block_city', 'block_city');
                            $a_land    = $pick('k_landmark', 'landmark');
                            $a_state   = $pick('k_state', 'state');
                            $a_dist    = $pick('k_district', 'district');
                            $a_pin     = $pick('k_pincode', 'pincode');
                            $kyc_status = $c['kyc_status'] ?? '';
                            $jsName = htmlspecialchars(addslashes($c['name']), ENT_QUOTES);
                        ?>
                            <tr class="hover:bg-slate-50/50 transition align-top">
                                <!-- PROFILE (existing: profile_pic) -->
                                <td class="p-3">
                                    <?php if(!empty($c['profile_pic']) && file_exists('../uploads/profiles/'.$c['profile_pic'])): ?>
                                        <img src="../uploads/profiles/<?php echo $c['profile_pic']; ?>" class="w-12 h-12 rounded-lg object-cover border border-gray-200">
                                    <?php else: ?>
                                        <div class="w-12 h-12 rounded-lg bg-indigo-100 text-indigo-600 flex items-center justify-center font-bold"><?php echo strtoupper(substr($c['name'],0,1)); ?></div>
                                    <?php endif; ?>
                                </td>
                                <!-- USER DETAILS (existing: code, name, mobile, email) -->
                                <td class="p-3">
                                    <p class="font-bold text-slate-800"><?php echo $code; ?></p>
                                    <p class="font-semibold text-slate-700 uppercase"><?php echo htmlspecialchars($c['name']); ?></p>
                                    <p class="text-slate-500"><?php echo htmlspecialchars($c['mobile']); ?></p>
                                    <p class="text-slate-500 lowercase"><?php echo htmlspecialchars($c['email']); ?></p>
                                </td>
                                <!-- ADDRESS BLOCK (from KYC if submitted, else registration) -->
                                <td class="p-3 text-slate-700 leading-5">
                                    <p><?php echo !empty($a_village) ? htmlspecialchars($a_village) : '<span class="text-slate-300">—</span>'; ?></p>
                                    <p><?php echo !empty($a_post) ? htmlspecialchars($a_post) : '<span class="text-slate-300">—</span>'; ?></p>
                                    <p><?php echo !empty($a_block) ? htmlspecialchars($a_block) : '<span class="text-slate-300">—</span>'; ?></p>
                                    <p class="text-slate-500"><?php echo !empty($a_land) ? htmlspecialchars($a_land) : '<span class="text-slate-300">—</span>'; ?></p>
                                </td>
                                <!-- STATE / DISTRICT / PIN (from KYC if submitted, else registration) -->
                                <td class="p-3 text-slate-700">
                                    <p class="font-semibold"><?php echo !empty($a_state) ? htmlspecialchars($a_state) : '<span class="text-slate-400">—</span>'; ?></p>
                                    <p><?php echo !empty($a_dist) ? htmlspecialchars($a_dist) : '<span class="text-slate-400">—</span>'; ?></p>
                                    <p class="text-slate-500"><?php echo !empty($a_pin) ? htmlspecialchars($a_pin) : '<span class="text-slate-400">—</span>'; ?></p>
                                </td>
                                <!-- USER TYPE + DATE/TIME (existing) ; "Approved" line is # -->
                                <td class="p-3">
                                    <?php
                                        $utype = $type_labels[$c['user_type']] ?? ucfirst($c['user_type']);
                                        $utype_col = $c['user_type']==='customer' ? 'text-blue-600' : ($c['user_type']==='seller' ? 'text-emerald-600' : 'text-purple-600');
                                    ?>
                                    <p class="font-semibold uppercase <?php echo $utype_col; ?>"><?php echo $utype; ?></p>
                                    <p class="text-slate-500"><?php echo date('d/m/Y', strtotime($c['created_at'])); ?></p>
                                    <p class="text-slate-500"><?php echo date('h:i A', strtotime($c['created_at'])); ?></p>
                                    <?php $__act = ((int)($c['status'] ?? 1) === 1); ?>
                                    <span class="inline-block mt-1 px-2 py-0.5 rounded-full text-[9px] font-black uppercase <?php echo $__act ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700'; ?>">
                                        <?php echo $__act ? 'Approved' : 'Blocked'; ?>
                                    </span>
                                </td>
                                <!-- CREATED BY (existing: referred_by -> referrer user) -->
                                <td class="p-3">
                                    <?php if(!empty($c['ref_id'])): ?>
                                        <p class="font-bold text-slate-800"><?php echo userCode($c['ref_id']); ?></p>
                                        <p class="text-slate-600 uppercase"><?php echo htmlspecialchars($c['ref_name']); ?></p>
                                    <?php else: ?>
                                        <span class="text-slate-400 text-[11px]">Direct / Self</span>
                                    <?php endif; ?>
                                </td>
                                <!-- KYC STATUS (from kyc_details; click to review) -->
                                <td class="p-3">
                                    <?php
                                        $kyc_map = [
                                            'approved' => ['Approved', 'bg-emerald-100 text-emerald-700 border-emerald-200'],
                                            'pending'  => ['Pending',  'bg-amber-100 text-amber-700 border-amber-200'],
                                            'rejected' => ['Rejected', 'bg-rose-100 text-rose-700 border-rose-200'],
                                        ];
                                    ?>
                                    <?php if($has_kyc && isset($kyc_map[$kyc_status])): ?>
                                        <button type="button" @click="openKyc(<?php echo $c['id']; ?>, '<?php echo $jsName ?? ''; ?>')" class="text-[10px] font-bold px-2.5 py-1 rounded-full uppercase border whitespace-nowrap <?php echo $kyc_map[$kyc_status][1]; ?> hover:shadow">
                                            <?php echo $kyc_map[$kyc_status][0]; ?> <i class="fas fa-eye ml-0.5"></i>
                                        </button>
                                    <?php else: ?>
                                        <span class="text-[10px] font-bold px-2.5 py-1 rounded-full uppercase border bg-slate-100 text-slate-400 border-slate-200 whitespace-nowrap">Not submitted</span>
                                    <?php endif; ?>
                                </td>
                                <!-- SUBSCRIPTION (existing: is_subscribed) -->
                                <td class="p-3">
                                    <?php if(!empty($c['is_subscribed']) && $c['is_subscribed'] == 1): ?>
                                        <span class="bg-emerald-100 text-emerald-700 text-[10px] font-bold px-2.5 py-1 rounded-full uppercase border border-emerald-200">Yes</span>
                                    <?php else: ?>
                                        <span class="bg-slate-100 text-slate-500 text-[10px] font-bold px-2.5 py-1 rounded-full uppercase border border-slate-200">No</span>
                                    <?php endif; ?>
                                </td>
                                <!-- BALANCE (existing: wallet_balance) -->
                                <td class="p-3">
                                    <span class="font-bold text-emerald-600 whitespace-nowrap">₹<?php echo number_format($c['wallet_balance'], 2); ?></span>
                                </td>
                                <!-- TRANSFER (existing: credit wallet + log txn ; Transfer Type = #) -->
                                <td class="p-3">
                                    <button type="button" @click="openMoney(<?php echo (int)$c['id']; ?>, '<?php echo htmlspecialchars(addslashes($c['name']), ENT_QUOTES); ?>', <?php echo (float)$c['wallet_balance']; ?>, <?php echo (float)($c['bonus_wallet'] ?? 0); ?>)"
                                            class="cell-btn bg-blue-600 hover:bg-blue-700 w-full"><i class="fas fa-right-left mr-1"></i>Credit / Debit</button>
                                </td>
                                <!-- QUICK RESPONSE (existing: call/whatsapp/email links ; Chatbot = #) -->
                                <td class="p-3 space-y-1">
                                    <a href="tel:<?php echo htmlspecialchars($call); ?>" class="cell-btn bg-slate-500 hover:bg-slate-600"><i class="fas fa-phone-alt mr-1"></i>Call</a>
                                    <a href="https://wa.me/91<?php echo preg_replace('/\D/','',$wa); ?>" target="_blank" class="cell-btn bg-green-500 hover:bg-green-600"><i class="fab fa-whatsapp mr-1"></i>Whatsapp</a>
                                    <a href="mailto:<?php echo htmlspecialchars($c['email']); ?>" class="cell-btn bg-rose-600 hover:bg-rose-700"><i class="fas fa-envelope mr-1"></i>Email</a>
                                    <span class="cell-btn bg-purple-300 cursor-not-allowed" title="# Chatbot integration pending"># Chatbot</span>
                                </td>
                                <!-- NOTES (working: user_notes table) -->
                                <td class="p-3 space-y-1">
                                    <button type="button" @click="openNotesHistory(<?php echo $c['id']; ?>, '<?php echo $jsName; ?>')" class="cell-btn bg-cyan-500 hover:bg-cyan-600"><i class="fas fa-clock-rotate-left mr-1"></i>History</button>
                                    <button type="button" @click="openNewNote(<?php echo $c['id']; ?>, '<?php echo $jsName; ?>')" class="cell-btn bg-amber-500 hover:bg-amber-600"><i class="fas fa-plus mr-1"></i>New Notes</button>
                                </td>
                                <!-- UPDATE (working: update form, history log, reset password) -->
                                <td class="p-3 space-y-1">
                                    <button type="button" @click="openUpdateHistory(<?php echo $c['id']; ?>, '<?php echo $jsName; ?>')" class="cell-btn bg-orange-500 hover:bg-orange-600"><i class="fas fa-clock-rotate-left mr-1"></i>Update History</button>
                                    <button type="button" @click="openUpdateForm(<?php echo $c['id']; ?>, '<?php echo $jsName; ?>')" class="cell-btn bg-lime-600 hover:bg-lime-700"><i class="fas fa-pen mr-1"></i>Update</button>
                                    <button type="button" @click="openReset(<?php echo $c['id']; ?>, '<?php echo $jsName; ?>')" class="cell-btn bg-red-600 hover:bg-red-700"><i class="fas fa-key mr-1"></i>Reset Password</button>
                                </td>
                                <!-- ACTION (account status + role change) -->
                                <td class="p-3 space-y-1">
                                    <?php $__ok = ((int)($c['status'] ?? 1) === 1); ?>
                                    <span class="cell-btn <?php echo $__ok ? 'bg-emerald-500' : 'bg-rose-500'; ?> cursor-default">
                                        <i class="fas <?php echo $__ok ? 'fa-circle-check' : 'fa-ban'; ?> mr-1"></i><?php echo $__ok ? 'Approved' : 'Blocked'; ?>
                                    </span>
                                    <form method="POST" onsubmit="return confirm('Change this user type?');" class="space-y-1">
                                        <input type="hidden" name="target_user_id" value="<?php echo $c['id']; ?>">
                                        <select name="new_role" class="w-full border border-gray-300 rounded px-2 py-1 text-xs">
                                            <option value="customer">Customer</option>
                                            <option value="seller">Seller</option>
                                        </select>
                                        <button type="submit" name="change_role" class="cell-btn bg-blue-600 hover:bg-blue-700">SUBMIT</button>
                                    </form>
                                    <form method="POST" class="pt-1">
                                        <input type="hidden" name="target_user_id" value="<?php echo $c['id']; ?>">
                                        <input type="hidden" name="current_status" value="<?php echo $c['status']; ?>">
                                        <button type="submit" name="toggle_status" class="cell-btn <?php echo $c['status']==1 ? 'bg-emerald-500 hover:bg-emerald-600' : 'bg-rose-500 hover:bg-rose-600'; ?>">
                                            <?php echo $c['status']==1 ? 'Active (Suspend)' : 'Suspended (Activate)'; ?>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; else: ?>
                            <tr><td colspan="14" class="p-12 text-center text-gray-500">
                                <div class="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4 text-gray-400 text-2xl border border-gray-100"><i class="fas fa-users-slash"></i></div>
                                <p class="text-lg font-medium">No users found.</p>
                            </td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- ===== MOBILE / TABLET CARDS ===== -->
            <div class="lg:hidden space-y-3">
            <?php if(!empty($customers)): foreach($customers as $c):
                $mcall = !empty($c['call_number']) ? $c['call_number'] : $c['mobile'];
                $mwa   = !empty($c['whatsapp_number']) ? $c['whatsapp_number'] : $c['mobile'];
                $mact  = ((int)($c['status'] ?? 1) === 1);
                $mtype = $type_labels[$c['user_type']] ?? ucfirst($c['user_type']);
                $mtcol = $c['user_type']==='customer' ? 'blue' : ($c['user_type']==='seller' ? 'emerald' : 'purple');
                $mkyc  = $c['kyc_status'] ?? '';
                $mkcol = $mkyc==='approved' ? 'emerald' : ($mkyc==='pending' ? 'amber' : ($mkyc==='rejected' ? 'rose' : 'slate'));
                $mvill = $c['k_village'] ?: ($c['village'] ?? '');
                $mdist = $c['k_district'] ?: ($c['district'] ?? '');
                $mstate= $c['k_state'] ?: ($c['state'] ?? '');
                $mpin  = $c['k_pincode'] ?: ($c['pincode'] ?? '');
                $maddr = trim(implode(', ', array_filter([$mvill, $mdist, $mstate, $mpin])));
            ?>
                <div class="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
                    <!-- header -->
                    <div class="p-3.5 flex items-start gap-3 border-b border-slate-100">
                        <div class="w-11 h-11 rounded-xl bg-slate-100 flex items-center justify-center text-sm font-black text-slate-500 flex-shrink-0 overflow-hidden">
                            <?php if(!empty($c['profile_pic'])): ?>
                                <img src="../uploads/profiles/<?php echo htmlspecialchars($c['profile_pic']); ?>" class="w-full h-full object-cover" alt="">
                            <?php else: ?><?php echo strtoupper(substr($c['name'], 0, 2)); ?><?php endif; ?>
                        </div>
                        <div class="min-w-0 flex-1">
                            <div class="flex flex-wrap items-center gap-1.5 mb-0.5">
                                <span class="font-mono text-[10px] font-bold text-slate-400"><?php echo userCode($c['id']); ?></span>
                                <span class="px-1.5 py-0.5 rounded text-[9px] font-black uppercase bg-<?php echo $mtcol; ?>-50 text-<?php echo $mtcol; ?>-600"><?php echo $mtype; ?></span>
                                <span class="px-1.5 py-0.5 rounded text-[9px] font-black uppercase <?php echo $mact ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700'; ?>"><?php echo $mact ? 'Approved' : 'Blocked'; ?></span>
                            </div>
                            <p class="font-extrabold text-slate-800 text-sm leading-tight truncate"><?php echo htmlspecialchars($c['name']); ?></p>
                            <p class="text-[11px] text-slate-500 truncate"><?php echo htmlspecialchars($c['mobile']); ?><?php if(!empty($c['email'])): ?> · <?php echo htmlspecialchars($c['email']); ?><?php endif; ?></p>
                        </div>
                    </div>

                    <!-- facts -->
                    <div class="grid grid-cols-2 gap-px bg-slate-100">
                        <div class="bg-white p-2.5">
                            <p class="text-[9px] font-black uppercase tracking-wider text-slate-400">Main Wallet</p>
                            <p class="text-sm font-black text-emerald-600">₹<?php echo number_format((float)$c['wallet_balance'], 2); ?></p>
                        </div>
                        <div class="bg-white p-2.5">
                            <p class="text-[9px] font-black uppercase tracking-wider text-slate-400">Virtual Wallet</p>
                            <p class="text-sm font-black text-amber-600">₹<?php echo number_format((float)($c['bonus_wallet'] ?? 0), 2); ?></p>
                        </div>
                        <div class="bg-white p-2.5">
                            <p class="text-[9px] font-black uppercase tracking-wider text-slate-400">KYC</p>
                            <p class="text-[11px] font-bold text-<?php echo $mkcol; ?>-600 capitalize"><?php echo $mkyc ?: 'not submitted'; ?></p>
                        </div>
                        <div class="bg-white p-2.5">
                            <p class="text-[9px] font-black uppercase tracking-wider text-slate-400">Subscription</p>
                            <p class="text-[11px] font-bold <?php echo !empty($c['is_subscribed']) ? 'text-fuchsia-600' : 'text-slate-400'; ?>"><?php echo !empty($c['is_subscribed']) ? 'Subscribed' : 'Not subscribed'; ?></p>
                        </div>
                    </div>

                    <?php if($maddr !== '' || !empty($c['ref_id'])): ?>
                    <div class="px-3 py-2 border-t border-slate-100 space-y-0.5">
                        <?php if($maddr !== ''): ?>
                            <p class="text-[10px] text-slate-500"><i class="fas fa-location-dot w-3 text-slate-300 mr-1"></i><?php echo htmlspecialchars($maddr); ?></p>
                        <?php endif; ?>
                        <?php if(!empty($c['ref_id'])): ?>
                            <p class="text-[10px] text-slate-500"><i class="fas fa-user-plus w-3 text-slate-300 mr-1"></i>Referred by <b><?php echo htmlspecialchars($c['ref_name']); ?></b> (<?php echo userCode($c['ref_id']); ?>)</p>
                        <?php endif; ?>
                        <p class="text-[10px] text-slate-400"><i class="fas fa-clock w-3 text-slate-300 mr-1"></i>Joined <?php echo date('d M Y, h:i A', strtotime($c['created_at'])); ?></p>
                    </div>
                    <?php endif; ?>

                    <!-- actions -->
                    <div class="p-2.5 border-t border-slate-100 bg-slate-50/60 space-y-2">
                        <button type="button" @click="openMoney(<?php echo (int)$c['id']; ?>, '<?php echo htmlspecialchars(addslashes($c['name']), ENT_QUOTES); ?>', <?php echo (float)$c['wallet_balance']; ?>, <?php echo (float)($c['bonus_wallet'] ?? 0); ?>)"
                                class="w-full py-2.5 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold">
                            <i class="fas fa-right-left mr-1.5"></i>Credit / Debit
                        </button>

                        <div class="grid grid-cols-3 gap-1.5">
                            <a href="tel:<?php echo htmlspecialchars($mcall); ?>" class="py-2 rounded-lg bg-white border border-slate-200 text-slate-600 text-[11px] font-bold text-center"><i class="fas fa-phone"></i></a>
                            <a href="https://wa.me/91<?php echo preg_replace('/\D/','',$mwa); ?>" target="_blank" class="py-2 rounded-lg bg-green-500 text-white text-[11px] font-bold text-center"><i class="fab fa-whatsapp"></i></a>
                            <a href="mailto:<?php echo htmlspecialchars($c['email']); ?>" class="py-2 rounded-lg bg-rose-500 text-white text-[11px] font-bold text-center"><i class="fas fa-envelope"></i></a>
                        </div>

                        <div class="grid grid-cols-2 gap-1.5">
                            <button type="button" @click="openUpdateForm(<?php echo $c['id']; ?>, '<?php echo htmlspecialchars(addslashes($c['name']), ENT_QUOTES); ?>')" class="py-2 rounded-lg bg-lime-600 text-white text-[11px] font-bold"><i class="fas fa-pen mr-1"></i>Update</button>
                            <button type="button" @click="openUpdateHistory(<?php echo $c['id']; ?>, '<?php echo htmlspecialchars(addslashes($c['name']), ENT_QUOTES); ?>')" class="py-2 rounded-lg bg-orange-500 text-white text-[11px] font-bold"><i class="fas fa-clock-rotate-left mr-1"></i>History</button>
                            <button type="button" @click="openNewNote(<?php echo $c['id']; ?>, '<?php echo htmlspecialchars(addslashes($c['name']), ENT_QUOTES); ?>')" class="py-2 rounded-lg bg-amber-500 text-white text-[11px] font-bold"><i class="fas fa-plus mr-1"></i>Note</button>
                            <button type="button" @click="openNotesHistory(<?php echo $c['id']; ?>, '<?php echo htmlspecialchars(addslashes($c['name']), ENT_QUOTES); ?>')" class="py-2 rounded-lg bg-cyan-500 text-white text-[11px] font-bold"><i class="fas fa-note-sticky mr-1"></i>Notes</button>
                        </div>

                        <form method="POST">
                            <input type="hidden" name="target_user_id" value="<?php echo $c['id']; ?>">
                            <input type="hidden" name="current_status" value="<?php echo $c['status']; ?>">
                            <button type="submit" name="toggle_status" class="w-full py-2 rounded-lg text-white text-[11px] font-bold <?php echo $mact ? 'bg-emerald-500' : 'bg-rose-500'; ?>">
                                <?php echo $mact ? 'Active — tap to suspend' : 'Suspended — tap to activate'; ?>
                            </button>
                        </form>
                    </div>
                </div>
            <?php endforeach; else: ?>
                <div class="bg-white rounded-2xl border border-slate-200 p-12 text-center text-slate-400">
                    <i class="fas fa-users-slash text-3xl mb-3 block text-slate-300"></i>
                    <p class="text-sm font-semibold text-slate-500">No users found</p>
                </div>
            <?php endif; ?>
            </div>

            <div class="mt-4 bg-emerald-50 border border-emerald-200 rounded-xl p-4 text-xs text-emerald-800">
                <p class="font-bold mb-1"><i class="fas fa-circle-check mr-1"></i> Everything on this page is live</p>
                <p>Address, KYC, Subscription, Balance, Notes and Update History all read real data.
                   <b>Credit / Debit</b> now asks for a mandatory reason, and the account status column shows
                   <b>Approved</b> or <b>Blocked</b> from the user's real status.
                   Only <b>Chatbot</b> is still pending.</p>
            </div>
        </main>
    </div>
</div>

<!-- ================================================================
     MODALS  (Notes History / New Note / Update History / Update / Reset)
     ================================================================ -->
<template x-teleport="body">
<div x-show="modal" x-transition.opacity class="fixed inset-0 z-[100] flex items-center justify-center p-4" style="display:none;">
    <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="close()"></div>

    <!-- ===== NOTES HISTORY ===== -->
    <!-- ================= CREDIT / DEBIT ================= -->
    <div x-show="modal==='money'" x-transition class="relative w-full sm:max-w-md 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="money.action === 'credit' ? 'background:linear-gradient(135deg,#059669,#047857)' : 'background:linear-gradient(135deg,#e11d48,#be123c)'">
            <div class="min-w-0">
                <h3 class="text-white font-bold text-base"><i class="fas fa-right-left mr-2"></i><span x-text="money.action === 'credit' ? 'Credit Wallet' : 'Debit Wallet'"></span></h3>
                <p class="text-white/70 text-[11px] truncate" x-text="money.name + ' (ID ' + money.id + ')'"></p>
            </div>
            <button @click="modal=null" class="text-white/70 hover:text-white text-3xl leading-none">&times;</button>
        </div>

        <form method="POST" class="p-5 overflow-y-auto space-y-4">
            <input type="hidden" name="target_user_id" :value="money.id">
            <input type="hidden" name="transfer_action" :value="money.action">
            <input type="hidden" name="transfer_wallet" :value="money.wallet">

            <div class="grid grid-cols-2 gap-2">
                <button type="button" @click="money.action='credit'"
                        class="py-2.5 rounded-xl text-xs font-black border-2 transition-all"
                        :class="money.action==='credit' ? 'border-emerald-500 bg-emerald-50 text-emerald-700' : 'border-slate-200 text-slate-500'">
                    <i class="fas fa-plus mr-1"></i> CREDIT
                </button>
                <button type="button" @click="money.action='debit'"
                        class="py-2.5 rounded-xl text-xs font-black border-2 transition-all"
                        :class="money.action==='debit' ? 'border-rose-500 bg-rose-50 text-rose-700' : 'border-slate-200 text-slate-500'">
                    <i class="fas fa-minus mr-1"></i> DEBIT
                </button>
            </div>

            <div>
                <label class="al-l">Which wallet</label>
                <div class="grid grid-cols-2 gap-2">
                    <button type="button" @click="money.wallet='main'"
                            class="p-2.5 rounded-xl border-2 text-left transition-all"
                            :class="money.wallet==='main' ? 'border-indigo-500 bg-indigo-50' : 'border-slate-200'">
                        <span class="block text-[10px] font-bold uppercase text-slate-400">Main</span>
                        <span class="block text-sm font-black text-slate-800">₹<span x-text="money.main.toFixed(2)"></span></span>
                    </button>
                    <button type="button" @click="money.wallet='virtual'"
                            class="p-2.5 rounded-xl border-2 text-left transition-all"
                            :class="money.wallet==='virtual' ? 'border-amber-500 bg-amber-50' : 'border-slate-200'">
                        <span class="block text-[10px] font-bold uppercase text-slate-400">Virtual</span>
                        <span class="block text-sm font-black text-amber-600">₹<span x-text="money.virtual.toFixed(2)"></span></span>
                    </button>
                </div>
            </div>

            <div>
                <label class="al-l">Amount (₹) <span class="text-rose-500">*</span></label>
                <div class="relative">
                    <span class="absolute left-0 top-0 bottom-0 w-10 flex items-center justify-center text-slate-400 font-bold text-base pointer-events-none">₹</span>
                    <input type="number" step="0.01" min="0.01" name="transfer_amount" x-model.number="money.amount" required
                           inputmode="decimal" placeholder="0.00" class="al-f pl-10 text-base font-black"
                           :class="moneyErr() && 'border-rose-400 bg-rose-50'">
                </div>
                <p x-show="moneyErr()" x-cloak class="text-[11px] font-bold text-rose-600 mt-1"><i class="fas fa-circle-exclamation mr-1"></i><span x-text="moneyErr()"></span></p>
                <p x-show="money.amount > 0 && !moneyErr()" x-cloak class="text-[11px] text-slate-500 mt-1">
                    Balance after: <b class="text-slate-800">₹<span x-text="moneyAfter().toFixed(2)"></span></b>
                </p>
            </div>

            <div>
                <label class="al-l">Reason <span class="text-rose-500">*</span></label>
                <input name="transfer_reason" x-model="money.reason" required maxlength="150"
                       placeholder="Why is this being credited / debited?" class="al-f">
                <div class="flex flex-wrap gap-1.5 mt-2">
                    <template x-for="r in (money.action === 'credit' ? reasonsCredit : reasonsDebit)" :key="r">
                        <button type="button" @click="money.reason = r"
                                class="px-2.5 py-1 rounded-lg bg-slate-100 hover:bg-slate-200 text-[10.5px] font-bold text-slate-600" x-text="r"></button>
                    </template>
                </div>
            </div>

            <div>
                <label class="al-l">Extra note <span class="text-slate-400 font-normal normal-case">(optional)</span></label>
                <input name="transfer_note" maxlength="150" placeholder="Order id, ticket no, anything useful" class="al-f">
            </div>

            <div class="bg-slate-50 border border-slate-200 rounded-xl p-3 text-[11px] text-slate-600">
                <i class="fas fa-circle-info mr-1"></i> The reason is <b>required</b>. It is saved in the wallet history,
                the user's update history, and sent to the user as a notification.
            </div>

            <div class="flex gap-2">
                <button type="button" @click="modal=null" class="al-btn al-btn-ghost flex-1 py-3">Cancel</button>
                <button type="submit" name="wallet_transfer" :disabled="!moneyOk()"
                        class="al-btn flex-[2] py-3 text-white disabled:opacity-40 disabled:cursor-not-allowed"
                        :style="money.action === 'credit' ? 'background:#059669' : 'background:#e11d48'">
                    <i class="fas fa-check"></i> <span x-text="(money.action === 'credit' ? 'Credit ₹' : 'Debit ₹') + (Number(money.amount)||0).toFixed(2)"></span>
                </button>
            </div>
        </form>
    </div>

    <div x-show="modal==='notesHistory'" x-transition class="relative w-full max-w-lg bg-white rounded-2xl shadow-2xl overflow-hidden">
        <div class="bg-gradient-to-r from-cyan-500 to-blue-500 px-5 py-4 flex items-center justify-between">
            <h3 class="text-white font-bold text-lg"><i class="fas fa-clock-rotate-left mr-2"></i>Notes History</h3>
            <button @click="close()" class="text-white/80 hover:text-white text-xl"><i class="fas fa-times"></i></button>
        </div>
        <div class="px-5 py-2 bg-cyan-50 text-cyan-800 text-xs font-semibold border-b border-cyan-100"><i class="fas fa-user mr-1"></i><span x-text="curUser.name"></span></div>
        <div class="p-5 max-h-[60vh] overflow-y-auto">
            <template x-if="loading"><p class="text-center text-slate-400 py-6"><i class="fas fa-spinner fa-spin mr-2"></i>Loading...</p></template>
            <!-- List view -->
            <div x-show="!loading && !viewNote">
                <template x-if="notes.length===0"><p class="text-center text-slate-400 py-8"><i class="fas fa-note-sticky text-2xl mb-2 block"></i>No notes yet for this user.</p></template>
                <div class="space-y-2">
                    <template x-for="n in notes" :key="n.id">
                        <div class="flex items-center justify-between gap-3 p-3 rounded-xl border border-slate-100 bg-slate-50 hover:bg-slate-100 transition">
                            <div class="min-w-0">
                                <p class="font-bold text-slate-800 truncate" x-text="n.title"></p>
                                <p class="text-xs text-slate-500 mt-0.5">
                                    <i class="fas fa-user-pen mr-1"></i><span class="font-semibold text-indigo-600" x-text="n.created_by_name || 'Unknown'"></span>
                                    <span class="mx-1">•</span><span x-text="fmtDate(n.created_at)"></span>
                                </p>
                            </div>
                            <button @click="viewNote=n" class="flex-shrink-0 text-xs font-bold text-white bg-cyan-500 hover:bg-cyan-600 px-3 py-1.5 rounded-lg"><i class="fas fa-eye mr-1"></i>View</button>
                        </div>
                    </template>
                </div>
            </div>
            <!-- Single note view -->
            <div x-show="viewNote" class="space-y-3">
                <button @click="viewNote=null" class="text-xs font-semibold text-slate-500 hover:text-cyan-600"><i class="fas fa-arrow-left mr-1"></i>Back to list</button>
                <h4 class="text-lg font-bold text-slate-800" x-text="viewNote?.title"></h4>
                <p class="text-xs text-slate-500"><i class="fas fa-user-pen mr-1"></i><span x-text="viewNote?.created_by_name"></span> <span class="mx-1">•</span> <span x-text="fmtDate(viewNote?.created_at)"></span></p>
                <div class="bg-slate-50 border border-slate-100 rounded-xl p-4 text-sm text-slate-700 whitespace-pre-wrap" x-text="viewNote?.description || '(no description)'"></div>
            </div>
        </div>
    </div>

    <!-- ===== NEW NOTE ===== -->
    <div x-show="modal==='newNote'" x-transition class="relative w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden">
        <div class="bg-gradient-to-r from-amber-500 to-orange-500 px-5 py-4 flex items-center justify-between">
            <h3 class="text-white font-bold text-lg"><i class="fas fa-plus mr-2"></i>New Note</h3>
            <button @click="close()" class="text-white/80 hover:text-white text-xl"><i class="fas fa-times"></i></button>
        </div>
        <form method="POST" class="p-5 space-y-4">
            <input type="hidden" name="target_user_id" :value="curUser.id">
            <div>
                <label class="block text-xs font-semibold text-slate-600 mb-1">Note Title <span class="text-rose-500">*</span></label>
                <input name="note_title" required maxlength="255" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-amber-400" placeholder="e.g. Called about pending KYC">
            </div>
            <div>
                <label class="block text-xs font-semibold text-slate-600 mb-1">Description</label>
                <textarea name="note_description" rows="4" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-amber-400" placeholder="Write the note details..."></textarea>
            </div>
            <div class="flex justify-end gap-2 pt-1">
                <button type="button" @click="close()" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-100 rounded-lg">Cancel</button>
                <button type="submit" name="add_note" class="px-5 py-2 text-sm font-bold text-white bg-amber-500 hover:bg-amber-600 rounded-lg shadow">Submit</button>
            </div>
        </form>
    </div>

    <!-- ===== UPDATE HISTORY ===== -->
    <div x-show="modal==='updateHistory'" x-transition class="relative w-full max-w-2xl bg-white rounded-2xl shadow-2xl overflow-hidden">
        <div class="bg-gradient-to-r from-orange-500 to-rose-500 px-5 py-4 flex items-center justify-between">
            <h3 class="text-white font-bold text-lg"><i class="fas fa-clock-rotate-left mr-2"></i>Update History</h3>
            <button @click="close()" class="text-white/80 hover:text-white text-xl"><i class="fas fa-times"></i></button>
        </div>
        <div class="px-5 py-2 bg-orange-50 text-orange-800 text-xs font-semibold border-b border-orange-100"><i class="fas fa-user mr-1"></i><span x-text="curUser.name"></span></div>
        <div class="p-5 max-h-[60vh] overflow-y-auto">
            <template x-if="loading"><p class="text-center text-slate-400 py-6"><i class="fas fa-spinner fa-spin mr-2"></i>Loading...</p></template>
            <template x-if="!loading && history.length===0"><p class="text-center text-slate-400 py-8"><i class="fas fa-clock-rotate-left text-2xl mb-2 block"></i>No updates recorded yet.</p></template>
            <div x-show="!loading && history.length" class="overflow-x-auto">
                <table class="w-full text-left text-xs">
                    <thead><tr class="text-slate-500 uppercase text-[10px] border-b">
                        <th class="py-2 pr-2">Field</th><th class="py-2 px-2">Old</th><th class="py-2 px-2">New</th><th class="py-2 px-2">By</th><th class="py-2 pl-2">When</th>
                    </tr></thead>
                    <tbody class="divide-y divide-slate-100">
                        <template x-for="h in history" :key="h.id">
                            <tr>
                                <td class="py-2 pr-2 font-bold text-slate-700" x-text="h.field_label"></td>
                                <td class="py-2 px-2 text-rose-500 max-w-[120px] truncate" x-text="h.old_value || '—'"></td>
                                <td class="py-2 px-2 text-emerald-600 max-w-[120px] truncate" x-text="h.new_value || '—'"></td>
                                <td class="py-2 px-2 font-semibold text-indigo-600" x-text="h.updated_by_name || '—'"></td>
                                <td class="py-2 pl-2 text-slate-500 whitespace-nowrap" x-text="fmtDate(h.updated_at)"></td>
                            </tr>
                        </template>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- ===== UPDATE FORM (full KYC editor) ===== -->
    <div x-show="modal==='updateForm'" x-transition class="relative w-full max-w-3xl bg-white rounded-2xl shadow-2xl overflow-hidden max-h-[90vh] flex flex-col">
        <div class="bg-gradient-to-r from-lime-600 to-emerald-600 px-5 py-4 flex items-center justify-between flex-shrink-0">
            <h3 class="text-white font-bold text-lg"><i class="fas fa-pen mr-2"></i>Update KYC — <span x-text="curUser.name"></span></h3>
            <button @click="close()" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
        </div>
        <form method="POST" enctype="multipart/form-data" class="flex flex-col overflow-hidden">
            <input type="hidden" name="target_user_id" :value="curUser.id">
            <div class="p-5 overflow-y-auto space-y-5">
                <template x-if="loading"><p class="text-center text-slate-400 py-6"><i class="fas fa-spinner fa-spin mr-2"></i>Loading...</p></template>
                <div x-show="!loading" class="space-y-5">
                    <!-- Personal -->
                    <div>
                        <p class="text-[11px] font-bold uppercase tracking-wide text-amber-600 mb-2 border-b pb-1"><i class="fas fa-user mr-1"></i>Personal Details</p>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                            <div><label class="lbl">Name</label><input name="full_name" x-model="form.full_name" class="fld"></div>
                            <div><label class="lbl">Gender</label><select name="gender" x-model="form.gender" class="fld"><option value="male">Male</option><option value="female">Female</option><option value="other">Other</option></select></div>
                            <div><label class="lbl">D.O.B</label><input type="date" name="dob" x-model="form.dob" class="fld"></div>
                            <div><label class="lbl">Father Name</label><input name="father_name" x-model="form.father_name" class="fld"></div>
                            <div><label class="lbl">Email</label><input name="email" x-model="form.email" class="fld"></div>
                            <div><label class="lbl">Aadhar Number</label><input name="aadhar_number" x-model="form.aadhar_number" class="fld"></div>
                            <div><label class="lbl">Pancard Number</label><input name="pancard_number" x-model="form.pancard_number" class="fld"></div>
                        </div>
                        <div class="grid grid-cols-2 md:grid-cols-4 gap-2 mt-2">
                            <div><label class="lbl">Aadhar Front</label><input type="file" name="aadhar_front" class="filein"></div>
                            <div><label class="lbl">Aadhar Back</label><input type="file" name="aadhar_back" class="filein"></div>
                            <div><label class="lbl">Pan Card</label><input type="file" name="pan_card" class="filein"></div>
                            <div><label class="lbl">Photo</label><input type="file" name="photo" class="filein"></div>
                        </div>
                    </div>
                    <!-- Address -->
                    <div>
                        <p class="text-[11px] font-bold uppercase tracking-wide text-blue-600 mb-2 border-b pb-1"><i class="fas fa-location-dot mr-1"></i>Address Details</p>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                            <div><label class="lbl">Village / Locality</label><input name="village" x-model="form.village" class="fld"></div>
                            <div><label class="lbl">Post Office</label><input name="post_office" x-model="form.post_office" class="fld"></div>
                            <div><label class="lbl">Block / City / Municipality</label><input name="block_city" x-model="form.block_city" class="fld"></div>
                            <div><label class="lbl">Landmark</label><input name="landmark" x-model="form.landmark" class="fld"></div>
                            <div><label class="lbl">District</label><input name="district" x-model="form.district" class="fld"></div>
                            <div><label class="lbl">State</label><input name="state" x-model="form.state" class="fld"></div>
                            <div><label class="lbl">Pin Code</label><input name="pincode" x-model="form.pincode" class="fld"></div>
                            <div><label class="lbl">Address Proof</label><input type="file" name="address_proof" class="filein"></div>
                        </div>
                    </div>
                    <!-- Bank -->
                    <div>
                        <p class="text-[11px] font-bold uppercase tracking-wide text-rose-600 mb-2 border-b pb-1"><i class="fas fa-building-columns mr-1"></i>Bank Details</p>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                            <div><label class="lbl">Bank Name</label><input name="bank_name" x-model="form.bank_name" class="fld"></div>
                            <div><label class="lbl">Branch Name</label><input name="branch_name" x-model="form.branch_name" class="fld"></div>
                            <div><label class="lbl">Account Number</label><input name="account_number" x-model="form.account_number" class="fld"></div>
                            <div><label class="lbl">IFSC Code</label><input name="ifsc_code" x-model="form.ifsc_code" class="fld"></div>
                            <div><label class="lbl">Bank Passbook</label><input type="file" name="bank_passbook" class="filein"></div>
                        </div>
                    </div>
                    <!-- Business -->
                    <div>
                        <p class="text-[11px] font-bold uppercase tracking-wide text-emerald-600 mb-2 border-b pb-1"><i class="fas fa-store mr-1"></i>Business Details</p>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                            <div><label class="lbl">Business / Shop Name</label><input name="business_name" x-model="form.business_name" class="fld"></div>
                            <div><label class="lbl">Business Phone</label><input name="business_phone" x-model="form.business_phone" class="fld"></div>
                            <div><label class="lbl">Business Email</label><input name="business_email" x-model="form.business_email" class="fld"></div>
                            <div><label class="lbl">Village / Locality</label><input name="biz_village" x-model="form.biz_village" class="fld"></div>
                            <div><label class="lbl">Post Office</label><input name="biz_post_office" x-model="form.biz_post_office" class="fld"></div>
                            <div><label class="lbl">Block / City / Municipality</label><input name="biz_block_city" x-model="form.biz_block_city" class="fld"></div>
                            <div><label class="lbl">Landmark</label><input name="biz_landmark" x-model="form.biz_landmark" class="fld"></div>
                            <div><label class="lbl">District</label><input name="biz_district" x-model="form.biz_district" class="fld"></div>
                            <div><label class="lbl">State</label><input name="biz_state" x-model="form.biz_state" class="fld"></div>
                            <div><label class="lbl">Pin Code</label><input name="biz_pincode" x-model="form.biz_pincode" class="fld"></div>
                            <div><label class="lbl">Business Proof</label><input type="file" name="business_proof" class="filein"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="flex justify-end gap-2 px-5 py-4 border-t bg-slate-50 flex-shrink-0">
                <button type="button" @click="close()" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-200 rounded-lg">Cancel</button>
                <button type="submit" name="admin_kyc_save" class="px-5 py-2 text-sm font-bold text-white bg-emerald-600 hover:bg-emerald-700 rounded-lg shadow">Save All Changes</button>
            </div>
        </form>
    </div>

    <!-- ===== RESET PASSWORD ===== -->
    <div x-show="modal==='reset'" x-transition class="relative w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden">
        <div class="bg-gradient-to-r from-rose-500 to-red-600 px-5 py-4 flex items-center justify-between">
            <h3 class="text-white font-bold text-lg"><i class="fas fa-key mr-2"></i>Reset Password</h3>
            <button @click="close()" class="text-white/80 hover:text-white text-xl"><i class="fas fa-times"></i></button>
        </div>
        <form method="POST" class="p-5 space-y-4">
            <input type="hidden" name="target_user_id" :value="curUser.id">
            <p class="text-xs text-slate-500">Set a new password for <span class="font-bold text-slate-700" x-text="curUser.name"></span>. This action is recorded in the update history.</p>
            <div>
                <label class="block text-xs font-semibold text-slate-600 mb-1">New Password <span class="text-rose-500">*</span></label>
                <input type="text" name="new_password" required minlength="4" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-rose-400" placeholder="Enter new password">
            </div>
            <div class="flex justify-end gap-2 pt-1">
                <button type="button" @click="close()" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-100 rounded-lg">Cancel</button>
                <button type="submit" name="reset_password" class="px-5 py-2 text-sm font-bold text-white bg-red-600 hover:bg-red-700 rounded-lg shadow">Submit</button>
            </div>
        </form>
    </div>

    <!-- ===== KYC REVIEW ===== -->
    <div x-show="modal==='kyc'" x-transition class="relative w-full max-w-3xl bg-white rounded-2xl shadow-2xl overflow-hidden">
        <div class="bg-gradient-to-r from-blue-600 to-indigo-600 px-5 py-4 flex items-center justify-between">
            <h3 class="text-white font-bold text-lg"><i class="fas fa-id-card mr-2"></i>KYC Verification</h3>
            <button @click="close()" class="text-white/80 hover:text-white text-xl"><i class="fas fa-times"></i></button>
        </div>
        <div class="px-5 py-2 bg-blue-50 text-blue-800 text-xs font-semibold border-b border-blue-100 flex items-center justify-between">
            <span><i class="fas fa-user mr-1"></i><span x-text="curUser.name"></span></span>
            <span class="uppercase px-2 py-0.5 rounded-full text-[10px]"
                  :class="kyc?.status==='approved' ? 'bg-emerald-100 text-emerald-700' : (kyc?.status==='rejected' ? 'bg-rose-100 text-rose-700' : 'bg-amber-100 text-amber-700')"
                  x-text="kyc?.status || '—'"></span>
        </div>
        <div class="p-5 max-h-[70vh] overflow-y-auto">
            <template x-if="loading"><p class="text-center text-slate-400 py-6"><i class="fas fa-spinner fa-spin mr-2"></i>Loading...</p></template>
            <template x-if="!loading && !kyc"><p class="text-center text-slate-400 py-8">No KYC submitted by this user.</p></template>
            <div x-show="!loading && kyc" class="space-y-5 text-sm">
                <!-- Personal -->
                <div>
                    <p class="text-[11px] font-bold uppercase tracking-wide text-amber-600 mb-2 border-b pb-1"><i class="fas fa-user mr-1"></i>Personal Details</p>
                    <div class="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-1.5">
                        <p><span class="text-slate-400">Name:</span> <b x-text="kyc?.full_name || '—'"></b></p>
                        <p><span class="text-slate-400">Gender:</span> <b x-text="kyc?.gender || '—'"></b></p>
                        <p><span class="text-slate-400">DOB:</span> <b x-text="kyc?.dob || '—'"></b></p>
                        <p><span class="text-slate-400">Father:</span> <b x-text="kyc?.father_name || '—'"></b></p>
                        <p><span class="text-slate-400">Email:</span> <b x-text="kyc?.email || '—'"></b></p>
                        <p><span class="text-slate-400">Aadhar:</span> <b x-text="kyc?.aadhar_number || '—'"></b></p>
                        <p><span class="text-slate-400">PAN:</span> <b x-text="kyc?.pancard_number || '—'"></b></p>
                    </div>
                    <div class="flex flex-wrap gap-2 mt-2">
                        <template x-for="f in [['aadhar_front','Aadhar Front'],['aadhar_back','Aadhar Back'],['pan_card','PAN Card'],['photo','Photo']]" :key="f[0]">
                            <span x-show="kyc?.[f[0]]" class="inline-flex items-center gap-1.5 bg-slate-100 rounded-lg px-2 py-1 text-[11px]">
                                <span class="font-semibold text-slate-600" x-text="f[1]"></span>
                                <a :href="'../uploads/kyc/'+kyc?.[f[0]]" target="_blank" class="text-blue-600 hover:text-blue-800 font-bold"><i class="fas fa-eye"></i> View</a>
                                <a :href="'../uploads/kyc/'+kyc?.[f[0]]" :download="kyc?.[f[0]]" class="text-emerald-600 hover:text-emerald-800 font-bold"><i class="fas fa-download"></i> Download</a>
                            </span>
                        </template>
                    </div>
                </div>
                <!-- Address -->
                <div>
                    <p class="text-[11px] font-bold uppercase tracking-wide text-blue-600 mb-2 border-b pb-1"><i class="fas fa-location-dot mr-1"></i>Address Details</p>
                    <div class="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-1.5">
                        <p><span class="text-slate-400">Village:</span> <b x-text="kyc?.village || '—'"></b></p>
                        <p><span class="text-slate-400">Post Office:</span> <b x-text="kyc?.post_office || '—'"></b></p>
                        <p><span class="text-slate-400">Block/City:</span> <b x-text="kyc?.block_city || '—'"></b></p>
                        <p><span class="text-slate-400">Landmark:</span> <b x-text="kyc?.landmark || '—'"></b></p>
                        <p><span class="text-slate-400">District:</span> <b x-text="kyc?.district || '—'"></b></p>
                        <p><span class="text-slate-400">State:</span> <b x-text="kyc?.state || '—'"></b></p>
                        <p><span class="text-slate-400">Pincode:</span> <b x-text="kyc?.pincode || '—'"></b></p>
                    </div>
                    <span x-show="kyc?.address_proof" class="inline-flex items-center gap-1.5 bg-slate-100 rounded-lg px-2 py-1 text-[11px] mt-2">
                        <span class="font-semibold text-slate-600">Address Proof</span>
                        <a :href="'../uploads/kyc/'+kyc?.address_proof" target="_blank" class="text-blue-600 hover:text-blue-800 font-bold"><i class="fas fa-eye"></i> View</a>
                        <a :href="'../uploads/kyc/'+kyc?.address_proof" :download="kyc?.address_proof" class="text-emerald-600 hover:text-emerald-800 font-bold"><i class="fas fa-download"></i> Download</a>
                    </span>
                </div>
                <!-- Bank -->
                <div>
                    <p class="text-[11px] font-bold uppercase tracking-wide text-rose-600 mb-2 border-b pb-1"><i class="fas fa-building-columns mr-1"></i>Bank Details</p>
                    <div class="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-1.5">
                        <p><span class="text-slate-400">Bank:</span> <b x-text="kyc?.bank_name || '—'"></b></p>
                        <p><span class="text-slate-400">Branch:</span> <b x-text="kyc?.branch_name || '—'"></b></p>
                        <p><span class="text-slate-400">Account:</span> <b x-text="kyc?.account_number || '—'"></b></p>
                        <p><span class="text-slate-400">IFSC:</span> <b x-text="kyc?.ifsc_code || '—'"></b></p>
                    </div>
                    <span x-show="kyc?.bank_passbook" class="inline-flex items-center gap-1.5 bg-slate-100 rounded-lg px-2 py-1 text-[11px] mt-2">
                        <span class="font-semibold text-slate-600">Passbook</span>
                        <a :href="'../uploads/kyc/'+kyc?.bank_passbook" target="_blank" class="text-blue-600 hover:text-blue-800 font-bold"><i class="fas fa-eye"></i> View</a>
                        <a :href="'../uploads/kyc/'+kyc?.bank_passbook" :download="kyc?.bank_passbook" class="text-emerald-600 hover:text-emerald-800 font-bold"><i class="fas fa-download"></i> Download</a>
                    </span>
                </div>
                <!-- Business -->
                <div>
                    <p class="text-[11px] font-bold uppercase tracking-wide text-emerald-600 mb-2 border-b pb-1"><i class="fas fa-store mr-1"></i>Business Details</p>
                    <div class="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-1.5">
                        <p><span class="text-slate-400">Business:</span> <b x-text="kyc?.business_name || '—'"></b></p>
                        <p><span class="text-slate-400">Phone:</span> <b x-text="kyc?.business_phone || '—'"></b></p>
                        <p><span class="text-slate-400">Email:</span> <b x-text="kyc?.business_email || '—'"></b></p>
                        <p><span class="text-slate-400">Village:</span> <b x-text="kyc?.biz_village || '—'"></b></p>
                        <p><span class="text-slate-400">Post Office:</span> <b x-text="kyc?.biz_post_office || '—'"></b></p>
                        <p><span class="text-slate-400">Block/City:</span> <b x-text="kyc?.biz_block_city || '—'"></b></p>
                        <p><span class="text-slate-400">Landmark:</span> <b x-text="kyc?.biz_landmark || '—'"></b></p>
                        <p><span class="text-slate-400">District:</span> <b x-text="kyc?.biz_district || '—'"></b></p>
                        <p><span class="text-slate-400">State:</span> <b x-text="kyc?.biz_state || '—'"></b></p>
                        <p><span class="text-slate-400">Pincode:</span> <b x-text="kyc?.biz_pincode || '—'"></b></p>
                    </div>
                    <span x-show="kyc?.business_proof" class="inline-flex items-center gap-1.5 bg-slate-100 rounded-lg px-2 py-1 text-[11px] mt-2">
                        <span class="font-semibold text-slate-600">Business Proof</span>
                        <a :href="'../uploads/kyc/'+kyc?.business_proof" target="_blank" class="text-blue-600 hover:text-blue-800 font-bold"><i class="fas fa-eye"></i> View</a>
                        <a :href="'../uploads/kyc/'+kyc?.business_proof" :download="kyc?.business_proof" class="text-emerald-600 hover:text-emerald-800 font-bold"><i class="fas fa-download"></i> Download</a>
                    </span>
                </div>
                <!-- Approve / Reject -->
                <form method="POST" class="border-t pt-4 mt-2">
                    <input type="hidden" name="target_user_id" :value="curUser.id">
                    <label class="block text-xs font-semibold text-slate-600 mb-1">Remark (optional, shown to user if rejected)</label>
                    <textarea name="kyc_remark" rows="2" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400" x-text="kyc?.admin_remark || ''"></textarea>
                    <div class="flex justify-end gap-2 mt-3">
                        <button type="submit" name="kyc_action" value="rejected" class="px-5 py-2 text-sm font-bold text-white bg-rose-600 hover:bg-rose-700 rounded-lg shadow"><i class="fas fa-times mr-1"></i>Reject</button>
                        <button type="submit" name="kyc_action" value="approved" class="px-5 py-2 text-sm font-bold text-white bg-emerald-600 hover:bg-emerald-700 rounded-lg shadow"><i class="fas fa-check mr-1"></i>Approve</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</template>

<script>
function userListApp() {
    return {
        sidebarOpen: window.innerWidth >= 768,
        modal: null,
        curUser: { id: null, name: '' },
        notes: [], history: [], viewNote: null,
        form: {}, kyc: null, loading: false,
        money: { id: null, name: '', main: 0, virtual: 0, action: 'credit', wallet: 'main', amount: null, reason: '' },
        reasonsCredit: ['Manual top-up','Refund for a failed order','Promotional bonus','Correction of a wrong debit','Support compensation'],
        reasonsDebit:  ['Wrong credit reversal','Order cancelled','Penalty / policy violation','Duplicate transaction','Manual adjustment'],
        openMoney(id, name, main, virtual) {
            this.money = { id, name, main: Number(main) || 0, virtual: Number(virtual) || 0,
                           action: 'credit', wallet: 'main', amount: null, reason: '' };
            this.modal = 'money';
        },
        moneyMax() { return this.money.wallet === 'virtual' ? this.money.virtual : this.money.main; },
        moneyErr() {
            const a = Number(this.money.amount) || 0;
            if (!this.money.amount) return '';
            if (a <= 0) return 'Enter an amount above zero';
            if (this.money.action === 'debit' && a > this.moneyMax()) return 'That wallet only holds ₹' + this.moneyMax().toFixed(2);
            return '';
        },
        moneyAfter() {
            const a = Number(this.money.amount) || 0;
            const cur = this.moneyMax();
            return this.money.action === 'credit' ? cur + a : Math.max(0, cur - a);
        },
        moneyOk() { return this.money.amount > 0 && !this.moneyErr() && this.money.reason.trim() !== ''; },
        openNotesHistory(id, name) { this.curUser = { id, name }; this.viewNote = null; this.notes = []; this.modal = 'notesHistory'; this.fetchJSON('notes', id, d => this.notes = d); },
        openNewNote(id, name)      { this.curUser = { id, name }; this.modal = 'newNote'; },
        openUpdateHistory(id, name){ this.curUser = { id, name }; this.history = []; this.modal = 'updateHistory'; this.fetchJSON('history', id, d => this.history = d); },
        openUpdateForm(id, name)   { this.curUser = { id, name }; this.form = {}; this.modal = 'updateForm'; this.fetchJSON('adminkyc', id, d => this.form = d || {}); },
        openReset(id, name)        { this.curUser = { id, name }; this.modal = 'reset'; },
        openKyc(id, name)          { this.curUser = { id, name }; this.kyc = null; this.modal = 'kyc'; this.fetchJSON('kyc', id, d => this.kyc = d); },
        close() { this.modal = null; this.viewNote = null; },
        async fetchJSON(kind, id, cb) {
            this.loading = true;
            try { const r = await fetch('user_list.php?ajax=' + kind + '&uid=' + id); cb(await r.json()); }
            catch (e) { cb([]); }
            this.loading = false;
        },
        fmtDate(s) {
            if (!s) return '';
            const d = new Date(s.replace(' ', 'T'));
            if (isNaN(d)) return s;
            return d.toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }) + ', ' + d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
        }
    }
}
</script>
</body>
</html>
