<?php
/**
 * DZQCOD Integrations — Google Sheets, Zapier, Tracking, Reviews, Popup, Multi-step
 */
namespace DZQCOD;
defined('ABSPATH') || exit;

class Integrations {
    public function __construct() {
        // Google Sheets sync
        add_action('dzqcod_order_created', [$this, 'sheets_sync'], 40, 2);
        add_action('woocommerce_order_status_changed', [$this, 'sheets_status_sync'], 40, 4);
        // Zapier/Make webhook
        add_action('dzqcod_order_created', [$this, 'webhook_fire'], 50, 2);
        add_action('woocommerce_order_status_changed', [$this, 'webhook_status'], 10, 4);
        // Tracking page
        add_shortcode('dzqcod_tracking', [$this, 'tracking_shortcode']);
        add_action('wp_ajax_dzqcod_track_order', [$this, 'track_order']);
        add_action('wp_ajax_nopriv_dzqcod_track_order', [$this, 'track_order']);
        // Reviews
        add_action('wp_ajax_dzqcod_submit_review', [$this, 'submit_review']);
        add_action('wp_ajax_nopriv_dzqcod_submit_review', [$this, 'submit_review']);
        add_shortcode('dzqcod_reviews', [$this, 'reviews_shortcode']);
        // Popup form
        add_action('wp_footer', [$this, 'popup_form']);
        // Settings
        add_action('wp_ajax_dzqcod_save_integrations', [$this, 'save_settings']);
        // CRM sync
        add_action('dzqcod_order_created', [$this, 'crm_sync'], 45, 2);
        add_action('wp_ajax_dzqcod_crm_save', [$this, 'crm_save']);
        // Retargeting
        add_action('wp_ajax_dzqcod_retarget_build', [$this, 'retarget_build_audience']);
        // Export Excel + Import
        add_action('wp_ajax_dzqcod_export_excel', [$this, 'export_excel']);
        add_action('wp_ajax_dzqcod_import_orders', [$this, 'import_orders']);
        // Webhook retry cron
        add_action('dzqcod_webhook_retry', [$this, 'webhook_retry_handler'], 10, 4);
    }

    // ═══════════════════════════════════════════════
    //  GOOGLE SHEETS SYNC
    // ═══════════════════════════════════════════════
    public function sheets_sync(int $oid, $order): void {
        if (Core::opt('sheets_enabled', '') !== 'yes') return;
        $webhook = Core::opt('sheets_webhook_url', '');
        if (!$webhook) return;

        $items = []; $colors = []; $sizes = [];
        foreach ($order->get_items() as $i) {
            $items[] = $i->get_name(); $cl = $i->get_meta('اللون'); $sz = $i->get_meta('المقاس');
            if ($cl) $colors[] = $cl; if ($sz) $sizes[] = $sz;
        }

        $data = [
            'order_id' => $oid, 'date' => $order->get_date_created() ? $order->get_date_created()->format('Y-m-d H:i') : '',
            'name' => $order->get_billing_first_name(), 'phone' => $order->get_billing_phone(),
            'phone2' => $order->get_meta('_dzqcod_phone2'), 'wilaya' => $order->get_shipping_state(),
            'commune' => $order->get_shipping_city(), 'address' => $order->get_shipping_address_1(),
            'products' => implode(', ', $items), 'colors' => implode(', ', $colors), 'sizes' => implode(', ', $sizes),
            'quantity' => array_sum(array_map(fn($i) => $i->get_quantity(), $order->get_items())),
            'subtotal' => (float)$order->get_subtotal(), 'shipping' => (float)$order->get_shipping_total(),
            'total' => (float)$order->get_total(), 'payment' => $order->get_payment_method_title() ?: 'COD',
            'status' => $order->get_status(), 'fraud_score' => (int)$order->get_meta('_dzqcod_fraud_score'),
            'utm_source' => $order->get_meta('_dzqcod_utm_source'), 'utm_campaign' => $order->get_meta('_dzqcod_utm_campaign'),
            'notes' => $order->get_customer_note(),
            // Custom product data
            'custom_dimensions' => $order->get_meta('_dzqcod_custom_dimensions'),
            'custom_options' => $order->get_meta('_dzqcod_custom_options'),
            'files' => $order->get_meta('_dzqcod_uploaded_files'),
        ];

        wp_remote_post($webhook, ['headers' => ['Content-Type' => 'application/json'],
            'body' => wp_json_encode($data), 'timeout' => 10, 'blocking' => false]);
    }

