<?php
/**
 * Addon Name: Ads Manager
 * Description: نظام إدارة إعلانات المتجر — بانرات ذكية، Pop-ups، شريط عروض، مناطق إعلانية مخصصة مع جدولة واستهداف وتحليلات
 * Version: 1.0.0
 * Author: NIBRA Technology
 * Type: enterprise
 * Category: marketing
 */

namespace DZQCOD\Addons;

if (!defined('ABSPATH')) exit;
if (!\DZQCOD\Modules::is_on('ads-manager')) return;

class AdsManager {

    const DB_ADS     = 'dz_ads';
    const DB_STATS   = 'dz_ads_stats';
    const DB_ZONES   = 'dz_ads_zones';

    // ═══════════════════════════════════════════
    //  AD TYPES
    // ═══════════════════════════════════════════
    const TYPES = [
        'banner'       => ['l' => '🖼️ بانر', 'desc' => 'صورة أو HTML في أي منطقة'],
        'popup'        => ['l' => '💬 نافذة منبثقة', 'desc' => 'Pop-up مع تخصيص الوقت والمحتوى'],
        'topbar'       => ['l' => '📢 شريط علوي', 'desc' => 'شريط إعلان ثابت أعلى الموقع'],
        'slide_in'     => ['l' => '↗️ Slide-In', 'desc' => 'رسالة تنزلق من الزاوية'],
        'inline'       => ['l' => '📝 مضمّن', 'desc' => 'إعلان داخل المحتوى أو بين المنتجات'],
        'exit_intent'  => ['l' => '🚪 Exit Intent', 'desc' => 'يظهر عند محاولة مغادرة الموقع'],
        'floating'     => ['l' => '🎈 عائم', 'desc' => 'زر أو بانر عائم على الشاشة'],
        'countdown'    => ['l' => '⏰ عد تنازلي', 'desc' => 'عرض مع مؤقت لإنشاء إلحاح'],
        'product_rec'  => ['l' => '🛍️ توصيات', 'desc' => 'منتجات مقترحة ديناميكية'],
        'video'        => ['l' => '🎬 فيديو', 'desc' => 'إعلان فيديو قصير (YouTube/محلي)'],
    ];

    // ═══════════════════════════════════════════
    //  PLACEMENT ZONES
    // ═══════════════════════════════════════════
    const ZONES = [
        'header_above'    => 'فوق الهيدر',
        'header_below'    => 'تحت الهيدر',
        'sidebar_top'     => 'أعلى السايدبار',
        'sidebar_bottom'  => 'أسفل السايدبار',
        'content_top'     => 'بداية المحتوى',
        'content_middle'  => 'وسط المحتوى',
        'content_bottom'  => 'نهاية المحتوى',
        'product_before'  => 'قبل المنتج',
        'product_after'   => 'بعد المنتج',
        'cart_top'        => 'أعلى السلة',
        'cart_bottom'     => 'أسفل السلة',
        'checkout_top'    => 'أعلى الدفع',
        'footer_above'    => 'فوق الفوتر',
        'between_products'=> 'بين المنتجات',
        'order_form'      => 'داخل نموذج DZQCOD',
        'thankyou_page'   => 'صفحة شكراً',
        'custom'          => 'منطقة مخصصة (Shortcode)',
    ];

    // ═══════════════════════════════════════════
    //  TARGETING RULES
    // ═══════════════════════════════════════════
    const TARGETS = [
        'all'            => 'الجميع',
        'new_visitor'    => 'زائر جديد',
        'returning'      => 'زائر عائد',
        'cart_value_gt'  => 'قيمة السلة أكبر من',
        'cart_value_lt'  => 'قيمة السلة أصغر من',
        'product_cat'    => 'فئة منتج محددة',
        'specific_product'=> 'منتج محدد',
        'wilaya'         => 'ولاية محددة',
        'device_mobile'  => 'موبايل فقط',
        'device_desktop' => 'كمبيوتر فقط',
        'utm_source'     => 'مصدر UTM محدد',
        'time_range'     => 'نطاق زمني',
        'page_url'       => 'رابط صفحة محدد',
        'scroll_depth'   => 'عمق التمرير %',
        'visit_count'    => 'عدد الزيارات',
    ];

    // ═══════════════════════════════════════════
    //  INIT
    // ═══════════════════════════════════════════
    public static function init(): void {
        // Admin
        add_action('wp_ajax_dzqcod_ads_save',     [self::class, 'ajax_save']);
        add_action('wp_ajax_dzqcod_ads_delete',    [self::class, 'ajax_delete']);
        add_action('wp_ajax_dzqcod_ads_toggle',    [self::class, 'ajax_toggle']);
        add_action('wp_ajax_dzqcod_ads_duplicate', [self::class, 'ajax_duplicate']);
        add_action('wp_ajax_dzqcod_ads_stats',     [self::class, 'ajax_stats']);
        add_action('wp_ajax_dzqcod_ads_ab_winner', [self::class, 'ajax_ab_winner']);
        add_action('wp_ajax_dzqcod_ads_bulk',      [self::class, 'ajax_bulk']);
        add_action('wp_ajax_dzqcod_ads_zone_save', [self::class, 'ajax_zone_save']);

        // Frontend rendering
        add_action('wp_head',      [self::class, 'render_topbar'], 1);
        add_action('wp_footer',    [self::class, 'render_popups']);
        add_action('wp_footer',    [self::class, 'render_floating']);
        add_action('wp_footer',    [self::class, 'render_slide_in']);
        add_action('wp_footer',    [self::class, 'render_exit_intent']);
        add_action('wp_footer',    [self::class, 'inject_frontend_js']);

        // Zone hooks
        add_action('woocommerce_before_single_product',    function() { self::render_zone('product_before'); });
        add_action('woocommerce_after_single_product',     function() { self::render_zone('product_after'); });
        add_action('woocommerce_before_cart',              function() { self::render_zone('cart_top'); });
        add_action('woocommerce_after_cart',               function() { self::render_zone('cart_bottom'); });
        add_action('woocommerce_before_checkout_form',     function() { self::render_zone('checkout_top'); });
        add_action('dzqcod_thankyou_after',                function() { self::render_zone('thankyou_page'); });
        add_action('dzqcod_form_before',                   function() { self::render_zone('order_form'); });
        add_action('loop_start',                           function() { self::render_zone('content_top'); });

        // Between products
        add_filter('woocommerce_product_loop_start', [self::class, 'inject_between_products']);

        // Track impressions/clicks
        add_action('wp_ajax_dzqcod_ad_track',        [self::class, 'ajax_track']);
        add_action('wp_ajax_nopriv_dzqcod_ad_track', [self::class, 'ajax_track']);

        // Shortcode
        add_shortcode('dzqcod_ad', [self::class, 'shortcode_ad']);
        add_shortcode('dzqcod_ad_zone', [self::class, 'shortcode_zone']);

        // Admin page
        add_action('dzqcod_admin_page_ads-manager', [self::class, 'admin_page']);

        // Install tables
        add_action('admin_init', [self::class, 'install'], 5);
    }

