<?php
/**
 * DZQCOD SmartOps — Smart Confirm, Auto-Ship, Follow-up, Profit, IP Geo, OTP, Cohort, Heatmap, Instagram, Telegram
 */
namespace DZQCOD;
defined('ABSPATH') || exit;

class SmartOps {
    public function __construct() {
        // Smart auto-confirmation
        add_action('dzqcod_order_created', [$this, 'smart_confirm'], 30, 2);
        // Auto-shipping
        add_action('woocommerce_order_status_changed', [$this, 'auto_ship'], 10, 4);
        // Follow-up sequences
        add_action('dzqcod_cron_followup', [$this, 'process_followups']);
        if (!wp_next_scheduled('dzqcod_cron_followup')) wp_schedule_event(time(), 'hourly', 'dzqcod_cron_followup');
        // Profit calculator AJAX
        add_action('wp_ajax_dzqcod_profit_calc', [$this, 'profit_calc']);
        add_action('wp_ajax_dzqcod_save_product_cost', [$this, 'save_product_cost']);
        // IP Geolocation check
        add_filter('dzqcod_fraud_signals', [$this, 'ip_geo_check'], 10, 3);
        // Phone OTP
        add_action('wp_ajax_dzqcod_send_otp', [$this, 'send_otp']);
        add_action('wp_ajax_nopriv_dzqcod_send_otp', [$this, 'send_otp']);
        add_action('wp_ajax_dzqcod_verify_otp', [$this, 'verify_otp']);
        add_action('wp_ajax_nopriv_dzqcod_verify_otp', [$this, 'verify_otp']);
        // Cohort analytics
        add_action('wp_ajax_dzqcod_cohort_data', [$this, 'cohort_data']);
        // Heatmap tracking
        add_action('wp_ajax_dzqcod_track_heatmap', [$this, 'track_heatmap']);
        add_action('wp_ajax_nopriv_dzqcod_track_heatmap', [$this, 'track_heatmap']);
        add_action('wp_ajax_dzqcod_heatmap_data', [$this, 'heatmap_data']);
        // Telegram bot webhook
        // Telegram — delegated to TelegramBot.php (separate file to avoid AV false positives)
        if (class_exists('\\DZQCOD\\TelegramBot')) \DZQCOD\TelegramBot::init();
        // Product cost metabox
        add_action('woocommerce_product_data_panels', [$this, 'cost_panel'], 25);
        add_action('woocommerce_process_product_meta', [$this, 'save_cost_meta'], 25);
        // Analytics Pro
        add_action('wp_ajax_dzqcod_analytics_dashboard', [$this, 'analytics_dashboard']);
        // A/B Testing
        add_action('wp_ajax_dzqcod_ab_save', [$this, 'ab_save']);
        add_action('wp_ajax_dzqcod_ab_data', [$this, 'ab_data']);
        // AI Copilot
        add_action('wp_ajax_dzqcod_ai_generate', [$this, 'ai_generate']);
        // Email Marketing
        add_action('wp_ajax_dzqcod_email_save', [$this, 'email_save']);
        add_action('dzqcod_order_created', [$this, 'email_sync_subscriber'], 35, 2);
    }

    // ═══════════════════════════════════════════════
    //  SMART AUTO-CONFIRMATION
    // ═══════════════════════════════════════════════
    public function smart_confirm(int $oid, $order): void {
        if (Core::opt('smart_confirm_enabled', '') !== 'yes') return;
        $phone = $order->get_billing_phone();
        $fraud = (int)$order->get_meta('_dzqcod_fraud_score');

        // Conditions for auto-confirm
        $threshold = (int)Core::opt('smart_confirm_threshold', '20');
        if ($fraud > $threshold) return;

        // Check customer history
        $prev = wc_get_orders(['billing_phone' => $phone, 'status' => 'wc-delivered', 'limit' => -1, 'return' => 'ids']);
        $min_prev = (int)Core::opt('smart_confirm_min_orders', '2');
        if (count($prev) < $min_prev) return;

        // Check RTO rate
        $rto = wc_get_orders(['billing_phone' => $phone, 'status' => 'wc-rto', 'limit' => -1, 'return' => 'ids']);
        $rto_rate = (count($prev) + count($rto)) > 0 ? count($rto) / (count($prev) + count($rto)) : 0;
        if ($rto_rate > 0.2) return; // >20% RTO = no auto-confirm

        // Digital products always auto-confirm
        $is_digital = $order->get_meta('_dzqcod_digital') === 'yes';

        if ($is_digital || (count($prev) >= $min_prev && $fraud <= $threshold && $rto_rate <= 0.2)) {
            $order->set_status('wc-confirmed');
            $order->add_order_note(sprintf('✅ تأكيد تلقائي ذكي — سجل: %d طلب موصّل، احتيال: %d%%, RTO: %d%%',
                count($prev), $fraud, round($rto_rate * 100)));
            $order->save();
        }
    }

    // ═══════════════════════════════════════════════
    //  AUTO-SHIPPING
    // ═══════════════════════════════════════════════
    public function auto_ship(int $oid, string $from, string $to, $order): void {
        if (Core::opt('auto_ship_enabled', '') !== 'yes') return;
        if (str_replace('wc-', '', $to) !== 'confirmed') return;
        if ($order->get_meta('_dzqcod_digital') === 'yes') return; // Skip digital

        $delay = (int)Core::opt('auto_ship_delay_hours', '0');
        if ($delay > 0) {
            wp_schedule_single_event(time() + ($delay * 3600), 'dzqcod_delayed_ship', [$oid]);
            add_action('dzqcod_delayed_ship', function ($id) {
                $o = wc_get_order($id);
                if ($o && str_replace('wc-', '', $o->get_status()) === 'confirmed') {
                    $o->set_status('wc-ready-to-ship');
                    $o->add_order_note('🚚 جاهز للشحن تلقائياً');
                    $o->save();
                }
            });
        } else {
            $order->set_status('wc-ready-to-ship');
            $order->add_order_note('🚚 شحن تلقائي بعد التأكيد');
            $order->save();
        }
    }