    // ═══════════════════════════════════════════════
    //  ZAPIER / MAKE WEBHOOK
    // ═══════════════════════════════════════════════
    public function webhook_fire(int $oid, $order): void {
        $url = Core::opt('zapier_webhook_url', '');
        if (!$url) return;
        $items = []; foreach ($order->get_items() as $i) $items[] = ['name' => $i->get_name(), 'qty' => $i->get_quantity(), 'total' => (float)$i->get_total()];
        $payload = wp_json_encode(['event' => 'order_created', 'order_id' => $oid, 'name' => $order->get_billing_first_name(),
            'phone' => $order->get_billing_phone(), 'wilaya' => $order->get_shipping_state(),
            'total' => (float)$order->get_total(), 'items' => $items, 'status' => $order->get_status(),
            'timestamp' => current_time('mysql')]);
        $this->webhook_send_with_retry($url, $payload, 'order_created', $oid);
    }

    public function webhook_status(int $oid, string $from, string $to, $order): void {
        $url = Core::opt('zapier_webhook_url', '');
        if (!$url) return;
        $tracking = $order->get_meta('_dzqcod_tracking_number') ?: '';
        $payload = wp_json_encode(['event' => 'status_changed', 'order_id' => $oid, 'from' => str_replace('wc-', '', $from),
            'to' => str_replace('wc-', '', $to), 'status_label' => Core::ST[str_replace('wc-', '', $to)]['l'] ?? $to,
            'name' => $order->get_billing_first_name(), 'phone' => $order->get_billing_phone(),
            'total' => (float)$order->get_total(), 'tracking' => $tracking, 'timestamp' => current_time('mysql')]);
        $this->webhook_send_with_retry($url, $payload, 'status_changed', $oid);
    }

    private function webhook_send_with_retry(string $url, string $payload, string $event, int $oid): void {
        $r = wp_remote_post($url, ['headers' => ['Content-Type' => 'application/json'], 'body' => $payload, 'timeout' => 10]);
        $code = !is_wp_error($r) ? wp_remote_retrieve_response_code($r) : 0;
        $ok = $code >= 200 && $code < 300;
        // Log webhook
        global $wpdb;
        $t = $wpdb->prefix . \DZQCOD_DB . 'message_logs';
        if ($wpdb->get_var("SHOW TABLES LIKE '{$t}'")) {
            $wpdb->insert($t, ['order_id' => $oid, 'channel' => 'webhook', 'phone' => $url,
                'body' => substr($payload, 0, 500), 'status' => $ok ? 'sent' : 'failed:' . $code, 'template' => $event]);
        }
        // Retry once after 30s if failed
        if (!$ok) {
            wp_schedule_single_event(time() + 30, 'dzqcod_webhook_retry', [$url, $payload, $event, $oid]);
        }
    }

