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

final class Core {
    private static ?self $i = null;

    /** NIBRA License Server API */
    const LICENSE_API = 'https://productes.nibra.cloud/api/v1';
    const PRODUCT_SLUG = 'dzqcod';
    public static function boot(): void { self::$i ??= new self(); self::$instance = self::$i; }
    public static function i(): self { return self::$i; }
    public static function opt(string $k, string $d=''): string { return get_option("dzqcod_{$k}", $d); }
    private static function db(): string { global $wpdb; return $wpdb->prefix.\DZQCOD_DB; }

    private function __construct() {
        // Statuses
        add_action('init', [$this, 'register_statuses']);
        add_action('init', function(){ add_shortcode('dzqcod_order', [$this,'shortcode_form']); add_shortcode('dzqcod_quick_order', [$this,'shortcode_form']); add_shortcode('dzqcod_hot_offers', [$this,'shortcode_hot_offers']); });
        add_filter('wc_order_statuses', [$this, 'wc_statuses']);
        add_filter('bulk_actions-edit-shop_order', [$this, 'bulk_statuses']);
        add_filter('bulk_actions-woocommerce_page_wc-orders', [$this, 'bulk_statuses']);

        // WC Override
        if (self::opt('form_enabled','yes')==='yes' && self::opt('form_replace_woo','yes')==='yes') {
            // Remove ALL default WooCommerce product elements
            remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_title', 5);
            remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_rating', 10);
            remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);
            remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20);
            remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
            remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_meta', 40);
            remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_sharing', 50);
            // Also remove quantity+cart for variable products
            remove_action('woocommerce_simple_add_to_cart', 'woocommerce_simple_add_to_cart', 30);
            remove_action('woocommerce_variable_add_to_cart', 'woocommerce_variable_add_to_cart', 30);
            // Add our form
            add_action('woocommerce_single_product_summary', [$this, 'render_product_form'], 5);
            // CSS to hide any remaining WooCommerce elements
            add_action('wp_head', function(){
                if(!is_product()) return;
                global $post; if(!$post || !is_object($post) || !isset($post->ID)) return;
                $prod = wc_get_product($post->ID); if(!$prod || !is_object($prod)) return;
                if(get_post_meta($prod->get_id(),'_dzqcod_disabled',true)==='yes') return;
                echo '<style>.single-product .product .summary .price,.single-product .product .summary .cart,.single-product .product .summary form.cart,.single-product .product .summary .quantity,.single-product .product .summary .single_add_to_cart_button,.single-product .product .summary .product_meta,.single-product .product .summary .woocommerce-product-rating,.product .woocommerce-tabs{display:none!important}</style>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- safe static HTML
            });
        }

        // Frontend
        add_action('wp_enqueue_scripts', [$this, 'enqueue_front']);
        add_action('wp_head', [$this, 'dynamic_css']);
        add_action('wp_head', [$this, 'tracking_pixels']);

        // Meta CAPI on order events
        add_action('dzqcod_order_created', [$this, 'fire_pixel_lead'], 5, 2);
        add_action('woocommerce_order_status_changed', [$this, 'fire_pixel_status'], 5, 4);

        // Admin
        add_action('admin_menu', [$this, 'admin_menus']);
        add_action('admin_menu', [$this, 'apply_rbac'], 999);
        add_action('admin_init', [self::class, 'maybe_redirect_wizard']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin']);

        // License verification cron
        add_action('dzqcod_license_check', [__CLASS__, 'verify_license_cron']);

        // Product metabox now handled by ProductEnhanced.php

        // Public AJAX
        foreach (['dzqcod_submit_order','dzqcod_get_communes','dzqcod_verify_order_otp','dzqcod_set_callback_pref','dzqcod_send_otp'] as $a) {
            add_action("wp_ajax_{$a}", [$this, $a]);
            add_action("wp_ajax_nopriv_{$a}", [$this, $a]);
        }
        // Admin AJAX
        foreach (['dzqcod_log_call','dzqcod_print_receipt','dzqcod_print_batch','dzqcod_save_form_settings','dzqcod_save_settings','dzqcod_export_orders','dzqcod_create_shipment','dzqcod_update_order_status','dzqcod_activate_license','dzqcod_deactivate_license','dzqcod_fraud_blacklist','dzqcod_send_message','dzqcod_save_offer','dzqcod_delete_offer','dzqcod_save_postorder_settings','dzqcod_save_product_meta','dzqcod_save_full_product','dzqcod_pos_create_order','dzqcod_add_order_note','dzqcod_clear_errors','dzqcod_refresh_notifs','dzqcod_delete_order','dzqcod_delete_product','dzqcod_delete_wilaya','dzqcod_toggle_mode'] as $a) {
            add_action("wp_ajax_{$a}", [$this, $a]);
        }

        // Status colors in admin
        add_action('admin_head', [$this, 'status_colors_css']);

        // Cron
        add_action('dzqcod_daily_cleanup', [$this, 'daily_cleanup']);
        if (!wp_next_scheduled('dzqcod_daily_cleanup')) wp_schedule_event(time(), 'daily', 'dzqcod_daily_cleanup');

        // Telemetry — send daily heartbeat to NIBRA
        add_action('dzqcod_telemetry', [$this, 'send_telemetry']);
        if (!wp_next_scheduled('dzqcod_telemetry')) wp_schedule_event(time(), 'daily', 'dzqcod_telemetry');

        // Send telemetry immediately on first admin visit (or after update)
        if (is_admin() && get_option('dzqcod_last_telemetry_ver','') !== \DZQCOD_VER) {
            add_action('admin_init', function(){
                if (get_option('dzqcod_last_telemetry_ver','') !== \DZQCOD_VER) {
                    update_option('dzqcod_last_telemetry_ver', \DZQCOD_VER, false);
                    $this->send_telemetry();
                }
            }, 999);
        }
    }

    // ════════════════════════════════════════════════════════════════
    //  TELEMETRY — reports to productes.nibra.cloud
    // ════════════════════════════════════════════════════════════════
    public function send_telemetry(): void {
        if (self::opt('telemetry_optout','') === 'yes') return;
        // Safe orders count — wc-confirmed is custom status
        $completed = function_exists('wc_orders_count') ? (int)wc_orders_count('wc-completed') : 0;
        $confirmed = 0;
        if (function_exists('wc_orders_count')) {
            try { $confirmed = (int)wc_orders_count('wc-confirmed'); } catch (\Throwable $e) { $confirmed = 0; }
        }
        $data = [
            'domain'      => preg_replace('#^https?://#', '', rtrim(site_url(), '/')),
            'plugin_ver'  => \DZQCOD_VER,
            'wp_ver'      => get_bloginfo('version'),
            'wc_ver'      => defined('WC_VERSION') ? WC_VERSION : 'n/a',
            'php_ver'     => PHP_VERSION,
            'plan'        => self::opt('license_plan','free'),
            'license_hash' => self::opt('license_key','') ? hash('sha256', self::opt('license_key','')) : '',
            'locale'      => get_locale(),
            'users'       => (int)(count_users()['total_users'] ?? 0),
            'products'    => (int)(wp_count_posts('product')->publish ?? 0),
            'orders_30d'  => $completed + $confirmed,
            'addons'      => self::opt('active_addons',''),
            'errors'      => get_option('dzqcod_last_errors',''),
            'ts'          => current_time('mysql'),
        ];
        wp_remote_post('https://dzqcod.nibra.cloud/admin/api/?route=telemetry', [
            'body'     => wp_json_encode($data),
            'headers'  => ['Content-Type' => 'application/json'],
            'timeout'  => 15,
            'blocking' => false,
            'sslverify'=> apply_filters('dzqcod_ssl_verify', true),
        ]);
        update_option('dzqcod_last_errors', '', false);
    }

    // Error tracker — captures PHP errors for telemetry
    public static function log_error(string $msg): void {
        $errors = get_option('dzqcod_last_errors', '');
        $line = '['.current_time('H:i').'] '.$msg;
        $errors = $errors ? $errors."\n".$line : $line;
        // Keep last 20 errors max
        $lines = explode("\n", $errors);
        if(count($lines) > 20) $lines = array_slice($lines, -20);
        update_option('dzqcod_last_errors', implode("\n", $lines), false);
    }

    // ════════════════════════════════════════════════════════════════
    //  STATUSES
    // ════════════════════════════════════════════════════════════════
    const ST = [
        'pending-call'=>['l'=>'بانتظار الاتصال','c'=>'#f39c12','i'=>'📞'],
        'callback'=>['l'=>'معاودة الاتصال','c'=>'#e67e22','i'=>'🔄'],
        'no-answer'=>['l'=>'لا يجيب','c'=>'#95a5a6','i'=>'❌'],
        'confirmed'=>['l'=>'مؤكد','c'=>'#27ae60','i'=>'✅'],
        'ready-to-ship'=>['l'=>'جاهز للشحن','c'=>'#2980b9','i'=>'📦'],
        'shipped'=>['l'=>'تم الشحن','c'=>'#3498db','i'=>'🚚'],
        'in-transit'=>['l'=>'في الطريق','c'=>'#1abc9c','i'=>'🛣️'],
        'out-for-delivery'=>['l'=>'قيد التوصيل','c'=>'#16a085','i'=>'🏃'],
        'delivered'=>['l'=>'تم التوصيل','c'=>'#2ecc71','i'=>'🎉'],
        'rto'=>['l'=>'مرتجع RTO','c'=>'#e74c3c','i'=>'↩️'],
        'rto-received'=>['l'=>'مرتجع مستلم','c'=>'#c0392b','i'=>'📥'],
        'cancelled'=>['l'=>'ملغي','c'=>'#7f8c8d','i'=>'🚫'],
        'fake'=>['l'=>'مزيف','c'=>'#2c3e50','i'=>'⚠️'],
        'duplicate'=>['l'=>'مكرر','c'=>'#8e44ad','i'=>'📋'],
        'postponed'=>['l'=>'مؤجل','c'=>'#d35400','i'=>'⏰'],
        'workshop-received'=>['l'=>'الورشة: مستلم','c'=>'#f97316','i'=>'📥'],
        'workshop-progress'=>['l'=>'الورشة: قيد الإنجاز','c'=>'#eab308','i'=>'⚙️'],
        'workshop-done'=>['l'=>'الورشة: منجز','c'=>'#22c55e','i'=>'✅'],
        'ready-ship'=>['l'=>'جاهز للإرسال','c'=>'#8b5cf6','i'=>'📦'],
    ];
    public function register_statuses(): void {
        foreach (self::ST as $s=>$c) {
            register_post_status('wc-'.$s, ['label'=>$c['l'],'public'=>true,'show_in_admin_status_list'=>true,'show_in_admin_all_list'=>true,'label_count'=>_n_noop($c['l'].' <span class="count">(%s)</span>',$c['l'].' <span class="count">(%s)</span>','dzqcod')]);
        }
    }
    public function wc_statuses(array $s): array { foreach(self::ST as $k=>$c) $s['wc-'.$k]=$c['l']; return $s; }
    public function bulk_statuses(array $a): array { foreach(self::ST as $k=>$c) $a['mark_'.$k]=$c['i'].' '.$c['l']; return $a; }
    public function status_colors_css(): void {
        echo '<style>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- safe static HTML
        foreach(self::ST as $k=>$c) echo ".order-status.status-{$k},.wc-{$k}{background:{$c['c']} !important;color:#fff !important;border-radius:4px;padding:2px 6px;}"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- inline script/style with escaped vars
        echo '</style>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- safe static HTML
    }

    // ════════════════════════════════════════════════════════════════
    //  TRACKING PIXELS (Meta, TikTok, Google)
    // ════════════════════════════════════════════════════════════════
    public function tracking_pixels(): void {
        $meta_pid = self::opt('meta_pixel_id', '');
        $tiktok_pid = self::opt('tiktok_pixel_id', '');
        $ga_id = self::opt('google_analytics_id', '');
        $gads_id = self::opt('google_ads_id', '');
        $gads_label = self::opt('google_ads_label', '');
        if (!$meta_pid && !$tiktok_pid && !$ga_id && !$gads_id) return;
        echo '<!-- DZQCOD Tracking -->'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- safe static HTML
        // Meta Pixel + Advanced Matching
        if ($meta_pid) {
            $am = ''; // Advanced Matching
            echo "<script>!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js');fbq('init','" . esc_js($meta_pid) . "');fbq('track','PageView');</script>"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- inline tracking script with esc_js vars
            // ViewContent on product page
            if (is_singular('product')) {
                global $post; $p = wc_get_product($post->ID);
                if ($p) echo "<script>fbq('track','ViewContent',{content_name:'" . esc_js($p->get_name()) . "',content_ids:['" . $p->get_id() . "'],content_type:'product',value:" . (float)$p->get_price() . ",currency:'DZD'});</script>"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- inline tracking script with esc_js vars
            }
        }
        // TikTok Pixel + ViewContent
        if ($tiktok_pid) {
            echo "<script>!function(w,d,t){w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=['page','track','identify','instances','debug','on','off','once','ready','alias','group','enableCookie','disableCookie'];ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndDefer(e,ttq.methods[n]);return e};ttq.load=function(e,n){var i='https://analytics.tiktok.com/i18n/pixel/events.js';ttq._i=ttq._i||{};ttq._i[e]=[];ttq._i[e]._u=i;ttq._t=ttq._t||{};ttq._t[e+\"_\"+n]=1;var o=document.createElement('script');o.type='text/javascript';o.async=!0;o.src=i+'?sdkid='+e+'&lib='+t;var a=document.getElementsByTagName('script')[0];a.parentNode.insertBefore(o,a)};ttq.load('" . esc_js($tiktok_pid) . "');ttq.page();}(window,document,'ttq');</script>"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- inline tracking script with esc_js vars
            if (is_singular('product')) {
                global $post; $p = wc_get_product($post->ID);
                if ($p) echo "<script>ttq.track('ViewContent',{content_id:'" . $p->get_id() . "',content_name:'" . esc_js($p->get_name()) . "',value:" . (float)$p->get_price() . ",currency:'DZD'});</script>"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- inline tracking script with esc_js vars
            }
        }
        // Google Analytics + Ads
        if ($ga_id || $gads_id) {
            $tag = $ga_id ?: $gads_id;
            echo "<script async src='https://www.googletagmanager.com/gtag/js?id=" . esc_attr($tag) . "'></script><script>window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag('js',new Date());";
            if ($ga_id) echo "gtag('config','" . esc_js($ga_id) . "');"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- tracking script continuation
            if ($gads_id) echo "gtag('config','" . esc_js($gads_id) . "');"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- tracking script continuation
            echo "</script>"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- tracking script continuation
        }
    }

    public function fire_pixel_lead(int $oid, $order): void {
        $event_id = 'dzqcod_lead_' . $oid . '_' . time();
        $phone_hash = hash('sha256', preg_replace('/^0/', '213', $order->get_billing_phone()));
        $fn_hash = hash('sha256', strtolower(trim($order->get_billing_first_name())));
        $total = (float)$order->get_total();
        $items = []; foreach ($order->get_items() as $i) $items[] = ['id' => (string)$i->get_product_id(), 'quantity' => $i->get_quantity(), 'item_price' => (float)$i->get_total()/$i->get_quantity()];

        // Meta CAPI — Lead + InitiateCheckout with event_id dedup
        $meta_token = self::opt('meta_capi_token', '');
        $meta_pid = self::opt('meta_pixel_id', '');
        if ($meta_token && $meta_pid) {
            $user_data = ['ph' => [$phone_hash], 'fn' => [$fn_hash], 'country' => [hash('sha256', 'dz')],
                'client_ip_address' => $_SERVER['REMOTE_ADDR'] ?? '', 'client_user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? ''];
            $data = ['data' => [
                ['event_name' => 'Lead', 'event_time' => time(), 'event_id' => $event_id,
                 'action_source' => 'website', 'event_source_url' => home_url(),
                 'user_data' => $user_data,
                 'custom_data' => ['currency' => 'DZD', 'value' => $total, 'content_name' => 'Order #' . $oid,
                    'contents' => array_map(fn($i) => ['id' => $i['id'], 'quantity' => $i['quantity']], $items)]],
                ['event_name' => 'InitiateCheckout', 'event_time' => time(), 'event_id' => 'dzqcod_ic_' . $oid,
                 'action_source' => 'website', 'user_data' => $user_data,
                 'custom_data' => ['currency' => 'DZD', 'value' => $total, 'num_items' => count($items)]]
            ]];
            wp_remote_post("https://graph.facebook.com/v18.0/{$meta_pid}/events?access_token={$meta_token}",
                ['body' => wp_json_encode($data), 'headers' => ['Content-Type' => 'application/json'], 'timeout' => 10, 'blocking' => false]);
        }

        // TikTok Events API — server-side
        $tt_token = self::opt('tiktok_access_token', '');
        $tt_pid = self::opt('tiktok_pixel_id', '');
        if ($tt_token && $tt_pid) {
            $tt_data = ['pixel_code' => $tt_pid, 'event' => 'SubmitForm', 'event_id' => $event_id,
                'timestamp' => gmdate('c'), 'context' => ['user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'ip' => $_SERVER['REMOTE_ADDR'] ?? ''],
                'properties' => ['contents' => array_map(fn($i) => ['content_id' => $i['id'], 'quantity' => $i['quantity'], 'price' => $i['item_price']], $items),
                    'currency' => 'DZD', 'value' => $total]];
            wp_remote_post('https://business-api.tiktok.com/open_api/v1.3/pixel/track/', [
                'headers' => ['Access-Token' => $tt_token, 'Content-Type' => 'application/json'],
                'body' => wp_json_encode(['data' => [$tt_data]]), 'timeout' => 10, 'blocking' => false]);
        }

        // Google Ads Conversion
        $gads_id = self::opt('google_ads_id', '');
        $gads_label = self::opt('google_ads_label', '');
        if ($gads_id && $gads_label) {
            $order->update_meta_data('_dzqcod_gads_conversion_pending', 'yes');
            $order->save();
        }
    }

    public function fire_pixel_status(int $oid, string $from, string $to, $order): void {
        $st = str_replace('wc-', '', $to);
        $total = (float)$order->get_total();
        $phone_hash = hash('sha256', preg_replace('/^0/', '213', $order->get_billing_phone()));

        // Meta CAPI — Purchase on confirmed, OfflineConversion on delivered
        $meta_token = self::opt('meta_capi_token', '');
        $meta_pid = self::opt('meta_pixel_id', '');
        if ($meta_token && $meta_pid) {
            $events_map = ['confirmed' => 'Purchase', 'delivered' => 'OfflineConversion', 'rto' => 'CancelOrder'];
            if (isset($events_map[$st])) {
                $data = ['data' => [['event_name' => $events_map[$st], 'event_time' => time(),
                    'event_id' => 'dzqcod_' . $st . '_' . $oid, 'action_source' => $st === 'delivered' ? 'physical_store' : 'website',
                    'user_data' => ['ph' => [$phone_hash], 'client_ip_address' => $_SERVER['REMOTE_ADDR'] ?? ''],
                    'custom_data' => ['currency' => 'DZD', 'value' => $total, 'order_id' => (string)$oid]]]];
                wp_remote_post("https://graph.facebook.com/v18.0/{$meta_pid}/events?access_token={$meta_token}",
                    ['body' => wp_json_encode($data), 'headers' => ['Content-Type' => 'application/json'], 'timeout' => 10, 'blocking' => false]);
            }
        }

        // TikTok — CompletePayment on confirmed
        $tt_token = self::opt('tiktok_access_token', '');
        $tt_pid = self::opt('tiktok_pixel_id', '');
        if ($tt_token && $tt_pid && $st === 'confirmed') {
            wp_remote_post('https://business-api.tiktok.com/open_api/v1.3/pixel/track/', [
                'headers' => ['Access-Token' => $tt_token, 'Content-Type' => 'application/json'],
                'body' => wp_json_encode(['data' => [['pixel_code' => $tt_pid, 'event' => 'CompletePayment',
                    'event_id' => 'dzqcod_pay_' . $oid, 'timestamp' => gmdate('c'),
                    'properties' => ['currency' => 'DZD', 'value' => $total, 'content_type' => 'product']]]]),
                'timeout' => 10, 'blocking' => false]);
        }

        // Google Ads — conversion on confirmed
        $gads_id = self::opt('google_ads_id', '');
        $gads_label = self::opt('google_ads_label', '');
        if ($gads_id && $gads_label && $st === 'confirmed') {
            // Store conversion data for frontend firing
            $order->update_meta_data('_dzqcod_gads_fired', 'yes');
            $order->save();
        }
    }

    // ════════════════════════════════════════════════════════════════
    //  THE FORM — Product page override + Shortcode
    // ════════════════════════════════════════════════════════════════
    public function render_product_form(): void {
        global $product, $post;
        // Try global $product first, fallback to wc_get_product($post->ID)
        $p = null;
        if ($product && is_object($product) && method_exists($product, 'get_id')) $p = $product;
        elseif ($post) $p = wc_get_product($post->ID);
        if (!$p) { woocommerce_template_single_add_to_cart(); return; }
        if (get_post_meta($p->get_id(),'_dzqcod_disabled',true)==='yes') { woocommerce_template_single_add_to_cart(); return; }
        echo $this->build_form($p->get_id(), false); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- internally generated HTML with escaped variables
    }
    public function shortcode_form(array $a=[]): string {
        $a=shortcode_atts(['product_id'=>0],$a);$pid=absint($a['product_id']);
        if(!$pid){global $product,$post;if($product && is_object($product))$pid=$product->get_id();elseif($post)$pid=$post->ID;}
        return $pid?$this->build_form($pid,true):'';
    }

    private static $instance;
    public static function inst(): self { return self::$instance ?? self::$i; }
    public function build_form_public(int $pid, bool $show_img): string { return $this->build_form($pid, $show_img); }
    public function shortcode_hot_offers(array $a=[]): string {
        global $wpdb; $p=self::db();
        $offers=$wpdb->get_results("SELECT * FROM {$p}offers WHERE is_active=1 AND (ends_at IS NULL OR ends_at > NOW()) ORDER BY priority ASC, id DESC");
        if(empty($offers)) return '<div style="text-align:center;padding:40px;color:#94a3b8">لا توجد عروض حالياً</div>';
        $currency=self::opt('currency_symbol','دج'); $pc=self::opt('form_primary_color','#667eea');$gc=self::opt('form_success_color','#27ae60');
        $r=intval(self::opt('form_border_radius','12'));
        ob_start(); ?>
<div class="dzqcod-hot-offers" dir="rtl" style="max-width:800px;margin:0 auto;padding:16px;font-family:Arial,Tahoma,sans-serif">
<h2 style="text-align:center;font-size:24px;margin-bottom:20px">🔥 العروض الساخنة</h2>
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px">
<?php foreach($offers as $of):
$types=['percentage'=>'خصم','fixed'=>'تخفيض','free_shipping'=>'شحن مجاني','buy_x_get_y'=>'عرض خاص'];
$val=$of->type==='percentage'?$of->value.'%':($of->type==='free_shipping'?'🚚 مجاني':number_format($of->value,0).' '.$currency);
$tid='coupon-'.$of->id; ?>
<div style="background:#fff;border-radius:<?php echo esc_html($r);?>px;border:2px solid #e2e8f0;padding:20px;text-align:center;transition:.2s" onmouseenter="this.style.borderColor='<?php echo esc_html($pc);?>'" onmouseleave="this.style.borderColor='#e2e8f0'">
<div style="font-size:36px;font-weight:900;color:<?php echo esc_html($pc);?>"><?php echo esc_html($val);?></div>
<h3 style="margin:8px 0 4px;font-size:16px"><?php echo esc_html($of->name);?></h3>
<?php if(!empty($of->description)):?><p style="font-size:13px;color:#64748b;margin:0 0 10px"><?php echo esc_html($of->description);?></p><?php endif;?>
<?php if(!empty($of->coupon_code)):?>
<div style="margin:12px 0">
<div id="<?php echo esc_attr($tid);?>-hide" style="cursor:pointer" onclick="document.getElementById('<?php echo esc_attr($tid);?>-hide').style.display='none';document.getElementById('<?php echo esc_attr($tid);?>-show').style.display='block'">
<div style="background:<?php echo esc_html($gc);?>;color:#fff;padding:10px 20px;border-radius:<?php echo esc_html($r);?>px;font-weight:700;font-size:14px;display:inline-block">🎁 إظهار الكوبون</div></div>
<div id="<?php echo esc_attr($tid);?>-show" style="display:none">
<div style="background:#f0f9ff;border:2px dashed <?php echo esc_html($pc);?>;border-radius:<?php echo esc_html($r);?>px;padding:12px;cursor:pointer" onclick="navigator.clipboard.writeText('<?php echo esc_html($of->coupon_code);?>');this.querySelector('small').textContent='✅ تم نسخ الكود!'">
<code style="font-size:20px;font-weight:900;letter-spacing:3px;color:<?php echo esc_html($pc);?>"><?php echo esc_html($of->coupon_code);?></code>
<br><small style="font-size:11px;color:#64748b">انقر للنسخ</small></div></div>
</div>
<?php endif;?>
<?php if($of->ends_at):?><div style="font-size:11px;color:#ef4444;font-weight:600">⏰ ينتهي: <?php echo esc_html(date('Y/m/d',strtotime($of->ends_at)));?></div><?php endif;?>
<?php if($of->min_amount>0):?><div style="font-size:11px;color:#94a3b8">الحد الأدنى: <?php echo number_format($of->min_amount,0);?> <?php echo esc_html($currency);?></div><?php endif;?>
</div>
<?php endforeach;?>
</div></div>
<?php return ob_get_clean();
    }

    private function build_form(int $pid, bool $show_img): string {
        $product=wc_get_product($pid); if(!$product)return '';
        $price=(float)$product->get_price(); $reg=(float)$product->get_regular_price(); $sale=$product->is_on_sale();
        $qty_json=get_post_meta($pid,'_dzqcod_qty_pricing',true)?:'';
        $tiers=$qty_json?json_decode($qty_json,true):[];
        // Dynamic country data
        $country_map=['DZ'=>['🇩🇿','+213'],'TN'=>['🇹🇳','+216'],'MA'=>['🇲🇦','+212'],'LY'=>['🇱🇾','+218'],'EG'=>['🇪🇬','+20'],'SA'=>['🇸🇦','+966'],'AE'=>['🇦🇪','+971'],'IQ'=>['🇮🇶','+964'],'JO'=>['🇯🇴','+962'],'SD'=>['🇸🇩','+249'],'MR'=>['🇲🇷','+222']];
        $cc=self::opt('country','DZ'); $cm=$country_map[$cc]??['🌍','+'];
        $phone_flag=$cm[0]; $phone_prefix=$cm[1];
        $wilayas=$this->get_wilayas();
        $wa_num=self::opt('form_whatsapp_number','');
        $prod_wa=get_post_meta($pid,'_dzqcod_whatsapp',true);
        if($prod_wa)$wa_num=$prod_wa;
        $wa_num=preg_replace('/[^0-9]/','',$wa_num);
        $wa_msg=str_replace(['{product}','{price}'],[$product->get_name(),number_format($price,0)],self::opt('form_whatsapp_message','مرحباً أريد طلب: {product} - {price} دج'));
        $trust=self::opt('form_trust_text','✅ الدفع عند الاستلام • 🚚 توصيل لكل الولايات • 🔄 إرجاع مجاني');
        $r=intval(self::opt('form_border_radius','12'));
        // Enhanced product data
        $colors=array_filter(array_map('trim',explode(',',get_post_meta($pid,'_dzqcod_colors',true)?:'')));
        $sizes=array_filter(array_map('trim',explode(',',get_post_meta($pid,'_dzqcod_sizes',true)?:'')));
        $badge=get_post_meta($pid,'_dzqcod_badge',true)?:'';
        $countdown=get_post_meta($pid,'_dzqcod_countdown',true)?:'';
        $is_digital=get_post_meta($pid,'_dzqcod_digital',true)==='yes';
        $custom_fields=json_decode(get_post_meta($pid,'_dzqcod_custom_fields',true)?:'',true)?:[];
        $min_qty=max(1,(int)get_post_meta($pid,'_dzqcod_min_per_order',true));
        $max_qty=min(99,max(1,(int)(get_post_meta($pid,'_dzqcod_max_per_order',true)?:99)));
        $chargily_on=self::opt('chargily_enabled','no')==='yes'&&self::opt('chargily_secret','');
        // Field ordering
        $default_order='product_header,tiers,name,phone,phone2,colors,sizes,custom_builder,delivery_type,wilaya,commune,address,quantity,custom_fields,notes,breakdown,payment,submit,whatsapp,trust';
        $field_order=array_map('trim',explode(',',self::opt('form_field_order',$default_order)));
        $fi=0;$ord=[];foreach($field_order as $f)$ord[$f]=++$fi;
        // Custom Product config
        $cpc = class_exists('\\DZQCOD\\CustomProducts') ? \DZQCOD\CustomProducts::get_config($pid) : null;

        ob_start(); ?>
<div class="dzqcod-quick-order" id="dzqcod-form" data-pid="<?php echo esc_html($pid);?>" data-price="<?php echo esc_html($price);?>" data-qty-pricing='<?php echo esc_attr($qty_json);?>' dir="rtl">

<?php if($badge): ?><div class="dzqcod-badge"><?php echo esc_html($badge); ?></div><?php endif; ?>

<form class="dzqcod-form" novalidate style="display:flex;flex-direction:column">
<input type="hidden" name="action" value="dzqcod_submit_order">
<input type="hidden" name="product_id" value="<?php echo esc_html($pid); ?>">
<?php wp_nonce_field('dzqcod_order','_n'); ?>

<?php if(self::opt('show_price','yes')==='yes'): ?>
<div class="dzqcod-form-section" style="order:<?php echo esc_html($ord['product_header']??1); ?>">
<div class="dzqcod-price-block">
<?php if($show_img && self::opt('show_product_image','yes')==='yes' && $product->get_image_id()): echo wp_get_attachment_image($product->get_image_id(),'medium',false,['class'=>'dzqcod-img']); endif; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
<?php if($is_digital): ?><span class="dzqcod-digital-tag">💾 منتج رقمي</span><?php endif; ?>
<div class="dzqcod-pname"><?php echo esc_html($product->get_name()); ?></div>
<?php if($product->get_short_description()): ?><div class="dzqcod-pdesc"><?php echo wp_kses_post(wp_trim_words($product->get_short_description(),20)); ?></div><?php endif; ?>
<div class="dzqcod-price-row"><?php if($sale): ?><del class="dzqcod-old"><?php echo number_format($reg,0); ?> دج</del> <span class="dzqcod-discount">-<?php echo esc_html(round((1-$price/$reg)*100)); ?>%</span><?php endif; ?>
<span class="dzqcod-cprice"><?php echo number_format($price,0); ?> دج</span></div>
<?php if($countdown && strtotime($countdown)>time()): ?>
<div class="dzqcod-countdown" data-end="<?php echo esc_attr($countdown); ?>"><span class="cd-label">⏰ ينتهي العرض خلال</span><span class="cd-timer"></span></div>
<?php endif; ?>
<?php if($product->managing_stock()): ?><div class="dzqcod-stock"><?php $stk=$product->get_stock_quantity(); if($stk>0&&$stk<=10): ?>🔥 بقي <?php echo esc_html($stk); ?> قطعة فقط!<?php elseif($stk>10): ?>✅ متوفر<?php endif; ?></div><?php endif; ?>
</div>
</div>
<?php endif; ?>

<?php if(!empty($tiers) && self::opt('show_quantity','yes')==='yes'): ?>
<div class="dzqcod-form-section" style="order:<?php echo esc_html($ord['tiers']??2); ?>">
<div class="dzqcod-tiers"><div class="dzqcod-tiers-hd">🏷️ اشترِ أكثر وفّر أكثر!</div><div class="dzqcod-tiers-row">
<?php foreach($tiers as $i=>$t): $d=$price>0?round((1-$t['price']/$price)*100):0; ?>
<button type="button" class="dzqcod-tier<?php echo esc_html($i===0?' active':''); ?>" data-qty="<?php echo (int)$t['min_qty']; ?>" data-price="<?php echo esc_html((float)$t['price']); ?>">
<strong><?php echo (int)$t['min_qty']; ?>+ قطعة</strong><span><?php echo number_format((float)$t['price'],0); ?> دج</span>
<?php if($d>0): ?><small>وفّر <?php echo esc_html($d); ?>%</small><?php endif; ?>
<?php if(!empty($t['label'])): ?><em>⭐ <?php echo esc_html($t['label']); ?></em><?php endif; ?>
</button>
<?php endforeach; ?></div></div>
</div>
<?php endif; ?>

<?php $inline = self::opt('form_layout','stacked')==='inline'; ?>
<?php if(self::opt('show_name','yes')==='yes' || self::opt('show_phone','yes')==='yes'): ?>
<?php if($inline): ?><div class="dzqcod-form-section dzqcod-inline-group" style="order:<?php echo esc_html(min($ord['name']??3,$ord['phone']??4)); ?>"><?php endif; ?>
<?php if(self::opt('show_name','yes')==='yes'): ?>
<div class="<?php echo esc_html($inline?'dzqcod-field-inline':'dzqcod-form-section'); ?>" <?php if(!$inline): ?>style="order:<?php echo esc_html($ord['name']??3); ?>"<?php endif; ?>>
<div class="dzqcod-field"><label>الاسم الكامل *</label><input type="text" name="full_name" required placeholder="أدخل اسمك الكامل" autocomplete="name"></div>
</div>
<?php endif; ?>

<?php if(self::opt('show_phone','yes')==='yes'): ?>
<div class="<?php echo esc_html($inline?'dzqcod-field-inline':'dzqcod-form-section'); ?>" <?php if(!$inline): ?>style="order:<?php echo esc_html($ord['phone']??4); ?>"<?php endif; ?>>
<div class="dzqcod-field"><label>رقم الهاتف 1 *</label><div class="dzqcod-phone-wrap"><span class="dzqcod-pfix"><?php echo esc_html($phone_flag." ".$phone_prefix); ?></span><input type="tel" name="phone" required placeholder="0555 12 34 56" maxlength="10" autocomplete="tel"></div></div>
</div>
<?php endif; ?>
<?php if($inline): ?></div><?php endif; ?>
<?php endif; ?>

<?php if(self::opt('show_phone2','yes')==='yes'): ?>
<div class="dzqcod-form-section" style="order:<?php echo esc_html($ord['phone2']??5); ?>">
<div class="dzqcod-field"><label>رقم الهاتف 2 (اختياري)</label><div class="dzqcod-phone-wrap"><span class="dzqcod-pfix"><?php echo esc_html($phone_flag." ".$phone_prefix); ?></span><input type="tel" name="phone2" placeholder="رقم إضافي للتأكيد" maxlength="10"></div></div>
</div>
<?php endif; ?>

<?php if(!empty($colors)): ?>
<div class="dzqcod-form-section" style="order:<?php echo esc_html($ord['colors']??6); ?>">
<div class="dzqcod-field"><label>🎨 اللون *</label><div class="dzqcod-variants">
<?php foreach($colors as $c): ?><button type="button" class="dzqcod-vbtn color-btn" data-value="<?php echo esc_attr($c); ?>"><?php echo esc_html($c); ?></button><?php endforeach; ?>
<input type="hidden" name="color" required></div></div>
</div>
<?php endif; ?>

<?php if(!empty($sizes)): ?>
<div class="dzqcod-form-section" style="order:<?php echo esc_html($ord['sizes']??7); ?>">
<div class="dzqcod-field"><label>📐 المقاس *</label><div class="dzqcod-variants">
<?php foreach($sizes as $s): ?><button type="button" class="dzqcod-vbtn size-btn" data-value="<?php echo esc_attr($s); ?>"><?php echo esc_html($s); ?></button><?php endforeach; ?>
<input type="hidden" name="size" required></div></div>
</div>
<?php endif; ?>

<?php if ($cpc): ?>
<div class="dzqcod-form-section" style="order:<?php echo esc_html($ord['custom_builder']??8); ?>">
<div class="dzqcod-custom-builder" data-mode="<?php echo esc_attr($cpc['mode']); ?>" data-ppu="<?php echo esc_html($cpc['ppu']); ?>" data-base="<?php echo esc_html($cpc['base']); ?>" data-unit="<?php echo esc_attr($cpc['unit']); ?>">
<?php if (!empty($cpc['dimensions'])): ?>
<div class="dzqcod-section-title">📐 الأبعاد</div>
<?php foreach ($cpc['dimensions'] as $di => $dim): ?>
<div class="dzqcod-field"><label><?php echo esc_html($dim['name']); ?> (<?php echo esc_html($dim['unit']); ?>)</label>
<input type="number" name="dim_<?php echo esc_html($di); ?>" class="dzqcod-dim" data-index="<?php echo esc_html($di); ?>"
    min="<?php echo esc_html($dim['min']); ?>" max="<?php echo esc_html($dim['max']); ?>" step="<?php echo esc_html($dim['step']); ?>"
    placeholder="<?php echo esc_html($dim['min'] ? $dim['min'] . ' - ' . $dim['max'] : ''); ?>" required></div>
<?php endforeach; endif; ?>
<?php if (!empty($cpc['options'])): ?>
<div class="dzqcod-section-title">✨ الخيارات والميزات</div>
<?php foreach ($cpc['options'] as $oi => $opt):
    $okey = 'opt_' . $oi;
    if ($opt['type'] === 'checkbox'): ?>
<div class="dzqcod-field"><label class="dzqcod-opt-check"><input type="checkbox" name="<?php echo esc_html($okey); ?>" value="yes" class="dzqcod-opt" data-price="<?php echo esc_html((float)$opt['price']); ?>">
<span><?php echo esc_html($opt['name']); ?></span><?php if ($opt['price']): ?><strong class="dzqcod-opt-price">+<?php echo number_format((float)$opt['price'], 0); ?> دج</strong><?php endif; ?></label></div>
<?php elseif ($opt['type'] === 'select' && !empty($opt['values'])): $pairs = array_map('trim', explode(',', $opt['values'])); ?>
<div class="dzqcod-field"><label><?php echo esc_html($opt['name']); ?></label>
<select name="<?php echo esc_html($okey); ?>" class="dzqcod-opt-select">
<option value="">اختر...</option>
<?php foreach ($pairs as $pair): $parts = explode(':', $pair); if (count($parts) === 2): ?>
<option value="<?php echo esc_attr(trim($parts[0])); ?>" data-price="<?php echo esc_html((float)$parts[1]); ?>"><?php echo esc_html(trim($parts[0])); ?><?php if ((float)$parts[1] > 0): ?> (+<?php echo number_format((float)$parts[1], 0); ?> دج)<?php endif; ?></option>
<?php endif; endforeach; ?></select></div>
<?php elseif ($opt['type'] === 'number'): ?>
<div class="dzqcod-field"><label><?php echo esc_html($opt['name']); ?> <?php if ($opt['price']): ?><small>(<?php echo number_format((float)$opt['price'], 0); ?> دج/وحدة)</small><?php endif; ?></label>
<input type="number" name="<?php echo esc_html($okey); ?>" class="dzqcod-opt-num" data-price="<?php echo esc_html((float)$opt['price']); ?>" value="0" min="0"></div>
<?php endif; endforeach; endif; ?>
<?php if ($cpc['upload']): ?>
<div class="dzqcod-section-title">📁 رفع ملفات</div>
<div class="dzqcod-field"><label>ارفع تصميمك/صورتك (<?php echo esc_html($cpc['upload_types']); ?> — حتى <?php echo esc_html($cpc['upload_max_mb']); ?> MB)</label>
<input type="file" id="dzqcod-file-input" accept=".<?php echo esc_attr(str_replace(',', ',.', $cpc['upload_types'])); ?>" multiple>
<div id="dzqcod-files-list" style="margin-top:6px"></div>
<input type="hidden" name="uploaded_files" id="dzqcod-uploaded-files" value=""></div>
<?php endif; ?>
<?php if ($cpc['custom_note']): ?>
<div class="dzqcod-field"><label>📝 <?php echo esc_html($cpc['note_label']); ?></label>
<textarea name="custom_order_note" rows="3" placeholder="اشرح طلبك بالتفصيل..."></textarea></div>
<?php endif; ?>
<div class="dzqcod-calc-box">
<div class="dzqcod-calc-title">💰 حاسبة السعر</div>
<div class="dzqcod-calc-row" id="cc-base" style="display:none"><span>السعر الأساسي</span><span id="cc-base-v">-</span></div>
<div class="dzqcod-calc-row" id="cc-dims" style="display:none"><span>الأبعاد</span><span id="cc-dims-v">-</span></div>
<div class="dzqcod-calc-row" id="cc-opts" style="display:none"><span>الخيارات</span><span id="cc-opts-v">-</span></div>
<div id="cc-opts-detail" style="font-size:11px;color:#888;padding:0 10px"></div>
<div class="dzqcod-calc-row dzqcod-calc-total"><strong>💰 المجموع</strong><strong id="cc-total">-</strong></div>
</div>
</div>
</div>
<?php endif; ?>

<?php if(self::opt('show_wilaya','yes')==='yes' && !$is_digital): ?>
<!-- Delivery Type Toggle -->
<?php if(self::opt('show_delivery_type','yes')==='yes'):
    $del_label = self::opt('delivery_label','📦 نوع التوصيل *');
    $del_home_label = self::opt('delivery_home_label','توصيل للمنزل');
    $del_home_desc = self::opt('delivery_home_desc','حتى باب منزلك');
    $del_desk_label = self::opt('delivery_desk_label','مكتب الاستلام');
    $del_desk_desc = self::opt('delivery_desk_desc','Stop Desk');
    $del_default = self::opt('delivery_default','home');
?>
<div class="dzqcod-form-section" style="order:<?php echo esc_html($ord['delivery_type']??8); ?>">
<div class="dzqcod-field"><label><?php echo esc_html($del_label); ?></label>
<div class="dzqcod-del-toggle" style="display:flex;gap:8px">
<button type="button" class="dzqcod-del-btn <?php echo $del_default==='home'?'active':''; ?>" data-del="home" onclick="dzqcodSetDel(this)">
<span style="font-size:18px">🏠</span><strong><?php echo esc_html($del_home_label); ?></strong><small><?php echo esc_html($del_home_desc); ?></small>
</button>
<button type="button" class="dzqcod-del-btn <?php echo $del_default==='desk'?'active':''; ?>" data-del="desk" onclick="dzqcodSetDel(this)">
<span style="font-size:18px">🏪</span><strong><?php echo esc_html($del_desk_label); ?></strong><small><?php echo esc_html($del_desk_desc); ?></small>
</button>
</div>
<input type="hidden" name="delivery_mode" value="<?php echo esc_attr($del_default); ?>">
</div>
</div>
<?php else: ?>
<input type="hidden" name="delivery_mode" value="home">
<?php endif; ?>

<?php if($inline): ?><div class="dzqcod-form-section dzqcod-inline-group" style="order:<?php echo esc_html($ord['wilaya']??9); ?>"><?php endif; ?>
<div class="<?php echo esc_html($inline?'dzqcod-field-inline':'dzqcod-form-section'); ?>" <?php if(!$inline): ?>style="order:<?php echo esc_html($ord['wilaya']??9); ?>"<?php endif; ?>>
<div class="dzqcod-field"><label><?php echo esc_html(self::state_label()); ?> *</label><select name="wilaya" required>
<option value=""><?php echo esc_html('اختر '.self::state_label()); ?></option>
<?php foreach($wilayas as $w): ?><option value="<?php echo esc_attr($w->code); ?>" data-desk="<?php echo esc_html($w->shipping_desk); ?>" data-home="<?php echo esc_html($w->shipping_home); ?>"><?php echo esc_html($w->code.' - '.$w->name_ar); ?></option><?php endforeach; ?>
</select></div>
</div>

<?php if(self::opt('show_commune','yes')==='yes'): ?>
<div class="<?php echo esc_html($inline?'dzqcod-field-inline':'dzqcod-form-section'); ?>" <?php if(!$inline): ?>style="order:<?php echo esc_html($ord['commune']??10); ?>"<?php endif; ?>>
<div class="dzqcod-field"><label><?php echo esc_html(self::commune_label()); ?> *</label><select name="commune" required disabled><option value=""><?php echo esc_html('اختر '.self::state_label().' أولاً'); ?></option></select></div>
</div>
<?php endif; ?>
<?php if($inline): ?></div><?php endif; ?>
<?php endif; ?>

<?php if(!$is_digital): ?>
<div class="dzqcod-form-section" style="order:<?php echo esc_html($ord['address']??11); ?>">
<div class="dzqcod-field"><label>العنوان التفصيلي</label><input type="text" name="address" placeholder="الحي، الشارع، رقم المنزل..."></div>
</div>
<?php endif; ?>

<?php if(self::opt('show_quantity','yes')==='yes'): ?>
<div class="dzqcod-form-section" style="order:<?php echo esc_html($ord['quantity']??12); ?>">
<div class="dzqcod-field"><label>الكمية</label><div class="dzqcod-qty-wrap"><button type="button" class="dzqcod-qb minus">−</button><input type="number" name="quantity" value="<?php echo esc_html($min_qty); ?>" min="<?php echo esc_html($min_qty); ?>" max="<?php echo esc_html($max_qty); ?>"><button type="button" class="dzqcod-qb plus">+</button></div><div class="dzqcod-qty-hint"></div></div>
</div>
<?php endif; ?>

<?php foreach($custom_fields as $cf): $fname='custom_'.sanitize_title($cf['name']); ?>
<div class="dzqcod-form-section" style="order:<?php echo esc_html($ord['custom_fields']??13); ?>">
<div class="dzqcod-field"><label><?php echo esc_html($cf['name']); ?><?php echo esc_html(!empty($cf['required'])?' *':''); ?></label>
<?php if(($cf['type']??'text')==='textarea'): ?><textarea name="<?php echo esc_html($fname); ?>" rows="2" <?php echo esc_html(!empty($cf['required'])?'required':''); ?>></textarea>
<?php else: ?><input type="text" name="<?php echo esc_html($fname); ?>" <?php echo esc_html(!empty($cf['required'])?'required':''); ?>>
<?php endif; ?></div>
</div>
<?php endforeach; ?>

<?php if(self::opt('show_notes','yes')==='yes'): ?>
<div class="dzqcod-form-section" style="order:<?php echo esc_html($ord['notes']??14); ?>">
<div class="dzqcod-field"><label>ملاحظات</label><textarea name="notes" rows="2" placeholder="أي تفاصيل إضافية"></textarea></div>
</div>
<?php endif; ?>

<?php if(self::opt('show_breakdown','yes')==='yes'): ?>
<div class="dzqcod-form-section" style="order:<?php echo esc_html($ord['breakdown']??15); ?>">
<div class="dzqcod-breakdown" style="display:none">
<div class="bk-r"><span>المنتج (<span class="bk-qty">1</span>×)</span><span class="bk-sub">-</span></div>
<?php if(!$is_digital): ?><div class="bk-r"><span>🚚 الشحن</span><span class="bk-ship">-</span></div><?php endif; ?>
<div class="bk-r bk-total"><strong>💰 المجموع</strong><strong class="bk-tot">-</strong></div>
</div>
</div>
<?php endif; ?>

<?php if($chargily_on && !$is_digital): ?>
<div class="dzqcod-form-section" style="order:<?php echo esc_html($ord['payment']??16); ?>">
<div class="dzqcod-pay-choice">
<label class="dzqcod-pay-opt active"><input type="radio" name="payment_method" value="cod" checked><span>💰 الدفع عند الاستلام</span></label>
<label class="dzqcod-pay-opt"><input type="radio" name="payment_method" value="chargily"><span>💳 الدفع الإلكتروني (CIB/EDAHABIA)</span></label>
</div>
</div>
<?php elseif($is_digital && $chargily_on): ?>
<div class="dzqcod-form-section" style="order:<?php echo esc_html($ord['payment']??16); ?>">
<input type="hidden" name="payment_method" value="chargily">
<div class="dzqcod-digital-notice">💳 الدفع الإلكتروني — تحصل على رابط التحميل فوراً</div>
</div>
<?php endif; ?>

<div class="dzqcod-form-section" style="order:<?php echo esc_html($ord['submit']??17); ?>">
<button type="submit" class="dzqcod-submit"><span class="txt"><?php echo esc_html(self::opt('form_submit_text','🛒 اطلب الآن — الدفع عند الاستلام')); ?></span><span class="ld" style="display:none">⏳ جاري الإرسال...</span></button>
</div>

<?php if(self::opt('show_whatsapp_btn','yes')==='yes' && $wa_num): ?>
<div class="dzqcod-form-section" style="order:<?php echo esc_html($ord['whatsapp']??18); ?>">
<a href="https://wa.me/<?php echo esc_html($wa_num); ?>?text=<?php echo esc_html(rawurlencode($wa_msg)); ?>" class="dzqcod-wa" target="_blank" rel="noopener"><?php echo esc_html(self::opt('form_whatsapp_text','💬 اطلب عبر واتساب')); ?></a>
</div>
<?php endif; ?>

<?php if(self::opt('show_trust_badges','yes')==='yes'): ?>
<div class="dzqcod-form-section" style="order:<?php echo esc_html($ord['trust']??19); ?>">
<div class="dzqcod-trust"><?php foreach(array_filter(array_map('trim',explode('•',$trust))) as $b): ?><span><?php echo esc_html($b); ?></span><?php endforeach; ?></div>
</div>
<?php endif; ?>

<div class="dzqcod-msg" style="display:none;order:99"></div>
</form>
</div>
<?php if(self::opt('sticky_order_bar','no')==='yes'): ?>
<div class="dzqcod-sticky-bar" id="dzqcod-sticky">
<div><div style="font-size:10px;opacity:.7">المجموع</div><div class="dzqcod-sticky-total bk-tot-sticky"><?php echo number_format($price,0); ?> دج</div></div>
<button type="button" class="dzqcod-sticky-btn" onclick="document.querySelector('.dzqcod-submit').click()">🛒 <?php echo esc_html(self::opt('form_submit_text','اطلب الآن')); ?></button>
</div>
<?php endif; ?>
<?php return ob_get_clean();
    }

    // ════════════════════════════════════════════════════════════════
    //  AJAX: Submit Order
    // ════════════════════════════════════════════════════════════════
    public function dzqcod_submit_order(): void {
        check_ajax_referer('dzqcod_order','_n');
        $ip_k='dzqcod_rl_'.md5($_SERVER['REMOTE_ADDR']??'');
        if((int)get_transient($ip_k)>=5) wp_send_json_error(['message'=>'الرجاء الانتظار']);
        set_transient($ip_k,((int)get_transient($ip_k))+1,300);

        $pid=absint($_POST['product_id']??0);$name=sanitize_text_field($_POST['full_name']??'');
        $phone=sanitize_text_field($_POST['phone']??'');$phone2=sanitize_text_field($_POST['phone2']??'');
        $wil=sanitize_text_field($_POST['wilaya']??'');$com=sanitize_text_field($_POST['commune']??'');
        $addr=sanitize_text_field($_POST['address']??'');$qty=max(1,min(99,absint($_POST['quantity']??1)));
        $notes=sanitize_textarea_field($_POST['notes']??'');
        $color=sanitize_text_field($_POST['color']??'');$size=sanitize_text_field($_POST['size']??'');
        $pay_method=sanitize_text_field($_POST['payment_method']??'cod');

        $e=[];
        if(mb_strlen($name)<3)$e[]='الاسم مطلوب (3 أحرف)';
        if(!preg_match('/^0[567]\d{8}$/',$phone))$e[]='رقم هاتف جزائري صالح مطلوب';
        if($phone2 && !preg_match('/^0[567]\d{8}$/',$phone2))$e[]='رقم الهاتف 2 غير صالح';
        $is_digital=get_post_meta($pid,'_dzqcod_digital',true)==='yes';
        if(empty($wil)&&!$is_digital)$e[]='الولاية مطلوبة';
        if(!$pid||!wc_get_product($pid))$e[]='المنتج غير صالح';
        if($e)wp_send_json_error(['message'=>implode(', ',$e)]);

        // Fraud check
        $fraud=$this->fraud_check($phone,$_SERVER['REMOTE_ADDR']??'');
        if($fraud['blocked']) wp_send_json_error(['message'=>'لا يمكن معالجة هذا الطلب']);

        $product=wc_get_product($pid); $base=(float)$product->get_price();
        // Qty pricing (normal products)
        $unit=$base; $tiers=json_decode(get_post_meta($pid,'_dzqcod_qty_pricing',true)?:'',true);
        if(is_array($tiers)&&!empty($tiers)){usort($tiers,fn($a,$b)=>$b['min_qty']-$a['min_qty']);foreach($tiers as $t){if($qty>=$t['min_qty']){$unit=(float)$t['price'];break;}}}

        // ═══ CUSTOM PRODUCT PRICING (dimensions + options) ═══
        $cpc = class_exists('\DZQCOD\CustomProducts') ? \DZQCOD\CustomProducts::get_config($pid) : null;
        if ($cpc) {
            $cp_base = $cpc['base'];
            $cp_ppu  = $cpc['ppu'];
            $cp_mode = $cpc['mode'];
            $cp_unit = $cpc['unit'];
            $is_cm   = (stripos($cp_unit,'سم')!==false || stripos($cp_unit,'cm')!==false);

            // Dimensions
            $dim_vals = [];
            foreach ($_POST as $dk => $dv) { if (strpos($dk,'dim_')===0) $dim_vals[] = max(0,floatval($dv)); }

            $dim_price = 0;
            switch ($cp_mode) {
                case 'area':
                    $area = ($dim_vals[0]??0) * ($dim_vals[1]??0);
                    if ($is_cm) $area /= 10000;
                    $dim_price = $area * $cp_ppu;
                    break;
                case 'linear':
                    $len = $dim_vals[0]??0;
                    if ($is_cm) $len /= 100;
                    $dim_price = $len * $cp_ppu;
                    break;
                case 'volume':
                    $vol = ($dim_vals[0]??0) * ($dim_vals[1]??0) * ($dim_vals[2]??0);
                    if ($is_cm) $vol /= 1000000;
                    $dim_price = $vol * $cp_ppu;
                    break;
                case 'weight':
                    $dim_price = ($dim_vals[0]??0) * $cp_ppu;
                    break;
            }

            // Paid options
            $opts_total = 0;
            if (!empty($cpc['options'])) {
                foreach ($cpc['options'] as $oi => $opt) {
                    $okey = 'opt_'.$oi;
                    $oval = sanitize_text_field(wp_unslash($_POST[$okey] ?? ''));
                    if (!$oval || $oval==='0') continue;
                    if ($opt['type']==='checkbox' && $oval==='yes') {
                        $opts_total += (float)$opt['price'];
                    } elseif ($opt['type']==='select' && !empty($opt['values'])) {
                        foreach (array_map('trim',explode(',',$opt['values'])) as $pair) {
                            $parts = explode(':',$pair);
                            if (count($parts)===2 && trim($parts[0])===$oval) $opts_total += (float)$parts[1];
                        }
                    } elseif ($opt['type']==='number') {
                        $opts_total += max(0,(int)$oval) * (float)$opt['price'];
                    }
                }
            }

            $unit = $cp_base + $dim_price + $opts_total;
        }

        $order=wc_create_order(['status'=>'wc-pending-call']);
        if(is_wp_error($order))wp_send_json_error(['message'=>'خطأ في إنشاء الطلب']);

        $item_id=$order->add_product($product,$qty);
        if(abs($unit-$base)>0.01){$item=$order->get_item($item_id);$item->set_subtotal($unit*$qty);$item->set_total($unit*$qty);$item->save();}

        // Shipping
        global $wpdb;
        $wrow=$wpdb->get_row($wpdb->prepare("SELECT * FROM ".self::db()."wilayas WHERE code=%s",$wil));
        $del_mode = sanitize_text_field($_POST['delivery_mode']??'home');
        $ship_cost=$wrow ? (float)($del_mode==='desk' ? $wrow->shipping_desk : $wrow->shipping_home) : 0;
        $ship_label = $del_mode==='desk' ? 'استلام من المكتب (Stop Desk)' : 'توصيل للمنزل';
        if($ship_cost>0){$si=new \WC_Order_Item_Shipping();$si->set_method_title($ship_label);$si->set_total($ship_cost);$order->add_item($si);}

        $adr=['first_name'=>$name,'last_name'=>'','phone'=>$phone,'address_1'=>$addr,'state'=>$wil,'city'=>$com,'country'=>'DZ'];
        $order->set_address($adr,'billing');$order->set_address($adr,'shipping');
        $order->set_payment_method('cod');$order->set_payment_method_title('الدفع عند الاستلام');
        if($notes)$order->set_customer_note($notes);
        $order->calculate_totals();

        $order->update_meta_data('_dzqcod_source','quick_order');
        $order->update_meta_data('_dzqcod_delivery_mode',$del_mode);
        $order->update_meta_data('_dzqcod_wilaya_code',$wil);
        $order->update_meta_data('_dzqcod_commune',$com);
        if($phone2)$order->update_meta_data('_dzqcod_phone2',$phone2);
        if($color)$order->update_meta_data('_dzqcod_color',$color);
        if($size)$order->update_meta_data('_dzqcod_size',$size);
        if($is_digital)$order->update_meta_data('_dzqcod_digital','yes');
        // Save custom fields
        foreach($_POST as $pk=>$pv){if(strpos($pk,'custom_')===0)$order->update_meta_data('_dzqcod_'.$pk,sanitize_text_field($pv));}
        // Custom product: dimensions + paid options + files + note
        $dim_data=[];foreach($_POST as $dk=>$dv){if(strpos($dk,'dim_')===0)$dim_data[$dk]=sanitize_text_field($dv);}
        if(!empty($dim_data))$order->update_meta_data('_dzqcod_custom_dimensions',wp_json_encode($dim_data));
        $opt_data=[];foreach($_POST as $ok=>$ov){if(strpos($ok,'opt_')===0)$opt_data[$ok]=sanitize_text_field($ov);}
        if(!empty($opt_data))$order->update_meta_data('_dzqcod_custom_options',wp_json_encode($opt_data));
        $uploaded=sanitize_text_field($_POST['uploaded_files']??'');if($uploaded)$order->update_meta_data('_dzqcod_uploaded_files',$uploaded);
        $cnote=sanitize_textarea_field($_POST['custom_order_note']??'');if($cnote){$order->update_meta_data('_dzqcod_custom_order_note',$cnote);$order->set_customer_note($cnote);}
        if($fraud['score']>0){$order->update_meta_data('_dzqcod_fraud_score',$fraud['score']);$order->update_meta_data('_dzqcod_fraud_signals',wp_json_encode($fraud['signals']));}
        // Add color/size to item meta for display
        if($color||$size){$item=$order->get_item($item_id);if($color)wc_add_order_item_meta($item_id,'اللون',$color);if($size)wc_add_order_item_meta($item_id,'المقاس',$size);}

        // UTM touchpoint
        $this->save_touchpoint($order->get_id());
        if($pay_method==='chargily'){$order->set_payment_method('chargily');$order->set_payment_method_title('الدفع الإلكتروني');}
        $order->save();
        do_action('dzqcod_order_created',$order->get_id(),$order);

        // Chargily payment redirect
        if($pay_method==='chargily'){
            $url=\DZQCOD\Modules::chargily_create($order->get_id());
            if($url)wp_send_json_success(['message'=>'جاري التحويل للدفع...','redirect'=>$url,'order_id'=>$order->get_id()]);
            else wp_send_json_error(['message'=>'خطأ في بوابة الدفع، حاول لاحقاً']);
        }

        // Log fraud score
        if($fraud['score']>0){$wpdb->insert(self::db().'fraud_scores',['order_id'=>$order->get_id(),'score'=>$fraud['score'],'signals_json'=>wp_json_encode($fraud['signals']),'action_taken'=>$fraud['blocked']?'blocked':'passed']);}

        // ═══ POST-ORDER FLOW ═══
        $oid = $order->get_id();
        $otp_on = self::opt('otp_enabled','') === 'yes';
        $post_order_page = self::opt('post_order_page', 'builtin'); // builtin or wp_page_id

        // Generate OTP if enabled
        if ($otp_on) {
            $code = str_pad(random_int(1000, 9999), 4, '0', STR_PAD_LEFT);
            set_transient('dzqcod_order_otp_' . $oid, $code, 600); // 10 min
            // Send OTP via SMS/WhatsApp
            $phone_intl = '213' . substr($phone, 1);
            $msg = str_replace('{code}', $code, self::opt('otp_message', 'رمز تأكيد طلبك #{order}: {code} — DZQCOD'));
            $msg = str_replace('{order}', $oid, $msg);
            $wa_api = self::opt('wa_api_url',''); $wa_token = self::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' => $phone_intl, 'message' => $msg]), 'timeout' => 10, 'blocking' => false]);
            }
            $sms_provider = self::opt('sms_provider',''); $sms_key = self::opt('sms_api_key','');
            if ($sms_provider && $sms_key) {
                wp_remote_post(self::opt('sms_api_url',''), ['body' => ['to' => $phone_intl, 'message' => $msg, 'api_key' => $sms_key], 'timeout' => 10, 'blocking' => false]);
            }
        }

        wp_send_json_success([
            'message' => self::opt('form_success_text','✅ تم إرسال طلبك بنجاح!'),
            'order_id' => $oid,
            'phone' => $phone,
            'phone_masked' => substr($phone, 0, 4) . '****' . substr($phone, -2),
            'total' => number_format((float)$order->get_total(), 0),
            'name' => $name,
            'otp_enabled' => $otp_on,
            'post_flow' => $otp_on ? 'otp' : 'thankyou',
        ]);
    }

    // ════════════════════════════════════════════════════════════════
    //  AJAX: Verify Order OTP — confirms order if code matches
    // ════════════════════════════════════════════════════════════════
    public function dzqcod_verify_order_otp(): void {
        if(!check_ajax_referer('dzqcod_order','_n',false))wp_send_json_error(['message'=>'nonce']);
        $oid = absint($_POST['order_id'] ?? 0);
        $code = sanitize_text_field($_POST['otp_code'] ?? '');
        if (!$oid || !$code) wp_send_json_error(['message' => 'بيانات ناقصة']);

        $stored = get_transient('dzqcod_order_otp_' . $oid);
        if (!$stored) wp_send_json_error(['message' => 'انتهت صلاحية الرمز. سيتم الاتصال بك لتأكيد الطلب.', 'expired' => true]);
        if ($stored !== $code) wp_send_json_error(['message' => 'رمز خاطئ. حاول مرة أخرى.']);

        // OTP correct — auto-confirm
        $order = wc_get_order($oid);
        if (!$order) wp_send_json_error(['message' => 'طلب غير موجود']);

        delete_transient('dzqcod_order_otp_' . $oid);
        $order->set_status('wc-confirmed');
        $order->add_order_note('✅ تأكيد تلقائي عبر OTP من العميل');
        $order->update_meta_data('_dzqcod_otp_confirmed', 'yes');
        $order->save();

        do_action('dzqcod_order_otp_confirmed', $oid, $order);

        wp_send_json_success([
            'message' => self::opt('otp_success_text', '🎉 تم تأكيد طلبك بنجاح! سيتم شحنه قريباً.'),
            'order_id' => $oid,
            'confirmed' => true,
        ]);
    }

    // ════════════════════════════════════════════════════════════════
    //  AJAX: Set Callback Preference — when OTP skipped/expired
    // ════════════════════════════════════════════════════════════════
    public function dzqcod_set_callback_pref(): void {
        if(!check_ajax_referer('dzqcod_order','_n',false))wp_send_json_error(['message'=>'nonce']);
        $oid = absint($_POST['order_id'] ?? 0);
        $slot = sanitize_text_field($_POST['time_slot'] ?? '');
        if (!$oid) wp_send_json_error(['message' => 'بيانات ناقصة']);

        $order = wc_get_order($oid);
        if (!$order) wp_send_json_error(['message' => 'طلب غير موجود']);

        $valid_slots = ['morning' => 'صباحاً (9:00-12:00)', 'afternoon' => 'ظهراً (12:00-15:00)',
            'evening' => 'مساءً (15:00-18:00)', 'night' => 'ليلاً (18:00-21:00)', 'anytime' => 'أي وقت'];
        $slot_label = $valid_slots[$slot] ?? $valid_slots['anytime'];

        $order->update_meta_data('_dzqcod_callback_slot', $slot);
        $order->update_meta_data('_dzqcod_callback_slot_label', $slot_label);
        $order->add_order_note('📞 العميل يفضل الاتصال: ' . $slot_label);
        $order->save();

        wp_send_json_success([
            'message' => '📞 شكراً! سيتم الاتصال بك ' . $slot_label . ' لتأكيد طلبك.',
            'slot' => $slot,
            'slot_label' => $slot_label,
        ]);
    }

    // ════════════════════════════════════════════════════════════════
    // ════════════════════════════════════════════════════════════════
    //  AJAX: OTP Resend
    // ════════════════════════════════════════════════════════════════
    public function dzqcod_send_otp(): void {
        $oid = absint($_POST['order_id'] ?? 0);
        $phone = sanitize_text_field($_POST['phone'] ?? '');
        if (!$oid || !$phone) wp_send_json_error(['message' => 'بيانات ناقصة']);
        $key = 'dzqcod_otp_resend_' . $oid;
        $count = (int)get_transient($key);
        if ($count >= 3) wp_send_json_error(['message' => 'الحد الأقصى لإعادة الإرسال: 3 مرات']);
        set_transient($key, $count + 1, 3600);
        $code = str_pad(random_int(1000, 9999), 4, '0', STR_PAD_LEFT);
        set_transient('dzqcod_order_otp_' . $oid, $code, 600);
        $phone_intl = '213' . substr($phone, 1);
        $msg = str_replace('{code}', $code, self::opt('otp_message', 'رمز تأكيد طلبك: {code}'));
        $wa_api = self::opt('wa_api_url', ''); $wa_token = self::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' => $phone_intl, 'message' => $msg]), 'timeout' => 10, 'blocking' => false]);
        }
        wp_send_json_success(['message' => 'تم إرسال رمز جديد', 'phone_masked' => substr($phone,0,4).'****'.substr($phone,-2)]);
    }

    //  AJAX: Get Communes
    // ════════════════════════════════════════════════════════════════
    public function dzqcod_get_communes(): void {
        if(!check_ajax_referer('dzqcod_order','_n',false))wp_send_json_error(['message'=>'nonce']);
        $wil=sanitize_text_field($_POST['wilaya']??$_GET['wilaya']??'');
        if(!$wil)wp_send_json_error();
        global $wpdb;
        $communes=$wpdb->get_results($wpdb->prepare("SELECT name_ar FROM ".self::db()."communes WHERE wilaya_code=%s AND is_active=1 ORDER BY name_ar",$wil));
        wp_send_json_success(['communes'=>array_map(fn($c)=>$c->name_ar,$communes)]);
    }

    // ════════════════════════════════════════════════════════════════
    //  FRAUD ENGINE
    // ════════════════════════════════════════════════════════════════
    private function fraud_check(string $phone, string $ip): array {
        global $wpdb; $p=self::db(); $score=0; $signals=[];
        $threshold=(int)self::opt('fraud_threshold','70');

        // Blacklist check
        $ph_hash=hash('sha256',$phone);$ip_hash=hash('sha256',$ip);
        $bl=$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$p}blacklist WHERE (hash_value=%s OR hash_value=%s) AND (expires_at IS NULL OR expires_at>NOW())",$ph_hash,$ip_hash));
        if($bl>0)return ['blocked'=>true,'score'=>100,'signals'=>['blacklisted']];

        // Duplicate phone in last 24h
        $dup=(int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->prefix}wc_orders o JOIN {$wpdb->prefix}wc_orders_meta m ON o.id=m.order_id WHERE m.meta_key='_billing_phone' AND m.meta_value=%s AND o.date_created_gmt>DATE_SUB(NOW(),INTERVAL 24 HOUR)",$phone));
        if(!$dup)$dup=(int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key='_billing_phone' AND meta_value=%s",$phone));
        if($dup>=3){$score+=30;$signals[]='duplicate_phone_24h';}
        elseif($dup>=1){$score+=10;$signals[]='repeat_phone';}

        // Same IP multiple orders
        $ip_orders=(int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$p}touchpoints WHERE SUBSTRING_INDEX(referrer,'/',3)=%s AND created_at>DATE_SUB(NOW(),INTERVAL 1 HOUR)",hash('sha256',$ip)));
        if($ip_orders>=3){$score+=20;$signals[]='ip_velocity';}

        // Phone pattern (all same digits)
        if(preg_match('/^0(\d)\1{8}$/',$phone)){$score+=40;$signals[]='suspicious_phone_pattern';}

        // Previous RTO/fake/cancelled
        $bad=0;if(class_exists('\\Automattic\\WooCommerce\\Utilities\\OrderUtil')&&\Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled()){$bad=(int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->prefix}wc_orders o JOIN {$wpdb->prefix}wc_orders_meta m ON o.id=m.order_id WHERE m.meta_key='_billing_phone' AND m.meta_value=%s AND o.status IN ('wc-rto','wc-fake','wc-cancelled')",$phone));}else{$bad=(int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->postmeta} pm JOIN {$wpdb->posts} p ON p.ID=pm.post_id WHERE pm.meta_key='_billing_phone' AND pm.meta_value=%s AND p.post_status IN ('wc-rto','wc-fake','wc-cancelled')",$phone));}
        if($bad>=2){$score+=35;$signals[]='history_rto_fake';}

        return ['blocked'=>$score>=$threshold,'score'=>min(100,$score),'signals'=>$signals];
    }

    // ════════════════════════════════════════════════════════════════
    //  UTM TOUCHPOINT
    // ════════════════════════════════════════════════════════════════
    private function save_touchpoint(int $oid): void {
        global $wpdb;
        $utm=[];foreach(['utm_source','utm_medium','utm_campaign','utm_content','utm_term'] as $k){$v=sanitize_text_field($_REQUEST[$k]??$_COOKIE["dzqcod_{$k}"]??'');if($v)$utm[$k]=$v;}
        $wpdb->insert(self::db().'touchpoints',[
            'session_id'=>sanitize_text_field($_COOKIE['dzqcod_sid']??wp_generate_uuid4()),
            'order_id'=>$oid,
            'first_utm_json'=>wp_json_encode($utm),
            'last_utm_json'=>wp_json_encode($utm),
            'fbclid'=>sanitize_text_field($_REQUEST['fbclid']??$_COOKIE['dzqcod_fbclid']??''),
            'fbp'=>sanitize_text_field($_COOKIE['_fbp']??''),
            'fbc'=>sanitize_text_field($_COOKIE['_fbc']??''),
            'ttclid'=>sanitize_text_field($_REQUEST['ttclid']??''),
            'gclid'=>sanitize_text_field($_REQUEST['gclid']??''),
            'landing_page'=>sanitize_url($_COOKIE['dzqcod_landing']??''),
            'referrer'=>sanitize_url(wp_get_referer()?:''),
            'device'=>$this->detect_device(),
            'time_on_page'=>absint($_POST['time_on_page']??0),
            'scroll_depth'=>min(100,absint($_POST['scroll_depth']??0)),
        ]);
    }
    private function detect_device():string{$ua=$_SERVER['HTTP_USER_AGENT']??'';if(preg_match('/Mobile|Android|iPhone/i',$ua))return'mobile';if(preg_match('/Tablet|iPad/i',$ua))return'tablet';return'desktop';}

    // ════════════════════════════════════════════════════════════════
    //  CALL CENTER, PRINTING, SHIPPING, STATUS, SETTINGS (AJAX)
    // ════════════════════════════════════════════════════════════════
    public function dzqcod_log_call(): void {
        check_ajax_referer('dzqcod_admin','nonce'); global $wpdb;
        if(!current_user_can('manage_woocommerce'))wp_send_json_error(['message'=>'صلاحيات غير كافية']);
        $oid=absint($_POST['order_id']??0);$outcome=sanitize_text_field($_POST['outcome']??'');
        $notes=sanitize_textarea_field($_POST['notes']??'');$next=sanitize_text_field($_POST['next_call']??'');
        if(!$oid||!$outcome)wp_send_json_error();
        $attempts=(int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM ".self::db()."call_logs WHERE order_id=%d",$oid));
        $wpdb->insert(self::db().'call_logs',['order_id'=>$oid,'agent_id'=>get_current_user_id(),'outcome'=>$outcome,'attempt_number'=>$attempts+1,'notes'=>$notes,'next_call_at'=>$next?:null]);
        $order=wc_get_order($oid);
        if($order){
            $map=['confirmed'=>'wc-confirmed','callback'=>'wc-callback','no-answer'=>'wc-no-answer','cancelled'=>'wc-cancelled','fake'=>'wc-fake','postponed'=>'wc-postponed','duplicate'=>'wc-duplicate'];
            if(isset($map[$outcome])){$order->set_status($map[$outcome]);$order->add_order_note("📞 {$outcome} — {$notes}");$order->save();}
            $order->update_meta_data('_dzqcod_call_attempts',$attempts+1);$order->save();
        }
        // Audit
        $wpdb->insert(self::db().'audit_log',['user_id'=>get_current_user_id(),'action'=>'call_logged','object_type'=>'order','object_id'=>$oid,'details_json'=>wp_json_encode(['outcome'=>$outcome]),'ip_address'=>$_SERVER['REMOTE_ADDR']??'']);
        wp_send_json_success(['message'=>'تم تسجيل الاتصال']);
    }

    public function dzqcod_print_receipt(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if(!current_user_can('manage_woocommerce'))wp_send_json_error(['message'=>'صلاحيات غير كافية']);
        $o=wc_get_order(absint($_POST['order_id']??0));
        if(!$o)wp_send_json_error(['message'=>'الطلب غير موجود']);
        $copies=(int)self::opt('print_copies','1');
        $html='';for($c=0;$c<max(1,$copies);$c++){$html.=$this->receipt_html($o);if($c<$copies-1)$html.='<div style="page-break-after:always"></div>';}
        wp_send_json_success(['html'=>$html]);
    }
    public function dzqcod_print_batch(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if(!current_user_can('manage_woocommerce'))wp_send_json_error(['message'=>'صلاحيات غير كافية']);
        $ids=array_map('absint',(array)($_POST['order_ids']??[]));
        $fmt=self::opt('print_format','a5');
        $fs=['small'=>'10px','medium'=>'12px','large'=>'14px'];
        $fsBase=$fs[self::opt('print_font_size','medium')]??'12px';
        $pgSize=['a5'=>'A5','a4'=>'A4','thermal'=>'80mm 297mm','thermal58'=>'58mm 297mm'];
        $pg=$pgSize[$fmt]??'A5';
        $copies=(int)self::opt('print_copies','1');
        $h='<!DOCTYPE html><html dir="rtl" lang="ar"><head><meta charset="UTF-8"><link href="https://fonts.googleapis.com/css2?family=Libre+Barcode+39&display=swap" rel="stylesheet"><style>@page{size:'.$pg.';margin:5mm}body{font-family:Arial,Tahoma,sans-serif;font-size:'.$fsBase.'}.r{page-break-after:always}.r:last-child{page-break-after:auto}</style></head><body>';
        foreach($ids as $id){$o=wc_get_order($id);if($o){for($c=0;$c<max(1,$copies);$c++)$h.='<div class="r">'.$this->receipt_html($o).'</div>';}}
        $h.='</body></html>';
        wp_send_json_success(['html'=>$h]);
    }
    private function receipt_html(\WC_Order $o):string{
        // ═══ Inherit ALL settings from الطباعة tab ═══
        $P=function($k,$d=''){return self::opt('print_'.$k,$d);};
        $fmt=$P('format','a5');
        $showLogo=$P('show_logo','yes')==='yes';
        $logoUrl=$P('logo_url','');
        $showStore=$P('show_store_info','yes')==='yes';
        $showPhone=$P('show_phone','yes')==='yes';
        $showEmail=$P('show_email','no')==='yes';
        $showAddr=$P('show_address','yes')==='yes';
        $showProducts=$P('show_products','yes')==='yes';
        $showTotal=$P('show_total','yes')==='yes';
        $showShipping=$P('show_shipping','yes')==='yes';
        $showBarcode=$P('show_barcode','yes')==='yes';
        $showNotes=$P('show_notes','no')==='yes';
        $footerText=$P('footer_text','شكراً لتسوقكم معنا!');
        $color=$P('primary_color','#667eea');
        $fontSize=$P('font_size','medium');
        $borderStyle=$P('border_style','dashed');
        $headerBg=$P('header_bg','#f8fafc');
        $storeName=get_bloginfo('name');
        $storeSlogan=self::opt('store_slogan','');

        // Font size mapping
        $fs=['small'=>'10px','medium'=>'12px','large'=>'14px'];
        $fsBase=$fs[$fontSize]??'12px';
        $fsTitleMap=['small'=>'13px','medium'=>'16px','large'=>'20px'];
        $fsTitle=$fsTitleMap[$fontSize]??'16px';

        // Width based on format
        $maxW=['a5'=>'148mm','a4'=>'190mm','thermal'=>'80mm','thermal58'=>'58mm'];
        $mw=$maxW[$fmt]??'80mm';

        // Border style
        $brd=$borderStyle==='none'?'none':('2px '.$borderStyle.' '.$color);

        $h='<div style="max-width:'.$mw.';margin:0 auto;font-family:Arial,Tahoma,sans-serif;font-size:'.$fsBase.';direction:rtl;color:#000">';

        // ═══ HEADER: logo + store info ═══
        $h.='<div style="text-align:center;border-bottom:'.$brd.';padding-bottom:8px;margin-bottom:8px;background:'.$headerBg.';padding:10px;border-radius:4px">';
        if($showLogo&&$logoUrl){
            $h.='<img src="'.esc_url($logoUrl).'" style="max-height:50px;max-width:160px;margin-bottom:4px;display:block;margin-left:auto;margin-right:auto" alt="">';
        }
        if($showStore){
            $h.='<strong style="font-size:'.$fsTitle.';color:'.$color.'">'.esc_html($storeName).'</strong>';
            if($storeSlogan)$h.='<br><span style="font-size:'.($fontSize==='small'?'8px':'10px').';color:#666">'.esc_html($storeSlogan).'</span>';
        }
        $h.='</div>';

        // ═══ Store contact ═══
        $contactParts=[];
        if($showPhone){$sp=get_option('woocommerce_store_phone',self::opt('store_phone',''));if($sp)$contactParts[]='📱 '.$sp;}
        if($showEmail){$se=get_option('woocommerce_email_from_address',get_option('admin_email',''));if($se)$contactParts[]='📧 '.$se;}
        if($showAddr){$sa=get_option('woocommerce_store_address','');if($sa)$contactParts[]='📍 '.$sa;}
        if($contactParts)$h.='<div style="text-align:center;font-size:'.($fontSize==='small'?'8px':'9px').';color:#888;margin-bottom:8px">'.implode(' — ',$contactParts).'</div>';

        // ═══ Order info table ═══
        $h.='<table style="width:100%;font-size:'.$fsBase.';margin-bottom:8px">';
        $h.='<tr><td><strong style="color:'.$color.'">طلب #'.$o->get_id().'</strong></td><td style="text-align:left">'.($o->get_date_created()?$o->get_date_created()->format('Y-m-d H:i'):'').'</td></tr>';
        $h.='<tr><td>العميل:</td><td>'.esc_html($o->get_billing_first_name()).'</td></tr>';
        $h.='<tr><td>الهاتف:</td><td style="direction:ltr">'.esc_html($o->get_billing_phone()).'</td></tr>';
        $p2=$o->get_meta('_dzqcod_phone2');if($p2)$h.='<tr><td>الهاتف 2:</td><td style="direction:ltr">'.esc_html($p2).'</td></tr>';
        $h.='<tr><td>الولاية:</td><td>'.esc_html($o->get_shipping_state()).'</td></tr>';
        $h.='<tr><td>البلدية:</td><td>'.esc_html($o->get_shipping_city()).'</td></tr>';
        if($showAddr){$a1=$o->get_shipping_address_1();if($a1)$h.='<tr><td>العنوان:</td><td>'.esc_html($a1).'</td></tr>';}
        $tk=$o->get_meta('_dzqcod_tracking_number');if($tk)$h.='<tr><td>التتبع:</td><td>'.esc_html($tk).'</td></tr>';
        $h.='</table>';

        // ═══ Products table ═══
        if($showProducts){
            $h.='<table style="width:100%;border-collapse:collapse;margin-bottom:8px"><tr style="border-bottom:1px solid '.$color.'"><th style="text-align:right;padding:4px">المنتج</th><th style="padding:4px">الكمية</th><th style="padding:4px">السعر</th></tr>';
            foreach($o->get_items() as $i){
                $meta=[];$cl=$i->get_meta('اللون');$sz=$i->get_meta('المقاس');if($cl)$meta[]='🎨 '.$cl;if($sz)$meta[]='📐 '.$sz;
                $h.='<tr><td style="padding:4px">'.esc_html($i->get_name()).($meta?' <small>('.implode(' | ',$meta).')</small>':'').'</td><td style="text-align:center;padding:4px">'.$i->get_quantity().'</td><td style="text-align:center;padding:4px">'.number_format((float)$i->get_total(),0).' دج</td></tr>';
            }
            $h.='</table>';
        }

        // ═══ Totals ═══
        $h.='<div style="border-top:'.$brd.';padding-top:8px">';
        $ship=(float)$o->get_shipping_total();
        if($showShipping&&$ship>0)$h.='🚚 الشحن: '.number_format($ship,0).' دج<br>';
        if($showTotal){
            $tfs=['small'=>'13px','medium'=>'15px','large'=>'18px'];
            $h.='<strong style="font-size:'.($tfs[$fontSize]??'15px').';color:'.$color.'">المجموع: '.number_format((float)$o->get_total(),0).' دج</strong><br>';
        }
        $pm=$o->get_payment_method();$pLabel=($pm&&$pm!=='cod')?$o->get_payment_method_title():'💰 الدفع عند الاستلام';
        $h.='<div style="text-align:center;margin-top:6px;padding:4px;border:1px solid '.$color.';font-weight:bold;border-radius:4px;color:'.$color.'">'.esc_html($pLabel).'</div></div>';

        // ═══ Notes ═══
        if($showNotes){$n=$o->get_customer_note();if($n)$h.='<div style="margin-top:6px;font-size:'.($fontSize==='small'?'8px':'10px').';color:#555">📝 '.esc_html($n).'</div>';}

        // ═══ Barcode ═══
        if($showBarcode){
            $bc=$o->get_id();
            $h.='<div style="text-align:center;margin-top:8px;font-family:\'Libre Barcode 39\',monospace;font-size:32px;letter-spacing:2px">*'.esc_html($bc).'*</div>';
            $h.='<div style="text-align:center;font-size:9px;color:#999">#'.$bc.'</div>';
        }

        // ═══ Footer text ═══
        if($footerText)$h.='<div style="text-align:center;margin-top:8px;font-size:'.($fontSize==='small'?'8px':'10px').';color:#888;border-top:1px dotted #ccc;padding-top:6px">'.esc_html($footerText).'</div>';

        $h.='<div style="text-align:center;margin-top:4px;font-size:8px;color:#bbb">DZQCOD v'.\DZQCOD_VER.'</div></div>';
        return $h;
    }

    public function dzqcod_update_order_status():void{check_ajax_referer('dzqcod_admin','nonce');$o=wc_get_order(absint($_POST['order_id']??0));$st=sanitize_text_field($_POST['status']??'');if(!$o||!$st)wp_send_json_error();$o->set_status($st);$o->save();wp_send_json_success();}
    public function dzqcod_create_shipment():void{check_ajax_referer('dzqcod_admin','nonce');$o=wc_get_order(absint($_POST['order_id']??0));if(!$o)wp_send_json_error();$o->set_status('wc-shipped');$o->add_order_note('🚚 تم الشحن');$o->save();wp_send_json_success(['message'=>'تم شحن #'.$o->get_id()]);}
    public function dzqcod_save_form_settings():void{check_ajax_referer('dzqcod_admin','nonce');if(!current_user_can('manage_options'))wp_send_json_error();$d=$_POST['settings']??[];if(!is_array($d))wp_send_json_error();foreach($d as $k=>$v)update_option('dzqcod_'.sanitize_key($k),sanitize_text_field($v),false);wp_send_json_success(['message'=>'تم الحفظ']);}
    public function dzqcod_save_settings():void{
        check_ajax_referer('dzqcod_admin','nonce');
        if(!current_user_can('manage_options'))wp_send_json_error();

        // ═══ Add Wilaya ═══
        if(!empty($_POST['add_wilaya'])){
            global $wpdb; $p=$wpdb->prefix.DZQCOD_DB;
            $code=sanitize_text_field($_POST['wil_code']??'');
            $name_ar=sanitize_text_field($_POST['wil_name_ar']??'');
            $name_fr=sanitize_text_field($_POST['wil_name_fr']??'');
            $desk=floatval($_POST['wil_desk']??0);
            $home=floatval($_POST['wil_home']??0);
            $cc=self::opt('country','DZ');
            if(!$code||!$name_ar) wp_send_json_error(['message'=>'الكود والاسم مطلوبان']);
            $wpdb->replace($p.'wilayas',['code'=>$code,'name_ar'=>$name_ar,'name_fr'=>$name_fr,'country'=>$cc,'shipping_desk'=>$desk,'shipping_home'=>$home,'is_active'=>1],['%s','%s','%s','%s','%f','%f','%d']);
            // Add communes
            $communes=sanitize_text_field($_POST['wil_communes']??'');
            if($communes){foreach(explode(',',$communes) as $c){$c=trim($c);if($c)$wpdb->insert($p.'communes',['wilaya_code'=>$code,'name_ar'=>$c,'is_active'=>1],['%s','%s','%d']);}}
            wp_send_json_success(['message'=>'تمت إضافة الولاية '.$name_ar.' بنجاح']);
        }

        // ═══ Import Wilayas from CSV ═══
        if(!empty($_POST['import_wilayas']) && !empty($_FILES['file'])){
            global $wpdb; $p=$wpdb->prefix.DZQCOD_DB;
            $file=$_FILES['file']['tmp_name']??'';
            if(!$file||!is_readable($file)) wp_send_json_error(['message'=>'ملف غير صالح']);
            $ext=strtolower(pathinfo($_FILES['file']['name']??'',PATHINFO_EXTENSION));
            $rows=[];
            if($ext==='csv'){
                $h=fopen($file,'r'); if(!$h) wp_send_json_error(['message'=>'لا يمكن فتح الملف']);
                $header=fgetcsv($h);
                while(($r=fgetcsv($h))!==false){if(count($r)>=2)$rows[]=$r;}
                fclose($h);
            } else { wp_send_json_error(['message'=>'يرجى رفع ملف CSV — الأعمدة: code, name_ar, name_fr, shipping_desk, shipping_home']); }
            $count=0;
            foreach($rows as $r){
                $code=sanitize_text_field($r[0]??''); $name_ar=sanitize_text_field($r[1]??'');
                if(!$code||!$name_ar) continue;
                $wpdb->replace($p.'wilayas',['code'=>$code,'name_ar'=>$name_ar,'name_fr'=>sanitize_text_field($r[2]??''),'shipping_desk'=>floatval($r[3]??0),'shipping_home'=>floatval($r[4]??0),'is_active'=>1],['%s','%s','%s','%f','%f','%d']);
                $count++;
            }
            wp_send_json_success(['message'=>'تم استيراد '.$count.' ولاية بنجاح']);
        }

        // ═══ Import WooCommerce States ═══
        if(!empty($_POST['import_wc_states'])){
            $cc=self::opt('country','DZ');$cnt=0;
            if(class_exists('WC_Countries')){
                $wc=new \WC_Countries();$states=$wc->get_states($cc);
                if(!empty($states)){
                    foreach($states as $code=>$name){
                        $wpdb->replace($p.'wilayas',['code'=>$code,'name_ar'=>$name,'name_fr'=>$name,'shipping_desk'=>0,'shipping_home'=>0,'is_active'=>1,'country'=>$cc],['%s','%s','%s','%f','%f','%d','%s']);
                        $cnt++;
                    }
                }
            }
            wp_send_json_success(['message'=>"تم استيراد {$cnt} ولاية/محافظة من WooCommerce"]);
        }

        $data=array_map('sanitize_text_field',$_POST['settings']??[]);
        foreach($data as $k=>$v)update_option('dzqcod_'.sanitize_key($k),sanitize_text_field($v),false);
        wp_send_json_success(['message'=>'تم الحفظ']);
    }

    // ════════════════════════════════════════════════════════════════
    //  AJAX: Save Post-Order Confirmation Pages Settings
    // ════════════════════════════════════════════════════════════════
    public function dzqcod_save_postorder_settings(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if(!current_user_can('manage_options'))wp_send_json_error();
        $fields = [
            'otp_enabled','otp_message','otp_success_text','otp_expire_minutes',
            'thankyou_title','thankyou_message','thankyou_show_order_details','thankyou_show_callback',
            'callback_title','callback_message','callback_store_phone','callback_slots',
            'confirmed_title','confirmed_message',
            'post_order_redirect_url','post_order_upsell_enabled','post_order_upsell_text',
        ];
        foreach ($fields as $f) {
            if (isset($_POST[$f])) {
                $v = ($f === 'otp_message' || $f === 'thankyou_message' || $f === 'callback_message' || $f === 'confirmed_message' || $f === 'post_order_upsell_text')
                    ? sanitize_textarea_field($_POST[$f])
                    : sanitize_text_field($_POST[$f]);
                update_option('dzqcod_' . $f, $v, false);
            }
        }
        wp_send_json_success(['message' => '✅ تم حفظ إعدادات صفحات التأكيد']);
    }

    public function dzqcod_save_product_meta(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if(!current_user_can('manage_options'))wp_send_json_error();
        // Redirect to full handler
        $this->dzqcod_save_full_product();
    }

    public function dzqcod_save_full_product(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if(!current_user_can('manage_options'))wp_send_json_error(['message'=>'صلاحيات غير كافية']);
        parse_str($_POST['data']??'',$d);
        $pid = absint($_POST['product_id']??0);
        $is_new = !$pid;

        // ═══ WooCommerce Product ═══
        $name = sanitize_text_field($d['name']??'');
        if(!$name) wp_send_json_error(['message'=>'اسم المنتج مطلوب']);

        if($is_new){
            $product = new \WC_Product_Simple();
        } else {
            $product = wc_get_product($pid);
            if(!$product) wp_send_json_error(['message'=>'منتج غير موجود']);
        }
        $product->set_name($name);
        $product->set_description(sanitize_textarea_field($d['description']??''));
        $product->set_status(sanitize_text_field($d['status']??'publish'));
        $product->set_catalog_visibility('visible');

        // Image
        $img_id = absint($d['image_id']??0);
        if($img_id) $product->set_image_id($img_id);

        // Custom product mode — when enabled, set WC price to custom_base as fallback
        $cpc_on = ($d['custom_enabled']??'')==='yes';
        if($cpc_on){
            $cbase = max(0, floatval($d['custom_base']??0));
            $product->set_regular_price($cbase > 0 ? $cbase : 0);
            $product->set_sale_price('');
        } else {
            $reg = max(0, floatval($d['price']??0));
            $sale = floatval($d['sale_price']??0);
            if($reg > 0) $product->set_regular_price($reg);
            if($sale > 0 && $sale < $reg) $product->set_sale_price($sale); else $product->set_sale_price('');
        }

        $pid = $product->save();
        if(!$pid) wp_send_json_error(['message'=>'خطأ في حفظ المنتج']);

        // ═══ DZQCOD Meta ═══
        update_post_meta($pid,'_dzqcod_disabled', ($d['disabled']??'')==='yes'?'yes':'no');
        update_post_meta($pid,'_dzqcod_colors', sanitize_text_field($d['colors']??''));
        update_post_meta($pid,'_dzqcod_sizes', sanitize_text_field($d['sizes']??''));
        update_post_meta($pid,'_dzqcod_badge', sanitize_text_field($d['badge']??''));
        update_post_meta($pid,'_dzqcod_whatsapp', sanitize_text_field($d['whatsapp']??''));
        update_post_meta($pid,'_dzqcod_cost_price', floatval($d['cost_price']??0));
        update_post_meta($pid,'_dzqcod_digital', ($d['digital']??'')==='yes'?'yes':'no');

        // Qty tiers
        $tiers=[];
        if(!empty($d['tier_min']) && is_array($d['tier_min'])){
            foreach($d['tier_min'] as $i=>$m){
                $m=absint($m); $p=floatval($d['tier_price'][$i]??0);
                if($m<1||$p<=0)continue;
                $tiers[]=['min_qty'=>$m,'price'=>$p,'label'=>sanitize_text_field($d['tier_label'][$i]??'')];
            }
            usort($tiers,fn($a,$b)=>$a['min_qty']-$b['min_qty']);
        }
        update_post_meta($pid,'_dzqcod_qty_pricing', !empty($tiers)?json_encode($tiers,JSON_UNESCAPED_UNICODE):'');

        // Custom product
        update_post_meta($pid,'_dzqcod_custom_enabled', $cpc_on?'yes':'no');
        update_post_meta($pid,'_dzqcod_pricing_mode', sanitize_text_field($d['pricing_mode']??'fixed'));
        update_post_meta($pid,'_dzqcod_price_per_unit', sanitize_text_field($d['ppu']??''));
        update_post_meta($pid,'_dzqcod_unit_label', sanitize_text_field($d['unit_label']??'م²'));
        update_post_meta($pid,'_dzqcod_custom_base', sanitize_text_field($d['custom_base']??''));

        // Dimensions
        $dims=[];
        if(!empty($d['dim_name']) && is_array($d['dim_name'])){
            foreach($d['dim_name'] as $i=>$n){
                $n=sanitize_text_field($n); if(!$n)continue;
                $dims[]=['name'=>$n,'unit'=>sanitize_text_field($d['dim_unit'][$i]??'سم'),'min'=>floatval($d['dim_min'][$i]??0),'max'=>floatval($d['dim_max'][$i]??0),'step'=>floatval($d['dim_step'][$i]??1)];
            }
        }
        update_post_meta($pid,'_dzqcod_dimensions', json_encode($dims,JSON_UNESCAPED_UNICODE));

        // Paid options
        $opts=[];
        if(!empty($d['opt_name']) && is_array($d['opt_name'])){
            foreach($d['opt_name'] as $i=>$n){
                $n=sanitize_text_field($n); if(!$n)continue;
                $opts[]=['name'=>$n,'type'=>sanitize_text_field($d['opt_type'][$i]??'checkbox'),'price'=>floatval($d['opt_price'][$i]??0),'values'=>sanitize_text_field($d['opt_values'][$i]??'')];
            }
        }
        update_post_meta($pid,'_dzqcod_paid_options', json_encode($opts,JSON_UNESCAPED_UNICODE));

        // Upload & notes
        update_post_meta($pid,'_dzqcod_upload_enabled', ($d['upload_enabled']??'')==='yes'?'yes':'no');
        update_post_meta($pid,'_dzqcod_custom_note', ($d['custom_note']??'')==='yes'?'yes':'no');

        // Video URL
        update_post_meta($pid,'_dzqcod_video_url', esc_url_raw($d['video_url']??''));

        // Payment methods
        $pm = isset($d['payment_methods']) && is_array($d['payment_methods']) ? array_map('sanitize_text_field', $d['payment_methods']) : ['cod'];
        update_post_meta($pid, '_dzqcod_payment_methods', implode(',', $pm));

        // Gallery
        if(!empty($d['gallery_ids']) && is_array($d['gallery_ids'])){
            $gallery = array_map('absint', $d['gallery_ids']);
            $product->set_gallery_image_ids($gallery);
            $product->save();
        }

        // Digital product features
        if(($d['digital']??'')==='yes'){
            update_post_meta($pid,'_dzqcod_download_url', esc_url_raw($d['download_url']??''));
            update_post_meta($pid,'_dzqcod_download_limit', absint($d['download_limit']??3));
            update_post_meta($pid,'_dzqcod_download_expiry', absint($d['download_expiry']??48));
            update_post_meta($pid,'_dzqcod_download_files', sanitize_textarea_field($d['download_files']??''));
            // Set WooCommerce virtual + downloadable
            $product->set_virtual(true);
            $product->set_downloadable(true);
            $product->set_download_limit(absint($d['download_limit']??3));
            $product->set_download_expiry(absint($d['download_expiry']??48));
            // Add download files to WC
            $wc_downloads = [];
            $main_url = esc_url_raw($d['download_url']??'');
            if($main_url){
                $dl = new \WC_Product_Download();
                $dl->set_id(md5($main_url));
                $dl->set_name(basename($main_url) ?: 'الملف الرئيسي');
                $dl->set_file($main_url);
                $wc_downloads[] = $dl;
            }
            $extra = array_filter(array_map('trim', explode("\n", $d['download_files']??'')));
            foreach($extra as $ef){
                $ef = esc_url_raw($ef); if(!$ef) continue;
                $dl = new \WC_Product_Download();
                $dl->set_id(md5($ef));
                $dl->set_name(basename($ef));
                $dl->set_file($ef);
                $wc_downloads[] = $dl;
            }
            if($wc_downloads) $product->set_downloads($wc_downloads);
            $product->save();
        } else {
            // Unset virtual/downloadable if toggled off
            if($product->is_virtual()){$product->set_virtual(false);$product->set_downloadable(false);$product->save();}
        }

        // Scheduling
        if(($d['status']??'')==='future' && !empty($d['schedule_date'])){
            $sched = sanitize_text_field($d['schedule_date']);
            wp_update_post(['ID'=>$pid,'post_status'=>'future','post_date'=>$sched,'post_date_gmt'=>get_gmt_from_date($sched)]);
        }

        wp_send_json_success(['message'=>'✅ تم حفظ المنتج','product_id'=>$pid]);
    }

    // ════════════════════════════════════════════════════════════════
    //  AJAX: POS Create Order — creates order from POS interface
    // ════════════════════════════════════════════════════════════════
    public function dzqcod_pos_create_order(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if(!current_user_can('manage_woocommerce')) wp_send_json_error(['message'=>'صلاحيات غير كافية']);

        $items = json_decode(stripslashes($_POST['items']??'[]'),true);
        $customer_name = sanitize_text_field($_POST['customer_name']??'عميل POS');
        $customer_phone = sanitize_text_field($_POST['customer_phone']??'');
        $delivery_type = sanitize_text_field($_POST['delivery_type']??'store_pickup');
        $wilaya = sanitize_text_field($_POST['wilaya']??'');
        $commune = sanitize_text_field($_POST['commune']??'');
        $address = sanitize_text_field($_POST['address']??'');
        $payment = sanitize_text_field($_POST['payment_method']??'cash');
        $discount = max(0,floatval($_POST['discount']??0));
        $note = sanitize_textarea_field($_POST['note']??'');

        if(empty($items)) wp_send_json_error(['message'=>'السلة فارغة']);

        // Check if any item is custom → route to workshop
        $has_custom = false;
        foreach($items as $item){
            if(!empty($item['customData'])) $has_custom=true;
        }

        $status = ($delivery_type==='store_pickup' && !$has_custom) ? 'wc-completed' : ($has_custom ? 'wc-confirmed' : 'wc-confirmed');
        $order = wc_create_order(['status'=>$status]);
        if(is_wp_error($order)) wp_send_json_error(['message'=>'خطأ في إنشاء الطلب']);

        $subtotal = 0;
        foreach($items as $item){
            $p = wc_get_product(absint($item['id']??0));
            if(!$p) continue;
            $qty = max(1,absint($item['qty']??1));
            $price = floatval($item['price']??$p->get_price());
            $item_id = $order->add_product($p,$qty);
            if(abs($price-(float)$p->get_price())>0.01){
                $it=$order->get_item($item_id);
                $it->set_subtotal($price*$qty);$it->set_total($price*$qty);$it->save();
            }
            $subtotal += $price * $qty;

            // Save custom data per item
            if(!empty($item['customData'])){
                $cd = $item['customData'];
                if(!empty($cd['dims'])){
                    $order->update_meta_data('_dzqcod_custom_dimensions', json_encode($cd['dims'],JSON_UNESCAPED_UNICODE));
                }
                if(!empty($cd['opts'])){
                    $order->update_meta_data('_dzqcod_custom_options', json_encode($cd['opts'],JSON_UNESCAPED_UNICODE));
                }
            }
        }

        // Shipping for delivery
        $ship_cost = 0;
        if($delivery_type==='home_delivery' && $wilaya){
            global $wpdb;
            $wrow=$wpdb->get_row($wpdb->prepare("SELECT * FROM ".self::db()."wilayas WHERE code=%s",$wilaya));
            $ship_cost = $wrow ? (float)$wrow->shipping_home : 0;
            if($ship_cost>0){
                $si=new \WC_Order_Item_Shipping();$si->set_method_title('توصيل للمنزل');$si->set_total($ship_cost);$order->add_item($si);
            }
        }

        // Discount
        if($discount>0){
            $fe=new \WC_Order_Item_Fee();$fe->set_name('خصم POS');$fe->set_total(-$discount);$order->add_item($fe);
        }

        $adr=['first_name'=>$customer_name,'phone'=>$customer_phone,'address_1'=>$address,'state'=>$wilaya,'city'=>$commune,'country'=>'DZ'];
        $order->set_address($adr,'billing');
        if($delivery_type==='home_delivery') $order->set_address($adr,'shipping');

        $pay_titles = ['cash'=>'نقداً','card'=>'بطاقة بنكية','baridimob'=>'بريدي موب','transfer'=>'تحويل بنكي'];
        $order->set_payment_method($payment);
        $order->set_payment_method_title($pay_titles[$payment]??'نقداً');
        if($note) $order->set_customer_note($note);
        $order->update_meta_data('_dzqcod_source','pos');
        $order->update_meta_data('_dzqcod_delivery_type',$delivery_type);
        $order->update_meta_data('_dzqcod_pos_operator',wp_get_current_user()->display_name);
        $order->calculate_totals();
        $order->save();

        // Receipt data
        $receipt = [
            'order_id'=>$order->get_id(),'total'=>number_format((float)$order->get_total(),0),
            'subtotal'=>number_format($subtotal,0),'shipping'=>number_format($ship_cost,0),
            'discount'=>number_format($discount,0),'payment'=>$pay_titles[$payment]??$payment,
            'delivery'=>$delivery_type==='store_pickup'?'استلام من المتجر':'توصيل للمنزل',
            'customer'=>$customer_name,'phone'=>$customer_phone,
            'items'=>$items,'date'=>date('Y-m-d H:i'),
        ];

        wp_send_json_success(['message'=>'✅ تم إنشاء الطلب #'.$order->get_id(),'order_id'=>$order->get_id(),'receipt'=>$receipt]);
    }

    public function dzqcod_export_orders():void{
        check_ajax_referer('dzqcod_admin','nonce');
        if(!current_user_can('manage_woocommerce'))wp_die('Forbidden');
        $status=sanitize_key($_GET['status']??'');
        $args=['limit'=>-1,'orderby'=>'date','order'=>'DESC'];
        if($status)$args['status']='wc-'.$status;
        else $args['status']=array_map(fn($s)=>'wc-'.$s,array_keys(self::ST));
        $orders=wc_get_orders($args);
        header('Content-Type:text/csv;charset=UTF-8');
        header('Content-Disposition:attachment;filename=dzqcod-orders-'.gmdate('Y-m-d').'.csv');
        $fp=fopen('php://output','w');
        fprintf($fp,chr(0xEF).chr(0xBB).chr(0xBF));
        fputcsv($fp,['#','الاسم','الهاتف 1','الهاتف 2','الولاية','البلدية','العنوان','المنتجات','اللون','المقاس','الكمية','المبلغ','الشحن','المجموع','الحالة','الدفع','احتيال','تاريخ']);
        foreach($orders as $o){
            $items=[];$colors=[];$sizes=[];$qtys=0;
            foreach($o->get_items() as $i){$items[]=$i->get_name();$cl=$i->get_meta('اللون');$sz=$i->get_meta('المقاس');if($cl)$colors[]=$cl;if($sz)$sizes[]=$sz;$qtys+=$i->get_quantity();}
            fputcsv($fp,[$o->get_id(),$o->get_billing_first_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,number_format((float)$o->get_subtotal(),0),(float)$o->get_shipping_total(),number_format((float)$o->get_total(),0),self::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_date_created()?$o->get_date_created()->format('Y-m-d H:i'):'']);
        }
        fclose($fp);exit;
    }

    // ════════════════════════════════════════════════════════════════
    //  LICENSE
    // ════════════════════════════════════════════════════════════════
    // ════════════════════════════════════════════════════════════════
    //  NIBRA LICENSE API — productes.nibra.cloud
    // ════════════════════════════════════════════════════════════════
    private static function nibra_api(string $method, string $ep, array $body=[]): array {
        $url = self::LICENSE_API.'/'.ltrim($ep,'/');
        $args = ['headers'=>['Content-Type'=>'application/json','Accept'=>'application/json','X-Nibra-Client'=>'DZQCOD/'.DZQCOD_VER],'timeout'=>20,'sslverify'=>apply_filters('dzqcod_ssl_verify',true)];
        if($method==='GET'){if($body)$url.='?'.http_build_query($body);$resp=wp_remote_get($url,$args);}
        else{$args['body']=wp_json_encode($body);$resp=wp_remote_post($url,$args);}
        if(is_wp_error($resp))return['ok'=>false,'error'=>$resp->get_error_message()];
        $code=wp_remote_retrieve_response_code($resp);$data=json_decode(wp_remote_retrieve_body($resp),true)?:[];
        return['ok'=>$code>=200&&$code<300,'http'=>$code,'data'=>$data];
    }

    public function dzqcod_activate_license():void{
        check_ajax_referer('dzqcod_admin','nonce');
        $key=sanitize_text_field($_POST['license_key']??'');
        if(!$key)wp_send_json_error(['message'=>'المفتاح مطلوب']);
        $domain=wp_parse_url(home_url(),PHP_URL_HOST)?:($_SERVER['HTTP_HOST']??'');

        // Ping server first
        $ping=self::nibra_api('GET','ping');
        if(!$ping['ok']){wp_send_json_error(['message'=>'❌ لا يمكن الاتصال بسيرفر الترخيص: '.($ping['error']??'')]);return;}

        // Activate
        $r=self::nibra_api('POST','activate',['key'=>$key,'domain'=>$domain,'product'=>self::PRODUCT_SLUG]);
        $data=$r['data']??[];$valid=!empty($data['valid']);$code=$data['code']??'';$msg=$data['message']??'';

        // Debug log
        update_option('dzqcod_license_debug',['time'=>current_time('mysql'),'endpoint'=>'activate','http'=>$r['http']??0,'code'=>$code,'valid'=>$valid,'plan'=>$data['plan']??'','msg'=>$msg,'domain'=>$domain]);

        if($valid&&in_array($code,['ok','activated','already_active'])){
            $plan=$data['plan']??'pro';$expiry=$data['expiry']??'';$client=$data['client']??'';
            global $wpdb;$wpdb->replace(self::db().'license',['id'=>1,'license_key'=>$key,'plan'=>$plan,'status'=>'active','domain'=>home_url(),'activated_at'=>current_time('mysql'),'expires_at'=>$expiry?:null,'last_check'=>current_time('mysql')]);
            update_option('dzqcod_license_key',$key);update_option('dzqcod_license_plan',$plan);
            if(!empty($data['features']))update_option('dzqcod_license_features',$data['features']);
            if(!empty($data['addons']))update_option('dzqcod_license_addons',$data['addons']);
            if($client)update_option('dzqcod_license_client',$client);
            // Send install stats (non-blocking)
            wp_remote_post(self::LICENSE_API.'/install',['body'=>wp_json_encode(['key'=>$key,'domain'=>$domain,'product'=>self::PRODUCT_SLUG,'action'=>'install','plugin_version'=>DZQCOD_VER,'wp_version'=>get_bloginfo('version'),'php_version'=>PHP_VERSION,'locale'=>get_locale()]),'headers'=>['Content-Type'=>'application/json'],'timeout'=>5,'sslverify'=>apply_filters('dzqcod_ssl_verify',true),'blocking'=>false]);
            if(!wp_next_scheduled('dzqcod_license_check'))wp_schedule_event(time()+86400,'daily','dzqcod_license_check');
            wp_send_json_success(['message'=>'✅ '.$msg.' — الخطة: '.strtoupper($plan),'plan'=>$plan,'client'=>$client,'expiry'=>$expiry]);return;
        }
        if($code==='grace'){
            $plan=$data['plan']??'pro';global $wpdb;
            $wpdb->replace(self::db().'license',['id'=>1,'license_key'=>$key,'plan'=>$plan,'status'=>'grace','domain'=>home_url(),'activated_at'=>current_time('mysql'),'expires_at'=>$data['expiry']??null,'last_check'=>current_time('mysql')]);
            update_option('dzqcod_license_key',$key);update_option('dzqcod_license_plan',$plan);
            wp_send_json_success(['message'=>'⚠️ '.$msg,'plan'=>$plan]);return;
        }
        $errs=['invalid_key'=>'المفتاح أو المنتج أو النطاق غير صحيح','expired'=>'انتهت صلاحية الترخيص — يرجى التجديد','suspended'=>'الترخيص موقوف','revoked'=>'الترخيص ملغى نهائياً','domain_limit'=>'تجاوزت الحد الأقصى للنطاقات','error'=>'خطأ في البيانات'];
        wp_send_json_error(['message'=>'❌ '.($errs[$code]??$msg?:$code)]);
    }

    public function dzqcod_deactivate_license():void{
        check_ajax_referer('dzqcod_admin','nonce');
        $key=self::opt('license_key','');$domain=wp_parse_url(home_url(),PHP_URL_HOST)?:'';
        if($key){self::nibra_api('POST','deactivate',['key'=>$key,'domain'=>$domain,'product'=>self::PRODUCT_SLUG]);}
        global $wpdb;$wpdb->update(self::db().'license',['status'=>'inactive','plan'=>'free'],['id'=>1]);
        delete_option('dzqcod_license_key');delete_option('dzqcod_license_plan');
        delete_option('dzqcod_license_features');delete_option('dzqcod_license_addons');
        delete_option('dzqcod_license_client');wp_clear_scheduled_hook('dzqcod_license_check');
        wp_send_json_success(['message'=>'تم إلغاء تفعيل الترخيص']);
    }

    public static function verify_license_cron():void{
        $key=self::opt('license_key','');if(!$key)return;
        $domain=wp_parse_url(home_url(),PHP_URL_HOST)?:'';
        $r=self::nibra_api('POST','verify',['key'=>$key,'domain'=>$domain,'product'=>self::PRODUCT_SLUG]);
        if(!$r['ok'])return; // Don't deactivate on network error
        $data=$r['data']??[];$valid=!empty($data['valid']);$code=$data['code']??'';
        global $wpdb;$table=$wpdb->prefix.DZQCOD_DB.'license';
        if($valid&&in_array($code,['ok','grace'])){
            $plan=$data['plan']??self::opt('license_plan','pro');
            $wpdb->update($table,['plan'=>$plan,'status'=>$code==='grace'?'grace':'active','last_check'=>current_time('mysql'),'expires_at'=>$data['expiry']??null],['id'=>1]);
            update_option('dzqcod_license_plan',$plan);
            if(!empty($data['features']))update_option('dzqcod_license_features',$data['features']);
            if(!empty($data['addons']))update_option('dzqcod_license_addons',$data['addons']);
        } elseif(in_array($code,['expired','suspended','revoked','invalid_key'])){
            $wpdb->update($table,['status'=>'expired','plan'=>'free','last_check'=>current_time('mysql')],['id'=>1]);
            update_option('dzqcod_license_plan','free');
        }
    }
    public function apply_rbac(): void {
        $user = wp_get_current_user();
        if (!$user || current_user_can('manage_options')) return;
        global $wpdb;$pages_allowed = [];
        foreach ((array)$user->roles as $role) {
            $perm = $wpdb->get_var($wpdb->prepare("SELECT pages_json FROM " . self::db() . "rbac WHERE role_slug=%s", $role));
            if ($perm) { $a = json_decode($perm, true); if (is_array($a)) $pages_allowed = array_merge($pages_allowed, $a); }
        }
        if (empty($pages_allowed)) return;
        foreach (['dzqcod-orders','dzqcod-call-center','dzqcod-products','dzqcod-pos','dzqcod-workshop','dzqcod-shipping','dzqcod-printing','dzqcod-campaigns','dzqcod-offers','dzqcod-fraud','dzqcod-profit','dzqcod-settings','dzqcod-addons'] as $pg) {
            if (!in_array($pg, $pages_allowed)) remove_submenu_page('dzqcod', $pg);
        }
    }

    public static function is_pro():bool{return in_array(self::opt('license_plan','free'),['pro','enterprise']);}
    public static function is_ent():bool{return self::opt('license_plan','free')==='enterprise';}

    // ════════════════════════════════════════════════════════════════
    //  FRAUD BLACKLIST
    // ════════════════════════════════════════════════════════════════
    public function dzqcod_fraud_blacklist():void{
        check_ajax_referer('dzqcod_admin','nonce');global $wpdb;
        $type=sanitize_text_field($_POST['type']??'phone');$val=sanitize_text_field($_POST['value']??'');$reason=sanitize_text_field($_POST['reason']??'');
        if(!$val)wp_send_json_error();
        $wpdb->insert(self::db().'blacklist',['type'=>$type,'hash_value'=>hash('sha256',$val),'reason'=>$reason,'severity'=>'high','created_by'=>get_current_user_id()]);
        wp_send_json_success(['message'=>'تمت إضافة '.$val.' للقائمة السوداء']);
    }

    // ════════════════════════════════════════════════════════════════
    //  MESSAGING (SMS/WhatsApp stub)
    // ════════════════════════════════════════════════════════════════
    public function dzqcod_send_message():void{
        check_ajax_referer('dzqcod_admin','nonce');global $wpdb;
        $oid=absint($_POST['order_id']??0);$channel=sanitize_text_field($_POST['channel']??'whatsapp');$tpl=sanitize_text_field($_POST['template']??'');
        $order=wc_get_order($oid);if(!$order)wp_send_json_error();
        $phone=$order->get_billing_phone();
        $wpdb->insert(self::db().'message_logs',['order_id'=>$oid,'channel'=>$channel,'phone'=>$phone,'template'=>$tpl,'body'=>$tpl,'status'=>'queued']);
        wp_send_json_success(['message'=>'تم إرسال الرسالة']);
    }

    // ════════════════════════════════════════════════════════════════
    //  OFFERS
    // ════════════════════════════════════════════════════════════════
    public function dzqcod_save_offer():void{
        check_ajax_referer('dzqcod_admin','nonce');global $wpdb;
        $name=sanitize_text_field($_POST['name']??'');
        $type=sanitize_text_field($_POST['type']??'percentage');
        $value=floatval($_POST['value']??0);
        // Auto-generate coupon code if empty
        $code=sanitize_text_field($_POST['coupon_code']??'');
        if(!$code)$code=strtoupper('DZ'.wp_rand(100,999).substr(md5($name.time()),0,4));
        $data=[
            'name'=>$name,'coupon_code'=>$code,'type'=>$type,'value'=>$value,
            'description'=>sanitize_textarea_field($_POST['description']??''),
            'min_amount'=>floatval($_POST['min_amount']??0),
            'product_ids'=>sanitize_text_field($_POST['product_ids']??''),
            'rules_json'=>sanitize_text_field($_POST['rules']??'{}'),
            'max_uses'=>absint($_POST['max_uses']??0),
            'starts_at'=>sanitize_text_field($_POST['starts_at']??'')?:null,
            'ends_at'=>sanitize_text_field($_POST['ends_at']??'')?:null,
            'is_active'=>absint($_POST['is_active']??1),
        ];
        $id=absint($_POST['offer_id']??0);
        if($id)$wpdb->update(self::db().'offers',$data,['id'=>$id]);
        else{$data['priority']=10;$wpdb->insert(self::db().'offers',$data);$id=$wpdb->insert_id;}
        // Also create/update WooCommerce coupon
        $this->sync_wc_coupon($id,$code,$type,$value,$data);
        wp_send_json_success(['message'=>'تم حفظ العرض','coupon_code'=>$code,'id'=>$id]);
    }
    private function sync_wc_coupon(int $offer_id,string $code,string $type,float $value,array $data):void{
        $existing=wc_get_coupon_id_by_code($code);
        $coupon=$existing?new \WC_Coupon($existing):new \WC_Coupon();
        $coupon->set_code($code);
        $coupon->set_description($data['description']??'');
        $wc_type=$type==='percentage'?'percent':($type==='fixed'?'fixed_cart':($type==='free_shipping'?'percent':'percent'));
        $coupon->set_discount_type($wc_type);
        if($type==='free_shipping'){$coupon->set_free_shipping(true);$coupon->set_amount(0);}else{$coupon->set_amount($value);}
        if(!empty($data['min_amount']))$coupon->set_minimum_amount($data['min_amount']);
        if(!empty($data['max_uses']))$coupon->set_usage_limit($data['max_uses']);
        if(!empty($data['ends_at']))$coupon->set_date_expires($data['ends_at']);
        if(!empty($data['product_ids'])){$ids=array_map('absint',explode(',',$data['product_ids']));$coupon->set_product_ids($ids);}
        $coupon->update_meta_data('_dzqcod_offer_id',$offer_id);
        $coupon->save();
    }
    public function dzqcod_delete_offer():void{check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$id=absint($_POST['offer_id']??0);$row=$wpdb->get_row($wpdb->prepare("SELECT coupon_code FROM ".self::db()."offers WHERE id=%d",$id));if($row&&$row->coupon_code){$cid=wc_get_coupon_id_by_code($row->coupon_code);if($cid)wp_delete_post($cid,true);}$wpdb->delete(self::db().'offers',['id'=>$id]);wp_send_json_success();}

    // ═══ DELETE ORDER ═══
    public function dzqcod_delete_order(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if(!current_user_can('manage_woocommerce'))wp_send_json_error(['message'=>'غير مصرح']);
        $id=absint($_POST['order_id']??0);
        if(!$id)wp_send_json_error(['message'=>'معرّف الطلب مطلوب']);
        $o=wc_get_order($id);
        if(!$o)wp_send_json_error(['message'=>'الطلب غير موجود']);
        // Move to trash first, then permanently delete if already trashed
        $force=!empty($_POST['force']);
        if($force||$o->get_status()==='trash'){
            $o->delete(true);
            wp_send_json_success(['message'=>'تم حذف الطلب #'.$id.' نهائياً']);
        } else {
            $o->delete(false);
            wp_send_json_success(['message'=>'تم نقل الطلب #'.$id.' إلى المحذوفات']);
        }
    }

    // ═══ DELETE PRODUCT ═══
    public function dzqcod_delete_product(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if(!current_user_can('delete_products'))wp_send_json_error(['message'=>'غير مصرح']);
        $id=absint($_POST['product_id']??0);
        if(!$id)wp_send_json_error(['message'=>'معرّف المنتج مطلوب']);
        $p=wc_get_product($id);
        if(!$p)wp_send_json_error(['message'=>'المنتج غير موجود']);
        $force=!empty($_POST['force']);
        if($force||get_post_status($id)==='trash'){
            wp_delete_post($id,true);
            wp_send_json_success(['message'=>'تم حذف المنتج نهائياً']);
        } else {
            wp_trash_post($id);
            wp_send_json_success(['message'=>'تم نقل المنتج إلى المحذوفات']);
        }
    }

    // ═══ DELETE WILAYA ═══
    public function dzqcod_delete_wilaya(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if(!current_user_can('manage_options'))wp_send_json_error(['message'=>'غير مصرح']);
        $code=sanitize_text_field($_POST['wilaya_code']??'');
        if(!$code)wp_send_json_error(['message'=>'كود الولاية مطلوب']);
        global $wpdb; $p=$wpdb->prefix.DZQCOD_DB;
        $wpdb->delete($p.'communes',['wilaya_code'=>$code]);
        $wpdb->delete($p.'wilayas',['code'=>$code]);
        wp_send_json_success(['message'=>'تم حذف الولاية وبلدياتها']);
    }
    public function dzqcod_clear_errors():void{check_ajax_referer('dzqcod_admin','nonce');update_option('dzqcod_last_errors','',false);wp_send_json_success(['message'=>'تم مسح سجل الأخطاء']);}
    public function dzqcod_refresh_notifs():void{check_ajax_referer('dzqcod_admin','nonce');delete_transient('dzqcod_server_notifs');wp_send_json_success(['message'=>'تم تحديث الإشعارات']);}

    // ════════════════════════════════════════════════════════════════
    //  DAILY CLEANUP
    // ════════════════════════════════════════════════════════════════
    public function daily_cleanup():void{
        global $wpdb;$p=self::db();
        $wpdb->query("DELETE FROM {$p}blacklist WHERE expires_at IS NOT NULL AND expires_at<NOW()");
        $wpdb->query("DELETE FROM {$p}audit_log WHERE created_at<DATE_SUB(NOW(),INTERVAL 90 DAY)");
    }

    // ════════════════════════════════════════════════════════════════
    //  PRODUCT METABOX
    // ════════════════════════════════════════════════════════════════
    // Product tab/panel/save handled by ProductEnhanced.php

    // ════════════════════════════════════════════════════════════════
    //  FRONTEND + ADMIN ASSETS
    // ════════════════════════════════════════════════════════════════
    public function enqueue_front():void{
        // Load on product pages, shortcode pages, and popup pages
        $popup_on = self::opt('popup_enabled','') === 'yes' && absint(self::opt('popup_product_id','0')) > 0;
        $is_product = is_singular('product');
        $is_page_with_shortcode = false;
        if (is_page() || is_singular()) {
            global $post;
            if ($post && !empty($post->post_content)) {
                $is_page_with_shortcode = has_shortcode($post->post_content, 'dzqcod_order')
                    || has_shortcode($post->post_content, 'dzqcod_quick_order')
                    || has_shortcode($post->post_content, 'dzqcod_tracking')
                    || has_shortcode($post->post_content, 'dzqcod_reviews');
            }
        }
        if (!$is_product && !$is_page_with_shortcode && !$popup_on) return;
        wp_enqueue_style('dzqcod-f',\DZQCOD_URL.'assets/css/front.css',[],\DZQCOD_VER);
        wp_enqueue_script('dzqcod-f',\DZQCOD_URL.'assets/js/front.js',['jquery'],\DZQCOD_VER,true);
        wp_localize_script('dzqcod-f','dzqcod',['ajax'=>admin_url('admin-ajax.php'),'nonce'=>wp_create_nonce('dzqcod_order'),
            'upsell_enabled'=>self::opt('upsell_enabled',''),'otp_enabled'=>self::opt('otp_enabled',''),
            'bump_title'=>self::opt('bump_title','🔥 أضف لطلبك بخصم خاص!'),
            'po_thankyou_title'=>self::opt('thankyou_title','✅ تم إرسال طلبك بنجاح!'),
            'po_thankyou_msg'=>self::opt('thankyou_message','سيتم الاتصال بك قريباً لتأكيد الطلب'),
            'po_show_callback'=>self::opt('thankyou_show_callback','yes'),
            'po_callback_title'=>self::opt('callback_title','📞 سنتصل بك لتأكيد الطلب'),
            'po_callback_msg'=>self::opt('callback_message','اختر الفترة المناسبة للاتصال بك'),
            'po_callback_phone'=>self::opt('callback_store_phone',''),
            'po_confirmed_title'=>self::opt('confirmed_title','🎉 تم تأكيد طلبك!'),
            'po_confirmed_msg'=>self::opt('confirmed_message','سيتم شحن طلبك قريباً'),
            'po_upsell_enabled'=>self::opt('post_order_upsell_enabled',''),
            'po_upsell_text'=>self::opt('post_order_upsell_text','🔥 عروض حصرية لك!'),
        ]);
    }
    public function dynamic_css():void{
        $popup_on = self::opt('popup_enabled','') === 'yes';
        if(!is_singular('product')&&!is_page()&&!$popup_on)return;
        $pc=self::opt('form_primary_color','#667eea');$sc=self::opt('form_secondary_color','#764ba2');
        $gc=self::opt('form_success_color','#27ae60');$tc=self::opt('form_text_color','#333');
        $bg=self::opt('form_bg_color','#fff');$bt=self::opt('form_btn_text_color','#fff');
        $r=intval(self::opt('form_border_radius','12'));$mw=intval(self::opt('form_max_width','480'))?:480;
        // New design vars
        $gbg=self::opt('form_group_bg','#f8fafc');$fbg=self::opt('form_field_bg','#ffffff');
        $fbd=self::opt('form_field_border','#e2e8f0');$lc=self::opt('form_label_color','#374151');
        $shw=self::opt('form_shadow','none');$ts=self::opt('form_total_style','card');
        $gt=self::opt('form_group_title','yes');
        $shwV=$shw==='lg'?'0 12px 40px rgba(0,0,0,.15)':($shw==='sm'?'0 4px 16px rgba(0,0,0,.08)':'none');
        echo "<style id=dzqcod-vars>.dzqcod-quick-order{--c1:{$pc};--c2:{$sc};--cg:{$gc};--ct:{$tc};--cbg:{$bg};--cbt:{$bt};--r:{$r}px;--gbg:{$gbg};--fbg:{$fbg};--fbd:{$fbd};--lc:{$lc};max-width:{$mw}px;box-shadow:{$shwV}}</style>\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- inline script/style with escaped vars
        $layout = self::opt('form_layout','stacked');
        $istyle = self::opt('form_input_style','bordered');
        $font = self::opt('form_font','');
        $fsize = intval(self::opt('form_font_size','15'))?:15;
        $lsize = intval(self::opt('form_label_size','13'))?:13;
        $extra = '';
        if ($font) {
            $extra .= "@import url('https://fonts.googleapis.com/css2?family=".urlencode($font).":wght@400;700;800&display=swap');";
            $extra .= ".dzqcod-quick-order,.dzqcod-quick-order *{font-family:'{$font}',sans-serif!important}";
        }
        $extra .= ".dzqcod-quick-order{font-size:{$fsize}px}";
        $extra .= ".dzqcod-field label,.dzqcod-lbl{font-size:{$lsize}px;color:{$lc}!important;font-weight:700}";
        // Group backgrounds
        $extra .= ".dzqcod-form-section{background:{$gbg};border-radius:{$r}px;padding:12px;margin-bottom:8px}";
        // Group titles
        if ($gt === 'yes') {
            $extra .= ".dzqcod-section-title{font-size:12px;font-weight:800;color:{$pc};margin-bottom:8px;padding-bottom:4px;border-bottom:1px solid {$fbd}}";
        } else {
            $extra .= ".dzqcod-section-title{display:none}";
        }
        // Field styles
        $extra .= ".dzqcod-field input,.dzqcod-field select,.dzqcod-field textarea{background:{$fbg};border:2px solid {$fbd};border-radius:{$r}px}";
        $extra .= ".dzqcod-field input:focus,.dzqcod-field select:focus,.dzqcod-field textarea:focus{border-color:{$pc}!important;outline:none}";
        // Layout
        if ($layout === 'inline') {
            $extra .= ".dzqcod-form-section.dzqcod-inline-group{display:grid;grid-template-columns:1fr 1fr;gap:8px}";
            $extra .= ".dzqcod-field-inline{margin-bottom:0!important}";
        } elseif ($layout === 'compact') {
            $extra .= ".dzqcod-field input,.dzqcod-field select{padding:8px!important;font-size:13px!important}";
            $extra .= ".dzqcod-form-section{margin-bottom:6px!important;padding:8px!important}";
        }
        // Input style overrides
        if ($istyle === 'underline') {
            $extra .= ".dzqcod-field input,.dzqcod-field select,.dzqcod-field textarea{border:none!important;border-bottom:2px solid {$fbd}!important;border-radius:0!important;background:transparent!important}";
            $extra .= ".dzqcod-field input:focus,.dzqcod-field select:focus{border-bottom-color:{$pc}!important;box-shadow:none!important}";
        } elseif ($istyle === 'filled') {
            $extra .= ".dzqcod-field input,.dzqcod-field select,.dzqcod-field textarea{background:{$fbd}!important;border:2px solid transparent!important}";
            $extra .= ".dzqcod-field input:focus,.dzqcod-field select:focus{background:{$fbg}!important;border-color:{$pc}!important}";
        }
        // Total style — BIG
        if ($ts === 'gradient') {
            $extra .= ".dzqcod-breakdown{background:linear-gradient(135deg,{$pc},{$sc})!important;color:#fff!important;border:none!important}";
            $extra .= ".dzqcod-breakdown .bk-r span,.dzqcod-breakdown .bk-r strong{color:#fff!important}";
            $extra .= ".dzqcod-breakdown .bk-total{border-top:2px solid rgba(255,255,255,.3)!important}";
        } elseif ($ts === 'simple') {
            $extra .= ".dzqcod-breakdown{background:transparent!important;border:none!important;border-top:2px solid {$fbd}!important;border-radius:0!important}";
        } else {
            $extra .= ".dzqcod-breakdown{background:{$gbg}!important;border:2px solid {$fbd}!important}";
        }
        $extra .= ".dzqcod-breakdown .bk-total{font-size:22px!important;padding-top:10px!important;margin-top:8px!important}";
        $extra .= ".dzqcod-breakdown .bk-tot{font-size:22px!important;font-weight:900!important}";
        // Sticky order bar
        if (self::opt('sticky_order_bar','no') === 'yes') {
            $extra .= ".dzqcod-sticky-bar{position:fixed;bottom:0;left:0;right:0;z-index:9999;background:{$bg};border-top:2px solid {$fbd};padding:10px 16px;display:flex;align-items:center;justify-content:space-between;box-shadow:0 -4px 20px rgba(0,0,0,.1)}";
            $extra .= ".dzqcod-sticky-bar .dzqcod-sticky-total{font-size:20px;font-weight:900;color:{$pc}}";
            $extra .= ".dzqcod-sticky-bar .dzqcod-sticky-btn{padding:12px 24px;background:linear-gradient(135deg,{$gc},{$pc});color:{$bt};border:none;border-radius:{$r}px;font-size:14px;font-weight:800;cursor:pointer}";
        }
        if ($extra) echo "<style id=dzqcod-design>{$extra}</style>\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- inline script/style with escaped vars
        $cc=self::opt('form_custom_css','');if($cc)echo "<style id=dzqcod-custom>{$cc}</style>\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- inline script/style with escaped vars
    }
    public function admin_menus():void{
        add_menu_page('DZQCOD','DZQCOD','manage_woocommerce','dzqcod',[$this,'pg_dashboard'],'dashicons-store',56);
        // Setup Wizard (hidden from menu)
        add_submenu_page(null,'إعداد DZQCOD','إعداد','manage_options','dzqcod-setup',[$this,'pg_wizard']);
        // Register pages
        foreach([['dzqcod-orders','الطلبات','pg_orders'],['dzqcod-call-center','مركز الاتصال','pg_cc'],['dzqcod-products','المنتجات','pg_products'],['dzqcod-pos','نقطة البيع','pg_pos'],['dzqcod-workshop','الورشة','pg_workshop'],['dzqcod-shipping','الشحن','pg_ship'],['dzqcod-printing','الطباعة','pg_print'],['dzqcod-campaigns','الحملات','pg_campaigns'],['dzqcod-offers','العروض','pg_offers'],['dzqcod-fraud','مكافحة الاحتيال','pg_fraud'],['dzqcod-sales-boost','زيادة المبيعات','pg_sales'],['dzqcod-smart-ops','الأتمتة الذكية','pg_smart'],['dzqcod-post-order','صفحات التأكيد','pg_postorder'],['dzqcod-profit','حاسبة الأرباح','pg_profit'],['dzqcod-integrations','التكامل','pg_integrations'],['dzqcod-addons','متجر الإضافات','pg_addons'],['dzqcod-whatsapp','واتساب','pg_whatsapp'],['dzqcod-payment','وسائل الدفع','pg_payment'],['dzqcod-rbac','الصلاحيات','pg_rbac'],['dzqcod-form-design','تصميم النموذج','pg_design'],['dzqcod-license','الترخيص','pg_license'],['dzqcod-settings','الإعدادات','pg_settings'],['dzqcod-support','الدعم الفني','pg_support'],['dzqcod-page-generator','مولّد الصفحات','pg_pagegen']] as[$s,$t,$c])
            add_submenu_page('dzqcod',$t,$t,'manage_woocommerce',$s,[$this,$c]);
        // Remove auto-created "DZQCOD" duplicate submenu
        remove_submenu_page('dzqcod','dzqcod');

        // Register active addon pages dynamically
        $inst = \DZQCOD\Modules::installed_addons();
        $all_addons = \DZQCOD\Modules::get_addons();
        foreach($all_addons as $a){
            $slug = $a['slug'] ?? '';
            if(!$slug || empty($inst[$slug])) continue;
            if(has_action('dzqcod_admin_page_'.$slug)){
                add_submenu_page('dzqcod', $a['name']??$slug, $a['name']??$slug, 'manage_woocommerce', 'dzqcod-addon-'.$slug, function() use($slug){
                    include \DZQCOD_PATH.'templates/nav.php';
                    do_action('dzqcod_admin_page_'.$slug);
                    echo '</div></div>'; // close dza-main + dza-layout from nav.php
                });
            }
        }
    }
    public function enqueue_admin(string $h):void{
        $s=get_current_screen();
        if(!$s||strpos($s->id,'dzqcod')===false)return;
        // Fonts — preconnect for speed
        echo '<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>';
        wp_enqueue_style('dza-fonts','https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800;900&display=swap',[],null);
        // Admin CSS
        wp_enqueue_style('dza',\DZQCOD_URL.'assets/css/admin.css',[],\DZQCOD_VER);
        // Admin JS — in footer for performance
        wp_enqueue_script('dza',\DZQCOD_URL.'assets/js/admin.js',['jquery'],\DZQCOD_VER,true);
        wp_localize_script('dza','dza',[
            'ajax'=>admin_url('admin-ajax.php'),
            'nonce'=>wp_create_nonce('dzqcod_admin'),
            'is_pro'=>self::is_pro(),
            'is_ent'=>self::is_ent(),
            'currency'=>self::opt('currency_symbol','دج'),
            'currency_code'=>self::opt('currency_code','DZD'),
            'page'=>sanitize_key($_GET['page']??''),
        ]);
        // Print CSS — only on printing page
        if(strpos($s->id,'printing')!==false){
            wp_enqueue_style('dza-print',\DZQCOD_URL.'assets/css/print.css',[],\DZQCOD_VER,'print');
        }
        // Media library for product image picker
        if(strpos($s->id,'dzqcod-products')!==false) wp_enqueue_media();
    }

    // Page renderers
    public function pg_dashboard():void{include \DZQCOD_PATH.'templates/dashboard.php';}
    public function pg_orders():void{
        if(!empty($_GET['id']) && absint($_GET['id'])){include \DZQCOD_PATH.'templates/order-detail.php';return;}
        include \DZQCOD_PATH.'templates/orders.php';
    }
    public function pg_products():void{include \DZQCOD_PATH.'templates/products.php';}
    public function pg_pos():void{include \DZQCOD_PATH.'templates/pos.php';}
    public function pg_workshop():void{include \DZQCOD_PATH.'templates/workshop.php';}

    public function dzqcod_add_order_note():void{
        check_ajax_referer('dzqcod_admin','nonce');
        $oid=absint($_POST['order_id']??0); $note=sanitize_textarea_field($_POST['note']??'');
        $o=wc_get_order($oid); if(!$o||!$note)wp_send_json_error();
        $o->add_order_note($note,0,true);
        wp_send_json_success();
    }
    public function pg_cc():void{include \DZQCOD_PATH.'templates/call-center.php';}
    public function pg_ship():void{include \DZQCOD_PATH.'templates/shipping.php';}
    public function pg_print():void{include \DZQCOD_PATH.'templates/printing.php';}
    public function pg_campaigns():void{include \DZQCOD_PATH.'templates/campaigns.php';}
    public function pg_offers():void{include \DZQCOD_PATH.'templates/offers.php';}
    public function pg_fraud():void{include \DZQCOD_PATH.'templates/fraud.php';}
    public function pg_design():void{include \DZQCOD_PATH.'templates/form-design.php';}
    public function pg_addons():void{include \DZQCOD_PATH.'templates/addons.php';}
    public function pg_whatsapp():void{include \DZQCOD_PATH.'templates/whatsapp.php';}
    public function pg_rbac():void{include \DZQCOD_PATH.'templates/rbac.php';}
    public function pg_payment():void{include \DZQCOD_PATH.'templates/payment.php';}
    public function pg_sales():void{include \DZQCOD_PATH.'templates/sales-boost.php';}
    public function pg_smart():void{include \DZQCOD_PATH.'templates/smart-ops.php';}
    public function pg_profit():void{include \DZQCOD_PATH.'templates/profit.php';}
    public function pg_postorder():void{include \DZQCOD_PATH.'templates/post-order.php';}
    public function pg_integrations():void{include \DZQCOD_PATH.'templates/integrations.php';}
    public function pg_license():void{include \DZQCOD_PATH.'templates/license.php';}
    public function pg_settings():void{include \DZQCOD_PATH.'templates/settings.php';}
    public function pg_support():void{include \DZQCOD_PATH.'templates/support.php';}
    public function pg_pagegen():void{include \DZQCOD_PATH.'templates/page-generator.php';}
    public function pg_wizard():void{include \DZQCOD_PATH.'templates/setup-wizard.php';}

    // v4.1: Toggle Simple/Advanced mode
    public function dzqcod_toggle_mode(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if (!current_user_can('manage_woocommerce')) wp_send_json_error();
        $current = self::opt('ui_mode','simple');
        update_option('dzqcod_ui_mode', $current === 'simple' ? 'advanced' : 'simple');
        wp_send_json_success(['mode' => $current === 'simple' ? 'advanced' : 'simple']);
    }

    // Redirect to wizard on first install
    public static function maybe_redirect_wizard():void{
        if(get_option('dzqcod_wizard_completed'))return;
        if(get_transient('dzqcod_activating'))return;
        if(!current_user_can('manage_options'))return;
        if(wp_doing_ajax()||wp_doing_cron())return;
        $page=sanitize_key($_GET['page']??'');
        if($page==='dzqcod-setup')return;
        if(strpos($page,'dzqcod')===0){
            set_transient('dzqcod_activating',1,60);
            wp_safe_redirect(admin_url('admin.php?page=dzqcod-setup'));
            exit;
        }
    }

    // HELPERS
    public function get_wilayas():array{
        global $wpdb;$cc=self::opt('country','DZ');
        $rows=$wpdb->get_results($wpdb->prepare("SELECT * FROM ".self::db()."wilayas WHERE is_active=1 AND (country=%s OR country IS NULL OR country='') ORDER BY id",$cc));
        // If no custom wilayas, try WooCommerce states for this country
        if(empty($rows)&&class_exists('WC_Countries')){
            $wc=new \WC_Countries();$states=$wc->get_states($cc);
            if(!empty($states)){$rows=[];foreach($states as $code=>$name){$o=new \stdClass();$o->code=$code;$o->name_ar=$name;$o->name_fr=$name;$o->shipping_desk=0;$o->shipping_home=0;$o->is_active=1;$o->country=$cc;$rows[]=$o;}}
        }
        return $rows;
    }
    /** Get the term used for "state/wilaya" based on country */
    public static function state_label():string{
        $map=['DZ'=>'الولاية','TN'=>'الولاية','MA'=>'الجهة','LY'=>'المنطقة','EG'=>'المحافظة','SA'=>'المنطقة','AE'=>'الإمارة','IQ'=>'المحافظة','JO'=>'المحافظة','SD'=>'الولاية','MR'=>'الولاية'];
        return $map[self::opt('country','DZ')]??'الولاية';
    }
    public static function commune_label():string{
        $map=['DZ'=>'البلدية','TN'=>'المعتمدية','MA'=>'الإقليم','LY'=>'البلدية','EG'=>'المركز','SA'=>'المدينة','AE'=>'المدينة','IQ'=>'القضاء','JO'=>'اللواء','SD'=>'المحلية','MR'=>'المقاطعة'];
        return $map[self::opt('country','DZ')]??'البلدية';
    }
    public function get_call_queue(int $limit=30):array{
        $orders=wc_get_orders(['status'=>['wc-pending-call','wc-callback','wc-no-answer'],'limit'=>$limit,'orderby'=>'date','order'=>'ASC']);
        $q=[];foreach($orders as $o){$items=[];foreach($o->get_items() as $i){$n=$i->get_name();$im=$i->get_meta('اللون');$is=$i->get_meta('المقاس');if($im)$n.=' ['.$im.']';if($is)$n.=' ('.$is.')';$items[]=$n.'×'.$i->get_quantity();}
        $q[]=['id'=>$o->get_id(),'name'=>$o->get_billing_first_name(),'phone'=>$o->get_billing_phone(),'phone2'=>$o->get_meta('_dzqcod_phone2'),'wilaya'=>$o->get_shipping_state(),'commune'=>$o->get_shipping_city(),'total'=>$o->get_total(),'status'=>str_replace('wc-','',$o->get_status()),'items'=>implode(', ',$items),'attempts'=>(int)$o->get_meta('_dzqcod_call_attempts'),'notes'=>$o->get_customer_note(),'date'=>$o->get_date_created()?$o->get_date_created()->format('m/d H:i'):'-','fraud'=>(int)$o->get_meta('_dzqcod_fraud_score'),'color'=>$o->get_meta('_dzqcod_color'),'size'=>$o->get_meta('_dzqcod_size'),'payment'=>$o->get_payment_method_title()?:'COD','digital'=>$o->get_meta('_dzqcod_digital')==='yes'];}
        return $q;
    }
}