    // ═══════════════════════════════════════════
    //  DATABASE INSTALL
    // ═══════════════════════════════════════════
    public static function install(): void {
        if (get_option('dzqcod_ads_db_ver', '0') === '1.0.0') return;
        global $wpdb; $cs = $wpdb->get_charset_collate(); $p = $wpdb->prefix;

        $wpdb->query("CREATE TABLE IF NOT EXISTS {$p}" . self::DB_ADS . " (
            id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            title VARCHAR(255) NOT NULL DEFAULT '',
            ad_type VARCHAR(30) NOT NULL DEFAULT 'banner',
            zone VARCHAR(50) NOT NULL DEFAULT 'custom',
            content_html LONGTEXT,
            content_image VARCHAR(500) DEFAULT '',
            content_video VARCHAR(500) DEFAULT '',
            link_url VARCHAR(500) DEFAULT '',
            link_target VARCHAR(10) DEFAULT '_blank',
            cta_text VARCHAR(100) DEFAULT '',
            cta_color VARCHAR(10) DEFAULT '6366F1',
            bg_color VARCHAR(10) DEFAULT 'FFFFFF',
            text_color VARCHAR(10) DEFAULT '1F2937',
            custom_css TEXT,
            custom_js TEXT,
            width VARCHAR(20) DEFAULT '100%',
            height VARCHAR(20) DEFAULT 'auto',
            position VARCHAR(20) DEFAULT 'center',
            animation VARCHAR(30) DEFAULT 'fadeIn',
            delay_seconds INT DEFAULT 0,
            display_duration INT DEFAULT 0,
            scroll_trigger INT DEFAULT 0,
            close_button TINYINT(1) DEFAULT 1,
            cookie_days INT DEFAULT 1,
            is_active TINYINT(1) DEFAULT 1,
            priority INT DEFAULT 10,
            ab_variant VARCHAR(5) DEFAULT '',
            ab_parent_id BIGINT UNSIGNED DEFAULT 0,
            schedule_start DATETIME DEFAULT NULL,
            schedule_end DATETIME DEFAULT NULL,
            target_rules JSON,
            impressions BIGINT UNSIGNED DEFAULT 0,
            clicks BIGINT UNSIGNED DEFAULT 0,
            conversions BIGINT UNSIGNED DEFAULT 0,
            revenue DECIMAL(12,2) DEFAULT 0.00,
            max_impressions BIGINT UNSIGNED DEFAULT 0,
            max_clicks BIGINT UNSIGNED DEFAULT 0,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_type_zone (ad_type, zone),
            INDEX idx_active (is_active, schedule_start, schedule_end),
            INDEX idx_ab (ab_parent_id)
        ) $cs");

        $wpdb->query("CREATE TABLE IF NOT EXISTS {$p}" . self::DB_STATS . " (
            id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            ad_id BIGINT UNSIGNED NOT NULL,
            event_type ENUM('impression','click','conversion','close','cta_click') DEFAULT 'impression',
            revenue DECIMAL(12,2) DEFAULT 0.00,
            visitor_id VARCHAR(40) DEFAULT '',
            page_url VARCHAR(500) DEFAULT '',
            device VARCHAR(20) DEFAULT '',
            wilaya VARCHAR(50) DEFAULT '',
            utm_source VARCHAR(100) DEFAULT '',
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_ad_event (ad_id, event_type),
            INDEX idx_date (created_at)
        ) $cs");

        $wpdb->query("CREATE TABLE IF NOT EXISTS {$p}" . self::DB_ZONES . " (
            id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            slug VARCHAR(50) NOT NULL UNIQUE,
            name VARCHAR(100) NOT NULL,
            description VARCHAR(255) DEFAULT '',
            hook_name VARCHAR(100) DEFAULT '',
            max_ads INT DEFAULT 3,
            layout VARCHAR(30) DEFAULT 'stack',
            is_active TINYINT(1) DEFAULT 1,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        ) $cs");

        update_option('dzqcod_ads_db_ver', '1.0.0');
    }

    // ═══════════════════════════════════════════
    //  HELPER — Get Active Ads
    // ═══════════════════════════════════════════
    private static function get_active_ads(string $type = '', string $zone = ''): array {
        global $wpdb; $p = $wpdb->prefix . self::DB_ADS;
        $now = current_time('mysql');

        $sql = "SELECT * FROM {$p} WHERE is_active = 1";
        $sql .= " AND (schedule_start IS NULL OR schedule_start <= '{$now}')";
        $sql .= " AND (schedule_end IS NULL OR schedule_end >= '{$now}')";
        $sql .= " AND (max_impressions = 0 OR impressions < max_impressions)";
        $sql .= " AND (max_clicks = 0 OR clicks < max_clicks)";

        if ($type) $sql .= $wpdb->prepare(" AND ad_type = %s", $type);
        if ($zone) $sql .= $wpdb->prepare(" AND zone = %s", $zone);

        $sql .= " ORDER BY priority ASC, id DESC";

        $ads = $wpdb->get_results($sql, ARRAY_A);

        // Filter by targeting rules
        return array_filter($ads, function($ad) {
            return self::passes_targeting($ad);
        });
    }

    // ═══════════════════════════════════════════
    //  TARGETING ENGINE
    // ═══════════════════════════════════════════
    private static function passes_targeting(array $ad): bool {
        $rules = json_decode($ad['target_rules'] ?? '[]', true);
        if (empty($rules)) return true;

        foreach ($rules as $rule) {
            $type  = $rule['type'] ?? 'all';
            $value = $rule['value'] ?? '';

            switch ($type) {
                case 'all': break;

                case 'new_visitor':
                    if (isset($_COOKIE['dzqcod_visits']) && (int)$_COOKIE['dzqcod_visits'] > 1) return false;
                    break;

                case 'returning':
                    if (!isset($_COOKIE['dzqcod_visits']) || (int)$_COOKIE['dzqcod_visits'] <= 1) return false;
                    break;

                case 'device_mobile':
                    if (!wp_is_mobile()) return false;
                    break;

                case 'device_desktop':
                    if (wp_is_mobile()) return false;
                    break;

                case 'product_cat':
                    if (is_product()) {
                        global $product;
                        if ($product && !has_term($value, 'product_cat', $product->get_id())) return false;
                    }
                    break;

                case 'specific_product':
                    if (is_product()) {
                        global $product;
                        if ($product && (int)$product->get_id() !== (int)$value) return false;
                    }
                    break;

                case 'wilaya':
                    $visitor_wilaya = $_COOKIE['dzqcod_wilaya'] ?? '';
                    if ($visitor_wilaya && $visitor_wilaya !== $value) return false;
                    break;

                case 'utm_source':
                    $utm = sanitize_text_field($_GET['utm_source'] ?? ($_COOKIE['dzqcod_utm_source'] ?? ''));
                    if (!$utm || stripos($utm, $value) === false) return false;
                    break;

                case 'page_url':
                    $url = $_SERVER['REQUEST_URI'] ?? '';
                    if (stripos($url, $value) === false) return false;
                    break;

                case 'time_range':
                    $parts = explode('-', $value);
                    if (count($parts) === 2) {
                        $h = (int)date('H');
                        if ($h < (int)$parts[0] || $h > (int)$parts[1]) return false;
                    }
                    break;
            }
        }
        return true;
    }

    // ═══════════════════════════════════════════
    //  RENDER AD HTML
    // ═══════════════════════════════════════════
    private static function render_ad_html(array $ad, bool $wrap = true): string {
        $id   = (int)$ad['id'];
        $type = esc_attr($ad['ad_type']);
        $anim = esc_attr($ad['animation'] ?? 'fadeIn');
        $bg   = esc_attr($ad['bg_color'] ?? 'FFFFFF');
        $txt  = esc_attr($ad['text_color'] ?? '1F2937');
        $css  = $ad['custom_css'] ?? '';
        $w    = esc_attr($ad['width'] ?? '100%');
        $h    = esc_attr($ad['height'] ?? 'auto');
        $link = esc_url($ad['link_url'] ?? '');
        $cta  = esc_html($ad['cta_text'] ?? '');
        $ctaC = esc_attr($ad['cta_color'] ?? '6366F1');
        $close = (int)($ad['close_button'] ?? 1);
        $delay = (int)($ad['delay_seconds'] ?? 0);

        $html  = $ad['content_html'] ?? '';
        $image = esc_url($ad['content_image'] ?? '');
        $video = esc_url($ad['content_video'] ?? '');

        $content = '';

        // Build content based on type
        if ($image) {
            $imgTag = '<img src="'.$image.'" alt="'.esc_attr($ad['title']).'" style="width:100%;height:auto;display:block;border-radius:8px">';
            $content .= $link ? '<a href="'.$link.'" target="'.esc_attr($ad['link_target'] ?? '_blank').'" class="dzad-link" data-ad="'.$id.'">'.$imgTag.'</a>' : $imgTag;
        }
        if ($video) {
            if (strpos($video, 'youtube') !== false || strpos($video, 'youtu.be') !== false) {
                preg_match('/(?:v=|youtu\.be\/)([a-zA-Z0-9_-]{11})/', $video, $m);
                if (!empty($m[1])) $content .= '<div style="position:relative;padding-bottom:56.25%;height:0"><iframe src="https://www.youtube.com/embed/'.$m[1].'?autoplay=0" style="position:absolute;top:0;left:0;width:100%;height:100%;border:0;border-radius:8px" allowfullscreen></iframe></div>';
            } else {
                $content .= '<video src="'.$video.'" controls style="width:100%;border-radius:8px"></video>';
            }
        }
        if ($html) {
            $content .= $html;
        }
        if ($cta && $link) {
            $content .= '<div style="text-align:center;margin-top:12px"><a href="'.$link.'" target="'.esc_attr($ad['link_target'] ?? '_blank').'" class="dzad-cta" data-ad="'.$id.'" style="display:inline-block;padding:10px 28px;background:#'.$ctaC.';color:#fff;border-radius:8px;text-decoration:none;font-weight:700;font-family:Tajawal,sans-serif">'.$cta.'</a></div>';
        }

        if (!$wrap) return $content;

        $out = '<div class="dzad dzad-'.$type.'" data-ad-id="'.$id.'" data-type="'.$type.'"';
        $out .= ' data-delay="'.$delay.'" data-anim="'.$anim.'"';
        $out .= ' data-cookie="'.esc_attr($ad['cookie_days'] ?? 1).'"';
        $out .= ' style="background:#'.$bg.';color:#'.$txt.';width:'.$w.';max-width:100%;'.$css.'"';
        $out .= ' dir="rtl">';

        if ($close) {
            $out .= '<button class="dzad-close" onclick="dzadClose('.$id.')" style="position:absolute;top:8px;left:8px;background:rgba(0,0,0,0.4);color:#fff;border:none;border-radius:50%;width:28px;height:28px;cursor:pointer;font-size:14px;display:flex;align-items:center;justify-content:center;z-index:10">✕</button>';
        }

        $out .= $content;
        $out .= '</div>';

        return $out;
    }

