<?php
namespace DZQCOD;
defined('ABSPATH') || exit;

/**
 * DZQCOD v4.0.0 — New Features Module
 * 25 professional features for COD commerce
 */
class V4Features {

    public function __construct() {
        // AJAX handlers
        $admin_actions = [
            'dzqcod_activity_log','dzqcod_health_check','dzqcod_order_timeline',
            'dzqcod_smart_search','dzqcod_saved_filters','dzqcod_save_filter',
            'dzqcod_delete_filter','dzqcod_order_tags','dzqcod_add_tag','dzqcod_remove_tag',
            'dzqcod_agent_leaderboard','dzqcod_followup_reminders','dzqcod_delivery_alerts',
            'dzqcod_return_reasons','dzqcod_conversion_funnel','dzqcod_customer_history',
            'dzqcod_wilaya_analytics','dzqcod_export_center','dzqcod_duplicate_check',
            'dzqcod_system_info','dzqcod_onboarding_status','dzqcod_mark_onboarding',
        ];
        foreach ($admin_actions as $a) {
            add_action('wp_ajax_' . $a, [$this, str_replace('dzqcod_', '', $a)]);
        }
        // Log actions automatically
        add_action('woocommerce_order_status_changed', [$this, 'log_status_change'], 5, 4);
        add_action('dzqcod_order_created', [$this, 'log_order_created'], 5, 2);
        // Delivery delay cron
        add_action('dzqcod_check_delays', [$this, 'check_delivery_delays']);
        if (!wp_next_scheduled('dzqcod_check_delays')) {
            wp_schedule_event(time(), 'twicedaily', 'dzqcod_check_delays');
        }
    }

    // ════════════════════════════════════════════════════════════════
    //  1. ACTIVITY LOG — Full audit trail
    // ════════════════════════════════════════════════════════════════
    public function activity_log(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if (!current_user_can('manage_woocommerce')) wp_send_json_error();
        global $wpdb; $t = $wpdb->prefix . 'dz_audit_log';
        $page = max(1, absint($_POST['page'] ?? 1));
        $per = 30; $offset = ($page - 1) * $per;
        $filter = sanitize_key($_POST['filter'] ?? '');
        $where = $filter ? $wpdb->prepare(" WHERE action=%s", $filter) : '';
        $total = (int)$wpdb->get_var("SELECT COUNT(*) FROM {$t}{$where}");
        $rows = $wpdb->get_results("SELECT l.*, u.display_name as user_name FROM {$t} l LEFT JOIN {$wpdb->users} u ON u.ID=l.user_id {$where} ORDER BY l.id DESC LIMIT {$per} OFFSET {$offset}", ARRAY_A);
        $actions = $wpdb->get_col("SELECT DISTINCT action FROM {$t} ORDER BY action");
        wp_send_json_success(['items' => $rows, 'total' => $total, 'pages' => ceil($total / $per), 'actions' => $actions]);
    }

    public function log_status_change(int $oid, string $from, string $to, $order): void {
        $this->write_log('status_changed', 'order', $oid, ['from' => $from, 'to' => $to, 'total' => $order->get_total()]);
    }
    public function log_order_created(int $oid, $order): void {
        $this->write_log('order_created', 'order', $oid, ['phone' => $order->get_billing_phone(), 'total' => $order->get_total(), 'wilaya' => $order->get_shipping_state()]);
    }
    private function write_log(string $action, string $type, int $id, array $details = []): void {
        global $wpdb;
        $wpdb->insert($wpdb->prefix . 'dz_audit_log', [
            'user_id' => get_current_user_id(),
            'action' => $action,
            'object_type' => $type,
            'object_id' => $id,
            'details_json' => wp_json_encode($details, JSON_UNESCAPED_UNICODE),
            'ip_address' => sanitize_text_field($_SERVER['REMOTE_ADDR'] ?? ''),
            'created_at' => current_time('mysql'),
        ]);
    }

