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

class VS_Orders {

    public static function init() {
        add_action('woocommerce_order_details_after_order_table', [__CLASS__, 'render_customer_chat']);
    }

    public static function render_customer_chat($order) {
        if (!$order || !is_user_logged_in()) {
            return;
        }

        $current_user_id = (int) get_current_user_id();
        $customer_id = (int) $order->get_customer_id();
        if ($customer_id <= 0) {
            return;
        }
        if ($customer_id !== $current_user_id && !current_user_can('administrator')) {
            return;
        }

        $vendor_id = 0;
        $product_id = 0;
        foreach ($order->get_items() as $item) {
            $pid = (int) $item->get_product_id();
            if ($pid <= 0) {
                continue;
            }

            $item_vendor = (int) $item->get_meta('_vs_vendor_id');
            if ($item_vendor <= 0) {
                $item_vendor = (int) get_post_field('post_author', $pid);
            }

            if ($item_vendor > 0) {
                $vendor_id = $item_vendor;
                $product_id = $pid;
                break;
            }
        }

        if ($vendor_id <= 0 || $product_id <= 0) {
            return;
        }

        $vendor_user = get_userdata($vendor_id);
        $vendor_name = $vendor_user ? $vendor_user->display_name : __('Seller', 'vendor-space');
        $security = wp_create_nonce('vs_nonce');
        ?>
        <div class="vs-customer-chat-section" style="margin-top:30px; padding:20px; background:#f9f9f9; border-radius:8px;">
            <h3><?php echo esc_html__('Contact Seller', 'vendor-space'); ?></h3>
            <p><?php echo esc_html__('Have a question about your order? Chat directly with the seller.', 'vendor-space'); ?></p>
            <button type="button"
                    class="vs-customer-thread-open"
                    data-product-id="<?php echo esc_attr($product_id); ?>"
                    data-vendor-id="<?php echo esc_attr($vendor_id); ?>"
                    data-customer-id="<?php echo esc_attr($customer_id); ?>"
                    data-counterpart-name="<?php echo esc_attr($vendor_name); ?>"
                    style="position:relative; background:#2563eb; color:#fff; border:none; padding:10px 20px; border-radius:5px; cursor:pointer; font-size:16px;">
                <?php echo esc_html__('Start Chat', 'vendor-space'); ?>
                <span class="vs-customer-chat-btn-badge"
                      style="display:none; position:absolute; top:-8px; right:-10px; min-width:20px; height:20px; padding:0 6px; border-radius:999px; background:#dc2626; color:#fff; font-size:11px; font-weight:700; line-height:20px; text-align:center;">0</span>
            </button>
            
        </div>

       

        <script>
        jQuery(function ($) {
            const $modal = $('#vs-customer-thread-modal');
            if (!$modal.length) return;

            const ajaxUrl = '<?php echo esc_url(admin_url('admin-ajax.php')); ?>';
            const security = String($modal.data('security') || '');
            const $messages = $modal.find('.vs-customer-thread-messages');
            const $feedback = $modal.find('.vs-customer-thread-feedback');
            const $form = $modal.find('.vs-customer-thread-form');
            const $name = $modal.find('.vs-customer-thread-name');
            const $openBtn = $('.vs-customer-thread-open').first();
            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 setChatBadge(count) {
                const n = Math.max(0, Number(count || 0));
                const $badge = $openBtn.find('.vs-customer-chat-btn-badge');
                if (!$badge.length) return;
                if (n > 0) {
                    $badge.text(n).show();
                } else {
                    $badge.hide();
                }
            }

            function refreshChatBadge() {
                const pid = Number($openBtn.data('product-id') || 0);
                const vid = Number($openBtn.data('vendor-id') || 0);
                const cid = Number($openBtn.data('customer-id') || 0);
                if (!pid || !vid || !cid) return;
                $.post(ajaxUrl, {
                    action: 'vs_vendor_chat_threads',
                    security: security
                }, function (res) {
                    if (!(res && res.success && res.data && Array.isArray(res.data.threads))) return;
                    const t = res.data.threads.find(function (item) {
                        return Number(item.product_id || 0) === pid
                            && Number(item.vendor_id || 0) === vid
                            && Number(item.customer_id || 0) === cid;
                    });
                    setChatBadge(t ? Number(t.unread_count || 0) : 0);
                }, 'json');
            }

            function setError(message) {
                $feedback.text(message || '<?php echo esc_js(__('Request failed. Please try again.', 'vendor-space')); ?>').show();
            }

            function clearError() {
                $feedback.hide().text('');
            }

            function stopPoll() {
                if (poll) {
                    clearInterval(poll);
                    poll = null;
                }
            }

            function renderMessages(items) {
                if (!Array.isArray(items) || !items.length) {
                    $messages.html('<div style="text-align:center; color:#999; margin-top:20px;"><?php echo esc_js(__('No messages yet. Start the conversation!', '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' : '#e5e7eb';
                    const color = mine ? '#fff' : '#1f2937';
                    html += '<div style="display:flex; flex-direction:column; align-items:' + align + '; margin-bottom:10px;">';
                    if (m.message) html += '<div style="background:' + bg + '; color:' + color + '; padding:8px 12px; border-radius:12px; max-width:84%; word-wrap:break-word;">' + 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:#999; 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 loadMessages() {
                if (!thread.product_id || !thread.vendor_id || !thread.customer_id) 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) {
                                setChatBadge(0);
                            }
                        } else {
                            setError('<?php echo esc_js(__('Failed to load messages.', 'vendor-space')); ?>');
                        }
                    },
                    error: function () {
                        setError('<?php echo esc_js(__('Connection failed. Please try again.', 'vendor-space')); ?>');
                    }
                });
            }

            function openModal(data) {
                thread = {
                    product_id: Number(data.product_id || 0),
                    vendor_id: Number(data.vendor_id || 0),
                    customer_id: Number(data.customer_id || 0)
                };
                if (!thread.product_id || !thread.vendor_id || !thread.customer_id) return;
                clearError();
                $name.text(data.counterpart_name || '<?php echo esc_js(__('Seller', 'vendor-space')); ?>');
                $form.find('textarea[name="message"]').val('');
                $form.find('input[name="image"]').val('');
                $messages.html('<div style="text-align:center; color:#999; margin-top:20px;"><?php echo esc_js(__('Loading messages...', 'vendor-space')); ?></div>');
                $modal.css('display', 'flex');
                loadMessages();
                stopPoll();
                poll = setInterval(loadMessages, 5000);
            }

            function closeModal() {
                stopPoll();
                $modal.hide();
            }

            $(document).on('click', '.vs-customer-thread-open', function () {
                openModal({
                    product_id: $(this).data('product-id'),
                    vendor_id: $(this).data('vendor-id'),
                    customer_id: $(this).data('customer-id'),
                    counterpart_name: $(this).data('counterpart-name')
                });
            });