    // ═══════════════════════════════════════════
    //  FRONTEND RENDERERS
    // ═══════════════════════════════════════════
    public static function render_topbar(): void {
        $ads = self::get_active_ads('topbar');
        if (empty($ads)) return;
        $ad = $ads[0]; // One topbar at a time
        $id = (int)$ad['id'];
        if (isset($_COOKIE['dzad_closed_'.$id])) return;

        echo '<div id="dzad-topbar-'.$id.'" class="dzad-topbar" data-ad-id="'.$id.'" style="position:relative;background:#'.esc_attr($ad['bg_color']).';color:#'.esc_attr($ad['text_color']).';text-align:center;padding:10px 40px;font-family:Tajawal,sans-serif;font-size:14px;font-weight:600;z-index:9999;direction:rtl">';
        echo '<span>'.wp_kses_post($ad['content_html'] ?? $ad['title']).'</span>';
        if ($ad['link_url']) echo ' <a href="'.esc_url($ad['link_url']).'" style="color:inherit;text-decoration:underline;margin-right:8px" data-ad="'.$id.'" class="dzad-link">'.esc_html($ad['cta_text'] ?: 'اعرف المزيد').'</a>';
        if ($ad['close_button']) echo '<button onclick="dzadClose('.$id.')" style="position:absolute;top:50%;left:12px;transform:translateY(-50%);background:none;border:none;color:inherit;cursor:pointer;font-size:16px;opacity:0.7">✕</button>';
        echo '</div>';
    }

    public static function render_popups(): void {
        $ads = self::get_active_ads('popup');
        foreach ($ads as $ad) {
            $id = (int)$ad['id'];
            if (isset($_COOKIE['dzad_closed_'.$id])) continue;
            echo '<div id="dzad-popup-'.$id.'" class="dzad-popup-overlay" data-ad-id="'.$id.'" data-delay="'.esc_attr($ad['delay_seconds']).'" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.6);z-index:99999;align-items:center;justify-content:center;direction:rtl">';
            echo '<div class="dzad-popup-box" style="position:relative;background:#'.esc_attr($ad['bg_color']).';color:#'.esc_attr($ad['text_color']).';border-radius:16px;padding:32px;max-width:'.esc_attr($ad['width'] ?: '520px').';width:90%;max-height:90vh;overflow-y:auto;box-shadow:0 20px 60px rgba(0,0,0,0.3);animation:dzadSlideUp 0.4s ease">';
            echo self::render_ad_html($ad, false);
            echo '<button onclick="dzadClose('.$id.')" style="position:absolute;top:12px;left:12px;background:rgba(0,0,0,0.1);border:none;border-radius:50%;width:32px;height:32px;cursor:pointer;font-size:16px;display:flex;align-items:center;justify-content:center">✕</button>';
            echo '</div></div>';
        }
    }

    public static function render_floating(): void {
        $ads = self::get_active_ads('floating');
        foreach ($ads as $ad) {
            $id = (int)$ad['id'];
            if (isset($_COOKIE['dzad_closed_'.$id])) continue;
            $pos = $ad['position'] ?? 'bottom-right';
            $posStyle = strpos($pos, 'left') !== false ? 'left:20px' : 'right:20px';
            $posStyle .= ';' . (strpos($pos, 'top') !== false ? 'top:20px' : 'bottom:20px');
            echo '<div id="dzad-float-'.$id.'" class="dzad-floating" data-ad-id="'.$id.'" style="position:fixed;'.$posStyle.';z-index:9998;max-width:320px;direction:rtl;animation:dzadBounceIn 0.5s ease">';
            echo '<div style="position:relative;background:#'.esc_attr($ad['bg_color']).';color:#'.esc_attr($ad['text_color']).';border-radius:12px;padding:16px;box-shadow:0 8px 30px rgba(0,0,0,0.2)">';
            echo self::render_ad_html($ad, false);
            if ($ad['close_button']) echo '<button onclick="dzadClose('.$id.')" style="position:absolute;top:-8px;left:-8px;background:#ef4444;color:#fff;border:none;border-radius:50%;width:24px;height:24px;cursor:pointer;font-size:12px">✕</button>';
            echo '</div></div>';
        }
    }

    public static function render_slide_in(): void {
        $ads = self::get_active_ads('slide_in');
        foreach ($ads as $ad) {
            $id = (int)$ad['id'];
            if (isset($_COOKIE['dzad_closed_'.$id])) continue;
            echo '<div id="dzad-slidein-'.$id.'" class="dzad-slidein" data-ad-id="'.$id.'" data-delay="'.esc_attr($ad['delay_seconds']).'" data-scroll="'.esc_attr($ad['scroll_trigger']).'" style="display:none;position:fixed;bottom:20px;right:20px;z-index:9997;max-width:360px;direction:rtl">';
            echo '<div style="position:relative;background:#'.esc_attr($ad['bg_color']).';color:#'.esc_attr($ad['text_color']).';border-radius:12px;padding:20px;box-shadow:0 12px 40px rgba(0,0,0,0.25);animation:dzadSlideRight 0.4s ease">';
            echo self::render_ad_html($ad, false);
            echo '<button onclick="dzadClose('.$id.')" style="position:absolute;top:8px;left:8px;background:rgba(0,0,0,0.1);border:none;border-radius:50%;width:28px;height:28px;cursor:pointer;font-size:14px">✕</button>';
            echo '</div></div>';
        }
    }

    public static function render_exit_intent(): void {
        $ads = self::get_active_ads('exit_intent');
        foreach ($ads as $ad) {
            $id = (int)$ad['id'];
            if (isset($_COOKIE['dzad_closed_'.$id])) continue;
            echo '<div id="dzad-exit-'.$id.'" class="dzad-exit-overlay" data-ad-id="'.$id.'" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.7);z-index:99999;align-items:center;justify-content:center;direction:rtl">';
            echo '<div style="position:relative;background:#'.esc_attr($ad['bg_color']).';color:#'.esc_attr($ad['text_color']).';border-radius:16px;padding:32px;max-width:500px;width:90%;box-shadow:0 20px 60px rgba(0,0,0,0.4);animation:dzadShake 0.5s ease">';
            echo '<div style="text-align:center;margin-bottom:16px;font-size:32px">🛑</div>';
            echo self::render_ad_html($ad, false);
            echo '<button onclick="dzadClose('.$id.')" style="position:absolute;top:12px;left:12px;background:rgba(0,0,0,0.1);border:none;border-radius:50%;width:32px;height:32px;cursor:pointer;font-size:16px">✕</button>';
            echo '</div></div>';
        }
    }

    public static function render_zone(string $zone): void {
        $ads = self::get_active_ads('', $zone);
        if (empty($ads)) return;
        echo '<div class="dzad-zone dzad-zone-'.esc_attr($zone).'" style="direction:rtl;margin:12px 0">';
        foreach ($ads as $ad) {
            echo self::render_ad_html($ad);
        }
        echo '</div>';
    }

