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

class VS_Best_Clients {
    private const PERIOD_30_DAYS = '30d';
    private const PERIOD_6_MONTHS = '6m';
    private const PERIOD_ALL_TIME = 'all';
    private const ORDERS_PAGE_SIZE = 200;

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

        $vendor_id = (int) $user->ID;
        $period = self::sanitize_period(isset($_GET['vs_clients_period']) ? wp_unslash($_GET['vs_clients_period']) : self::PERIOD_ALL_TIME);
        $clients_all = self::get_best_clients($vendor_id, $period);

        if (self::should_export_csv($vendor_id)) {
            self::export_csv($clients_all, $period);
        }

        $clients_data = array_slice($clients_all, 0, 100);
        $total_unique_clients = count($clients_all);
        $top_client = !empty($clients_all) ? reset($clients_all) : false;
        $filter_action = remove_query_arg(['vs_clients_period', 'vs_best_clients_export', 'vs_best_clients_nonce', 'tab']);
        $export_url = wp_nonce_url(
            add_query_arg([
                'tab' => 'best-clients',
                'vs_clients_period' => $period,
                'vs_best_clients_export' => 1,
            ], $filter_action),
            'vs_best_clients_export_' . $vendor_id,
            'vs_best_clients_nonce'
        );
        $period_options = self::period_options();
        
        ob_start();
        ?>
        <div class="vs-tab" id="tab-best-clients" style="display:none;">
            <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; flex-wrap: wrap; gap: 10px;">
                <h2 style="margin:0; font-size:24px; color:#1e293b;"><?php echo esc_html__('Best Clients', 'vendor-space'); ?></h2>
               
            </div>

            <p class="vs-subtitle" style="margin-bottom: 20px; color: #64748b;">
                <?php
                printf(
                    esc_html__('Your top customers by total spent on your products (%s).', 'vendor-space'),
                    esc_html(self::period_label($period))
                );
                ?>
            </p>

            <div class="vs-metrics-grid" style="margin-bottom: 25px;">
                <div class="vs-metric-card vs-total" style="border-left: 4px solid #3b82f6;">
                    <span class="dashicons dashicons-groups"></span>
                    <div>
                        <small><?php echo esc_html__('Total Unique Clients', 'vendor-space'); ?></small>
                        <strong><?php echo esc_html((string) $total_unique_clients); ?></strong>
                    </div>
                </div>
                
                <?php if ($top_client): ?>
                <div class="vs-metric-card vs-published" style="border-left: 4px solid #10b981;">
                    <span class="dashicons dashicons-star-filled"></span>
                    <div>
                        <small><?php echo esc_html__('Top Spender', 'vendor-space'); ?></small>
                        <strong><?php echo wc_price($top_client['total_spent']); ?></strong>
                    </div>
                </div>
                <?php endif; ?>
            </div>
 <div class="vs-search-container" style="display:flex; align-items:center; gap:10px; flex-wrap:wrap;">
                    <form method="get" action="<?php echo esc_url($filter_action); ?>" style="display:flex; align-items:center; gap:8px;">
                        <input type="hidden" name="tab" value="best-clients">
                        <select name="vs_clients_period" style="padding:9px 12px; border: 1px solid #e5e7eb; border-radius: 8px; font-size: 14px;">
                            <?php foreach ($period_options as $value => $label): ?>
                                <option value="<?php echo esc_attr($value); ?>" <?php selected($period, $value); ?>><?php echo esc_html($label); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <button type="submit" style="background:#2563eb; color:#fff; border:none; border-radius:8px; padding:9px 14px; cursor:pointer; font-weight:600;">
                            <?php echo esc_html__('Apply', 'vendor-space'); ?>
                        </button>
                    </form>
                       <?php   $settings = get_option('vs_settings');
                        $can_export = $settings['vendors']['vendor_can_export_csv'] ?? 'no';

