<?php
if ( ! defined('ABSPATH') ) { exit; }

/**
 * Nikan Popups (theme core module)
 * CPT: nikan_popup
 * Types: image, text, coupon
 * Conditions: pages, date range, delay, frequency hours, user state
 */

class Nikan_Popups_Module {

    const CPT = 'nikan_popup';
    const META = '_nikan_popup';

    public static function init(){
        add_action('init', [__CLASS__, 'register_cpt']);
        add_action('add_meta_boxes', [__CLASS__, 'add_metaboxes']);
        add_action('save_post', [__CLASS__, 'save_metabox'], 10, 2);

        add_action('admin_menu', [__CLASS__, 'add_menu']);
        add_action('admin_enqueue_scripts', [__CLASS__, 'admin_assets']);

        add_action('wp_enqueue_scripts', [__CLASS__, 'enqueue_front']);
        add_action('wp_footer', [__CLASS__, 'render_front'], 50);
    }

    public static function register_cpt(){
        $labels = [
            'name' => 'پاپ‌آپ‌های نیکان',
            'singular_name' => 'پاپ‌آپ نیکان',
            'add_new' => 'افزودن پاپ‌آپ',
            'add_new_item' => 'افزودن پاپ‌آپ جدید',
            'edit_item' => 'ویرایش پاپ‌آپ',
            'new_item' => 'پاپ‌آپ جدید',
            'view_item' => 'مشاهده پاپ‌آپ',
            'search_items' => 'جستجوی پاپ‌آپ‌ها',
        ];

        register_post_type(self::CPT, [
            'labels' => $labels,
            'public' => false,
            'show_ui' => true,
            // Show under its own top-level menu.
            'show_in_menu' => 'nikan-popups',
            'supports' => ['title'],
            'capability_type' => 'post',
            'menu_icon' => 'dashicons-format-image',
        ]);
    }

    public static function add_menu(){
        // Top-level menu that hosts the CPT screens.
        add_menu_page(
            'پاپ‌آپ نیکان',
            'پاپ‌آپ نیکان',
            'manage_options',
            'nikan-popups',
            '__return_null',
            'dashicons-megaphone',
            58
        );
        // First submenu should point to CPT list.
        add_submenu_page(
            'nikan-popups',
            'همه پاپ‌آپ‌ها',
            'همه پاپ‌آپ‌ها',
            'manage_options',
            'edit.php?post_type=' . self::CPT
        );
        add_submenu_page(
            'nikan-popups',
            'افزودن پاپ‌آپ',
            'افزودن پاپ‌آپ',
            'manage_options',
            'post-new.php?post_type=' . self::CPT
        );
    }

    public static function admin_assets($hook){
        // Load only on popup CPT screens.
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if ( ! $screen ) return;
        if ( $screen->post_type !== self::CPT ) return;

        wp_enqueue_media();
        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('wp-color-picker');

        $ver = wp_get_theme()->get('Version') ?: '1.0.0';
        wp_enqueue_script('nikan-popups-admin', get_template_directory_uri().'/assets/js/nikan-popups-admin.js', ['jquery','wp-color-picker'], $ver, true);
        wp_enqueue_style('nikan-popups-admin', get_template_directory_uri().'/assets/css/nikan-popups-admin.css', [], $ver);
    }

    public static function add_metaboxes(){
        add_meta_box('nikan_popup_settings', 'تنظیمات پاپ‌آپ', [__CLASS__, 'metabox_html'], self::CPT, 'normal', 'high');
    }

    private static function defaults(){
        return [
            'enabled' => '1',
            'type' => 'image', // image|text|coupon
            'image_id' => '',
            'image' => '',
            'link' => '',
            'title' => '',
            'text' => '',
            'coupon' => '',
            'btn_text' => 'مشاهده',
            'btn_url' => '',
            'date_mode' => 'none', // none|range
            'start' => '', // stored as Gregorian "Y-m-d H:i" when date_mode=range
            'end' => '',
            'exclude_hours_enabled' => '0',
            'exclude_hours' => '', // e.g. "0-6,23"
            'pages' => 'all', // all|home|shop|checkout|product|cart|pages
            'page_ids' => '',
            'delay' => '0', // seconds
            'frequency' => '12', // hours
            'always_show' => '0', // if 1, ignore frequency and always display
            'priority' => '10', // lower = higher priority
            'user' => 'all', // all|guest|logged
            'overlay' => '0.55',
            'width' => '520',
            'radius' => '18',
            'bg' => '#ffffff',
            'accent' => '#ff6a00',
        ];
    }