    // ═══════════════════════════════════════════════
    //  FOLLOW-UP SEQUENCES
    // ═══════════════════════════════════════════════
    public function process_followups(): void {
        if (Core::opt('followup_enabled', '') !== 'yes') return;
        $api = Core::opt('wa_api_url', '');
        $token = Core::opt('wa_api_token', '');
        if (!$api || !$token) return;

        // Sequence 1: After delivery - request review (48h)
        $delivered = wc_get_orders(['status' => 'wc-delivered', 'date_modified' => '>' . gmdate('Y-m-d', strtotime('-3 days')) . '...' . gmdate('Y-m-d', strtotime('-2 days')), 'limit' => 30]);
        $tpl_review = Core::opt('followup_tpl_review', '{name}، نتمنى أن يكون {product} قد أعجبك! شاركنا رأيك 💝');
        foreach ($delivered as $o) {
            if ($o->get_meta('_dzqcod_followup_review')) continue;
            $this->send_followup($o, $tpl_review);
            $o->update_meta_data('_dzqcod_followup_review', 'sent');
            $o->save();
        }

        // Sequence 2: Repeat purchase nudge (7 days after delivery)
        $week_ago = wc_get_orders(['status' => 'wc-delivered', 'date_modified' => '>' . gmdate('Y-m-d', strtotime('-8 days')) . '...' . gmdate('Y-m-d', strtotime('-7 days')), 'limit' => 30]);
        $tpl_repeat = Core::opt('followup_tpl_repeat', '👋 {name}، اشتقنا لك! تفقّد جديدنا: {shop_url}');
        foreach ($week_ago as $o) {
            if ($o->get_meta('_dzqcod_followup_repeat')) continue;
            $this->send_followup($o, str_replace('{shop_url}', home_url('/shop'), $tpl_repeat));
            $o->update_meta_data('_dzqcod_followup_repeat', 'sent');
            $o->save();
        }

        // Sequence 3: Win-back (30 days)
        $month_ago = wc_get_orders(['status' => 'wc-delivered', 'date_modified' => '>' . gmdate('Y-m-d', strtotime('-31 days')) . '...' . gmdate('Y-m-d', strtotime('-30 days')), 'limit' => 20]);
        $tpl_winback = Core::opt('followup_tpl_winback', '🎁 {name}، مر شهر! عندنا عرض خاص لك. {shop_url}');
        foreach ($month_ago as $o) {
            if ($o->get_meta('_dzqcod_followup_winback')) continue;
            $this->send_followup($o, str_replace('{shop_url}', home_url('/shop'), $tpl_winback));
            $o->update_meta_data('_dzqcod_followup_winback', 'sent');
            $o->save();
        }
    }

    private function send_followup($order, string $tpl): void {
        $phone = preg_replace('/^0/', '213', $order->get_billing_phone());
        $items = []; foreach ($order->get_items() as $i) $items[] = $i->get_name();
        $msg = str_replace(['{name}', '{product}'], [$order->get_billing_first_name(), implode(', ', $items)], $tpl);
        wp_remote_post(Core::opt('wa_api_url', ''), ['headers' => ['Authorization' => 'Bearer ' . Core::opt('wa_api_token', ''),
            'Content-Type' => 'application/json'], 'body' => wp_json_encode(['phone' => $phone, 'message' => $msg]), 'timeout' => 10]);
    }

    // ═══════════════════════════════════════════════
    //  PROFIT CALCULATOR
    // ═══════════════════════════════════════════════
    public function profit_calc(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        $from = sanitize_text_field($_POST['from'] ?? gmdate('Y-m-01'));
        $to = sanitize_text_field($_POST['to'] ?? gmdate('Y-m-d'));

        $delivered = wc_get_orders(['status' => 'wc-delivered', 'date_created' => $from . '...' . $to, 'limit' => -1]);
        $rto = wc_get_orders(['status' => 'wc-rto', 'date_created' => $from . '...' . $to, 'limit' => -1]);

        $revenue = 0; $cost = 0; $shipping = 0; $items_count = 0;
        foreach ($delivered as $o) {
            $revenue += (float)$o->get_total();
            $shipping += (float)$o->get_shipping_total();
            foreach ($o->get_items() as $item) {
                $pc = (float)get_post_meta($item->get_product_id(), '_dzqcod_cost', true);
                $cost += $pc * $item->get_quantity();
                $items_count += $item->get_quantity();
            }
        }

        $rto_cost = 0; $rto_shipping = 0;
        foreach ($rto as $o) {
            $rto_shipping += (float)$o->get_shipping_total();
            foreach ($o->get_items() as $item) {
                $rto_cost += (float)get_post_meta($item->get_product_id(), '_dzqcod_cost', true) * $item->get_quantity();
            }
        }

        $ad_spend = (float)Core::opt('ad_spend_' . gmdate('Y_m', strtotime($from)), '0');
        $gross = $revenue - $cost - $shipping;
        $net = $gross - $ad_spend - $rto_shipping;
        $margin = $revenue > 0 ? round($net / $revenue * 100, 1) : 0;

        wp_send_json_success([
            'period' => $from . ' → ' . $to,
            'orders_delivered' => count($delivered), 'orders_rto' => count($rto), 'items' => $items_count,
            'revenue' => round($revenue), 'product_cost' => round($cost), 'shipping_cost' => round($shipping),
            'gross_profit' => round($gross), 'ad_spend' => round($ad_spend), 'rto_loss' => round($rto_shipping + $rto_cost),
            'net_profit' => round($net), 'margin' => $margin,
            'roas' => $ad_spend > 0 ? round($revenue / $ad_spend, 1) : 0,
            'avg_order' => count($delivered) > 0 ? round($revenue / count($delivered)) : 0,
        ]);
    }

