jQuery(document).ready(function($) {

window.BizOrders = {
    page: 1,
    perPage: 25,
    sortField: 'date_created',
    sortDir: 'desc',
    searchTimer: null,
    trendChart: null,
    methodChart: null,
    cachedData: null,
    selectedIds: new Set(),
    activeStatus: '',
    panelOrderId: null,
    pendingInitialOrderId: parseInt(BizOrdersConfig.initialOrderId || 0, 10) || 0,

    // --- Helpers ---
    t(en, fr, ar) { const l = BizOrdersConfig.lang; return l === 'ar' ? (ar || en) : l === 'fr' ? (fr || en) : en; },
    parseDate(str) {
        if (!str) return null;
        let d = new Date(str.replace(' ', 'T'));
        if (isNaN(d.getTime())) {
            d = new Date(str.replace(/-/g, '/'));
        }
        return isNaN(d.getTime()) ? null : d;
    },
    fmt(n) { return parseFloat(n||0).toLocaleString('fr-FR', {minimumFractionDigits:2, maximumFractionDigits:2}); },
    fmtCur(n) { return this.fmt(n) + ' ' + BizOrdersConfig.currency; },
    escHtml(s) { if (!s) return ''; const d=document.createElement('div'); d.textContent=s; return d.innerHTML; },
    ajaxError(xhr, fallback = 'Network error') {
        const payload = xhr && xhr.responseJSON ? xhr.responseJSON.data : null;
        if (payload && typeof payload.message === 'string' && payload.message) return payload.message;
        if (typeof payload === 'string' && payload) return payload;
        return fallback;
    },

    syncOrderUrl(orderId) {
        if (!(window.history && typeof window.history.replaceState === 'function')) return;
        const url = new URL(window.location.href);
        if (orderId && orderId > 0) {
            url.searchParams.set('order_id', String(orderId));
        } else {
            url.searchParams.delete('order_id');
        }
        window.history.replaceState({}, '', url.toString());
    },

    statusInfo(key) {
        return BizOrdersConfig.statuses[key] || { label: key, color:'#6b7280', bg:'#f9fafb', icon:'📋' };
    },

    statusBadgeHtml(status) {
        const s = this.statusInfo(status);
        return `<span class="biz-status-badge" style="background:${s.bg}; color:${s.color};">${s.icon} ${s.label}</span>`;
    },

    validNextStatuses(current) {
        const map = {
            'pending':    ['processing','on-hold','cancelled'],
            'processing': ['completed','on-hold','cancelled','refunded'],
            'on-hold':    ['processing','completed','cancelled'],
            'completed':  ['processing','refunded'],
            'cancelled':  ['processing','pending'],
            'refunded':   [],
            'failed':     ['processing','pending','cancelled'],
        };
        return map[current] || ['processing','completed','cancelled'];
    },

    // --- Data Fetch ---
    fetch() {
        const params = {
            action: 'bizmart_get_orders',
            nonce: BizOrdersConfig.nonce,
            page: this.page,
            per_page: this.perPage,
            status: this.activeStatus || '',
            search: $('#ord-search').val(),
            payment_method: $('#ord-filter-method').val(),
            start_date: $('#ord-filter-from').val(),
            end_date: $('#ord-filter-to').val(),
            orderby: this.sortField === 'number' ? 'ID' : this.sortField === 'total' ? 'total' : 'date',
            order: this.sortDir.toUpperCase(),
        };
        $('#ord-tbody').html('<tr><td colspan="10" class="biz-ord-loading"><div class="spin"></div></td></tr>');

        $.post(BizOrdersConfig.ajaxUrl, params, (res) => {
            if (!res.success) { this.showError(res.data||'Error'); return; }
            this.cachedData = res.data;
            this.renderStats(res.data);
            this.renderStatusStrip(res.data.status_counts);
            this.renderTable(res.data.orders);
            this.renderPagination(res.data);
            this.renderCharts(res.data);
            this.populateGatewayFilter(res.data.gateways);
            this.selectedIds.clear();
            this.updateBulkBar();
            if (this.pendingInitialOrderId > 0) {
                const initialOrderId = this.pendingInitialOrderId;
                this.pendingInitialOrderId = 0;
                this.openDetail(initialOrderId);
            }
        }).fail((xhr) => this.showError(this.ajaxError(xhr)));
    },

    debounceSearch() { clearTimeout(this.searchTimer); this.searchTimer = setTimeout(() => { this.page=1; this.fetch(); }, 350); },
    clearFilters() { $('#ord-search').val(''); $('#ord-filter-status').val(''); $('#ord-filter-method').val(''); $('#ord-filter-from').val(''); $('#ord-filter-to').val(''); this.activeStatus=''; this.page=1; this.fetch(); },

    filterByStatus(status) {
        this.activeStatus = status;
        $('#ord-filter-status').val(status);
        // Update strip active state
        document.querySelectorAll('.biz-ord-status-chip, .biz-ord-status-chip-all').forEach(el => el.classList.remove('active'));
        if (!status) {
            document.querySelector('.biz-ord-status-chip-all').classList.add('active');
        } else {
            const chip = document.querySelector(`.biz-ord-status-chip[data-status="${status}"]`);
            if (chip) chip.classList.add('active');
        }
        this.page = 1;
        this.fetch();
    },

    // --- Rendering ---
    renderStats(d) {
        const s = d.stats;
        $('#stat-sales').text(this.fmtCur(s.total_sales));
        $('#stat-orders-count').text(s.total_orders + ' ' + this.t('completed orders','commandes terminées','طلبات مكتملة'));

        // Gains card
        $('#stat-gains').text(this.fmtCur(s.total_gains));
        $('#stat-month-gains').text(this.t('This month','Ce mois','هذا الشهر') + ': ' + this.fmtCur(s.this_month_gains || 0));

        $('#stat-month').text(this.fmtCur(s.this_month));

        let cmp = '';
        if (s.last_month > 0) {
            const diff = ((s.this_month - s.last_month) / s.last_month * 100);
            const arrow = diff >= 0 ? '↑' : '↓';
            cmp = arrow + ' ' + Math.abs(diff).toFixed(1) + '% ' + this.t('vs last month','vs mois dernier','مقارنة بالشهر السابق');
        } else {
            cmp = this.t('No data last month','Aucune donnée mois dernier','لا بيانات الشهر الماضي');
        }
        $('#stat-month-cmp').text(cmp);

        $('#stat-avg').text(this.fmtCur(s.avg_order));
        $('#stat-pending').text(s.pending_count);
        $('#stat-today').text(s.today_count + ' ' + this.t('today','aujourd\'hui','اليوم') + ' (' + this.fmtCur(s.today_sales) + ')');
    },

    renderStatusStrip(counts) {
        if (!counts) return;
        let totalAll = 0;
        counts.forEach(c => totalAll += c.count);
        $('#strip-all-count').text(totalAll);

        // Build status chips
        let html = '';
        counts.forEach(c => {
            const si = this.statusInfo(c.status);
            if (c.count === 0) return; // hide empty statuses
            html += `<div class="biz-ord-status-chip${this.activeStatus===c.status?' active':''}" data-status="${c.status}" onclick="BizOrders.filterByStatus('${c.status}')" style="background:${si.bg}; color:${si.color};">
                ${si.icon} ${si.label} <span class="chip-count">${c.count}</span>
            </div>`;
        });

        // Insert after the All chip
        const strip = document.getElementById('status-strip');
        // Remove old chips except all
        strip.querySelectorAll('.biz-ord-status-chip').forEach(el => el.remove());
        $(strip).append(html);

        // Update All active
        if (!this.activeStatus) {
            strip.querySelector('.biz-ord-status-chip-all').classList.add('active');
        } else {
            strip.querySelector('.biz-ord-status-chip-all').classList.remove('active');
        }
    },

    renderTable(orders) {
        if (!orders || orders.length === 0) {
            $('#ord-tbody').html(`<tr><td colspan="10" class="biz-ord-empty">
                <div class="empty-ico">📦</div>
                <p style="font-size:15px; margin:0;">${this.t('No orders found','Aucune commande trouvée','لم يتم العثور على طلبات')}</p>
                <p style="font-size:12px; margin:6px 0 0; color:#94a3b8;">${this.t('Try adjusting your filters','Essayez de modifier vos filtres','حاول تعديل الفلاتر')}</p>
            </td></tr>`);
            return;
        }

        let html = '';
        orders.forEach(o => {
            const dt = this.parseDate(o.date_created);
            const dateFmt = dt ? dt.toLocaleDateString('fr-FR', {day:'2-digit', month:'short', year:'numeric'}) : '—';
            const timeFmt = dt ? dt.toLocaleTimeString('fr-FR', {hour:'2-digit', minute:'2-digit'}) : '';
            const checked = this.selectedIds.has(o.id) ? 'checked' : '';
            const nextStatuses = this.validNextStatuses(o.status);
            let ddItems = '';
            nextStatuses.forEach(ns => {
                const nsi = this.statusInfo(ns);
                ddItems += `<div class="dd-item" onclick="BizOrders.changeStatus(${o.id},'${ns}'); event.stopPropagation();">${nsi.icon} ${nsi.label}</div>`;
            });
            const payBadge = o.payment_title
                ? `<span class="biz-ord-pay-badge">${this.escHtml(o.payment_title)}</span>`
                : '<span style="color:#cbd5e1;">—</span>';

            html += `<tr>
                <td><input type="checkbox" class="biz-ord-cb ord-row-cb" value="${o.id}" ${checked} onchange="BizOrders.onRowCheck(${o.id}, this.checked)"></td>
                <td class="td-num" onclick="BizOrders.openDetail(${o.id})">#${this.escHtml(o.number)}</td>
                <td>
                    <div style="font-weight:600; color:#1e293b;">${dateFmt}</div>
                    <div style="font-size:10px; color:#94a3b8;">${timeFmt}</div>
                </td>
                <td class="td-customer">
                    <span class="cname" title="${this.escHtml(o.billing_email)}">${this.escHtml(o.billing_name || this.t('Guest','Invité','زائر'))}</span>
                    <span class="cemail">${this.escHtml(o.billing_email || '')}</span>
                </td>
                <td class="td-items">
                    <span class="icount">${o.item_count} ${this.t('items','articles','عنصر')}</span>
                    <span class="ipreview" title="${this.escHtml(o.item_preview)}">${this.escHtml(o.item_preview)}</span>
                </td>
                <td class="td-total" style="color:#059669;">${this.fmtCur(o.total)}</td>
                <td style="text-align:right; font-weight:600; color:${parseFloat(o.gains||0) >= 0 ? '#059669' : '#ef4444'};">${this.fmtCur(o.gains||0)}</td>
                <td>${payBadge}</td>
                <td>
                    <div class="biz-status-dd" id="sdd-${o.id}">
                        <div class="dd-trigger" onclick="BizOrders.toggleStatusDD(${o.id})">${this.statusBadgeHtml(o.status)}</div>
                        <div class="dd-menu" id="ddm-${o.id}">${ddItems.length ? ddItems : '<div class="dd-item" style="color:#94a3b8; cursor:default;">'+this.t('No transitions','Aucune transition','لا تحويلات')+'</div>'}</div>
                    </div>
                </td>
                <td style="text-align:center; white-space:nowrap;">
                    <button class="biz-ord-act" onclick="BizOrders.openDetail(${o.id})" title="${this.t('View','Voir','عرض')}">👁️</button>
                    <button class="biz-ord-act danger" onclick="BizOrders.trashOrder(${o.id})" title="${this.t('Trash','Supprimer','حذف')}">🗑️</button>
                </td>
            </tr>`;
        });
        $('#ord-tbody').html(html);
    },

    renderPagination(d) {
        const total = parseInt(d.total)||0;
        const totalPages = parseInt(d.total_pages)||1;
        const page = parseInt(d.page)||1;
        const from = total > 0 ? ((page-1)*this.perPage+1) : 0;
        const to = Math.min(page*this.perPage, total);
        $('#ord-pg-info').html(`${this.t('Showing','Affichage','عرض')} <b>${from}–${to}</b> ${this.t('of','sur','من')} <b>${total}</b> ${this.t('orders','commandes','طلبات')}`);

        if (totalPages <= 1) { $('#ord-pg-btns').html(''); return; }
        let btns = '';
        if (page > 1) btns += `<button class="pg-btn" onclick="BizOrders.goPage(${page-1})">«</button>`;
        const start = Math.max(1, page-2), end = Math.min(totalPages, page+2);
        if (start > 1) btns += `<button class="pg-btn" onclick="BizOrders.goPage(1)">1</button>`;
        if (start > 2) btns += `<span style="color:#94a3b8; padding:0 4px;">…</span>`;
        for (let i = start; i <= end; i++) btns += `<button class="pg-btn ${i===page?'active':''}" onclick="BizOrders.goPage(${i})">${i}</button>`;
        if (end < totalPages-1) btns += `<span style="color:#94a3b8; padding:0 4px;">…</span>`;
        if (end < totalPages) btns += `<button class="pg-btn" onclick="BizOrders.goPage(${totalPages})">${totalPages}</button>`;
        if (page < totalPages) btns += `<button class="pg-btn" onclick="BizOrders.goPage(${page+1})">»</button>`;
        $('#ord-pg-btns').html(btns);
    },

    // --- Charts ---
    renderCharts(d) {
        try {
            this.renderTrendChart(d.daily_trend || []);
        } catch (e) {
            console.error('Bizmart Trend Chart Error:', e);
        }
        try {
            this.renderMethodDonut(d.payment_methods || []);
        } catch (e) {
            console.error('Bizmart Method Donut Chart Error:', e);
        }
    },

    renderTrendChart(data) {
        const ctx = document.getElementById('ord-trend-chart');
        if (!ctx) return;
        const parent = $(ctx).parent();
        parent.find('.biz-chart-placeholder').remove();
        if (this.trendChart) {
            try {
                this.trendChart.destroy();
            } catch (e) {
                console.warn('Error destroying trendChart:', e);
            }
        }
        if (!data || data.length === 0) {
            $(ctx).hide();
            parent.append(`<div class="biz-chart-placeholder" style="position:absolute; inset:0; display:flex; flex-direction:column; align-items:center; justify-content:center; color:#94a3b8; font-size:13px; font-weight:500;">
                <div style="font-size:28px; margin-bottom:6px;">📈</div>
                <div>${this.t('No sales data yet', 'Aucune donnée de vente', 'لا توجد بيانات مبيعات بعد')}</div>
            </div>`);
            return;
        }
        $(ctx).show();

        const labels = data.map(r => {
            if (!r.day) return '';
            const parts = r.day.split('-');
            if (parts.length < 3) return r.day;
            const dt = new Date(parseInt(parts[0], 10), parseInt(parts[1], 10) - 1, parseInt(parts[2], 10));
            if (isNaN(dt.getTime())) return r.day;
            return dt.toLocaleDateString('fr-FR', {day: '2-digit', month: 'short'});
        });
        const totals = data.map(r => parseFloat(r.total) || 0);
        const counts = data.map(r => parseInt(r.count) || 0);

        try {
            this.trendChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels,
                    datasets: [
                        { label: this.t('Sales','Ventes','المبيعات'), data: totals, backgroundColor: 'rgba(59,130,246,0.7)', borderRadius: 5, maxBarThickness: 18, yAxisID: 'y' },
                        { label: this.t('Orders','Commandes','الطلبات'), data: counts, type: 'line', borderColor: '#f59e0b', backgroundColor: 'rgba(245,158,11,0.1)', pointRadius: 2, borderWidth: 2, tension: 0.4, yAxisID: 'y1' }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { position: 'top', labels: { font: {size: 11}, usePointStyle: true, pointStyleWidth: 8, padding: 12 } },
                        tooltip: { callbacks: { label: (ctx) => ctx.dataset.yAxisID === 'y' ? this.fmtCur(ctx.raw) : ctx.raw + ' ' + this.t('orders','commandes','طلبات') } }
                    },
                    scales: {
                        x: { grid: {display: false}, ticks: {font: {size: 9}, maxRotation: 45} },
                        y: { beginAtZero: true, position: 'left', grid: {color: '#f1f5f9'}, ticks: {font: {size: 10}, callback: v => this.fmt(v)} },
                        y1: { beginAtZero: true, position: 'right', grid: {display: false}, ticks: {font: {size: 10}, stepSize: 1} }
                    }
                }
            });
        } catch (err) {
            console.error('Error instantiating trend Chart:', err);
        }
    },

    renderMethodDonut(stats) {
        const ctx = document.getElementById('ord-method-chart');
        if (!ctx) return;
        const parent = $(ctx).parent();
        parent.find('.biz-chart-placeholder').remove();
        if (this.methodChart) {
            try {
                this.methodChart.destroy();
            } catch (e) {
                console.warn('Error destroying methodChart:', e);
            }
        }
        if (!stats || stats.length === 0) {
            $(ctx).hide();
            parent.append(`<div class="biz-chart-placeholder" style="position:absolute; inset:0; display:flex; flex-direction:column; align-items:center; justify-content:center; color:#94a3b8; font-size:13px; font-weight:500;">
                <div style="font-size:28px; margin-bottom:6px;">💳</div>
                <div>${this.t('No payment methods recorded yet', 'Aucune méthode enregistrée', 'لا توجد طرق دفع مسجلة بعد')}</div>
            </div>`);
            return;
        }
        $(ctx).show();
        const colors = ['#3b82f6','#059669','#f59e0b','#8b5cf6','#ef4444','#ec4899','#6b7280'];
        try {
            this.methodChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: stats.map(s => s.label || s.method),
                    datasets: [{ data: stats.map(s => parseFloat(s.total) || 0), backgroundColor: colors.slice(0, stats.length), borderWidth: 2, borderColor: '#fff' }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '65%',
                    plugins: {
                        legend: { position: 'bottom', labels: {padding: 12, font: {size: 11}, usePointStyle: true, pointStyleWidth: 8} },
                        tooltip: { callbacks: { label: (ctx) => ctx.label + ': ' + this.fmtCur(ctx.raw) } }
                    }
                }
            });
        } catch (err) {
            console.error('Error instantiating method donut Chart:', err);
        }
    },

    // --- Populate gateway filter ---
    populateGatewayFilter(gateways) {
        if (!gateways) return;
        const sel = $('#ord-filter-method');
        const cur = sel.val();
        let html = `<option value="">${this.t('All Methods','Toutes Méthodes','كل الطرق')}</option>`;
        gateways.forEach(g => { html += `<option value="${g.id}">${this.escHtml(g.title)}</option>`; });
        sel.html(html).val(cur);
    },

    // --- Sorting ---
    sort(field) {
        if (this.sortField === field) { this.sortDir = this.sortDir === 'asc' ? 'desc' : 'asc'; }
        else { this.sortField = field; this.sortDir = field === 'total' ? 'desc' : 'asc'; }
        this.page = 1;
        this.fetch();
    },

    goPage(p) { this.page = p; this.fetch(); },

    // --- Status dropdown ---
    toggleStatusDD(orderId) {
        // Close all others
        document.querySelectorAll('.dd-menu.open').forEach(el => el.classList.remove('open'));
        const menu = document.getElementById('ddm-' + orderId);
        if (menu) menu.classList.toggle('open');
    },

    changeStatus(orderId, newStatus) {
        document.querySelectorAll('.dd-menu.open').forEach(el => el.classList.remove('open'));
        $.post(BizOrdersConfig.ajaxUrl, {
            action: 'bizmart_update_order_status',
            nonce: BizOrdersConfig.nonce,
            order_id: orderId,
            status: newStatus
        }, (res) => {
            if (res.success) {
                this.toast(this.t('Status updated','Statut mis à jour','تم تحديث الحالة'), 'success');
                this.fetch();
                if (this.panelOrderId === orderId) this.openDetail(orderId);
            } else {
                this.toast(res.data || 'Error', 'error');
            }
        }).fail((xhr) => this.toast(this.ajaxError(xhr), 'error'));
    },

    // --- Selection / Bulk ---
    onRowCheck(id, checked) {
        if (checked) this.selectedIds.add(id); else this.selectedIds.delete(id);
        this.updateBulkBar();
    },
    toggleSelectAll() {
        const cbs = document.querySelectorAll('.ord-row-cb');
        const allChecked = this.selectedIds.size > 0 && this.selectedIds.size === cbs.length;
        if (allChecked) {
            this.selectedIds.clear();
            cbs.forEach(cb => cb.checked = false);
        } else {
            cbs.forEach(cb => { cb.checked = true; this.selectedIds.add(parseInt(cb.value)); });
        }
        this.updateBulkBar();
    },
    updateBulkBar() {
        const n = this.selectedIds.size;
        const bar = document.getElementById('ord-bulk-bar');
        if (n > 0) {
            bar.classList.add('visible');
            $('#ord-bulk-count').text(n + ' ' + this.t('selected','sélectionnés','محدد'));
        } else {
            bar.classList.remove('visible');
        }
    },
    bulkAction() {
        const status = $('#ord-bulk-status').val();
        if (!status) { this.toast(this.t('Select a status','Choisissez un statut','اختر حالة'), 'error'); return; }
        const n = this.selectedIds.size;
        if (n === 0) return;

        const si = this.statusInfo(status);
        $('#bulk-modal-msg').html(this.t(
            `Change <b>${n}</b> orders to <b>${si.label}</b>?`,
            `Changer <b>${n}</b> commandes en <b>${si.label}</b> ?`,
            `تغيير <b>${n}</b> طلبات إلى <b>${si.label}</b>؟`
        ));
        $('#ord-bulk-modal').addClass('active');
        $('#bulk-modal-confirm').off('click').on('click', () => {
            $('#ord-bulk-modal').removeClass('active');
            $.post(BizOrdersConfig.ajaxUrl, {
                action: 'bizmart_bulk_update_orders',
                nonce: BizOrdersConfig.nonce,
                order_ids: Array.from(this.selectedIds),
                status: status
            }, (res) => {
                if (res.success) {
                    this.toast(this.t(`${res.data.updated} orders updated`, `${res.data.updated} commandes mises à jour`, `تم تحديث ${res.data.updated} طلبات`), 'success');
                    this.selectedIds.clear();
                    this.fetch();
                } else {
                    this.toast(res.data || 'Error', 'error');
                }
            });
        });
    },

    // --- Detail Panel ---
    openDetail(orderId) {
        this.panelOrderId = orderId;
        this.syncOrderUrl(orderId);
        $('#ord-panel-overlay').addClass('open');
        $('#ord-panel').addClass('open');
        $('#panel-body').html('<div class="biz-ord-loading"><div class="spin"></div></div>');
        $('#panel-footer').html('');

        $.post(BizOrdersConfig.ajaxUrl, {
            action: 'bizmart_get_order_details',
            nonce: BizOrdersConfig.nonce,
            order_id: orderId
        }, (res) => {
            if (!res.success) { $('#panel-body').html('<p style="color:#ef4444;">'+this.escHtml(res.data)+'</p>'); return; }
            this.renderPanel(res.data);
        }).fail((xhr) => { $('#panel-body').html('<p style="color:#ef4444;">'+this.escHtml(this.ajaxError(xhr))+'</p>'); });
    },

    closeDetail() {
        this.panelOrderId = null;
        this.syncOrderUrl(0);
        $('#ord-panel-overlay').removeClass('open');
        $('#ord-panel').removeClass('open');
    },

    renderPanel(o) {
        $('#panel-title').html(`#${this.escHtml(o.number)} &nbsp; ${this.statusBadgeHtml(o.status)}`);

        const dtObj = this.parseDate(o.date_created);
        const dt = dtObj ? dtObj.toLocaleDateString('fr-FR',{day:'2-digit',month:'long',year:'numeric',hour:'2-digit',minute:'2-digit'}) : '—';
        const dtPaidObj = this.parseDate(o.date_paid);
        const dtPaid = dtPaidObj ? dtPaidObj.toLocaleDateString('fr-FR',{day:'2-digit',month:'long',year:'numeric'}) : '—';

        let html = '';

        // Order Meta
        html += `<div class="biz-ord-section">
            <div style="display:flex; gap:12px; flex-wrap:wrap; font-size:12px; color:#64748b;">
                <span>📅 ${this.t('Created','Créée','أُنشئ في')}: <b style="color:#1e293b;">${dt}</b></span>
                <span>💳 ${this.escHtml(o.payment_title||'—')}</span>
                ${o.transaction_id ? `<span>🔗 ${this.escHtml(o.transaction_id)}</span>` : ''}
                <span>📅 ${this.t('Paid','Payé','مدفوع')}: <b style="color:#1e293b;">${dtPaid}</b></span>
                <span>🌐 ${this.t('Via','Via','عبر')}: ${this.escHtml(o.created_via||'—')}</span>
            </div>
        </div>`;

        // Quick status change
        const nextSt = this.validNextStatuses(o.status);
        if (nextSt.length > 0) {
            html += `<div class="biz-ord-section"><div class="biz-ord-section-title">🔄 ${this.t('Change Status','Changer Statut','تغيير الحالة')}</div>
                <div style="display:flex; gap:6px; flex-wrap:wrap;">`;
            nextSt.forEach(ns => {
                const nsi = this.statusInfo(ns);
                html += `<button class="biz-ord-btn-sm" style="background:${nsi.bg}; color:${nsi.color}; border:1px solid ${nsi.color}30; border-radius:8px; cursor:pointer; font-weight:600; font-size:11px; padding:5px 12px;" onclick="BizOrders.changeStatus(${o.id},'${ns}')">${nsi.icon} ${nsi.label}</button>`;
            });
            html += `</div></div>`;
        }

        // Customer addresses
        html += `<div class="biz-ord-section"><div class="biz-ord-section-title">👤 ${this.t('Customer','Client','العميل')}</div>
            <div class="biz-ord-addr-grid">
                <div class="biz-ord-addr-card" id="panel-addr-billing">
                    <strong>📋 ${this.t('Billing','Facturation','الفوترة')} <button class="biz-ord-edit-btn" onclick='BizOrders.toggleEditAddr(${o.id},"billing",${JSON.stringify(o.billing).replace(/'/g,"&#39;")})'>✏️ ${this.t('Edit','Modifier','تعديل')}</button></strong>
                    ${this.escHtml(o.billing.first_name + ' ' + o.billing.last_name)}<br>
                    ${o.billing.company ? this.escHtml(o.billing.company)+'<br>' : ''}
                    ${this.escHtml(o.billing.address_1)}${o.billing.address_2 ? ', '+this.escHtml(o.billing.address_2) : ''}<br>
                    ${this.escHtml(o.billing.postcode + ' ' + o.billing.city)}<br>
                    ${this.escHtml(o.billing.country)}
                    ${o.billing.email ? '<br><a href="mailto:'+this.escHtml(o.billing.email)+'">'+this.escHtml(o.billing.email)+'</a>' : ''}
                    ${o.billing.phone ? '<br>📞 '+this.escHtml(o.billing.phone) : ''}
                </div>
                <div class="biz-ord-addr-card" id="panel-addr-shipping">
                    <strong>🚚 ${this.t('Shipping','Livraison','الشحن')} <button class="biz-ord-edit-btn" onclick='BizOrders.toggleEditAddr(${o.id},"shipping",${JSON.stringify(o.shipping).replace(/'/g,"&#39;")})'>✏️ ${this.t('Edit','Modifier','تعديل')}</button></strong>
                    ${this.escHtml(o.shipping.first_name + ' ' + o.shipping.last_name)}<br>
                    ${o.shipping.company ? this.escHtml(o.shipping.company)+'<br>' : ''}
                    ${this.escHtml(o.shipping.address_1)}${o.shipping.address_2 ? ', '+this.escHtml(o.shipping.address_2) : ''}<br>
                    ${this.escHtml(o.shipping.postcode + ' ' + o.shipping.city)}<br>
                    ${this.escHtml(o.shipping.country)}
                    ${o.shipping.phone ? '<br>📞 '+this.escHtml(o.shipping.phone) : ''}
                </div>
            </div>
        </div>`;

        // Line items
        html += `<div class="biz-ord-section"><div class="biz-ord-section-title">📦 ${this.t('Items','Articles','العناصر')} (${o.line_items.length})
                <button class="biz-ord-edit-btn" onclick="BizOrders.showAddItemSearch(${o.id})">➕ ${this.t('Add Item','Ajouter','إضافة')}</button>
            </div>
            <div id="panel-add-item-area" style="display:none;"></div>
            <div style="overflow-x:auto;">
            <table class="biz-ord-items-table">
                <thead><tr>
                    <th></th><th>${this.t('Product','Produit','المنتج')}</th><th>SKU</th>
                    <th style="text-align:center;">Qty</th><th style="text-align:right;">${this.t('Price','Prix','السعر')}</th><th style="text-align:right;">Total</th><th style="width:60px;"></th>
                </tr></thead><tbody>`;
        o.line_items.forEach(it => {
            const unitPrice = it.quantity > 0 ? it.subtotal / it.quantity : 0;
            html += `<tr>
                <td>${it.image ? '<img class="item-img" src="'+this.escHtml(it.image)+'" alt="">' : '<div class="item-img" style="display:inline-block;"></div>'}</td>
                <td><span class="item-name">${this.escHtml(it.name)}</span></td>
                <td><span class="item-sku">${this.escHtml(it.sku||'—')}</span></td>
                <td style="text-align:center;">
                    <input type="number" value="${it.quantity}" min="1" style="width:50px;padding:3px 6px;border:1px solid #d1d5db;border-radius:6px;text-align:center;font-size:12px;font-weight:600;"
                        onchange="BizOrders.updateItemQty(${o.id},${it.id},this.value)">
                </td>
                <td style="text-align:right;">
                    <input type="number" value="${unitPrice.toFixed(2)}" min="0" step="0.01" style="width:80px;padding:3px 6px;border:1px solid #d1d5db;border-radius:6px;text-align:right;font-size:12px;font-weight:600;"
                        onchange="BizOrders.updateItemPrice(${o.id},${it.id},this.value)">
                </td>
                <td style="text-align:right; font-weight:700;">${this.fmtCur(it.total)}</td>
                <td style="text-align:center;"><button class="biz-ord-act danger" onclick="BizOrders.removeItemFromOrder(${o.id},${it.id})" title="${this.t('Remove','Supprimer','إزالة')}" style="font-size:12px;">✕</button></td>
            </tr>`;
        });
        html += `</tbody></table></div></div>`;

        // Totals
        html += `<div class="biz-ord-section">
            <div class="biz-ord-totals">
                <div class="t-row"><span>${this.t('Subtotal','Sous-total','المجموع الفرعي')}</span><span>${this.fmtCur(o.subtotal)}</span></div>`;
        if (o.discount_total > 0) html += `<div class="t-row"><span>${this.t('Discount','Remise','الخصم')}</span><span>-${this.fmtCur(o.discount_total)}</span></div>`;
        if (o.shipping_total > 0) html += `<div class="t-row"><span>${this.t('Shipping','Livraison','الشحن')}</span><span>${this.fmtCur(o.shipping_total)}</span></div>`;
        if (o.tax_total > 0) html += `<div class="t-row"><span>${this.t('Tax','Taxe','الضريبة')}</span><span>${this.fmtCur(o.tax_total)}</span></div>`;
        html += `<div class="t-row grand"><span>${this.t('Total','Total','الإجمالي')}</span><span>${this.fmtCur(o.total)}</span></div>`;
        const _gains = parseFloat(o.gains || 0);
        html += `<div class="t-row" style="color:${_gains >= 0 ? '#059669' : '#ef4444'}; font-weight:700;"><span>📈 ${this.t('Gains','Gains','الأرباح')}</span><span>${this.fmtCur(_gains)}</span></div>`;
        if (o.total_refunded > 0) {
            html += `<div class="t-row refund"><span>${this.t('Refunded','Remboursé','مستردّ')}</span><span>-${this.fmtCur(o.total_refunded)}</span></div>`;
            html += `<div class="t-row" style="font-weight:700;"><span>${this.t('Net','Net','الصافي')}</span><span>${this.fmtCur(o.net_total)}</span></div>`;
        }
        html += `</div></div>`;

        // Coupons
        if (o.coupon_lines && o.coupon_lines.length > 0) {
            html += `<div class="biz-ord-section"><div class="biz-ord-section-title">🎟️ ${this.t('Coupons','Coupons','الكوبونات')}</div>
                <div style="display:flex; gap:6px; flex-wrap:wrap;">`;
            o.coupon_lines.forEach(c => {
                html += `<span style="background:#fef3c7; color:#92400e; padding:4px 10px; border-radius:8px; font-size:11px; font-weight:700;">${this.escHtml(c.code)} (-${this.fmtCur(c.discount)})</span>`;
            });
            html += `</div></div>`;
        }

        // Refunds list
        if (o.refunds && o.refunds.length > 0) {
            html += `<div class="biz-ord-section"><div class="biz-ord-section-title">↩️ ${this.t('Refunds','Remboursements','المرتجعات')}</div>`;
            o.refunds.forEach(r => {
                const rdObj = this.parseDate(r.date);
                const rd = rdObj ? rdObj.toLocaleDateString('fr-FR',{day:'2-digit',month:'short',year:'numeric'}) : '';
                html += `<div style="display:flex; justify-content:space-between; align-items:center; padding:8px 10px; background:#fef2f2; border:1px solid #fecaca; border-radius:8px; margin-bottom:6px; font-size:12px;">
                    <div><b style="color:#dc2626;">-${this.fmtCur(r.amount)}</b> ${r.reason ? '<span style="color:#6b7280; margin-left:6px;">'+this.escHtml(r.reason)+'</span>' : ''}</div>
                    <span style="color:#94a3b8; font-size:10px;">${rd}</span>
                </div>`;
            });
            html += `</div>`;
        }

        // Notes
        html += `<div class="biz-ord-section"><div class="biz-ord-section-title">📝 ${this.t('Notes','Notes','الملاحظات')} (${o.notes.length})</div>
            <div class="biz-ord-notes-list" id="panel-notes">`;
        if (o.notes.length === 0) {
            html += `<p style="color:#94a3b8; font-size:12px; text-align:center;">${this.t('No notes yet','Aucune note','لا ملاحظات بعد')}</p>`;
        }
        o.notes.forEach(n => {
            const ndObj = this.parseDate(n.date);
            const nd = ndObj ? ndObj.toLocaleDateString('fr-FR',{day:'2-digit',month:'short',year:'numeric',hour:'2-digit',minute:'2-digit'}) : '';
            const cls = n.customer_note ? 'customer' : 'internal';
            const typeLabel = n.customer_note ? this.t('Customer','Client','عميل') : this.t('Private','Privée','خاصة');
            html += `<div class="biz-ord-note ${cls}">
                <div>${n.content}</div>
                <div class="note-meta">
                    <span>${typeLabel} · ${this.escHtml(n.added_by)} · ${nd}</span>
                    <span class="note-del" onclick="BizOrders.deleteNote(${n.id}, ${o.id})">✕ ${this.t('Delete','Supprimer','حذف')}</span>
                </div>
            </div>`;
        });
        html += `</div>
            <div class="biz-ord-note-form">
                <textarea id="panel-note-text" placeholder="${this.t('Add a note...','Ajouter une note...','أضف ملاحظة...')}"></textarea>
                <div style="display:flex; flex-direction:column; gap:6px;">
                    <div class="biz-ord-note-type">
                        <div class="biz-ord-chk-wrap"><input type="checkbox" id="panel-note-customer"><label for="panel-note-customer">${this.t('Customer note','Note client','ملاحظة العميل')}</label></div>
                    </div>
                    <button class="biz-ord-btn-primary biz-ord-btn-sm" onclick="BizOrders.addNote(${o.id})">${this.t('Add','Ajouter','إضافة')}</button>
                </div>
            </div>
        </div>`;

        // Refund form (hidden by default)
        const remaining = o.total - o.total_refunded;
        html += `<div class="biz-ord-section">
            <button class="biz-ord-btn-secondary" onclick="document.getElementById('refund-form').classList.toggle('open')" style="width:100%;">↩️ ${this.t('Issue Refund','Rembourser','إصدار استرداد')}</button>
            <div class="biz-ord-refund-form" id="refund-form" style="margin-top:10px;">
                <label>${this.t('Amount','Montant','المبلغ')} (${this.t('max','max','الحد')}: ${this.fmtCur(remaining)})</label>
                <input type="number" id="refund-amount" step="0.01" min="0.01" max="${remaining.toFixed(2)}" placeholder="0.00">
                <label>${this.t('Reason','Raison','السبب')}</label>
                <textarea id="refund-reason" rows="2" placeholder="${this.t('Optional reason...','Raison optionnelle...','سبب اختياري...')}"></textarea>
                <div class="biz-ord-chk-wrap" style="margin-bottom:10px;">
                    <input type="checkbox" id="refund-restock"><label for="refund-restock">${this.t('Restock items','Restockter les articles','إعادة التخزين')}</label>
                </div>
                <button class="biz-ord-btn-danger" onclick="BizOrders.processRefund(${o.id})" style="width:100%;">↩️ ${this.t('Process Refund','Rembourser','معالجة الاسترداد')}</button>
            </div>
        </div>`;

        // Customer note
        if (o.customer_note) {
            html += `<div class="biz-ord-section">
                <div class="biz-ord-section-title">💬 ${this.t('Customer Note','Note Client','ملاحظة العميل')}</div>
                <p style="font-size:13px; color:#475569; background:#f8fafc; padding:10px; border-radius:8px; border:1px solid #e2e8f0;">${this.escHtml(o.customer_note)}</p>
            </div>`;
        }

        $('#panel-body').html(html);

        // Footer actions
        let footHtml = `
            <button class="biz-ord-btn-primary biz-ord-btn-sm" onclick="BizOrders.duplicateOrder(${o.id})">📋 ${this.t('Duplicate','Dupliquer','تكرار')}</button>
            <button class="biz-ord-btn-secondary biz-ord-btn-sm" onclick="BizOrders.resendEmail(${o.id},'new_order')">📧 ${this.t('Resend Email','Renvoyer Email','إعادة إرسال')}</button>
            <button class="biz-ord-btn-secondary biz-ord-btn-sm" onclick="window.open(BizOrdersConfig.ordersPageUrl + '&order_id=${o.id}', '_blank')">🔗 ${this.t('Edit','Modifier','تعديل')}</button>
            <button class="biz-ord-btn-secondary biz-ord-btn-sm danger" onclick="BizOrders.trashOrder(${o.id})" style="color:#ef4444; border-color:#fca5a5;">🗑️ ${this.t('Trash','Supprimer','حذف')}</button>
        `;
        $('#panel-footer').html(footHtml);
    },

    // --- Notes ---
    addNote(orderId) {
        const text = $('#panel-note-text').val().trim();
        if (!text) return;
        const isCust = $('#panel-note-customer').is(':checked') ? '1' : '0';
        $.post(BizOrdersConfig.ajaxUrl, {
            action: 'bizmart_add_order_note',
            nonce: BizOrdersConfig.nonce,
            order_id: orderId,
            note: text,
            is_customer: isCust
        }, (res) => {
            if (res.success) {
                this.toast(this.t('Note added','Note ajoutée','تمت إضافة الملاحظة'), 'success');
                this.openDetail(orderId); // refresh panel
            } else {
                this.toast(res.data||'Error','error');
            }
        });
    },

    deleteNote(noteId, orderId) {
        if (!confirm(this.t('Delete this note?','Supprimer cette note ?','حذف هذه الملاحظة؟'))) return;
        $.post(BizOrdersConfig.ajaxUrl, {
            action: 'bizmart_delete_order_note',
            nonce: BizOrdersConfig.nonce,
            note_id: noteId
        }, (res) => {
            if (res.success) {
                this.toast(this.t('Note deleted','Note supprimée','تم حذف الملاحظة'), 'success');
                this.openDetail(orderId);
            } else {
                this.toast(res.data||'Error','error');
            }
        });
    },

    // --- Refund ---
    processRefund(orderId) {
        const amount = parseFloat($('#refund-amount').val());
        const reason = $('#refund-reason').val();
        const restock = $('#refund-restock').is(':checked') ? '1' : '0';
        if (!amount || amount <= 0) { this.toast(this.t('Enter a valid amount','Montant invalide','أدخل مبلغًا صالحًا'),'error'); return; }
        if (!confirm(this.t(`Refund ${this.fmtCur(amount)}?`, `Rembourser ${this.fmtCur(amount)} ?`, `استرداد ${this.fmtCur(amount)}؟`))) return;

        $.post(BizOrdersConfig.ajaxUrl, {
            action: 'bizmart_refund_order',
            nonce: BizOrdersConfig.nonce,
            order_id: orderId,
            amount: amount,
            reason: reason,
            restock: restock
        }, (res) => {
            if (res.success) {
                this.toast(this.t('Refund processed','Remboursement effectué','تم الاسترداد'), 'success');
                this.openDetail(orderId);
                this.fetch();
            } else {
                this.toast(res.data||'Error','error');
            }
        });
    },

    // --- Resend Email ---
    resendEmail(orderId, type) {
        $.post(BizOrdersConfig.ajaxUrl, {
            action: 'bizmart_resend_order_email',
            nonce: BizOrdersConfig.nonce,
            order_id: orderId,
            email_type: type || 'new_order'
        }, (res) => {
            if (res.success) this.toast(this.t('Email sent','Email envoyé','تم إرسال البريد'), 'success');
            else this.toast(res.data||'Error','error');
        });
    },

    // --- Trash ---
    trashOrder(orderId) {
        if (!confirm(this.t('Move this order to trash?','Mettre cette commande à la corbeille ?','نقل هذا الطلب إلى سلة المحذوفات؟'))) return;
        $.post(BizOrdersConfig.ajaxUrl, {
            action: 'bizmart_trash_order',
            nonce: BizOrdersConfig.nonce,
            order_id: orderId
        }, (res) => {
            if (res.success) {
                this.toast(this.t('Order trashed','Commande supprimée','تم حذف الطلب'), 'success');
                if (this.panelOrderId === orderId) this.closeDetail();
                this.fetch();
            } else {
                this.toast(res.data||'Error','error');
            }
        });
    },

    // --- Export CSV ---
    exportCSV() {
        if (!this.cachedData || !this.cachedData.orders || this.cachedData.orders.length === 0) {
            this.toast(this.t('No data to export','Aucune donnée','لا بيانات للتصدير'), 'error'); return;
        }
        const hdr = ['#', this.t('Date','Date','التاريخ'), this.t('Customer','Client','العميل'), 'Email', this.t('Items','Articles','العناصر'), this.t('Total','Total','الإجمالي'), this.t('Gains','Gains','الأرباح'), this.t('Payment','Paiement','الدفع'), this.t('Status','Statut','الحالة')];
        let csv = hdr.join(';') + '\n';
        this.cachedData.orders.forEach(o => {
            const si = this.statusInfo(o.status);
            csv += [
                o.number,
                o.date_created ? o.date_created.substring(0,10) : '',
                '"'+(o.billing_name||'').replace(/"/g,'""')+'"',
                o.billing_email||'',
                o.item_count,
                parseFloat(o.total||0).toFixed(2).replace('.',','),
                parseFloat(o.gains||0).toFixed(2).replace('.',','),
                o.payment_title||o.payment_method||'',
                si.label
            ].join(';') + '\n';
        });
        const blob = new Blob(['\ufeff'+csv], {type:'text/csv;charset=utf-8;'});
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `Bizmart_Orders_${(function(d){var dt=(d instanceof Date)?d:new Date(d); if(isNaN(dt.getTime())) return ''; var y=dt.getFullYear(), m=String(dt.getMonth()+1).padStart(2,'0'), day=String(dt.getDate()).padStart(2,'0'); return y+'-'+m+'-'+day; })(new Date())}.csv`;
        link.click();
        this.toast(this.t('CSV exported','CSV exporté','CSV تم تصديره'), 'success');
    },

    // --- Toast ---
    toast(msg, type) {
        const el = $(`<div class="biz-ord-toast ${type||'success'}">${this.escHtml(msg)}</div>`);
        $('body').append(el);
        setTimeout(() => el.fadeOut(300, function(){ $(this).remove(); }), 3000);
    },
    showError(msg) {
        $('#ord-tbody').html(`<tr><td colspan="10" style="text-align:center;padding:40px;color:#ef4444;">${this.escHtml(msg)}</td></tr>`);
    },

    // ==================================================================
    //              CREATE ORDER — Modal, Searches, Submit
    // ==================================================================
    createItems: [],
    createCustomer: null,
    custSearchTimer: null,
    prodSearchTimer: null,

    openCreateModal() {
        this.createItems = [];
        this.createCustomer = null;
        this.renderCreateItems();
        $('#create-cust-search').val('').show();
        $('#create-cust-results').removeClass('active').html('');
        $('#create-cust-selected').hide().html('');
        $('#create-prod-search').val('');
        $('#create-prod-results').removeClass('active').html('');
        $('#c-bill-fn, #c-bill-ln, #c-bill-company, #c-bill-addr1, #c-bill-addr2, #c-bill-city, #c-bill-zip, #c-bill-email, #c-bill-phone').val('');
        $('#c-bill-country').val('MA');
        $('#c-ship-fn, #c-ship-ln, #c-ship-addr1, #c-ship-city, #c-ship-zip').val('');
        $('#c-ship-country').val('MA');
        $('#c-same-addr').prop('checked', true);
        $('#create-shipping-fields').hide();
        $('#c-status').val('pending');
        $('#c-note').val('');
        $('#create-modal-title').text('➕ ' + this.t('New Order','Nouvelle Commande','طلب جديد'));

        // Populate payment methods from cached gateways
        if (this.cachedData && this.cachedData.gateways) {
            let html = `<option value="">${this.t('None','Aucune','بدون')}</option>`;
            this.cachedData.gateways.forEach(g => { html += `<option value="${g.id}">${this.escHtml(g.title)}</option>`; });
            $('#c-payment').html(html);
        }

        $('#ord-create-overlay').addClass('active');
    },

    closeCreateModal() {
        $('#ord-create-overlay').removeClass('active');
    },

    toggleSameAddr() {
        const same = $('#c-same-addr').is(':checked');
        $('#create-shipping-fields').toggle(!same);
    },

    // Customer search
    searchCustomers(term) {
        if (term.length < 2) { $('#create-cust-results').removeClass('active'); return; }
        $.post(BizOrdersConfig.ajaxUrl, {
            action: 'bizmart_search_customers',
            nonce: BizOrdersConfig.nonce,
            term: term
        }, (res) => {
            if (!res.success || !res.data.length) {
                $('#create-cust-results').html(`<div class="biz-ord-sr-item" style="color:#94a3b8; cursor:default;">${this.t('No customers found','Aucun client trouvé','لم يتم العثور على عملاء')}</div>`).addClass('active');
                return;
            }
            let html = `<div class="biz-ord-sr-item" style="color:#3b82f6; font-weight:600;" onclick="BizOrders.selectCustomer(null)">👤 ${this.t('Guest Order','Commande Invité','طلب زائر')}</div>`;
            res.data.forEach(c => {
                html += `<div class="biz-ord-sr-item" onclick='BizOrders.selectCustomer(${JSON.stringify(c).replace(/'/g,"&#39;")})'>
                    <div style="width:34px;height:34px;border-radius:50%;background:#e0e7ff;display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:700;color:#4338ca;">
                        ${this.escHtml((c.name||'?')[0].toUpperCase())}
                    </div>
                    <div><div class="sr-name">${this.escHtml(c.name)}</div><div class="sr-sub">${this.escHtml(c.email)}${c.phone ? ' · '+this.escHtml(c.phone) : ''}</div></div>
                </div>`;
            });
            $('#create-cust-results').html(html).addClass('active');
        });
    },

    selectCustomer(cust) {
        this.createCustomer = cust;
        $('#create-cust-results').removeClass('active');
        if (!cust) {
            // Guest
            $('#create-cust-search').hide();
            $('#create-cust-selected').show().html(`<div class="biz-ord-cust-card">
                <div style="width:40px;height:40px;border-radius:50%;background:#f1f5f9;display:flex;align-items:center;justify-content:center;font-size:18px;">\ud83d\udc64</div>
                <div class="cc-info"><div class="cc-name">${this.t('Guest Order','Commande Invité','طلب زائر')}</div><div class="cc-email">${this.t('No customer account','Pas de compte client','لا حساب عميل')}</div></div>
                <button class="cc-remove" onclick="BizOrders.clearCustomer()" title="${this.t('Change','Changer','تغيير')}">✕</button>
            </div>`);
        } else {
            $('#create-cust-search').hide();
            $('#create-cust-selected').show().html(`<div class="biz-ord-cust-card">
                <div style="width:40px;height:40px;border-radius:50%;background:#dbeafe;display:flex;align-items:center;justify-content:center;font-size:16px;font-weight:700;color:#2563eb;">
                    ${this.escHtml((cust.name||'?')[0].toUpperCase())}
                </div>
                <div class="cc-info"><div class="cc-name">${this.escHtml(cust.name)}</div><div class="cc-email">${this.escHtml(cust.email)}${cust.phone ? ' · '+this.escHtml(cust.phone) : ''}</div></div>
                <button class="cc-remove" onclick="BizOrders.clearCustomer()" title="${this.t('Change','Changer','تغيير')}">✕</button>
            </div>`);
            // Auto-fill billing address from customer
            if (cust.billing) {
                $('#c-bill-fn').val(cust.billing.first_name||'');
                $('#c-bill-ln').val(cust.billing.last_name||'');
                $('#c-bill-company').val(cust.billing.company||'');
                $('#c-bill-addr1').val(cust.billing.address_1||'');
                $('#c-bill-addr2').val(cust.billing.address_2||'');
                $('#c-bill-city').val(cust.billing.city||'');
                $('#c-bill-zip').val(cust.billing.postcode||'');
                $('#c-bill-country').val(cust.billing.country||'MA');
                $('#c-bill-email').val(cust.billing.email||cust.email||'');
                $('#c-bill-phone').val(cust.billing.phone||'');
            }
        }
    },

    clearCustomer() {
        this.createCustomer = null;
        $('#create-cust-selected').hide().html('');
        $('#create-cust-search').val('').show().focus();
    },

    // Product search
    searchProducts(term) {
        if (term.length < 1) { $('#create-prod-results').removeClass('active'); return; }
        $.post(BizOrdersConfig.ajaxUrl, {
            action: 'bizmart_search_products_for_order',
            nonce: BizOrdersConfig.nonce,
            term: term
        }, (res) => {
            if (!res.success || !res.data.length) {
                $('#create-prod-results').html(`<div class="biz-ord-sr-item" style="color:#94a3b8; cursor:default;">${this.t('No products found','Aucun produit trouvé','لم يتم العثور على منتجات')}</div>`).addClass('active');
                return;
            }
            let html = '';
            res.data.forEach(p => {
                const imgHtml = p.image ? `<img src="${this.escHtml(p.image)}" alt="">` : `<div style="width:34px;height:34px;background:#f1f5f9;border-radius:6px;display:flex;align-items:center;justify-content:center;font-size:14px;">📦</div>`;
                const stock = p.managing_stock && p.stock !== null ? `<span style="color:${p.stock>0?'#059669':'#ef4444'};">${p.stock} ${this.t('in stock','en stock','في المخزون')}</span>` : '';
                html += `<div class="biz-ord-sr-item" onclick='BizOrders.addCreateItem(${JSON.stringify(p).replace(/'/g,"&#39;")})'>
                    ${imgHtml}
                    <div><div class="sr-name">${this.escHtml(p.name)}</div><div class="sr-sub">${p.sku ? 'SKU: '+this.escHtml(p.sku) : 'ID: '+p.id} ${stock}</div></div>
                    <div class="sr-price">${this.fmtCur(p.price)}</div>
                </div>`;
            });
            $('#create-prod-results').html(html).addClass('active');
        });
    },

    addCreateItem(product) {
        // Check if already added
        const existing = this.createItems.find(i => i.product_id === product.id);
        if (existing) { existing.quantity++; }
        else {
            this.createItems.push({
                product_id: product.id,
                name: product.name,
                sku: product.sku || '',
                price: product.price,
                quantity: 1,
                image: product.image || ''
            });
        }
        $('#create-prod-search').val('');
        $('#create-prod-results').removeClass('active');
        this.renderCreateItems();
    },

    removeCreateItem(idx) {
        this.createItems.splice(idx, 1);
        this.renderCreateItems();
    },

    updateCreateItemQty(idx, qty) {
        qty = parseInt(qty);
        if (qty < 1) qty = 1;
        this.createItems[idx].quantity = qty;
        this.renderCreateItems();
    },

    updateCreateItemPrice(idx, price) {
        price = parseFloat(price);
        if (isNaN(price) || price < 0) price = 0;
        this.createItems[idx].price = price;
        this.renderCreateItems();
    },

    renderCreateItems() {
        const list = $('#create-items-list');
        const totalEl = $('#create-items-total');
        if (this.createItems.length === 0) {
            list.html(`<div style="text-align:center; padding:20px; color:#94a3b8; font-size:13px;">${this.t('No items added yet. Search and add products above.','Aucun article. Cherchez et ajoutez des produits.','لم تتم إضافة عناصر بعد. ابحث وأضف منتجات.')}</div>`);
            totalEl.hide();
            return;
        }
        let html = '';
        let grandTotal = 0;
        this.createItems.forEach((item, idx) => {
            const lineTotal = item.price * item.quantity;
            grandTotal += lineTotal;
            const imgHtml = item.image ? `<img src="${this.escHtml(item.image)}" alt="">` : `<div style="width:36px;height:36px;background:#f1f5f9;border-radius:6px;display:flex;align-items:center;justify-content:center;">📦</div>`;
            html += `<div class="biz-ord-new-item">
                ${imgHtml}
                <div class="ni-name" title="${this.escHtml(item.name)}">${this.escHtml(item.name)}${item.sku ? ' <span style=\"color:#94a3b8; font-weight:400; font-size:11px;\">'+this.escHtml(item.sku)+'</span>' : ''}</div>
                <input type="number" class="ni-qty" value="${item.quantity}" min="1" onchange="BizOrders.updateCreateItemQty(${idx}, this.value)">
                <span style="color:#94a3b8; font-size:12px;">×</span>
                <input type="number" class="ni-price" value="${item.price.toFixed(2)}" min="0" step="0.01" onchange="BizOrders.updateCreateItemPrice(${idx}, this.value)">
                <div class="ni-total">${this.fmtCur(lineTotal)}</div>
                <button class="ni-remove" onclick="BizOrders.removeCreateItem(${idx})">✕</button>
            </div>`;
        });
        list.html(html);
        totalEl.show().html(`<span>${this.t('Total','Total','الإجمالي')}:</span> <span>${this.fmtCur(grandTotal)}</span>`);
    },

    // Submit create order
    submitCreateOrder() {
        if (this.createItems.length === 0) {
            this.toast(this.t('Add at least one product','Ajoutez au moins un produit','أضف منتجًا واحدًا على الأقل'), 'error');
            return;
        }

        const billing = {
            first_name: $('#c-bill-fn').val(),
            last_name:  $('#c-bill-ln').val(),
            company:    $('#c-bill-company').val(),
            address_1:  $('#c-bill-addr1').val(),
            address_2:  $('#c-bill-addr2').val(),
            city:       $('#c-bill-city').val(),
            postcode:   $('#c-bill-zip').val(),
            country:    $('#c-bill-country').val(),
            email:      $('#c-bill-email').val(),
            phone:      $('#c-bill-phone').val(),
        };

        let shipping;
        if ($('#c-same-addr').is(':checked')) {
            shipping = { ...billing };
            delete shipping.email;
            delete shipping.phone;
        } else {
            shipping = {
                first_name: $('#c-ship-fn').val(),
                last_name:  $('#c-ship-ln').val(),
                address_1:  $('#c-ship-addr1').val(),
                city:       $('#c-ship-city').val(),
                postcode:   $('#c-ship-zip').val(),
                country:    $('#c-ship-country').val(),
            };
        }

        const data = {
            action: 'bizmart_create_order',
            nonce: BizOrdersConfig.nonce,
            customer_id: this.createCustomer ? this.createCustomer.id : 0,
            status: $('#c-status').val(),
            payment_method: $('#c-payment').val(),
            customer_note: $('#c-note').val(),
            items: this.createItems.map(i => ({
                product_id: i.product_id,
                quantity: i.quantity,
                price: i.price,
            })),
            billing: billing,
            shipping: shipping,
        };

        $('#create-order-submit').prop('disabled', true).text('⏳ ...');

        $.post(BizOrdersConfig.ajaxUrl, data, (res) => {
            $('#create-order-submit').prop('disabled', false).text('✅ ' + this.t('Create Order','Créer Commande','إنشاء طلب'));
            if (res.success) {
                this.toast(this.t('Order #'+res.data.number+' created!','Commande #'+res.data.number+' créée!','الطلب #'+res.data.number+' تم إنشاؤه!'), 'success');
                this.closeCreateModal();
                this.fetch();
                // Open the new order detail
                setTimeout(() => this.openDetail(res.data.order_id), 600);
            } else {
                this.toast(res.data || 'Error', 'error');
            }
        }).fail((xhr) => {
            $('#create-order-submit').prop('disabled', false).text('✅ ' + this.t('Create Order','Créer Commande','إنشاء طلب'));
            this.toast(this.ajaxError(xhr), 'error');
        });
    },

    // ==================================================================
    //          EDIT ORDER — Addresses, Items, Duplicate
    // ==================================================================

    // Duplicate order
    duplicateOrder(orderId) {
        if (!confirm(this.t('Duplicate this order?','Dupliquer cette commande ?','تكرار هذا الطلب؟'))) return;
        $.post(BizOrdersConfig.ajaxUrl, {
            action: 'bizmart_duplicate_order',
            nonce: BizOrdersConfig.nonce,
            order_id: orderId
        }, (res) => {
            if (res.success) {
                this.toast(this.t('Order duplicated: #'+res.data.number, 'Commande dupliquée: #'+res.data.number, 'تم تكرار الطلب: #'+res.data.number), 'success');
                this.fetch();
                this.openDetail(res.data.order_id);
            } else {
                this.toast(res.data||'Error','error');
            }
        });
    },

    // Save edited addresses in panel
    saveAddresses(orderId, type) {
        const prefix = 'edit-' + type + '-';
        const fields = type === 'billing'
            ? ['first_name','last_name','company','address_1','address_2','city','state','postcode','country','email','phone']
            : ['first_name','last_name','company','address_1','address_2','city','state','postcode','country','phone'];

        const data = {
            action: 'bizmart_update_order',
            nonce: BizOrdersConfig.nonce,
            order_id: orderId,
        };
        data[type] = {};
        fields.forEach(f => {
            const el = document.getElementById(prefix + f);
            data[type][f] = el ? el.value : '';
        });

        $.post(BizOrdersConfig.ajaxUrl, data, (res) => {
            if (res.success) {
                this.toast(this.t('Address updated','Adresse mise à jour','تم تحديث العنوان'), 'success');
                this.openDetail(orderId);
            } else {
                this.toast(res.data||'Error','error');
            }
        });
    },

    // Toggle address edit mode in panel
    toggleEditAddr(orderId, type, addrData) {
        const container = document.getElementById('panel-addr-' + type);
        if (!container) return;
        const fields = type === 'billing'
            ? [['first_name','First Name','Prénom','الاسم الأول'],['last_name','Last Name','Nom','اللقب'],['company','Company','Entreprise','الشركة'],['address_1','Address','Adresse','العنوان'],['address_2','Address 2','Adresse 2','العنوان 2'],['city','City','Ville','المدينة'],['postcode','Postcode','Code Postal','الرمز البريدي'],['country','Country','Pays','البلد'],['email','Email','Email','البريد'],['phone','Phone','Téléphone','الهاتف']]
            : [['first_name','First Name','Prénom','الاسم الأول'],['last_name','Last Name','Nom','اللقب'],['company','Company','Entreprise','الشركة'],['address_1','Address','Adresse','العنوان'],['address_2','Address 2','Adresse 2','العنوان 2'],['city','City','Ville','المدينة'],['postcode','Postcode','Code Postal','الرمز البريدي'],['country','Country','Pays','البلد'],['phone','Phone','Téléphone','الهاتف']];

        let html = '<div class="biz-ord-addr-form">';
        fields.forEach(([key, en, fr, ar]) => {
            html += `<input type="text" id="edit-${type}-${key}" value="${this.escHtml(addrData[key]||'')}" placeholder="${this.t(en,fr,ar)}">`;
        });
        html += `</div>
            <div style="display:flex;gap:6px;margin-top:8px;">
                <button class="biz-ord-btn-primary biz-ord-btn-sm" onclick="BizOrders.saveAddresses(${orderId},'${type}')">\u2705 ${this.t('Save','Enregistrer','حفظ')}</button>
                <button class="biz-ord-btn-secondary biz-ord-btn-sm" onclick="BizOrders.openDetail(${orderId})">${this.t('Cancel','Annuler','إلغاء')}</button>
            </div>`;
        container.innerHTML = html;
    },

    // Add item to existing order
    panelProdSearchTimer: null,

    showAddItemSearch(orderId) {
        const container = document.getElementById('panel-add-item-area');
        if (!container) return;
        container.innerHTML = `<div class="biz-ord-inline-search">
            <input type="text" id="panel-add-item-input" placeholder="${this.t('Search product...','Chercher un produit...','بحث عن منتج...')}" autocomplete="off">
            <div class="biz-ord-search-results" id="panel-add-item-results"></div>
        </div>`;
        container.style.display = 'block';
        document.getElementById('panel-add-item-input').focus();

        // Bind search
        $(document).off('input.panelAddItem').on('input.panelAddItem', '#panel-add-item-input', (e) => {
            clearTimeout(this.panelProdSearchTimer);
            this.panelProdSearchTimer = setTimeout(() => {
                this.searchProductsForPanel(e.target.value, orderId);
            }, 300);
        });
    },

    searchProductsForPanel(term, orderId) {
        if (term.length < 1) { $('#panel-add-item-results').removeClass('active'); return; }
        $.post(BizOrdersConfig.ajaxUrl, {
            action: 'bizmart_search_products_for_order',
            nonce: BizOrdersConfig.nonce,
            term: term
        }, (res) => {
            if (!res.success || !res.data.length) {
                $('#panel-add-item-results').html(`<div class="biz-ord-sr-item" style="color:#94a3b8; cursor:default;">${this.t('No products found','Aucun produit','لا منتجات')}</div>`).addClass('active');
                return;
            }
            let html = '';
            res.data.forEach(p => {
                const imgHtml = p.image ? `<img src="${this.escHtml(p.image)}" alt="">` : `<div style="width:34px;height:34px;background:#f1f5f9;border-radius:6px;"></div>`;
                html += `<div class="biz-ord-sr-item" onclick="BizOrders.addItemToOrder(${orderId},${p.id})">
                    ${imgHtml}
                    <div><div class="sr-name">${this.escHtml(p.name)}</div><div class="sr-sub">${p.sku?'SKU: '+this.escHtml(p.sku):'ID: '+p.id}</div></div>
                    <div class="sr-price">${this.fmtCur(p.price)}</div>
                </div>`;
            });
            $('#panel-add-item-results').html(html).addClass('active');
        });
    },

    addItemToOrder(orderId, productId) {
        $.post(BizOrdersConfig.ajaxUrl, {
            action: 'bizmart_add_order_item',
            nonce: BizOrdersConfig.nonce,
            order_id: orderId,
            product_id: productId,
            quantity: 1
        }, (res) => {
            if (res.success) {
                this.toast(this.t('Item added','Article ajouté','تمت إضافة العنصر'), 'success');
                this.openDetail(orderId);
                this.fetch();
            } else {
                this.toast(res.data||'Error','error');
            }
        });
    },

    removeItemFromOrder(orderId, itemId) {
        if (!confirm(this.t('Remove this item?','Supprimer cet article ?','إزالة هذا العنصر؟'))) return;
        $.post(BizOrdersConfig.ajaxUrl, {
            action: 'bizmart_remove_order_item',
            nonce: BizOrdersConfig.nonce,
            order_id: orderId,
            item_id: itemId
        }, (res) => {
            if (res.success) {
                this.toast(this.t('Item removed','Article supprimé','تم إزالة العنصر'), 'success');
                this.openDetail(orderId);
                this.fetch();
            } else {
                this.toast(res.data||'Error','error');
            }
        });
    },

    updateItemQty(orderId, itemId, qty) {
        $.post(BizOrdersConfig.ajaxUrl, {
            action: 'bizmart_update_order_item',
            nonce: BizOrdersConfig.nonce,
            order_id: orderId,
            item_id: itemId,
            quantity: qty
        }, (res) => {
            if (res.success) {
                this.toast(this.t('Quantity updated','Quantité mise à jour','تم تحديث الكمية'), 'success');
                this.openDetail(orderId);
                this.fetch();
            } else {
                this.toast(res.data||'Error','error');
            }
        });
    },

    updateItemPrice(orderId, itemId, price) {
        $.post(BizOrdersConfig.ajaxUrl, {
            action: 'bizmart_update_order_item',
            nonce: BizOrdersConfig.nonce,
            order_id: orderId,
            item_id: itemId,
            price: price
        }, (res) => {
            if (res.success) {
                this.toast(this.t('Price updated','Prix mis à jour','تم تحديث السعر'), 'success');
                this.openDetail(orderId);
                this.fetch();
            } else {
                this.toast(res.data||'Error','error');
            }
        });
    }
};