    private static function g2j($gy,$gm,$gd){
        // Gregorian to Jalali (Iranian) date conversion.
        $g_d_m = [0,31,59,90,120,151,181,212,243,273,304,334];
        $gy2 = ($gm > 2) ? ($gy + 1) : $gy;
        $days = 355666 + (365 * $gy) + intdiv($gy2 + 3,4) - intdiv($gy2 + 99,100) + intdiv($gy2 + 399,400) + $gd + $g_d_m[$gm-1];
        $jy = -1595 + (33 * intdiv($days,12053));
        $days %= 12053;
        $jy += 4 * intdiv($days,1461);
        $days %= 1461;
        if ($days > 365) {
            $jy += intdiv($days - 1, 365);
            $days = ($days - 1) % 365;
        }
        $jm = ($days < 186) ? (1 + intdiv($days,31)) : (7 + intdiv($days - 186,30));
        $jd = 1 + (($days < 186) ? ($days % 31) : (($days - 186) % 30));
        return [$jy,$jm,$jd];
    }

    private static function j2g($jy,$jm,$jd){
        // Jalali to Gregorian conversion.
        $jy += 1595;
        $days = -355668 + (365 * $jy) + (intdiv($jy,33) * 8) + intdiv(($jy % 33) + 3,4) + $jd;
        if ($jm < 7) $days += ($jm - 1) * 31;
        else $days += (($jm - 7) * 30) + 186;
        $gy = 400 * intdiv($days,146097);
        $days %= 146097;
        if ($days > 36524) {
            $gy += 100 * intdiv(--$days,36524);
            $days %= 36524;
            if ($days >= 365) $days++;
        }
        $gy += 4 * intdiv($days,1461);
        $days %= 1461;
        if ($days > 365) {
            $gy += intdiv($days - 1,365);
            $days = ($days - 1) % 365;
        }
        $gd = $days + 1;
        $sal_a = [0,31, ( ($gy%4==0 && $gy%100!=0) || ($gy%400==0) ) ? 29 : 28, 31,30,31,30,31,31,30,31,30,31];
        $gm = 1;
        while ($gm <= 12 && $gd > $sal_a[$gm]) { $gd -= $sal_a[$gm]; $gm++; }
        return [$gy,$gm,$gd];
    }

    private static function gregorian_string_to_jalali_parts(string $greg): array {
        // Returns [jy,jm,jd,time] with time HH:ii
        $greg = trim($greg);
        if (!$greg) return [null,null,null,'00:00'];
        $ts = strtotime($greg);
        if (!$ts) return [null,null,null,'00:00'];
        $gy = (int)date('Y',$ts);
        $gm = (int)date('n',$ts);
        $gd = (int)date('j',$ts);
        [$jy,$jm,$jd] = self::g2j($gy,$gm,$gd);
        $time = date('H:i',$ts);
        return [$jy,$jm,$jd,$time];
    }

    private static function build_gregorian_from_jalali($jy,$jm,$jd,$time): string {
        $jy = (int)$jy; $jm = (int)$jm; $jd = (int)$jd;
        if ($jy < 1200 || $jm < 1 || $jm > 12 || $jd < 1 || $jd > 31) return '';
        [$gy,$gm,$gd] = self::j2g($jy,$jm,$jd);
        $time = preg_match('/^\d{2}:\d{2}$/', (string)$time) ? (string)$time : '00:00';
        return sprintf('%04d-%02d-%02d %s', $gy, $gm, $gd, $time);
    }