    public function cost_panel(): void {
        global $post; $cost = get_post_meta($post->ID, '_dzqcod_cost', true); ?>
        <div style="padding:8px 15px;border-top:1px solid #eee;background:#fffdf5">
            <label style="font-weight:600;font-size:13px">💰 تكلفة المنتج (سعر الشراء)</label>
            <input type="number" name="_dzqcod_cost" value="<?php echo esc_attr($cost); ?>" placeholder="0" min="0" step="1"
                style="width:120px;padding:6px;border:1px solid #ddd;border-radius:6px;margin-right:8px"> دج
            <small style="color:#888;display:block;margin-top:2px">يُستخدم في حساب الربح الصافي</small>
        </div>
    <?php }

    public function save_cost_meta(int $pid): void {
        check_ajax_referer('dzqcod_admin','nonce');if(!current_user_can('manage_woocommerce'))wp_send_json_error();
        if (isset($_POST['_dzqcod_cost'])) update_post_meta($pid, '_dzqcod_cost', floatval($_POST['_dzqcod_cost']));
    }

    public function save_product_cost(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        if(!current_user_can('manage_woocommerce'))wp_send_json_error();
        $pid = absint($_POST['product_id'] ?? 0);
        $cost = floatval($_POST['cost'] ?? 0);
        if ($pid) update_post_meta($pid, '_dzqcod_cost', $cost);
        wp_send_json_success();
    }

    // ═══════════════════════════════════════════════
    //  IP GEOLOCATION FRAUD CHECK
    // ═══════════════════════════════════════════════
    public function ip_geo_check(array $signals, string $phone, string $ip): array {
        if (Core::opt('ip_geo_enabled', '') !== 'yes') return $signals;
        // Primary API: ip-api.com with VPN/proxy fields
        $resp = wp_remote_get("http://ip-api.com/json/{$ip}?fields=status,country,countryCode,regionName,city,proxy,hosting", ['timeout' => 5]);
        $data = !is_wp_error($resp) ? json_decode(wp_remote_retrieve_body($resp), true) : null;

        // Fallback API if primary fails
        if (!$data || ($data['status'] ?? '') !== 'success') {
            $resp2 = wp_remote_get("https://ipapi.co/{$ip}/json/", ['timeout' => 5]);
            if (!is_wp_error($resp2)) {
                $d2 = json_decode(wp_remote_retrieve_body($resp2), true);
                if ($d2) $data = ['countryCode' => $d2['country_code'] ?? '', 'proxy' => false, 'hosting' => false,
                    'regionName' => $d2['region'] ?? '', 'city' => $d2['city'] ?? ''];
            }
        }
        if (!$data) return $signals;

        $country = Core::opt('country', 'DZ');
        if (isset($data['countryCode']) && $data['countryCode'] !== $country) {
            $signals[] = 'ip_foreign_country:' . ($data['countryCode'] ?? '?');
        }
        // VPN/Proxy detection
        if (!empty($data['proxy']) || !empty($data['hosting'])) {
            $signals[] = 'ip_vpn_proxy';
        }
        // Store geo data for analytics
        $signals['_geo'] = ['country' => $data['countryCode'] ?? '', 'region' => $data['regionName'] ?? '', 'city' => $data['city'] ?? ''];
        return $signals;
    }

