<?php
if (!defined('ABSPATH')) exit;

class VS_Vendors {

    public static function init() {
        add_action('wp_ajax_vs_get_vendors', [__CLASS__, 'get_vendors_ajax']);
        add_action('wp_ajax_vs_update_vendor', [__CLASS__, 'update_vendor_ajax']);
        add_action('wp_ajax_vs_delete_vendor', [__CLASS__, 'delete_vendor_ajax']);
        add_action('wp_ajax_vs_bulk_vendor_action', [__CLASS__, 'bulk_vendor_action_ajax']);
        add_action('wp_ajax_vs_delete_vendor_permanently', [__CLASS__, 'delete_vendor_permanently_ajax']);
        add_action('wp_ajax_vs_restore_vendor', [__CLASS__, 'restore_vendor_ajax']);
        add_action('wp_ajax_vs_export_vendors_csv', [__CLASS__, 'export_vendors_csv_ajax']);
    }

    public static function render($user) {
        if (!current_user_can('administrator')) return '';

        ob_start();
        ?>
        <div class="vs-tab" id="tab-vendors-management" style="display:none;">
        <style>
        /* ═══════════════════ USERS MANAGEMENT — MOBILE ═══════════════════ */
        @media (max-width: 768px) {
            #tab-vendors-management .vs-dashboard-header {
                flex-direction: column !important; align-items: flex-start !important; gap: 10px !important;
            }
            #tab-vendors-management .vs-dashboard-header h2 { font-size: 18px !important; }
            #tab-vendors-management .vs-header-actions, #vs-export-vendors-csv {
                width: 100% !important; min-height: 44px !important; box-sizing: border-box !important;
            }
            #tab-vendors-management .vs-stats-grid {
                grid-template-columns: 1fr !important; gap: 10px !important; margin-bottom: 14px !important;
            }
            #tab-vendors-management .vs-table-tools {
                flex-direction: column !important; gap: 10px !important;
                padding: 14px !important; align-items: stretch !important;
            }
            #tab-vendors-management .vs-search-box {
                width: 100% !important; flex: none !important; min-width: 0 !important;
            }
            #vs-vendor-search {
                width: 100% !important; min-height: 44px !important;
                font-size: 14px !important; box-sizing: border-box !important;
            }
            #vs-vendor-type-filter, #vs-vendor-status-filter {
                width: 100% !important; min-height: 44px !important; font-size: 14px !important;
                flex: none !important; min-width: 0 !important; box-sizing: border-box !important;
                padding: 10px 12px !important;
            }
            #tab-vendors-management .vs-bulk-tools {
                flex-direction: row !important; gap: 8px !important;
                flex: none !important; width: 100% !important; margin-left: 0 !important;
                justify-content: space-between !important; align-items: center !important;
            }
            #vs-vendors-selected-count {
                font-size: 12px !important; min-width: 70px !important;
                text-align: left !important; white-space: nowrap !important;
            }
            #vs-vendors-bulk-action {
                flex: 1 !important; min-height: 44px !important;
                font-size: 13px !important; min-width: 0 !important;
            }
            #vs-vendors-bulk-apply {
                min-height: 44px !important; padding: 10px 14px !important;
                white-space: nowrap !important; flex-shrink: 0 !important;
            }
            #vs-users-table-wrap { border-radius: 12px !important; }
            .vs-vendors-table { min-width: 500px !important; font-size: 12px !important; }
            .vs-vendors-table th, .vs-vendors-table td {
                padding: 10px 8px !important; white-space: nowrap !important;
            }
            .vs-vendors-table th:nth-child(6), .vs-vendors-table td:nth-child(6) { display: none !important; }
            #vs-vendors-pagination { justify-content: center !important; gap: 6px !important; }
        }
        @media (max-width: 480px) {
            #tab-vendors-management .vs-bulk-tools {
                flex-direction: column !important; align-items: stretch !important;
            }
            #vs-vendors-bulk-action, #vs-vendors-bulk-apply { width: 100% !important; }
            #vs-vendors-selected-count { text-align: center !important; }
        }
        </style>
            <div class="vs-dashboard-header" style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; border-bottom: 2px solid #2563eb; padding-bottom: 10px;">
                <h2 style="margin:0; font-size:24px; color:#1e293b;"><?php echo esc_html__('Users Management', 'vendor-space'); ?></h2>
                <div class="vs-header-actions" style="display: flex; gap: 10px;">
                    <button id="vs-export-vendors-csv" class="vs-btn-success" style="background: #27ae60; color: white; border: none; padding: 8px 15px; border-radius: 6px; cursor: pointer; font-weight: 600;">
                        <i class="fas fa-file-export"></i> <?php echo esc_html__('Export CSV', 'vendor-space'); ?>
                    </button>
                </div>
            </div>

            <!-- Stats Row -->
            <div class="vs-stats-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 25px;">
    <div class="vs-stat-card" style="position:relative; background:white; padding:20px; border-radius:12px; box-shadow:0 4px 6px rgba(0,0,0,0.05); overflow:hidden; cursor:pointer;">
        <div class="vs-stat-overlay" style="position:absolute; top:0; left:0; width:4px; height:100%; background:#3498db; transition: all 0.3s;"></div>
        <div style="z-index:2; position:relative; display:flex; align-items:center; gap:10px;">
            <i class="fas fa-users" style="font-size:24px; color:#3498db;"></i>
            <div style="color:#64748b; font-size:14px; font-weight:600;"><?php echo esc_html__('Total Users', 'vendor-space'); ?></div>
        </div>
        <div id="vs-total-vendors-count" style="font-size:24px; font-weight:700; color:#1e293b; margin-top:5px; z-index:2; position:relative;">0</div>
    </div>

    <div class="vs-stat-card" style="position:relative; background:white; padding:20px; border-radius:12px; box-shadow:0 4px 6px rgba(0,0,0,0.05); overflow:hidden; cursor:pointer;">
        <div class="vs-stat-overlay" style="position:absolute; top:0; left:0; width:4px; height:100%; background:#27ae60; transition: all 0.3s;"></div>
        <div style="z-index:2; position:relative; display:flex; align-items:center; gap:10px;">
            <i class="fas fa-user-check" style="font-size:24px; color:#27ae60;"></i>
            <div style="color:#64748b; font-size:14px; font-weight:600;"><?php echo esc_html__('Active Users', 'vendor-space'); ?></div>
        </div>
        <div id="vs-active-vendors-count" style="font-size:24px; font-weight:700; color:#1e293b; margin-top:5px; z-index:2; position:relative;">0</div>
    </div>

    <div class="vs-stat-card" style="position:relative; background:white; padding:20px; border-radius:12px; box-shadow:0 4px 6px rgba(0,0,0,0.05); overflow:hidden; cursor:pointer;">
        <div class="vs-stat-overlay" style="position:absolute; top:0; left:0; width:4px; height:100%; background:#e74c3c; transition: all 0.3s;"></div>
        <div style="z-index:2; position:relative; display:flex; align-items:center; gap:10px;">
            <i class="fas fa-user-slash" style="font-size:24px; color:#e74c3c;"></i>
            <div style="color:#64748b; font-size:14px; font-weight:600;"><?php echo esc_html__('Banned/Deleted', 'vendor-space'); ?></div>
        </div>
        <div id="vs-deleted-vendors-count" style="font-size:24px; font-weight:700; color:#1e293b; margin-top:5px; z-index:2; position:relative;">0</div>
    </div>