    // ═══════════════════════════════════════════
    //  FRONTEND JS + CSS
    // ═══════════════════════════════════════════
    public static function inject_frontend_js(): void {
        ?>
<style>
@keyframes dzadSlideUp{from{transform:translateY(40px);opacity:0}to{transform:translateY(0);opacity:1}}
@keyframes dzadSlideRight{from{transform:translateX(100px);opacity:0}to{transform:translateX(0);opacity:1}}
@keyframes dzadBounceIn{0%{transform:scale(0.3);opacity:0}50%{transform:scale(1.05)}70%{transform:scale(0.9)}100%{transform:scale(1);opacity:1}}
@keyframes dzadShake{0%,100%{transform:translateX(0)}10%,30%,50%,70%,90%{transform:translateX(-5px)}20%,40%,60%,80%{transform:translateX(5px)}}
@keyframes dzadFadeIn{from{opacity:0}to{opacity:1}}
.dzad{position:relative;border-radius:12px;overflow:hidden;animation:dzadFadeIn 0.5s ease}
.dzad img{transition:transform 0.3s}.dzad img:hover{transform:scale(1.02)}
.dzad-topbar a:hover{opacity:0.8}
</style>
<script>
(function(){
    var aj='<?php echo esc_js(admin_url('admin-ajax.php')); ?>';

    // Track impressions on visible ads
    document.querySelectorAll('[data-ad-id]').forEach(function(el){
        var id=el.dataset.adId;
        if(el.offsetParent!==null||el.style.display!=='none'){
            fetch(aj+'?action=dzqcod_ad_track&ad_id='+id+'&event=impression&_='+Date.now());
        }
    });

    // Track clicks
    document.addEventListener('click',function(e){
        var link=e.target.closest('.dzad-link,.dzad-cta');
        if(link){
            var id=link.dataset.ad;
            if(id)fetch(aj+'?action=dzqcod_ad_track&ad_id='+id+'&event=click&_='+Date.now());
        }
    });

    // Show delayed popups
    document.querySelectorAll('.dzad-popup-overlay').forEach(function(el){
        var d=parseInt(el.dataset.delay||'3')*1000;
        setTimeout(function(){el.style.display='flex';
            fetch(aj+'?action=dzqcod_ad_track&ad_id='+el.dataset.adId+'&event=impression&_='+Date.now());
        },d);
    });

    // Show slide-ins
    document.querySelectorAll('.dzad-slidein').forEach(function(el){
        var d=parseInt(el.dataset.delay||'5')*1000;
        var s=parseInt(el.dataset.scroll||'0');
        if(s>0){
            window.addEventListener('scroll',function check(){
                var pct=(window.scrollY/(document.body.scrollHeight-window.innerHeight))*100;
                if(pct>=s){el.style.display='block';
                    fetch(aj+'?action=dzqcod_ad_track&ad_id='+el.dataset.adId+'&event=impression&_='+Date.now());
                    window.removeEventListener('scroll',check);}
            });
        } else {
            setTimeout(function(){el.style.display='block';
                fetch(aj+'?action=dzqcod_ad_track&ad_id='+el.dataset.adId+'&event=impression&_='+Date.now());
            },d);
        }
    });

    // Exit intent
    var exitShown=false;
    document.addEventListener('mouseout',function(e){
        if(exitShown||e.clientY>10)return;exitShown=true;
        document.querySelectorAll('.dzad-exit-overlay').forEach(function(el){
            el.style.display='flex';
            fetch(aj+'?action=dzqcod_ad_track&ad_id='+el.dataset.adId+'&event=impression&_='+Date.now());
        });
    });

    // Close handler
    window.dzadClose=function(id){
        ['popup','topbar','float','slidein','exit'].forEach(function(t){
            var el=document.getElementById('dzad-'+t+'-'+id);
            if(el){el.style.display='none';el.remove();}
        });
        // Also close zone ads
        document.querySelectorAll('[data-ad-id="'+id+'"]').forEach(function(el){el.style.display='none'});
        document.cookie='dzad_closed_'+id+'=1;path=/;max-age='+(86400*(parseInt(document.querySelector('[data-ad-id="'+id+'"]')?.dataset?.cookie)||1));
        fetch(aj+'?action=dzqcod_ad_track&ad_id='+id+'&event=close&_='+Date.now());
    };

    // Visit counter
    var v=parseInt(document.cookie.replace(/(?:(?:^|.*;\s*)dzqcod_visits\s*=\s*([^;]*).*$)|^.*$/,"$1")||'0')+1;
    document.cookie='dzqcod_visits='+v+';path=/;max-age=31536000';
})();
</script>
        <?php
    }

    // ═══════════════════════════════════════════
    //  BETWEEN PRODUCTS INJECTION
    // ═══════════════════════════════════════════
    public static function inject_between_products(string $html): string {
        $ads = self::get_active_ads('inline', 'between_products');
        if (empty($ads)) return $html;
        // Store ads to inject after every N products
        $GLOBALS['dzad_inline_ads'] = $ads;
        $GLOBALS['dzad_inline_counter'] = 0;
        add_action('woocommerce_after_shop_loop_item', function() {
            $GLOBALS['dzad_inline_counter']++;
            if ($GLOBALS['dzad_inline_counter'] % 4 === 0 && !empty($GLOBALS['dzad_inline_ads'])) {
                $ad = $GLOBALS['dzad_inline_ads'][array_rand($GLOBALS['dzad_inline_ads'])];
                echo '</li><li class="product dzad-inline-product" style="list-style:none">';
                echo self::render_ad_html($ad); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                echo '</li><li class="product" style="display:none">';
            }
        });
        return $html;
    }