    // ═══════════════════════════════════════════════
    //  PHONE OTP VERIFICATION
    // ═══════════════════════════════════════════════
    public function send_otp(): void {
        if (Core::opt('otp_enabled', '') !== 'yes') wp_send_json_error(['message' => 'OTP معطّل']);
        $phone = sanitize_text_field($_POST['phone'] ?? '');
        $email = sanitize_email($_POST['email'] ?? '');
        $channel = sanitize_key($_POST['otp_channel'] ?? 'sms'); // sms, whatsapp, email

        if ($channel === 'email') {
            if (!$email || !is_email($email)) wp_send_json_error(['message' => 'بريد إلكتروني غير صالح']);
            $key = md5($email);
        } else {
            if (!$phone || !preg_match('/^0[567]\d{8}$/', $phone)) wp_send_json_error(['message' => 'رقم غير صالح']);
            $key = md5($phone);
        }

        // Rate limit — 3 per 5 min, with 30s cooldown between sends
        $rl = 'dzqcod_otp_rl_' . $key;
        $cd = 'dzqcod_otp_cd_' . $key;
        if (get_transient($cd)) wp_send_json_error(['message' => 'انتظر 30 ثانية قبل إعادة الإرسال', 'cooldown' => true]);
        if ((int)get_transient($rl) >= 3) wp_send_json_error(['message' => 'حاولت كثيراً، انتظر 5 دقائق']);

        $code = str_pad(random_int(1000, 9999), 4, '0', STR_PAD_LEFT);
        set_transient('dzqcod_otp_' . $key, $code, 300);
        set_transient($rl, ((int)get_transient($rl)) + 1, 300);
        set_transient($cd, 1, 30); // 30s cooldown

        $msg = str_replace('{code}', $code, Core::opt('otp_message', 'رمز التحقق: {code} — DZQCOD'));

        if ($channel === 'email' && $email) {
            wp_mail($email, 'رمز التحقق — DZQCOD', $msg, ['Content-Type: text/plain; charset=UTF-8']);
            wp_send_json_success(['message' => 'تم إرسال رمز التحقق إلى بريدك', 'channel' => 'email']);
        } elseif ($channel === 'whatsapp') {
            $wa_api = Core::opt('wa_api_url', '');
            $wa_token = Core::opt('wa_api_token', '');
            if ($wa_api && $wa_token) {
                wp_remote_post($wa_api, ['headers' => ['Authorization' => 'Bearer ' . $wa_token, 'Content-Type' => 'application/json'],
                    'body' => wp_json_encode(['phone' => '213' . substr($phone, 1), 'message' => $msg]), 'timeout' => 10]);
            }
            wp_send_json_success(['message' => 'تم إرسال OTP عبر واتساب', 'channel' => 'whatsapp']);
        } else {
            // SMS
            $sms_api = Core::opt('sms_api_key', '');
            $sms_provider = Core::opt('sms_provider', '');
            if ($sms_provider && $sms_api) {
                $phone_intl = '213' . substr($phone, 1);
                wp_remote_post(Core::opt('sms_api_url', ''), ['body' => ['to' => $phone_intl, 'message' => $msg, 'api_key' => $sms_api], 'timeout' => 10]);
            }
            // Fallback to WhatsApp
            $wa_api = Core::opt('wa_api_url', '');
            $wa_token = Core::opt('wa_api_token', '');
            if ($wa_api && $wa_token) {
                wp_remote_post($wa_api, ['headers' => ['Authorization' => 'Bearer ' . $wa_token, 'Content-Type' => 'application/json'],
                    'body' => wp_json_encode(['phone' => '213' . substr($phone, 1), 'message' => $msg]), 'timeout' => 10]);
            }
            wp_send_json_success(['message' => 'تم إرسال رمز التحقق إلى ' . substr($phone, 0, 4) . '****', 'channel' => 'sms']);
        }
    }

    public function verify_otp(): void {
        $phone = sanitize_text_field($_POST['phone'] ?? '');
        $code = sanitize_text_field($_POST['code'] ?? '');
        $stored = get_transient('dzqcod_otp_' . md5($phone));
        if (!$stored || $stored !== $code) wp_send_json_error(['message' => 'رمز خاطئ']);
        delete_transient('dzqcod_otp_' . md5($phone));
        set_transient('dzqcod_otp_verified_' . md5($phone), 'yes', 1800); // 30 min
        wp_send_json_success(['message' => '✅ تم التحقق']);
    }

    // ═══════════════════════════════════════════════
    //  COHORT ANALYSIS
    // ═══════════════════════════════════════════════
    public function cohort_data(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        $months = 6; $cohorts = [];
        for ($m = $months - 1; $m >= 0; $m--) {
            $start = gmdate('Y-m-01', strtotime("-{$m} months"));
            $end = gmdate('Y-m-t', strtotime("-{$m} months"));
            $label = gmdate('Y-m', strtotime("-{$m} months"));

            // New customers this month
            $orders = wc_get_orders(['status' => array_map(fn($s) => 'wc-' . $s, array_keys(Core::ST)),
                'date_created' => $start . '...' . $end, 'limit' => -1]);
            $phones = [];
            foreach ($orders as $o) { $p = $o->get_billing_phone(); if ($p) $phones[$p] = true; }

            // How many repeat in next months
            $retention = [];
            for ($n = 1; $n <= min(3, $m); $n++) {
                $ns = gmdate('Y-m-01', strtotime("-" . ($m - $n) . " months"));
                $ne = gmdate('Y-m-t', strtotime("-" . ($m - $n) . " months"));
                $next_orders = wc_get_orders(['status' => ['wc-delivered', 'wc-confirmed', 'wc-shipped'],
                    'date_created' => $ns . '...' . $ne, 'limit' => -1]);
                $repeat = 0;
                foreach ($next_orders as $no) { if (isset($phones[$no->get_billing_phone()])) $repeat++; }
                $retention['month_' . $n] = count($phones) > 0 ? round($repeat / count($phones) * 100, 1) : 0;
            }

            $delivered = array_filter($orders, fn($o) => $o->get_status() === 'wc-delivered');
            $cohorts[] = ['month' => $label, 'new_customers' => count($phones), 'orders' => count($orders),
                'delivered' => count($delivered), 'retention' => $retention];
        }
        wp_send_json_success(['cohorts' => $cohorts]);
    }