                        if ($can_export === 'yes' && VS_Modules::is_active('export_import')) :
                        ?>  
                    <a href="<?php echo esc_url($export_url); ?>" style="display:inline-flex; align-items:center; gap:6px; background:#0f766e; color:#fff; border:none; border-radius:8px; padding:9px 14px; text-decoration:none; font-weight:600;">
                        <span class="dashicons dashicons-download" style="font-size:16px; width:16px; height:16px;"></span>
                        <?php echo esc_html__('Export CSV', 'vendor-space'); ?>
                    </a>
                                            <?php endif; ?>

<div class="vs-search-input-wrapper">
    <i class="fas fa-search"></i>
    <input type="text" id="vs-best-clients-search"
        placeholder="<?php echo esc_attr__('Search clients...', 'vendor-space'); ?>">
</div>                </div>
                <style>
                    .vs-search-container {
    display: flex;
    align-items: center;
    gap: 14px;
    flex-wrap: wrap;
    padding: 18px;
    border-radius: 18px;

    background: rgba(255,255,255,0.75);
    backdrop-filter: blur(12px);

    box-shadow:
        0 10px 30px rgba(0,0,0,0.05),
        0 1px 2px rgba(0,0,0,0.02);
}

/* Form */
.vs-search-container form {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
}

/* Select */
.vs-search-container select {
    padding: 11px 16px;
    border-radius: 12px;
    border: 1px solid #e5e7eb;
    font-size: 14px;
    background: white;
    min-width: 180px;

    transition: all .25s ease;
}

.vs-search-container select:focus {
    border-color: #3b82f6;
    box-shadow: 0 0 0 4px rgba(59,130,246,0.12);
    transform: translateY(-1px);
}

/* Search input wrapper */
.vs-search-input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
}

/* Search icon */
.vs-search-input-wrapper i {
    position: absolute;
    left: 14px;
    color: #94a3b8;
    font-size: 14px;
}

/* Search input */
#vs-best-clients-search {
    padding: 11px 16px 11px 40px;
    border-radius: 12px;
    border: 1px solid #e5e7eb;
    min-width: 260px;
    font-size: 14px;

    transition: all .25s ease;
}

#vs-best-clients-search:focus {
    border-color: #6366f1;
    box-shadow: 0 0 0 4px rgba(99,102,241,0.12);
    outline: none;
}

/* Buttons */
.vs-search-container button,
.vs-search-container a {
    display: inline-flex;
    align-items: center;
    gap: 8px;

    padding: 11px 18px;
    border-radius: 12px;
    font-weight: 600;
    font-size: 14px;
    text-decoration: none;
    border: none;

    transition: all .25s ease;
    cursor: pointer;
}

/* Hover animation */
.vs-search-container button:hover,
.vs-search-container a:hover {
    transform: translateY(-2px);
    filter: brightness(1.05);
}