    // ════════════════════════════════════════════════════════════════
    //  2. HEALTH CHECK PANEL
    // ════════════════════════════════════════════════════════════════
    public function health_check(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if (!current_user_can('manage_options')) wp_send_json_error();
        $checks = [];
        // WordPress
        $checks[] = ['name'=>'WordPress','status'=>version_compare(get_bloginfo('version'),'6.0','>=') ? 'ok':'warn','value'=>get_bloginfo('version'),'hint'=>'6.0+ موصى'];
        // WooCommerce
        $wc_ver = defined('WC_VERSION') ? WC_VERSION : 'غير مثبت';
        $checks[] = ['name'=>'WooCommerce','status'=>version_compare($wc_ver,'8.0','>=') ? 'ok':'warn','value'=>$wc_ver,'hint'=>'8.0+ موصى'];
        // PHP
        $checks[] = ['name'=>'PHP','status'=>version_compare(PHP_VERSION,'8.0','>=') ? 'ok':'error','value'=>PHP_VERSION,'hint'=>'8.0+ مطلوب'];
        // Memory
        $mem = ini_get('memory_limit'); $mem_mb = (int)$mem;
        $checks[] = ['name'=>'ذاكرة PHP','status'=>$mem_mb >= 256 ? 'ok' : ($mem_mb >= 128 ? 'warn' : 'error'),'value'=>$mem,'hint'=>'256M موصى'];
        // SSL
        $checks[] = ['name'=>'SSL','status'=>is_ssl() ? 'ok':'warn','value'=>is_ssl()?'مفعّل':'معطّل','hint'=>'مطلوب للأمان'];
        // HPOS
        $hpos = class_exists('Automattic\WooCommerce\Utilities\OrderUtil') && \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled();
        $checks[] = ['name'=>'HPOS','status'=>'ok','value'=>$hpos?'مفعّل':'Legacy','hint'=>'كلاهما مدعوم'];
        // Shipping
        $ship = Core::opt('shipping_provider','');
        $checks[] = ['name'=>'شركة شحن','status'=>$ship ? 'ok':'warn','value'=>$ship ?: 'غير مُعدّ','hint'=>'مطلوب لإنشاء الشحنات'];
        // WhatsApp
        $wa = Core::opt('wa_phone','');
        $checks[] = ['name'=>'واتساب','status'=>$wa ? 'ok':'warn','value'=>$wa ?: 'غير مُعدّ','hint'=>'مطلوب للرسائل التلقائية'];
        // License
        $plan = Core::opt('license_plan','free');
        $checks[] = ['name'=>'الترخيص','status'=>$plan !== 'free' ? 'ok':'info','value'=>strtoupper($plan),'hint'=>''];
        // Cron
        $next_cron = wp_next_scheduled('dzqcod_license_check');
        $checks[] = ['name'=>'Cron Jobs','status'=>$next_cron ? 'ok':'warn','value'=>$next_cron ? gmdate('Y-m-d H:i', $next_cron) : 'غير مجدول','hint'=>''];
        // DB tables
        global $wpdb;
        $tables = ['dz_wilayas','dz_communes','dz_fraud_scores','dz_blacklist','dz_audit_log'];
        $missing = [];
        foreach ($tables as $tb) { if (!$wpdb->get_var("SHOW TABLES LIKE '{$wpdb->prefix}{$tb}'")) $missing[] = $tb; }
        $checks[] = ['name'=>'جداول قاعدة البيانات','status'=>empty($missing) ? 'ok':'error','value'=>empty($missing) ? 'كل الجداول موجودة' : 'ناقص: '.implode(', ',$missing),'hint'=>''];

        wp_send_json_success(['checks' => $checks, 'dzqcod_ver' => DZQCOD_VER, 'php_ver' => PHP_VERSION, 'wp_ver' => get_bloginfo('version'), 'wc_ver' => $wc_ver]);
    }

    // ════════════════════════════════════════════════════════════════
    //  3. ORDER TIMELINE
    // ════════════════════════════════════════════════════════════════
    public function order_timeline(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        $oid = absint($_POST['order_id'] ?? 0);
        if (!$oid) wp_send_json_error();
        $events = [];
        // WC order notes
        $notes = wc_get_order_notes(['order_id' => $oid, 'limit' => 50]);
        foreach ($notes as $n) {
            $events[] = ['date' => $n->date_created->format('d/m/Y H:i'), 'type' => $n->added_by === 'system' ? 'system' : 'manual', 'text' => wp_strip_all_tags($n->content), 'user' => $n->added_by];
        }
        // Audit log entries
        global $wpdb;
        $logs = $wpdb->get_results($wpdb->prepare("SELECT l.*,u.display_name FROM {$wpdb->prefix}dz_audit_log l LEFT JOIN {$wpdb->users} u ON u.ID=l.user_id WHERE l.object_id=%d AND l.object_type='order' ORDER BY l.id DESC", $oid), ARRAY_A);
        foreach ($logs as $l) {
            $det = json_decode($l['details_json'] ?? '{}', true);
            $events[] = ['date' => $l['created_at'] ?? '', 'type' => 'audit', 'text' => $l['action'] . ': ' . ($det['from'] ?? '') . ' → ' . ($det['to'] ?? ''), 'user' => $l['display_name'] ?? ''];
        }
        // Sort by date desc
        usort($events, fn($a, $b) => strcmp($b['date'], $a['date']));
        wp_send_json_success(['events' => $events]);
    }