    // ═══════════════════════════════════════════════
    //  TRACKING PAGE — Customer-facing
    // ═══════════════════════════════════════════════
    public function tracking_shortcode(): string {
        ob_start(); ?>
<div class="dzqcod-tracking" dir="rtl" style="max-width:500px;margin:20px auto;font-family:Arial,Tahoma,sans-serif">
<div style="text-align:center;padding:20px;background:linear-gradient(135deg,#667eea,#764ba2);border-radius:16px 16px 0 0;color:#fff">
<h2 style="margin:0">📦 تتبع طلبك</h2></div>
<div style="padding:20px;background:#fff;border:1px solid #e0e0e0;border-radius:0 0 16px 16px">
<div style="display:flex;gap:8px"><input type="text" id="dzt-phone" placeholder="رقم الهاتف" style="flex:1;padding:12px;border:1px solid #ddd;border-radius:10px;font-size:15px">
<button id="dzt-search" style="padding:12px 20px;background:#667eea;color:#fff;border:none;border-radius:10px;cursor:pointer;font-weight:700">🔍 بحث</button></div>
<div id="dzt-results" style="margin-top:16px"></div></div></div>
<script>jQuery(function($){$('#dzt-search').on('click',function(){var ph=$('#dzt-phone').val();if(!ph)return;
$(this).prop('disabled',true).text('⏳');
$.post('<?php echo esc_url(admin_url("admin-ajax.php")); ?>',{action:'dzqcod_track_order',phone:ph},function(r){
$('#dzt-search').prop('disabled',false).text('🔍 بحث');if(!r.success)return $('#dzt-results').html('<p style="color:red">'+r.data.message+'</p>');
var h='';r.data.orders.forEach(function(o){
var colors={delivered:'#27ae60',shipped:'#3498db',confirmed:'#2ecc71','pending-call':'#f39c12','in-transit':'#9b59b6',rto:'#e74c3c'};
h+='<div style="border:1px solid #eee;border-radius:10px;padding:12px;margin-bottom:8px;border-right:4px solid '+(colors[o.status]||'#999')+'">';
h+='<div style="display:flex;justify-content:space-between"><strong>#'+o.id+'</strong><span style="background:'+(colors[o.status]||'#999')+';color:#fff;padding:2px 10px;border-radius:10px;font-size:12px">'+o.status_label+'</span></div>';
h+='<div style="font-size:13px;margin-top:6px">🛍 '+o.items+'</div>';
h+='<div style="font-size:13px">💰 '+o.total+' دج</div>';
if(o.tracking)h+='<div style="font-size:13px">📍 تتبع: '+o.tracking+'</div>';
h+='<div style="font-size:11px;color:#888;margin-top:4px">'+o.date+'</div></div>';});
$('#dzt-results').html(h||'<p>لا توجد طلبات</p>')})})});</script>
        <?php return ob_get_clean();
    }

    public function track_order(): void {
        $phone = sanitize_text_field($_POST['phone'] ?? '');
        if (!$phone) wp_send_json_error(['message' => 'أدخل رقم الهاتف']);
        $orders = wc_get_orders(['billing_phone' => $phone, 'limit' => 10, 'orderby' => 'date', 'order' => 'DESC']);
        if (empty($orders)) wp_send_json_error(['message' => 'لا توجد طلبات بهذا الرقم']);

        $result = [];
        foreach ($orders as $o) {
            $items = []; foreach ($o->get_items() as $i) $items[] = $i->get_name();
            $st = str_replace('wc-', '', $o->get_status());
            $result[] = ['id' => $o->get_id(), 'status' => $st,
                'status_label' => Core::ST[$st]['l'] ?? $st, 'items' => implode(', ', $items),
                'total' => number_format((float)$o->get_total(), 0),
                'tracking' => $o->get_meta('_dzqcod_tracking_number') ?: '',
                'date' => $o->get_date_created() ? $o->get_date_created()->format('Y-m-d H:i') : ''];
        }
        wp_send_json_success(['orders' => $result]);
    }