    public static function metabox_html($post){
        $val = get_post_meta($post->ID, self::META, true);
        $val = is_array($val) ? array_merge(self::defaults(), $val) : self::defaults();

        wp_nonce_field('nikan_popup_save', 'nikan_popup_nonce');
        ?>
        <div class="nikan-popup-grid">
            <div>
                <label>فعال</label>
                <select name="nikan_popup[enabled]">
                    <option value="1" <?php selected($val['enabled'],'1'); ?>>فعال</option>
                    <option value="0" <?php selected($val['enabled'],'0'); ?>>غیرفعال</option>
                </select>
            </div>
            <div>
                <label>نوع پاپ‌آپ</label>
                <select name="nikan_popup[type]" class="nikan-popup-type">
                    <option value="image" <?php selected($val['type'],'image'); ?>>تصویری</option>
                    <option value="text" <?php selected($val['type'],'text'); ?>>متنی</option>
                    <option value="coupon" <?php selected($val['type'],'coupon'); ?>>کد تخفیف (با کپی)</option>
                </select>
                <div class="nikan-help">برای نوع تصویری، «تصویر» و (اختیاری) «لینک» را پر کنید.</div>
            </div>

            <div class="nikan-popup-field" data-show="image">
                <label>تصویر</label>
                <input type="hidden" class="nikan-popup-image-id" name="nikan_popup[image_id]" value="<?php echo esc_attr($val['image_id']); ?>">
                <input type="text" class="nikan-popup-image-url" name="nikan_popup[image]" value="<?php echo esc_attr($val['image']); ?>" placeholder="URL تصویر (خودکار)">
                <div style="margin-top:8px;display:flex;gap:10px;align-items:center;flex-wrap:wrap">
                    <button type="button" class="button nikan-popup-pick-image">انتخاب/آپلود تصویر</button>
                    <button type="button" class="button nikan-popup-remove-image">حذف تصویر</button>
                </div>
                <div class="nikan-popup-image-preview" style="margin-top:10px"></div>
            </div>
            <div class="nikan-popup-field" data-show="image">
                <label>لینک تصویر</label>
                <input type="text" name="nikan_popup[link]" value="<?php echo esc_attr($val['link']); ?>" placeholder="https://...">
            </div>

            <div class="full">
                <label>عنوان</label>
                <input type="text" name="nikan_popup[title]" value="<?php echo esc_attr($val['title']); ?>">
            </div>
            <div class="full">
                <label>متن</label>
                <textarea name="nikan_popup[text]" rows="4"><?php echo esc_textarea($val['text']); ?></textarea>
            </div>

            <div class="nikan-popup-field" data-show="coupon">
                <label>کد تخفیف</label>
                <input type="text" name="nikan_popup[coupon]" value="<?php echo esc_attr($val['coupon']); ?>">
                <div class="nikan-help">فقط برای نوع «کد تخفیف» استفاده می‌شود.</div>
            </div>
            <div>
                <label>متن دکمه</label>
                <input type="text" name="nikan_popup[btn_text]" value="<?php echo esc_attr($val['btn_text']); ?>">
            </div>
            <div class="full">
                <label>لینک دکمه</label>
                <input type="text" name="nikan_popup[btn_url]" value="<?php echo esc_attr($val['btn_url']); ?>" placeholder="https://...">
            </div>

            <div class="full">
                <label>محدودیت زمانی</label>
                <select name="nikan_popup[date_mode]" class="nikan-popup-date-mode">
                    <option value="none" <?php selected($val['date_mode'],'none'); ?>>بدون محدودیت (همیشه فعال)</option>
                    <option value="range" <?php selected($val['date_mode'],'range'); ?>>نمایش در بازه زمانی (شمسی)</option>
                </select>
                <div class="nikan-help">اگر «بدون محدودیت» باشد، پاپ‌آپ همیشه (طبق سایر شرایط) نمایش داده می‌شود.</div>
            </div>

            <?php
            [$s_jy,$s_jm,$s_jd,$s_time] = self::gregorian_string_to_jalali_parts((string)$val['start']);
            [$e_jy,$e_jm,$e_jd,$e_time] = self::gregorian_string_to_jalali_parts((string)$val['end']);
            $years = range(1398, 1450);
            ?>
            <div class="nikan-popup-field" data-show="date_range">
                <label>شروع (شمسی)</label>
                <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">
                    <select name="nikan_popup[start_jy]">
                        <option value="">سال</option>
                        <?php foreach ($years as $y): ?>
                            <option value="<?php echo esc_attr($y); ?>" <?php selected((string)$s_jy, (string)$y); ?>><?php echo esc_html($y); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <select name="nikan_popup[start_jm]">
                        <option value="">ماه</option>
                        <?php for($m=1;$m<=12;$m++): ?>
                            <option value="<?php echo esc_attr($m); ?>" <?php selected((string)$s_jm, (string)$m); ?>><?php echo esc_html($m); ?></option>
                        <?php endfor; ?>
                    </select>
                    <select name="nikan_popup[start_jd]">
                        <option value="">روز</option>
                        <?php for($d=1;$d<=31;$d++): ?>
                            <option value="<?php echo esc_attr($d); ?>" <?php selected((string)$s_jd, (string)$d); ?>><?php echo esc_html($d); ?></option>
                        <?php endfor; ?>
                    </select>
                    <input type="time" name="nikan_popup[start_time]" value="<?php echo esc_attr($s_time ?: '00:00'); ?>" style="max-width:140px">
                </div>
                <div class="nikan-help">اگر فقط تاریخ را انتخاب کنید و زمان را خالی بگذارید، 00:00 در نظر گرفته می‌شود.</div>
            </div>
            <div class="nikan-popup-field" data-show="date_range">
                <label>پایان (شمسی)</label>
                <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">
                    <select name="nikan_popup[end_jy]">
                        <option value="">سال</option>
                        <?php foreach ($years as $y): ?>
                            <option value="<?php echo esc_attr($y); ?>" <?php selected((string)$e_jy, (string)$y); ?>><?php echo esc_html($y); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <select name="nikan_popup[end_jm]">
                        <option value="">ماه</option>
                        <?php for($m=1;$m<=12;$m++): ?>
                            <option value="<?php echo esc_attr($m); ?>" <?php selected((string)$e_jm, (string)$m); ?>><?php echo esc_html($m); ?></option>
                        <?php endfor; ?>
                    </select>
                    <select name="nikan_popup[end_jd]">
                        <option value="">روز</option>
                        <?php for($d=1;$d<=31;$d++): ?>
                            <option value="<?php echo esc_attr($d); ?>" <?php selected((string)$e_jd, (string)$d); ?>><?php echo esc_html($d); ?></option>
                        <?php endfor; ?>
                    </select>
                    <input type="time" name="nikan_popup[end_time]" value="<?php echo esc_attr($e_time ?: '23:59'); ?>" style="max-width:140px">
                </div>
                <div class="nikan-help">اگر پایان را خالی بگذارید، محدودیت پایان ندارد.</div>
            </div>

            <div class="full">
                <label style="display:flex;align-items:center;gap:10px">
                    <input type="hidden" name="nikan_popup[exclude_hours_enabled]" value="0">
                    <input type="checkbox" name="nikan_popup[exclude_hours_enabled]" value="1" <?php checked($val['exclude_hours_enabled'],'1'); ?>>
                    عدم نمایش در ساعات مشخص (اختیاری)
                </label>
                <input type="text" name="nikan_popup[exclude_hours]" value="<?php echo esc_attr($val['exclude_hours']); ?>" placeholder="مثال: 0-6,23">
                <div class="nikan-help">مثال: 0-6,23 یعنی از ساعت 0 تا 6 و همچنین ساعت 23 نمایش ندهد.</div>
            </div>

            <div>
                <label>نمایش در</label>
                <select name="nikan_popup[pages]">
                    <option value="all" <?php selected($val['pages'],'all'); ?>>کل سایت</option>
                    <option value="home" <?php selected($val['pages'],'home'); ?>>فقط صفحه اصلی</option>
                    <option value="shop" <?php selected($val['pages'],'shop'); ?>>فقط فروشگاه</option>
                    <option value="cart" <?php selected($val['pages'],'cart'); ?>>فقط سبد خرید</option>
                    <option value="checkout" <?php selected($val['pages'],'checkout'); ?>>فقط تسویه حساب</option>
                    <option value="product" <?php selected($val['pages'],'product'); ?>>فقط صفحات محصول</option>
                    <option value="pages" <?php selected($val['pages'],'pages'); ?>>فقط صفحات انتخابی</option>
                </select>
            </div>
            <div>
                <label>شناسه صفحات (در حالت صفحات انتخابی)</label>
                <input type="text" name="nikan_popup[page_ids]" value="<?php echo esc_attr($val['page_ids']); ?>" placeholder="12,34,56">
            </div>

            <div>
                <label>تاخیر نمایش (ثانیه)</label>
                <input type="number" min="0" max="60" name="nikan_popup[delay]" value="<?php echo esc_attr($val['delay']); ?>">
            </div>
            <div class="nikan-popup-frequency-field">
                <label>عدم نمایش مجدد (ساعت)</label>
                <input type="number" min="1" max="720" name="nikan_popup[frequency]" value="<?php echo esc_attr($val['frequency']); ?>">
                <div class="nikan-help">بعد از بستن، تا این مدت به همان کاربر دوباره نمایش داده نمی‌شود.</div>
            </div>
            <div class="nikan-popup-always-field">
                <label style="display:flex;align-items:center;gap:8px">
                    <input type="checkbox" name="nikan_popup[always_show]" value="1" <?php checked($val['always_show'],'1'); ?>>
                    <span>همیشه قابل نمایش بدون محدودیت</span>
                </label>
                <div class="nikan-help">اگر فعال باشد، پاپ‌آپ در هر صفحه/هر بار بازدید نمایش داده می‌شود و «عدم نمایش مجدد» نادیده گرفته می‌شود.</div>
            </div>
            <div>
                <label>اولویت نمایش</label>
                <input type="number" min="1" max="100" name="nikan_popup[priority]" value="<?php echo esc_attr($val['priority']); ?>">
                <div class="nikan-help">عدد کمتر یعنی اولویت بالاتر. وقتی چند پاپ‌آپ فعال باشد، فقط یکی با اولویت بالاتر نمایش داده می‌شود.</div>
            </div>


            <div>
                <label>نوع کاربر</label>
                <select name="nikan_popup[user]">
                    <option value="all" <?php selected($val['user'],'all'); ?>>همه</option>
                    <option value="guest" <?php selected($val['user'],'guest'); ?>>فقط مهمان</option>
                    <option value="logged" <?php selected($val['user'],'logged'); ?>>فقط لاگین</option>
                </select>
            </div>

            <div>
                <label>عرض پاپ‌آپ (px)</label>
                <input type="number" min="280" max="900" name="nikan_popup[width]" value="<?php echo esc_attr($val['width']); ?>">
            </div>
            <div>
                <label>گردی گوشه‌ها (px)</label>
                <input type="number" min="0" max="50" name="nikan_popup[radius]" value="<?php echo esc_attr($val['radius']); ?>">
            </div>
            <div>
                <label>رنگ پس‌زمینه</label>
                <input type="text" class="nikan-color" name="nikan_popup[bg]" value="<?php echo esc_attr($val['bg']); ?>" placeholder="#ffffff">
            </div>
            <div>
                <label>رنگ Accent</label>
                <input type="text" class="nikan-color" name="nikan_popup[accent]" value="<?php echo esc_attr($val['accent']); ?>" placeholder="#ff6a00">
            </div>
            <div class="full">
                <label>شدت بک‌گراند (Overlay 0 تا 1)</label>
                <input type="number" step="0.05" min="0" max="0.9" name="nikan_popup[overlay]" value="<?php echo esc_attr($val['overlay']); ?>">
            </div>
        </div>
        <?php
    }