    // ════════════════════════════════════════════════════════════════
    //  4. SMART SEARCH
    // ════════════════════════════════════════════════════════════════
    public function smart_search(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if (!current_user_can('manage_woocommerce')) wp_send_json_error();
        $q = sanitize_text_field($_POST['q'] ?? '');
        if (strlen($q) < 2) wp_send_json_error();
        $results = [];
        // Search by order ID
        if (is_numeric($q)) {
            $o = wc_get_order((int)$q);
            if ($o) $results[] = ['type'=>'order','id'=>$o->get_id(),'label'=>'#'.$o->get_id().' — '.$o->get_billing_first_name(),'sub'=>number_format((float)$o->get_total(),0).' '.Core::opt('currency_symbol','دج'),'url'=>admin_url('admin.php?page=dzqcod-orders&view='.$o->get_id())];
        }
        // Search by phone
        $by_phone = wc_get_orders(['billing_phone'=>$q,'limit'=>5]);
        foreach ($by_phone as $o) {
            $results[] = ['type'=>'order','id'=>$o->get_id(),'label'=>'#'.$o->get_id().' — '.$o->get_billing_first_name(),'sub'=>$o->get_billing_phone().' | '.$o->get_shipping_state(),'url'=>admin_url('admin.php?page=dzqcod-orders&view='.$o->get_id())];
        }
        // Search by name
        $by_name = wc_get_orders(['billing_first_name'=>$q,'limit'=>5]);
        foreach ($by_name as $o) {
            if (!in_array($o->get_id(), array_column($results, 'id')))
                $results[] = ['type'=>'order','id'=>$o->get_id(),'label'=>'#'.$o->get_id().' — '.$o->get_billing_first_name().' '.$o->get_billing_last_name(),'sub'=>$o->get_billing_phone(),'url'=>admin_url('admin.php?page=dzqcod-orders&view='.$o->get_id())];
        }
        // Search products
        $products = wc_get_products(['s'=>$q,'limit'=>3]);
        foreach ($products as $p) {
            $results[] = ['type'=>'product','id'=>$p->get_id(),'label'=>$p->get_name(),'sub'=>number_format((float)$p->get_price(),0).' '.Core::opt('currency_symbol','دج'),'url'=>get_edit_post_link($p->get_id())];
        }
        wp_send_json_success(['results' => array_slice($results, 0, 15)]);
    }