    // ═══════════════════════════════════════════════
    //  REVIEWS & RATINGS
    // ═══════════════════════════════════════════════
    public function submit_review(): void {
        $oid = absint($_POST['order_id'] ?? 0);
        $rating = min(5, max(1, absint($_POST['rating'] ?? 5)));
        $text = sanitize_textarea_field($_POST['review'] ?? '');
        $phone = sanitize_text_field($_POST['phone'] ?? '');

        $order = wc_get_order($oid);
        if (!$order || $order->get_billing_phone() !== $phone) wp_send_json_error(['message' => 'طلب غير صالح']);

        global $wpdb;
        $t = $wpdb->prefix . \DZQCOD_DB . 'reviews';
        $wpdb->query("CREATE TABLE IF NOT EXISTS {$t} (
            id BIGINT AUTO_INCREMENT PRIMARY KEY, order_id BIGINT, product_id BIGINT,
            phone VARCHAR(20), name VARCHAR(100), rating TINYINT DEFAULT 5,
            review TEXT, status ENUM('pending','approved','rejected') DEFAULT 'pending',
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP, INDEX(product_id,status)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

        foreach ($order->get_items() as $item) {
            $wpdb->insert($t, ['order_id' => $oid, 'product_id' => $item->get_product_id(),
                'phone' => $phone, 'name' => $order->get_billing_first_name(),
                'rating' => $rating, 'review' => $text]);
        }
        wp_send_json_success(['message' => 'شكراً! تم إرسال تقييمك 💝']);
    }

    public function reviews_shortcode(array $a = []): string {
        $a = shortcode_atts(['product_id' => 0, 'limit' => 10], $a);
        $pid = absint($a['product_id']);
        if (!$pid) { global $product; if ($product) $pid = $product->get_id(); }
        if (!$pid) return '';

        global $wpdb;
        $t = $wpdb->prefix . \DZQCOD_DB . 'reviews';
        $reviews = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$t} WHERE product_id=%d AND status='approved' ORDER BY created_at DESC LIMIT %d", $pid, (int)$a['limit']));
        $avg = $wpdb->get_var($wpdb->prepare("SELECT AVG(rating) FROM {$t} WHERE product_id=%d AND status='approved'", $pid));

        ob_start(); ?>
<div class="dzqcod-reviews" dir="rtl" style="margin:20px 0">
<?php if ($avg): ?><div style="font-size:18px;font-weight:700;margin-bottom:10px"><?php echo esc_html(str_repeat('⭐', round($avg))); ?> <?php echo number_format((float)$avg, 1); ?>/5 (<?php echo count($reviews); ?> تقييم)</div><?php endif; ?>
<?php foreach ($reviews as $r): ?>
<div style="border:1px solid #eee;border-radius:10px;padding:12px;margin-bottom:8px">
<div style="display:flex;justify-content:space-between"><strong><?php echo esc_html($r->name); ?></strong><span><?php echo esc_html(str_repeat('⭐', $r->rating)); ?></span></div>
<?php if ($r->review): ?><p style="font-size:13px;margin:6px 0 0;color:#555"><?php echo esc_html($r->review); ?></p><?php endif; ?>
</div>
<?php endforeach; if (empty($reviews)): ?><p style="color:#888">لا توجد تقييمات بعد</p><?php endif; ?>
</div>
        <?php return ob_get_clean();
    }