    public static function save_metabox($post_id, $post){
        if ( $post->post_type !== self::CPT ) return;
        if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;
        if ( ! current_user_can('edit_post', $post_id) ) return;
        if ( empty($_POST['nikan_popup_nonce']) || ! wp_verify_nonce($_POST['nikan_popup_nonce'], 'nikan_popup_save') ) return;

        $in = $_POST['nikan_popup'] ?? [];
        $val = self::defaults();

        foreach ($val as $k => $d) {
            if (!isset($in[$k])) continue;
            $v = $in[$k];
            if (is_string($v)) $v = trim($v);
            $val[$k] = $v;
        }

        // build dates from Jalali parts (only when date_mode=range)
        $in_date_mode = isset($in['date_mode']) ? trim((string)$in['date_mode']) : 'none';
        if ($in_date_mode === 'range') {
            $val['date_mode'] = 'range';
            $start = self::build_gregorian_from_jalali($in['start_jy'] ?? '', $in['start_jm'] ?? '', $in['start_jd'] ?? '', $in['start_time'] ?? '00:00');
            $end   = self::build_gregorian_from_jalali($in['end_jy'] ?? '', $in['end_jm'] ?? '', $in['end_jd'] ?? '', $in['end_time'] ?? '23:59');
            $val['start'] = $start;
            $val['end']   = $end;
        } else {
            $val['date_mode'] = 'none';
            $val['start'] = '';
            $val['end'] = '';
        }

        // sanitize
        $val['enabled'] = $val['enabled'] === '0' ? '0' : '1';
        $val['type'] = in_array($val['type'], ['image','text','coupon'], true) ? $val['type'] : 'image';
        $val['exclude_hours_enabled'] = ($val['exclude_hours_enabled'] ?? '0') === '1' ? '1' : '0';
        $val['exclude_hours'] = sanitize_text_field((string)($val['exclude_hours'] ?? ''));
        $val['delay'] = (string)max(0, min(60, intval($val['delay'])));
        $val['frequency'] = (string)max(1, min(720, intval($val['frequency'])));
        $val['always_show'] = (($val['always_show'] ?? '0') === '1') ? '1' : '0';
        $val['priority'] = (string)max(1, min(100, intval($val['priority'])));
        $val['width'] = (string)max(280, min(900, intval($val['width'])));
        $val['radius'] = (string)max(0, min(60, intval($val['radius'])));
        $val['overlay'] = (string)max(0, min(0.9, floatval($val['overlay'])));

        // clean coupon for non-coupon types
        if ($val['type'] !== 'coupon') {
            $val['coupon'] = '';
        }

        // if image id exists, prefer its URL
        $img_id = absint($val['image_id'] ?? 0);
        if ($img_id) {
            $url = wp_get_attachment_image_url($img_id, 'full');
            if ($url) $val['image'] = $url;
        }

        update_post_meta($post_id, self::META, $val);
    }

