<?php
/**
 * Bizmart — Orders admin page.
 *
 * @package Bizmart
 * @license GPL-2.0-or-later
 */
if (!defined('ABSPATH')) exit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
if (!class_exists('WooCommerce')) {
    echo '<div class="wrap"><div class="notice notice-error"><p><strong>Bizmart:</strong> WooCommerce is required.</p></div></div>';
    return;
}

(static function() {
$currency_symbol = function_exists('bizmart_get_currency_symbol') ? html_entity_decode(bizmart_get_currency_symbol(), ENT_QUOTES, 'UTF-8') : '€';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$order_id_param = isset($_GET['order_id']) ? (int) absint(wp_unslash($_GET['order_id'])) : 0;

// Chart.js is enqueued centrally via admin_enqueue_scripts hook in bizmart-cost-of-goods.php
?>
<div class="biz-ord-wrap">
<?php
wp_enqueue_style('bizmart-orders-css', BIZMART_CORE_URL . 'assets/orders.css', ['bizmart-admin-css'], BIZMART_CORE_VERSION);
wp_enqueue_script('bizmart-orders-js', BIZMART_CORE_URL . 'assets/orders.js', ['jquery', 'bizmart-chartjs'], BIZMART_CORE_VERSION, true);
wp_localize_script('bizmart-orders-js', 'BizOrdersConfig', [
    'ajaxUrl' => admin_url('admin-ajax.php'),
    'nonce' => wp_create_nonce('bizmart-analytics-nonce'),
    'currency' => function_exists('get_woocommerce_currency_symbol') ? get_woocommerce_currency_symbol() : '$',
    'currencySymbol' => function_exists('get_woocommerce_currency_symbol') ? get_woocommerce_currency_symbol() : '$',
    'currencyPosition' => get_option('woocommerce_currency_pos'),
    'thousandSeparator' => function_exists('wc_get_price_thousand_separator') ? wc_get_price_thousand_separator() : ',',
    'decimalSeparator' => function_exists('wc_get_price_decimal_separator') ? wc_get_price_decimal_separator() : '.',
    'decimals' => function_exists('wc_get_price_decimals') ? absint(wc_get_price_decimals()) : 2,
    'initialOrderId' => $order_id_param,
    'lang' => function_exists('bizmart_admin_lang') ? bizmart_admin_lang() : 'en',
    'statuses' => [
        'pending'    => [ 'label' => bizmart_text('Pending','En attente','قيد الانتظار'),    'color' => '#f59e0b', 'bg' => '#fffbeb', 'icon' => '⏳' ],
        'processing' => [ 'label' => bizmart_text('Processing','En cours','قيد المعالجة'),   'color' => '#3b82f6', 'bg' => '#eff6ff', 'icon' => '⚙️' ],
        'on-hold'    => [ 'label' => bizmart_text('On Hold','En pause','معلّقة'),      'color' => '#f97316', 'bg' => '#fff7ed', 'icon' => '⏸️' ],
        'completed'  => [ 'label' => bizmart_text('Completed','Terminée','مكتملة'),    'color' => '#059669', 'bg' => '#ecfdf5', 'icon' => '✅' ],
        'cancelled'  => [ 'label' => bizmart_text('Cancelled','Annulée','ملغاة'),     'color' => '#ef4444', 'bg' => '#fef2f2', 'icon' => '❌' ],
        'refunded'   => [ 'label' => bizmart_text('Refunded','Remboursée','مستردّة'),   'color' => '#8b5cf6', 'bg' => '#f5f3ff', 'icon' => '↩️' ],
        'failed'     => [ 'label' => bizmart_text('Failed','Échouée','فاشلة'),        'color' => '#6b7280', 'bg' => '#f9fafb', 'icon' => '⚠️' ]
    ]
]);
?>

<!-- Orders CSS moved to assets/orders.css -->

<!-- ===== 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-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 ===== -->
<!-- Orders JS script moved to assets/orders.js -->
</div>
<?php })(); ?>
