<?php
/**
 * Bizmart — Orders admin page.
 *
 * @package Bizmart
 * @license GPL-2.0-or-later
 */
if (!defined('ABSPATH')) exit;
if (!class_exists('WooCommerce')) {
    echo '<div class="wrap"><div class="notice notice-error"><p><strong>Bizmart:</strong> WooCommerce is required.</p></div></div>';
    return;
}
$currency_symbol = function_exists('bizmart_get_currency_symbol') ? html_entity_decode(bizmart_get_currency_symbol(), ENT_QUOTES, 'UTF-8') : '€';

// Load Chart.js
if (!wp_script_is('bizmart-chartjs', 'enqueued')) {
    wp_enqueue_script('bizmart-chartjs', BIZMART_CORE_URL . 'assets/vendor/chart.umd.min.js', [], '4.0.0', true);
}
?>
<div class="biz-ord-wrap">
<script>
window.BizOrdersConfig = {
    currency: "<?php echo esc_js($currency_symbol); ?>",
    nonce: "<?php echo wp_create_nonce('bizmart-analytics-nonce'); ?>",
    ajaxUrl: "<?php echo esc_url(admin_url('admin-ajax.php')); ?>",
    lang: <?php echo function_exists('bizmart_admin_lang') ? wp_json_encode(bizmart_admin_lang()) : "'en'"; ?>,
    statuses: {
        pending:    { label: "<?php echo esc_js(bizmart_text('Pending','En attente','قيد الانتظار')); ?>",    color: '#f59e0b', bg: '#fffbeb', icon: '⏳' },
        processing: { label: "<?php echo esc_js(bizmart_text('Processing','En cours','قيد المعالجة')); ?>",   color: '#3b82f6', bg: '#eff6ff', icon: '⚙️' },
        'on-hold':  { label: "<?php echo esc_js(bizmart_text('On Hold','En pause','معلّقة')); ?>",      color: '#f97316', bg: '#fff7ed', icon: '⏸️' },
        completed:  { label: "<?php echo esc_js(bizmart_text('Completed','Terminée','مكتملة')); ?>",    color: '#059669', bg: '#ecfdf5', icon: '✅' },
        cancelled:  { label: "<?php echo esc_js(bizmart_text('Cancelled','Annulée','ملغاة')); ?>",     color: '#ef4444', bg: '#fef2f2', icon: '❌' },
        refunded:   { label: "<?php echo esc_js(bizmart_text('Refunded','Remboursée','مستردّة')); ?>",   color: '#8b5cf6', bg: '#f5f3ff', icon: '↩️' },
        failed:     { label: "<?php echo esc_js(bizmart_text('Failed','Échouée','فاشلة')); ?>",        color: '#6b7280', bg: '#f9fafb', icon: '⚠️' }
    }
};
</script>

<style>
/* ===== Orders Page — biz-ord- prefix ===== */
.biz-ord-wrap { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 1200px; margin: 20px auto; padding: 0 16px; }
.biz-ord-wrap * { box-sizing: border-box; }

