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

/**
 * VS_Ajax_Pagination
 * Handles server-side AJAX pagination for:
 *  - Restore Products
 *  - Orders
 *  - Categories
 *  - Best Clients
 */
class VS_Ajax_Pagination {

    const PER_PAGE = 10;

    public static function init() {
        add_action('wp_ajax_vs_page_restore',      [__CLASS__, 'ajax_restore']);
        add_action('wp_ajax_vs_page_orders',       [__CLASS__, 'ajax_orders']);
        add_action('wp_ajax_vs_page_categories',   [__CLASS__, 'ajax_categories']);
        add_action('wp_ajax_vs_page_best_clients', [__CLASS__, 'ajax_best_clients']);
    }

    // =========================================================
    //  RESTORE
    // =========================================================
    public static function ajax_restore() {
        check_ajax_referer('vs_nonce', 'security');
        $user = wp_get_current_user();
        if (!$user->ID) wp_send_json_error(['message' => 'Not logged in']);

        $paged   = max(1, intval($_POST['paged'] ?? 1));
        $search  = sanitize_text_field($_POST['search'] ?? '');

        $args = [
            'post_type'      => 'product',
            'post_status'    => 'trash',
            'posts_per_page' => self::PER_PAGE,
            'paged'          => $paged,
            'orderby'        => 'date',
            'order'          => 'DESC',
        ];
        if (!current_user_can('administrator')) {
            $args['author'] = $user->ID;
        }
        if ($search !== '') {
            $args['s'] = $search;
        }

        $query    = new WP_Query($args);
        $products = $query->posts;
        $total_pages = max(1, $query->max_num_pages);
        $total       = $query->found_posts;
        wp_reset_postdata();

        ob_start();
        if (empty($products)) {
            echo '<tr><td colspan="5" style="text-align:center;padding:30px;color:#94a3b8;">'
                . esc_html__('No deleted products found.', 'vendor-space') . '</td></tr>';
        } else {
            foreach ($products as $p) {
                $price  = get_post_meta($p->ID, '_price', true);
                $vendor = get_userdata($p->post_author);
                $img    = get_the_post_thumbnail($p->ID, [50, 50])
                        ?: '<i class="fas fa-box" style="font-size:30px;color:#cbd5e1;"></i>';
                ?>
                <tr id="vs-restore-row-<?php echo $p->ID; ?>"
                    style="border-bottom:1px solid #f1f5f9;transition:background 0.2s;">
                    <td style="padding:15px;">
                        <input type="checkbox" class="vs-select-product-restore" value="<?php echo $p->ID; ?>"
                            style="width:18px;height:18px;cursor:pointer;">
                    </td>
                    <td style="padding:15px;">
                        <div style="display:flex;align-items:center;gap:15px;">
                            <div style="width:50px;height:50px;border-radius:8px;overflow:hidden;border:1px solid #f1f5f9;flex-shrink:0;">
                                <?php echo $img; ?>
                            </div>
                            <span style="font-weight:600;color:#1e293b;">
                                <?php echo esc_html($p->post_title); ?>
                            </span>
                        </div>
                    </td>
                    <?php if (current_user_can('administrator')): ?>
                    <td style="padding:15px;">
                        <span style="background:#e0f2fe;color:#0369a1;padding:4px 10px;border-radius:6px;font-size:12px;font-weight:600;">
                            <?php echo esc_html($vendor ? $vendor->display_name : __('Guest', 'vendor-space')); ?>
                        </span>
                    </td>
                    <?php endif; ?>
                    <td style="padding:15px;font-weight:600;color:#1e293b;">
                        <?php echo wc_price($price); ?>
                    </td>
                    <td style="padding:15px;text-align:right;">
                        <div style="display:inline-flex;gap:10px;">
                            <button class="vs-restore-btn" data-product-id="<?php echo $p->ID; ?>"
                                style="background:#10b981;color:#fff;border:none;padding:8px 16px;border-radius:8px;cursor:pointer;font-size:13px;font-weight:600;display:flex;align-items:center;gap:6px;transition:0.2s;">
                                <i class="fas fa-undo-alt"></i> <?php echo esc_html__('Restore', 'vendor-space'); ?>
                            </button>
                            <button class="vs-delete-btn" data-product-id="<?php echo $p->ID; ?>" data-mode="permanent"
                                style="background:#fff;color:#ef4444;border:1px solid #fca5a5;padding:8px 16px;border-radius:8px;cursor:pointer;font-size:13px;font-weight:600;display:flex;align-items:center;gap:6px;transition:0.2s;">
                                <i class="fas fa-trash-alt"></i> <?php echo esc_html__('Delete', 'vendor-space'); ?>
                            </button>
                        </div>
                    </td>
                </tr>
                <?php
            }
        }
        $rows_html = ob_get_clean();

        wp_send_json_success([
            'rows'        => $rows_html,
            'total'       => $total,
            'total_pages' => $total_pages,
            'paged'       => $paged,
            'per_page'    => self::PER_PAGE,
        ]);
    }