    // ═══════════════════════════════════════════════
    //  POPUP FORM
    // ═══════════════════════════════════════════════
    public function popup_form(): void {
        if (Core::opt('popup_enabled', '') !== 'yes') return;
        if (is_admin()) return;
        $pid = absint(Core::opt('popup_product_id', '0'));
        if (!$pid || !wc_get_product($pid)) return;
        $delay = max(1, (int)Core::opt('popup_delay', '5'));
        $pages = Core::opt('popup_pages', 'all');
        $trigger = Core::opt('popup_trigger', 'delay'); // delay, scroll, exit
        $scroll_pct = (int)Core::opt('popup_scroll_pct', '50');
        if ($pages === 'home' && !is_front_page()) return;
        if ($pages === 'shop' && !is_shop() && !is_product_category()) return;
        if ($pages === 'product' && !is_product()) return;
        // Don't show if already ordered or dismissed
        ?>
<div id="dzqcod-popup-overlay" style="display:none;position:fixed;inset:0;background:rgba(15,23,42,.7);z-index:999999;justify-content:center;align-items:center;padding:16px;backdrop-filter:blur(4px)">
<div id="dzqcod-popup-inner" style="background:#fff;border-radius:20px;max-width:500px;width:100%;max-height:85vh;overflow-y:auto;position:relative;padding:16px;box-shadow:0 20px 60px rgba(0,0,0,.3);animation:dzqPopIn .4s ease">
<button id="dzqcod-popup-close" style="position:sticky;top:0;float:left;background:#f1f5f9;border:none;width:36px;height:36px;border-radius:50%;font-size:18px;cursor:pointer;z-index:2;display:flex;align-items:center;justify-content:center;transition:.2s;margin-bottom:8px" onmouseover="this.style.background='#fee2e2';this.style.color='#ef4444'" onmouseout="this.style.background='#f1f5f9';this.style.color='inherit'">✕</button>
<?php echo wp_kses_post(Core::inst()->build_form_public($pid, true)); ?>
</div></div>
<style>
@keyframes dzqPopIn{from{opacity:0;transform:scale(.9) translateY(30px)}to{opacity:1;transform:none}}
#dzqcod-popup-overlay{scrollbar-width:thin}
</style>
<script>
(function(){
    var shown=false,overlay=document.getElementById('dzqcod-popup-overlay');
    if(!overlay||sessionStorage.getItem('dzqcod_popup_closed'))return;
    var freqHours=<?php echo (int)Core::opt('popup_frequency_hours', 24); ?>;
    var lastShown=localStorage.getItem('dzqcod_popup_last');
    if(lastShown&&(Date.now()-parseInt(lastShown))<freqHours*3600000)return;
    function showPopup(){
        if(shown)return;shown=true;
        overlay.style.display='flex';
    }
    function closePopup(){
        overlay.style.display='none';
        sessionStorage.setItem('dzqcod_popup_closed','1');
        localStorage.setItem('dzqcod_popup_last',Date.now().toString());
    }
    // Close button
    document.getElementById('dzqcod-popup-close').addEventListener('click',closePopup);
    // Click backdrop to close
    overlay.addEventListener('click',function(e){if(e.target===overlay)closePopup()});
    // ESC key to close
    document.addEventListener('keydown',function(e){if(e.key==='Escape'&&overlay.style.display==='flex')closePopup()});
    // Trigger
    var trigger='<?php echo esc_html(esc_js($trigger)); ?>';
    if(trigger==='scroll'){
        window.addEventListener('scroll',function(){
            var h=document.documentElement.scrollHeight-window.innerHeight;
            if(h>0&&(window.scrollY/h*100)>=<?php echo esc_html($scroll_pct); ?>)showPopup();
        });
    }else if(trigger==='exit'){
        document.addEventListener('mouseleave',function(e){if(e.clientY<0)showPopup()});
    }else{
        setTimeout(showPopup,<?php echo esc_html($delay*1000); ?>);
    }
})();
</script>
        <?php
    }

    // ═══════════════════════════════════════════════
    //  GOOGLE SHEETS — Status update sync
    // ═══════════════════════════════════════════════
    public function sheets_status_sync(int $oid, string $from, string $to, $order): void {
        if (Core::opt('sheets_enabled', '') !== 'yes') return;
        $webhook = Core::opt('sheets_webhook_url', '');
        if (!$webhook) return;
        $tracking = $order->get_meta('_dzqcod_tracking_number') ?: '';
        wp_remote_post($webhook, ['headers' => ['Content-Type' => 'application/json'],
            'body' => wp_json_encode(['event' => 'status_update', 'order_id' => $oid,
                'old_status' => str_replace('wc-', '', $from), 'new_status' => str_replace('wc-', '', $to),
                'status_label' => Core::ST[str_replace('wc-', '', $to)]['l'] ?? $to,
                'tracking' => $tracking, 'phone' => $order->get_billing_phone(),
                'total' => (float)$order->get_total(), 'timestamp' => current_time('mysql')]),
            'timeout' => 10, 'blocking' => false]);
    }