            $modal.on('click', '.vs-customer-thread-close', closeModal);
            $modal.on('click', function (e) {
                if (e.target === this) closeModal();
            });

            $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', String(thread.product_id || 0));
                fd.append('vendor_id', String(thread.vendor_id || 0));
                fd.append('customer_id', String(thread.customer_id || 0));
                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();
                            refreshChatBadge();
                        } else {
                            setError((res && res.data && res.data.message) ? res.data.message : '<?php echo esc_js(__('Failed to send message.', 'vendor-space')); ?>');
                        }
                    },
                    error: function () {
                        $form.find('button[type="submit"]').prop('disabled', false);
                        setError('<?php echo esc_js(__('Connection failed. Please try again.', 'vendor-space')); ?>');
                    }
                });
            });

            refreshChatBadge();
            if (badgePoll) clearInterval(badgePoll);
            badgePoll = setInterval(refreshChatBadge, 20000);
        });
        </script>
        <?php
    }
    public static function render($user) {
        ob_start();
        ?>
        
        <!-- My Orders Tab -->
        <div class="vs-tab" id="tab-my-orders" 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;">
                <h2 style="margin:0; font-size:24px; color:#1e293b;"><?php echo esc_html__('My Orders', 'vendor-space'); ?></h2>
            </div>

            <p class="vs-subtitle" style="margin-bottom: 20px; color: #64748b;"><?php echo esc_html__('Manage and track your customer orders.', 'vendor-space'); ?></p>

            <?php
            $user_id = get_current_user_id();
            $orders = wc_get_orders(['limit' => 50, 'orderby' => 'date', 'order' => 'DESC']);
            $my_orders = [];
            
            $total_orders       = 0;
            $completed_orders   = 0;
            $processing_orders  = 0;
            $total_net_earnings = 0;

            foreach($orders as $order) {
                $items = $order->get_items();
                $has_item = false;
                
                foreach($items as $item) {
                    // Prefer saved vendor id on line item (works even if product deleted)
                    $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 === (int) $user_id) {
                        $has_item = true;
                        break;
                    }
                }
                
                if ($has_item) {
                    $fin = VS_Commission::get_order_financials($order->get_id(), $user_id);
                    $order->vendor_total = (float) $fin['net_earning'];
                    $my_orders[] = $order;
                    
                    $total_orders++;
                    $status = $order->get_status();
                    if ($status === 'processing') $processing_orders++;
                    if ($status === 'completed') $completed_orders++;
                    $total_net_earnings += $order->vendor_total;
                }
            }
            ?>

            <style>
                .vs-metrics-grid {
                    display: grid;
                    grid-template-columns: repeat(4, minmax(0, 1fr));
                    gap: 14px;
                    margin-bottom: 25px;
                }
                .vs-metric-card {
                    display: flex;
                    align-items: center;
                    gap: 14px;
                    padding: 16px;
                    background: #fff;
                    border-radius: 12px;
                    box-shadow: 0 4px 14px rgba(15, 23, 42, 0.06);
                    min-width: 0;
                }
                .vs-metric-card .dashicons {
                    flex: 0 0 auto;
                    width: 38px;
                    height: 38px;
                    font-size: 20px;
                    line-height: 38px;
                    text-align: center;
                    border-radius: 999px;
                    background: #eff6ff;
                  
                }
                .vs-metric-card small {
                    display: block;
                    margin-bottom: 4px;
                    color: #64748b;
                    font-size: 12px;
                    line-height: 1.4;
                }
                .vs-metric-card strong {
                    display: block;
                    color: #0f172a;
                    font-size: 20px;
                    line-height: 1.2;
                    word-break: break-word;
                }
                @media (max-width: 991px) {
                    .vs-metrics-grid {
                        grid-template-columns: repeat(2, minmax(0, 1fr));
                    }
                }
                @media (max-width: 767px) {
                    .vs-metrics-grid {
                        grid-template-columns: 1fr;
                        gap: 12px;
                    }
                    .vs-metric-card {
                        width: 100%;
                    }
                }
            </style>
            <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-cart"></span>
                    <div>
                        <small><?php echo esc_html__('Total Orders', 'vendor-space'); ?></small>
                        <strong id="vs-metric-total-orders" data-raw-value="<?php echo esc_attr($total_orders); ?>"><?php echo $total_orders; ?></strong>
                    </div>
                </div>

                <div class="vs-metric-card vs-published" style="border-left: 4px solid #10b981;">
                    <span class="dashicons dashicons-yes-alt"></span>
                    <div>
                        <small><?php echo esc_html__('Completed', 'vendor-space'); ?></small>
                        <strong id="vs-metric-completed-orders" data-raw-value="<?php echo esc_attr($completed_orders); ?>"><?php echo $completed_orders; ?></strong>
                    </div>
                </div>

                <div class="vs-metric-card vs-pending" style="border-left: 4px solid #f59e0b;">
                    <span class="dashicons dashicons-clock"></span>
                    <div>
                        <small><?php echo esc_html__('Processing', 'vendor-space'); ?></small>
                        <strong id="vs-metric-processing-orders" data-raw-value="<?php echo esc_attr($processing_orders); ?>"><?php echo $processing_orders; ?></strong>
                    </div>
                </div>

                <div class="vs-metric-card vs-stock" style="border-left: 4px solid #8b5cf6;">
                    <span class="dashicons dashicons-chart-area"></span>
                    <div>
                        <small><?php echo esc_html__('Total Earnings', 'vendor-space'); ?></small>
                        <strong id="vs-metric-total-earnings" data-raw-value="<?php echo esc_attr((string) $total_net_earnings); ?>"><?php echo wc_price($total_net_earnings); ?></strong>
                    </div>
                </div>
            </div>


            <div class="vs-orders-tools" style="margin: 15px 0; display:flex; gap:10px; flex-wrap:wrap; align-items:center;">
                <input type="text" id="vs-orders-search" placeholder="<?php echo esc_attr__('Search by order #, name, email...', 'vendor-space'); ?>" style="padding:10px; flex:1; min-width:220px; border: 1px solid #e5e7eb; border-radius: 8px;">

                <select id="vs-orders-filter-status" style="padding:10px; min-width:170px; border: 1px solid #e5e7eb; border-radius: 8px;">
                    <option value=""><?php echo esc_html__('All statuses', 'vendor-space'); ?></option>
                    <option value="processing"><?php echo esc_html__('Processing', 'vendor-space'); ?></option>
                    <option value="completed"><?php echo esc_html__('Completed', 'vendor-space'); ?></option>
                </select>

                <div class="vs-date-filter-group" style="display:flex; align-items:center; gap:8px; background:white; border:1px solid #e5e7eb; padding:2px 12px; border-radius:8px;">
                    <div style="display:flex; align-items:center; gap:5px;">
                        <label for="vs-orders-date-from" style="font-size:12px; font-weight:600; color:#6b7280; text-transform:uppercase;"><?php echo esc_html__('From', 'vendor-space'); ?></label>
                        <input type="date" id="vs-orders-date-from" style="border:none; padding:8px 4px; font-size:13px; outline:none; color:#374151;">
                    </div>
                    <div style="width:1px; height:20px; background:#e5e7eb;"></div>
                    <div style="display:flex; align-items:center; gap:5px;">
                        <label for="vs-orders-date-to" style="font-size:12px; font-weight:600; color:#6b7280; text-transform:uppercase;"><?php echo esc_html__('To', 'vendor-space'); ?></label>
                        <input type="date" id="vs-orders-date-to" style="border:none; padding:8px 4px; font-size:13px; outline:none; color:#374151;">
                    </div>
                </div>
                <?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')) :
                ?>
                <button type="button" id="vs-orders-export" class="vs-btn-sm" style="background:#0ea5e9; color:white; border:none; padding:10px 12px; border-radius:8px; cursor:pointer; font-weight: 600;">
                    <?php echo esc_html__('Export CSV', 'vendor-space'); ?>
                </button>
                <?php endif; ?>

                <button type="button" id="vs-orders-toggle-select" class="vs-btn-sm" style="background:#334155; color:white; border:none; padding:10px 12px; border-radius:8px; cursor:pointer; font-weight: 600;">
                    <?php echo esc_html__('Select All', 'vendor-space'); ?>
                </button>
                <button type="button" id="vs-orders-delete-selected" class="vs-btn-sm" style="background:#ef4444; color:white; border:none; padding:10px 12px; border-radius:8px; cursor:pointer; font-weight: 600;">
                    <?php echo esc_html__('Delete Selected', 'vendor-space'); ?>
                </button>
            </div>

            <?php if (!empty($my_orders)): ?>
                <style>
                    .vs-orders-table-wrap {
                        width: 100%;
                    }
                    .vs-orders-table {
                        width: 100%;
                        border-collapse: collapse;
                        margin-top: 20px;
                        border: 1px solid #e5e7eb;
                    }
                    @media (max-width: 767px) {
                        .vs-orders-table-wrap {
                            overflow: hidden;
                        }
                        .vs-orders-table,
                        .vs-orders-table thead,
                        .vs-orders-table tbody,
                        .vs-orders-table tr,
                        .vs-orders-table th,
                        .vs-orders-table td {
                            display: block;
                            width: 100%;
                        }
                        .vs-orders-table {
                            border: none;
                            margin-top: 16px;
                        }
                        .vs-orders-table thead {
                            display: none;
                        }
                        .vs-orders-table tr {
                            margin-bottom: 14px;
                            border: 1px solid #e5e7eb;
                            border-radius: 12px;
                            overflow: hidden;
                            background: #fff;
                            box-shadow: 0 4px 14px rgba(15, 23, 42, 0.06);
                        }
                        .vs-orders-table td {
                            border: none;
                            border-bottom: 1px solid #f1f5f9;
                            padding: 12px 14px !important;
                            text-align: left !important;
                        }
                        .vs-orders-table td:last-child {
                            border-bottom: none;
                        }
                        .vs-orders-table td::before {
                            content: attr(data-label);
                            display: block;
                            margin-bottom: 6px;
                            font-size: 11px;
                            font-weight: 700;
                            color: #64748b;
                            text-transform: uppercase;
                            letter-spacing: 0.04em;
                        }
                        .vs-orders-table td[data-label="<?php echo esc_attr__('Actions', 'vendor-space'); ?>"] > div {
                            justify-content: flex-start;
                        }
                        .vs-orders-tools,
                        .vs-date-filter-group {
                            width: 100%;
                        }
                        .vs-date-filter-group {
                            flex-direction: column;
                            align-items: stretch !important;
                            padding: 10px 12px !important;
                        }
                    }
                </style>
                <div class="vs-orders-table-wrap">
                <table class="vs-orders-table" style="width:100%; border-collapse:collapse; margin-top:20px; border: 1px solid #e5e7eb;">
                    <thead>
                        <tr  style="background: #f8fafc; border-bottom: 1px solid #e2e8f0;">
                            <th  style="padding: 15px 20px; font-weight: 600; background-color: #f8fafc;">
                                <input type="checkbox" id="vs-orders-select-all" aria-label="<?php echo esc_attr__('Select all orders', 'vendor-space'); ?>">
                            </th>
                            <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Order #', 'vendor-space'); ?></th>
                            <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Customer', 'vendor-space'); ?></th>
                            <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Date', 'vendor-space'); ?></th>
                            <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Status', 'vendor-space'); ?></th>
                            <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Net Earning', 'vendor-space'); ?></th>
                            <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Actions', 'vendor-space'); ?></th>
                        </tr>
                    </thead>
                    <tbody id="vs-orders-tbody">
                        <?php 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_name = $customer_name;
                            $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;
                            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 === (int) $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 && $pid > 0) {
                                            $image_id = get_post_thumbnail_id($pid);
                                        }
                                        if (!$image_id) {
                                            $variation_id = (int) $item->get_variation_id();
                                            if ($variation_id > 0) {
                                                $image_id = get_post_thumbnail_id($variation_id);
                                            }
                                        }
                                        if ($image_id) {
                                            $image_url = (string) wp_get_attachment_image_url($image_id, 'thumbnail');
                                        }
                                        if (!$image_url && $pid > 0) {
                                            $image_url = (string) get_the_post_thumbnail_url($pid, '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);
                            $chat_vendor_id = (int) $user_id;
                            $chat_customer_id = (int) $order->get_customer_id();
                        ?>
                        <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($billing_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="<?php echo esc_attr__('Select', 'vendor-space'); ?>" style="padding:15px;">
                                <input type="checkbox" class="vs-order-select" value="<?php echo esc_attr($order->get_id()); ?>" aria-label="<?php echo esc_attr(sprintf(__('Select order %s', 'vendor-space'), $order->get_order_number())); ?>">
                            </td>
                            <td data-label="<?php echo esc_attr__('Order #', 'vendor-space'); ?>" style="padding:15px; font-weight: 700; color: #2563eb;">#<?php echo $order->get_order_number(); ?></td>
                            <td data-label="<?php echo esc_attr__('Customer', 'vendor-space'); ?>" style="padding:15px;">
                                <div style="font-weight: 600; color: #1e293b;"><?php echo $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(); ?></div>
                                <small style="color:#64748b;"><?php echo $order->get_billing_email(); ?></small>
                            </td>
                            <td data-label="<?php echo esc_attr__('Date', 'vendor-space'); ?>" style="padding:15px; color: #475569;"><?php echo $order->get_date_created()->date('M j, Y'); ?></td>
                            <td data-label="<?php echo esc_attr__('Status', 'vendor-space'); ?>" style="padding:15px; vertical-align:middle;">
                                <?php
                                $statuses = wc_get_order_statuses();
                                $allowed_statuses = ['processing', 'completed', 'cancelled'];
                                $clean_statuses = [];
                                foreach ( $statuses as $key => $label ) {
                                    $slug = str_replace( 'wc-', '', $key );
                                    if ( in_array( $slug, $allowed_statuses ) ) {
                                        // Rename 'cancelled' to 'Rejected' for the user
                                        if($slug === 'cancelled') $label = __('Rejected', 'vendor-space');
                                        $clean_statuses[ $slug ] = $label;
                                    }
                                }
                                ?>
                                <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':($status_slug==='cancelled'?'#fee2e2':'#f3f4f6')); ?>;
                                        color:<?php echo $status_slug==='completed'?'#065f46':($status_slug==='processing'?'#1e40af':($status_slug==='cancelled'?'#991b1b':'#374151')); ?>; border:none; outline:none; appearance: none; text-align: center;">
                                    <?php foreach ( $clean_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="<?php echo esc_attr__('Net Earning', 'vendor-space'); ?>" style="padding:15px; font-weight:700; color: #1e293b;"><?php echo wc_price($order->vendor_total); ?></td>
                            <td data-label="<?php echo esc_attr__('Actions', 'vendor-space'); ?>" style="padding:15px;">
                                <div style="display:flex; gap:8px; flex-wrap:wrap;">
                                    <button type="button" class="vs-view-order vs-action-btn " 
                                            data-tooltip="<?php echo esc_attr__('View', 'vendor-space'); ?>"
                                            style="background:#3b82f6; color:white; border:none; padding:8px 12px; border-radius:6px; cursor:pointer; font-weight: 500; transition: 0.2s;"
                                            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" data-tooltip="<?php echo esc_attr__('Print', 'vendor-space'); ?>" style="background:#6366f1; color:white; border:none; padding:8px 12px; border-radius:6px; cursor:pointer; font-weight: 500; transition: 0.2s;" ><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;" title="<?php echo esc_attr__('Message', 'vendor-space'); ?>">
                                            <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(); ?>"
                                            data-tooltip="<?php echo esc_attr__('Delete', 'vendor-space'); ?>"
                                            style="background:#ef4444; color:white; border:none; padding:8px 12px; border-radius:6px; cursor:pointer; font-weight: 500; transition: 0.2s;">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                </div>

                <div class="vs-orders-pagination" id="vs-orders-pagination" style="margin-top:15px; display:flex; gap:8px; justify-content:flex-end; flex-wrap:wrap;"></div>
            <?php else: ?>
                <div class="no-orders" 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 orders containing your products.', 'vendor-space'); ?>
                </div>
            <?php endif; ?>

            <!-- Modal for Order Details -->
            <div id="vs-order-modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:10000; justify-content:center; align-items:center;">
                <div style="background:white; padding:25px; width:560px; max-width:92%; border-radius:10px; box-shadow:0 10px 40px rgba(0,0,0,0.25);">
                    <div style="display:flex; align-items:center; justify-content:space-between; gap:12px; margin-bottom:12px;">
                        <h3 id="vs-order-modal-title" style="margin:0;"><?php echo esc_html__('Order Items', 'vendor-space'); ?></h3>
                        <button type="button" id="vs-close-modal-x" aria-label="<?php echo esc_attr__('Close', 'vendor-space'); ?>" style="background:transparent; border:none; font-size:22px; line-height:1; cursor:pointer;">&times;</button>
                    </div>
                    <div id="vs-order-items-content" style="max-height:60vh; overflow-y:auto; margin-bottom:20px;"></div>
                    <button id="vs-close-modal" style="width:100%; padding:10px; background:#f3f4f6; border:none; border-radius:4px; cursor:pointer; font-weight:bold;"><?php echo esc_html__('Close', 'vendor-space'); ?></button>
                </div>
            </div>

            <!-- Orders Chat Modal -->
            <div id="vs-orders-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:540px; 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 -', 'vendor-space'); ?> <span class="vs-orders-thread-name"></span></h3>
                        <button type="button" class="vs-orders-thread-close" style="border:none; background:transparent; font-size:20px; cursor:pointer;">&times;</button>
                    </div>

                    <div class="vs-orders-thread-messages" style="flex:1; padding:15px; overflow-y:auto; background:#f9f9f9; display:flex; flex-direction:column; gap:10px;">
                        <div style="text-align:center; color:#999; margin-top:30px;"><?php echo esc_html__('Select an order chat.', 'vendor-space'); ?></div>
                    </div>

                    <form class="vs-orders-thread-form" style="padding:12px 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 #ddd; border-radius:6px; padding:8px; resize:vertical;"></textarea>
                        <div style="display:flex; gap:10px; align-items:center;">
                            <input type="file" name="image" accept="image/*">
                            <button type="submit" class="vs-orders-thread-send" style="margin-left:auto; background:#2563eb; color:#fff; border:none; padding:8px 16px; border-radius:5px; cursor:pointer;"><?php echo esc_html__('Send', 'vendor-space'); ?></button>
                        </div>
                    </form>
                    <div class="vs-orders-thread-feedback" style="padding:0 15px 12px; color:#b91c1c; display:none;"></div>
                </div>
            </div>

        </div>

        <?php self::render_scripts(); ?>
        
        <?php
        return ob_get_clean();
    }

    private static function render_scripts() {
        ?>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
        <script>
        document.addEventListener("DOMContentLoaded", function(){
            const modal = document.getElementById('vs-order-modal');
            const content = document.getElementById('vs-order-items-content');
            const titleEl = document.getElementById('vs-order-modal-title');
            const closeX = document.getElementById('vs-close-modal-x');
            const ordersAjaxUrl = '<?php echo esc_url(admin_url('admin-ajax.php')); ?>';
            const ordersSecurity = '<?php echo esc_js(wp_create_nonce('vs_orders_nonce')); ?>';
            const selectAllOrders = document.getElementById('vs-orders-select-all');
            const toggleSelectBtn = document.getElementById('vs-orders-toggle-select');
            const exportOrdersBtn = document.getElementById('vs-orders-export');
            const deleteSelectedBtn = document.getElementById('vs-orders-delete-selected');

            const getOrderRows = () => Array.from(document.querySelectorAll('#vs-orders-tbody tr'));
            const getSelectedRows = () => getOrderRows().filter(row => {
                const checkbox = row.querySelector('.vs-order-select');
                return checkbox && checkbox.checked;
            });
            const getRowsForBulkAction = () => {
                const selected = getSelectedRows();
                return selected.length ? selected : getOrderRows();
            };
            const csvEscape = (value) => '"' + String(value == null ? '' : value).replace(/"/g, '""') + '"';

            function syncSelectAllState() {
                const checkboxes = Array.from(document.querySelectorAll('.vs-order-select'));
                const checked = checkboxes.filter(input => input.checked);
                if (selectAllOrders) {
                    selectAllOrders.checked = checkboxes.length > 0 && checked.length === checkboxes.length;
                    selectAllOrders.indeterminate = checked.length > 0 && checked.length < checkboxes.length;
                }
                if (toggleSelectBtn) {
                    toggleSelectBtn.textContent = checkboxes.length > 0 && checked.length === checkboxes.length ? 'Clear Selection' : 'Select All';
                }
            }

            function setAllSelections(checked) {
                document.querySelectorAll('.vs-order-select').forEach(input => {
                    input.checked = checked;
                });
                syncSelectAllState();
            }

            function removeOrderRow(row) {
                if (!row) return;
                const totalOrdersEl = document.getElementById('vs-metric-total-orders');
                const completedOrdersEl = document.getElementById('vs-metric-completed-orders');
                const processingOrdersEl = document.getElementById('vs-metric-processing-orders');
                const totalEarningsEl = document.getElementById('vs-metric-total-earnings');
                const status = row.getAttribute('data-status') || '';
                const amount = Number(row.getAttribute('data-order-total') || row.getAttribute('data-vendor-total') || 0);

                if (totalOrdersEl) {
                    const value = Math.max(0, Number(totalOrdersEl.getAttribute('data-raw-value') || 0) - 1);
                    totalOrdersEl.setAttribute('data-raw-value', String(value));
                    totalOrdersEl.textContent = String(value);
                }
                if (status === 'completed' && completedOrdersEl) {
                    const value = Math.max(0, Number(completedOrdersEl.getAttribute('data-raw-value') || 0) - 1);
                    completedOrdersEl.setAttribute('data-raw-value', String(value));
                    completedOrdersEl.textContent = String(value);
                }
                if (status === 'processing' && processingOrdersEl) {
                    const value = Math.max(0, Number(processingOrdersEl.getAttribute('data-raw-value') || 0) - 1);
                    processingOrdersEl.setAttribute('data-raw-value', String(value));
                    processingOrdersEl.textContent = String(value);
                }
                if (totalEarningsEl && !Number.isNaN(amount)) {
                    const currentAmount = Number(totalEarningsEl.getAttribute('data-raw-value') || 0);
                    const updatedAmount = Math.max(0, currentAmount - amount);
                    totalEarningsEl.setAttribute('data-raw-value', String(updatedAmount));
                    totalEarningsEl.textContent = updatedAmount.toFixed(2);
                }
                row.remove();
                syncSelectAllState();
            }

            function exportOrdersToCsv(rows) {
                if (!rows.length) {
                    alert('<?php echo esc_js(__('No orders available to export.', 'vendor-space')); ?>');
                    return;
                }

                const headers = ['<?php echo esc_js(__('Order #', 'vendor-space')); ?>', '<?php echo esc_js(__('Date', 'vendor-space')); ?>', '<?php echo esc_js(__('Customer Name', 'vendor-space')); ?>', '<?php echo esc_js(__('Customer Email', 'vendor-space')); ?>', '<?php echo esc_js(__('Payment Method', 'vendor-space')); ?>', '<?php echo esc_js(__('Billing Name', 'vendor-space')); ?>', '<?php echo esc_js(__('Billing Address', 'vendor-space')); ?>', '<?php echo esc_js(__('Billing City', 'vendor-space')); ?>', '<?php echo esc_js(__('Billing ZIP', 'vendor-space')); ?>', '<?php echo esc_js(__('Billing Country', 'vendor-space')); ?>', '<?php echo esc_js(__('Billing Phone', 'vendor-space')); ?>', '<?php echo esc_js(__('Order Total', 'vendor-space')); ?>', '<?php echo esc_js(__('Items', 'vendor-space')); ?>'];
                // Build XLSX data array
                const xlsxRows = [headers];
                rows.forEach(row => {
                    const rawItems = row.getAttribute('data-order-items') || '[]';
                    let items = [];
                    try { items = JSON.parse(rawItems); } catch (_) { items = []; }
                    const itemText = items.map(item => {
                        const name = item && item.name ? item.name : '';
                        const qty = item && item.qty ? item.qty : 0;
                        const total = item && item.total ? item.total : 0;
                        return `${name} x${qty} (${total})`;
                    }).join(' | ');

                    xlsxRows.push([
                        row.getAttribute('data-order-number') || '',
                        row.getAttribute('data-order-date') || row.getAttribute('data-date') || '',
                        row.getAttribute('data-customer-name') || '',
                        row.getAttribute('data-customer-email') || '',
                        row.getAttribute('data-payment-method') || '',
                        row.getAttribute('data-billing-name') || '',
                        row.getAttribute('data-billing-address') || '',
                        row.getAttribute('data-billing-city') || '',
                        row.getAttribute('data-billing-zip') || '',
                        row.getAttribute('data-billing-country') || '',
                        row.getAttribute('data-billing-phone') || '',
                        row.getAttribute('data-order-total') || row.getAttribute('data-vendor-total') || '',
                        itemText
                    ]);
                });

                const ws = XLSX.utils.aoa_to_sheet(xlsxRows);
                const colWidths = xlsxRows[0].map((_, ci) => ({
                    wch: Math.max(...xlsxRows.map(row => row[ci] ? String(row[ci]).length : 10)) + 2
                }));
                ws['!cols'] = colWidths;
                const wb = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(wb, ws, 'Orders');
                XLSX.writeFile(wb, `orders-${new Date().toISOString().slice(0, 10)}.xlsx`);
            }

            async function deleteOrders(rows) {
    if (!rows.length) {
        Swal.fire({
            icon: 'info',
            text: '<?php echo esc_js(__('No orders selected.', 'vendor-space')); ?>'
        });
        return;
    }

    const result = await Swal.fire({
        title: '<?php echo esc_js(__('Are you sure?', 'vendor-space')); ?>',
        text: '<?php echo esc_js(__('Delete', 'vendor-space')); ?> ' + rows.length + ' <?php echo esc_js(__('order(s)? This cannot be undone.', 'vendor-space')); ?>',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: '<?php echo esc_js(__('Yes, delete it!', 'vendor-space')); ?>',
        cancelButtonText: '<?php echo esc_js(__('Cancel', 'vendor-space')); ?>'
    });

    if (!result.isConfirmed) return;

    if (deleteSelectedBtn) deleteSelectedBtn.disabled = true;

    const failures = [];
    let successCount = 0;

    for (const row of rows) {
        const orderId = row.getAttribute('data-order-id') || '';
        if (!orderId) {
            failures.push(orderId);
            continue;
        }

        const formData = new URLSearchParams();
        formData.set('action', 'vs_delete_order');
        formData.set('security', ordersSecurity);
        formData.set('order_id', orderId);

        try {
            const response = await fetch(ordersAjaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                body: formData.toString()
            });

            const data = await response.json();

            if (data && data.success) {
                removeOrderRow(row);
                successCount++;
            } else {
                failures.push(orderId);
            }
        } catch (e) {
            failures.push(orderId);
        }
    }

    if (deleteSelectedBtn) deleteSelectedBtn.disabled = false;

    // 🔥 result notification
    if (failures.length > 0) {
        Swal.fire({
            icon: 'warning',
            title: '<?php echo esc_js(__('Completed with errors', 'vendor-space')); ?>',
            text: `${successCount} <?php echo esc_js(__('deleted successfully,', 'vendor-space')); ?> ${failures.length} <?php echo esc_js(__('failed.', 'vendor-space')); ?>`
        });
    } else {
        Swal.fire({
            icon: 'success',
            title: '<?php echo esc_js(__('Deleted!', 'vendor-space')); ?>',
            text: `${successCount} <?php echo esc_js(__('order(s) deleted successfully.', 'vendor-space')); ?>`
        });
    }
}
            if (selectAllOrders) {
                selectAllOrders.addEventListener('change', function() {
                    setAllSelections(this.checked);
                });
            }

            if (toggleSelectBtn) {
                toggleSelectBtn.addEventListener('click', function() {
                    const rows = getOrderRows();
                    if (!rows.length) return;
                    const allSelected = rows.every(row => {
                        const checkbox = row.querySelector('.vs-order-select');
                        return checkbox && checkbox.checked;
                    });
                    setAllSelections(!allSelected);
                });
            }

            document.addEventListener('change', function(e) {
                if (e.target && e.target.classList.contains('vs-order-select')) {
                    syncSelectAllState();
                }
            });

            if (exportOrdersBtn) {
                exportOrdersBtn.addEventListener('click', function() {
                    exportOrdersToCsv(getRowsForBulkAction());
                });
            }

            if (deleteSelectedBtn) {
                deleteSelectedBtn.addEventListener('click', function() {
                    deleteOrders(getSelectedRows());
                });
            }

            document.addEventListener('click', function(e) {
                const btn = e.target.closest('.vs-delete-order');
                if (!btn) return;
                e.preventDefault();
                const row = btn.closest('tr');
                if (!row) return;
                deleteOrders([row]);
            });

            syncSelectAllState();
            
            document.querySelectorAll('.vs-view-order').forEach(btn => {
                btn.addEventListener('click', function(){
                    const raw = this.getAttribute('data-order-json') || '[]';
                    let data = [];
                    try { data = JSON.parse(raw); } catch(e) { data = []; }

                    const row = this.closest('tr');
                    const orderNumber = this.getAttribute('data-order-number') || (row ? (row.getAttribute('data-order-number') || '') : '');
                    const orderDate = row ? (row.getAttribute('data-order-date') || row.getAttribute('data-date') || '') : '';
                    const customerName = row ? (row.getAttribute('data-customer-name') || '') : '';
                    const customerEmail = row ? (row.getAttribute('data-customer-email') || '') : '';
                    const paymentMethod = row ? (row.getAttribute('data-payment-method') || '') : '';
                    const billingName = row ? (row.getAttribute('data-billing-name') || '') : '';
                    const billingAddress = row ? (row.getAttribute('data-billing-address') || '') : '';
                    const billingCity = row ? (row.getAttribute('data-billing-city') || '') : '';
                    const billingZip = row ? (row.getAttribute('data-billing-zip') || '') : '';
                    const billingCountry = row ? (row.getAttribute('data-billing-country') || '') : '';
                    const billingPhone = row ? (row.getAttribute('data-billing-phone') || '') : '';
                    const orderTotal = row ? (row.getAttribute('data-order-total') || row.getAttribute('data-vendor-total') || '0') : '0';
                    titleEl.textContent = orderNumber ? ('<?php echo esc_js(__('Order #', 'vendor-space')); ?>' + orderNumber + ' <?php echo esc_js(__('details', 'vendor-space')); ?>') : '<?php echo esc_js(__('Order Details', 'vendor-space')); ?>';

                    const currency = (data[0] && data[0].currency) ? data[0].currency : '';
                    const esc = (value) => String(value == null ? '' : value)
                        .replace(/&/g, '&amp;')
                        .replace(/</g, '&lt;')
                        .replace(/>/g, '&gt;')
                        .replace(/"/g, '&quot;')
                        .replace(/'/g, '&#39;');
                    const money = (value) => {
                        const n = Number(value || 0);
                        try {
                            return new Intl.NumberFormat(undefined, { style: 'currency', currency: currency || 'USD' }).format(n);
                        } catch(_) {
                            return (Math.round(n * 100) / 100).toFixed(2);
                        }
                    };

                    let html = '<div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(160px, 1fr)); gap:12px; margin-bottom:16px;">';
                    html += '<div style="padding:12px; border:1px solid #e2e8f0; border-radius:10px; background:#f8fafc;"><div style="font-size:11px; text-transform:uppercase; color:#64748b; font-weight:700; margin-bottom:4px;"><?php echo esc_js(__('Order', 'vendor-space')); ?></div><div style="font-weight:700; color:#0f172a;">#'+esc(orderNumber)+'</div><div style="margin-top:4px; color:#475569;">'+esc(orderDate)+'</div></div>';
                    html += '<div style="padding:12px; border:1px solid #e2e8f0; border-radius:10px; background:#f8fafc;"><div style="font-size:11px; text-transform:uppercase; color:#64748b; font-weight:700; margin-bottom:4px;"><?php echo esc_js(__('Customer', 'vendor-space')); ?></div><div style="font-weight:700; color:#0f172a;">'+esc(customerName)+'</div><div style="margin-top:4px; color:#475569;">'+esc(customerEmail)+'</div></div>';
                    html += '<div style="padding:12px; border:1px solid #e2e8f0; border-radius:10px; background:#f8fafc;"><div style="font-size:11px; text-transform:uppercase; color:#64748b; font-weight:700; margin-bottom:4px;"><?php echo esc_js(__('Payment', 'vendor-space')); ?></div><div style="font-weight:700; color:#0f172a;">'+esc(paymentMethod || '<?php echo esc_js(__('N/A', 'vendor-space')); ?>')+'</div><div style="margin-top:4px; color:#475569;">'+esc(money(orderTotal))+'</div></div>';
                    html += '</div>';

                    html += '<div style="margin-bottom:16px; padding:14px; border:1px solid #e2e8f0; border-radius:10px; background:#fff;"><div style="font-size:12px; text-transform:uppercase; color:#64748b; font-weight:700; margin-bottom:8px;"><?php echo esc_js(__('Billing Address', 'vendor-space')); ?></div>';
                    html += '<div style="line-height:1.6; color:#0f172a;">'
                        + (billingName ? '<div>'+esc(billingName)+'</div>' : '')
                        + (billingAddress ? '<div>'+esc(billingAddress)+'</div>' : '')
                        + ((billingCity || billingZip) ? '<div>'+esc([billingCity, billingZip].filter(Boolean).join(' '))+'</div>' : '')
                        + (billingCountry ? '<div>'+esc(billingCountry)+'</div>' : '')
                        + (billingPhone ? '<div>'+esc(billingPhone)+'</div>' : '')
                        + '</div></div>';

                    html += '<table style="width:100%; text-align:left; border-collapse:collapse;">';
                    html += '<thead><tr style="border-bottom:1px solid #eee;"><th style="padding:10px 0;"><?php echo esc_js(__('Item', 'vendor-space')); ?></th><th style="padding:10px 0; width:80px;"><?php echo esc_js(__('Qty', 'vendor-space')); ?></th><th style="padding:10px 0; width:140px;"><?php echo esc_js(__('Total', 'vendor-space')); ?></th></tr></thead><tbody>';
                    
                    data.forEach(item => {
                        html += `<tr style="border-bottom:1px solid #eee;">
                            <td style="padding:10px 0; display:flex; align-items:center; gap:10px;">
                                ${item.image ? `<img src="${item.image}" width="40" height="40" style="border-radius:4px;">` : ''}
                                <span>${item.name}</span>
                            </td>
                            <td>${item.qty}</td>
                            <td>${money(item.total)}</td>
                        </tr>`;
                    });
                    
                    html += `<tr style="border-top:2px solid #e2e8f0; font-weight:700;">
                        <td style="padding:12px 0;"><?php echo esc_js(__('Order Total', 'vendor-space')); ?></td>
                        <td></td>
                        <td>${money(orderTotal)}</td>
                    </tr>`;
                    html += '</tbody></table>';
                    content.innerHTML = html;
                    modal.style.display = 'flex';
                });
            });

            document.querySelectorAll('.vs-print-order').forEach(btn => {
                btn.addEventListener('click', function(){
                    const row = this.closest('tr');
                    if(!row) return;

                    const raw = row.getAttribute('data-order-items') || '[]';
                    let data = [];
                    try { data = JSON.parse(raw); } catch(e) { data = []; }
                    
                    const orderNumber = row.getAttribute('data-order-number') || '';
                    const customerName = row.getAttribute('data-customer-name') || '';
                    const customerEmail = row.getAttribute('data-customer-email') || '';
                    const paymentMethod = row.getAttribute('data-payment-method') || '';
                    const billingName = row.getAttribute('data-billing-name') || '';
                    const billingAddress = row.getAttribute('data-billing-address') || '';
                    const billingCity = row.getAttribute('data-billing-city') || '';
                    const billingZip = row.getAttribute('data-billing-zip') || '';
                    const billingCountry = row.getAttribute('data-billing-country') || '';
                    const billingPhone = row.getAttribute('data-billing-phone') || '';
                    const date = row.getAttribute('data-order-date') || row.getAttribute('data-date') || '';
                    const totalRaw = row.getAttribute('data-order-total') || row.getAttribute('data-vendor-total') || '0';
                    const currency = (data[0] && data[0].currency) ? data[0].currency : '$';
                    const esc = (value) => {
                        return String(value == null ? '' : value)
                            .replace(/&/g, '&amp;')
                            .replace(/</g, '&lt;')
                            .replace(/>/g, '&gt;')
                            .replace(/"/g, '&quot;')
                            .replace(/'/g, '&#39;');
                    };
                    
                    const money = (val) => {
                        const n = Number(val || 0);
                        try {
                            return new Intl.NumberFormat(undefined, { style: 'currency', currency: currency }).format(n);
                        } catch(_) {
                            return currency + ' ' + (Math.round(n * 100) / 100).toFixed(2);
                        }
                    };

                    const printWindow = window.open('', '_blank', 'width=800,height=600');
                    if(!printWindow) {
                        alert('<?php echo esc_js(__('Please allow pop-ups to print.', 'vendor-space')); ?>');
                        return;
                    }

                    const billingLines = [
                        billingName,
                        billingAddress,
                        [billingCity, billingZip].filter(Boolean).join(' '),
                        billingCountry,
                        billingPhone
                    ].filter(Boolean);

                    let html = '<html><head><title><?php echo esc_js(__('Order #', 'vendor-space')); ?>'+esc(orderNumber)+'</title><style>body { font-family: Arial, sans-serif; padding: 28px; color: #111827; font-size: 13px; line-height: 1.45; } h1 { margin: 0 0 10px; font-size: 34px; font-weight: 500; color: #111827; } .lead { margin: 0 0 18px; color: #111827; } .meta-grid { width: 100%; border-collapse: collapse; margin-bottom: 18px; } .meta-grid td { padding: 0 18px 0 0; vertical-align: top; } .meta-label { display: block; font-size: 10px; font-weight: 700; color: #111827; margin-bottom: 4px; } .meta-value { color: #111827; } .section-title { font-size: 15px; font-weight: 500; margin: 24px 0 10px; color: #111827; } .card { background: #f5f5f5; padding: 18px; margin: 18px 0 24px; } .card p { margin: 0 0 12px; } .chat-btn { display: inline-block; background: #2563eb; color: #fff; padding: 6px 12px; font-size: 11px; text-decoration: none; border-radius: 0; } table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid #d1d5db; padding: 8px 10px; text-align: left; vertical-align: top; } th { background: #fff; font-size: 11px; font-weight: 700; } .text-right { text-align: right; } .billing-box { border: 1px solid #d1d5db; padding: 14px; min-height: 110px; } .additional-table td { border: 1px solid #d1d5db; } .close-btn { margin-top: 20px; padding: 10px 20px; cursor: pointer; } @media print { .no-print { display: none !important; } body { padding: 0; } }</style></head><body>';

                    html += '<h1><?php echo esc_js(__('Order received', 'vendor-space')); ?></h1>';
                    html += '<p class="lead"><?php echo esc_js(__('Thank you. Your order has been received.', 'vendor-space')); ?></p>';
                    html += '<table class="meta-grid"><tr>'
                        + '<td><span class="meta-label"><?php echo esc_js(__('Order number:', 'vendor-space')); ?></span><span class="meta-value">'+esc(orderNumber)+'</span></td>'
                        + '<td><span class="meta-label"><?php echo esc_js(__('Date:', 'vendor-space')); ?></span><span class="meta-value">'+esc(date)+'</span></td>'
                        + '<td><span class="meta-label"><?php echo esc_js(__('Total:', 'vendor-space')); ?></span><span class="meta-value">'+esc(money(totalRaw))+'</span></td>'
                        + '<td><span class="meta-label"><?php echo esc_js(__('Email:', 'vendor-space')); ?></span><span class="meta-value">'+esc(customerEmail)+'</span></td>'
                        + '<td><span class="meta-label"><?php echo esc_js(__('Payment:', 'vendor-space')); ?></span><span class="meta-value">'+esc(paymentMethod)+'</span></td>'
                        + '</tr></table>';

                    html += '<div class="section-title"><?php echo esc_js(__('Order details', 'vendor-space')); ?></div>';
                    html += '<table><thead><tr><th><?php echo esc_js(__('Product', 'vendor-space')); ?></th><th style="width:120px;" class="text-right"><?php echo esc_js(__('Total', 'vendor-space')); ?></th></tr></thead><tbody>';
                    
                    data.forEach(item => {
                        const productImage = item.image
                            ? '<img src="'+esc(item.image)+'" alt="" style="width:42px; height:42px; object-fit:cover; border:1px solid #d1d5db; margin-right:10px; vertical-align:middle;">'
                            : '';
                        html += '<tr><td>'+productImage+'<span style="vertical-align:middle;">'+esc(item.name)+' &times; '+esc(item.qty)+'</span></td><td class="text-right">'+esc(money(item.total))+'</td></tr>';
                    });

                    html += '<tr><td><strong><?php echo esc_js(__('Total:', 'vendor-space')); ?></strong></td><td class="text-right">'+esc(money(totalRaw))+'</td></tr></tbody></table>';

                    html += '<div class="section-title"><?php echo esc_js(__('Billing address', 'vendor-space')); ?></div>';
                    html += '<div class="billing-box">'+ billingLines.map(line => '<div>'+esc(line)+'</div>').join('') +'</div>';

                    html += '<div class="section-title"><?php echo esc_js(__('Additional information', 'vendor-space')); ?></div>';
                    html += '<table class="additional-table"><tbody><tr><td><?php echo esc_js(__('Subscribe to our newsletter', 'vendor-space')); ?></td><td class="text-right"><?php echo esc_js(__('No', 'vendor-space')); ?></td></tr></tbody></table>';

                    html += '<button onclick="window.close()" class="close-btn no-print"><?php echo esc_js(__('Close', 'vendor-space')); ?></button>';

                    html += '<script>window.onload = function() { window.print(); };<\/script></body></html>';
                    
                    printWindow.document.write(html);
                    printWindow.document.close();
                });
            });

            document.getElementById('vs-close-modal').addEventListener('click', function(){
                modal.style.display = 'none';
            });

            if (closeX) {
                closeX.addEventListener('click', function(){
                    modal.style.display = 'none';
                });
            }
            
            modal.addEventListener('click', function(e){
                if(e.target === modal) modal.style.display = 'none';
            });

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

                    function esc(v) {
                        return $('<div/>').text(v == null ? '' : String(v)).html();
                    }

                    function setError(message) {
                        $feedback.text(message || 'Request failed.').show();
                    }

                    function clearError() {
                        $feedback.hide().text('');
                    }

                    function stopPoll() {
                        if (poll) {
                            clearInterval(poll);
                            poll = null;
                        }
                    }

                    function renderMessages(items) {
                        if (!Array.isArray(items) || !items.length) {
                            $messages.html('<div style="text-align:center; color:#999; margin-top:20px;"><?php echo esc_js(__('No messages yet. Start the conversation!', 'vendor-space')); ?></div>');
                            return;
                        }

                        let html = '';
                        items.forEach(function (m) {
                            const mine = (Number(thread.vendor_id) === currentUserId) ? !!m.is_vendor : !m.is_vendor;
                            const align = mine ? 'flex-end' : 'flex-start';
                            const bg = mine ? '#10b981' : '#e5e7eb';
                            const color = mine ? '#fff' : '#1f2937';
                            html += '<div style="display:flex; flex-direction:column; align-items:' + align + '; margin-bottom:10px;">';
                            if (m.message) {
                                html += '<div style="background:' + bg + '; color:' + color + '; padding:8px 12px; border-radius:12px; max-width:84%; word-wrap:break-word;">' + 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:#999; 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 loadMessages() {
                        if (!thread.product_id || !thread.vendor_id || !thread.customer_id) 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);
                                } else {
                                    setError('<?php echo esc_js(__('Failed to load messages.', 'vendor-space')); ?>');
                                }
                            },
                            error: function () {
                                setError('<?php echo esc_js(__('Connection failed. Please try again.', 'vendor-space')); ?>');
                            }
                        });
                    }

                    function openModal(data) {
                        thread = {
                            product_id: Number(data.product_id || 0),
                            vendor_id: Number(data.vendor_id || 0),
                            customer_id: Number(data.customer_id || 0)
                        };
                        if (!thread.product_id || !thread.vendor_id || !thread.customer_id) {
                            return;
                        }

                        clearError();
                        $name.text(data.counterpart_name || '');
                        $messages.html('<div style="text-align:center; color:#999; margin-top:20px;"><?php echo esc_js(__('Loading messages...', 'vendor-space')); ?></div>');
                        $form.find('textarea[name="message"]').val('');
                        $form.find('input[name="image"]').val('');
                        $chatModal.css('display', 'flex');
                        loadMessages();
                        stopPoll();
                        poll = setInterval(loadMessages, 5000);
                    }

                    function closeModal() {
                        stopPoll();
                        $chatModal.hide();
                    }

                    $(document).on('click', '.vs-orders-thread-open', function () {
                        openModal({
                            product_id: $(this).data('product-id'),
                            vendor_id: $(this).data('vendor-id'),
                            customer_id: $(this).data('customer-id'),
                            counterpart_name: $(this).data('counterpart-name')
                        });
                    });

                    $chatModal.on('click', '.vs-orders-thread-close', closeModal);
                    $chatModal.on('click', function (e) {
                        if (e.target === this) {
                            closeModal();
                        }
                    });

                    $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', String(thread.product_id || 0));
                        fd.append('vendor_id', String(thread.vendor_id || 0));
                        fd.append('customer_id', String(thread.customer_id || 0));
                        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();
                                } else {
                                    const m = (res && res.data && res.data.message) ? res.data.message : '<?php echo esc_js(__('Failed to send message.', 'vendor-space')); ?>';
                                    setError(m);
                                }
                            },
                            error: function () {
                                $form.find('button[type="submit"]').prop('disabled', false);
                                setError('<?php echo esc_js(__('Connection failed. Please try again.', 'vendor-space')); ?>');
                            }
                        });
                    });
                }

                $(document).on('click', '.vs-admin-message-vendor-btn', function(e){
                    e.preventDefault();
                    const customerId = $(this).data('id');
                    const customerName = $(this).data('display-name');
                    
                    if (!customerId || customerId === '0') {
                        if (typeof Swal !== 'undefined') {
                            Swal.fire({
                                icon: 'info',
                                title: '<?php echo esc_js(__('Note', 'vendor-space')); ?>',
                                text: '<?php echo esc_js(__('Cannot message a guest customer.', 'vendor-space')); ?>'
                            });
                        } else {
                            alert('<?php echo esc_js(__('Cannot message a guest customer.', 'vendor-space')); ?>');
                        }
                        return;
                    }
                    
                    const $msgTabLink = $('.vs-tab-link[data-tab="notifications"]');
                    if ($msgTabLink.length) {
                        $msgTabLink.trigger('click');
                        
                        // Wait for tab to switch then load thread
                        setTimeout(() => {
                            if (window.vsLoadChatThread) {
                                window.vsLoadChatThread(customerId, customerName);
                            } else {
                                // Fallback if VS_Pro_LiveChat JS isn't initialized yet
                                console.warn('vsLoadChatThread not found');
                            }
                        }, 300);
                    }
                });
            }
        });
        </script>
        <?php
    }
}