    // =========================================================
    //  ORDERS
    // =========================================================
    public static function ajax_orders() {
        check_ajax_referer('vs_nonce', 'security');
        $user_id = get_current_user_id();
        if (!$user_id) wp_send_json_error(['message' => 'Not logged in']);

        $paged      = max(1, intval($_POST['paged'] ?? 1));
        $search     = sanitize_text_field($_POST['search'] ?? '');
        $status_f   = sanitize_text_field($_POST['status_filter'] ?? '');
        $date_from  = sanitize_text_field($_POST['date_from'] ?? '');
        $date_to    = sanitize_text_field($_POST['date_to'] ?? '');

        $query_args = [
            'limit'   => self::PER_PAGE,
            'paged'   => $paged,
            'orderby' => 'date',
            'order'   => 'DESC',
            'paginate' => true,
            'status'  => ['processing', 'completed', 'cancelled', 'on-hold', 'pending', 'refunded'],
        ];
        if ($status_f && in_array($status_f, ['processing', 'completed', 'cancelled', 'on-hold', 'pending', 'refunded'])) {
            $query_args['status'] = [$status_f];
        }
        if ($date_from) $query_args['date_created'] = '>=' . $date_from;
        if ($date_to)   $query_args['date_created'] = '<=' . $date_to . ' 23:59:59';
        if ($date_from && $date_to) $query_args['date_created'] = $date_from . '...' . $date_to . ' 23:59:59';

        $result      = wc_get_orders($query_args);
        $all_orders  = is_object($result) ? $result->orders : $result;
        $max_pages   = is_object($result) ? max(1, (int)$result->max_num_pages) : 1;
        $total_found = is_object($result) ? (int)$result->total : count($all_orders);

        // Filter by vendor and search
        $my_orders = [];
        foreach ($all_orders as $order) {
            if (!is_a($order, 'WC_Order')) continue;
            $has_item = false;
            foreach ($order->get_items() as $item) {
                $item_vendor = $item->get_meta('_vs_vendor_id');
                if (empty($item_vendor)) {
                    $product = $item->get_product();
                    if ($product) $item_vendor = get_post_field('post_author', $product->get_id());
                }
                if ((int)$item_vendor === $user_id) { $has_item = true; break; }
            }
            if (!$has_item && !current_user_can('administrator')) continue;

            // Search filter
            if ($search) {
                $q = strtolower($search);
                $num  = strtolower((string)$order->get_order_number());
                $name = strtolower(trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name()));
                $mail = strtolower((string)$order->get_billing_email());
                if (strpos($num, $q) === false && strpos($name, $q) === false && strpos($mail, $q) === false) continue;
            }

            $fin = class_exists('VS_Commission') ? VS_Commission::get_order_financials($order->get_id(), $user_id) : [];
            $order->vendor_total = isset($fin['net_earning']) ? (float)$fin['net_earning'] : 0;
            $my_orders[] = $order;
        }