/* Hero */
.biz-ord-hero {
    background: radial-gradient(circle at 10% 10%, rgba(59,130,246,0.15), transparent 50%),
                radial-gradient(circle at 90% 0%, rgba(16,185,129,0.12), transparent 40%),
                linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border: 1px solid #e2e8f0; border-radius: 18px; padding: 24px 28px 20px; margin-bottom: 24px;
}
.biz-ord-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px; flex-wrap: wrap; gap: 12px; }
.biz-ord-header h1 { margin: 0; font-size: 28px; font-weight: 800; color: #0f172a; letter-spacing: -0.5px; }
.biz-ord-header p.subtitle { margin: 6px 0 0; color: #64748b; font-size: 14px; }
.biz-ord-header .header-actions { display: flex; gap: 10px; flex-wrap: wrap; }

/* Stat Cards */
.biz-ord-stats { display: grid; grid-template-columns: repeat(5, 1fr); gap: 14px; margin-bottom: 0; }
.biz-ord-stat { padding: 20px 22px; border-radius: 14px; position: relative; overflow: hidden; }
.biz-ord-stat::after { content:''; position:absolute; top:-20px; right:-20px; width:80px; height:80px; border-radius:50%; background:rgba(255,255,255,0.15); }
.biz-ord-stat .s-icon { font-size: 22px; margin-bottom: 8px; }
.biz-ord-stat .s-label { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.6px; opacity: 0.85; }
.biz-ord-stat .s-value { font-size: 24px; font-weight: 800; margin: 4px 0 0; letter-spacing: -0.5px; }
.biz-ord-stat .s-sub { font-size: 11px; margin-top: 4px; opacity: 0.7; }
.s-green  { background: linear-gradient(135deg, #059669 0%, #10b981 100%); color: #fff; }
.s-blue   { background: linear-gradient(135deg, #3b82f6 0%, #60a5fa 100%); color: #fff; }
.s-purple { background: linear-gradient(135deg, #7c3aed 0%, #a78bfa 100%); color: #fff; }
.s-amber  { background: linear-gradient(135deg, #d97706 0%, #f59e0b 100%); color: #fff; }

/* Status Strip */
.biz-ord-status-strip { display: flex; gap: 8px; margin-bottom: 24px; flex-wrap: wrap; }
.biz-ord-status-chip {
    display: flex; align-items: center; gap: 6px; padding: 8px 14px; border-radius: 10px;
    border: 2px solid transparent; cursor: pointer; transition: all 0.2s; font-size: 12px; font-weight: 600;
    user-select: none; white-space: nowrap;
}
.biz-ord-status-chip:hover { transform: translateY(-1px); box-shadow: 0 2px 8px rgba(0,0,0,0.08); }
.biz-ord-status-chip.active { border-color: currentColor; box-shadow: 0 4px 12px rgba(0,0,0,0.1); transform: translateY(-1px); }
.biz-ord-status-chip .chip-count { background: rgba(0,0,0,0.12); padding: 2px 7px; border-radius: 6px; font-size: 11px; font-weight: 700; }
.biz-ord-status-chip-all {
    background: #f1f5f9; color: #475569; padding: 8px 14px; border-radius: 10px; border: 2px solid transparent;
    cursor: pointer; font-size: 12px; font-weight: 700; transition: all 0.2s; user-select: none;
}
.biz-ord-status-chip-all.active { border-color: #475569; background: #e2e8f0; }
.biz-ord-status-chip-all:hover { background: #e2e8f0; }

/* Card */
.biz-ord-card { background: #fff; border-radius: 14px; box-shadow: 0 1px 3px rgba(0,0,0,0.06), 0 1px 2px rgba(0,0,0,0.04); overflow: hidden; }

/* Charts Row */
.biz-ord-charts { display: grid; grid-template-columns: 2fr 1fr; gap: 16px; margin-bottom: 24px; }
.biz-ord-chart-box { padding: 20px; }
.biz-ord-chart-box h3 { margin: 0 0 14px; font-size: 14px; font-weight: 700; color: #1e293b; display: flex; align-items: center; gap: 6px; }

/* Filters */
.biz-ord-filters { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; padding: 16px 22px; background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%); border-bottom: 1px solid #e2e8f0; }
.biz-ord-filters input,
.biz-ord-filters select { padding: 8px 12px; border: 1px solid #d1d5db; border-radius: 8px; font-size: 13px; background: #fff; color: #374151; outline:none; transition: border-color 0.2s; }
.biz-ord-filters input:focus,
.biz-ord-filters select:focus { border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59,130,246,0.1); }
.biz-ord-filters .search-wrap { position:relative; }
.biz-ord-filters .search-wrap input { padding-left: 34px; width: 240px; }
.biz-ord-filters .search-wrap .ico { position:absolute; left:10px; top:50%; transform:translateY(-50%); color:#9ca3af; pointer-events:none; font-size:14px; }

/* Bulk Bar */
.biz-ord-bulk { display:none; align-items:center; gap:12px; padding:12px 22px; background:#eff6ff; border-bottom:1px solid #bfdbfe; }
.biz-ord-bulk.visible { display:flex; }
.biz-ord-bulk .bulk-count { font-size:13px; font-weight:700; color:#1d4ed8; }
.biz-ord-bulk select { padding:6px 10px; border:1px solid #93c5fd; border-radius:8px; font-size:13px; background:#fff; }

/* Table */
.biz-ord-table { width:100%; border-collapse:collapse; }
.biz-ord-table thead th {
    background:#f9fafb; color:#64748b; font-size:11px; font-weight:700; text-transform:uppercase;
    letter-spacing:0.05em; padding:12px 14px; border-bottom:2px solid #e5e7eb; text-align:left;
    white-space:nowrap; cursor:pointer; user-select:none;
}
.biz-ord-table thead th:hover { color:#334155; }
.biz-ord-table thead th .sa { margin-left:3px; font-size:9px; color:#cbd5e1; }
.biz-ord-table thead th.sorted .sa { color:#3b82f6; }
.biz-ord-table tbody td { padding:12px 14px; border-bottom:1px solid #f1f5f9; vertical-align:middle; font-size:13px; color:#334155; }
.biz-ord-table tbody tr { transition: background 0.15s; }
.biz-ord-table tbody tr:hover td { background:#f8fafc; }
.biz-ord-table .td-num { font-weight:700; color:#1e40af; cursor:pointer; }
.biz-ord-table .td-num:hover { text-decoration:underline; }
.biz-ord-table .td-total { text-align:right; font-weight:700; font-variant-numeric:tabular-nums; }
.biz-ord-table .td-customer { max-width:180px; }
.biz-ord-table .td-customer .cname { font-weight:600; color:#1e293b; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; display:block; }
.biz-ord-table .td-customer .cemail { font-size:11px; color:#94a3b8; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; display:block; }
.biz-ord-table .td-items { max-width:200px; }
.biz-ord-table .td-items .icount { font-weight:600; color:#475569; }
.biz-ord-table .td-items .ipreview { font-size:11px; color:#94a3b8; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; display:block; max-width:190px; }

/* Status Badge */
.biz-status-badge { display:inline-flex; align-items:center; gap:4px; padding:4px 10px; border-radius:20px; font-size:11px; font-weight:700; letter-spacing:0.3px; white-space:nowrap; }

/* Quick Status Dropdown */
.biz-status-dd { position:relative; display:inline-block; }
.biz-status-dd .dd-trigger { cursor:pointer; }
.biz-status-dd .dd-menu {
    display:none; position:absolute; top:calc(100% + 4px); left:0; background:#fff; border:1px solid #e2e8f0;
    border-radius:10px; box-shadow:0 8px 24px rgba(0,0,0,0.12); z-index:100; min-width:160px; padding:6px 0;
    animation: biz-ord-fadeIn 0.15s ease;
}
.biz-status-dd .dd-menu.open { display:block; }
.biz-status-dd .dd-menu .dd-item {
    display:flex; align-items:center; gap:6px; padding:8px 14px; font-size:12px; font-weight:600;
    color:#374151; cursor:pointer; transition:background 0.15s; white-space:nowrap;
}
.biz-status-dd .dd-menu .dd-item:hover { background:#f1f5f9; }
@keyframes biz-ord-fadeIn { from { opacity:0; transform:translateY(-4px); } to { opacity:1; transform:translateY(0); } }

/* Action Buttons */
.biz-ord-act { width:30px; height:30px; border-radius:7px; border:1px solid #e5e7eb; background:#fff; cursor:pointer; display:inline-flex; align-items:center; justify-content:center; font-size:13px; transition:all 0.2s; color:#64748b; }
.biz-ord-act:hover { background:#f1f5f9; border-color:#cbd5e1; transform:translateY(-1px); }
.biz-ord-act.danger:hover { background:#fef2f2; border-color:#fca5a5; color:#ef4444; }

/* Pagination */
.biz-ord-pag { display:flex; align-items:center; justify-content:space-between; padding:14px 22px; border-top:1px solid #f1f5f9; }
.biz-ord-pag .pg-info { font-size:13px; color:#64748b; }
.biz-ord-pag .pg-btns { display:flex; gap:4px; }
.pg-btn { padding:6px 12px; border:1px solid #d1d5db; border-radius:7px; font-size:12px; font-weight:500; color:#374151; background:#fff; cursor:pointer; transition:all 0.2s; text-decoration:none; }
.pg-btn:hover { background:#f9fafb; border-color:#9ca3af; }
.pg-btn.active { background:#3b82f6; color:#fff; border-color:#3b82f6; font-weight:700; }
.pg-btn:disabled { opacity:0.4; cursor:default; }

/* Buttons */
.biz-ord-btn-primary { background:linear-gradient(135deg,#3b82f6 0%,#2563eb 100%); color:#fff; border:none; padding:9px 20px; border-radius:9px; cursor:pointer; font-size:13px; font-weight:600; display:inline-flex; align-items:center; gap:6px; transition:all 0.3s; box-shadow:0 2px 8px rgba(37,99,235,0.25); }
.biz-ord-btn-primary:hover { transform:translateY(-1px); box-shadow:0 4px 14px rgba(37,99,235,0.35); }
.biz-ord-btn-secondary { background:#fff; color:#374151; border:1px solid #d1d5db; padding:9px 16px; border-radius:9px; cursor:pointer; font-size:13px; font-weight:500; display:inline-flex; align-items:center; gap:6px; transition:all 0.2s; }
.biz-ord-btn-secondary:hover { background:#f9fafb; border-color:#9ca3af; }
.biz-ord-btn-danger { background:#ef4444; color:#fff; border:none; padding:9px 18px; border-radius:9px; cursor:pointer; font-size:13px; font-weight:600; transition:all 0.2s; }
.biz-ord-btn-danger:hover { background:#dc2626; }
.biz-ord-btn-sm { padding:5px 10px; font-size:11px; border-radius:7px; }

/* Detail Panel (slideout from right) */
.biz-ord-panel-overlay { position:fixed; inset:0; background:rgba(0,0,0,0.35); z-index:99998; display:none; backdrop-filter:blur(2px); }
.biz-ord-panel-overlay.open { display:block; }
.biz-ord-panel {
    position:fixed; top:0; right:-620px; width:600px; max-width:100vw; height:100vh;
    background:#fff; z-index:99999; box-shadow:-8px 0 40px rgba(0,0,0,0.15);
    transition: right 0.35s cubic-bezier(0.4,0,0.2,1); overflow-y:auto;
    display:flex; flex-direction:column;
}
.biz-ord-panel.open { right:0; }
.biz-ord-panel-head {
    display:flex; align-items:center; justify-content:space-between; padding:20px 24px;
    border-bottom:1px solid #e2e8f0; background:linear-gradient(135deg,#f8fafc,#f1f5f9);
    position:sticky; top:0; z-index:2;
}
.biz-ord-panel-head h2 { margin:0; font-size:20px; font-weight:700; color:#0f172a; }
.biz-ord-panel-close { width:34px; height:34px; border-radius:9px; border:1px solid #e2e8f0; background:#fff; cursor:pointer; font-size:16px; color:#64748b; display:flex; align-items:center; justify-content:center; transition:all 0.2s; }
.biz-ord-panel-close:hover { background:#f1f5f9; color:#0f172a; }
.biz-ord-panel-body { flex:1; padding:20px 24px; overflow-y:auto; }

/* Panel Sections */
.biz-ord-section { margin-bottom:22px; }
.biz-ord-section-title { font-size:13px; font-weight:700; color:#475569; text-transform:uppercase; letter-spacing:0.04em; margin:0 0 10px; display:flex; align-items:center; gap:6px; }

/* Panel: Customer + Addresses */
.biz-ord-addr-grid { display:grid; grid-template-columns:1fr 1fr; gap:14px; }
.biz-ord-addr-card { background:#f8fafc; border:1px solid #e2e8f0; border-radius:10px; padding:14px; font-size:12px; color:#475569; line-height:1.7; }
.biz-ord-addr-card strong { color:#1e293b; display:block; margin-bottom:4px; font-size:13px; }
.biz-ord-addr-card a { color:#2563eb; text-decoration:none; }
.biz-ord-addr-card a:hover { text-decoration:underline; }

/* Panel: Line Items */
.biz-ord-items-table { width:100%; border-collapse:collapse; font-size:12px; }
.biz-ord-items-table th { background:#f8fafc; color:#64748b; font-weight:700; text-transform:uppercase; letter-spacing:0.04em; padding:8px 10px; border-bottom:1px solid #e2e8f0; text-align:left; font-size:10px; }
.biz-ord-items-table td { padding:10px; border-bottom:1px solid #f1f5f9; vertical-align:middle; }
.biz-ord-items-table .item-img { width:36px; height:36px; border-radius:6px; object-fit:cover; background:#f1f5f9; }
.biz-ord-items-table .item-name { font-weight:600; color:#1e293b; }
.biz-ord-items-table .item-sku { font-size:10px; color:#94a3b8; }

/* Panel: Totals */
.biz-ord-totals { background:#f8fafc; border:1px solid #e2e8f0; border-radius:10px; padding:14px 16px; }
.biz-ord-totals .t-row { display:flex; justify-content:space-between; padding:5px 0; font-size:13px; color:#475569; }
.biz-ord-totals .t-row.grand { font-weight:800; font-size:15px; color:#0f172a; border-top:2px solid #e2e8f0; padding-top:10px; margin-top:6px; }
.biz-ord-totals .t-row.refund { color:#ef4444; }

/* Panel: Notes */
.biz-ord-notes-list { max-height:320px; overflow-y:auto; display:flex; flex-direction:column; gap:8px; margin-bottom:12px; }
.biz-ord-note { padding:10px 12px; border-radius:10px; font-size:12px; line-height:1.6; }
.biz-ord-note.internal { background:#f1f5f9; border:1px solid #e2e8f0; color:#475569; }
.biz-ord-note.customer { background:#ecfdf5; border:1px solid #a7f3d0; color:#065f46; }
.biz-ord-note .note-meta { display:flex; justify-content:space-between; align-items:center; margin-top:6px; font-size:10px; color:#94a3b8; }
.biz-ord-note .note-del { cursor:pointer; color:#ef4444; font-size:10px; font-weight:600; opacity:0; transition:opacity 0.2s; }
.biz-ord-note:hover .note-del { opacity:1; }
.biz-ord-note-form { display:flex; gap:8px; flex-wrap:wrap; }
.biz-ord-note-form textarea { flex:1; min-width:200px; padding:8px 10px; border:1px solid #d1d5db; border-radius:8px; font-size:12px; resize:vertical; min-height:50px; outline:none; }
.biz-ord-note-form textarea:focus { border-color:#3b82f6; box-shadow:0 0 0 3px rgba(59,130,246,0.08); }
.biz-ord-note-type { display:flex; align-items:center; gap:6px; font-size:11px; }
.biz-ord-note-type label { cursor:pointer; }

/* Panel: Refund */
.biz-ord-refund-form { background:#fef2f2; border:1px solid #fecaca; border-radius:10px; padding:14px; display:none; }
.biz-ord-refund-form.open { display:block; }
.biz-ord-refund-form label { font-size:12px; font-weight:600; color:#7f1d1d; display:block; margin-bottom:4px; }
.biz-ord-refund-form input,
.biz-ord-refund-form textarea { width:100%; padding:8px 10px; border:1px solid #fca5a5; border-radius:8px; font-size:13px; background:#fff; outline:none; margin-bottom:10px; }
.biz-ord-refund-form input:focus,
.biz-ord-refund-form textarea:focus { border-color:#ef4444; }

/* Panel: Actions footer */
.biz-ord-panel-footer {
    padding:16px 24px; border-top:1px solid #e2e8f0; display:flex; gap:8px; flex-wrap:wrap;
    position:sticky; bottom:0; background:#fff; z-index:2;
}

/* Modal (generic) */
.biz-ord-modal-overlay { position:fixed; inset:0; display:none; align-items:center; justify-content:center; background:rgba(0,0,0,0.45); z-index:100000; padding:20px; backdrop-filter:blur(3px); }
.biz-ord-modal-overlay.active { display:flex !important; }
.biz-ord-modal { background:#fff; border-radius:14px; box-shadow:0 20px 50px rgba(0,0,0,0.2); width:480px; max-width:100%; animation:biz-ord-fadeIn 0.25s ease; }
.biz-ord-modal-head { padding:20px 24px 0; display:flex; align-items:center; justify-content:space-between; }
.biz-ord-modal-head h3 { margin:0; font-size:18px; font-weight:700; color:#0f172a; }
.biz-ord-modal-body { padding:20px 24px; }
.biz-ord-modal-body label { display:block; font-size:12px; font-weight:600; color:#475569; margin-bottom:4px; }
.biz-ord-modal-body .fg { margin-bottom:14px; }
.biz-ord-modal-body input,
.biz-ord-modal-body select,
.biz-ord-modal-body textarea { width:100%; padding:9px 12px; border:1px solid #d1d5db; border-radius:8px; font-size:13px; background:#fff; outline:none; }
.biz-ord-modal-body input:focus,
.biz-ord-modal-body select:focus,
.biz-ord-modal-body textarea:focus { border-color:#3b82f6; box-shadow:0 0 0 3px rgba(59,130,246,0.08); }
.biz-ord-modal-foot { padding:0 24px 20px; display:flex; justify-content:flex-end; gap:8px; }

/* Loading & Empty */
.biz-ord-loading { padding:60px 20px; text-align:center; color:#94a3b8; }
.biz-ord-loading .spin { display:inline-block; width:32px; height:32px; border:3px solid #e2e8f0; border-top-color:#3b82f6; border-radius:50%; animation:biz-ord-spin 0.7s linear infinite; }
@keyframes biz-ord-spin { to { transform:rotate(360deg); } }
.biz-ord-empty { padding:60px 20px; text-align:center; color:#94a3b8; }
.biz-ord-empty .empty-ico { font-size:48px; margin-bottom:10px; }

/* Toast */
.biz-ord-toast { position:fixed; top:40px; right:24px; padding:12px 20px; border-radius:10px; font-size:13px; font-weight:600; color:#fff; z-index:999999; animation:biz-ord-fadeIn 0.3s ease; box-shadow:0 6px 20px rgba(0,0,0,0.15); }
.biz-ord-toast.success { background:linear-gradient(135deg,#059669,#10b981); }
.biz-ord-toast.error { background:linear-gradient(135deg,#dc2626,#ef4444); }

/* Checkbox */
.biz-ord-cb { width:16px; height:16px; accent-color:#3b82f6; cursor:pointer; }
.biz-ord-chk-wrap { display:flex; align-items:center; gap:6px; font-size:11px; color:#475569; }
.biz-ord-chk-wrap input[type="checkbox"] { width:14px; height:14px; accent-color:#3b82f6; cursor:pointer; }

/* Payment badge */
.biz-ord-pay-badge { display:inline-flex; align-items:center; gap:4px; padding:3px 9px; border-radius:14px; font-size:10px; font-weight:700; background:#f1f5f9; color:#475569; text-transform:capitalize; }

/* Responsive */
@media (max-width:1100px) { .biz-ord-stats { grid-template-columns: repeat(3,1fr); } }
@media (max-width:900px) {
    .biz-ord-charts { grid-template-columns:1fr; }
    .biz-ord-filters { flex-direction:column; align-items:stretch; }
    .biz-ord-addr-grid { grid-template-columns:1fr; }
    .biz-ord-panel { width:100vw; }
}
@media (max-width:600px) {
    .biz-ord-stats { grid-template-columns:1fr; }
    .biz-ord-status-strip { justify-content:center; }
}

/* ===== Create / Edit Order Modal ===== */
.biz-ord-create-overlay { position:fixed; inset:0; background:rgba(15,23,42,0.55); z-index:100020; display:none; justify-content:center; align-items:flex-start; padding:40px 16px; overflow-y:auto; }
.biz-ord-create-overlay.active { display:flex; }
.biz-ord-create-modal { background:#fff; border-radius:16px; width:100%; max-width:780px; box-shadow:0 25px 50px -12px rgba(0,0,0,0.25); animation:biz-ord-slideUp .25s ease; }
@keyframes biz-ord-slideUp { from{opacity:0;transform:translateY(24px);} to{opacity:1;transform:translateY(0);} }
.biz-ord-create-head { display:flex; justify-content:space-between; align-items:center; padding:20px 24px; border-bottom:1px solid #e2e8f0; }
.biz-ord-create-head h2 { margin:0; font-size:20px; font-weight:700; color:#0f172a; }
.biz-ord-create-body { padding:24px; max-height:calc(100vh - 200px); overflow-y:auto; display:flex; flex-direction:column; gap:20px; }
.biz-ord-create-foot { display:flex; justify-content:flex-end; gap:10px; padding:16px 24px; border-top:1px solid #e2e8f0; background:#f8fafc; border-radius:0 0 16px 16px; }
.biz-ord-field-group { display:flex; flex-direction:column; gap:6px; }
.biz-ord-field-group label { font-size:12px; font-weight:600; color:#374151; }
.biz-ord-field-group input, .biz-ord-field-group select, .biz-ord-field-group textarea { padding:9px 12px; border:1px solid #d1d5db; border-radius:10px; font-size:13px; color:#1e293b; transition:border-color .2s; width:100%; background:#fff; }
.biz-ord-field-group input:focus, .biz-ord-field-group select:focus, .biz-ord-field-group textarea:focus { border-color:#3b82f6; outline:none; box-shadow:0 0 0 3px rgba(59,130,246,0.1); }
.biz-ord-field-row { display:grid; grid-template-columns:1fr 1fr; gap:12px; }
.biz-ord-field-row-3 { display:grid; grid-template-columns:1fr 1fr 1fr; gap:12px; }

/* Search box */
.biz-ord-search-wrap { position:relative; }
.biz-ord-search-results { position:absolute; top:100%; left:0; right:0; background:#fff; border:1px solid #e2e8f0; border-radius:10px; box-shadow:0 8px 24px rgba(0,0,0,0.1); max-height:220px; overflow-y:auto; z-index:10; display:none; }
.biz-ord-search-results.active { display:block; }
.biz-ord-sr-item { display:flex; align-items:center; gap:10px; padding:10px 12px; cursor:pointer; font-size:13px; transition:background .15s; border-bottom:1px solid #f1f5f9; }
.biz-ord-sr-item:last-child { border-bottom:none; }
.biz-ord-sr-item:hover { background:#f0f9ff; }
.biz-ord-sr-item img { width:34px; height:34px; border-radius:6px; object-fit:cover; border:1px solid #e2e8f0; }
.biz-ord-sr-item .sr-name { font-weight:600; color:#1e293b; }
.biz-ord-sr-item .sr-sub { font-size:11px; color:#94a3b8; }
.biz-ord-sr-item .sr-price { margin-left:auto; font-weight:700; color:#059669; white-space:nowrap; }

/* Items list in create modal */
.biz-ord-new-items { display:flex; flex-direction:column; gap:6px; }
.biz-ord-new-item { display:flex; align-items:center; gap:10px; padding:10px 12px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:10px; font-size:13px; }
.biz-ord-new-item img { width:36px; height:36px; border-radius:6px; object-fit:cover; }
.biz-ord-new-item .ni-name { flex:1; font-weight:600; color:#1e293b; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.biz-ord-new-item .ni-qty { width:60px; padding:5px 8px; border:1px solid #d1d5db; border-radius:8px; text-align:center; font-size:12px; font-weight:600; }
.biz-ord-new-item .ni-price { width:90px; padding:5px 8px; border:1px solid #d1d5db; border-radius:8px; text-align:right; font-size:12px; }
.biz-ord-new-item .ni-total { min-width:80px; text-align:right; font-weight:700; color:#059669; font-size:13px; }
.biz-ord-new-item .ni-remove { background:none; border:none; font-size:16px; cursor:pointer; color:#ef4444; padding:2px 6px; border-radius:6px; transition:background .15s; }
.biz-ord-new-item .ni-remove:hover { background:#fef2f2; }
.biz-ord-new-total { display:flex; justify-content:flex-end; align-items:center; gap:12px; padding:10px 12px; background:#ecfdf5; border:1px solid #6ee7b7; border-radius:10px; font-size:15px; font-weight:700; color:#059669; }

/* Selected customer card */
.biz-ord-cust-card { display:flex; align-items:center; gap:12px; padding:12px; background:#f0f9ff; border:1px solid #93c5fd; border-radius:10px; }
.biz-ord-cust-card .cc-info { flex:1; }
.biz-ord-cust-card .cc-name { font-weight:700; color:#1e293b; font-size:14px; }
.biz-ord-cust-card .cc-email { font-size:12px; color:#64748b; }
.biz-ord-cust-card .cc-remove { background:none; border:none; cursor:pointer; font-size:14px; color:#6b7280; padding:4px 8px; border-radius:6px; }
.biz-ord-cust-card .cc-remove:hover { background:#fef2f2; color:#ef4444; }

/* Section divider */
.biz-ord-create-divider { font-size:13px; font-weight:700; color:#475569; padding:6px 0 2px; border-bottom:2px solid #e2e8f0; display:flex; align-items:center; gap:6px; }

/* Inline edit in panel */
.biz-ord-edit-btn { background:none; border:none; font-size:11px; cursor:pointer; color:#3b82f6; font-weight:600; margin-left:8px; padding:2px 8px; border-radius:6px; transition:background .15s; }
.biz-ord-edit-btn:hover { background:#eff6ff; }
.biz-ord-addr-form { display:grid; grid-template-columns:1fr 1fr; gap:8px; margin-top:8px; }
.biz-ord-addr-form input { padding:7px 10px; border:1px solid #d1d5db; border-radius:8px; font-size:12px; }
.biz-ord-addr-form input:focus { border-color:#3b82f6; outline:none; }
.biz-ord-inline-search { position:relative; margin-top:8px; }
.biz-ord-inline-search input { width:100%; padding:8px 12px; border:1px solid #d1d5db; border-radius:8px; font-size:12px; }

@media (max-width:600px) {
    .biz-ord-create-modal { max-width:100%; }
    .biz-ord-field-row, .biz-ord-field-row-3 { grid-template-columns:1fr; }
    .biz-ord-addr-form { grid-template-columns:1fr; }
}
</style>

<!-- ===== HERO + STATS ===== -->
<div class="biz-ord-hero">
    <div class="biz-ord-header">
        <div>
            <h1>📦 <?php echo esc_html(bizmart_text('Orders', 'Commandes', 'الطلبات')); ?></h1>
            <p class="subtitle"><?php echo esc_html(bizmart_text('View and manage all WooCommerce orders in one place', 'Visualiser et gérer toutes les commandes WooCommerce', 'عرض وإدارة جميع طلبات WooCommerce في مكان واحد')); ?></p>
        </div>
        <div class="header-actions">
            <button class="biz-ord-btn-primary" onclick="BizOrders.openCreateModal()" title="New Order">➕ <?php echo esc_html(bizmart_text('New Order', 'Nouvelle Commande', 'طلب جديد')); ?></button>
            <button class="biz-ord-btn-secondary" onclick="BizOrders.exportCSV()" title="Export CSV">📥 <?php echo esc_html(bizmart_text('Export', 'Exporter', 'تصدير')); ?></button>
            <button class="biz-ord-btn-secondary" onclick="BizOrders.fetch()" title="Refresh">🔄 <?php echo esc_html(bizmart_text('Refresh', 'Actualiser', 'تحديث')); ?></button>
        </div>
    </div>
    <div class="biz-ord-stats">
        <div class="biz-ord-stat s-green">
            <div class="s-icon">💰</div>
            <div class="s-label"><?php echo esc_html(bizmart_text('Total Sales', 'Ventes Totales', 'إجمالي المبيعات')); ?></div>
            <div class="s-value" id="stat-sales">—</div>
            <div class="s-sub" id="stat-orders-count"></div>
        </div>
        <div class="biz-ord-stat s-blue">
            <div class="s-icon">📈</div>
            <div class="s-label"><?php echo esc_html(bizmart_text('Total Gains', 'Gains Totaux', 'إجمالي الأرباح')); ?></div>
            <div class="s-value" id="stat-gains">—</div>
            <div class="s-sub" id="stat-month-gains"></div>
        </div>
        <div class="biz-ord-stat s-purple">
            <div class="s-icon">📅</div>
            <div class="s-label"><?php echo esc_html(bizmart_text('This Month', 'Ce Mois', 'هذا الشهر')); ?></div>
            <div class="s-value" id="stat-month">—</div>
            <div class="s-sub" id="stat-month-cmp"></div>
        </div>
        <div class="biz-ord-stat s-purple">
            <div class="s-icon">📊</div>
            <div class="s-label"><?php echo esc_html(bizmart_text('Avg. Order', 'Commande Moy.', 'معدل الطلب')); ?></div>
            <div class="s-value" id="stat-avg">—</div>
            <div class="s-sub"><?php echo esc_html(bizmart_text('per order', 'par commande', 'لكل طلب')); ?></div>
        </div>
        <div class="biz-ord-stat s-amber">
            <div class="s-icon">⏳</div>
            <div class="s-label"><?php echo esc_html(bizmart_text('Pending / On Hold', 'En attente', 'قيد الانتظار / معلّقة')); ?></div>
            <div class="s-value" id="stat-pending">—</div>
            <div class="s-sub" id="stat-today"></div>
        </div>
    </div>
</div>

<!-- ===== STATUS STRIP ===== -->
<div class="biz-ord-status-strip" id="status-strip">
    <div class="biz-ord-status-chip-all active" onclick="BizOrders.filterByStatus('')"><?php echo esc_html(bizmart_text('All', 'Tout', 'الكل')); ?> <span class="chip-count" id="strip-all-count">0</span></div>
</div>

<!-- ===== CHARTS ===== -->
<div class="biz-ord-charts">
    <div class="biz-ord-card biz-ord-chart-box">
        <h3>📈 <?php echo esc_html(bizmart_text('Daily Trend (30 days)', 'Tendance (30 jours)', 'الاتجاه اليومي (30 يوم)')); ?></h3>
        <div style="height:220px; position:relative;"><canvas id="ord-trend-chart"></canvas></div>
    </div>
    <div class="biz-ord-card biz-ord-chart-box">
        <h3>💳 <?php echo esc_html(bizmart_text('By Payment Method', 'Par Méthode', 'حسب طريقة الدفع')); ?></h3>
        <div style="height:220px; position:relative;"><canvas id="ord-method-chart"></canvas></div>
    </div>
</div>

<!-- ===== TABLE CARD ===== -->
<div class="biz-ord-card">
    <!-- Filters -->
    <div class="biz-ord-filters">
        <div class="search-wrap">
            <span class="ico">🔍</span>
            <input type="text" id="ord-search" placeholder="<?php echo esc_attr(bizmart_text('Search order #, customer...', 'Rechercher #commande, client...', 'بحث برقم الطلب، العميل...')); ?>" oninput="BizOrders.debounceSearch()">
        </div>
        <select id="ord-filter-status" onchange="BizOrders.filterByStatus(this.value)">
            <option value=""><?php echo esc_html(bizmart_text('All Statuses', 'Tous Statuts', 'كل الحالات')); ?></option>
            <option value="pending"><?php echo esc_html(bizmart_text('Pending', 'En attente', 'قيد الانتظار')); ?></option>
            <option value="processing"><?php echo esc_html(bizmart_text('Processing', 'En cours', 'قيد المعالجة')); ?></option>
            <option value="on-hold"><?php echo esc_html(bizmart_text('On Hold', 'En pause', 'معلّقة')); ?></option>
            <option value="completed"><?php echo esc_html(bizmart_text('Completed', 'Terminée', 'مكتملة')); ?></option>
            <option value="cancelled"><?php echo esc_html(bizmart_text('Cancelled', 'Annulée', 'ملغاة')); ?></option>
            <option value="refunded"><?php echo esc_html(bizmart_text('Refunded', 'Remboursée', 'مستردّة')); ?></option>
            <option value="failed"><?php echo esc_html(bizmart_text('Failed', 'Échouée', 'فاشلة')); ?></option>
        </select>
        <select id="ord-filter-method" onchange="BizOrders.fetch()">
            <option value=""><?php echo esc_html(bizmart_text('All Methods', 'Toutes Méthodes', 'كل الطرق')); ?></option>
        </select>
        <input type="date" id="ord-filter-from" onchange="BizOrders.fetch()">
        <span style="color:#94a3b8; font-size:13px;">→</span>
        <input type="date" id="ord-filter-to" onchange="BizOrders.fetch()">
        <button class="biz-ord-btn-secondary biz-ord-btn-sm" onclick="BizOrders.clearFilters()">✕ <?php echo esc_html(bizmart_text('Clear', 'Effacer', 'مسح')); ?></button>
    </div>

    <!-- Bulk Bar -->
    <div class="biz-ord-bulk" id="ord-bulk-bar">
        <input type="checkbox" class="biz-ord-cb" id="ord-select-all" onchange="BizOrders.toggleSelectAll()">
        <span class="bulk-count" id="ord-bulk-count">0 selected</span>
        <select id="ord-bulk-status">
            <option value=""><?php echo esc_html(bizmart_text('Change status to...', 'Changer statut en...', 'تغيير الحالة إلى...')); ?></option>
            <option value="processing"><?php echo esc_html(bizmart_text('Processing', 'En cours', 'قيد المعالجة')); ?></option>
            <option value="on-hold"><?php echo esc_html(bizmart_text('On Hold', 'En pause', 'معلّقة')); ?></option>
            <option value="completed"><?php echo esc_html(bizmart_text('Completed', 'Terminée', 'مكتملة')); ?></option>
            <option value="cancelled"><?php echo esc_html(bizmart_text('Cancelled', 'Annulée', 'ملغاة')); ?></option>
        </select>
        <button class="biz-ord-btn-primary biz-ord-btn-sm" onclick="BizOrders.bulkAction()"><?php echo esc_html(bizmart_text('Apply', 'Appliquer', 'تطبيق')); ?></button>
    </div>

    <!-- Table -->
    <div style="overflow-x:auto;">
        <table class="biz-ord-table">
            <thead>
                <tr>
                    <th style="width:36px;"><input type="checkbox" class="biz-ord-cb" id="ord-th-cb" onchange="BizOrders.toggleSelectAll()"></th>
                    <th onclick="BizOrders.sort('number')" style="width:70px;"># <span class="sa">↕</span></th>
                    <th onclick="BizOrders.sort('date_created')"><?php echo esc_html(bizmart_text('Date', 'Date', 'التاريخ')); ?> <span class="sa">↕</span></th>
                    <th><?php echo esc_html(bizmart_text('Customer', 'Client', 'العميل')); ?></th>
                    <th><?php echo esc_html(bizmart_text('Items', 'Articles', 'المنتجات')); ?></th>
                    <th onclick="BizOrders.sort('total')" style="text-align:right;"><?php echo esc_html(bizmart_text('Total', 'Total', 'الإجمالي')); ?> <span class="sa">↕</span></th>
                    <th style="text-align:right;"><?php echo esc_html(bizmart_text('Gains', 'Gains', 'الأرباح')); ?></th>
                    <th><?php echo esc_html(bizmart_text('Payment', 'Paiement', 'الدفع')); ?></th>
                    <th onclick="BizOrders.sort('status')"><?php echo esc_html(bizmart_text('Status', 'Statut', 'الحالة')); ?> <span class="sa">↕</span></th>
                    <th style="width:80px; text-align:center;"><?php echo esc_html(bizmart_text('Actions', 'Actions', 'الإجراءات')); ?></th>
                </tr>
            </thead>
            <tbody id="ord-tbody">
                <tr><td colspan="10" class="biz-ord-loading"><div class="spin"></div><p><?php echo esc_html(bizmart_text('Loading...', 'Chargement...', 'جارٍ التحميل...')); ?></p></td></tr>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <div class="biz-ord-pag">
        <div class="pg-info" id="ord-pg-info">—</div>
        <div class="pg-btns" id="ord-pg-btns"></div>
    </div>
</div>

<!-- ===== DETAIL SLIDEOUT PANEL ===== -->
<div class="biz-ord-panel-overlay" id="ord-panel-overlay" onclick="BizOrders.closeDetail()"></div>
<div class="biz-ord-panel" id="ord-panel">
    <div class="biz-ord-panel-head">
        <h2 id="panel-title"><?php echo esc_html(bizmart_text('Order Details', 'Détails Commande')); ?></h2>
        <button class="biz-ord-panel-close" onclick="BizOrders.closeDetail()">✕</button>
    </div>
    <div class="biz-ord-panel-body" id="panel-body">
        <div class="biz-ord-loading"><div class="spin"></div></div>
    </div>
    <div class="biz-ord-panel-footer" id="panel-footer"></div>
</div>

<!-- ===== BULK CONFIRM MODAL ===== -->
<div class="biz-ord-modal-overlay" id="ord-bulk-modal" onclick="if(event.target===this)document.getElementById('ord-bulk-modal').classList.remove('active')">
    <div class="biz-ord-modal">
        <div class="biz-ord-modal-head">
            <h3>⚠️ <?php echo esc_html(bizmart_text('Confirm Bulk Action', 'Confirmer Action')); ?></h3>
        </div>
        <div class="biz-ord-modal-body" style="text-align:center;">
            <p id="bulk-modal-msg" style="font-size:14px; color:#374151;"></p>
        </div>
        <div class="biz-ord-modal-foot" style="justify-content:center;">
            <button class="biz-ord-btn-secondary" onclick="document.getElementById('ord-bulk-modal').classList.remove('active')"><?php echo esc_html(bizmart_text('Cancel', 'Annuler')); ?></button>
            <button class="biz-ord-btn-primary" id="bulk-modal-confirm"><?php echo esc_html(bizmart_text('Confirm', 'Confirmer')); ?></button>
        </div>
    </div>
</div>

<!-- ===== CREATE ORDER MODAL ===== -->
<div class="biz-ord-create-overlay" id="ord-create-overlay" onclick="if(event.target===this)BizOrders.closeCreateModal()">
    <div class="biz-ord-create-modal">
        <div class="biz-ord-create-head">
            <h2 id="create-modal-title">➕ <?php echo esc_html(bizmart_text('New Order', 'Nouvelle Commande', 'طلب جديد')); ?></h2>
            <button class="biz-ord-panel-close" onclick="BizOrders.closeCreateModal()">✕</button>
        </div>
        <div class="biz-ord-create-body">
            <!-- Customer -->
            <div class="biz-ord-create-divider">👤 <?php echo esc_html(bizmart_text('Customer', 'Client', 'العميل')); ?></div>
            <div id="create-customer-area">
                <div class="biz-ord-search-wrap">
                    <input type="text" id="create-cust-search" placeholder="<?php echo esc_attr(bizmart_text('Search customer by name or email...', 'Chercher un client...', 'بحث عن عميل بالاسم أو البريد...')); ?>" autocomplete="off">
                    <div class="biz-ord-search-results" id="create-cust-results"></div>
                </div>
            </div>
            <div id="create-cust-selected" style="display:none;"></div>

            <!-- Products -->
            <div class="biz-ord-create-divider">📦 <?php echo esc_html(bizmart_text('Products', 'Produits', 'المنتجات')); ?></div>
            <div class="biz-ord-search-wrap">
                <input type="text" id="create-prod-search" placeholder="<?php echo esc_attr(bizmart_text('Search product by name, SKU or ID...', 'Chercher un produit...', 'بحث عن منتج بالاسم، SKU أو المعرف...')); ?>" autocomplete="off">
                <div class="biz-ord-search-results" id="create-prod-results"></div>
            </div>
            <div class="biz-ord-new-items" id="create-items-list"></div>
            <div class="biz-ord-new-total" id="create-items-total" style="display:none;"></div>

            <!-- Billing Address -->
            <div class="biz-ord-create-divider">📋 <?php echo esc_html(bizmart_text('Billing Address', 'Adresse de Facturation', 'عنوان الفوترة')); ?></div>
            <div class="biz-ord-field-row">
                <div class="biz-ord-field-group"><label><?php echo esc_html(bizmart_text('First Name', 'Prénom', 'الاسم الأول')); ?></label><input type="text" id="c-bill-fn"></div>
                <div class="biz-ord-field-group"><label><?php echo esc_html(bizmart_text('Last Name', 'Nom', 'اللقب')); ?></label><input type="text" id="c-bill-ln"></div>
            </div>
            <div class="biz-ord-field-group"><label><?php echo esc_html(bizmart_text('Company', 'Entreprise', 'الشركة')); ?></label><input type="text" id="c-bill-company"></div>
            <div class="biz-ord-field-group"><label><?php echo esc_html(bizmart_text('Address', 'Adresse', 'العنوان')); ?></label><input type="text" id="c-bill-addr1"></div>
            <div class="biz-ord-field-group"><label><?php echo esc_html(bizmart_text('Address 2', 'Adresse 2', 'العنوان 2')); ?></label><input type="text" id="c-bill-addr2"></div>
            <div class="biz-ord-field-row-3">
                <div class="biz-ord-field-group"><label><?php echo esc_html(bizmart_text('City', 'Ville', 'المدينة')); ?></label><input type="text" id="c-bill-city"></div>
                <div class="biz-ord-field-group"><label><?php echo esc_html(bizmart_text('Postcode', 'Code Postal', 'الرمز البريدي')); ?></label><input type="text" id="c-bill-zip"></div>
                <div class="biz-ord-field-group"><label><?php echo esc_html(bizmart_text('Country', 'Pays', 'البلد')); ?></label><input type="text" id="c-bill-country" value="MA"></div>
            </div>
            <div class="biz-ord-field-row">
                <div class="biz-ord-field-group"><label>Email</label><input type="email" id="c-bill-email"></div>
                <div class="biz-ord-field-group"><label><?php echo esc_html(bizmart_text('Phone', 'Téléphone', 'الهاتف')); ?></label><input type="text" id="c-bill-phone"></div>
            </div>

            <!-- Shipping Address -->
            <div class="biz-ord-create-divider">🚚 <?php echo esc_html(bizmart_text('Shipping Address', 'Adresse de Livraison', 'عنوان الشحن')); ?>
                <label style="margin-left:auto; font-size:11px; font-weight:500; color:#64748b; display:flex; align-items:center; gap:4px; cursor:pointer;"><input type="checkbox" id="c-same-addr" checked onchange="BizOrders.toggleSameAddr()"> <?php echo esc_html(bizmart_text('Same as billing', 'Identique à facturation', 'نفس عنوان الفوترة')); ?></label>
            </div>
            <div id="create-shipping-fields" style="display:none;">
                <div class="biz-ord-field-row" style="margin-bottom:8px;">
                    <div class="biz-ord-field-group"><label><?php echo esc_html(bizmart_text('First Name', 'Prénom', 'الاسم الأول')); ?></label><input type="text" id="c-ship-fn"></div>
                    <div class="biz-ord-field-group"><label><?php echo esc_html(bizmart_text('Last Name', 'Nom', 'اللقب')); ?></label><input type="text" id="c-ship-ln"></div>
                </div>
                <div class="biz-ord-field-group" style="margin-bottom:8px;"><label><?php echo esc_html(bizmart_text('Address', 'Adresse', 'العنوان')); ?></label><input type="text" id="c-ship-addr1"></div>
                <div class="biz-ord-field-row-3" style="margin-bottom:8px;">
                    <div class="biz-ord-field-group"><label><?php echo esc_html(bizmart_text('City', 'Ville', 'المدينة')); ?></label><input type="text" id="c-ship-city"></div>
                    <div class="biz-ord-field-group"><label><?php echo esc_html(bizmart_text('Postcode', 'Code Postal', 'الرمز البريدي')); ?></label><input type="text" id="c-ship-zip"></div>
                    <div class="biz-ord-field-group"><label><?php echo esc_html(bizmart_text('Country', 'Pays', 'البلد')); ?></label><input type="text" id="c-ship-country" value="MA"></div>
                </div>
            </div>

            <!-- Status & Payment -->
            <div class="biz-ord-create-divider">⚙️ <?php echo esc_html(bizmart_text('Order Settings', 'Paramètres', 'إعدادات الطلب')); ?></div>
            <div class="biz-ord-field-row">
                <div class="biz-ord-field-group">
                    <label><?php echo esc_html(bizmart_text('Status', 'Statut', 'الحالة')); ?></label>
                    <select id="c-status">
                        <option value="pending"><?php echo esc_html(bizmart_text('Pending', 'En attente', 'قيد الانتظار')); ?></option>
                        <option value="processing"><?php echo esc_html(bizmart_text('Processing', 'En cours', 'قيد المعالجة')); ?></option>
                        <option value="on-hold"><?php echo esc_html(bizmart_text('On Hold', 'En pause', 'معلّقة')); ?></option>
                        <option value="completed"><?php echo esc_html(bizmart_text('Completed', 'Terminée', 'مكتملة')); ?></option>
                    </select>
                </div>
                <div class="biz-ord-field-group">
                    <label><?php echo esc_html(bizmart_text('Payment Method', 'Méthode de Paiement', 'طريقة الدفع')); ?></label>
                    <select id="c-payment"><option value=""><?php echo esc_html(bizmart_text('None', 'Aucune', 'بدون')); ?></option></select>
                </div>
            </div>
            <div class="biz-ord-field-group">
                <label><?php echo esc_html(bizmart_text('Customer Note', 'Note Client', 'ملاحظة العميل')); ?></label>
                <textarea id="c-note" rows="2" placeholder="<?php echo esc_attr(bizmart_text('Optional note...', 'Note optionnelle...', 'ملاحظة اختيارية...')); ?>"></textarea>
            </div>
        </div>
        <div class="biz-ord-create-foot">
            <button class="biz-ord-btn-secondary" onclick="BizOrders.closeCreateModal()"><?php echo esc_html(bizmart_text('Cancel', 'Annuler', 'إلغاء')); ?></button>
            <button class="biz-ord-btn-primary" id="create-order-submit" onclick="BizOrders.submitCreateOrder()">✅ <?php echo esc_html(bizmart_text('Create Order', 'Créer Commande', 'إنشاء طلب')); ?></button>
        </div>
    </div>
</div>

<!-- ===== JAVASCRIPT ===== -->
<script>
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,

    // --- Helpers ---
    t(en, fr, ar) { const l = BizOrdersConfig.lang; return l === 'ar' ? (ar || en) : l === 'fr' ? (fr || en) : en; },
    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; },

    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();
        }).fail(() => this.showError('Network error'));
    },

    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 = o.date_created ? new Date(o.date_created.replace(' ','T')) : null;
            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) {
        this.renderTrendChart(d.daily_trend || []);
        this.renderMethodDonut(d.payment_methods || []);
    },

    renderTrendChart(data) {
        const ctx = document.getElementById('ord-trend-chart');
        if (!ctx) return;
        if (this.trendChart) this.trendChart.destroy();
        const labels = data.map(r => { const dt = new Date(r.day+'T00:00:00'); 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);
        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} }
                }
            }
        });
    },

    renderMethodDonut(stats) {
        const ctx = document.getElementById('ord-method-chart');
        if (!ctx) return;
        if (this.methodChart) this.methodChart.destroy();
        if (!stats || stats.length === 0) return;
        const colors = ['#3b82f6','#059669','#f59e0b','#8b5cf6','#ef4444','#ec4899','#6b7280'];
        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) } } }
            }
        });
    },

    // --- 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(() => this.toast('Network error', '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;
        $('#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(() => { $('#panel-body').html('<p style="color:#ef4444;">Network error</p>'); });
    },

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

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

        const dt = o.date_created ? new Date(o.date_created.replace(' ','T')).toLocaleDateString('fr-FR',{day:'2-digit',month:'long',year:'numeric',hour:'2-digit',minute:'2-digit'}) : '—';
        const dtPaid = o.date_paid ? new Date(o.date_paid.replace(' ','T')).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 rd = r.date ? new Date(r.date.replace(' ','T')).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 nd = n.date ? new Date(n.date.replace(' ','T')).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('post.php?post=${o.id}&action=edit', '_blank')">🔗 ${this.t('WC Edit','Éditer WC','تعديل WC')}</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(() => {
            $('#create-order-submit').prop('disabled', false).text('✅ ' + this.t('Create Order','Créer Commande','إنشاء طلب'));
            this.toast('Network error', '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 =====
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'));
    }
});

});
</script>
</div>