    public static function enqueue_front(){
        // enqueue only if at least one popup is active for this request
        if ( is_admin() ) return;
        $popup = self::pick_popup_for_request();
        if ( ! $popup ) return;

        $ver = wp_get_theme()->get('Version') ?: '1.0.0';
        wp_enqueue_style('nikan-popups', get_template_directory_uri().'/assets/css/nikan-popups.css', [], $ver);
        wp_enqueue_script('nikan-popups', get_template_directory_uri().'/assets/js/nikan-popups.js', [], $ver, true);
    }

    private static function request_matches(array $cfg): bool {
        // user state
        if ($cfg['user'] === 'guest' && is_user_logged_in()) return false;
        if ($cfg['user'] === 'logged' && ! is_user_logged_in()) return false;

        // date range (optional)
        $now = time();
        if (($cfg['date_mode'] ?? 'none') === 'range') {
            if (!empty($cfg['start'])) {
                $ts = strtotime($cfg['start']);
                if ($ts && $now < $ts) return false;
            }
            if (!empty($cfg['end'])) {
                $ts = strtotime($cfg['end']);
                if ($ts && $now > $ts) return false;
            }
        }

        // exclude hours (optional)
        if (($cfg['exclude_hours_enabled'] ?? '0') === '1' && !empty($cfg['exclude_hours'])) {
            $hour = (int)wp_date('G');
            $rule = (string)$cfg['exclude_hours'];
            $parts = array_filter(array_map('trim', explode(',', $rule)));
            foreach ($parts as $part) {
                if (preg_match('/^(\d{1,2})\s*-\s*(\d{1,2})$/', $part, $m)) {
                    $a = max(0, min(23, (int)$m[1]));
                    $b = max(0, min(23, (int)$m[2]));
                    if ($a <= $b) {
                        if ($hour >= $a && $hour <= $b) return false;
                    } else {
                        // wrap around (e.g. 22-2)
                        if ($hour >= $a || $hour <= $b) return false;
                    }
                } elseif (preg_match('/^\d{1,2}$/', $part)) {
                    $h = max(0, min(23, (int)$part));
                    if ($hour === $h) return false;
                }
            }
        }

        // pages
        $pages = $cfg['pages'] ?? 'all';
        if ($pages === 'home') return is_front_page();
        if ($pages === 'shop') return function_exists('is_shop') && is_shop();
        if ($pages === 'cart') return function_exists('is_cart') && is_cart();
        if ($pages === 'checkout') return function_exists('is_checkout') && is_checkout();
        if ($pages === 'product') return function_exists('is_product') && is_product();
        if ($pages === 'pages') {
            $ids = array_filter(array_map('absint', explode(',', (string)($cfg['page_ids'] ?? ''))));
            return !empty($ids) && is_page($ids);
        }
        return true; // all
    }