// ===== Init =====
const urlParams = new URLSearchParams(window.location.search);
const statusParam = urlParams.get('status');
if (statusParam) {
    BizOrders.filterByStatus(statusParam);
} else {
    BizOrders.fetch();
}

// Customer search — debounced
$(document).on('input', '#create-cust-search', function() {
    clearTimeout(BizOrders.custSearchTimer);
    BizOrders.custSearchTimer = setTimeout(() => BizOrders.searchCustomers($(this).val()), 300);
});

// Product search — debounced
$(document).on('input', '#create-prod-search', function() {
    clearTimeout(BizOrders.prodSearchTimer);
    BizOrders.prodSearchTimer = setTimeout(() => BizOrders.searchProducts($(this).val()), 300);
});

// Close search dropdowns on outside click
$(document).on('click', function(e) {
    if (!$(e.target).closest('.biz-ord-search-wrap, .biz-ord-inline-search').length) {
        $('.biz-ord-search-results').removeClass('active');
    }
});

// Close status dropdowns on outside click
$(document).on('click', function(e) {
    if (!$(e.target).closest('.biz-status-dd').length) {
        document.querySelectorAll('.dd-menu.open').forEach(el => el.classList.remove('open'));
    }
});

// Escape key closes panel/modals
$(document).on('keydown', function(e) {
    if (e.key === 'Escape') {
        BizOrders.closeDetail();
        BizOrders.closeCreateModal();
        document.querySelectorAll('.biz-ord-modal-overlay.active').forEach(el => el.classList.remove('active'));
    }
});

});