        ob_start();
        if (empty($my_orders)) {
            echo '<tr><td colspan="7" style="text-align:center;padding:30px;color:#94a3b8;">'
                . esc_html__('No orders found.', 'vendor-space') . '</td></tr>';
        } else {
            foreach ($my_orders as $order) {
                $status_slug  = $order->get_status();
                $order_date   = $order->get_date_created();
                $order_date_ymd = $order_date ? $order_date->date('Y-m-d') : '';
                $customer_name = trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name());
                $customer_email = (string)$order->get_billing_email();
                $payment_method = (string)$order->get_payment_method_title();
                $billing_address = trim($order->get_billing_address_1() . ' ' . $order->get_billing_address_2());
                $billing_city    = (string)$order->get_billing_city();
                $billing_zip     = (string)$order->get_billing_postcode();
                $billing_country = (string)$order->get_billing_country();
                $billing_phone   = (string)$order->get_billing_phone();
                $order_items = [];
                $chat_product_id  = 0;
                $chat_customer_id = (int)$order->get_customer_id();

                foreach ($order->get_items() as $item) {
                    $item_vendor = (int)$item->get_meta('_vs_vendor_id');
                    $pid = (int)$item->get_product_id();
                    if ($item_vendor <= 0 && $pid > 0)
                        $item_vendor = (int)get_post_field('post_author', $pid);
                    if ($item_vendor === $user_id) {
                        $product    = $item->get_product();
                        $line_total = (float)$order->get_item_total($item, false, true);
                        $image_url  = '';
                        if ($product) {
                            $image_id = $product->get_image_id();
                            if ($image_id) $image_url = (string)wp_get_attachment_image_url($image_id, 'thumbnail');
                        }
                        if (!$image_url && function_exists('wc_placeholder_img_src'))
                            $image_url = (string)wc_placeholder_img_src('thumbnail');
                        $order_items[] = [
                            'name'     => $product ? $product->get_name() : $item->get_name(),
                            'qty'      => (int)$item->get_quantity(),
                            'total'    => $line_total,
                            'currency' => (string)$order->get_currency(),
                            'image'    => $image_url,
                        ];
                        if (!$chat_product_id) $chat_product_id = $pid;
                    }
                }
                $order_items_json = wp_json_encode($order_items, JSON_UNESCAPED_UNICODE);

                $statuses = ['processing' => __('Processing', 'vendor-space'), 'completed' => __('Completed', 'vendor-space'), 'cancelled' => __('Rejected', 'vendor-space')];
                ?>
                <tr style="border-bottom:1px solid #e5e7eb;"
                    data-order-id="<?php echo esc_attr($order->get_id()); ?>"
                    data-order-number="<?php echo esc_attr($order->get_order_number()); ?>"
                    data-order-date="<?php echo esc_attr($order_date_ymd); ?>"
                    data-customer-name="<?php echo esc_attr($customer_name); ?>"
                    data-customer-email="<?php echo esc_attr($customer_email); ?>"
                    data-payment-method="<?php echo esc_attr($payment_method); ?>"
                    data-billing-name="<?php echo esc_attr($customer_name); ?>"
                    data-billing-address="<?php echo esc_attr($billing_address); ?>"
                    data-billing-city="<?php echo esc_attr($billing_city); ?>"
                    data-billing-zip="<?php echo esc_attr($billing_zip); ?>"
                    data-billing-country="<?php echo esc_attr($billing_country); ?>"
                    data-billing-phone="<?php echo esc_attr($billing_phone); ?>"
                    data-order-items="<?php echo esc_attr($order_items_json); ?>"
                    data-order-total="<?php echo esc_attr((string)(float)$order->vendor_total); ?>"
                    data-status="<?php echo esc_attr($status_slug); ?>"
                    data-date="<?php echo esc_attr($order_date_ymd); ?>"
                    data-vendor-total="<?php echo esc_attr((string)(float)$order->vendor_total); ?>">
                    <td data-label="Select" style="padding:15px;">
                        <input type="checkbox" class="vs-order-select" value="<?php echo esc_attr($order->get_id()); ?>">
                    </td>
                    <td data-label="Order #" style="padding:15px;font-weight:700;color:#2563eb;">#<?php echo $order->get_order_number(); ?></td>
                    <td data-label="Customer" style="padding:15px;">
                        <div style="font-weight:600;color:#1e293b;"><?php echo esc_html($customer_name); ?></div>
                        <small style="color:#64748b;"><?php echo esc_html($customer_email); ?></small>
                    </td>
                    <td data-label="Date" style="padding:15px;color:#475569;">
                        <?php echo $order_date ? $order_date->date('M j, Y') : '—'; ?>
                    </td>
                    <td data-label="Status" style="padding:15px;vertical-align:middle;">
                        <select class="vs-order-status-select"
                            data-order-id="<?php echo $order->get_id(); ?>"
                            style="padding:8px 12px;border-radius:20px;font-size:12px;font-weight:700;cursor:pointer;text-transform:uppercase;
                            background:<?php echo $status_slug==='completed'?'#d1fae5':($status_slug==='processing'?'#dbeafe':'#fee2e2'); ?>;
                            color:<?php echo $status_slug==='completed'?'#065f46':($status_slug==='processing'?'#1e40af':'#991b1b'); ?>;
                            border:none;outline:none;appearance:none;text-align:center;">
                            <?php foreach ($statuses as $slug => $name): ?>
                            <option value="<?php echo esc_attr($slug); ?>" <?php selected($status_slug, $slug); ?>>
                                <?php echo esc_html($name); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td data-label="Net Earning" style="padding:15px;font-weight:700;color:#1e293b;">
                        <?php echo wc_price($order->vendor_total); ?>
                    </td>
                    <td data-label="Actions" style="padding:15px;">
                        <div style="display:flex;gap:8px;flex-wrap:wrap;">
                            <button type="button" class="vs-view-order vs-action-btn"
                                style="background:#3b82f6;color:white;border:none;padding:8px 12px;border-radius:6px;cursor:pointer;"
                                data-order-number="<?php echo esc_attr($order->get_order_number()); ?>"
                                data-order-json="<?php echo esc_attr($order_items_json); ?>">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button type="button" class="vs-print-order vs-action-btn"
                                style="background:#6366f1;color:white;border:none;padding:8px 12px;border-radius:6px;cursor:pointer;">
                                <i class="fas fa-print"></i>
                            </button>
                            <button type="button" class="vs-admin-message-vendor-btn"
                                data-id="<?php echo $chat_customer_id; ?>"
                                data-display-name="<?php echo esc_attr($customer_name); ?>"
                                style="background:#f0f9ff;color:#0369a1;border:none;width:32px;height:32px;border-radius:8px;cursor:pointer;">
                                <i class="fas fa-comment"></i>
                            </button>
                            <button type="button" class="vs-delete-order vs-action-btn"
                                data-order-id="<?php echo $order->get_id(); ?>"
                                style="background:#ef4444;color:white;border:none;padding:8px 12px;border-radius:6px;cursor:pointer;">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
                <?php
            }
        }
        $rows_html = ob_get_clean();

        wp_send_json_success([
            'rows'        => $rows_html,
            'total'       => count($my_orders),
            'total_pages' => $max_pages,
            'paged'       => $paged,
            'per_page'    => self::PER_PAGE,
        ]);
    }

    // =========================================================
    //  CATEGORIES
    // =========================================================
    public static function ajax_categories() {
        check_ajax_referer('vs_nonce', 'security');
        if (!is_user_logged_in()) wp_send_json_error(['message' => 'Not logged in']);

        $paged   = max(1, intval($_POST['paged'] ?? 1));
        $search  = sanitize_text_field($_POST['search'] ?? '');

        $args = [
            'taxonomy'   => 'product_cat',
            'hide_empty' => false,
            'number'     => self::PER_PAGE,
            'offset'     => ($paged - 1) * self::PER_PAGE,
            'orderby'    => 'name',
            'order'      => 'ASC',
        ];
        if ($search !== '') {
            $args['search'] = $search;
            $args['name__like'] = $search;
        }

        $terms = get_terms($args);
        $total_args = $args;
        unset($total_args['number'], $total_args['offset']);
        $total_args['fields'] = 'count';
        $total       = (int) get_terms($total_args);
        $total_pages = max(1, ceil($total / self::PER_PAGE));

        ob_start();
        if (empty($terms) || is_wp_error($terms)) {
            echo '<tr><td colspan="6" style="padding:40px;text-align:center;color:#6b7280;">'
                . esc_html__('No categories found.', 'vendor-space') . '</td></tr>';
        } else {
            foreach ($terms as $t) {
                if (!($t instanceof WP_Term)) continue;
                $parent_name = '';
                if ((int)$t->parent > 0) {
                    $pt = get_term((int)$t->parent, 'product_cat');
                    if ($pt && !is_wp_error($pt)) $parent_name = $pt->name;
                }
                ?>
                <tr id="vs-cat-row-<?php echo (int)$t->term_id; ?>" style="border-bottom:1px solid #f1f5f9;">
                    <td style="padding:15px;width:40px;">
                        <input type="checkbox" class="vs-cat-checkbox" value="<?php echo (int)$t->term_id; ?>"
                            style="cursor:pointer;width:18px;height:18px;">
                    </td>
                    <td style="padding:15px;font-weight:600;color:#1e293b;"><?php echo esc_html($t->name); ?></td>
                    <td style="padding:15px;color:#475569;"><?php echo esc_html($t->slug); ?></td>
                    <td style="padding:15px;color:#475569;"><?php echo esc_html($parent_name); ?></td>
                    <td style="padding:15px;color:#475569;"><?php echo (int)$t->count; ?></td>
                    <td style="padding:15px;text-align:right;">
                        <div style="display:inline-flex;gap:10px;flex-wrap:wrap;justify-content:flex-end;">
                            <button type="button" class="vs-edit-category-btn"
                                data-term-id="<?php echo (int)$t->term_id; ?>"
                                data-name="<?php echo esc_attr($t->name); ?>"
                                data-slug="<?php echo esc_attr($t->slug); ?>"
                                data-parent="<?php echo (int)$t->parent; ?>"
                                data-description="<?php echo esc_attr($t->description); ?>"
                                style="background:#0ea5e9;color:white;border:none;padding:8px 14px;border-radius:8px;cursor:pointer;font-size:13px;font-weight:600;display:flex;align-items:center;gap:6px;">
                                <i class="fas fa-pen"></i> Edit
                            </button>
                            <button type="button" class="vs-delete-category-btn"
                                data-term-id="<?php echo (int)$t->term_id; ?>"
                                style="background:#fff;color:#ef4444;border:1px solid #fca5a5;padding:8px 14px;border-radius:8px;cursor:pointer;font-size:13px;font-weight:600;display:flex;align-items:center;gap:6px;">
                                <i class="fas fa-trash-alt"></i> Delete
                            </button>
                        </div>
                    </td>
                </tr>
                <?php
            }
        }
        $rows_html = ob_get_clean();

        wp_send_json_success([
            'rows'        => $rows_html,
            'total'       => $total,
            'total_pages' => $total_pages,
            'paged'       => $paged,
            'per_page'    => self::PER_PAGE,
        ]);
    }

    // =========================================================
    //  BEST CLIENTS
    // =========================================================
    public static function ajax_best_clients() {
        check_ajax_referer('vs_nonce', 'security');
        $user_id = get_current_user_id();
        if (!$user_id) wp_send_json_error(['message' => 'Not logged in']);

        $paged  = max(1, intval($_POST['paged'] ?? 1));
        $period = sanitize_text_field($_POST['period'] ?? 'all');
        $search = sanitize_text_field($_POST['search'] ?? '');
        $sort   = sanitize_text_field($_POST['sort'] ?? 'total_spent');
        $dir    = sanitize_text_field($_POST['direction'] ?? 'desc');

        // Re-use existing VS_Best_Clients::get_best_clients via reflection
        // (it's private, so we use a public wrapper pattern)
        $all_clients = self::get_clients_data($user_id, $period);

        // Search filter
        if ($search !== '') {
            $q = strtolower($search);
            $all_clients = array_filter($all_clients, function($c) use ($q) {
                return strpos(strtolower($c['name'] ?? ''), $q) !== false
                    || strpos(strtolower($c['email'] ?? ''), $q) !== false;
            });
            $all_clients = array_values($all_clients);
        }

        // Sort
        $allowed_sort = ['order_count', 'total_spent', 'last_order_ts'];
        if (!in_array($sort, $allowed_sort)) $sort = 'total_spent';
        $dir = ($dir === 'asc') ? 'asc' : 'desc';
        usort($all_clients, function($a, $b) use ($sort, $dir) {
            $av = $a[$sort] ?? 0;
            $bv = $b[$sort] ?? 0;
            return $dir === 'asc' ? ($av <=> $bv) : ($bv <=> $av);
        });

        $total       = count($all_clients);
        $total_pages = max(1, (int)ceil($total / self::PER_PAGE));
        $paged       = min($paged, $total_pages);
        $offset      = ($paged - 1) * self::PER_PAGE;
        $page_clients = array_slice($all_clients, $offset, self::PER_PAGE);

        ob_start();
        if (empty($page_clients)) {
            echo '<tr><td colspan="6" style="text-align:center;padding:30px;color:#94a3b8;">'
                . esc_html__('No clients found.', 'vendor-space') . '</td></tr>';
        } else {
            foreach ($page_clients as $client) {
                ?>
                <tr style="border-bottom:1px solid #e5e7eb;"
                    data-order-count="<?php echo esc_attr((int)($client['order_count'] ?? 0)); ?>"
                    data-total-spent="<?php echo esc_attr((float)($client['total_spent'] ?? 0)); ?>"
                    data-last-order-ts="<?php echo esc_attr((int)($client['last_order_ts'] ?? 0)); ?>">
                    <td style="padding:15px;">
                        <div style="font-weight:600;color:#1e293b;"><?php echo esc_html($client['name'] ?? ''); ?></div>
                        <small style="color:#64748b;"><?php echo esc_html($client['email'] ?? ''); ?></small>
                    </td>
                    <td style="padding:15px;color:#475569;"><?php echo esc_html($client['order_count'] ?? 0); ?></td>
                    <td style="padding:15px;font-weight:700;color:#1e293b;"><?php echo wc_price($client['total_spent'] ?? 0); ?></td>
                    <td style="padding:15px;color:#475569;"><?php echo esc_html($client['last_order_date'] ?? ''); ?></td>
                    <td style="padding:15px;">
                        <span style="display:inline-flex;align-items:center;gap:6px;color:#334155;">
                            <span style="display:inline-block;width:9px;height:9px;border-radius:50%;background:<?php echo esc_attr($client['activity_color'] ?? '#94a3b8'); ?>;"></span>
                            <?php echo esc_html($client['activity_label'] ?? ''); ?>
                        </span>
                    </td>
                    <td style="padding:15px;">
                        <?php echo isset($client['following']) && $client['following']
                            ? '<span style="color:#10b981;font-weight:600;">✓ ' . esc_html__('Yes', 'vendor-space') . '</span>'
                            : '<span style="color:#94a3b8;">—</span>'; ?>
                    </td>
                </tr>
                <?php
            }
        }
        $rows_html = ob_get_clean();

        wp_send_json_success([
            'rows'        => $rows_html,
            'total'       => $total,
            'total_pages' => $total_pages,
            'paged'       => $paged,
            'per_page'    => self::PER_PAGE,
        ]);
    }

    /**
     * Re-uses VS_Best_Clients logic via a public relay.
     * Reads orders and builds clients array identical to the main class.
     */
    private static function get_clients_data($vendor_id, $period = 'all') {
        // Use public static relay if class exposes it, otherwise duplicate minimal logic
        if (method_exists('VS_Best_Clients', 'get_best_clients_public')) {
            return VS_Best_Clients::get_best_clients_public($vendor_id, $period);
        }

        $vendor_id = (int)$vendor_id;
        if ($vendor_id <= 0) return [];

        $period_map = ['30d' => '-30 days', '6m' => '-6 months', 'all' => ''];
        $period = isset($period_map[$period]) ? $period : 'all';

        $clients   = [];
        $paged_q   = 1;
        $max_pages = 1;
        $date_filter = '';
        if ($period !== 'all' && !empty($period_map[$period])) {
            $ts = strtotime($period_map[$period]);
            $date_filter = '>=' . gmdate('Y-m-d', $ts);
        }

        do {
            $q = ['limit' => 200, 'paginate' => true, 'paged' => $paged_q,
                  'status' => ['completed', 'processing']];
            if ($date_filter) $q['date_created'] = $date_filter;

            $result  = wc_get_orders($q);
            $orders  = [];
            if (is_object($result) && isset($result->orders)) {
                $orders    = $result->orders;
                $max_pages = max(1, (int)$result->max_num_pages);
            } elseif (is_array($result)) {
                $orders = $result;
            }

            foreach ($orders as $order) {
                if (!is_a($order, 'WC_Order')) continue;
                $order_date = $order->get_date_created();
                if (!$order_date) continue;
                $order_ts   = (int)$order_date->getTimestamp();
                $order_date_label = wp_date('Y-m-d', $order_ts);

                $vendor_total = 0;
                $has_vendor   = false;
                foreach ($order->get_items() as $item) {
                    $iv  = $item->get_meta('_vs_vendor_id');
                    $pid = $item->get_product_id();
                    if (empty($iv) && $pid) $iv = get_post_field('post_author', $pid);
                    if ((int)$iv === $vendor_id) {
                        $has_vendor = true;
                        if (!class_exists('VS_Commission')) $vendor_total += (float)$item->get_total();
                    }
                }
                if (!$has_vendor) continue;

                if (class_exists('VS_Commission')) {
                    $fin = VS_Commission::get_order_financials($order->get_id(), $vendor_id);
                    $vendor_total = isset($fin['net_earning']) ? (float)$fin['net_earning'] : 0;
                }

                $email = strtolower(trim($order->get_billing_email()));
                if (empty($email)) continue;
                if (!isset($clients[$email])) {
                    $clients[$email] = [
                        'name'            => trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name()),
                        'email'           => $email,
                        'order_count'     => 0,
                        'total_spent'     => 0,
                        'last_order_date' => $order_date_label,
                        'last_order_ts'   => $order_ts,
                        'following'       => false,
                    ];
                }
                $clients[$email]['order_count']++;
                $clients[$email]['total_spent'] += $vendor_total;
                if ($order_ts > $clients[$email]['last_order_ts']) {
                    $clients[$email]['last_order_ts']   = $order_ts;
                    $clients[$email]['last_order_date'] = $order_date_label;
                }
            }
            $paged_q++;
        } while ($paged_q <= $max_pages);

        // Activity meta
        foreach ($clients as $email => $c) {
            $diff_days = (time() - $c['last_order_ts']) / 86400;
            if ($diff_days <= 30)      { $clients[$email]['activity_label'] = __('Active', 'vendor-space');   $clients[$email]['activity_color'] = '#22c55e'; }
            elseif ($diff_days <= 90)  { $clients[$email]['activity_label'] = __('Regular', 'vendor-space');  $clients[$email]['activity_color'] = '#f59e0b'; }
            else                       { $clients[$email]['activity_label'] = __('Inactive', 'vendor-space');  $clients[$email]['activity_color'] = '#94a3b8'; }
        }

        return array_values($clients);
    }
}