    private static function pick_popup_for_request(){
        $q = new WP_Query([
            'post_type' => self::CPT,
            'post_status' => 'publish',
            'posts_per_page' => 50,
            'orderby' => 'date',
            'order' => 'DESC',
            'no_found_rows' => true,
        ]);
        if ( ! $q->have_posts() ) return null;

        $candidates = [];
        foreach ($q->posts as $p) {
            $cfg = get_post_meta($p->ID, self::META, true);
            if (!is_array($cfg)) continue;
            $cfg = array_merge(self::defaults(), $cfg);
            if ($cfg['enabled'] !== '1') continue;
            if (!self::request_matches($cfg)) continue;
            $pri = intval($cfg['priority'] ?? 10);
            $candidates[] = ['post'=>$p, 'cfg'=>$cfg, 'pri'=>$pri, 'date'=>strtotime($p->post_date_gmt ?: $p->post_date)];
        }

        if (empty($candidates)) return null;

        usort($candidates, function($a,$b){
            if ($a['pri'] === $b['pri']) {
                return ($b['date'] <=> $a['date']); // newer first
            }
            return ($a['pri'] <=> $b['pri']); // lower = higher priority
        });

        return ['post'=>$candidates[0]['post'], 'cfg'=>$candidates[0]['cfg']];
    }