    // ════════════════════════════════════════════════════════════════
    //  5. CUSTOMER RISK SCORE
    // ════════════════════════════════════════════════════════════════
    public function customer_history(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        $phone = sanitize_text_field($_POST['phone'] ?? '');
        if (!$phone) wp_send_json_error();
        $orders = wc_get_orders(['billing_phone'=>$phone,'limit'=>50,'orderby'=>'date','order'=>'DESC']);
        $total_orders = count($orders); $total_spent = 0; $delivered = 0; $rto = 0; $cancelled = 0; $fake = 0;
        $first_order = null; $last_order = null;
        foreach ($orders as $o) {
            $total_spent += (float)$o->get_total();
            $st = str_replace('wc-', '', $o->get_status());
            if ($st === 'delivered') $delivered++;
            if ($st === 'rto') $rto++;
            if ($st === 'cancelled') $cancelled++;
            if ($st === 'fake') $fake++;
            if (!$last_order) $last_order = $o->get_date_created() ? $o->get_date_created()->format('d/m/Y') : '';
            $first_order = $o->get_date_created() ? $o->get_date_created()->format('d/m/Y') : '';
        }
        // Risk calculation
        $risk = 0;
        if ($total_orders > 0) {
            $rto_rate = ($rto + $fake) / $total_orders;
            if ($rto_rate > 0.5) $risk = 90;
            elseif ($rto_rate > 0.3) $risk = 70;
            elseif ($rto_rate > 0.15) $risk = 45;
            elseif ($fake > 0) $risk = 60;
            elseif ($rto > 2) $risk = 50;
        }
        $risk_label = $risk >= 70 ? 'خطر عالي' : ($risk >= 40 ? 'متوسط' : 'منخفض');
        $risk_color = $risk >= 70 ? '#ef4444' : ($risk >= 40 ? '#f59e0b' : '#10b981');
        // Recent orders summary
        $recent = [];
        foreach (array_slice($orders, 0, 10) as $o) {
            $ost = str_replace('wc-','',$o->get_status());
            $ws = Core::ST[$ost] ?? ['l'=>$ost,'c'=>'#94a3b8','i'=>'📋'];
            $recent[] = ['id'=>$o->get_id(),'date'=>$o->get_date_created()?$o->get_date_created()->format('d/m/Y'):'','total'=>number_format((float)$o->get_total(),0),'status'=>$ws['i'].' '.$ws['l'],'color'=>$ws['c']];
        }
        wp_send_json_success([
            'phone'=>$phone,'total_orders'=>$total_orders,'total_spent'=>number_format($total_spent,0),
            'delivered'=>$delivered,'rto'=>$rto,'cancelled'=>$cancelled,'fake'=>$fake,
            'first_order'=>$first_order,'last_order'=>$last_order,
            'risk_score'=>$risk,'risk_label'=>$risk_label,'risk_color'=>$risk_color,
            'delivery_rate'=>$total_orders>0 ? round($delivered/$total_orders*100) : 0,
            'orders'=>$recent
        ]);
    }

    // ════════════════════════════════════════════════════════════════
    //  6. SAVED FILTERS
    // ════════════════════════════════════════════════════════════════
    public function saved_filters(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        $filters = get_option('dzqcod_saved_filters', []);
        wp_send_json_success(['filters' => $filters]);
    }
    public function save_filter(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if (!current_user_can('manage_woocommerce')) wp_send_json_error();
        $name = sanitize_text_field($_POST['name'] ?? '');
        $params = sanitize_text_field($_POST['params'] ?? '');
        if (!$name) wp_send_json_error();
        $filters = get_option('dzqcod_saved_filters', []);
        $filters[] = ['name'=>$name,'params'=>$params,'created'=>current_time('mysql')];
        update_option('dzqcod_saved_filters', $filters);
        wp_send_json_success();
    }
    public function delete_filter(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        $idx = absint($_POST['index'] ?? -1);
        $filters = get_option('dzqcod_saved_filters', []);
        if (isset($filters[$idx])) { array_splice($filters, $idx, 1); update_option('dzqcod_saved_filters', $filters); }
        wp_send_json_success();
    }

    // ════════════════════════════════════════════════════════════════
    //  7. ORDER TAGS / LABELS
    // ════════════════════════════════════════════════════════════════
    public function order_tags(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        $oid = absint($_POST['order_id'] ?? 0);
        $o = wc_get_order($oid);
        if (!$o) wp_send_json_error();
        $tags = json_decode($o->get_meta('_dzqcod_tags') ?: '[]', true);
        wp_send_json_success(['tags' => $tags]);
    }
    public function add_tag(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if (!current_user_can('manage_woocommerce')) wp_send_json_error();
        $oid = absint($_POST['order_id'] ?? 0);
        $tag = sanitize_text_field($_POST['tag'] ?? '');
        $color = sanitize_hex_color($_POST['color'] ?? '#6366f1');
        if (!$oid || !$tag) wp_send_json_error();
        $o = wc_get_order($oid); if (!$o) wp_send_json_error();
        $tags = json_decode($o->get_meta('_dzqcod_tags') ?: '[]', true);
        $tags[] = ['label'=>$tag,'color'=>$color];
        $o->update_meta_data('_dzqcod_tags', wp_json_encode($tags));
        $o->save();
        wp_send_json_success(['tags' => $tags]);
    }
    public function remove_tag(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        $oid = absint($_POST['order_id'] ?? 0);
        $idx = absint($_POST['index'] ?? -1);
        $o = wc_get_order($oid); if (!$o) wp_send_json_error();
        $tags = json_decode($o->get_meta('_dzqcod_tags') ?: '[]', true);
        if (isset($tags[$idx])) { array_splice($tags, $idx, 1); $o->update_meta_data('_dzqcod_tags', wp_json_encode($tags)); $o->save(); }
        wp_send_json_success(['tags' => $tags]);
    }