    // ═══════════════════════════════════════════════
    //  CRM INTEGRATION — HubSpot / Zoho sync
    // ═══════════════════════════════════════════════
    public function crm_save(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        if (!current_user_can('manage_options')) wp_send_json_error();
        foreach (['crm_provider', 'crm_api_key', 'crm_auto_sync'] as $k) {
            if (isset($_POST[$k])) update_option('dzqcod_' . $k, sanitize_text_field($_POST[$k]), false);
        }
        wp_send_json_success(['message' => 'تم حفظ إعدادات CRM ✅']);
    }

    public function crm_sync(int $oid, $order): void {
        if (Core::opt('crm_auto_sync', '') !== 'yes') return;
        $provider = Core::opt('crm_provider', '');
        $api_key = Core::opt('crm_api_key', '');
        if (!$provider || !$api_key) return;

        $contact = [
            'firstname' => $order->get_billing_first_name(),
            'lastname' => $order->get_billing_last_name(),
            'phone' => $order->get_billing_phone(),
            'email' => $order->get_billing_email(),
            'city' => $order->get_shipping_city(),
            'state' => $order->get_shipping_state(),
        ];

        switch ($provider) {
            case 'hubspot':
                // Create/update contact
                wp_remote_post('https://api.hubapi.com/crm/v3/objects/contacts', [
                    'headers' => ['Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json'],
                    'body' => wp_json_encode(['properties' => $contact]),
                    'timeout' => 15, 'blocking' => false
                ]);
                // Create deal
                $items = []; foreach ($order->get_items() as $i) $items[] = $i->get_name();
                wp_remote_post('https://api.hubapi.com/crm/v3/objects/deals', [
                    'headers' => ['Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json'],
                    'body' => wp_json_encode(['properties' => ['dealname' => 'طلب #' . $oid, 'amount' => (float)$order->get_total(),
                        'pipeline' => 'default', 'dealstage' => 'appointmentscheduled',
                        'description' => implode(', ', $items)]]),
                    'timeout' => 15, 'blocking' => false
                ]);
                break;
            case 'zoho':
                wp_remote_post('https://www.zohoapis.com/crm/v2/Contacts', [
                    'headers' => ['Authorization' => 'Zoho-oauthtoken ' . $api_key, 'Content-Type' => 'application/json'],
                    'body' => wp_json_encode(['data' => [['First_Name' => $contact['firstname'], 'Last_Name' => $contact['lastname'] ?: 'عميل',
                        'Phone' => $contact['phone'], 'Email' => $contact['email'], 'City' => $contact['city']]]]),
                    'timeout' => 15, 'blocking' => false
                ]);
                break;
        }
    }

    // ═══════════════════════════════════════════════
    //  RETARGETING — Build custom audiences
    // ═══════════════════════════════════════════════
    public function retarget_build_audience(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        $type = sanitize_key($_POST['type'] ?? 'rto'); // rto, abandoned, repeat, high_value
        $days = (int)($_POST['days'] ?? 30);
        $from = gmdate('Y-m-d', strtotime("-{$days} days"));
        $phones = [];

        switch ($type) {
            case 'rto': // RTO customers — retarget with better offers
                $orders = wc_get_orders(['status' => 'wc-rto', 'date_created' => '>' . $from, 'limit' => -1]);
                foreach ($orders as $o) $phones[$o->get_billing_phone()] = true;
                break;
            case 'abandoned': // Started but didn't complete
                global $wpdb;
                $t = $wpdb->prefix . \DZQCOD_DB . 'abandoned_carts';
                if ($wpdb->get_var("SHOW TABLES LIKE '{$t}'")) {
                    $rows = $wpdb->get_results("SELECT DISTINCT phone FROM {$t} WHERE recovery_status='pending' AND created_at > '{$from}'");
                    foreach ($rows as $r) $phones[$r->phone] = true;
                }
                break;
            case 'repeat': // Repeat buyers — upsell
                $orders = wc_get_orders(['status' => 'wc-delivered', 'date_created' => '>' . $from, 'limit' => -1]);
                $counts = [];
                foreach ($orders as $o) { $p = $o->get_billing_phone(); $counts[$p] = ($counts[$p] ?? 0) + 1; }
                $phones = array_filter($counts, fn($c) => $c >= 2);
                break;
            case 'high_value': // High value customers
                $orders = wc_get_orders(['status' => 'wc-delivered', 'date_created' => '>' . $from, 'limit' => -1]);
                foreach ($orders as $o) { if ((float)$o->get_total() >= 5000) $phones[$o->get_billing_phone()] = true; }
                break;
        }

        $phone_list = array_keys($phones);
        // Hash for Meta Custom Audience
        $hashed = array_map(fn($p) => hash('sha256', preg_replace('/^0/', '213', preg_replace('/[^0-9]/', '', $p))), $phone_list);

        wp_send_json_success([
            'type' => $type, 'count' => count($phone_list),
            'phones' => $phone_list, 'hashed_phones' => $hashed,
            'csv' => implode("\n", $phone_list),
            'message' => count($phone_list) . ' رقم هاتف — جاهز للرفع كـ Custom Audience'
        ]);
    }