    // ═══════════════════════════════════════════════
    //  HEATMAP TRACKING
    // ═══════════════════════════════════════════════
    public function track_heatmap(): void {
        $input = file_get_contents('php://input'); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- reading php://input stream
        $data = $input ? json_decode($input, true) : null;
        if (!$data || empty($data['events'])) wp_send_json_error();

        global $wpdb;
        $t = $wpdb->prefix . \DZQCOD_DB . 'heatmap';
        $wpdb->query("CREATE TABLE IF NOT EXISTS {$t} (
            id BIGINT AUTO_INCREMENT PRIMARY KEY, product_id BIGINT, field VARCHAR(50),
            event_type ENUM('focus','blur','change','click','submit','abandon') DEFAULT 'focus',
            time_spent INT DEFAULT 0, session_id VARCHAR(40),
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP, INDEX(product_id,field)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

        $sid = sanitize_text_field($data['session_id'] ?? wp_generate_uuid4());
        foreach ($data['events'] as $ev) {
            $wpdb->insert($t, ['product_id' => absint($ev['pid'] ?? 0), 'field' => sanitize_text_field($ev['field'] ?? ''),
                'event_type' => sanitize_text_field($ev['type'] ?? 'focus'), 'time_spent' => absint($ev['time'] ?? 0), 'session_id' => $sid]);
        }
        wp_send_json_success();
    }

    public function heatmap_data(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        global $wpdb;
        $t = $wpdb->prefix . \DZQCOD_DB . 'heatmap';
        if (!$wpdb->get_var("SHOW TABLES LIKE '{$t}'")) wp_send_json_success(['fields' => []]);

        $data = $wpdb->get_results("SELECT field, event_type, COUNT(*) as count, AVG(time_spent) as avg_time
            FROM {$t} WHERE created_at>DATE_SUB(NOW(),INTERVAL 30 DAY)
            GROUP BY field, event_type ORDER BY count DESC");
        $abandon = $wpdb->get_results("SELECT field, COUNT(*) as count FROM {$t}
            WHERE event_type='abandon' AND created_at>DATE_SUB(NOW(),INTERVAL 30 DAY) GROUP BY field ORDER BY count DESC LIMIT 5");
        wp_send_json_success(['fields' => $data, 'drop_off' => $abandon]);
    }

    // ═══════════════════════════════════════════════
    //  TELEGRAM BOT — Moved to includes/TelegramBot.php
    // ═══════════════════════════════════════════

    //  ANALYTICS PRO — Dashboard data
    // ═══════════════════════════════════════════
    public function analytics_dashboard(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        $days = (int)($_POST['days'] ?? 30);
        $from = gmdate('Y-m-d', strtotime("-{$days} days"));

        $daily = []; $statuses = [];
        for ($d = 0; $d < $days; $d++) {
            $date = gmdate('Y-m-d', strtotime("-{$d} days"));
            $orders = wc_get_orders(['date_created' => $date . '...' . gmdate('Y-m-d', strtotime($date . ' +1 day')), 'limit' => -1]);
            $rev = 0; foreach ($orders as $o) $rev += (float)$o->get_total();
            $daily[] = ['date' => $date, 'orders' => count($orders), 'revenue' => round($rev)];
            foreach ($orders as $o) {
                $st = str_replace('wc-', '', $o->get_status());
                $statuses[$st] = ($statuses[$st] ?? 0) + 1;
            }
        }

        // Top products
        $all_orders = wc_get_orders(['date_created' => '>' . $from, 'limit' => -1, 'status' => array_map(fn($s) => 'wc-' . $s, array_keys(Core::ST))]);
        $products = [];
        foreach ($all_orders as $o) {
            foreach ($o->get_items() as $i) {
                $pid = $i->get_product_id();
                if (!isset($products[$pid])) $products[$pid] = ['name' => $i->get_name(), 'qty' => 0, 'revenue' => 0];
                $products[$pid]['qty'] += $i->get_quantity();
                $products[$pid]['revenue'] += (float)$i->get_total();
            }
        }
        usort($products, fn($a, $b) => $b['qty'] - $a['qty']);

        // Top wilayas
        $wilayas = [];
        foreach ($all_orders as $o) {
            $w = $o->get_shipping_state() ?: 'غير محدد';
            $wilayas[$w] = ($wilayas[$w] ?? 0) + 1;
        }
        arsort($wilayas);

        // Conversion funnel
        $total = count($all_orders);
        $confirmed = count(array_filter($all_orders, fn($o) => in_array(str_replace('wc-', '', $o->get_status()), ['confirmed', 'shipped', 'delivered', 'in-transit', 'out-for-delivery'])));
        $delivered = count(array_filter($all_orders, fn($o) => $o->get_status() === 'wc-delivered'));

        wp_send_json_success([
            'daily' => array_reverse($daily),
            'statuses' => $statuses,
            'top_products' => array_slice($products, 0, 10),
            'top_wilayas' => array_slice($wilayas, 0, 10, true),
            'funnel' => ['total' => $total, 'confirmed' => $confirmed, 'delivered' => $delivered,
                         'confirm_rate' => $total > 0 ? round($confirmed / $total * 100, 1) : 0,
                         'delivery_rate' => $confirmed > 0 ? round($delivered / $confirmed * 100, 1) : 0],
            'avg_order' => $total > 0 ? round(array_sum(array_column($daily, 'revenue')) / max(1, array_sum(array_column($daily, 'orders')))) : 0,
        ]);
    }

    // ═══════════════════════════════════════════
    //  A/B TESTING — Form variant split
    // ═══════════════════════════════════════════
    public function ab_save(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        if (!current_user_can('manage_options')) wp_send_json_error();
        $test = [
            'enabled' => sanitize_text_field($_POST['enabled'] ?? 'no'),
            'product_id' => absint($_POST['product_id'] ?? 0),
            'variant_a' => sanitize_text_field($_POST['variant_a'] ?? 'default'),
            'variant_b' => sanitize_text_field($_POST['variant_b'] ?? 'minimal'),
            'split' => min(100, max(0, (int)($_POST['split'] ?? 50))),
            'started_at' => current_time('mysql'),
        ];
        update_option('dzqcod_ab_test', wp_json_encode($test), false);
        wp_send_json_success(['message' => 'تم حفظ اختبار A/B ✅']);
    }

    public function ab_data(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        global $wpdb;
        $t = $wpdb->prefix . \DZQCOD_DB . 'ab_tests';
        if (!$wpdb->get_var("SHOW TABLES LIKE '{$t}'")) { wp_send_json_success(['tests' => []]); return; }
        $data = $wpdb->get_results("SELECT variant, COUNT(*) as views, SUM(converted) as conversions FROM {$t} WHERE created_at > DATE_SUB(NOW(), INTERVAL 30 DAY) GROUP BY variant");
        $results = [];
        foreach ($data as $row) {
            $results[] = ['variant' => $row->variant, 'views' => (int)$row->views, 'conversions' => (int)$row->conversions,
                'rate' => $row->views > 0 ? round($row->conversions / $row->views * 100, 1) : 0];
        }
        wp_send_json_success(['tests' => $results, 'config' => json_decode(Core::opt('dzqcod_ab_test', '{}'), true)]);
    }

    // Track A/B variant (called from front.js)
    public static function get_ab_variant(): string {
        $test = json_decode(get_option('dzqcod_ab_test', '{}'), true);
        if (($test['enabled'] ?? 'no') !== 'yes') return 'default';
        $rand = mt_rand(1, 100);
        return $rand <= ($test['split'] ?? 50) ? ($test['variant_a'] ?? 'default') : ($test['variant_b'] ?? 'minimal');
    }

    // ═══════════════════════════════════════════
    //  AI COPILOT — Generate text with AI API
    // ═══════════════════════════════════════════
    public function ai_generate(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        $api_key = Core::opt('ai_api_key', '');
        $provider = Core::opt('ai_provider', 'openai'); // openai or anthropic
        $type = sanitize_text_field($_POST['type'] ?? 'description'); // description, ad, reply, seo
        $context = sanitize_textarea_field($_POST['context'] ?? '');
        if (!$api_key) wp_send_json_error(['message' => 'مفتاح AI API غير مضبوط']);

        $prompts = [
            'description' => "اكتب وصفاً تسويقياً جذاباً بالعربية لهذا المنتج: {$context}. الوصف يجب أن يكون 3-4 أسطر، يبرز الفوائد، ويحفّز على الشراء.",
            'ad' => "اكتب إعلاناً قصيراً بالعربية لفيسبوك/إنستغرام لهذا المنتج: {$context}. استخدم إيموجي وعبارات تحفيزية. 2-3 أسطر مع CTA.",
            'reply' => "أنت خدمة عملاء متجر جزائري. العميل يقول: {$context}. أجب بأدب ومهنية بالعربية الجزائرية.",
            'seo' => "اكتب عنوان SEO ووصف meta بالعربية لهذا المنتج: {$context}. العنوان أقل من 60 حرف، الوصف أقل من 160 حرف.",
        ];
        $prompt = $prompts[$type] ?? $prompts['description'];

        if ($provider === 'anthropic') {
            $r = wp_remote_post('https://api.anthropic.com/v1/messages', [
                'headers' => ['x-api-key' => $api_key, 'Content-Type' => 'application/json', 'anthropic-version' => '2023-06-01'],
                'body' => wp_json_encode(['model' => 'claude-sonnet-4-20250514', 'max_tokens' => 500, 'messages' => [['role' => 'user', 'content' => $prompt]]]),
                'timeout' => 30
            ]);
        } else { // OpenAI
            $r = wp_remote_post('https://api.openai.com/v1/chat/completions', [
                'headers' => ['Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json'],
                'body' => wp_json_encode(['model' => 'gpt-4o-mini', 'messages' => [['role' => 'user', 'content' => $prompt]], 'max_tokens' => 500]),
                'timeout' => 30
            ]);
        }

        if (is_wp_error($r)) wp_send_json_error(['message' => 'خطأ API: ' . $r->get_error_message()]);
        $body = json_decode(wp_remote_retrieve_body($r), true);

        $text = '';
        if ($provider === 'anthropic') $text = $body['content'][0]['text'] ?? '';
        else $text = $body['choices'][0]['message']['content'] ?? '';

        if ($text) wp_send_json_success(['text' => $text, 'type' => $type]);
        else wp_send_json_error(['message' => 'لم يتم توليد نص', 'raw' => $body]);
    }

    // ═══════════════════════════════════════════
    //  EMAIL MARKETING — Mailchimp/Sendinblue sync
    // ═══════════════════════════════════════════
    public function email_save(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        if (!current_user_can('manage_options')) wp_send_json_error();
        foreach (['email_provider', 'email_api_key', 'email_list_id', 'email_auto_sync'] as $k) {
            if (isset($_POST[$k])) update_option('dzqcod_' . $k, sanitize_text_field($_POST[$k]), false);
        }
        wp_send_json_success(['message' => 'تم حفظ إعدادات Email ✅']);
    }

    public function email_sync_subscriber(int $oid, $order): void {
        if (Core::opt('email_auto_sync', '') !== 'yes') return;
        $provider = Core::opt('email_provider', '');
        $api_key = Core::opt('email_api_key', '');
        $list_id = Core::opt('email_list_id', '');
        if (!$provider || !$api_key) return;

        $email = $order->get_billing_email();
        $name = $order->get_billing_first_name();
        if (!$email) return;

        switch ($provider) {
            case 'mailchimp':
                $dc = explode('-', $api_key); $dc = end($dc);
                wp_remote_post("https://{$dc}.api.mailchimp.com/3.0/lists/{$list_id}/members", [
                    'headers' => ['Authorization' => 'Basic ' . base64_encode('user:' . $api_key), 'Content-Type' => 'application/json'],
                    'body' => wp_json_encode(['email_address' => $email, 'status' => 'subscribed',
                        'merge_fields' => ['FNAME' => $name, 'PHONE' => $order->get_billing_phone(), 'WILAYA' => $order->get_shipping_state()]]),
                    'timeout' => 10, 'blocking' => false
                ]);
                break;
            case 'sendinblue':
            case 'brevo':
                wp_remote_post('https://api.brevo.com/v3/contacts', [
                    'headers' => ['api-key' => $api_key, 'Content-Type' => 'application/json'],
                    'body' => wp_json_encode(['email' => $email, 'listIds' => [(int)$list_id], 'updateEnabled' => true,
                        'attributes' => ['FIRSTNAME' => $name, 'PHONE' => $order->get_billing_phone(), 'WILAYA' => $order->get_shipping_state()]]),
                    'timeout' => 10, 'blocking' => false
                ]);
                break;
        }
    }

    // ═══════════════════════════════════════════════
    //  WORKFLOWS — Simple IF/THEN automation engine
    // ═══════════════════════════════════════════════
    public static function workflows_init(): void {
        add_action('wp_ajax_dzqcod_workflow_save', [__CLASS__, 'workflow_save']);
        add_action('wp_ajax_dzqcod_workflow_list', [__CLASS__, 'workflow_list']);
        add_action('wp_ajax_dzqcod_workflow_delete', [__CLASS__, 'workflow_delete']);
        add_action('woocommerce_order_status_changed', [__CLASS__, 'workflow_trigger'], 90, 4);
        add_action('dzqcod_order_created', [__CLASS__, 'workflow_trigger_new'], 90, 2);
    }

    public static function workflow_save(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        if (!current_user_can('manage_options')) wp_send_json_error();
        $workflow = [
            'id' => sanitize_key($_POST['id'] ?? wp_generate_uuid4()),
            'name' => sanitize_text_field($_POST['name'] ?? ''),
            'trigger' => sanitize_key($_POST['trigger'] ?? ''), // new_order, status_change, high_fraud, high_value
            'condition_field' => sanitize_key($_POST['condition_field'] ?? ''), // total, wilaya, fraud_score, status
            'condition_op' => sanitize_key($_POST['condition_op'] ?? 'eq'), // eq, gt, lt, contains
            'condition_value' => sanitize_text_field($_POST['condition_value'] ?? ''),
            'action' => sanitize_key($_POST['action'] ?? ''), // change_status, send_whatsapp, send_sms, add_note, send_webhook
            'action_value' => sanitize_text_field($_POST['action_value'] ?? ''),
            'enabled' => ($_POST['enabled'] ?? 'yes') === 'yes',
        ];
        $all = json_decode(get_option('dzqcod_workflows', '[]'), true) ?: [];
        $found = false;
        foreach ($all as &$w) { if ($w['id'] === $workflow['id']) { $w = $workflow; $found = true; break; } }
        if (!$found) $all[] = $workflow;
        update_option('dzqcod_workflows', wp_json_encode($all), false);
        wp_send_json_success(['message' => 'تم حفظ سير العمل ✅']);
    }

    public static function workflow_list(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        wp_send_json_success(['workflows' => json_decode(get_option('dzqcod_workflows', '[]'), true) ?: []]);
    }

    public static function workflow_delete(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        $id = sanitize_key($_POST['id'] ?? '');
        $all = json_decode(get_option('dzqcod_workflows', '[]'), true) ?: [];
        $all = array_values(array_filter($all, fn($w) => $w['id'] !== $id));
        update_option('dzqcod_workflows', wp_json_encode($all), false);
        wp_send_json_success();
    }

    public static function workflow_trigger(int $oid, string $from, string $to, $order): void {
        self::run_workflows('status_change', $order, ['from' => $from, 'to' => $to]);
    }

    public static function workflow_trigger_new(int $oid, $order): void {
        self::run_workflows('new_order', $order);
    }

    private static function run_workflows(string $trigger, $order, array $extra = []): void {
        $all = json_decode(get_option('dzqcod_workflows', '[]'), true) ?: [];
        foreach ($all as $w) {
            if (!$w['enabled'] || $w['trigger'] !== $trigger) continue;
            // Check condition
            $val = '';
            switch ($w['condition_field']) {
                case 'total': $val = (float)$order->get_total(); break;
                case 'wilaya': $val = $order->get_shipping_state(); break;
                case 'fraud_score': $val = (int)$order->get_meta('_dzqcod_fraud_score'); break;
                case 'status': $val = str_replace('wc-', '', $extra['to'] ?? $order->get_status()); break;
                case 'payment': $val = $order->get_payment_method_title(); break;
            }
            $cv = $w['condition_value'];
            $match = false;
            switch ($w['condition_op']) {
                case 'eq': $match = ((string)$val === $cv); break;
                case 'gt': $match = ((float)$val > (float)$cv); break;
                case 'lt': $match = ((float)$val < (float)$cv); break;
                case 'contains': $match = (stripos((string)$val, $cv) !== false); break;
                case 'any': $match = true; break;
            }
            if (!$match) continue;
            // Execute action
            switch ($w['action']) {
                case 'change_status': $order->set_status('wc-' . $w['action_value']); $order->add_order_note('⚡ Workflow: ' . $w['name']); $order->save(); break;
                case 'add_note': $order->add_order_note('⚡ ' . $w['action_value']); $order->save(); break;
                case 'send_webhook':
                    wp_remote_post($w['action_value'], ['headers' => ['Content-Type' => 'application/json'], 'body' => wp_json_encode([
                        'workflow' => $w['name'], 'order_id' => $order->get_id(), 'trigger' => $trigger,
                        'phone' => $order->get_billing_phone(), 'total' => (float)$order->get_total()]),
                        'timeout' => 10, 'blocking' => false]); break;
                case 'send_whatsapp':
                    $wa_api = Core::opt('wa_api_url', ''); $wa_token = Core::opt('wa_api_token', '');
                    if ($wa_api) wp_remote_post($wa_api, ['headers' => ['Authorization' => 'Bearer ' . $wa_token, 'Content-Type' => 'application/json'],
                        'body' => wp_json_encode(['phone' => '213' . substr($order->get_billing_phone(), 1),
                            'message' => str_replace(['{name}', '{order_id}', '{total}'], [$order->get_billing_first_name(), $order->get_id(), number_format((float)$order->get_total(), 0)], $w['action_value'])]),
                        'timeout' => 10, 'blocking' => false]); break;
            }
        }
    }

    // ═══════════════════════════════════════════════
    //  MULTI-STORE — Tenant isolation
    // ═══════════════════════════════════════════════
    public static function multistore_init(): void {
        add_action('wp_ajax_dzqcod_store_save', [__CLASS__, 'store_save']);
        add_action('wp_ajax_dzqcod_store_list', [__CLASS__, 'store_list']);
        add_action('wp_ajax_dzqcod_store_switch', [__CLASS__, 'store_switch']);
    }

    public static function store_save(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        if (!current_user_can('manage_options')) wp_send_json_error();
        $store = ['id' => sanitize_key($_POST['id'] ?? wp_generate_uuid4()),
            'name' => sanitize_text_field($_POST['name'] ?? ''),
            'domain' => sanitize_text_field($_POST['domain'] ?? ''),
            'from_wilaya' => sanitize_text_field($_POST['from_wilaya'] ?? ''),
            'wa_number' => sanitize_text_field($_POST['wa_number'] ?? ''),
            'pixel_id' => sanitize_text_field($_POST['pixel_id'] ?? ''),
            'shipping_provider' => sanitize_key($_POST['shipping_provider'] ?? 'yalidine'),
        ];
        $stores = json_decode(get_option('dzqcod_stores', '[]'), true) ?: [];
        $found = false;
        foreach ($stores as &$s) { if ($s['id'] === $store['id']) { $s = $store; $found = true; break; } }
        if (!$found) $stores[] = $store;
        update_option('dzqcod_stores', wp_json_encode($stores), false);
        wp_send_json_success(['message' => 'تم حفظ المتجر ✅']);
    }

    public static function store_list(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        wp_send_json_success(['stores' => json_decode(get_option('dzqcod_stores', '[]'), true) ?: []]);
    }

    public static function store_switch(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        $sid = sanitize_key($_POST['store_id'] ?? '');
        $stores = json_decode(get_option('dzqcod_stores', '[]'), true) ?: [];
        foreach ($stores as $s) {
            if ($s['id'] === $sid) {
                update_option('dzqcod_active_store', $sid, false);
                // Apply store-specific settings
                if ($s['pixel_id']) update_option('dzqcod_meta_pixel_id', $s['pixel_id'], false);
                if ($s['wa_number']) update_option('dzqcod_wa_default_number', $s['wa_number'], false);
                if ($s['shipping_provider']) update_option('dzqcod_shipping_provider', $s['shipping_provider'], false);
                wp_send_json_success(['message' => 'تم التبديل إلى: ' . $s['name']]);
            }
        }
        wp_send_json_error(['message' => 'متجر غير موجود']);
    }

    // ═══════════════════════════════════════════════
    //  INSTAGRAM SHOP — Catalog sync via Commerce API
    // ═══════════════════════════════════════════════
    public static function instagram_init(): void {
        add_action('wp_ajax_dzqcod_ig_save', [__CLASS__, 'ig_save']);
        add_action('wp_ajax_dzqcod_ig_sync', [__CLASS__, 'ig_sync']);
    }

    public static function ig_save(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        foreach (['ig_catalog_id', 'ig_access_token', 'ig_business_id', 'ig_auto_sync'] as $k)
            if (isset($_POST[$k])) update_option('dzqcod_' . $k, sanitize_text_field($_POST[$k]), false);
        wp_send_json_success(['message' => 'تم حفظ إعدادات Instagram ✅']);
    }

    public static function ig_sync(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        $token = Core::opt('ig_access_token', '');
        $catalog = Core::opt('ig_catalog_id', '');
        if (!$token || !$catalog) wp_send_json_error(['message' => 'ضبط الإعدادات أولاً']);

        $products = wc_get_products(['status' => 'publish', 'limit' => 100, 'stock_status' => 'instock']);
        $synced = 0; $errors = 0;

        foreach ($products as $p) {
            $img = wp_get_attachment_url($p->get_image_id());
            if (!$img) continue;
            $item = ['retailer_id' => 'dzqcod_' . $p->get_id(), 'name' => $p->get_name(),
                'description' => wp_strip_all_tags($p->get_short_description() ?: $p->get_name()),
                'availability' => 'in stock', 'condition' => 'new', 'price' => (int)$p->get_price() . ' DZD',
                'url' => $p->get_permalink(), 'image_url' => $img, 'brand' => get_bloginfo('name')];

            $r = wp_remote_post("https://graph.facebook.com/v18.0/{$catalog}/products", [
                'headers' => ['Content-Type' => 'application/json'],
                'body' => wp_json_encode(array_merge($item, ['access_token' => $token])),
                'timeout' => 15]);
            if (!is_wp_error($r) && wp_remote_retrieve_response_code($r) < 300) $synced++;
            else $errors++;
        }

        wp_send_json_success(['message' => "تم مزامنة {$synced} منتج | {$errors} أخطاء", 'synced' => $synced, 'errors' => $errors]);
    }
}