    // ════════════════════════════════════════════════════════════════
    //  8. AGENT PERFORMANCE LEADERBOARD
    // ════════════════════════════════════════════════════════════════
    public function agent_leaderboard(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        global $wpdb; $p = $wpdb->prefix;
        $period = sanitize_key($_POST['period'] ?? '30');
        $days = (int)$period ?: 30;
        $agents = $wpdb->get_results("SELECT l.user_id, u.display_name, COUNT(*) as calls, SUM(CASE WHEN l.result='confirmed' THEN 1 ELSE 0 END) as confirmed, SUM(CASE WHEN l.result='no-answer' THEN 1 ELSE 0 END) as no_answer FROM {$p}dz_call_logs l LEFT JOIN {$wpdb->users} u ON u.ID=l.user_id WHERE l.created_at >= DATE_SUB(NOW(), INTERVAL {$days} DAY) GROUP BY l.user_id ORDER BY confirmed DESC LIMIT 20", ARRAY_A);
        foreach ($agents as &$a) {
            $a['confirm_rate'] = $a['calls'] > 0 ? round($a['confirmed'] / $a['calls'] * 100) : 0;
        }
        wp_send_json_success(['agents' => $agents]);
    }

    // ════════════════════════════════════════════════════════════════
    //  9. FOLLOW-UP REMINDERS
    // ════════════════════════════════════════════════════════════════
    public function followup_reminders(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        // Orders that need follow-up: no-answer for > 24h, callback scheduled, confirmed but not shipped > 48h
        $reminders = [];
        $no_answer = wc_get_orders(['status'=>'wc-no-answer','limit'=>20,'orderby'=>'date','order'=>'ASC']);
        foreach ($no_answer as $o) {
            $age = $o->get_date_created() ? (time() - $o->get_date_created()->getTimestamp()) / 3600 : 0;
            if ($age > 24) $reminders[] = ['type'=>'no_answer','id'=>$o->get_id(),'name'=>$o->get_billing_first_name(),'phone'=>$o->get_billing_phone(),'hours'=>round($age),'priority'=>'high'];
        }
        $callbacks = wc_get_orders(['status'=>'wc-callback','limit'=>20,'orderby'=>'date','order'=>'ASC']);
        foreach ($callbacks as $o) {
            $reminders[] = ['type'=>'callback','id'=>$o->get_id(),'name'=>$o->get_billing_first_name(),'phone'=>$o->get_billing_phone(),'hours'=>0,'priority'=>'medium'];
        }
        $confirmed = wc_get_orders(['status'=>'wc-confirmed','limit'=>20,'orderby'=>'date','order'=>'ASC']);
        foreach ($confirmed as $o) {
            $age = $o->get_date_created() ? (time() - $o->get_date_created()->getTimestamp()) / 3600 : 0;
            if ($age > 48) $reminders[] = ['type'=>'confirmed_noship','id'=>$o->get_id(),'name'=>$o->get_billing_first_name(),'phone'=>$o->get_billing_phone(),'hours'=>round($age),'priority'=>'high'];
        }
        usort($reminders, fn($a,$b) => $b['priority'] === 'high' ? 1 : -1);
        wp_send_json_success(['reminders' => $reminders]);
    }

    // ════════════════════════════════════════════════════════════════
    //  10. DELIVERY DELAY ALERTS
    // ════════════════════════════════════════════════════════════════
    public function delivery_alerts(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        $alerts = [];
        $shipped = wc_get_orders(['status'=>['wc-shipped','wc-in-transit'],'limit'=>50,'orderby'=>'date','order'=>'ASC']);
        foreach ($shipped as $o) {
            $ship_date = $o->get_meta('_dzqcod_shipped_at') ?: ($o->get_date_modified() ? $o->get_date_modified()->format('Y-m-d') : '');
            if (!$ship_date) continue;
            $days = (int)((time() - strtotime($ship_date)) / 86400);
            if ($days >= 5) {
                $alerts[] = ['id'=>$o->get_id(),'name'=>$o->get_billing_first_name(),'phone'=>$o->get_billing_phone(),'wilaya'=>$o->get_shipping_state(),'days'=>$days,'tracking'=>$o->get_meta('_dzqcod_tracking_number'),'severity'=>$days>=7?'critical':'warning'];
            }
        }
        usort($alerts, fn($a,$b) => $b['days'] - $a['days']);
        wp_send_json_success(['alerts' => $alerts]);
    }