</div>




            <!-- Search & Filters -->
            <div class="vs-table-tools" style="background: white; padding: 20px; border-radius: 12px; margin-bottom: 20px; display: flex; gap: 15px; align-items: center; flex-wrap: wrap; box-shadow: 0 2px 4px rgba(0,0,0,0.02);">
                <div class="vs-search-box" style="flex: 1 1 320px; min-width: 240px; position: relative;">
                    <i class="fas fa-search" style="position: absolute; left: 15px; top: 50%; transform: translateY(-50%); color: #94a3b8;"></i>
                    <input type="text" id="vs-vendor-search" placeholder="<?php echo esc_attr__('Search by name, email...', 'vendor-space'); ?>" style="width: 100%; padding: 12px 15px 12px 45px; border: 1px solid #e2e8f0; border-radius: 8px; outline: none; transition: border-color 0.2s; box-sizing:border-box;">
                </div>
                <select id="vs-vendor-type-filter" style="padding: 12px 15px; border: 1px solid #e2e8f0; border-radius: 8px; color: #475569; outline: none; min-width: 180px; flex: 0 0 180px;">
                    <option value="all_users" selected><?php echo esc_html__('All (Vendors + Customers)', 'vendor-space'); ?></option>
                    <option value="vendors"><?php echo esc_html__('Vendors', 'vendor-space'); ?></option>
                    <option value="customers"><?php echo esc_html__('Customers', 'vendor-space'); ?></option>
                    <option value="banned"><?php echo esc_html__('Banned/Deleted', 'vendor-space'); ?></option>
                </select>
                <select id="vs-vendor-status-filter" style="padding: 12px 15px; border: 1px solid #e2e8f0; border-radius: 8px; color: #475569; outline: none; min-width: 170px; flex: 0 0 170px;">
                    <option value="all" selected><?php echo esc_html__('All Status', 'vendor-space'); ?></option>
                    <option value="active"><?php echo esc_html__('Active', 'vendor-space'); ?></option>
                    <option value="deleted"><?php echo esc_html__('Banned/Deleted', 'vendor-space'); ?></option>
                </select>

                <div class="vs-bulk-tools" style="display:flex; gap:10px; align-items:center; margin-left:auto; flex: 1 1 320px; justify-content:flex-end;">
                    <div id="vs-vendors-selected-count" style="color:#64748b; font-weight:700; font-size:13px; min-width:120px; text-align:right;"><?php echo esc_html__('0 selected', 'vendor-space'); ?></div>
                    <select id="vs-vendors-bulk-action" style="padding: 12px 15px; border: 1px solid #e2e8f0; border-radius: 8px; color: #475569; outline: none; min-width: 190px;">
                        <option value="" selected><?php echo esc_html__('Bulk actions', 'vendor-space'); ?></option>
                        <option value="ban"><?php echo esc_html__('Ban (Block)', 'vendor-space'); ?></option>
                        <option value="restore"><?php echo esc_html__('Restore', 'vendor-space'); ?></option>
                        <option value="delete_permanently"><?php echo esc_html__('Delete permanently', 'vendor-space'); ?></option>
                    </select>
                    <button type="button" id="vs-vendors-bulk-apply" class="vs-btn-primary" style="background:#2563eb; color:white; border:none; padding: 10px 16px; border-radius: 10px; cursor:pointer; font-weight:800;">
                        <?php echo esc_html__('Apply', 'vendor-space'); ?>
                    </button>
                </div>
            </div>

            <!-- Vendors Table -->
            <div class="vs-table-responsive" id="vs-users-table-wrap" style="background: white; border-radius: 12px; overflow-x: auto; -webkit-overflow-scrolling: touch; box-shadow: 0 4px 6px rgba(0,0,0,0.05);">
                <table class="vs-vendors-table" style="width: 100%; border-collapse: collapse; text-align: left;">
                    <thead>
                        <tr style="background: #f8fafc; border-bottom: 1px solid #e2e8f0;">
                            <th style="padding: 15px 14px; font-weight: 600; color: #475569; width:44px;">
                                <input type="checkbox" id="vs-vendors-select-all" style="width:16px; height:16px; cursor:pointer;">
                            </th>
                            <th style="padding: 15px 20px; font-weight: 600; color: #475569;"><?php echo esc_html__('User', 'vendor-space'); ?></th>
                            <th style="padding: 15px 20px; font-weight: 600; color: #475569;"><?php echo esc_html__('User Info', 'vendor-space'); ?></th>
                            <th style="padding: 15px 20px; font-weight: 600; color: #475569;"><?php echo esc_html__('Type', 'vendor-space'); ?></th>
                            <th style="padding: 15px 20px; font-weight: 600; color: #475569;"><?php echo esc_html__('Status', 'vendor-space'); ?></th>
                            <th style="padding: 15px 20px; font-weight: 600; color: #475569;"><?php echo esc_html__('Sales', 'vendor-space'); ?></th>
                            <th style="padding: 15px 20px; font-weight: 600; color: #475569; text-align: right;display:flex; justify-content:center;"><?php echo esc_html__('Actions', 'vendor-space'); ?></th>
                        </tr>
                    </thead>
                    <tbody id="vs-vendors-list-body">
                        <!-- Loaded via AJAX -->
                    </tbody>
                </table>
            </div>
            
            <div id="vs-vendors-pagination" style="margin-top:20px; display:flex; justify-content:flex-end; gap:10px; align-items:center; min-height:40px;">
                <button type="button" class="vs-page-btn is-disabled" style="padding:15px 15px; cursor:not-allowed; opacity:0.5; border:1px solid #e5e7eb; border-radius:10px; background:#fff; color:#0f172a; font-weight:700;" disabled><?php echo esc_html__('Prev', 'vendor-space'); ?></button>
                <button type="button" class="vs-page-btn is-active" style="padding:15px 15px; background:#2563eb; color:white; border:1px solid #2563eb; border-radius:10px; font-weight:700;">1</button>
                <button type="button" class="vs-page-btn is-disabled" style="padding:15px 15px; cursor:not-allowed; opacity:0.5; border:1px solid #e5e7eb; border-radius:10px; background:#fff; color:#0f172a; font-weight:700;" disabled><?php echo esc_html__('Next', 'vendor-space'); ?></button>
            </div>
        </div>

        <!-- Vendor Edit Modal -->
        <div id="vs-vendor-edit-modal" class="vs-modal" style="display:none; position:fixed; z-index:9999; left:0; top:0; width:100%; height:100%; background:rgba(0,0,0,0.5); align-items:center; justify-content:center;">
            <div class="vs-modal-content" style="background:white; padding:30px; border-radius:16px; width:90%; max-width:600px; max-height:90vh; overflow-y:auto; position:relative; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1);">
                <span class="vs-close-modal" style="position:absolute; right:20px; top:20px; cursor:pointer; font-size:24px; color:#94a3b8;">&times;</span>
                <h3 id="vs-edit-user-modal-title" style="margin-top:0; margin-bottom:25px; color:#1e293b; border-bottom: 1px solid #e2e8f0; padding-bottom:15px;"><?php echo esc_html__('Edit User Details', 'vendor-space'); ?></h3>
                <form id="vs-vendor-edit-form">
                    <input type="hidden" name="vendor_id" id="edit-vendor-id">
                    <input type="hidden" name="is_vendor" id="edit-is-vendor" value="0">
                    
                    <div style="display:grid; grid-template-columns: 1fr 1fr; gap:20px;">
                        <div class="vs-form-group" style="margin-bottom:15px;">
                            <label style="display:block; margin-bottom:8px; font-weight:600; color:#475569;"><?php echo esc_html__('Display Name', 'vendor-space'); ?></label>
                            <input type="text" name="display_name" id="edit-display-name" style="width:100%; padding:10px; border:1px solid #e2e8f0; border-radius:8px;" required>
                        </div>
                        <div class="vs-form-group" style="margin-bottom:15px;">
                            <label style="display:block; margin-bottom:8px; font-weight:600; color:#475569;"><?php echo esc_html__('Email', 'vendor-space'); ?></label>
                            <input type="email" name="user_email" id="edit-vendor-email" style="width:100%; padding:10px; border:1px solid #e2e8f0; border-radius:8px;" readonly>
                        </div>
                    </div>

                    <div id="vs-store-fields-wrap" style="display:none;">
                        <div style="display:grid; grid-template-columns: 1fr 1fr; gap:20px;">
                            <div class="vs-form-group" style="margin-bottom:15px;">
                                <label style="display:block; margin-bottom:8px; font-weight:600; color:#475569;"><?php echo esc_html__('Store Name', 'vendor-space'); ?></label>
                                <input type="text" name="store_name" id="edit-store-name" style="width:100%; padding:10px; border:1px solid #e2e8f0; border-radius:8px;">
                            </div>
                            <div class="vs-form-group" style="margin-bottom:15px;">
                                <label style="display:block; margin-bottom:8px; font-weight:600; color:#475569;"><?php echo esc_html__('Location', 'vendor-space'); ?></label>
                                <input type="text" name="store_location" id="edit-store-location" style="width:100%; padding:10px; border:1px solid #e2e8f0; border-radius:8px;">
                            </div>
                        </div>

                        <div class="vs-form-group" style="margin-bottom:15px;">
                            <label style="display:block; margin-bottom:8px; font-weight:600; color:#475569;"><?php echo esc_html__('Store Description', 'vendor-space'); ?></label>
                            <textarea name="store_description" id="edit-store-desc" rows="3" style="width:100%; padding:10px; border:1px solid #e2e8f0; border-radius:8px;"></textarea>
                        </div>

                        <div class="vs-form-group" style="margin-bottom:15px; display:flex; align-items:center; gap:12px;">
                            <input type="hidden" name="store_logo_id" id="edit-store-logo-id" value="">
                            <img id="edit-store-logo-preview" class="vs-store-logo-preview" src="" alt="" style="display:none; border-radius:8px;max-width:80%;height:80px;">
                            <div style="display:flex; gap:8px; align-items:center;">
                                <button type="button" id="edit-store-logo-button" class="button" style="padding:8px 12px; border-radius:8px; background:#2563eb; color:#fff; border:none; cursor:pointer;"><?php echo esc_html__('Select Logo', 'vendor-space'); ?></button>
                                <button type="button" id="edit-store-logo-remove" class="button" style="padding:8px 12px; border-radius:8px; background:#ef4444; color:#fff; border:none; cursor:pointer; display:none;"><?php echo esc_html__('Remove', 'vendor-space'); ?></button>
                            </div>
                        </div>
                    </div>

                    <div style="display:grid; grid-template-columns: 1fr 1fr; gap:20px;">
                        <div class="vs-form-group" style="margin-bottom:15px;">
                            <label style="display:block; margin-bottom:8px; font-weight:600; color:#475569;"><?php echo esc_html__('Status', 'vendor-space'); ?></label>
                            <select name="vendor_status" id="edit-vendor-status" style="width:100%; padding:10px; border:1px solid #e2e8f0; border-radius:8px;">
                                <option value="active"><?php echo esc_html__('Active', 'vendor-space'); ?></option>
                                <option value="deleted"><?php echo esc_html__('Deleted (Soft)', 'vendor-space'); ?></option>
                            </select>
                        </div>
                    </div>

                    <div style="margin-top:30px; display:flex; justify-content:flex-end; gap:10px;">
                        <button type="button" class="vs-close-modal" style="padding:10px 20px; border:1px solid #e2e8f0; border-radius:8px; background:white; cursor:pointer;"><?php echo esc_html__('Cancel', 'vendor-space'); ?></button>
                        <button type="submit" style="padding:10px 25px; border:none; border-radius:8px; background:#2563eb; color:white; cursor:pointer; font-weight:600;"><?php echo esc_html__('Save Changes', 'vendor-space'); ?></button>
                    </div>
                </form>
            </div>
        </div>

        <script>
        jQuery(document).ready(function($) {
            var vs_security = '';
            try {
                vs_security = (typeof vs_vars !== 'undefined' && (vs_vars.setup_nonce || vs_vars.nonce)) ? (vs_vars.setup_nonce || vs_vars.nonce) : '';
            } catch (e) {
                vs_security = '';
            }
            let currentSearch = '';
            let currentFilter = 'all_users';
            let currentStatus = 'all';
            let currentPage = 1;

            function vsParseMaybeJson(resp) {
                if (resp && typeof resp === 'object') return resp;
                if (typeof resp !== 'string') return null;
                const cleaned = resp.replace(/^\uFEFF/, '').trim();
                try { return JSON.parse(cleaned); } catch (e) { return null; }
            }

            function vsRenderLoadError(message, raw) {
                const safeMsg = message ? String(message) : '<?php echo esc_js(__('Failed to load users.', 'vendor-space')); ?>';
                let safeRaw = '';
                if (raw !== undefined && raw !== null) {
                    safeRaw = String(raw);
                    if (safeRaw.length > 600) safeRaw = safeRaw.slice(0, 600) + '...';
                    safeRaw = safeRaw
                        .replace(/</g, '&lt;')
                        .replace(/>/g, '&gt;');
                }

                $('#vs-vendors-list-body').html(
                    '<tr><td colspan="7" style="padding:18px 20px; color:#b91c1c; font-weight:700;">' +
                        safeMsg +
                        (safeRaw ? '<div style="margin-top:8px; color:#64748b; font-weight:500; font-family:monospace; white-space:pre-wrap;">' + safeRaw + '</div>' : '') +
                    '</td></tr>'
                );
            }

            function vsGetSelectedVendorIds() {
                const ids = [];
                $('#vs-vendors-list-body .vs-vendor-bulk-checkbox:checked').each(function() {
                    const id = parseInt($(this).val(), 10);
                    if (!isNaN(id) && id > 0) ids.push(id);
                });
                return ids;
            }

            function vsUpdateSelectedCount() {
                const count = vsGetSelectedVendorIds().length;
                $('#vs-vendors-selected-count').text(count + ' <?php echo esc_js(__('selected', 'vendor-space')); ?>');
            }

            function loadVendors() {
                $.ajax({
                    url: vs_vars.ajaxurl,
                    type: 'POST',
                    dataType: 'text',
                    data: {
                        action: 'vs_get_vendors',
                        search: currentSearch,
                        filter: currentFilter,
                        status: currentStatus,
                        page: currentPage,
                        security: vs_security
                    },
                    beforeSend: function() {
                        $('#vs-vendors-list-body').html('<tr><td colspan="7" style="padding:18px 20px; color:#64748b;"><?php echo esc_js(__('Loading...', 'vendor-space')); ?></td></tr>');
                    },
                    success: function(raw) {
                        const response = vsParseMaybeJson(raw);
                        if (!response) {
                            const trimmed = String(raw || '').replace(/^\uFEFF/, '').trim();
                            const msg = (trimmed === '-1' || trimmed === '0') ? '<?php echo esc_js(__('Security check failed (nonce). Refresh the page and try again.', 'vendor-space')); ?>' : '<?php echo esc_js(__('AJAX returned non-JSON.', 'vendor-space')); ?>';
                            vsRenderLoadError(msg, trimmed);
                            return;
                        }

                        if (response.success && response.data) {
                            $('#vs-vendors-list-body').html(response.data.html || '');
                            $('#vs-total-vendors-count').text(response.data.total_all ?? '0');
                            $('#vs-active-vendors-count').text(response.data.total_active ?? '0');
                            $('#vs-deleted-vendors-count').text(response.data.total_deleted ?? '0');
                            $('#vs-vendors-pagination').html(response.data.pagination || '');
                            if (typeof window.vsRefreshTableSorters === 'function') {
                                window.vsRefreshTableSorters('#tab-vendors-management');
                            }
                            $('#vs-vendors-select-all').prop('checked', false);
                            vsUpdateSelectedCount();
                            // ─── Highlight search term in yellow ──────────────
                            vsHighlightSearch(response.data.search || '');
                        } else {
                            vsRenderLoadError(response.data || '<?php echo esc_js(__('Failed to load users.', 'vendor-space')); ?>', raw);
                        }
                    },
                    error: function(xhr, status, error) {
                        const body = xhr && xhr.responseText ? xhr.responseText : '';
                        vsRenderLoadError('Request failed: ' + status + (error ? ' (' + error + ')' : ''), body);
                    }
                });
            }

            // ─── Highlight matching text in yellow inside the table ──────────────
            function vsHighlightSearch(term) {
                const $body = $('#vs-vendors-list-body');
                $body.find('mark.vs-hl').each(function() {
                    $(this).replaceWith(document.createTextNode($(this).text()));
                });
                if (!term || term.length < 1) return;
                const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
                const regex = new RegExp('(' + escaped + ')', 'gi');
                $body.find('td:nth-child(2), td:nth-child(3)').each(function() {
                    vsHighlightNode(this, regex);
                });
            }
            function vsHighlightNode(node, regex) {
                $(node).contents().each(function() {
                    if (this.nodeType === 3) {
                        const text = this.nodeValue;
                        if (regex.test(text)) {
                            const span = document.createElement('span');
                            span.innerHTML = text.replace(regex,
                                '<mark class="vs-hl" style="background:#FDE047;color:#1e293b;border-radius:3px;padding:0 2px;">$1</mark>'
                            );
                            this.parentNode.replaceChild(span, this);
                        }
                        regex.lastIndex = 0;
                    } else if (this.nodeType === 1 && !$(this).is('mark,input,button,select,textarea')) {
                        vsHighlightNode(this, regex);
                    }
                });
            }

            // ─── Tab click: load users when tab is opened ───────────────────────────
            $(document).on('click', '.vs-tab-link[data-tab="vendors-management"]', function() {
                const selectedFilter = $(this).data('filter');
                if (selectedFilter) {
                    currentFilter = selectedFilter;
                    $('#vs-vendor-type-filter').val(currentFilter);
                }
                loadVendors();
            });

            // ─── FIX: Load immediately if the tab is already visible on page load ──
            if ($('#tab-vendors-management').is(':visible')) {
                loadVendors();
            }

            // ─── FIX: Search — use event delegation + debounce ───────────────────
            // Delegation via $(document) ensures the listener works even if the
            // input is rendered after this script runs (dynamic tabs).
            // Debounce (350 ms) avoids firing an AJAX call on every keystroke.
            let vsSearchTimer = null;
            $(document).on('keyup input', '#vs-vendor-search', function() {
                clearTimeout(vsSearchTimer);
                currentSearch = $(this).val().trim();
                currentPage = 1;
                vsSearchTimer = setTimeout(function() {
                    loadVendors();
                }, 350);
            });

            // Filter
            $('#vs-vendor-type-filter').on('change', function() {
                currentFilter = $(this).val();
                currentPage = 1;
                loadVendors();
            });

            $('#vs-vendor-status-filter').on('change', function() {
                currentStatus = $(this).val();
                currentPage = 1;
                loadVendors();
            });

            // Bulk selection
            $(document).on('change', '#vs-vendors-select-all', function() {
                const checked = $(this).is(':checked');
                $('#vs-vendors-list-body .vs-vendor-bulk-checkbox').prop('checked', checked);
                vsUpdateSelectedCount();
            });
            $(document).on('change', '#vs-vendors-list-body .vs-vendor-bulk-checkbox', function() {
                const $boxes = $('#vs-vendors-list-body .vs-vendor-bulk-checkbox');
                const $checked = $('#vs-vendors-list-body .vs-vendor-bulk-checkbox:checked');
                $('#vs-vendors-select-all').prop('checked', $boxes.length > 0 && $checked.length === $boxes.length);
                vsUpdateSelectedCount();
            });

            // Bulk apply
            $(document).on('click', '#vs-vendors-bulk-apply', function() {
                const action = $('#vs-vendors-bulk-action').val();
                const ids = vsGetSelectedVendorIds();
                if (!action) {
                    Swal.fire('<?php echo esc_js(__('Select action', 'vendor-space')); ?>', '<?php echo esc_js(__('Please choose a bulk action first.', 'vendor-space')); ?>', 'info');
                    return;
                }
                if (!ids.length) {
                    Swal.fire('<?php echo esc_js(__('No users selected', 'vendor-space')); ?>', '<?php echo esc_js(__('Please select at least one user.', 'vendor-space')); ?>', 'info');
                    return;
                }

                let title = '<?php echo esc_js(__('Apply bulk action?', 'vendor-space')); ?>';
                let text = '<?php echo esc_js(__('This will apply the selected action to %s users.', 'vendor-space')); ?>'.replace('%s', ids.length);
                let confirmText = '<?php echo esc_js(__('Apply', 'vendor-space')); ?>';
                let confirmColor = '#2563eb';
                if (action === 'ban') {
                    title = '<?php echo esc_js(__('Ban selected users?', 'vendor-space')); ?>';
                    text = '<?php echo esc_js(__('Selected users will be blocked (soft ban).', 'vendor-space')); ?>';
                    confirmText = '<?php echo esc_js(__('Yes, ban', 'vendor-space')); ?>';
                    confirmColor = '#d33';
                } else if (action === 'restore') {
                    title = '<?php echo esc_js(__('Restore selected users?', 'vendor-space')); ?>';
                    text = '<?php echo esc_js(__('Selected users will be restored to active.', 'vendor-space')); ?>';
                    confirmText = '<?php echo esc_js(__('Yes, restore', 'vendor-space')); ?>';
                    confirmColor = '#16a34a';
                } else if (action === 'delete_permanently') {
                    title = '<?php echo esc_js(__('Delete permanently?', 'vendor-space')); ?>';
                    text = '<?php echo esc_js(__('This will permanently delete selected user accounts and cannot be undone.', 'vendor-space')); ?>';
                    confirmText = '<?php echo esc_js(__('Yes, delete permanently', 'vendor-space')); ?>';
                    confirmColor = '#b91c1c';
                }

                Swal.fire({
                    title: title,
                    text: text,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: confirmColor,
                    confirmButtonText: confirmText
                }).then((result) => {
                    if (!result.isConfirmed) return;

                    $.ajax({
                        url: vs_vars.ajaxurl,
                        type: 'POST',
                        dataType: 'text',
                        data: {
                                action: 'vs_bulk_vendor_action',
                                bulk_action: action,
                                vendor_ids: ids,
                                security: vs_security
                            },
                        success: function(raw) {
                            const resp = vsParseMaybeJson(raw);
                            if (!resp) {
                                Swal.fire('<?php echo esc_js(__('Error', 'vendor-space')); ?>', '<?php echo esc_js(__('AJAX returned non-JSON.', 'vendor-space')); ?>', 'error');
                                return;
                            }
                            if (resp.success) {
                                const d = resp.data || {};
                                const safe = (v) => String(v ?? '').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                                const msg = safe(d.message ? d.message : '<?php echo esc_js(__('Bulk action completed.', 'vendor-space')); ?>');
                                const summary = d.summary ? safe(d.summary) : '';
                                Swal.fire({ title: '<?php echo esc_js(__('Success', 'vendor-space')); ?>', html: msg + (summary ? ('<br><div style=\"margin-top:8px; color:#64748b; font-weight:600;\">' + summary + '</div>') : ''), icon: 'success' });
                                $('#vs-vendors-bulk-action').val('');
                                loadVendors();
                            } else {
                                Swal.fire('<?php echo esc_js(__('Error', 'vendor-space')); ?>', resp.data || '<?php echo esc_js(__('Bulk action failed.', 'vendor-space')); ?>', 'error');
                            }
                        },
                        error: function(xhr, status, error) {
                            Swal.fire('<?php echo esc_js(__('Error', 'vendor-space')); ?>', '<?php echo esc_js(__('Request failed:', 'vendor-space')); ?>' + ' ' + status + (error ? ' (' + error + ')' : ''), 'error');
                        }
                    });
                });
            });

            // Pagination
            $(document).on('click', '.vs-vendor-page-link', function(e) {
                e.preventDefault();
                currentPage = $(this).data('page');
                loadVendors();
            });

            // Edit Vendor Modal
            $(document).on('click', '.vs-edit-vendor-btn', function() {
                const data = $(this).data();
                $('#edit-vendor-id').val(data.id);
                $('#edit-is-vendor').val(data.isVendor ? '1' : '0');
                $('#edit-display-name').val(data.displayName || '');
                $('#edit-store-name').val(data.storeName);
                $('#edit-store-location').val(data.storeLocation);
                $('#edit-store-desc').val(data.storeDesc);
                $('#edit-vendor-email').val(data.email);
                $('#edit-vendor-status').val(data.status);

                $('#edit-store-logo-id').val(data.storeLogoId || '');
                if (data.storeLogoUrl) {
                    $('#edit-store-logo-preview').attr('src', data.storeLogoUrl).show();
                    $('#edit-store-logo-remove').show();
                } else {
                    $('#edit-store-logo-preview').hide().attr('src', '');
                    $('#edit-store-logo-remove').hide();
                }

                const isVendor = !!data.isVendor;
                const $storeWrap = $('#vs-store-fields-wrap');
                $storeWrap.toggle(isVendor);
                $storeWrap.find('input, textarea, select').prop('disabled', !isVendor);
                $('#vs-edit-user-modal-title').text(isVendor ? '<?php echo esc_js(__('Edit Vendor Details', 'vendor-space')); ?>' : '<?php echo esc_js(__('Edit Customer Details', 'vendor-space')); ?>');
                
                $('#vs-vendor-edit-modal').css('display', 'flex').hide().fadeIn(200);
            });

            $('.vs-close-modal').on('click', function() {
                $('#vs-vendor-edit-modal').fadeOut(200);
            });

            // Save Vendor
            $('#vs-vendor-edit-form').on('submit', function(e) {
                e.preventDefault();
                const formData = $(this).serialize();
                $.ajax({
                    url: vs_vars.ajaxurl,
                    type: 'POST',
                    data: formData + '&action=vs_update_vendor&security=' + encodeURIComponent(vs_security),
                    success: function(response) {
                        if (response.success) {
                            Swal.fire('<?php echo esc_js(__('Success', 'vendor-space')); ?>', '<?php echo esc_js(__('User updated successfully', 'vendor-space')); ?>', 'success');
                            $('#vs-vendor-edit-modal').fadeOut(200);
                            loadVendors();
                        } else {
                            Swal.fire('<?php echo esc_js(__('Error', 'vendor-space')); ?>', response.data || '<?php echo esc_js(__('Failed to update user', 'vendor-space')); ?>', 'error');
                        }
                    }
                });
            });

            // Media picker for store logo
            let vsMediaFrame = null;
            $(document).on('click', '#edit-store-logo-button', function(e) {
                e.preventDefault();
                if (typeof wp === 'undefined' || !wp.media) {
                    alert('<?php echo esc_js(__('Media uploader not available.', 'vendor-space')); ?>');
                    return;
                }
                if (vsMediaFrame) vsMediaFrame.close();
                vsMediaFrame = wp.media({
                    title: '<?php echo esc_js(__('Select Store Logo', 'vendor-space')); ?>',
                    library: { type: 'image' },
                    multiple: false,
                    button: { text: '<?php echo esc_js(__('Select', 'vendor-space')); ?>' }
                });
                vsMediaFrame.on('select', function() {
                    const attachment = vsMediaFrame.state().get('selection').first().toJSON();
                    if (!attachment) return;
                    $('#edit-store-logo-id').val(attachment.id);
                    const thumb = (attachment.sizes && attachment.sizes.thumbnail) ? attachment.sizes.thumbnail.url : attachment.url;
                    $('#edit-store-logo-preview').attr('src', thumb).show();
                    $('#edit-store-logo-remove').show();
                });
                vsMediaFrame.open();
            });

            $(document).on('click', '#edit-store-logo-remove', function(e) {
                e.preventDefault();
                $('#edit-store-logo-id').val('');
                $('#edit-store-logo-preview').hide().attr('src', '');
                $(this).hide();
            });

            // Delete Vendor (Soft)
            $(document).on('click', '.vs-delete-vendor-btn', function() {
                const vendorId = $(this).data('id');
                Swal.fire({
                    title: '<?php echo esc_js(__('Ban User?', 'vendor-space')); ?>',
                    text: '<?php echo esc_js(__('The user will be marked as Banned but their data will remain.', 'vendor-space')); ?>',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    confirmButtonText: '<?php echo esc_js(__('Yes, Ban!', 'vendor-space')); ?>'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: vs_vars.ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'vs_delete_vendor',
                                vendor_id: vendorId,
                                security: vs_security
                            },
                            success: function(response) {
                                if (response.success) {
                                    Swal.fire('<?php echo esc_js(__('Banned', 'vendor-space')); ?>', '<?php echo esc_js(__('Vendor has been soft-deleted.', 'vendor-space')); ?>', 'success');
                                    loadVendors();
                                }
                            }
                        });
                    }
                });
            });

            // Delete Vendor (Permanent)
            $(document).on('click', '.vs-delete-vendor-permanently-btn', function() {
                const vendorId = $(this).data('id');
                Swal.fire({
                    title: '<?php echo esc_js(__('Delete permanently?', 'vendor-space')); ?>',
                    text: '<?php echo esc_js(__('This will permanently delete the user account and cannot be undone.', 'vendor-space')); ?>',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#b91c1c',
                    confirmButtonText: '<?php echo esc_js(__('Yes, delete permanently', 'vendor-space')); ?>'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: vs_vars.ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'vs_delete_vendor_permanently',
                                vendor_id: vendorId,
                                security: vs_security
                            },
                            success: function(response) {
                                if (response.success) {
                                    Swal.fire('<?php echo esc_js(__('Deleted', 'vendor-space')); ?>', '<?php echo esc_js(__('User has been permanently deleted.', 'vendor-space')); ?>', 'success');
                                    loadVendors();
                                } else {
                                    Swal.fire('<?php echo esc_js(__('Error', 'vendor-space')); ?>', response.data || '<?php echo esc_js(__('Failed to delete user.', 'vendor-space')); ?>', 'error');
                                }
                            }
                        });
                    }
                });
            });

            // Restore Vendor
            $(document).on('click', '.vs-restore-vendor-btn', function() {
                const vendorId = $(this).data('id');
                $.ajax({
                    url: vs_vars.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'vs_restore_vendor',
                        vendor_id: vendorId,
                        security: vs_security
                    },
                    success: function(response) {
                        if (response.success) {
                            Swal.fire('<?php echo esc_js(__('Restored', 'vendor-space')); ?>', '<?php echo esc_js(__('Vendor has been activated.', 'vendor-space')); ?>', 'success');
                            loadVendors();
                        }
                    }
                });
            });

            // Export CSV
            $('#vs-export-vendors-csv').on('click', function() {
                window.location.href = vs_vars.ajaxurl + '?action=vs_export_vendors_csv&security=' + encodeURIComponent(vs_security);
            });

            // Message Vendor (Admin initiator)
            $(document).on('click', '.vs-admin-message-vendor-btn', function() {
                const vendorId = $(this).data('id');
                const adminId = <?php echo get_current_user_id(); ?>;
                
                $('.vs-tab-link[data-tab="notifications"]').click();
                
                const $app = $('#vs-vendor-chat-app');
                if ($app.length && typeof window.vsLoadChatThread === 'function') {
                    window.vsLoadChatThread(0, vendorId, adminId);
                }
            });
        });
        </script>
        <?php
        return ob_get_clean();
    }

    public static function get_vendors_ajax() {
        $security = isset($_POST['security']) ? sanitize_text_field($_POST['security']) : '';
        $nonce_ok = false;
        if ($security && (wp_verify_nonce($security, 'vs_setup_nonce') || wp_verify_nonce($security, 'vs_nonce'))) {
            $nonce_ok = true;
        }
        if (!$nonce_ok) {
            wp_send_json_error('Security check failed (nonce)');
        }
        if (!current_user_can('administrator')) wp_send_json_error('Permission denied');

        $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
        $filter = isset($_POST['filter']) ? sanitize_key($_POST['filter']) : 'all_users';
        $allowed_filters = ['all_users', 'vendors', 'customers', 'banned'];
        if (!in_array($filter, $allowed_filters, true)) {
            $filter = 'all_users';
        }
        $status = isset($_POST['status']) ? sanitize_key($_POST['status']) : 'all';
        if (!in_array($status, ['all', 'active', 'deleted'], true)) {
            $status = 'all';
        }
        $paged = isset($_POST['page']) ? intval($_POST['page']) : 1;
        $per_page = 10;

        $args = [
            'number' => -1,
            'fields' => 'all',
        ];

        $all_users = get_users($args);
        $vendors = [];

        foreach ($all_users as $user) {
            $uid = (int) $user->ID;
            if (user_can($uid, 'manage_options')) {
                continue;
            }

            $store_name_meta = trim((string) get_user_meta($uid, 'vs_store_name', true));
            $location = (string) get_user_meta($uid, 'vs_store_location', true);
            $is_vendor_role = in_array('vendor', (array) $user->roles, true);
            $can_edit_products = user_can($uid, 'edit_products');
            $is_vendor = ($is_vendor_role || $can_edit_products);
            $is_customer = in_array('customer', (array) $user->roles, true) && !$is_vendor;
            $v_status = get_user_meta($uid, 'vs_vendor_status', true) ?: 'active';
            $is_banned = ($v_status === 'deleted');

            if (!$is_vendor && !$is_customer) {
                continue;
            }

            $matches_filter = false;
            if ($filter === 'all_users') {
                $matches_filter = true;
            } elseif ($filter === 'vendors') {
                $matches_filter = $is_vendor;
            } elseif ($filter === 'customers') {
                $matches_filter = $is_customer;
            } elseif ($filter === 'banned') {
                $matches_filter = $is_banned;
            }
            if (!$matches_filter) {
                continue;
            }

            if ($status !== 'all' && $v_status !== $status) {
                continue;
            }

            $store_name = $store_name_meta !== '' ? $store_name_meta : $user->display_name;
            $roles_text = implode(', ', (array) $user->roles);
            if (!empty($search)) {
                $first_name = (string) $user->first_name;
                $last_name = (string) $user->last_name;
                $haystack = $store_name . ' ' . $location . ' ' . $user->user_email . ' ' . $user->display_name . ' ' . $user->user_login . ' ' . $first_name . ' ' . $last_name . ' ' . $roles_text;
                
                if (stripos($haystack, $search) === false) {
                    continue;
                }
            }

            $vendors[] = $user;
        }

        // Stats
        $total_all = 0;
        $total_active = 0;
        $total_deleted = 0;
        
        foreach($all_users as $u) {
            if (user_can($u->ID, 'manage_options')) continue;
            $u_is_vendor = in_array('vendor', (array) $u->roles, true) || user_can((int) $u->ID, 'edit_products');
            $u_is_customer = in_array('customer', (array) $u->roles, true) && !$u_is_vendor;
            if (!$u_is_vendor && !$u_is_customer) continue;
            $total_all++;
            $st = get_user_meta($u->ID, 'vs_vendor_status', true) ?: 'active';
            if ($st !== 'deleted') $total_active++;
            elseif ($st === 'deleted') $total_deleted++;
        }

        $total_found = count($vendors);
        $total_pages = ceil($total_found / $per_page);
        $paged_vendors = array_slice($vendors, ($paged - 1) * $per_page, $per_page);

        $all_completed_orders = wc_get_orders(['status' => 'completed', 'limit' => -1]);
        $vendor_sales_map = [];
        foreach ($all_completed_orders as $order) {
            foreach ($order->get_items() as $item) {
                $v_id = $item->get_meta('_vs_vendor_id');
                if (empty($v_id)) {
                    $product = $item->get_product();
                    if ($product) $v_id = get_post_field('post_author', $product->get_id());
                }
                if ($v_id) {
                    if (!isset($vendor_sales_map[$v_id])) $vendor_sales_map[$v_id] = 0;
                    $vendor_sales_map[$v_id] += (float)$item->get_total();
                }
            }
        }

        

        ob_start();
        if (empty($paged_vendors)) {
            ?>
            <tr>
                <td colspan="7" class="vs-empty-results-cell">
                    <style>
                        .vs-empty-results-cell { padding: 56px 20px; text-align: center; }
                    </style>
                    <div class="vs-empty-results">
                        <div class="vs-empty-results-icon">
                            <i class="fas fa-user-slash"></i>
                        </div>
                        <div class="vs-empty-results-title">
                            <?php echo esc_html__('No results found', 'vendor-space'); ?>
                        </div>
                        <div class="vs-empty-results-subtitle">
                            <?php echo esc_html__('Try changing the selected filter or search keyword.', 'vendor-space'); ?>
                        </div>
                    </div>
                    <style>
                    .vs-empty-results { text-align:center; padding:35px 20px; border-radius:16px; border:1px dashed #dbe3ee; background:linear-gradient(180deg,#ffffff,#f8fafc); margin:30px auto; max-width:500px; transition:all 0.35s ease; }
                    .vs-empty-results:hover { transform:translateY(-4px); box-shadow:0 12px 28px rgba(0,0,0,0.08); }
                    .vs-empty-results-icon { font-size:60px; color:#cbd5e1; margin-bottom:12px; animation:vsFloatUser 3s ease-in-out infinite; }
                    .vs-empty-results-title { font-size:18px; font-weight:700; color:#1e293b; margin-bottom:6px; }
                    .vs-empty-results-subtitle { font-size:14px; color:#64748b; }
                    @keyframes vsFloatUser { 0%,100%{transform:translateY(0)} 50%{transform:translateY(-6px)} }
                    </style>
                </td>
            </tr>
            <?php
        } else {
            foreach ($paged_vendors as $vendor) {
                $v_id = $vendor->ID;
                $store_name = get_user_meta($v_id, 'vs_store_name', true) ?: $vendor->display_name;
                $location = get_user_meta($v_id, 'vs_store_location', true);
                $v_status = get_user_meta($v_id, 'vs_vendor_status', true) ?: 'active';
                $is_vendor_role = in_array('vendor', (array) $vendor->roles, true);
                $can_edit_products = user_can($v_id, 'edit_products');
                $is_vendor = ($is_vendor_role || $can_edit_products);
                $is_customer = in_array('customer', (array) $vendor->roles, true) && !$is_vendor;
                $logo_id = get_user_meta($v_id, 'vs_store_logo_id', true);
                $logo_url = $logo_id ? wp_get_attachment_image_url($logo_id, 'thumbnail') : '';
                
                $total_sales = isset($vendor_sales_map[$v_id]) ? $vendor_sales_map[$v_id] : 0;
                
                $status_label = ($v_status === 'active') ? '<span style="background:#dcfce7; color:#166534; padding:4px 10px; border-radius:12px; font-size:12px; font-weight:600;">' . esc_html__('Active', 'vendor-space') . '</span>' : '<span style="background:#fee2e2; color:#991b1b; padding:4px 10px; border-radius:12px; font-size:12px; font-weight:600;">' . esc_html__('Deleted', 'vendor-space') . '</span>';
                if ($is_vendor) {
                    $user_type = __('Vendor', 'vendor-space');
                    $type_badge = 'background:#dcfce7;color:#166534;';
                } elseif ($is_customer) {
                    $user_type = __('Customer', 'vendor-space');
                    $type_badge = 'background:#fef3c7;color:#92400e;';
                } else {
                    $user_type = __('User', 'vendor-space');
                    $type_badge = 'background:#e2e8f0;color:#334155;';
                }
                $roles_text = implode(', ', (array) $vendor->roles);
                if ($roles_text === '') {
                    $roles_text = __('none', 'vendor-space');
                }
                $display_name = $vendor->display_name ?: $vendor->user_login;
                $store_details_url = '';
                if ($is_vendor) {
                    $store_details_url = get_author_posts_url($v_id);
                }

                ?>
                <tr style="border-bottom: 1px solid #f1f5f9;">
                    <td style="padding: 15px 14px;">
                        <input type="checkbox" class="vs-vendor-bulk-checkbox" value="<?php echo (int) $v_id; ?>" style="width:16px; height:16px; cursor:pointer;">
                    </td>
                    <td style="padding: 15px 20px;">
                        <div style="display:flex; align-items:center; gap:12px;">
                            <?php if($logo_url): ?>
                                <img src="<?php echo esc_url($logo_url); ?>" style="width:40px; height:40px; border-radius:50%; object-fit:cover;">
                            <?php else: ?>
                                <div style="width:40px; height:40px; border-radius:50%; background:#e2e8f0; display:flex; align-items:center; justify-content:center; color:#64748b; font-weight:700;">
                                    <?php echo strtoupper(substr($display_name, 0, 1)); ?>
                                </div>
                            <?php endif; ?>
                            <div>
                                <div style="font-weight:600; color:#1e293b;"><?php echo esc_html($display_name); ?></div>
                            </div>
                        </div>
                    </td>
                    <td style="padding: 15px 20px;">
                        <div style="color:#475569; font-size:13px;"><?php echo esc_html($vendor->user_email); ?></div>
                        <div style="font-size:12px; color:#94a3b8; margin-top:4px;"><?php echo esc_html__('Roles:', 'vendor-space'); ?> <?php echo esc_html($roles_text); ?></div>
                        <?php if ($is_vendor): ?>
                            <div style="font-size:12px; color:#94a3b8; margin-top:4px;">
                                <?php echo esc_html__('Store:', 'vendor-space'); ?>
                                <a href="<?php echo esc_url($store_details_url); ?>" style="color:#2563eb; text-decoration:none; font-weight:600;">
                                    <?php echo esc_html($store_name); ?>
                                </a>
                                <?php if ($location): ?> | <?php echo esc_html($location); ?><?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </td>
                    <td style="padding: 15px 20px;">
                        <span style="padding:4px 10px; border-radius:12px; font-size:12px; font-weight:600; <?php echo esc_attr($type_badge); ?>">
                            <?php echo esc_html($user_type); ?>
                        </span>
                    </td>
                    <td style="padding: 15px 20px;">
                        <?php echo $status_label; ?>
                    </td>
                    <td style="padding: 15px 20px;">
                        <div style="font-weight:700; color:#14b8a6;"><?php echo wc_price($total_sales); ?></div>
                    </td>
                    <td style="padding: 15px 20px; text-align: right;">
                        <button class="vs-edit-vendor-btn" 
                                data-id="<?php echo $v_id; ?>" 
                                data-display-name="<?php echo esc_attr($display_name); ?>"
                                data-is-vendor="<?php echo $is_vendor ? '1' : '0'; ?>"
                                data-store-name="<?php echo esc_attr($store_name); ?>"
                                data-store-location="<?php echo esc_attr($location); ?>"
                                data-store-desc="<?php echo esc_attr(get_user_meta($v_id, 'vs_store_desc', true)); ?>"
                                data-email="<?php echo esc_attr($vendor->user_email); ?>"
                                data-status="<?php echo esc_attr($v_status); ?>"
                                data-store-logo-url="<?php echo esc_url($logo_url); ?>"
                                style="background:#f1f5f9; color:#475569; border:none; width:32px; height:32px; border-radius:8px; cursor:pointer; margin-right:5px;" title="<?php echo esc_attr__('Edit', 'vendor-space'); ?>">
                            <i class="fas fa-edit"></i>
                        </button>
                    <?php    if ( function_exists('is_plugin_active') && is_plugin_active('vendor space pro/vendor-space.php') ) :
                             if ( class_exists('VS_Pro_LiveChat') && VS_Modules::is_active('live_chat')  ) :
    ?>
                        <button class="vs-admin-message-vendor-btn" 
                                data-id="<?php echo $v_id; ?>" 
                                data-display-name="<?php echo esc_attr($display_name); ?>"
                                style="background:#f0f9ff; color:#0369a1; border:none; width:32px; height:32px; border-radius:8px; cursor:pointer;" title="<?php echo esc_attr__('Message', 'vendor-space'); ?>">
                            <i class="fas fa-comment"></i>
                        </button>
                        <?php
                        endif;
                        endif;
                        ?>
                        <?php if($v_status === 'active'): ?>
                            <button class="vs-delete-vendor-btn" data-id="<?php echo $v_id; ?>" style="background:#fee2e2; color:#ef4444; border:none; width:32px; height:32px; border-radius:8px; cursor:pointer;" title="<?php echo esc_attr__('Delete', 'vendor-space'); ?>">
                                <i class="fas fa-trash-alt"></i>
                            </button>
                        <?php else: ?>
                            <button class="vs-restore-vendor-btn" data-id="<?php echo $v_id; ?>" style="background:#dcfce7; color:#22c55e; border:none; width:32px; height:32px; border-radius:8px; cursor:pointer;" title="<?php echo esc_attr__('Restore', 'vendor-space'); ?>">
                                <i class="fas fa-undo"></i>
                            </button>
                            <button class="vs-delete-vendor-permanently-btn" data-id="<?php echo $v_id; ?>" style="background:#7f1d1d; color:#fff; border:none; width:32px; height:32px; border-radius:8px; cursor:pointer; margin-left:5px;" title="<?php echo esc_attr__('Delete permanently', 'vendor-space'); ?>">
                                <i class="fas fa-skull-crossbones"></i>
                            </button>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php
            }
        }
        $html = ob_get_clean();

        // Pagination HTML
        $pagination_html = '';
        $total_pages = max(1, $total_pages);
        
        $prev_disabled = ($paged === 1) ? 'is-disabled' : '';
        $prev_attr = ($paged === 1) ? 'disabled' : '';
        $prev_style = ($paged === 1) ? 'opacity:0.5; cursor:not-allowed;' : 'cursor:pointer;';
        $pagination_html .= '<button class="vs-vendor-page-link vs-page-btn '.$prev_disabled.'" data-page="'.max(1, $paged - 1).'" style="border:1px solid #e5e7eb; padding:8px 15px; border-radius:10px; background:#fff; color:#0f172a; font-weight:700; '.$prev_style.'" '.$prev_attr.'>' . esc_html__('Prev', 'vendor-space') . '</button>';

        for ($i = 1; $i <= $total_pages; $i++) {
            if ($total_pages > 5 && abs($i - $paged) > 2 && $i !== 1 && $i !== $total_pages) continue;
            
            $active_class = ($i === $paged) ? 'is-active' : '';
            $active_style = ($i === $paged) ? 'background:#2563eb; color:white; border-color:#2563eb;' : 'background:#fff; color:#0f172a; border-color:#e5e7eb;';
            $pagination_html .= '<button class="vs-vendor-page-link vs-page-btn '.$active_class.'" data-page="'.$i.'" style="border:1px solid; padding:8px 15px; border-radius:10px; cursor:pointer; font-weight:700; '.$active_style.'">'.$i.'</button>';
        }

        $next_disabled = ($paged === $total_pages) ? 'is-disabled' : '';
        $next_attr = ($paged === $total_pages) ? 'disabled' : '';
        $next_style = ($paged === $total_pages) ? 'opacity:0.5; cursor:not-allowed;' : 'cursor:pointer;';
        $pagination_html .= '<button class="vs-vendor-page-link vs-page-btn '.$next_disabled.'" data-page="'.min($total_pages, $paged + 1).'" style="border:1px solid #e5e7eb; padding:8px 15px; border-radius:10px; background:#fff; color:#0f172a; font-weight:700; '.$next_style.'" '.$next_attr.'>' . esc_html__('Next', 'vendor-space') . '</button>';

        wp_send_json_success([
            'html'          => $html,
            'total_all'     => $total_all,
            'total_active'  => $total_active,
            'total_deleted' => $total_deleted,
            'pagination'    => $pagination_html,
            'search'        => $search,   // ← passed to JS for highlight
        ]);
    }
public static function update_vendor_ajax() {
        // Accept either the setup nonce or the general plugin nonce for compatibility
        $security = isset($_REQUEST['security']) ? sanitize_text_field(wp_unslash($_REQUEST['security'])) : '';
        $nonce_ok = false;
        if ($security && (wp_verify_nonce($security, 'vs_setup_nonce') || wp_verify_nonce($security, 'vs_nonce'))) {
            $nonce_ok = true;
        }
        if (!$nonce_ok) wp_send_json_error(__('Security check failed (nonce)', 'vendor-space'));
        if (!current_user_can('administrator')) wp_send_json_error(__('Permission denied', 'vendor-space'));

        $vendor_id = intval($_POST['vendor_id'] ?? 0);
        if (!$vendor_id) wp_send_json_error(__('Invalid vendor ID', 'vendor-space'));

        $user = get_userdata($vendor_id);
        if (!$user) {
            wp_send_json_error(__('User not found', 'vendor-space'));
        }

        // "Username" here is display name shown in UI. (Changing user_login is risky.)
        $display_name = isset($_POST['display_name']) ? sanitize_text_field(wp_unslash($_POST['display_name'])) : '';
        if ($display_name !== '' && $display_name !== (string) $user->display_name) {
            $result = wp_update_user([
                'ID' => $vendor_id,
                'display_name' => $display_name,
            ]);
            if (is_wp_error($result)) {
                wp_send_json_error($result->get_error_message());
            }
        }

        $is_vendor = in_array('vendor', (array) $user->roles, true) || user_can($vendor_id, 'edit_products');
        if ($is_vendor) {
            update_user_meta($vendor_id, 'vs_store_name', sanitize_text_field(wp_unslash($_POST['store_name'] ?? '')));
            update_user_meta($vendor_id, 'vs_store_location', sanitize_text_field(wp_unslash($_POST['store_location'] ?? '')));
            update_user_meta($vendor_id, 'vs_store_desc', sanitize_textarea_field(wp_unslash($_POST['store_description'] ?? '')));
            // Store logo attachment id
            $logo_id = isset($_POST['store_logo_id']) ? intval($_POST['store_logo_id']) : 0;
            if ($logo_id > 0) {
                update_user_meta($vendor_id, 'vs_store_logo_id', $logo_id);
            } else {
                delete_user_meta($vendor_id, 'vs_store_logo_id');
            }
        }

        update_user_meta($vendor_id, 'vs_vendor_status', sanitize_text_field(wp_unslash($_POST['vendor_status'] ?? 'active')));

        wp_send_json_success();

    }

   public static function delete_vendor_ajax() {

    check_ajax_referer('vs_setup_nonce', 'security');

    if (!current_user_can('administrator')) {
        wp_send_json_error(__('Permission denied', 'vendor-space'));
    }

    $vendor_id = intval($_POST['vendor_id']);

    update_user_meta($vendor_id, 'vs_vendor_status', 'deleted');

    $products = get_posts([
        'post_type'      => 'product',
        'author'         => $vendor_id,
        'posts_per_page' => -1,
        'post_status'    => ['publish', 'pending', 'draft']
    ]);

    foreach ($products as $product) {
        wp_update_post([
            'ID'          => $product->ID,
            'post_status' => 'draft' 
        ]);
    }

    wp_send_json_success();
}

    public static function bulk_vendor_action_ajax() {
        check_ajax_referer('vs_setup_nonce', 'security');
        if (!current_user_can('administrator')) {
            wp_send_json_error(__('Permission denied', 'vendor-space'));
        }

        $action = isset($_POST['bulk_action']) ? sanitize_key($_POST['bulk_action']) : '';
        if (!in_array($action, ['ban', 'restore', 'delete_permanently'], true)) {
            wp_send_json_error(__('Invalid bulk action', 'vendor-space'));
        }

        $ids_raw = $_POST['vendor_ids'] ?? [];
        if (!is_array($ids_raw)) {
            wp_send_json_error(__('Invalid user IDs', 'vendor-space'));
        }

        $ids = array_values(array_unique(array_filter(array_map('intval', $ids_raw), function($v) {
            return $v > 0;
            /*
         integer   تحويل إلى 
حذف القيم الفارغة
حذف التكرار
ترتيب array */
        })));
        if (empty($ids)) {
            wp_send_json_error(__('No users selected', 'vendor-space'));
        }

        $me = get_current_user_id();
        $success = 0;
        $failed = 0;
        $skipped = 0;
        $skipped_reasons = [];

        if ($action === 'delete_permanently') {
            require_once ABSPATH . 'wp-admin/includes/user.php';
        }

        foreach ($ids as $uid) {
            if ($uid === $me) {
                $skipped++;
                $skipped_reasons[] = sprintf(__('Skipped own account (ID %d)', 'vendor-space'), $uid);
                continue;            }
            if (user_can($uid, 'manage_options')) {
                $skipped++;
                $skipped_reasons[] = sprintf(__('Skipped administrator (ID %d)', 'vendor-space'), $uid);
                continue;
            }

          if ($action === 'ban') {

    $ok = update_user_meta($uid, 'vs_vendor_status', 'deleted');

    $products = get_posts([
        'post_type'      => 'product',
        'author'         => $uid,
        'posts_per_page' => -1,
        'post_status'    => ['publish', 'pending', 'draft'],
        'fields'         => 'ids'
    ]);

    foreach ($products as $pid) {
        wp_update_post([
            'ID'          => $pid,
            'post_status' => 'draft'
        ]);
    }

    if ($ok !== false) $success++; else $failed++;

    continue;
}
            if ($action === 'restore') {
                $ok = update_user_meta($uid, 'vs_vendor_status', 'active');
                if ($ok !== false) $success++; else $failed++;
                continue;
            }

            if ($action === 'delete_permanently') {

    $products = get_posts([
        'post_type' => 'product',
        'author' => $uid,
        'posts_per_page' => -1,
        'fields' => 'ids'
    ]);

    $ok = wp_delete_user($uid);

    if ($ok) {

        foreach ($products as $pid) {
            wp_delete_post($pid, true);
        }

        $success++;

    } else {
        $failed++;
    }

    continue;
}
        }

        $summary = sprintf(__('Success: %1$d | Failed: %2$d | Skipped: %3$d', 'vendor-space'), $success, $failed, $skipped);
        if (!empty($skipped_reasons)) {
            $summary .= ' | ' . implode('; ', array_slice($skipped_reasons, 0, 5));
            if (count($skipped_reasons) > 5) {
                $summary .= '; ...';
            }
        }

        wp_send_json_success([
            'message' => __('Bulk action completed.', 'vendor-space'),
            'summary' => $summary,
            'success' => $success,
            'failed' => $failed,
            'skipped' => $skipped,
        ]);
    }
public static function delete_vendor_permanently_ajax() {
    check_ajax_referer('vs_setup_nonce', 'security');

    if (!current_user_can('administrator')) {
        wp_send_json_error(__('Permission denied', 'vendor-space'));
    }

    $vendor_id = intval($_POST['vendor_id'] ?? 0);

    if ($vendor_id <= 0) {
        wp_send_json_error(__('Invalid vendor ID', 'vendor-space'));
    }

    if (get_current_user_id() === $vendor_id) {
        wp_send_json_error(__('You cannot delete your own account.', 'vendor-space'));
    }

    if (user_can($vendor_id, 'manage_options')) {
        wp_send_json_error(__('You cannot delete an administrator account.', 'vendor-space'));
    }

    $products = get_posts([
        'post_type'      => 'product',
        'author'         => $vendor_id,
        'posts_per_page' => -1,
        'post_status'    => ['publish', 'draft', 'pending', 'private'],
        'fields'         => 'ids'
    ]);

  require_once ABSPATH . 'wp-admin/includes/user.php';
$ok = wp_delete_user($vendor_id);

if ($ok) {
    foreach ($products as $product_id) {
        wp_delete_post($product_id, true);
    }
} else {
    wp_send_json_error(__('Failed to delete user.', 'vendor-space'));
}

    wp_send_json_success();
}

    public static function restore_vendor_ajax() {
        check_ajax_referer('vs_setup_nonce', 'security');
        if (!current_user_can('administrator')) wp_send_json_error(__('Permission denied', 'vendor-space'));

        $vendor_id = intval($_POST['vendor_id']);
        update_user_meta($vendor_id, 'vs_vendor_status', 'active');
        wp_send_json_success();
    }

    public static function export_vendors_csv_ajax() {
        if (!current_user_can('administrator')) wp_die(esc_html__('Permission denied', 'vendor-space'));
      
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=vendors-list.csv');

        $output = fopen('php://output', 'w');
        fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
        
        fputcsv($output, [
            __('Vendor ID', 'vendor-space'),
            __('Store Name', 'vendor-space'),
            __('Owner Name', 'vendor-space'),
            __('Email', 'vendor-space'),
            __('Location', 'vendor-space'),
            __('Status', 'vendor-space'),
            __('Total Sales', 'vendor-space'),
        ]);

        $all_completed_orders = wc_get_orders(['status' => 'completed', 'limit' => -1]);
        $vendor_sales_map = [];
        foreach ($all_completed_orders as $order) {
            foreach ($order->get_items() as $item) {
                $v_id = $item->get_meta('_vs_vendor_id');
                if (empty($v_id)) {
                    $product = $item->get_product();
                    if ($product) $v_id = get_post_field('post_author', $product->get_id());
                }
                if ($v_id) {
                    if (!isset($vendor_sales_map[$v_id])) $vendor_sales_map[$v_id] = 0;
                    $vendor_sales_map[$v_id] += (float)$item->get_total();
                }
            }
        }

        $users = get_users(['role__in' => ['vendor']]);
        foreach ($users as $user) {
            if (user_can($user->ID, 'manage_options')) continue;
            
            $v_id = $user->ID;
            $store_name = get_user_meta($v_id, 'vs_store_name', true) ?: $user->display_name;
            $location = get_user_meta($v_id, 'vs_store_location', true);
            $v_status = get_user_meta($v_id, 'vs_vendor_status', true) ?: 'active';
            $total_sales = isset($vendor_sales_map[$v_id]) ? $vendor_sales_map[$v_id] : 0;

            fputcsv($output, [
                $v_id,
                $store_name,
                $user->display_name,
                $user->user_email,
                $location,
                ucfirst($v_status),
                $total_sales
            ]);
        }
        fclose($output);
        exit;
    }
}