    public static function render_front(){
        if ( is_admin() ) return;
        $picked = self::pick_popup_for_request();
        if ( ! $picked ) return;

        $p = $picked['post'];
        $cfg = $picked['cfg'];

        $payload = [
            'id' => (int)$p->ID,
            'type' => $cfg['type'],
            'image' => esc_url_raw($cfg['image']),
            'link' => esc_url_raw($cfg['link']),
            'title' => wp_kses_post($cfg['title']),
            'text' => wp_kses_post($cfg['text']),
            'coupon' => sanitize_text_field($cfg['coupon']),
            'btn_text' => sanitize_text_field($cfg['btn_text']),
            'btn_url' => esc_url_raw($cfg['btn_url']),
            'delay' => (int)$cfg['delay'],
            'frequency_hours' => (int)$cfg['frequency'],
            'always_show' => ($cfg['always_show'] ?? '0') === '1' ? 1 : 0,
            'priority' => (int)($cfg['priority'] ?? 10),
            'style' => [
                'width' => (int)$cfg['width'],
                'radius' => (int)$cfg['radius'],
                'bg' => $cfg['bg'],
                'accent' => $cfg['accent'],
                'overlay' => (float)$cfg['overlay'],
            ],
        ];
        ?>
        <div class="nikan-popup-root" data-nikan-popup='<?php echo esc_attr(wp_json_encode($payload)); ?>'></div>
        <?php
    }
}

if ( function_exists('nikan_is_pro_active') && nikan_is_pro_active() ) {
    Nikan_Popups_Module::init();
} else {
    // If license is inactive, do not register popups (pro feature).
}