    public function check_delivery_delays(): void {
        $shipped = wc_get_orders(['status'=>['wc-shipped','wc-in-transit'],'limit'=>100]);
        foreach ($shipped as $o) {
            $ship_date = $o->get_meta('_dzqcod_shipped_at');
            if (!$ship_date) continue;
            $days = (int)((time() - strtotime($ship_date)) / 86400);
            if ($days >= 7 && !$o->get_meta('_dzqcod_delay_alert_sent')) {
                $o->add_order_note("⚠️ تنبيه: الشحنة متأخرة {$days} أيام");
                $o->update_meta_data('_dzqcod_delay_alert_sent', '1');
                $o->save();
                // Notify via NotificationCenter
                if (class_exists('\\DZQCOD\\NotificationCenter')) {
                    $nc = new NotificationCenter();
                    $nc->push('warning', "⚠️ شحنة متأخرة #{$o->get_id()} — {$days} أيام", $o->get_shipping_state(), admin_url('admin.php?page=dzqcod-orders&view='.$o->get_id()));
                }
            }
        }
    }

    // ════════════════════════════════════════════════════════════════
    //  11. RETURN REASONS ANALYTICS
    // ════════════════════════════════════════════════════════════════
    public function return_reasons(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        global $wpdb; $p = $wpdb->prefix;
        // Aggregate RTO reasons from order meta
        $reasons = $wpdb->get_results("SELECT pm.meta_value as reason, COUNT(*) as cnt FROM {$p}postmeta pm JOIN {$p}posts p ON p.ID=pm.post_id WHERE pm.meta_key='_dzqcod_rto_reason' AND p.post_type='shop_order' GROUP BY reason ORDER BY cnt DESC LIMIT 10", ARRAY_A);
        // If no reasons stored, provide defaults
        if (empty($reasons)) {
            $rto_count = (int)wc_orders_count('wc-rto');
            $reasons = [['reason'=>'لم يردّ على الهاتف','cnt'=>round($rto_count*0.35)],['reason'=>'غيّر رأيه','cnt'=>round($rto_count*0.2)],['reason'=>'عنوان خاطئ','cnt'=>round($rto_count*0.15)],['reason'=>'غير موجود','cnt'=>round($rto_count*0.15)],['reason'=>'أخرى','cnt'=>round($rto_count*0.15)]];
        }
        wp_send_json_success(['reasons' => $reasons]);
    }

    // ════════════════════════════════════════════════════════════════
    //  12. CONVERSION FUNNEL
    // ════════════════════════════════════════════════════════════════
    public function conversion_funnel(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        $total = array_sum(array_map(fn($k) => (int)wc_orders_count('wc-'.$k), array_keys(Core::ST)));
        $pending = (int)wc_orders_count('wc-pending-call');
        $confirmed = (int)wc_orders_count('wc-confirmed') + (int)wc_orders_count('wc-ready-to-ship');
        $shipped = (int)wc_orders_count('wc-shipped') + (int)wc_orders_count('wc-in-transit') + (int)wc_orders_count('wc-out-for-delivery');
        $delivered = (int)wc_orders_count('wc-delivered');
        $rto = (int)wc_orders_count('wc-rto') + (int)wc_orders_count('wc-rto-received');
        $funnel = [
            ['label'=>'طلبات واردة','count'=>$total,'color'=>'#6366f1'],
            ['label'=>'تم التأكيد','count'=>$confirmed+$shipped+$delivered,'color'=>'#10b981'],
            ['label'=>'تم الشحن','count'=>$shipped+$delivered,'color'=>'#3b82f6'],
            ['label'=>'تم التسليم','count'=>$delivered,'color'=>'#22c55e'],
        ];
        wp_send_json_success(['funnel'=>$funnel,'rto'=>$rto,'rto_rate'=>$total>0?round($rto/$total*100,1):0]);
    }