    // ═══════════════════════════════════════════════
    //  EXPORT EXCEL (.xlsx via CSV with BOM)
    // ═══════════════════════════════════════════════
    public function export_excel(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        if (!current_user_can('manage_woocommerce')) wp_send_json_error();

        $format = sanitize_key($_POST['format'] ?? 'csv'); // csv or tsv (Excel opens TSV natively)
        $statuses = $_POST['statuses'] ?? ['wc-pending-call', 'wc-confirmed', 'wc-shipped', 'wc-delivered'];
        $from = sanitize_text_field($_POST['from'] ?? '');
        $to = sanitize_text_field($_POST['to'] ?? '');

        $args = ['status' => array_map('sanitize_text_field', (array)$statuses), 'limit' => -1, 'orderby' => 'date'];
        if ($from) $args['date_created'] = $from . '...' . ($to ?: gmdate('Y-m-d', strtotime('+1 day')));

        $orders = wc_get_orders($args);
        $rows = [];
        $headers = ['ID', 'الاسم', 'الهاتف', 'هاتف2', 'الولاية', 'البلدية', 'العنوان', 'المنتجات', 'الألوان', 'المقاسات',
            'الكمية', 'المبلغ الفرعي', 'الشحن', 'الإجمالي', 'الحالة', 'الدفع', 'الاحتيال', 'التتبع', 'الشركة', 'التاريخ'];

        foreach ($orders as $o) {
            $items = []; $colors = []; $sizes = []; $qtys = 0;
            foreach ($o->get_items() as $i) {
                $items[] = $i->get_name(); $qtys += $i->get_quantity();
                $cl = $i->get_meta('اللون'); $sz = $i->get_meta('المقاس');
                if ($cl) $colors[] = $cl; if ($sz) $sizes[] = $sz;
            }
            $rows[] = [$o->get_id(), $o->get_billing_first_name() . ' ' . $o->get_billing_last_name(),
                $o->get_billing_phone(), $o->get_meta('_dzqcod_phone2'),
                $o->get_shipping_state(), $o->get_shipping_city(), $o->get_shipping_address_1(),
                implode(', ', $items), implode(', ', $colors), implode(', ', $sizes), $qtys,
                (float)$o->get_subtotal(), (float)$o->get_shipping_total(), (float)$o->get_total(),
                Core::ST[str_replace('wc-', '', $o->get_status())]['l'] ?? $o->get_status(),
                $o->get_payment_method_title() ?: 'COD', (int)$o->get_meta('_dzqcod_fraud_score'),
                $o->get_meta('_dzqcod_tracking_number') ?: '', $o->get_meta('_dzqcod_shipping_provider') ?: '',
                $o->get_date_created() ? $o->get_date_created()->format('Y-m-d H:i') : ''];
        }

        $sep = $format === 'tsv' ? "\t" : ',';
        $ext = $format === 'tsv' ? 'tsv' : 'csv';
        $filename = 'dzqcod-orders-' . gmdate('Y-m-d') . '.' . $ext;

        // Build CSV content
        $csv = "\xEF\xBB\xBF"; // BOM for Excel Arabic
        $csv .= implode($sep, $headers) . "\n";
        foreach ($rows as $row) {
            $csv .= implode($sep, array_map(function ($v) use ($sep) {
                $v = str_replace(['"', "\n", "\r"], ['""', ' ', ''], (string)$v);
                return (strpos($v, $sep) !== false || strpos($v, '"') !== false) ? '"' . $v . '"' : $v;
            }, $row)) . "\n";
        }

        wp_send_json_success(['csv' => $csv, 'filename' => $filename, 'count' => count($rows),
            'message' => count($rows) . ' طلب تم تصديره']);
    }

