<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || !isset($_SESSION['admin_user']) || !isset($_SESSION['admin_pass'])) {
    header("Location: admin_login.php");
    exit;
}

$config_paths = ['Config.php', 'config.php', '../Config.php', '../config.php'];
foreach ($config_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        break;
    }
}

if (!isset($conn) && isset($con)) {
    $conn = $con;
}

$has_permission = false;
$permission_value = '';

if (isset($conn) && is_object($conn)) {
    $admin_user = $_SESSION['admin_user'];
    $admin_pass = $_SESSION['admin_pass'];
    
    $sql = "SELECT users_control FROM modarator_permissions WHERE username = ? AND password = ? LIMIT 1";
    $stmt = @$conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param("ss", $admin_user, $admin_pass);
        if (@$stmt->execute()) {
            $res = $stmt->get_result();
            if ($res && $res->num_rows > 0) {
                $row = $res->fetch_assoc();
                $permission_value = strtolower(trim((string)$row['users_control']));
            }
        }
        $stmt->close();
    }
}

if ($permission_value === 'yes' || $permission_value === '1' || $permission_value === 'true') {
    $has_permission = true;
}

if (!$has_permission) {
    die('<!DOCTYPE html><html lang="bn"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>অ্যাক্সেস বাতিল</title></head><body style="margin:0;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;background:#f4f6f9;font-family:sans-serif;"><svg width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="#ff3b30" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg><h2 style="color:#ff3b30;margin:20px 0 10px;">অ্যাক্সেস বাতিল!</h2><p style="color:#71717a;margin-bottom:20px;">আপনার এই পেজটি দেখার পারমিশন নেই।</p><button onclick="window.location.href=\'admin_login.php\'" style="background:#007aff;color:#fff;border:none;padding:12px 24px;border-radius:10px;font-size:15px;cursor:pointer;">ফিরে যান</button></body></html>');
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>ইউজার ম্যানেজার</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
        :root {
            --bg-body: #f4f6f9; --bg-card: #ffffff; --bg-modal: #ffffff;
            --border-color: #e4e4e7; --border-hover: #cbd5e1;
            --text-main: #18181b; --text-muted: #71717a;
            --primary: #007aff; --success: #34c759; --danger: #ff3b30;
            --radius-lg: 20px; --radius-md: 14px; --radius-sm: 10px;
            --transition: all 0.25s cubic-bezier(0.2, 0.8, 0.2, 1);
        }
        * { margin: 0; padding: 0; box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
        body { font-family: 'Inter', sans-serif; background-color: var(--bg-body); color: var(--text-main); min-height: 100vh; overflow-y: scroll; overflow-x: hidden; -webkit-font-smoothing: antialiased; }
        .app-container { width: 100%; max-width: 1200px; margin: 0 auto; padding: 16px 14px calc(80px + env(safe-area-inset-bottom)); display: flex; flex-direction: column; gap: 20px; }
        @media (min-width: 768px) { .app-container { padding: 32px 24px; gap: 28px; } }
        .hero-section { display: flex; flex-direction: column; gap: 16px; }
        @media (min-width: 768px) { .hero-section { flex-direction: row; align-items: center; justify-content: space-between; background: var(--bg-card); padding: 24px; border-radius: var(--radius-lg); border: 1px solid var(--border-color); box-shadow: 0 4px 12px rgba(0,0,0,0.02); } }
        .title-area h1 { font-size: 30px; font-weight: 800; letter-spacing: -0.5px; }
        @media (min-width: 768px) { .title-area h1 { font-size: 34px; } }
        .title-area p { margin-top: 6px; font-size: 14px; color: var(--text-muted); font-weight: 500; }
        .title-area p span { color: var(--primary); font-weight: 700; }
        .stats-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
        .stat-card { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: var(--radius-md); padding: 14px 12px; text-align: center; box-shadow: 0 2px 6px rgba(0,0,0,0.01); }
        .stat-card .label { font-size: 12px; color: var(--text-muted); font-weight: 600; margin-bottom: 4px; }
        .stat-card .value { font-size: 22px; font-weight: 800; }
        .stat-card.blue .value { color: var(--primary); } .stat-card.green .value { color: var(--success); } .stat-card.red .value { color: var(--danger); }
        .toolbar { display: flex; flex-direction: column; gap: 14px; }
        @media (min-width: 768px) { .toolbar { flex-direction: row; align-items: center; justify-content: space-between; } }
        .search-box { display: flex; align-items: center; gap: 10px; background: var(--bg-card); border: 1px solid var(--border-color); border-radius: var(--radius-md); padding: 12px 16px; flex: 1; transition: var(--transition); box-shadow: 0 2px 6px rgba(0,0,0,0.01); }
        .search-box:focus-within { border-color: var(--primary); background: #ffffff; box-shadow: 0 0 0 4px rgba(0, 122, 255, 0.1); }
        .search-box input { flex: 1; border: none; outline: none; background: transparent; color: var(--text-main); font-size: 15px; font-weight: 500; }
        .search-box input::placeholder { color: #a1a1aa; }
        .controls-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
        .segment { display: flex; background: rgba(118, 118, 128, 0.12); border-radius: 12px; padding: 4px; }
        .segment button { flex: 1; border: none; background: transparent; color: var(--text-muted); padding: 8px 12px; border-radius: 8px; font-size: 13px; font-weight: 600; cursor: pointer; transition: var(--transition); white-space: nowrap; }
        .segment button.active { background: #ffffff; color: #000000; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }
        .show-limit select { background: var(--bg-card); color: var(--text-main); border: 1px solid var(--border-color); padding: 8px 12px; border-radius: 10px; font-size: 14px; font-weight: 600; outline: none; cursor: pointer; }
        .user-grid { display: grid; grid-template-columns: 1fr; gap: 12px; }
        @media (min-width: 640px) { .user-grid { grid-template-columns: repeat(2, 1fr); gap: 16px; } }
        @media (min-width: 1024px) { .user-grid { grid-template-columns: repeat(3, 1fr); gap: 18px; } }
        .card { display: flex; align-items: center; gap: 14px; background: var(--bg-card); border: 1px solid var(--border-color); padding: 16px; border-radius: var(--radius-lg); cursor: pointer; transition: var(--transition); animation: fadeIn 0.3s ease both; box-shadow: 0 4px 10px rgba(0,0,0,0.01); }
        .card:hover { border-color: var(--border-hover); transform: translateY(-2px); background: #fdfdfd; box-shadow: 0 6px 16px rgba(0,0,0,0.03); }
        .card:active { transform: scale(0.97); }
        .avatar { width: 48px; height: 48px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 18px; font-weight: 700; color: #fff; position: relative; flex-shrink: 0; }
        .avatar img { width: 100%; height: 100%; border-radius: 50%; object-fit: cover; }
        .badge-verified { position: absolute; bottom: -2px; right: -2px; width: 18px; height: 18px; background: var(--primary); border: 2px solid var(--bg-card); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-size: 10px; }
        .info { flex: 1; min-width: 0; }
        .name-row { display: flex; align-items: center; gap: 8px; margin-bottom: 4px; }
        .username { font-size: 16px; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .tag-unverified { font-size: 9px; font-weight: 800; padding: 3px 6px; border-radius: 6px; background: rgba(255, 59, 48, 0.1); color: var(--danger); text-transform: uppercase; }
        .details { font-size: 12px; color: var(--text-muted); display: flex; flex-direction: column; gap: 3px; }
        .details span { display: flex; align-items: center; gap: 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .balance-area { text-align: right; flex-shrink: 0; }
        .balance-area .amount { font-size: 17px; font-weight: 800; color: var(--success); }
        .balance-area .label { font-size: 11px; color: var(--text-muted); font-weight: 500; margin-top: 2px; }
        .skeleton-card { background: var(--bg-card); border: 1px solid var(--border-color); height: 86px; border-radius: var(--radius-lg); position: relative; overflow: hidden; }
        .skeleton-card::after { content: ""; position: absolute; inset: 0; background: linear-gradient(90deg, transparent, rgba(0,0,0,0.03), transparent); transform: translateX(-100%); animation: shimmer 1.5s infinite; }
        .pagination { display: flex; justify-content: center; gap: 6px; margin-top: 10px; flex-wrap: wrap; }
        .pagination button { min-width: 38px; height: 38px; border-radius: 10px; background: var(--bg-card); border: 1px solid var(--border-color); color: var(--text-main); font-weight: 600; font-size: 14px; cursor: pointer; transition: var(--transition); }
        .pagination button.active { background: var(--primary); border-color: var(--primary); color: white; }
        .pagination button:disabled { opacity: 0.4; cursor: not-allowed; }
        .modal-overlay { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.4); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); display: flex; align-items: flex-end; justify-content: center; z-index: 1000; opacity: 0; pointer-events: none; transition: var(--transition); }
        .modal-overlay.show { opacity: 1; pointer-events: all; }
        .modal-content { width: 100%; background: var(--bg-modal); border-radius: 24px 24px 0 0; padding: 20px 20px calc(20px + env(safe-area-inset-bottom)); transform: translateY(100%); transition: transform 0.35s cubic-bezier(0.2, 0.8, 0.2, 1); max-height: 90vh; overflow-y: auto; border-top: 1px solid var(--border-color); box-shadow: 0 -8px 30px rgba(0,0,0,0.08); }
        .modal-overlay.show .modal-content { transform: translateY(0); }
        @media (min-width: 768px) { .modal-overlay { align-items: center; padding: 24px; } .modal-content { max-width: 480px; border-radius: 20px; border: 1px solid var(--border-color); transform: scale(0.95); opacity: 0; padding: 24px; box-shadow: 0 12px 40px rgba(0,0,0,0.12); } .modal-overlay.show .modal-content { transform: scale(1); opacity: 1; } .drag-handle { display: none; } }
        .drag-handle { width: 40px; height: 5px; background: rgba(0,0,0,0.1); border-radius: 5px; margin: 0 auto 20px; }
        .modal-header { text-align: center; margin-bottom: 24px; }
        .modal-avatar { width: 80px; height: 80px; border-radius: 50%; margin: 0 auto 12px; display: flex; align-items: center; justify-content: center; font-size: 30px; font-weight: 800; color: white; }
        .modal-avatar img { width: 100%; height: 100%; border-radius: 50%; object-fit: cover; }
        .input-group { display: flex; flex-direction: column; gap: 14px; margin-bottom: 24px; }
        .input-row { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
        .input-field { background: #f4f4f5; border: 1px solid var(--border-color); border-radius: var(--radius-sm); padding: 10px 14px; }
        .input-field label { display: block; font-size: 11px; color: var(--text-muted); text-transform: uppercase; font-weight: 700; margin-bottom: 6px; }
        .input-field input, .input-field select { width: 100%; background: transparent; border: none; outline: none; color: var(--text-main); font-size: 15px; font-weight: 600; font-family: inherit; }
        .modal-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
        .btn { padding: 14px; border-radius: var(--radius-sm); border: none; font-size: 15px; font-weight: 700; cursor: pointer; transition: var(--transition); }
        .btn:active { transform: scale(0.97); }
        .btn-update { background: var(--success); color: #ffffff; }
        .btn-update:hover { opacity: 0.9; }
        .btn-delete { background: rgba(255, 59, 48, 0.1); color: var(--danger); }
        .btn-delete:hover { background: var(--danger); color: #ffffff; }
        .btn-close { grid-column: 1 / -1; background: #e4e4e7; color: #18181b; }
        .fab { position: fixed; bottom: max(20px, env(safe-area-inset-bottom)); right: 20px; width: 54px; height: 54px; border-radius: 16px; background: var(--primary); color: white; border: none; box-shadow: 0 8px 24px rgba(0, 122, 255, 0.3); display: flex; align-items: center; justify-content: center; cursor: pointer; z-index: 90; }
        .toast { position: fixed; bottom: max(30px, calc(10px + env(safe-area-inset-bottom))); left: 50%; transform: translate(-50%, 20px); background: #18181b; color: #ffffff; padding: 12px 20px; border-radius: 100px; font-weight: 700; font-size: 13px; box-shadow: 0 10px 30px rgba(0,0,0,0.15); opacity: 0; pointer-events: none; transition: var(--transition); z-index: 2000; white-space: nowrap; }
        .toast.show { opacity: 1; transform: translate(-50%, 0); }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes shimmer { 100% { transform: translateX(100%); } }
    </style>
</head>
<body>

<div class="app-container">
    <header class="hero-section">
        <div class="title-area">
            <h1>ইউজার ম্যানেজার</h1>
            <p>সর্বমোট <span id="totalCount">0</span> জন ইউজার</p>
        </div>
        <div class="stats-grid">
            <div class="stat-card blue">
                <div class="label">ভেরিফাইড</div>
                <div class="value" id="verifiedCount">0</div>
            </div>
            <div class="stat-card green">
                <div class="label">দেখাচ্ছে</div>
                <div class="value" id="shownCount">0</div>
            </div>
            <div class="stat-card red">
                <div class="label">অনভেরিফাইড</div>
                <div class="value" id="unverifiedCount">0</div>
            </div>
        </div>
    </header>

    <div class="toolbar">
        <div class="search-box">
            <svg width="18" height="18" fill="none" stroke="#71717a" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="7"></circle><path d="M21 21l-4.35-4.35"></path></svg>
            <input type="text" id="searchInput" placeholder="নাম, ইমেইল বা মোবাইল..." autocomplete="off">
        </div>
        <div class="controls-row">
            <div class="segment" id="segmentControl">
                <button class="active" data-filter="all">সব</button>
                <button data-filter="verified">ভেরিফাইড</button>
                <button data-filter="unverified">অনভেরিফাইড</button>
            </div>
            <div class="show-limit">
                <select id="showSelect"></select>
            </div>
        </div>
    </div>

    <main>
        <div class="user-grid" id="userList"></div>
        <div class="pagination" id="pagination"></div>
    </main>
</div>

<button class="fab" id="refreshBtn">
    <svg width="22" height="22" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 0 1-15.59 6.36M3 12a9 9 0 0 1 15.59-6.36M21 12v-6M3 12v6"></path></svg>
</button>

<div class="modal-overlay" id="profileModal">
    <div class="modal-content">
        <div class="drag-handle"></div>
        <div class="modal-header">
            <div class="modal-avatar" id="modalAvatar">U</div>
            <h2 id="modalName" style="font-size: 20px; margin-bottom: 2px;">নাম</h2>
            <p id="modalSub" style="color: var(--text-muted); font-size: 13px;">@username</p>
        </div>
        <div class="input-group">
            <div class="input-field"><label>ইউজারনেম</label><input type="text" id="editUsername" placeholder="ইউজারনেম"></div>
            <div class="input-row">
                <div class="input-field"><label>ইমেইল</label><input type="email" id="editEmail" placeholder="mail@example.com"></div>
                <div class="input-field"><label>মোবাইল</label><input type="text" id="editNumber" placeholder="017..."></div>
            </div>
            <div class="input-row">
                <div class="input-field"><label>ব্যালেন্স (৳)</label><input type="number" step="0.01" id="editBalance" placeholder="0.00"></div>
                <div class="input-field"><label>উইনিং (৳)</label><input type="number" step="0.01" id="editWinning" placeholder="0.00"></div>
            </div>
            <div class="input-field">
                <label>ভেরিফিকেশন</label>
                <select id="editVerified">
                    <option value="Yes">✓ ভেরিফাইড (Yes)</option>
                    <option value="No">× অনভেরিফাইড (No)</option>
                </select>
            </div>
        </div>
        <div class="modal-actions">
            <button class="btn btn-update" onclick="saveUser()">আপডেট করুন</button>
            <button class="btn btn-delete" onclick="deleteUser()">ডিলিট</button>
            <button class="btn btn-close" onclick="closeModal()">বন্ধ করুন</button>
        </div>
    </div>
</div>

<div class="toast" id="toastMessage"></div>

<script>
const API_URL = 'get_UserInfo.php';
let currentPage = 1, currentFilter = 'all', currentSearch = '', currentShow = 20, editingUserId = null, userCache = {}, searchTimer = null;
const userListEl = document.getElementById('userList'), paginationEl = document.getElementById('pagination'), searchInput = document.getElementById('searchInput'), showSelect = document.getElementById('showSelect'), segmentBtns = document.querySelectorAll('#segmentControl button'), refreshBtn = document.getElementById('refreshBtn'), modalOverlay = document.getElementById('profileModal');
const editFields = { username: document.getElementById('editUsername'), email: document.getElementById('editEmail'), number: document.getElementById('editNumber'), balance: document.getElementById('editBalance'), winning: document.getElementById('editWinning'), verified: document.getElementById('editVerified') };

function setupDeviceLimits() {
    const ua = navigator.userAgent || window.opera, isIOS = /iPad|iPhone|iPod/.test(ua) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1), isMobile = /android|webos|blackberry|iemobile|opera mini/i.test(ua.toLowerCase()) || window.innerWidth < 768;
    let options = isIOS ? [10, 20, 50, 100, 200] : (isMobile ? [10, 20, 50, 100] : [10, 20, 50, 100, 200, 500]);
    showSelect.innerHTML = '';
    options.forEach(opt => { const op = document.createElement('option'); op.value = opt; op.textContent = opt + ' জন'; if (opt === 20) op.selected = true; showSelect.appendChild(op); });
    currentShow = 20;
}

const escapeHtml = t => String(t ?? '').replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;','\'':'&#39;'}[m]));
const truncateText = (str, maxLength = 20) => (!str ? '' : (str.length > maxLength ? str.substring(0, maxLength) + '...' : str));
const stringToColor = str => { let hash = 0; for (let i = 0; i < str.length; i++) hash = str.charCodeAt(i) + ((hash << 5) - hash); return `hsl(${Math.abs(hash) % 360}, 65%, 55%)`; };

function showToast(msg) {
    const el = document.getElementById('toastMessage'); el.textContent = msg; el.classList.add('show');
    clearTimeout(window.toastTimer); window.toastTimer = setTimeout(() => el.classList.remove('show'), 2500);
}

function loadingView() { userListEl.innerHTML = Array(6).fill('<div class="skeleton-card"></div>').join(''); }
function isVerified(val) { if (!val) return false; const s = String(val).trim().toLowerCase(); return s === 'yes' || s === '1' || s === 'true'; }

function blockUnauthorizedAccess(message) {
    document.querySelector('.app-container').innerHTML = `<div style="display:flex; flex-direction:column; align-items:center; justify-content:center; height:70vh; text-align:center;"><svg width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="#ff3b30" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg><h2 style="color:#ff3b30; margin:20px 0 10px; font-size:24px;">অ্যাক্সেস বাতিল!</h2><p style="color:#71717a; font-size:16px; margin-bottom:20px; max-width:400px; line-height:1.5;">${escapeHtml(message)}</p><button onclick="window.location.href='admin_login.php'" style="background:#007aff; color:#fff; border:none; padding:12px 24px; border-radius:10px; font-size:15px; font-weight:600; cursor:pointer;">লগিন পেজে যান</button></div>`;
    document.getElementById('refreshBtn').style.display = 'none';
}

async function loadUsers(page = 1) {
    currentPage = page; loadingView();
    try {
        const res = await fetch(API_URL, { method: 'POST', body: new URLSearchParams({ action: 'list', show: currentShow, page: page, search: currentSearch }) });
        const data = await res.json();
        if (res.status === 403 || data.status === 'error') return blockUnauthorizedAccess(data.message || "Permission Denied!");
        if (data.status === 'success') {
            let users = Array.isArray(data.users) ? data.users : [];
            userCache = {}; users.forEach(u => { if (u?.id) userCache[u.id] = u; });
            if (currentFilter === 'verified') users = users.filter(u => isVerified(u.verify_badge));
            if (currentFilter === 'unverified') users = users.filter(u => !isVerified(u.verify_badge));
            document.getElementById('totalCount').textContent = data.total ?? 0;
            document.getElementById('verifiedCount').textContent = Array.isArray(data.users) ? data.users.filter(u => isVerified(u.verify_badge)).length : 0;
            document.getElementById('unverifiedCount').textContent = Array.isArray(data.users) ? data.users.filter(u => !isVerified(u.verify_badge)).length : 0;
            document.getElementById('shownCount').textContent = users.length;
            renderUsers(users); renderPagination(data);
        }
    } catch(e) { blockUnauthorizedAccess("সার্ভারের সাথে কানেক্ট করা যাচ্ছে না।"); }
}

function renderUsers(users) {
    if (!users.length) return userListEl.innerHTML = `<div style="grid-column:1/-1; text-align:center; padding:40px; border:1px dashed var(--border-color); border-radius:var(--radius-lg); color:var(--text-muted);"><h3>কোনো ইউজার পাওয়া যায়নি</h3></div>`;
    userListEl.innerHTML = users.map((user, i) => {
        const verified = isVerified(user.verify_badge), rawName = user.username || 'নাম নেই', displayShortName = truncateText(rawName, 20), color = stringToColor(rawName), initial = rawName.charAt(0).toUpperCase();
        return `<div class="card" style="animation-delay:${i * 0.03}s" onclick="openProfile('${user.id}')"><div class="avatar" style="background: linear-gradient(135deg, ${color}, #e2e8f0)">${user.profile_pic ? `<img src="${escapeHtml(user.profile_pic)}" onerror="this.remove()">` : initial}${verified ? `<div class="badge-verified"><svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round"><path d="M20 6L9 17l-5-5"></path></svg></div>` : ''}</div><div class="info"><div class="name-row"><div class="username" title="${escapeHtml(rawName)}">${escapeHtml(displayShortName)}</div>${!verified ? `<div class="tag-unverified">Unverified</div>` : ''}</div><div class="details"><span title="${escapeHtml(user.email)}"><svg width="11" height="11" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 4h16v16H4z"></path><path d="M4 7l8 5 8-5"></path></svg> ${escapeHtml(user.email || 'N/A')}</span><span><svg width="11" height="11" fill="none" stroke="currentColor" stroke-width="2"><rect x="5" y="2" width="14" height="20" rx="2"></rect><path d="M12 18h.01"></path></svg> ${escapeHtml(user.number || 'N/A')}</span></div></div><div class="balance-area"><div class="amount">৳${Number(user.balance || 0).toFixed(2)}</div><div class="label">ব্যালেন্স</div></div></div>`;
    }).join('');
}

function renderPagination(data) {
    const total = Number(data.total_pages || 1), current = Number(data.current_page || 1);
    if (total <= 1) return paginationEl.innerHTML = '';
    let html = `<button onclick="loadUsers(${current - 1})" ${current <= 1 ? 'disabled' : ''}>‹</button>`;
    const start = Math.max(1, current - 2), end = Math.min(total, current + 2);
    if (start > 1) html += `<button onclick="loadUsers(1)">1</button>${start > 2 ? '<span style="color:var(--text-muted); align-self:center;">...</span>' : ''}`;
    for (let i = start; i <= end; i++) html += `<button onclick="loadUsers(${i})" class="${i === current ? 'active' : ''}">${i}</button>`;
    if (end < total) html += `${end < total - 1 ? '<span style="color:var(--text-muted); align-self:center;">...</span>' : ''}<button onclick="loadUsers(${total})">${total}</button>`;
    html += `<button onclick="loadUsers(${current + 1})" ${current >= total ? 'disabled' : ''}>›</button>`;
    paginationEl.innerHTML = html;
}

function openProfile(id) {
    const user = userCache[id]; if (!user) return;
    editingUserId = id; const verified = isVerified(user.verify_badge), rawName = user.username || 'নাম নেই';
    document.getElementById('modalAvatar').style.background = `linear-gradient(135deg, ${stringToColor(rawName)}, #cbd5e1)`;
    document.getElementById('modalAvatar').innerHTML = user.profile_pic ? `<img src="${escapeHtml(user.profile_pic)}" onerror="this.remove()">` : escapeHtml(rawName.charAt(0).toUpperCase());
    document.getElementById('modalName').textContent = truncateText(rawName, 20); document.getElementById('modalName').title = rawName;
    document.getElementById('modalSub').textContent = `@${truncateText(rawName, 15)} • ${verified ? 'ভেরিফাইড' : 'অনভেরিফাইড'}`;
    editFields.username.value = user.username || ''; editFields.email.value = user.email || ''; editFields.number.value = user.number || ''; editFields.balance.value = user.balance || 0; editFields.winning.value = user.winning || 0; editFields.verified.value = verified ? "Yes" : "No";
    modalOverlay.classList.add('show'); document.body.style.overflow = 'hidden';
}

function closeModal() { modalOverlay.classList.remove('show'); document.body.style.overflow = ''; editingUserId = null; }

async function saveUser() {
    if (!editingUserId) return showToast('ইউজার সিলেক্ট করা নেই');
    try {
        const res = await fetch(API_URL, { method: 'POST', body: new URLSearchParams({ action: 'update', id: editingUserId, username: editFields.username.value.trim(), email: editFields.email.value.trim(), number: editFields.number.value.trim(), balance: parseFloat(editFields.balance.value) || 0, winning: parseFloat(editFields.winning.value) || 0, verify_badge: editFields.verified.value }) });
        const data = await res.json();
        if (res.status === 403 || data.status === 'error') { closeModal(); return blockUnauthorizedAccess(data.message || "Permission Denied!"); }
        if (data.status === 'success') { showToast('সফলভাবে আপডেট হয়েছে'); closeModal(); loadUsers(currentPage); } 
    } catch(e) { showToast('নেটওয়ার্ক এরর!'); }
}

async function deleteUser() {
    if (!editingUserId || !confirm('নিশ্চিত ডিলিট করতে চান?')) return;
    try {
        const res = await fetch(API_URL, { method: 'POST', body: new URLSearchParams({ action: 'delete', id: editingUserId }) });
        const data = await res.json();
        if (res.status === 403 || data.status === 'error') { closeModal(); return blockUnauthorizedAccess(data.message || "Permission Denied!"); }
        if (data.status === 'success') { showToast('ইউজার ডিলিট হয়েছে'); closeModal(); loadUsers(currentPage); } 
    } catch(e) { showToast('নেটওয়ার্ক এরর!'); }
}

searchInput.addEventListener('input', function() { currentSearch = this.value.trim(); clearTimeout(searchTimer); searchTimer = setTimeout(() => loadUsers(1), 350); });
showSelect.addEventListener('change', function() { currentShow = parseInt(this.value, 10); loadUsers(1); });
segmentBtns.forEach(btn => { btn.addEventListener('click', function() { segmentBtns.forEach(b => b.classList.remove('active')); this.classList.add('active'); currentFilter = this.dataset.filter; loadUsers(1); }); });
modalOverlay.addEventListener('click', e => { if (e.target === modalOverlay) closeModal(); });
window.addEventListener('keydown', e => { if (e.key === 'Escape' && modalOverlay.classList.contains('show')) closeModal(); });
refreshBtn.addEventListener('click', () => { refreshBtn.querySelector('svg').style.transform = 'rotate(180deg)'; refreshBtn.style.transition = 'transform 0.3s'; loadUsers(currentPage).then(() => setTimeout(() => refreshBtn.querySelector('svg').style.transform = 'none', 300)); });

setupDeviceLimits(); loadUsers(1);
</script>
</body>
</html>