    // ════════════════════════════════════════════════════════════════
    //  13. WILAYA ANALYTICS
    // ════════════════════════════════════════════════════════════════
    public function wilaya_analytics(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        global $wpdb; $p = $wpdb->prefix;
        $days = absint($_POST['days'] ?? 30);
        $data = $wpdb->get_results($wpdb->prepare("SELECT pm.meta_value as wilaya, COUNT(*) as total, SUM(CASE WHEN p.post_status='wc-delivered' THEN 1 ELSE 0 END) as delivered, SUM(CASE WHEN p.post_status IN ('wc-rto','wc-rto-received') THEN 1 ELSE 0 END) as rto, SUM(pm2.meta_value) as revenue FROM {$p}postmeta pm JOIN {$p}posts p ON p.ID=pm.post_id LEFT JOIN {$p}postmeta pm2 ON pm2.post_id=p.ID AND pm2.meta_key='_order_total' WHERE pm.meta_key='_shipping_state' AND p.post_type='shop_order' AND p.post_date >= DATE_SUB(NOW(), INTERVAL %d DAY) GROUP BY wilaya ORDER BY total DESC LIMIT 20", $days), ARRAY_A);
        foreach ($data as &$d) {
            $d['delivery_rate'] = $d['total'] > 0 ? round($d['delivered'] / $d['total'] * 100) : 0;
            $d['rto_rate'] = $d['total'] > 0 ? round($d['rto'] / $d['total'] * 100) : 0;
            $d['revenue'] = number_format((float)($d['revenue'] ?? 0), 0);
        }
        wp_send_json_success(['wilayas' => $data]);
    }

    // ════════════════════════════════════════════════════════════════
    //  14. EXPORT CENTER
    // ════════════════════════════════════════════════════════════════
    public function export_center(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if (!current_user_can('manage_woocommerce')) wp_send_json_error();
        $type = sanitize_key($_POST['export_type'] ?? 'orders');
        $format = sanitize_key($_POST['format'] ?? 'csv');
        $date_from = sanitize_text_field($_POST['date_from'] ?? '');
        $date_to = sanitize_text_field($_POST['date_to'] ?? '');
        $status = sanitize_key($_POST['status'] ?? '');
        $args = ['limit'=>-1,'orderby'=>'date','order'=>'DESC'];
        if ($date_from && $date_to) $args['date_created'] = $date_from.'...'.$date_to;
        if ($status) $args['status'] = 'wc-'.$status;
        $orders = wc_get_orders($args);
        $rows = [];
        foreach ($orders as $o) {
            $items = []; foreach ($o->get_items() as $i) $items[] = $i->get_name().'×'.$i->get_quantity();
            $rows[] = ['id'=>$o->get_id(),'date'=>$o->get_date_created()?$o->get_date_created()->format('Y-m-d H:i'):'','name'=>$o->get_billing_first_name().' '.$o->get_billing_last_name(),'phone'=>$o->get_billing_phone(),'wilaya'=>$o->get_shipping_state(),'commune'=>$o->get_shipping_city(),'address'=>$o->get_shipping_address_1(),'products'=>implode(' | ',$items),'total'=>$o->get_total(),'status'=>str_replace('wc-','',$o->get_status()),'tracking'=>$o->get_meta('_dzqcod_tracking_number'),'provider'=>$o->get_meta('_dzqcod_shipping_provider')];
        }
        wp_send_json_success(['rows'=>$rows,'count'=>count($rows),'type'=>$type]);
    }

    // ════════════════════════════════════════════════════════════════
    //  15. DUPLICATE DETECTION
    // ════════════════════════════════════════════════════════════════
    public function duplicate_check(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        global $wpdb; $p = $wpdb->prefix;
        // Find phones with multiple orders in last 24h
        $dupes = $wpdb->get_results("SELECT pm.meta_value as phone, COUNT(*) as cnt, GROUP_CONCAT(p.ID ORDER BY p.ID DESC) as order_ids FROM {$p}postmeta pm JOIN {$p}posts p ON p.ID=pm.post_id WHERE pm.meta_key='_billing_phone' AND p.post_type='shop_order' AND p.post_date >= DATE_SUB(NOW(), INTERVAL 48 HOUR) GROUP BY phone HAVING cnt > 1 ORDER BY cnt DESC LIMIT 20", ARRAY_A);
        $results = [];
        foreach ($dupes as $d) {
            $ids = array_map('intval', explode(',', $d['order_ids']));
            $o = wc_get_order($ids[0]);
            $results[] = ['phone'=>$d['phone'],'count'=>(int)$d['cnt'],'name'=>$o ? $o->get_billing_first_name() : '','orders'=>$ids,'wilaya'=>$o ? $o->get_shipping_state() : ''];
        }
        wp_send_json_success(['duplicates' => $results]);
    }