    // ═══════════════════════════════════════════════
    //  IMPORT ORDERS — From CSV
    // ═══════════════════════════════════════════════
    public function import_orders(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        if (!current_user_can('manage_woocommerce')) wp_send_json_error();
        if (empty($_FILES['import_file'])) wp_send_json_error(['message' => 'لم يتم رفع ملف']);

        $file = $_FILES['import_file']['tmp_name'];
        $rows = array_map('str_getcsv', file($file));
        if (count($rows) < 2) wp_send_json_error(['message' => 'ملف فارغ']);

        $headers = array_shift($rows); // Remove header row
        $imported = 0; $skipped = 0;

        foreach ($rows as $row) {
            if (count($row) < 5) { $skipped++; continue; }
            $name = $row[1] ?? ''; $phone = $row[2] ?? ''; $wilaya = $row[4] ?? '';
            $commune = $row[5] ?? ''; $total = (float)($row[13] ?? 0);
            if (!$phone || !$total) { $skipped++; continue; }

            $order = wc_create_order(['status' => 'wc-pending-call']);
            $name_parts = explode(' ', $name, 2);
            $order->set_billing_first_name($name_parts[0] ?? '');
            $order->set_billing_last_name($name_parts[1] ?? '');
            $order->set_billing_phone($phone);
            $order->set_shipping_state($wilaya);
            $order->set_shipping_city($commune);
            $order->set_shipping_address_1($row[6] ?? '');
            $order->set_total($total);
            $order->add_order_note('📥 استيراد من CSV');
            if (!empty($row[3])) $order->update_meta_data('_dzqcod_phone2', $row[3]);
            $order->save();
            $imported++;
        }

        wp_send_json_success(['message' => "تم استيراد {$imported} طلب | تم تخطي {$skipped}", 'imported' => $imported, 'skipped' => $skipped]);
    }

    // ═══════════════════════════════════════════════
    //  WEBHOOK RETRY HANDLER
    // ═══════════════════════════════════════════════
    public function webhook_retry_handler(string $url, string $payload, string $event, int $oid): void {
        $r = wp_remote_post($url, ['headers' => ['Content-Type' => 'application/json'], 'body' => $payload, 'timeout' => 15]);
        $code = !is_wp_error($r) ? wp_remote_retrieve_response_code($r) : 0;
        global $wpdb;
        $t = $wpdb->prefix . \DZQCOD_DB . 'message_logs';
        if ($wpdb->get_var("SHOW TABLES LIKE '{$t}'")) {
            $wpdb->insert($t, ['order_id' => $oid, 'channel' => 'webhook_retry', 'phone' => $url,
                'body' => 'retry', 'status' => ($code >= 200 && $code < 300) ? 'sent' : 'failed:' . $code, 'template' => $event]);
        }
    }

    // ═══════════════════════════════════════════════
    //  SAVE SETTINGS
    // ═══════════════════════════════════════════════
    public function save_settings(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        $data = $_POST['settings'] ?? [];
        foreach ($data as $k => $v) update_option('dzqcod_' . sanitize_key($k), sanitize_text_field($v), false);
        wp_send_json_success(['message' => 'تم الحفظ']);
    }
}