/* Export button glow */
.vs-export-btn {
    background: linear-gradient(135deg,#0f766e,#0ea5e9);
    color: white;
    box-shadow: 0 6px 18px rgba(15,118,110,0.25);
}

/* Apply button */
.vs-apply-btn {
    background: linear-gradient(135deg,#2563eb,#4f46e5);
    color: white;
    box-shadow: 0 6px 18px rgba(37,99,235,0.25);
}

/* Responsive */
@media (max-width: 768px){

    .vs-search-container{
        flex-direction: column;
        align-items: stretch;
    }

    .vs-search-container form{
        flex-direction: column;
        width: 100%;
    }

    .vs-search-container select,
    .vs-search-container input,
    .vs-search-container button,
    .vs-search-container a{
        width: 100%;
        min-width: 100%;
    }
}
                </style>
            <?php if (!empty($clients_data)): ?>
                <table class="vs-best-clients-table" style="width:100%; border-collapse:collapse; margin-top:20px; border: 1px solid #e5e7eb;">
                    <thead>
                        <tr style="background:#2563eb; color: white;">
                            <th style="padding:15px; text-align: left;"><?php echo esc_html__('Customer', 'vendor-space'); ?></th>
                            <th class="vs-sortable" data-sort-key="order_count" data-default-direction="desc" style="padding:15px; text-align: left; cursor:pointer; user-select:none;">
                                <?php echo esc_html__('Orders Count', 'vendor-space'); ?> <span class="vs-sort-indicator"></span>
                            </th>
                            <th class="vs-sortable" data-sort-key="total_spent" data-default-direction="desc" style="padding:15px; text-align: left; cursor:pointer; user-select:none;">
                                <?php echo esc_html__('Total Spent', 'vendor-space'); ?> <span class="vs-sort-indicator"></span>
                            </th>
                            <th class="vs-sortable" data-sort-key="last_order_ts" data-default-direction="desc" style="padding:15px; text-align: left; cursor:pointer; user-select:none;">
                                <?php echo esc_html__('Last Order', 'vendor-space'); ?> <span class="vs-sort-indicator"></span>
                            </th>
                            <th style="padding:15px; text-align: left;"><?php echo esc_html__('Activity', 'vendor-space'); ?></th>
                            <th style="padding:15px; text-align: left;"> <?php echo esc_html__('Following', 'vendor-space'); ?></th>
                      <?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')  ) :
?>
      <th style="padding:15px; text-align: left;"><?php echo esc_html__('Actions', 'vendor-space'); ?></th>
      <?php endif;endif;?>

                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($clients_data as $client): ?>
                        <tr style="border-bottom:1px solid #e5e7eb;"
                            data-order-count="<?php echo esc_attr((int) $client['order_count']); ?>"
                            data-total-spent="<?php echo esc_attr((float) $client['total_spent']); ?>"
                            data-last-order-ts="<?php echo esc_attr((int) $client['last_order_ts']); ?>">
                            <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']); ?></td>
                            <td style="padding:15px; font-weight:700; color: #1e293b;"><?php echo wc_price($client['total_spent']); ?></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']); ?>;"></span>
                                    <?php echo esc_html($client['activity_label']); ?>
                                </span>
                            </td>
                           
                               
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <div class="vs-orders-pagination" id="vs-best-clients-pagination"
                    style="margin:15px 20px 18px;display:flex;gap:8px;justify-content:flex-end;flex-wrap:wrap;">
                </div>
            <?php else: ?>
                <div class="no-clients" style="text-align:center; padding:40px; color:#666;">
                    <img src="https://cdn-icons-png.flaticon.com/512/3500/3500833.png" width="80" style="margin-bottom:15px; opacity:0.6;"><br>
                    <?php echo esc_html__('No client data found yet.', 'vendor-space'); ?>
                </div>
            <?php endif; ?>
        </div>

        <!-- Chat Modal for Best Clients -->
        <div id="vs-best-clients-thread-modal"
             data-security="<?php echo esc_attr(wp_create_nonce('vs_nonce')); ?>"
             data-current-user="<?php echo esc_attr((int) $user->ID); ?>"
             style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.5); z-index:10001; justify-content:center; align-items:center;">
            <div style="background:#fff; width:520px; max-width:94%; border-radius:10px; display:flex; flex-direction:column; height:560px; box-shadow:0 10px 40px rgba(0,0,0,0.25);">
                <div style="padding:15px; border-bottom:1px solid #eee; display:flex; justify-content:space-between; align-items:center;">
                    <h3 style="margin:0; font-size:16px;"><?php echo esc_html__('Chat with', 'vendor-space'); ?> <span class="vs-best-clients-thread-name"></span></h3>
                    <button type="button" class="vs-best-clients-thread-close" style="border:none; background:transparent; font-size:24px; cursor:pointer; color: #94a3b8;">&times;</button>
                </div>
                <div class="vs-best-clients-thread-messages" style="flex:1; padding:15px; overflow-y:auto; background:#f8fafc; display:flex; flex-direction:column; gap:10px;">
                    <div style="text-align:center; color:#94a3b8; margin-top:30px;"><?php echo esc_html__('Loading messages...', 'vendor-space'); ?></div>
                </div>
                <form class="vs-best-clients-thread-form" style="padding:15px; border-top:1px solid #eee; display:grid; gap:10px;" enctype="multipart/form-data">
                    <textarea name="message" rows="3" placeholder="<?php echo esc_attr__('Type a message...', 'vendor-space'); ?>" style="width:100%; border:1px solid #e2e8f0; border-radius:8px; padding:10px; resize:none; font-size: 14px; outline: none;"></textarea>
                    <div style="display:flex; gap:10px; align-items:center;">
                        <label style="cursor: pointer; color: #64748b;" title="<?php echo esc_attr__('Attach Image', 'vendor-space'); ?>">
                            <span class="dashicons dashicons-format-image"></span>
                            <input type="file" name="image" accept="image/*" style="display:none;">
                        </label>
                        <button type="submit" class="vs-best-clients-thread-send" style="margin-left:auto; background:#2563eb; color:#fff; border:none; padding:8px 20px; border-radius:6px; cursor:pointer; font-weight: 600;"><?php echo esc_html__('Send', 'vendor-space'); ?></button>
                    </div>
                </form>
                <div class="vs-best-clients-thread-feedback" style="padding:0 15px 12px; font-size: 13px; color:#ef4444; display:none;"></div>
            </div>
        </div>

        <script>
        jQuery(function ($) {
            // Search Filtering
            function applySearchFilter() {
                var value = String($('#vs-best-clients-search').val() || '').toLowerCase();
                $('.vs-best-clients-table tbody tr').each(function() {
                    $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
                });
                if (typeof window.vsApplyBestClientsPagination === 'function') {
                    window.vsApplyBestClientsPagination(true);
                }
            }
            $('#vs-best-clients-search').on('keyup', applySearchFilter);

            // Table Sorting
            const $table = $('.vs-best-clients-table');
            if ($table.length) {
                const $tbody = $table.find('tbody');
                const $headers = $table.find('th.vs-sortable');
                let currentSort = { key: 'total_spent', direction: 'desc' };

                function rowSortValue($row, key) {
                    if (key === 'order_count') return Number($row.data('order-count') || 0);
                    if (key === 'last_order_ts') return Number($row.data('last-order-ts') || 0);
                    return Number($row.data('total-spent') || 0);
                }

                function updateSortIndicators() {
                    $headers.find('.vs-sort-indicator').text('');
                    const $active = $headers.filter('[data-sort-key="' + currentSort.key + '"]');
                    $active.find('.vs-sort-indicator').text(currentSort.direction === 'asc' ? '^' : 'v');
                }

                function sortTableRows() {
                    const rows = $tbody.find('tr').get();
                    rows.sort(function(a, b) {
                        const $a = $(a);
                        const $b = $(b);
                        const av = rowSortValue($a, currentSort.key);
                        const bv = rowSortValue($b, currentSort.key);
                        if (av === bv) return 0;
                        if (currentSort.direction === 'asc') return av > bv ? 1 : -1;
                        return av < bv ? 1 : -1;
                    });
                    $.each(rows, function(_, row) {
                        $tbody.append(row);
                    });
                    updateSortIndicators();
                    applySearchFilter();
                    if (typeof window.vsApplyBestClientsPagination === 'function') {
                        window.vsApplyBestClientsPagination(true);
                    }
                }

                $headers.on('click', function() {
                    const $th = $(this);
                    const key = String($th.data('sort-key') || '');
                    const defaultDirection = String($th.data('default-direction') || 'desc');
                    if (!key) return;
                    if (currentSort.key === key) {
                        currentSort.direction = (currentSort.direction === 'asc') ? 'desc' : 'asc';
                    } else {
                        currentSort.key = key;
                        currentSort.direction = defaultDirection === 'asc' ? 'asc' : 'desc';
                    }
                    sortTableRows();
                });

                sortTableRows();
            }

            // Chat Modal Logic
            const $modal = $('#vs-best-clients-thread-modal');
            if (!$modal.length) return;

            const ajaxUrl = '<?php echo esc_url(admin_url('admin-ajax.php')); ?>';
            const security = String($modal.data('security') || '');
            const currentUserId = Number($modal.data('current-user') || 0);
            const $messages = $modal.find('.vs-best-clients-thread-messages');
            const $feedback = $modal.find('.vs-best-clients-thread-feedback');
            const $form = $modal.find('.vs-best-clients-thread-form');
            const $name = $modal.find('.vs-best-clients-thread-name');
            let thread = { product_id: 0, vendor_id: 0, customer_id: 0 };
            let poll = null;
            let badgePoll = null;

            function esc(v) { return $('<div/>').text(v == null ? '' : String(v)).html(); }
            function setError(msg) { $feedback.text(msg || '<?php echo esc_js(__('Request failed.', 'vendor-space')); ?>').show(); }
            function clearError() { $feedback.hide().text(''); }
            function stopPoll() { if (poll) { clearInterval(poll); poll = null; } }
            function stopBadgePoll() { if (badgePoll) { clearInterval(badgePoll); badgePoll = null; } }

            function renderMessages(items) {
                if (!Array.isArray(items) || !items.length) {
                    $messages.html('<div style="text-align:center; color:#94a3b8; margin-top:20px;"><?php echo esc_js(__('No messages yet.', 'vendor-space')); ?></div>');
                    return;
                }
                let html = '';
                items.forEach(function (m) {
                    const mine = !!m.is_vendor;
                    const align = mine ? 'flex-end' : 'flex-start';
                    const bg = mine ? '#2563eb' : '#fff';
                    const color = mine ? '#fff' : '#1e293b';
                    const border = mine ? 'none' : '1px solid #e2e8f0';
                    html += '<div style="display:flex; flex-direction:column; align-items:' + align + '; margin-bottom:10px;">';
                    if (m.message) html += '<div style="background:' + bg + '; color:' + color + '; border:' + border + '; padding:8px 12px; border-radius:12px; max-width:84%; word-wrap:break-word; font-size:14px;">' + esc(m.message) + '</div>';
                    if (m.image_url) html += '<img src="' + esc(m.image_url) + '" alt="" style="margin-top:6px; max-width:220px; border-radius:8px; border:1px solid #e2e8f0;">';
                    html += '<div style="font-size:10px; color:#94a3b8; margin-top:3px;">' + (mine ? '<?php echo esc_js(__('Me', 'vendor-space')); ?>' : esc($name.text())) + ' &bull; ' + esc(m.created_at || '') + '</div>';
                    html += '</div>';
                });
                $messages.html(html);
                $messages.scrollTop($messages[0].scrollHeight);
            }

            function applyThreadBadges(threads) {
                const customerUnread = {};
                if (Array.isArray(threads)) {
                    threads.forEach(function (t) {
                        const vendorId = Number(t.vendor_id || 0);
                        const customerId = Number(t.customer_id || 0);
                        const unread = Number(t.unread_count || 0);
                        if (!vendorId || !customerId || unread <= 0) return;
                        const key = vendorId + ':' + customerId;
                        customerUnread[key] = (customerUnread[key] || 0) + unread;
                    });
                }

                $('.vs-best-clients-thread-open').each(function () {
                    const $btn = $(this);
                    const vendorId = Number($btn.data('vendor-id') || 0);
                    const customerId = Number($btn.data('customer-id') || 0);
                    const key = vendorId + ':' + customerId;
                    const unread = Number(customerUnread[key] || 0);
                    const $badge = $btn.find('.vs-best-clients-chat-badge');
                    const $label = $btn.find('.vs-best-clients-chat-label');

                    if (unread > 0) {
                        $badge.text(unread).show();
                        $label.text('<?php echo esc_js(__('Chat', 'vendor-space')); ?> (' + unread + ')');
                    } else {
                        $badge.text('0').hide();
                        $label.text('<?php echo esc_js(__('Chat', 'vendor-space')); ?>');
                    }
                });
            }

            function loadThreadBadges() {
                $.ajax({
                    type: 'POST',
                    url: ajaxUrl,
                    dataType: 'json',
                    data: { action: 'vs_vendor_chat_threads', security: security },
                    success: function (res) {
                        if (res && res.success && res.data && Array.isArray(res.data.threads)) {
                            applyThreadBadges(res.data.threads);
                        }
                    }
                });
            }

            function loadMessages() {
                if (!thread.product_id || !thread.vendor_id || !thread.customer_id) {
                    setError('<?php echo esc_js(__('Invalid parameters for chat.', 'vendor-space')); ?>');
                    return;
                }
                $.ajax({
                    type: 'POST', url: ajaxUrl, dataType: 'json',
                    data: { action: 'vs_vendor_chat_messages', security: security, product_id: thread.product_id, vendor_id: thread.vendor_id, customer_id: thread.customer_id },
                    success: function (res) {
                        if (res && res.success && res.data && Array.isArray(res.data.messages)) {
                            clearError(); renderMessages(res.data.messages);
                            if (Number(res.data.marked_read || 0) > 0) {
                                loadThreadBadges();
                            }
                        } else {
                            setError(res.data ? res.data.message : '<?php echo esc_js(__('Failed to load messages.', 'vendor-space')); ?>');
                        }
                    },
                    error: function() {
                        setError('<?php echo esc_js(__('Connection error.', 'vendor-space')); ?>');
                    }
                });
            }

            $(document).on('click', '.vs-best-clients-thread-open', function () {
                thread = { product_id: $(this).data('product-id'), vendor_id: $(this).data('vendor-id'), customer_id: $(this).data('customer-id') };
                $name.text($(this).data('counterpart-name') || '');
                $messages.html('<div style="text-align:center; color:#94a3b8; margin-top:20px;"><?php echo esc_js(__('Loading...', 'vendor-space')); ?></div>');
                $form.find('textarea[name="message"]').val('');
                $form.find('input[name="image"]').val('');
                $modal.css('display', 'flex');
                loadMessages();
                stopPoll(); poll = setInterval(loadMessages, 5000);
            });

            $modal.on('click', '.vs-best-clients-thread-close', function() { stopPoll(); $modal.hide(); });
            $modal.on('click', function (e) { if (e.target === this) { stopPoll(); $modal.hide(); } });

            $form.on('submit', function (e) {
                e.preventDefault();
                const msg = String($form.find('textarea[name="message"]').val() || '').trim();
                const fi = $form.find('input[name="image"]')[0];
                const hasImg = !!(fi && fi.files && fi.files[0]);
                if (!msg && !hasImg) return;

                const fd = new FormData();
                fd.append('action', 'vs_vendor_chat_reply'); fd.append('security', security);
                fd.append('product_id', thread.product_id); fd.append('vendor_id', thread.vendor_id);
                fd.append('customer_id', thread.customer_id); fd.append('message', msg);
                if (hasImg) fd.append('image', fi.files[0]);

                $form.find('button[type="submit"]').prop('disabled', true);
                $.ajax({
                    url: ajaxUrl, type: 'POST', data: fd, processData: false, contentType: false, dataType: 'json',
                    success: function (res) {
                        $form.find('button[type="submit"]').prop('disabled', false);
                        if (res && res.success) {
                            $form.find('textarea[name="message"]').val(''); $form.find('input[name="image"]').val(''); loadMessages(); loadThreadBadges();
                        } else {
                            setError(res.data ? res.data.message : '<?php echo esc_js(__('Error sending message.', 'vendor-space')); ?>');
                        }
                    },
                    error: function () {
                        $form.find('button[type="submit"]').prop('disabled', false);
                        setError('<?php echo esc_js(__('Connection failed.', 'vendor-space')); ?>');
                    }
                });
            });

            loadThreadBadges();
            stopBadgePoll();
            badgePoll = setInterval(loadThreadBadges, 10000);
            $(window).on('beforeunload', function () { stopPoll(); stopBadgePoll(); });
        });
        </script>
        <?php
        return ob_get_clean();
    }

    private static function get_best_clients($vendor_id, $period = self::PERIOD_ALL_TIME) {
        $clients = [];
        $vendor_id = (int) $vendor_id;
        if ($vendor_id <= 0) {
            return [];
        }

        $period = self::sanitize_period($period);
        $paged = 1;
        $max_pages = 1;
        $fallback_product_id = null;
        $date_filter = self::date_created_filter($period);
        $has_commission = class_exists('VS_Commission');

        do {
            $query = [
                'limit' => self::ORDERS_PAGE_SIZE,
                'paginate' => true,
                'paged' => $paged,
                'status' => ['completed', 'processing'],
            ];
            if ($date_filter !== '') {
                $query['date_created'] = $date_filter;
            }

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

            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_order_total = 0;
            $has_vendor_product = false;
            $first_product_id = 0;

            foreach ($order->get_items() as $item) {
                $item_vendor = $item->get_meta('_vs_vendor_id');
                $pid = $item->get_product_id();

                if (empty($item_vendor) && $pid) {
                    $item_vendor = get_post_field('post_author', $pid);
                }

                if ((int) $item_vendor === (int) $vendor_id) {
                    $has_vendor_product = true;
                    if (!$first_product_id && $pid) {
                        $first_product_id = $pid;
                    }
                    if (!$has_commission) {
                        $vendor_order_total += (float) $item->get_total();
                    }
                }
            }

            if (!$has_vendor_product) {
                continue;
            }

            if ($has_commission) {
                $fin = VS_Commission::get_order_financials($order->get_id(), $vendor_id);
                if (is_array($fin) && isset($fin['net_earning'])) {
                    $vendor_order_total = (float) $fin['net_earning'];
                }
            }

            // Fallback: if we found a vendor product but couldn't get a specific ID, try to find any active product by this vendor
            if ($has_vendor_product && !$first_product_id) {
                if ($fallback_product_id === null) {
                    $vendor_products = get_posts(['post_type' => 'product', 'author' => $vendor_id, 'posts_per_page' => 1, 'fields' => 'ids']);
                    $fallback_product_id = !empty($vendor_products) ? (int) $vendor_products[0] : 0;
                }
                $first_product_id = (int) $fallback_product_id;
            }

            if ($has_vendor_product) {
                $email = sanitize_email($order->get_billing_email());
                if (!$email) continue;

                if (!isset($clients[$email])) {
                    // Try to get customer ID from order, fallback to searching by email
                    $customer_id = (int) $order->get_customer_id();
                    if (!$customer_id) {
                        $user_obj = get_user_by('email', $email);
                        if ($user_obj) {
                            $customer_id = $user_obj->ID;
                        }
                    }

                    $name = trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name());
                    if ($name === '' && $customer_id > 0) {
                        $customer_user = get_userdata($customer_id);
                        if ($customer_user) {
                            $name = (string) $customer_user->display_name;
                        }
                    }
                    if ($name === '') {
                        $name = $email;
                    }

                    $clients[$email] = [
                        'name'            => $name,
                        'email'           => $email,
                        'customer_id'     => $customer_id,
                        'order_count'     => 0,
                        'total_spent'     => 0,
                        'last_order_date' => $order_date_label,
                        'last_order_ts'   => $order_ts,
                        'product_id'      => $first_product_id,
                    ];
                }

                $clients[$email]['order_count']++;
                $clients[$email]['total_spent'] += $vendor_order_total;
                
                $current_last_ts = (int) $clients[$email]['last_order_ts'];
                if ($order_ts > $current_last_ts) {
                    $clients[$email]['last_order_date'] = $order_date_label;
                    $clients[$email]['last_order_ts'] = $order_ts;
                    $clients[$email]['product_id'] = $first_product_id;
                }
            }
        }

            $paged++;
        } while ($paged <= $max_pages);

        foreach ($clients as $email => $client) {
            $activity = self::activity_meta((int) $client['last_order_ts']);
            $clients[$email]['activity_label'] = $activity['label'];
            $clients[$email]['activity_color'] = $activity['color'];
        }

        // Sort by total spent DESC
        uasort($clients, function($a, $b) {
            return $b['total_spent'] <=> $a['total_spent'];
        });

        return array_values($clients);
    }

    private static function sanitize_period($period) {
        $period = sanitize_key((string) $period);
        $allowed = [self::PERIOD_30_DAYS, self::PERIOD_6_MONTHS, self::PERIOD_ALL_TIME];
        return in_array($period, $allowed, true) ? $period : self::PERIOD_ALL_TIME;
    }

    private static function period_options() {
        return [
            self::PERIOD_30_DAYS => __('Last 30 days', 'vendor-space'),
            self::PERIOD_6_MONTHS => __('Last 6 months', 'vendor-space'),
            self::PERIOD_ALL_TIME => __('All time', 'vendor-space'),
        ];
    }

    private static function period_label($period) {
        $options = self::period_options();
        return isset($options[$period]) ? $options[$period] : $options[self::PERIOD_ALL_TIME];
    }

    private static function date_created_filter($period) {
        $now = (int) current_time('timestamp');
        if ($period === self::PERIOD_30_DAYS) {
            return '>' . ($now - (30 * DAY_IN_SECONDS));
        }
        if ($period === self::PERIOD_6_MONTHS) {
            return '>' . ($now - (180 * DAY_IN_SECONDS));
        }
        return '';
    }

    private static function activity_meta($last_order_ts) {
        $last_order_ts = (int) $last_order_ts;
        $days = (int) floor((current_time('timestamp') - $last_order_ts) / DAY_IN_SECONDS);
        if ($days <= 30) {
            return ['label' => __('Active', 'vendor-space'), 'color' => '#16a34a'];
        }
        if ($days <= 180) {
            return ['label' => __('Recently', 'vendor-space'), 'color' => '#eab308'];
        }
        return ['label' => __('Inactive', 'vendor-space'), 'color' => '#6b7280'];
    }

    private static function should_export_csv($vendor_id) {
        if (!is_user_logged_in()) {
            return false;
        }
        if (empty($_GET['vs_best_clients_export'])) {
            return false;
        }
        $nonce = isset($_GET['vs_best_clients_nonce']) ? sanitize_text_field(wp_unslash($_GET['vs_best_clients_nonce'])) : '';
        return wp_verify_nonce($nonce, 'vs_best_clients_export_' . (int) $vendor_id) !== false;
    }

    private static function export_csv($clients_data, $period) {
        while (ob_get_level() > 0) {
            ob_end_clean();
        }

        nocache_headers();
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=clients-' . gmdate('Ymd-His') . '.csv');

        $out = fopen('php://output', 'w');
        if (!$out) {
            exit;
        }

        fputcsv($out, [__('Period', 'vendor-space'), self::period_label($period)]);
        fputcsv($out, [__('Customer', 'vendor-space'), __('Email', 'vendor-space'), __('Orders Count', 'vendor-space'), __('Total Spent', 'vendor-space'), __('Currency', 'vendor-space'), __('Last Order', 'vendor-space'), __('Activity', 'vendor-space')]);

        foreach ($clients_data as $client) {
            fputcsv($out, [
                (string) ($client['name'] ?? ''),
                (string) ($client['email'] ?? ''),
                (int) ($client['order_count'] ?? 0),
                (float) ($client['total_spent'] ?? 0),
                (string) get_woocommerce_currency(),
                (string) ($client['last_order_date'] ?? ''),
                (string) ($client['activity_label'] ?? ''),
            ]);
        }

        fclose($out);
        exit;
    }
}