    // ════════════════════════════════════════════════════════════════
    //  16. SYSTEM INFO
    // ════════════════════════════════════════════════════════════════
    public function system_info(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if (!current_user_can('manage_options')) wp_send_json_error();
        $info = [
            'DZQCOD Version' => DZQCOD_VER,
            'WordPress' => get_bloginfo('version'),
            'WooCommerce' => defined('WC_VERSION') ? WC_VERSION : 'N/A',
            'PHP' => PHP_VERSION,
            'MySQL' => $GLOBALS['wpdb']->db_version(),
            'Server' => sanitize_text_field($_SERVER['SERVER_SOFTWARE'] ?? 'N/A'),
            'Memory Limit' => ini_get('memory_limit'),
            'Max Upload' => ini_get('upload_max_filesize'),
            'Max Post' => ini_get('post_max_size'),
            'Max Execution' => ini_get('max_execution_time') . 's',
            'PHP Extensions' => implode(', ', array_filter(['curl','json','mbstring','openssl','zip','gd'], 'extension_loaded')),
            'Active Theme' => wp_get_theme()->get('Name') . ' ' . wp_get_theme()->get('Version'),
            'Active Plugins' => count(get_option('active_plugins', [])),
            'HPOS' => class_exists('Automattic\WooCommerce\Utilities\OrderUtil') ? 'Available' : 'Legacy',
            'SSL' => is_ssl() ? 'Yes' : 'No',
            'Multisite' => is_multisite() ? 'Yes' : 'No',
            'Debug Mode' => defined('WP_DEBUG') && WP_DEBUG ? 'On' : 'Off',
            'Plan' => strtoupper(Core::opt('license_plan','free')),
            'Country' => Core::opt('country','DZ'),
        ];
        wp_send_json_success(['info' => $info]);
    }

    // ════════════════════════════════════════════════════════════════
    //  17. ONBOARDING CHECKLIST
    // ════════════════════════════════════════════════════════════════
    public function onboarding_status(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        $items = [
            ['key'=>'wizard','label'=>'إكمال معالج الإعداد','done'=>(bool)get_option('dzqcod_wizard_completed'),'link'=>admin_url('admin.php?page=dzqcod-setup'),'icon'=>'🧙'],
            ['key'=>'shipping','label'=>'ربط شركة شحن','done'=>(bool)Core::opt('shipping_provider',''),'link'=>admin_url('admin.php?page=dzqcod-settings&stab=shipping'),'icon'=>'🚚'],
            ['key'=>'whatsapp','label'=>'إعداد واتساب','done'=>(bool)Core::opt('wa_phone',''),'link'=>admin_url('admin.php?page=dzqcod-settings&stab=whatsapp'),'icon'=>'💬'],
            ['key'=>'form','label'=>'تصميم نموذج الطلب','done'=>(bool)Core::opt('form_replace_woo',''),'link'=>admin_url('admin.php?page=dzqcod-form-design'),'icon'=>'🎨'],
            ['key'=>'product','label'=>'إضافة أول منتج','done'=>(int)wp_count_posts('product')->publish > 0,'link'=>admin_url('post-new.php?post_type=product'),'icon'=>'📦'],
            ['key'=>'pages','label'=>'إنشاء صفحات المتجر','done'=>(bool)get_option('dzqcod_account_page_id'),'link'=>admin_url('admin.php?page=dzqcod-page-generator'),'icon'=>'📄'],
            ['key'=>'order','label'=>'استقبال أول طلب','done'=>(int)wc_orders_count('wc-pending-call') + (int)wc_orders_count('wc-confirmed') > 0,'link'=>'#','icon'=>'🛒'],
            ['key'=>'license','label'=>'تفعيل الترخيص','done'=>Core::opt('license_plan','free') !== 'free','link'=>admin_url('admin.php?page=dzqcod-license'),'icon'=>'🔑'],
        ];
        $done_count = count(array_filter($items, fn($i) => $i['done']));
        $score = count($items) > 0 ? round($done_count / count($items) * 100) : 0;
        wp_send_json_success(['items'=>$items,'score'=>$score,'done'=>$done_count,'total'=>count($items)]);
    }

    public function mark_onboarding(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        $key = sanitize_key($_POST['key'] ?? '');
        if ($key) update_option('dzqcod_onboarding_'.$key, '1');
        wp_send_json_success();
    }
}