    // ═══════════════════════════════════════════
    //  SHORTCODES
    // ═══════════════════════════════════════════
    public static function shortcode_ad(array $atts = []): string {
        $a = shortcode_atts(['id' => 0], $atts);
        if (!$a['id']) return '';
        global $wpdb; $p = $wpdb->prefix . self::DB_ADS;
        $ad = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$p} WHERE id = %d AND is_active = 1", $a['id']), ARRAY_A);
        return $ad ? self::render_ad_html($ad) : '';
    }

    public static function shortcode_zone(array $atts = []): string {
        $a = shortcode_atts(['zone' => 'custom'], $atts);
        ob_start();
        self::render_zone($a['zone']);
        return ob_get_clean();
    }

    // ═══════════════════════════════════════════
    //  AJAX — TRACKING
    // ═══════════════════════════════════════════
    public static function ajax_track(): void {
        $ad_id = absint($_GET['ad_id'] ?? $_POST['ad_id'] ?? 0);
        $event = sanitize_text_field($_GET['event'] ?? $_POST['event'] ?? 'impression');
        if (!$ad_id || !in_array($event, ['impression', 'click', 'conversion', 'close', 'cta_click'])) {
            wp_send_json_success(); return;
        }

        global $wpdb; $p = $wpdb->prefix;

        // Update counter
        $col = $event === 'impression' ? 'impressions' : ($event === 'click' || $event === 'cta_click' ? 'clicks' : '');
        if ($col) $wpdb->query($wpdb->prepare("UPDATE {$p}" . self::DB_ADS . " SET {$col} = {$col} + 1 WHERE id = %d", $ad_id));

        // Log detail
        $wpdb->insert($p . self::DB_STATS, [
            'ad_id'      => $ad_id,
            'event_type' => $event,
            'visitor_id' => sanitize_text_field($_COOKIE['dzqcod_vid'] ?? substr(md5($_SERVER['REMOTE_ADDR'] . ($_SERVER['HTTP_USER_AGENT'] ?? '')), 0, 16)),
            'page_url'   => sanitize_text_field($_SERVER['HTTP_REFERER'] ?? ''),
            'device'     => wp_is_mobile() ? 'mobile' : 'desktop',
            'wilaya'     => sanitize_text_field($_COOKIE['dzqcod_wilaya'] ?? ''),
            'utm_source' => sanitize_text_field($_COOKIE['dzqcod_utm_source'] ?? ($_GET['utm_source'] ?? '')),
        ]);

        wp_send_json_success();
    }

    // ═══════════════════════════════════════════
    //  AJAX — CRUD
    // ═══════════════════════════════════════════
    public static function ajax_save(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        if (!current_user_can('manage_woocommerce')) wp_send_json_error(['message' => 'غير مصرح']);

        global $wpdb; $t = $wpdb->prefix . self::DB_ADS;
        $id = absint($_POST['ad_id'] ?? 0);

        $data = [
            'title'          => sanitize_text_field($_POST['title'] ?? ''),
            'ad_type'        => sanitize_text_field($_POST['ad_type'] ?? 'banner'),
            'zone'           => sanitize_text_field($_POST['zone'] ?? 'custom'),
            'content_html'   => wp_kses_post($_POST['content_html'] ?? ''),
            'content_image'  => esc_url_raw($_POST['content_image'] ?? ''),
            'content_video'  => esc_url_raw($_POST['content_video'] ?? ''),
            'link_url'       => esc_url_raw($_POST['link_url'] ?? ''),
            'link_target'    => sanitize_text_field($_POST['link_target'] ?? '_blank'),
            'cta_text'       => sanitize_text_field($_POST['cta_text'] ?? ''),
            'cta_color'      => sanitize_hex_color_no_hash($_POST['cta_color'] ?? '6366F1'),
            'bg_color'       => sanitize_hex_color_no_hash($_POST['bg_color'] ?? 'FFFFFF'),
            'text_color'     => sanitize_hex_color_no_hash($_POST['text_color'] ?? '1F2937'),
            'custom_css'     => sanitize_textarea_field($_POST['custom_css'] ?? ''),
            'width'          => sanitize_text_field($_POST['width'] ?? '100%'),
            'height'         => sanitize_text_field($_POST['height'] ?? 'auto'),
            'position'       => sanitize_text_field($_POST['position'] ?? 'center'),
            'animation'      => sanitize_text_field($_POST['animation'] ?? 'fadeIn'),
            'delay_seconds'  => absint($_POST['delay_seconds'] ?? 0),
            'display_duration'=> absint($_POST['display_duration'] ?? 0),
            'scroll_trigger' => absint($_POST['scroll_trigger'] ?? 0),
            'close_button'   => (int)(!empty($_POST['close_button'])),
            'cookie_days'    => absint($_POST['cookie_days'] ?? 1),
            'priority'       => absint($_POST['priority'] ?? 10),
            'schedule_start' => sanitize_text_field($_POST['schedule_start'] ?? '') ?: null,
            'schedule_end'   => sanitize_text_field($_POST['schedule_end'] ?? '') ?: null,
            'max_impressions' => absint($_POST['max_impressions'] ?? 0),
            'max_clicks'     => absint($_POST['max_clicks'] ?? 0),
            'target_rules'   => wp_json_encode(json_decode(wp_unslash($_POST['target_rules'] ?? '[]'), true) ?: []),
        ];

        if ($id) {
            $wpdb->update($t, $data, ['id' => $id]);
        } else {
            $wpdb->insert($t, $data);
            $id = $wpdb->insert_id;
        }

        wp_send_json_success(['id' => $id, 'message' => 'تم الحفظ']);
    }

    public static function ajax_delete(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        global $wpdb; $p = $wpdb->prefix;
        $id = absint($_POST['ad_id'] ?? 0);
        $wpdb->delete($p . self::DB_ADS, ['id' => $id]);
        $wpdb->delete($p . self::DB_STATS, ['ad_id' => $id]);
        // Delete A/B variants too
        $wpdb->delete($p . self::DB_ADS, ['ab_parent_id' => $id]);
        wp_send_json_success(['message' => 'تم الحذف']);
    }

    public static function ajax_toggle(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        global $wpdb; $t = $wpdb->prefix . self::DB_ADS;
        $id = absint($_POST['ad_id'] ?? 0);
        $wpdb->query($wpdb->prepare("UPDATE {$t} SET is_active = NOT is_active WHERE id = %d", $id));
        wp_send_json_success();
    }

    public static function ajax_duplicate(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        global $wpdb; $t = $wpdb->prefix . self::DB_ADS;
        $id = absint($_POST['ad_id'] ?? 0);
        $ad = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$t} WHERE id = %d", $id), ARRAY_A);
        if (!$ad) wp_send_json_error();
        unset($ad['id']); $ad['title'] .= ' (نسخة)'; $ad['impressions'] = 0; $ad['clicks'] = 0; $ad['conversions'] = 0;
        $wpdb->insert($t, $ad);
        wp_send_json_success(['id' => $wpdb->insert_id]);
    }

    public static function ajax_bulk(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        global $wpdb; $t = $wpdb->prefix . self::DB_ADS;
        $ids = array_map('absint', $_POST['ids'] ?? []);
        $action = sanitize_text_field($_POST['bulk_action'] ?? '');
        if (!$ids || !$action) wp_send_json_error();
        $in = implode(',', $ids);
        switch ($action) {
            case 'activate':   $wpdb->query("UPDATE {$t} SET is_active = 1 WHERE id IN ({$in})"); break;
            case 'deactivate': $wpdb->query("UPDATE {$t} SET is_active = 0 WHERE id IN ({$in})"); break;
            case 'delete':     $wpdb->query("DELETE FROM {$t} WHERE id IN ({$in})"); break;
            case 'reset_stats':$wpdb->query("UPDATE {$t} SET impressions=0, clicks=0, conversions=0, revenue=0 WHERE id IN ({$in})"); break;
        }
        wp_send_json_success();
    }

    // A/B Testing winner
    public static function ajax_ab_winner(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        global $wpdb; $t = $wpdb->prefix . self::DB_ADS;
        $winner_id = absint($_POST['winner_id'] ?? 0);
        $parent_id = absint($_POST['parent_id'] ?? 0);
        // Deactivate all variants except winner
        $wpdb->query($wpdb->prepare("UPDATE {$t} SET is_active = 0 WHERE ab_parent_id = %d AND id != %d", $parent_id, $winner_id));
        $wpdb->update($t, ['ab_parent_id' => 0, 'ab_variant' => ''], ['id' => $winner_id]);
        wp_send_json_success(['message' => 'تم اختيار الفائز']);
    }

    public static function ajax_zone_save(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        global $wpdb; $t = $wpdb->prefix . self::DB_ZONES;
        $wpdb->replace($t, [
            'slug'        => sanitize_title($_POST['slug'] ?? ''),
            'name'        => sanitize_text_field($_POST['name'] ?? ''),
            'description' => sanitize_text_field($_POST['description'] ?? ''),
            'max_ads'     => absint($_POST['max_ads'] ?? 3),
            'layout'      => sanitize_text_field($_POST['layout'] ?? 'stack'),
            'is_active'   => 1,
        ]);
        wp_send_json_success();
    }

    // ═══════════════════════════════════════════
    //  AJAX — STATS
    // ═══════════════════════════════════════════
    public static function ajax_stats(): void {
        check_ajax_referer('dzqcod_admin', 'nonce');
        global $wpdb; $p = $wpdb->prefix;
        $ad_id = absint($_POST['ad_id'] ?? 0);
        $days = absint($_POST['days'] ?? 30);
        $since = gmdate('Y-m-d', strtotime("-{$days} days"));

        if ($ad_id) {
            $stats = $wpdb->get_results($wpdb->prepare(
                "SELECT DATE(created_at) as dt, event_type, COUNT(*) as cnt
                 FROM {$p}" . self::DB_STATS . "
                 WHERE ad_id = %d AND created_at >= %s
                 GROUP BY dt, event_type ORDER BY dt ASC", $ad_id, $since
            ), ARRAY_A);
        } else {
            $stats = $wpdb->get_results($wpdb->prepare(
                "SELECT DATE(created_at) as dt, event_type, COUNT(*) as cnt
                 FROM {$p}" . self::DB_STATS . "
                 WHERE created_at >= %s
                 GROUP BY dt, event_type ORDER BY dt ASC", $since
            ), ARRAY_A);
        }

        // Top ads
        $top = $wpdb->get_results(
            "SELECT a.id, a.title, a.ad_type, a.impressions, a.clicks, a.conversions,
                    CASE WHEN a.impressions > 0 THEN ROUND(a.clicks / a.impressions * 100, 2) ELSE 0 END as ctr
             FROM {$p}" . self::DB_ADS . " a ORDER BY a.clicks DESC LIMIT 10", ARRAY_A
        );

        // Device breakdown
        $devices = $wpdb->get_results($wpdb->prepare(
            "SELECT device, COUNT(*) as cnt FROM {$p}" . self::DB_STATS . " WHERE created_at >= %s GROUP BY device", $since
        ), ARRAY_A);

        wp_send_json_success(compact('stats', 'top', 'devices'));
    }

    // ═══════════════════════════════════════════
    //  ADMIN PAGE
    // ═══════════════════════════════════════════
    public static function admin_page(): void {
        global $wpdb; $t = $wpdb->prefix . self::DB_ADS;
        $ads = $wpdb->get_results("SELECT * FROM {$t} ORDER BY is_active DESC, priority ASC, id DESC", ARRAY_A);
        $typeFilter = sanitize_text_field($_GET['type'] ?? '');
        $zoneFilter = sanitize_text_field($_GET['zone'] ?? '');
        ?>
<div class="dza-wrap" style="direction:rtl;font-family:Tajawal,sans-serif">

<!-- HEADER -->
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:24px">
    <div>
        <h2 style="margin:0;font-size:24px">📢 مدير الإعلانات</h2>
        <p style="color:#666;margin:4px 0 0">بانرات، Pop-ups، شريط عروض، إعلانات مضمّنة — مع جدولة واستهداف وتحليلات</p>
    </div>
    <div style="display:flex;gap:8px">
        <button class="dza-btn" onclick="dzadShowForm(0)" style="background:#6366F1;color:#fff;padding:8px 20px;border-radius:8px;border:none;cursor:pointer;font-weight:700">➕ إنشاء إعلان</button>
        <button class="dza-btn" onclick="dzadShowStats()" style="background:#10B981;color:#fff;padding:8px 20px;border-radius:8px;border:none;cursor:pointer;font-weight:700">📊 التحليلات</button>
    </div>
</div>

<!-- STATS SUMMARY -->
<?php
$total     = count($ads);
$active    = count(array_filter($ads, function($a){ return $a['is_active']; }));
$imps      = array_sum(array_column($ads, 'impressions'));
$clicks    = array_sum(array_column($ads, 'clicks'));
$ctr       = $imps > 0 ? round($clicks / $imps * 100, 2) : 0;
?>
<div style="display:grid;grid-template-columns:repeat(5,1fr);gap:12px;margin-bottom:20px">
<?php foreach ([
    ['📢', $total, 'إجمالي الإعلانات', '#6366F1'],
    ['✅', $active, 'نشط', '#10B981'],
    ['👁', number_format($imps), 'مشاهدات', '#F59E0B'],
    ['🖱️', number_format($clicks), 'نقرات', '#3B82F6'],
    ['📈', $ctr.'%', 'CTR', '#EF4444'],
] as $s): ?>
<div style="background:#fff;border-radius:12px;padding:16px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,0.06)">
    <div style="font-size:24px;margin-bottom:4px"><?php echo $s[0]; ?></div>
    <div style="font-size:28px;font-weight:800;color:<?php echo $s[3]; ?>"><?php echo $s[1]; ?></div>
    <div style="font-size:11px;color:#888"><?php echo $s[2]; ?></div>
</div>
<?php endforeach; ?>
</div>

<!-- FILTERS -->
<div style="display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap">
    <select id="filter-type" onchange="dzadFilter()" style="padding:6px 12px;border:1px solid #ddd;border-radius:6px">
        <option value="">كل الأنواع</option>
        <?php foreach (self::TYPES as $k => $v): ?>
        <option value="<?php echo esc_attr($k); ?>"><?php echo $v['l']; ?></option>
        <?php endforeach; ?>
    </select>
    <select id="filter-zone" onchange="dzadFilter()" style="padding:6px 12px;border:1px solid #ddd;border-radius:6px">
        <option value="">كل المناطق</option>
        <?php foreach (self::ZONES as $k => $v): ?>
        <option value="<?php echo esc_attr($k); ?>"><?php echo esc_html($v); ?></option>
        <?php endforeach; ?>
    </select>
    <select id="filter-status" onchange="dzadFilter()" style="padding:6px 12px;border:1px solid #ddd;border-radius:6px">
        <option value="">كل الحالات</option>
        <option value="1">نشط</option>
        <option value="0">متوقف</option>
    </select>
</div>

<!-- ADS TABLE -->
<div style="background:#fff;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,0.06);overflow:hidden">
<table style="width:100%;border-collapse:collapse;font-size:13px" id="ads-table">
<thead><tr style="background:#f8f9fa;font-weight:700">
    <th style="padding:10px;width:30px"><input type="checkbox" id="check-all" onclick="document.querySelectorAll('.ad-check').forEach(c=>c.checked=this.checked)"></th>
    <th style="padding:10px;text-align:right">#</th>
    <th style="padding:10px;text-align:right">العنوان</th>
    <th style="padding:10px;text-align:right">النوع</th>
    <th style="padding:10px;text-align:right">المنطقة</th>
    <th style="padding:10px;text-align:center">الحالة</th>
    <th style="padding:10px;text-align:center">👁 مشاهدات</th>
    <th style="padding:10px;text-align:center">🖱️ نقرات</th>
    <th style="padding:10px;text-align:center">📈 CTR</th>
    <th style="padding:10px;text-align:center">الجدولة</th>
    <th style="padding:10px;text-align:center">إجراءات</th>
</tr></thead>
<tbody>
<?php foreach ($ads as $ad):
    $type = self::TYPES[$ad['ad_type']] ?? ['l' => $ad['ad_type']];
    $zone = self::ZONES[$ad['zone']] ?? $ad['zone'];
    $ctr_val = $ad['impressions'] > 0 ? round($ad['clicks'] / $ad['impressions'] * 100, 2) : 0;
    $scheduled = $ad['schedule_start'] || $ad['schedule_end'];
?>
<tr class="ad-row" data-type="<?php echo esc_attr($ad['ad_type']); ?>" data-zone="<?php echo esc_attr($ad['zone']); ?>" data-active="<?php echo $ad['is_active']; ?>" style="border-bottom:1px solid #f0f0f0">
    <td style="padding:10px"><input type="checkbox" class="ad-check" value="<?php echo $ad['id']; ?>"></td>
    <td style="padding:10px;font-weight:700;color:#6366F1">#<?php echo $ad['id']; ?></td>
    <td style="padding:10px">
        <strong style="cursor:pointer;color:#1F2937" onclick="dzadShowForm(<?php echo $ad['id']; ?>)"><?php echo esc_html($ad['title'] ?: 'بدون عنوان'); ?></strong>
        <?php if ($ad['ab_variant']): ?><span style="background:#F59E0B;color:#fff;font-size:9px;padding:1px 6px;border-radius:4px;margin-right:4px">A/B <?php echo esc_html($ad['ab_variant']); ?></span><?php endif; ?>
    </td>
    <td style="padding:10px"><?php echo $type['l']; ?></td>
    <td style="padding:10px;font-size:11px"><?php echo esc_html($zone); ?></td>
    <td style="padding:10px;text-align:center">
        <label class="dza-toggle" style="display:inline-flex"><input type="checkbox" class="ad-toggle" data-id="<?php echo $ad['id']; ?>" <?php checked($ad['is_active']); ?>><span style="font-size:11px"><?php echo $ad['is_active'] ? '🟢 نشط' : '🔴 متوقف'; ?></span></label>
    </td>
    <td style="padding:10px;text-align:center;font-weight:600"><?php echo number_format($ad['impressions']); ?></td>
    <td style="padding:10px;text-align:center;font-weight:600"><?php echo number_format($ad['clicks']); ?></td>
    <td style="padding:10px;text-align:center;font-weight:700;color:<?php echo $ctr_val > 5 ? '#10B981' : ($ctr_val > 2 ? '#F59E0B' : '#EF4444'); ?>"><?php echo $ctr_val; ?>%</td>
    <td style="padding:10px;text-align:center;font-size:11px">
        <?php if ($scheduled): ?>
            ⏰ <?php echo $ad['schedule_start'] ? date_i18n('m/d', strtotime($ad['schedule_start'])) : ''; ?>
            → <?php echo $ad['schedule_end'] ? date_i18n('m/d', strtotime($ad['schedule_end'])) : '∞'; ?>
        <?php else: ?>
            <span style="color:#aaa">دائم</span>
        <?php endif; ?>
    </td>
    <td style="padding:10px;text-align:center;white-space:nowrap">
        <button onclick="dzadShowForm(<?php echo $ad['id']; ?>)" class="dza-btn ghost" style="padding:4px 8px;font-size:11px" title="تعديل">✏️</button>
        <button onclick="dzadDuplicate(<?php echo $ad['id']; ?>)" class="dza-btn ghost" style="padding:4px 8px;font-size:11px" title="نسخ">📋</button>
        <button onclick="dzadDelete(<?php echo $ad['id']; ?>)" class="dza-btn ghost" style="padding:4px 8px;font-size:11px;border-color:#ef4444;color:#ef4444" title="حذف">🗑️</button>
    </td>
</tr>
<?php endforeach; ?>
<?php if (empty($ads)): ?>
<tr><td colspan="11" style="padding:40px;text-align:center;color:#aaa">لا توجد إعلانات بعد — أنشئ أول إعلان!</td></tr>
<?php endif; ?>
</tbody></table>
</div>

<!-- BULK ACTIONS -->
<div style="margin-top:12px;display:flex;gap:8px;align-items:center">
    <select id="bulk-action" style="padding:6px 12px;border:1px solid #ddd;border-radius:6px">
        <option value="">إجراء جماعي</option>
        <option value="activate">✅ تفعيل</option>
        <option value="deactivate">⏸ إيقاف</option>
        <option value="reset_stats">🔄 تصفير الإحصائيات</option>
        <option value="delete">🗑️ حذف</option>
    </select>
    <button onclick="dzadBulk()" class="dza-btn" style="padding:6px 16px;border-radius:6px;background:#6366F1;color:#fff;border:none;cursor:pointer">تنفيذ</button>
</div>

<!-- FORM MODAL (hidden) -->
<div id="ad-form-modal" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:99999;overflow-y:auto">
<div style="max-width:800px;margin:30px auto;background:#fff;border-radius:16px;padding:32px;direction:rtl;position:relative">
    <h3 id="ad-form-title" style="margin:0 0 20px">➕ إنشاء إعلان جديد</h3>
    <button onclick="document.getElementById('ad-form-modal').style.display='none'" style="position:absolute;top:16px;left:16px;background:none;border:none;font-size:20px;cursor:pointer">✕</button>

    <input type="hidden" id="ad-edit-id" value="0">

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
        <!-- Title -->
        <div style="grid-column:span 2">
            <label style="font-weight:700;font-size:12px">عنوان الإعلان</label>
            <input type="text" id="ad-title" style="width:100%;padding:8px 12px;border:1px solid #ddd;border-radius:8px" placeholder="مثال: عرض الصيف — 50% خصم">
        </div>

        <!-- Type -->
        <div>
            <label style="font-weight:700;font-size:12px">نوع الإعلان</label>
            <select id="ad-type" style="width:100%;padding:8px 12px;border:1px solid #ddd;border-radius:8px">
                <?php foreach (self::TYPES as $k => $v): ?>
                <option value="<?php echo esc_attr($k); ?>"><?php echo $v['l']; ?> — <?php echo esc_html($v['desc']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <!-- Zone -->
        <div>
            <label style="font-weight:700;font-size:12px">منطقة العرض</label>
            <select id="ad-zone" style="width:100%;padding:8px 12px;border:1px solid #ddd;border-radius:8px">
                <?php foreach (self::ZONES as $k => $v): ?>
                <option value="<?php echo esc_attr($k); ?>"><?php echo esc_html($v); ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <!-- Image -->
        <div>
            <label style="font-weight:700;font-size:12px">🖼️ رابط الصورة</label>
            <input type="url" id="ad-image" style="width:100%;padding:8px 12px;border:1px solid #ddd;border-radius:8px;direction:ltr" placeholder="https://...">
        </div>

        <!-- Link -->
        <div>
            <label style="font-weight:700;font-size:12px">🔗 رابط الوجهة</label>
            <input type="url" id="ad-link" style="width:100%;padding:8px 12px;border:1px solid #ddd;border-radius:8px;direction:ltr" placeholder="https://...">
        </div>

        <!-- CTA -->
        <div>
            <label style="font-weight:700;font-size:12px">نص الزر (CTA)</label>
            <input type="text" id="ad-cta" style="width:100%;padding:8px 12px;border:1px solid #ddd;border-radius:8px" placeholder="اطلب الآن">
        </div>

        <!-- Priority -->
        <div>
            <label style="font-weight:700;font-size:12px">الأولوية (1=عالية)</label>
            <input type="number" id="ad-priority" value="10" min="1" max="100" style="width:100%;padding:8px 12px;border:1px solid #ddd;border-radius:8px">
        </div>

        <!-- Colors -->
        <div>
            <label style="font-weight:700;font-size:12px">🎨 لون الخلفية</label>
            <input type="color" id="ad-bg" value="#FFFFFF" style="width:100%;height:36px;border:1px solid #ddd;border-radius:8px;cursor:pointer">
        </div>
        <div>
            <label style="font-weight:700;font-size:12px">🎨 لون النص</label>
            <input type="color" id="ad-text-color" value="#1F2937" style="width:100%;height:36px;border:1px solid #ddd;border-radius:8px;cursor:pointer">
        </div>

        <!-- Schedule -->
        <div>
            <label style="font-weight:700;font-size:12px">📅 بداية الجدولة</label>
            <input type="datetime-local" id="ad-start" style="width:100%;padding:8px 12px;border:1px solid #ddd;border-radius:8px">
        </div>
        <div>
            <label style="font-weight:700;font-size:12px">📅 نهاية الجدولة</label>
            <input type="datetime-local" id="ad-end" style="width:100%;padding:8px 12px;border:1px solid #ddd;border-radius:8px">
        </div>

        <!-- Delay / Scroll -->
        <div>
            <label style="font-weight:700;font-size:12px">⏱ تأخير الظهور (ثوان)</label>
            <input type="number" id="ad-delay" value="0" min="0" style="width:100%;padding:8px 12px;border:1px solid #ddd;border-radius:8px">
        </div>
        <div>
            <label style="font-weight:700;font-size:12px">📜 عمق التمرير % (Slide-in)</label>
            <input type="number" id="ad-scroll" value="0" min="0" max="100" style="width:100%;padding:8px 12px;border:1px solid #ddd;border-radius:8px">
        </div>

        <!-- Cookie / Close -->
        <div>
            <label style="font-weight:700;font-size:12px">🍪 إخفاء بعد الإغلاق (أيام)</label>
            <input type="number" id="ad-cookie" value="1" min="0" style="width:100%;padding:8px 12px;border:1px solid #ddd;border-radius:8px">
        </div>
        <div style="display:flex;align-items:end;gap:12px;padding-bottom:4px">
            <label><input type="checkbox" id="ad-closeable" checked> زر إغلاق</label>
        </div>

        <!-- HTML Content -->
        <div style="grid-column:span 2">
            <label style="font-weight:700;font-size:12px">📝 محتوى HTML</label>
            <textarea id="ad-html" rows="5" style="width:100%;padding:8px 12px;border:1px solid #ddd;border-radius:8px;font-family:monospace;font-size:12px;direction:ltr" placeholder="<h2>عرض خاص!</h2><p>احصل على 50% خصم</p>"></textarea>
        </div>

        <!-- Targeting -->
        <div style="grid-column:span 2">
            <label style="font-weight:700;font-size:12px">🎯 قواعد الاستهداف</label>
            <div id="ad-targets" style="display:flex;flex-direction:column;gap:6px"></div>
            <button type="button" onclick="dzadAddTarget()" style="margin-top:6px;padding:4px 12px;border:1px dashed #6366F1;background:none;color:#6366F1;border-radius:6px;cursor:pointer;font-size:12px">➕ إضافة قاعدة</button>
        </div>
    </div>

    <div style="display:flex;gap:8px;margin-top:24px;justify-content:center">
        <button onclick="dzadSave()" style="padding:10px 40px;background:#6366F1;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:700;font-size:14px">💾 حفظ الإعلان</button>
        <button onclick="document.getElementById('ad-form-modal').style.display='none'" style="padding:10px 24px;background:#f3f4f6;border:none;border-radius:8px;cursor:pointer;font-size:14px">إلغاء</button>
    </div>
</div>
</div>

<!-- STATS MODAL (hidden) -->
<div id="ad-stats-modal" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:99999;overflow-y:auto">
<div style="max-width:900px;margin:30px auto;background:#fff;border-radius:16px;padding:32px;direction:rtl">
    <h3 style="margin:0 0 20px">📊 تحليلات الإعلانات</h3>
    <button onclick="document.getElementById('ad-stats-modal').style.display='none'" style="position:absolute;top:16px;left:16px;background:none;border:none;font-size:20px;cursor:pointer">✕</button>
    <div id="ad-stats-content" style="text-align:center;color:#888">جاري التحميل...</div>
</div>
</div>

<script>
var adTypes=<?php echo wp_json_encode(self::TYPES); ?>;
var adTargets=<?php echo wp_json_encode(self::TARGETS); ?>;
var adsList=<?php echo wp_json_encode($ads); ?>;

function dzadShowForm(id){
    document.getElementById('ad-form-modal').style.display='block';
    document.getElementById('ad-edit-id').value=id;
    document.getElementById('ad-form-title').textContent=id?'✏️ تعديل الإعلان #'+id:'➕ إنشاء إعلان جديد';
    if(id){
        var ad=adsList.find(function(a){return parseInt(a.id)===id});
        if(ad){
            document.getElementById('ad-title').value=ad.title||'';
            document.getElementById('ad-type').value=ad.ad_type||'banner';
            document.getElementById('ad-zone').value=ad.zone||'custom';
            document.getElementById('ad-image').value=ad.content_image||'';
            document.getElementById('ad-link').value=ad.link_url||'';
            document.getElementById('ad-cta').value=ad.cta_text||'';
            document.getElementById('ad-priority').value=ad.priority||10;
            document.getElementById('ad-bg').value='#'+(ad.bg_color||'FFFFFF');
            document.getElementById('ad-text-color').value='#'+(ad.text_color||'1F2937');
            document.getElementById('ad-start').value=(ad.schedule_start||'').replace(' ','T');
            document.getElementById('ad-end').value=(ad.schedule_end||'').replace(' ','T');
            document.getElementById('ad-delay').value=ad.delay_seconds||0;
            document.getElementById('ad-scroll').value=ad.scroll_trigger||0;
            document.getElementById('ad-cookie').value=ad.cookie_days||1;
            document.getElementById('ad-closeable').checked=!!parseInt(ad.close_button);
            document.getElementById('ad-html').value=ad.content_html||'';
            // Load targets
            document.getElementById('ad-targets').innerHTML='';
            var rules=JSON.parse(ad.target_rules||'[]');
            rules.forEach(function(r){dzadAddTarget(r.type,r.value)});
        }
    } else {
        // Reset form
        ['ad-title','ad-image','ad-link','ad-cta','ad-html','ad-start','ad-end'].forEach(function(f){document.getElementById(f).value=''});
        document.getElementById('ad-type').value='banner';
        document.getElementById('ad-zone').value='custom';
        document.getElementById('ad-priority').value=10;
        document.getElementById('ad-bg').value='#FFFFFF';
        document.getElementById('ad-text-color').value='#1F2937';
        document.getElementById('ad-delay').value=0;
        document.getElementById('ad-scroll').value=0;
        document.getElementById('ad-cookie').value=1;
        document.getElementById('ad-closeable').checked=true;
        document.getElementById('ad-targets').innerHTML='';
    }
}

function dzadAddTarget(type,value){
    var el=document.getElementById('ad-targets');
    var opts='';for(var k in adTargets)opts+='<option value="'+k+'"'+(k===type?' selected':'')+'>'+adTargets[k]+'</option>';
    el.insertAdjacentHTML('beforeend','<div style="display:flex;gap:6px;align-items:center"><select class="target-type" style="padding:6px;border:1px solid #ddd;border-radius:6px">'+opts+'</select><input type="text" class="target-value" value="'+(value||'')+'" placeholder="القيمة" style="flex:1;padding:6px;border:1px solid #ddd;border-radius:6px"><button type="button" onclick="this.parentElement.remove()" style="background:#ef4444;color:#fff;border:none;border-radius:6px;padding:4px 8px;cursor:pointer">✕</button></div>');
}

function dzadSave(){
    var targets=[];
    document.querySelectorAll('#ad-targets > div').forEach(function(r){
        targets.push({type:r.querySelector('.target-type').value,value:r.querySelector('.target-value').value});
    });
    var data={
        action:'dzqcod_ads_save',nonce:dza.nonce,
        ad_id:document.getElementById('ad-edit-id').value,
        title:document.getElementById('ad-title').value,
        ad_type:document.getElementById('ad-type').value,
        zone:document.getElementById('ad-zone').value,
        content_image:document.getElementById('ad-image').value,
        link_url:document.getElementById('ad-link').value,
        cta_text:document.getElementById('ad-cta').value,
        priority:document.getElementById('ad-priority').value,
        bg_color:document.getElementById('ad-bg').value.replace('#',''),
        text_color:document.getElementById('ad-text-color').value.replace('#',''),
        schedule_start:document.getElementById('ad-start').value.replace('T',' '),
        schedule_end:document.getElementById('ad-end').value.replace('T',' '),
        delay_seconds:document.getElementById('ad-delay').value,
        scroll_trigger:document.getElementById('ad-scroll').value,
        cookie_days:document.getElementById('ad-cookie').value,
        close_button:document.getElementById('ad-closeable').checked?1:0,
        content_html:document.getElementById('ad-html').value,
        target_rules:JSON.stringify(targets)
    };
    jQuery.post(dza.ajax,data,function(r){
        if(r.success){alert('✅ تم الحفظ');location.reload();}
        else alert('خطأ: '+(r.data&&r.data.message?r.data.message:'غير معروف'));
    });
}

function dzadDelete(id){
    if(!confirm('حذف الإعلان #'+id+'؟'))return;
    jQuery.post(dza.ajax,{action:'dzqcod_ads_delete',nonce:dza.nonce,ad_id:id},function(r){
        if(r.success)location.reload();
    });
}

function dzadDuplicate(id){
    jQuery.post(dza.ajax,{action:'dzqcod_ads_duplicate',nonce:dza.nonce,ad_id:id},function(r){
        if(r.success)location.reload();
    });
}

function dzadBulk(){
    var action=document.getElementById('bulk-action').value;
    var ids=[];document.querySelectorAll('.ad-check:checked').forEach(function(c){ids.push(c.value)});
    if(!action||!ids.length){alert('اختر إجراء وإعلانات');return}
    if(!confirm('تنفيذ على '+ids.length+' إعلان؟'))return;
    jQuery.post(dza.ajax,{action:'dzqcod_ads_bulk',nonce:dza.nonce,ids:ids,bulk_action:action},function(r){
        if(r.success)location.reload();
    });
}

// Toggle
jQuery(document).on('change','.ad-toggle',function(){
    jQuery.post(dza.ajax,{action:'dzqcod_ads_toggle',nonce:dza.nonce,ad_id:jQuery(this).data('id')});
});

// Filter
function dzadFilter(){
    var t=document.getElementById('filter-type').value;
    var z=document.getElementById('filter-zone').value;
    var s=document.getElementById('filter-status').value;
    document.querySelectorAll('.ad-row').forEach(function(r){
        var show=true;
        if(t&&r.dataset.type!==t)show=false;
        if(z&&r.dataset.zone!==z)show=false;
        if(s!==''&&r.dataset.active!==s)show=false;
        r.style.display=show?'':'none';
    });
}

function dzadShowStats(){
    document.getElementById('ad-stats-modal').style.display='block';
    document.getElementById('ad-stats-content').innerHTML='<div style="padding:40px;text-align:center;color:#888">⏳ جاري التحميل...</div>';
    jQuery.post(dza.ajax,{action:'dzqcod_ads_stats',nonce:dza.nonce,days:30},function(r){
        if(!r.success)return;
        var d=r.data,h='<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">';
        // Top ads table
        h+='<div style="grid-column:span 2"><h4>🏆 أفضل الإعلانات أداءً</h4><table style="width:100%;border-collapse:collapse;font-size:12px"><thead><tr style="background:#f8f9fa"><th style="padding:8px;text-align:right">#</th><th style="padding:8px;text-align:right">العنوان</th><th style="padding:8px;text-align:center">النوع</th><th style="padding:8px;text-align:center">👁</th><th style="padding:8px;text-align:center">🖱️</th><th style="padding:8px;text-align:center">CTR</th></tr></thead><tbody>';
        (d.top||[]).forEach(function(t){
            h+='<tr style="border-bottom:1px solid #f0f0f0"><td style="padding:6px">#'+t.id+'</td><td style="padding:6px">'+t.title+'</td><td style="padding:6px;text-align:center">'+t.ad_type+'</td><td style="padding:6px;text-align:center">'+parseInt(t.impressions).toLocaleString()+'</td><td style="padding:6px;text-align:center">'+parseInt(t.clicks).toLocaleString()+'</td><td style="padding:6px;text-align:center;font-weight:700;color:'+(parseFloat(t.ctr)>5?'#10B981':'#F59E0B')+'">'+t.ctr+'%</td></tr>';
        });
        h+='</tbody></table></div>';
        // Device breakdown
        h+='<div><h4>📱 الأجهزة</h4>';
        (d.devices||[]).forEach(function(dv){
            h+='<div style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid #f0f0f0"><span>'+(dv.device==='mobile'?'📱 موبايل':'💻 كمبيوتر')+'</span><strong>'+parseInt(dv.cnt).toLocaleString()+'</strong></div>';
        });
        h+='</div>';
        h+='</div>';
        document.getElementById('ad-stats-content').innerHTML=h;
    });
}
</script>

</div>
        <?php
    }
}

// Initialize
AdsManager::init();
