<?php

if (!defined('ABSPATH')) {
    exit;
}

class AIEO_DMM_Competitions extends AIEO_DMM_Module_Base {

    const NONCE = 'aieo_competitions';

    public function get_id()       { return 'competitions'; }
    public function get_label()    { return __('Competitions', 'ai-eshop-optimizer'); }
    public function get_priority() { return 46; } 
    public function get_group()    { return 'custom_post_types'; }

    public function is_pro_locked() { return true; }

    public function get_pro_promo() {
        return array(
            'title'       => __('Competitions', 'ai-eshop-optimizer'),
            'description' => __('Run prize competitions and giveaways through your existing Gravity Forms — with a ready-made landing page, desktop/mobile creatives, one-click social share links, and (next) participant tracking, winner selection and profiling insights.', 'ai-eshop-optimizer'),
            'bullets'     => array(
                __('Associate any Gravity Form as the entry form', 'ai-eshop-optimizer'),
                __('Branded landing page via a roosterx pattern + block', 'ai-eshop-optimizer'),
                __('Desktop + mobile creatives, used as the social preview', 'ai-eshop-optimizer'),
                __('Facebook / TikTok / Instagram share links', 'ai-eshop-optimizer'),
                __('Participants, winners and profiling metrics', 'ai-eshop-optimizer'),
            ),
        );
    }

    public function register_hooks() {
        
        
        if (!class_exists('AIEO_Competition_CPT') && defined('AIEO_DIR') && file_exists(AIEO_DIR . 'includes/dmm/competitions/class-aieo-competition-cpt.php')) {
            require_once AIEO_DIR . 'includes/dmm/competitions/class-aieo-competition-cpt.php';
        }
        if (class_exists('AIEO_Competition_CPT')) {
            AIEO_Competition_CPT::register();
        }
        
        
        
        if (!class_exists('AIEO_Competition_Participants') && defined('AIEO_DIR') && file_exists(AIEO_DIR . 'includes/dmm/competitions/class-aieo-competition-participants.php')) {
            require_once AIEO_DIR . 'includes/dmm/competitions/class-aieo-competition-participants.php';
        }
        if (class_exists('AIEO_Competition_Participants')) {
            AIEO_Competition_Participants::register();
        }
        
        if (!class_exists('AIEO_Competition_Analytics') && defined('AIEO_DIR') && file_exists(AIEO_DIR . 'includes/dmm/competitions/class-aieo-competition-analytics.php')) {
            require_once AIEO_DIR . 'includes/dmm/competitions/class-aieo-competition-analytics.php';
        }
        add_action('wp_ajax_aieo_competitions_save', array($this, 'ajax_save'));
        add_action('wp_ajax_aieo_competitions_settings_save', array($this, 'ajax_save_settings'));
        add_action('wp_ajax_aieo_competition_draw_winners', array($this, 'ajax_draw_winners'));
        add_action('wp_ajax_aieo_competition_toggle_winner', array($this, 'ajax_toggle_winner'));
        
        
        
        if (class_exists('AIEO_Competition_Analytics')) {
            add_action(AIEO_Competition_Analytics::STATS_REFRESH_HOOK, array('AIEO_Competition_Analytics', 'refresh_stats_cache'));
            
            
            
            
            add_action(AIEO_Competition_Analytics::STATS_REFRESH_HOOK . '_once', array('AIEO_Competition_Analytics', 'refresh_stats_cache'));
        }
        add_action('wp_ajax_aieo_competitions_refresh_stats', array($this, 'ajax_refresh_stats'));
        add_action('wp_ajax_aieo_competitions_stats_cadence', array($this, 'ajax_save_stats_cadence'));
        
        
        
        add_filter('cron_schedules', array($this, 'ensure_cron_schedules'));
        
        
        
        
        add_action('admin_init', array($this, 'maybe_schedule_stats'));
    }

    
    const STATS_CADENCES = array('off', 'hourly', 'daily', 'weekly', 'monthly');

    
    public static function get_stats_cadence() {
        $s = self::get_settings();
        $c = isset($s['stats_refresh']) ? (string) $s['stats_refresh'] : 'daily';
        return in_array($c, self::STATS_CADENCES, true) ? $c : 'daily';
    }

    
    public function ensure_cron_schedules($schedules) {
        if (!is_array($schedules)) { $schedules = array(); }
        if (!isset($schedules['weekly'])) {
            $schedules['weekly'] = array('interval' => 7 * DAY_IN_SECONDS, 'display' => __('Once Weekly', 'ai-eshop-optimizer'));
        }
        if (!isset($schedules['monthly'])) {
            $schedules['monthly'] = array('interval' => 30 * DAY_IN_SECONDS, 'display' => __('Once Monthly', 'ai-eshop-optimizer'));
        }
        return $schedules;
    }

    
    public function maybe_schedule_stats() {
        if (!class_exists('AIEO_Competition_Analytics')) { return; }
        $hook    = AIEO_Competition_Analytics::STATS_REFRESH_HOOK;
        $current = wp_get_schedule($hook); 
        $cadence = self::get_stats_cadence();

        
        if ('off' === $cadence || !self::competitions_exist()) {
            if (false !== $current) { wp_clear_scheduled_hook($hook); }
            return;
        }

        
        if ($current === $cadence) { return; } 
        if (false !== $current) { wp_clear_scheduled_hook($hook); } 
        wp_schedule_event(time() + 300, $cadence, $hook);
    }

    
    public function ajax_save_stats_cadence() {
        if (!check_ajax_referer(self::NONCE, 'nonce', false)) {
            wp_send_json_error(array('message' => __('Security check failed.', 'ai-eshop-optimizer')));
        }
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('You are not allowed to do this.', 'ai-eshop-optimizer')));
        }
        $cadence = isset($_POST['cadence']) ? sanitize_key(wp_unslash($_POST['cadence'])) : 'daily';
        if (!in_array($cadence, self::STATS_CADENCES, true)) { $cadence = 'daily'; }
        $s = self::get_settings();
        $s['stats_refresh'] = $cadence;
        update_option(self::SETTINGS_OPTION, $s, false);
        $this->maybe_schedule_stats(); 
        wp_send_json_success(array('cadence' => $cadence));
    }

    
    private static function competitions_exist() {
        if (!class_exists('AIEO_Competition_CPT')) { return false; }
        $counts = (array) wp_count_posts(AIEO_Competition_CPT::POST_TYPE);
        foreach (array('publish', 'draft', 'pending', 'future', 'private') as $st) {
            if (!empty($counts[$st])) { return true; }
        }
        return false;
    }

    
    public function ajax_refresh_stats() {
        if (!check_ajax_referer(self::NONCE, 'nonce', false)) {
            wp_send_json_error(array('message' => __('Security check failed.', 'ai-eshop-optimizer')));
        }
        if (!current_user_can('edit_posts') || !class_exists('AIEO_Competition_Analytics')) {
            wp_send_json_error(array('message' => __('Not allowed.', 'ai-eshop-optimizer')));
        }
        $payload = AIEO_Competition_Analytics::refresh_stats_cache(10);
        wp_send_json_success(array('generated_at' => $payload['generated_at']));
    }

    
    public function ajax_draw_winners() {
        if (!check_ajax_referer(self::NONCE, 'nonce', false)) {
            wp_send_json_error(array('message' => __('Security check failed.', 'ai-eshop-optimizer')));
        }
        if (!current_user_can('edit_posts') || !class_exists('AIEO_Competition_Participants')) {
            wp_send_json_error(array('message' => __('Not allowed.', 'ai-eshop-optimizer')));
        }
        $cid   = isset($_POST['competition_id']) ? (int) $_POST['competition_id'] : 0;
        $count = isset($_POST['count']) ? (int) $_POST['count'] : 1;
        if ($cid <= 0) { wp_send_json_error(array('message' => __('Missing competition.', 'ai-eshop-optimizer'))); }
        $winners = AIEO_Competition_Participants::draw_winners($cid, $count);
        wp_send_json_success(array('winners' => self::winners_payload($winners)));
    }

    
    public function ajax_toggle_winner() {
        if (!check_ajax_referer(self::NONCE, 'nonce', false)) {
            wp_send_json_error(array('message' => __('Security check failed.', 'ai-eshop-optimizer')));
        }
        if (!current_user_can('edit_posts') || !class_exists('AIEO_Competition_Participants')) {
            wp_send_json_error(array('message' => __('Not allowed.', 'ai-eshop-optimizer')));
        }
        $pid = isset($_POST['participant_id']) ? (int) $_POST['participant_id'] : 0;
        $on  = !empty($_POST['on']);
        if ($pid <= 0) { wp_send_json_error(array('message' => __('Missing participant.', 'ai-eshop-optimizer'))); }
        AIEO_Competition_Participants::set_winner($pid, $on);
        wp_send_json_success();
    }

    private static function winners_payload($winners) {
        $out = array();
        foreach ((array) $winners as $w) {
            $name = trim((string) ($w->first_name ?? '') . ' ' . (string) ($w->last_name ?? ''));
            $out[] = array('pid' => (int) $w->participant_id, 'name' => $name, 'email' => (string) $w->email);
        }
        return $out;
    }

    const SETTINGS_OPTION = 'aieo_competitions_settings';

    
    public static function get_settings() {
        $s = get_option(self::SETTINGS_OPTION, array());
        return is_array($s) ? $s : array();
    }

    public function enqueue_admin_assets() {
        if (!self::is_aieo_pro_user()) { return; } 
        wp_enqueue_media();
        $handle = 'aieo-competitions-admin';
        
        
        
        $js_rel = 'assets/js/aieo-competitions-admin.js';
        $js_abs = defined('AIEO_DIR') ? AIEO_DIR . $js_rel : '';
        $js_ver = ($js_abs && file_exists($js_abs)) ? (string) filemtime($js_abs) : (defined('AIEO_VERSION') ? AIEO_VERSION : '1.0');
        wp_enqueue_script(
            $handle,
            plugins_url($js_rel, AIEO_FILE),
            array('jquery'),
            $js_ver,
            true
        );
        wp_localize_script($handle, 'aieoCompetitions', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce'   => wp_create_nonce(self::NONCE),
            'i18n'    => array(
                'select' => __('Select image', 'ai-eshop-optimizer'),
                'use'    => __('Use this image', 'ai-eshop-optimizer'),
                'copied' => __('Copied!', 'ai-eshop-optimizer'),
                'saving' => __('Saving…', 'ai-eshop-optimizer'),
                'saved'  => __('Saved.', 'ai-eshop-optimizer'),
                'noname' => __('Please enter a competition name.', 'ai-eshop-optimizer'),
                'refreshing' => __('Refreshing…', 'ai-eshop-optimizer'),
            ),
        ));
    }

    public function render_subtab() {
        
        
        
        $this->maybe_schedule_stats();
        echo '<h2>' . esc_html__('Competitions', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description" style="max-width:760px;">' . esc_html__('Create a competition, associate its Gravity Form entry form, add a short description and desktop/mobile creatives, then share it. Each competition becomes a landing page you build with the “Competition” pattern (it inherits these details automatically).', 'ai-eshop-optimizer') . '</p>';

        
        echo '<div class="card" style="max-width:100%;padding:16px 20px;">';
        echo '<h3 style="margin-top:0;">' . esc_html__('New competition', 'ai-eshop-optimizer') . '</h3>';
        echo '<form id="aieo-comp-create" onsubmit="return false;">';
        echo '<input type="hidden" id="aieo-comp-post-id" value="0">';
        echo '<table class="form-table"><tbody>';
        echo '<tr><th><label for="aieo-comp-name">' . esc_html__('Name', 'ai-eshop-optimizer') . '</label></th><td><input type="text" id="aieo-comp-name" class="regular-text" placeholder="' . esc_attr__('e.g. Summer Giveaway 2026', 'ai-eshop-optimizer') . '"></td></tr>';
        echo '<tr><th><label>' . esc_html__('Gravity Form', 'ai-eshop-optimizer') . '</label></th><td>';
        echo AIEO_Competition_CPT::gf_form_select('aieo-comp-gf', 0); 
        echo '<p class="description">' . esc_html__('The entry form participants submit through.', 'ai-eshop-optimizer') . '</p></td></tr>';
        echo '<tr><th><label for="aieo-comp-desc">' . esc_html__('Short description', 'ai-eshop-optimizer') . '</label></th><td><textarea id="aieo-comp-desc" rows="3" class="large-text"></textarea></td></tr>';
        echo '<tr><th>' . esc_html__('Creatives', 'ai-eshop-optimizer') . '</th><td><div style="display:flex;gap:24px;flex-wrap:wrap;">';
        $this->image_field('desktop', __('Desktop image', 'ai-eshop-optimizer'));
        $this->image_field('mobile', __('Mobile image', 'ai-eshop-optimizer'));
        echo '</div></td></tr>';
        echo '<tr><th>' . esc_html__('Schedule', 'ai-eshop-optimizer') . '</th><td>';
        echo '<label style="margin-right:18px;">' . esc_html__('Starts', 'ai-eshop-optimizer') . ' <input type="datetime-local" id="aieo-comp-start"></label>';
        echo '<label style="margin-right:18px;">' . esc_html__('Ends', 'ai-eshop-optimizer') . ' <input type="datetime-local" id="aieo-comp-end"></label>';
        echo '<label>' . esc_html__('Winners announced', 'ai-eshop-optimizer') . ' <input type="datetime-local" id="aieo-comp-announce"></label>';
        echo '<p class="description">' . esc_html__('Optional. Visitors see a “coming soon” notice before the start and an “ended” message after the end; shop managers always see the live form. Leave start/end empty for an always-open competition. “Winners announced” is the date shown to entrants (and used by the Events timeline).', 'ai-eshop-optimizer') . '</p></td></tr>';
        
        echo '<tr><th><label for="aieo-comp-brands">' . esc_html__('Brands', 'ai-eshop-optimizer') . '</label></th><td>';
        echo '<select id="aieo-comp-brands" multiple class="aieo-dmm-brand-select regular-text" style="width:100%;max-width:520px;"></select>';
        echo '<p class="description">' . esc_html__('Optional — associate brands so you can later monitor the products they pull.', 'ai-eshop-optimizer') . '</p></td></tr>';
        echo '<tr><th><label for="aieo-comp-categories">' . esc_html__('Categories', 'ai-eshop-optimizer') . '</label></th><td>';
        echo '<select id="aieo-comp-categories" multiple class="aieo-dmm-category-select regular-text" style="width:100%;max-width:520px;"></select>';
        echo '<p class="description">' . esc_html__('Optional — associate product categories.', 'ai-eshop-optimizer') . '</p></td></tr>';
        if (class_exists('AIEO_DMM_Product_Picker')) {
            echo '<tr><th>' . esc_html__('Products', 'ai-eshop-optimizer') . '</th><td>';
            echo AIEO_DMM_Product_Picker::render_field(array( 
                'name'       => 'comp_products',
                'mode'       => 'include',
                'selected'   => array(),
                'help'       => __('Optional — specific products associated with this competition (to monitor their pull).', 'ai-eshop-optimizer'),
                'empty_text' => __('No products associated.', 'ai-eshop-optimizer'),
            ));
            echo '</td></tr>';
        }
        $cur = function_exists('get_woocommerce_currency_symbol') ? get_woocommerce_currency_symbol() : '';
        echo '<tr><th><label for="aieo-comp-winners">' . esc_html__('Winners & prize', 'ai-eshop-optimizer') . '</label></th><td>';
        echo '<label style="margin-right:18px;">' . esc_html__('Number of winners', 'ai-eshop-optimizer') . ' <input type="number" min="0" step="1" id="aieo-comp-winners" style="width:90px;"></label>';
        echo '<label>' . esc_html(trim(sprintf(__('Prize value per winner %s', 'ai-eshop-optimizer'), $cur !== '' ? '(' . $cur . ')' : ''))) . ' <input type="number" min="0" step="0.01" id="aieo-comp-prize" style="width:120px;"></label>';
        echo '<p class="description">' . esc_html__('e.g. 3 winners, 50 each → total prize pool 150. Use the prize value when winners get a bag of products rather than one SKU.', 'ai-eshop-optimizer') . '</p></td></tr>';
        echo '</tbody></table>';
        echo '<p><button type="submit" class="button button-primary" id="aieo-comp-create-btn">' . esc_html__('Create competition', 'ai-eshop-optimizer') . '</button> <span id="aieo-comp-create-status" style="margin-left:10px;color:#646970;"></span></p>';
        echo '</form>';
        echo '</div>';

        
        
        
        
        $stats_cache = class_exists('AIEO_Competition_Analytics') ? AIEO_Competition_Analytics::get_cached_stats() : null;

        
        $comps = get_posts(array(
            'post_type'   => AIEO_Competition_CPT::POST_TYPE,
            'post_status' => array('publish', 'draft', 'pending', 'future'),
            'numberposts' => 200,
            'orderby'     => 'date',
            'order'       => 'DESC',
        ));
        echo '<h3 style="margin-top:28px;">' . esc_html__('Your competitions', 'ai-eshop-optimizer') . '</h3>';
        if (empty($comps)) {
            echo '<p>' . esc_html__('No competitions yet — create one above.', 'ai-eshop-optimizer') . '</p>';
        } else {
            
            
            $rev_map = ($stats_cache && isset($stats_cache['revenue_by_competition'])) ? (array) $stats_cache['revenue_by_competition'] : array();
            $cur     = function_exists('get_woocommerce_currency_symbol') ? get_woocommerce_currency_symbol() : '';
            echo '<table class="wp-list-table widefat fixed striped"><thead><tr>';
            echo '<th>' . esc_html__('Name', 'ai-eshop-optimizer') . '</th><th>' . esc_html__('Form', 'ai-eshop-optimizer') . '</th><th>' . esc_html__('Status', 'ai-eshop-optimizer') . '</th><th>' . esc_html__('Schedule', 'ai-eshop-optimizer') . '</th><th>' . esc_html__('Entries', 'ai-eshop-optimizer') . '</th><th title="' . esc_attr__('Lifetime order revenue from this competition’s entrants', 'ai-eshop-optimizer') . '">' . esc_html__('Income', 'ai-eshop-optimizer') . '</th><th>' . esc_html__('Page', 'ai-eshop-optimizer') . '</th><th>' . esc_html__('Share', 'ai-eshop-optimizer') . '</th>';
            echo '</tr></thead><tbody>';
            foreach ($comps as $c) {
                $gf_id   = (int) get_post_meta($c->ID, AIEO_Competition_CPT::META_GF, true);
                $edit    = get_edit_post_link($c->ID);
                $view    = get_permalink($c->ID);
                $links   = AIEO_Competition_CPT::share_links($c->ID);
                echo '<tr>';
                echo '<td><strong><a href="' . esc_url($edit) . '">' . esc_html(get_the_title($c) ?: __('(untitled)', 'ai-eshop-optimizer')) . '</a></strong></td>';
                echo '<td>' . ($gf_id ? '#' . (int) $gf_id : '<span style="color:#b32d2e;">' . esc_html__('— none —', 'ai-eshop-optimizer') . '</span>') . '</td>';
                $sstate = class_exists('AIEO_Competition_CPT') ? AIEO_Competition_CPT::schedule_state($c->ID) : 'live';
                $sstate_labels = array('before' => __('upcoming', 'ai-eshop-optimizer'), 'live' => __('live', 'ai-eshop-optimizer'), 'ended' => __('ended', 'ai-eshop-optimizer'));
                echo '<td>' . esc_html(get_post_status($c)) . ' <span style="color:#646970;font-size:12px;">· ' . esc_html(isset($sstate_labels[$sstate]) ? $sstate_labels[$sstate] : $sstate) . '</span></td>';
                $start_disp = AIEO_Competition_CPT::fmt_dt(get_post_meta($c->ID, AIEO_Competition_CPT::META_START, true));
                $end_disp   = AIEO_Competition_CPT::fmt_dt(get_post_meta($c->ID, AIEO_Competition_CPT::META_END, true));
                if ($start_disp === '' && $end_disp === '') {
                    $sched_html = '<span style="color:#646970;">' . esc_html__('Always open', 'ai-eshop-optimizer') . '</span>';
                } else {
                    $sched_html = esc_html__('Starts', 'ai-eshop-optimizer') . ': ' . esc_html($start_disp !== '' ? $start_disp : '—')
                        . '<br>' . esc_html__('Ends', 'ai-eshop-optimizer') . ': ' . esc_html($end_disp !== '' ? $end_disp : '—');
                }
                echo '<td style="font-size:12px;line-height:1.5;white-space:nowrap;">' . $sched_html . '</td>'; 
                $m = class_exists('AIEO_Competition_Participants') ? AIEO_Competition_Participants::metrics($c->ID) : array('entries' => 0, 'confirmed' => 0, 'pending' => 0);
                echo '<td>' . (int) $m['entries'] . ' <span style="color:#646970;font-size:12px;">(' . (int) $m['confirmed'] . ' ' . esc_html__('confirmed', 'ai-eshop-optimizer') . ((int) $m['pending'] > 0 ? ', ' . (int) $m['pending'] . ' ' . esc_html__('pending', 'ai-eshop-optimizer') : '') . ')</span></td>';
                $inc = isset($rev_map[$c->ID]) ? $rev_map[$c->ID] : null;
                if ($inc && $inc['revenue'] > 0) {
                    echo '<td style="white-space:nowrap;"><strong>' . esc_html($cur . number_format_i18n($inc['revenue'], 2)) . '</strong> <span style="color:#646970;font-size:12px;">(' . (int) $inc['converting'] . ' ' . esc_html(_n('buyer', 'buyers', (int) $inc['converting'], 'ai-eshop-optimizer')) . ')</span></td>';
                } else {
                    echo '<td style="color:#646970;">' . (empty($rev_map) ? '<span title="' . esc_attr__('Order analytics not available yet.', 'ai-eshop-optimizer') . '">—</span>' : '—') . '</td>';
                }
                echo '<td style="white-space:nowrap;"><a href="' . esc_url($edit) . '">' . esc_html__('Edit', 'ai-eshop-optimizer') . '</a> · <a href="' . esc_url($view) . '" target="_blank" rel="noopener">' . esc_html__('View', 'ai-eshop-optimizer') . '</a></td>';
                echo '<td style="white-space:nowrap;">';
                foreach ($links as $net => $url) {
                    if ($url === '') { continue; }
                    echo '<button type="button" class="button-link aieo-comp-copy" data-url="' . esc_attr($url) . '" title="' . esc_attr(sprintf(__('Copy %s share link', 'ai-eshop-optimizer'), ucfirst($net))) . '" style="margin-right:8px;text-transform:capitalize;">' . esc_html($net) . '</button>';
                }
                echo '</td>';
                echo '</tr>';
            }
            echo '</tbody></table>';
        }

        
        if (class_exists('AIEO_Competition_Analytics')) {
            
            
            $agg  = ($stats_cache && isset($stats_cache['aggregate'])) ? (array) $stats_cache['aggregate'] : null;
            $gen  = ($stats_cache && !empty($stats_cache['generated_at'])) ? (string) $stats_cache['generated_at'] : '';
            $asof = '';
            if ($gen !== '') {
                
                $asof = sprintf(__('updated %s ago', 'ai-eshop-optimizer'), human_time_diff(strtotime($gen . ' UTC'), current_time('timestamp', true)));
            }
            $cadence  = self::get_stats_cadence();
            $cad_opts = array(
                'off'     => __('Off', 'ai-eshop-optimizer'),
                'hourly'  => __('Hourly', 'ai-eshop-optimizer'),
                'daily'   => __('Daily', 'ai-eshop-optimizer'),
                'weekly'  => __('Weekly', 'ai-eshop-optimizer'),
                'monthly' => __('Monthly', 'ai-eshop-optimizer'),
            );
            $cad_select = '<select id="aieo-comp-stats-cadence" style="font-size:12px;height:26px;padding:0 4px;">';
            foreach ($cad_opts as $val => $lbl) {
                $cad_select .= '<option value="' . esc_attr($val) . '"' . selected($cadence, $val, false) . '>' . esc_html($lbl) . '</option>';
            }
            $cad_select .= '</select>';
            echo '<h3 style="margin-top:28px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;">'
                . esc_html__('Insights', 'ai-eshop-optimizer')
                . ' <button type="button" class="button button-small" id="aieo-comp-refresh-stats">' . esc_html__('Refresh', 'ai-eshop-optimizer') . '</button>'
                . ' <label style="font-size:12px;font-weight:400;color:#646970;display:inline-flex;align-items:center;gap:5px;">' . esc_html__('Auto-refresh', 'ai-eshop-optimizer') . ' ' . $cad_select . '</label>' 
                . ' <span id="aieo-comp-stats-asof" style="color:#646970;font-size:12px;font-weight:400;">' . esc_html($asof) . '</span>'
                . '</h3>';
            echo '<div class="card" id="aieo-comp-insights" data-stats="' . ($agg ? 'ready' : 'empty') . '" style="max-width:100%;padding:16px 20px;">';
            if (!$agg) {
                echo '<p class="description" id="aieo-comp-stats-preparing">' . esc_html__('Preparing insights… this runs in the background and can take a few seconds the first time. The panel refreshes automatically when it’s ready.', 'ai-eshop-optimizer') . '</p>';
            } else {
                $cur = function_exists('get_woocommerce_currency_symbol') ? get_woocommerce_currency_symbol() : '';
                $pct = !empty($agg['unique_emails']) ? round(100 * $agg['identified'] / $agg['unique_emails'], 1) : 0;
                echo '<div style="display:flex;gap:28px;flex-wrap:wrap;margin-bottom:8px;">';
                echo $this->stat_tile(__('Total entries', 'ai-eshop-optimizer'), number_format_i18n((int) $agg['total_participants']));
                echo $this->stat_tile(__('Unique people', 'ai-eshop-optimizer'), number_format_i18n((int) $agg['unique_emails']));
                echo $this->stat_tile(__('Existing customers', 'ai-eshop-optimizer'), number_format_i18n((int) $agg['identified']) . ' (' . esc_html((string) $pct) . '%)');
                echo $this->stat_tile(__('Confirmed', 'ai-eshop-optimizer'), number_format_i18n((int) $agg['confirmed']));
                if (!empty($agg['has_order_data'])) {
                    echo $this->stat_tile(__('Entrants who ordered', 'ai-eshop-optimizer'), number_format_i18n((int) $agg['converting_entrants']));
                    echo $this->stat_tile(__('Revenue from entrants', 'ai-eshop-optimizer'), $cur . number_format_i18n((float) $agg['entrant_revenue'], 2));
                }
                echo '</div>';
                if (!empty($agg['top_participants'])) {
                    echo '<h4 style="margin:14px 0 6px;">' . esc_html__('Top participants by lifetime value', 'ai-eshop-optimizer') . '</h4>';
                    echo '<table class="wp-list-table widefat striped" style="max-width:760px;"><thead><tr>';
                    echo '<th>' . esc_html__('Customer', 'ai-eshop-optimizer') . '</th><th>' . esc_html__('Competitions entered', 'ai-eshop-optimizer') . '</th><th>' . esc_html__('Wins', 'ai-eshop-optimizer') . '</th><th>' . esc_html__('Lifetime value', 'ai-eshop-optimizer') . '</th>';
                    echo '</tr></thead><tbody>';
                    foreach ($agg['top_participants'] as $tp) {
                        $tp = (object) $tp;
                        echo '<tr><td>' . esc_html((string) $tp->email) . '</td><td>' . (int) $tp->entries . '</td><td>' . (int) $tp->wins . '</td><td>' . esc_html($cur . number_format_i18n((float) $tp->ltv_total, 2)) . '</td></tr>';
                    }
                    echo '</tbody></table>';
                } elseif (empty($agg['has_ci'])) {
                    echo '<p class="description">' . esc_html__('Top-participant ranking by lifetime value appears once Customer Intelligence data is built.', 'ai-eshop-optimizer') . '</p>';
                }
            }
            echo '</div>';
        }

        
        $cset        = self::get_settings();
        $msg_soon    = isset($cset['msg_soon'])     ? (string) $cset['msg_soon']     : '';
        $msg_ended   = isset($cset['msg_ended'])    ? (string) $cset['msg_ended']    : '';
        $msg_announce = isset($cset['msg_announce']) ? (string) $cset['msg_announce'] : '';
        echo '<h3 style="margin-top:28px;">' . esc_html__('Page messages', 'ai-eshop-optimizer') . '</h3>';
        echo '<div class="card" style="max-width:100%;padding:16px 20px;">';
        echo '<p class="description">' . esc_html__('Shown on the competition page to visitors. These apply to ALL competitions. Leave a field empty to use the built-in (translatable) default.', 'ai-eshop-optimizer') . '</p>';
        echo '<table class="form-table"><tbody>';
        echo '<tr><th><label for="aieo-comp-msg-soon">' . esc_html__('“Coming soon” message', 'ai-eshop-optimizer') . '</label></th><td>';
        echo '<textarea id="aieo-comp-msg-soon" rows="2" class="large-text">' . esc_textarea($msg_soon) . '</textarea>';
        echo '<p class="description">' . esc_html__('Shown before a competition starts. Use %s where the start date should appear (optional).', 'ai-eshop-optimizer') . '</p></td></tr>';
        echo '<tr><th><label for="aieo-comp-msg-ended">' . esc_html__('“Ended” message', 'ai-eshop-optimizer') . '</label></th><td>';
        echo '<textarea id="aieo-comp-msg-ended" rows="2" class="large-text">' . esc_textarea($msg_ended) . '</textarea>';
        echo '<p class="description">' . esc_html__('Shown after a competition ends.', 'ai-eshop-optimizer') . '</p></td></tr>';
        echo '<tr><th><label for="aieo-comp-msg-announce">' . esc_html__('“Winners announced on” message', 'ai-eshop-optimizer') . '</label></th><td>';
        echo '<textarea id="aieo-comp-msg-announce" rows="2" class="large-text">' . esc_textarea($msg_announce) . '</textarea>';
        echo '<p class="description">' . esc_html__('Shown while the winners are still to be revealed, when a competition has a “Winners announced” date set. Use %s where the date should appear.', 'ai-eshop-optimizer') . '</p></td></tr>';
        
        
        $col_live   = (isset($cset['color_live'])   && $cset['color_live']   !== '') ? (string) $cset['color_live']   : '#22c55e';
        $col_ended  = (isset($cset['color_ended'])  && $cset['color_ended']  !== '') ? (string) $cset['color_ended']  : '#ef4444';
        $col_before = (isset($cset['color_before']) && $cset['color_before'] !== '') ? (string) $cset['color_before'] : '#f59e0b';
        echo '<tr><th>' . esc_html__('Status badge colours', 'ai-eshop-optimizer') . '</th><td>';
        echo '<p class="description" style="margin-top:0;">' . esc_html__('Base colour of the glass status badge shown over each competition card (a translucency is applied automatically).', 'ai-eshop-optimizer') . '</p>';
        echo '<label style="display:inline-flex;align-items:center;gap:6px;margin-right:18px;">' . esc_html__('Active', 'ai-eshop-optimizer') . ' <input type="color" id="aieo-comp-color-live" value="' . esc_attr($col_live) . '"></label>';
        echo '<label style="display:inline-flex;align-items:center;gap:6px;margin-right:18px;">' . esc_html__('Ended', 'ai-eshop-optimizer') . ' <input type="color" id="aieo-comp-color-ended" value="' . esc_attr($col_ended) . '"></label>';
        echo '<label style="display:inline-flex;align-items:center;gap:6px;">' . esc_html__('Coming soon', 'ai-eshop-optimizer') . ' <input type="color" id="aieo-comp-color-before" value="' . esc_attr($col_before) . '"></label>';
        echo '</td></tr>';
        echo '</tbody></table>';
        echo '<p><button type="button" class="button" id="aieo-comp-settings-save">' . esc_html__('Save settings', 'ai-eshop-optimizer') . '</button> <span id="aieo-comp-settings-status" style="margin-left:10px;color:#646970;"></span></p>';
        echo '</div>';
    }

    public function ajax_save_settings() {
        if (!check_ajax_referer(self::NONCE, 'nonce', false)) {
            wp_send_json_error(array('message' => __('Security check failed.', 'ai-eshop-optimizer')));
        }
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('You are not allowed to do this.', 'ai-eshop-optimizer')));
        }
        $ended    = isset($_POST['msg_ended'])    ? sanitize_textarea_field(wp_unslash($_POST['msg_ended']))    : '';
        $soon     = isset($_POST['msg_soon'])     ? sanitize_textarea_field(wp_unslash($_POST['msg_soon']))     : '';
        $announce = isset($_POST['msg_announce']) ? sanitize_textarea_field(wp_unslash($_POST['msg_announce'])) : '';
        $col_live   = isset($_POST['color_live'])   ? (string) sanitize_hex_color(wp_unslash($_POST['color_live']))   : '';
        $col_ended  = isset($_POST['color_ended'])  ? (string) sanitize_hex_color(wp_unslash($_POST['color_ended']))  : '';
        $col_before = isset($_POST['color_before']) ? (string) sanitize_hex_color(wp_unslash($_POST['color_before'])) : '';
        
        
        $saved = array_merge(self::get_settings(), array(
            'msg_soon' => $soon, 'msg_ended' => $ended, 'msg_announce' => $announce,
            'color_live' => $col_live, 'color_ended' => $col_ended, 'color_before' => $col_before,
        ));
        update_option(self::SETTINGS_OPTION, $saved, false);
        wp_send_json_success(array('saved' => true));
    }

    
    private function stat_tile($label, $value) {
        return '<div style="min-width:120px;"><div style="font-size:22px;font-weight:600;line-height:1.2;">' . esc_html((string) $value) . '</div>'
            . '<div style="color:#646970;font-size:12px;">' . esc_html((string) $label) . '</div></div>';
    }

    private function image_field($which, $label) {
        echo '<div class="aieo-comp-image-field" data-which="' . esc_attr($which) . '" style="flex:1;min-width:200px;">';
        echo '<label><strong>' . esc_html($label) . '</strong></label><br>';
        echo '<img class="aieo-comp-image-preview" src="" style="max-width:100%;height:auto;border:1px solid #dcdcde;border-radius:6px;display:none;"><br>';
        echo '<input type="hidden" class="aieo-comp-image-id" value="0">';
        echo '<button type="button" class="button aieo-comp-image-select">' . esc_html__('Select image', 'ai-eshop-optimizer') . '</button> ';
        echo '<button type="button" class="button-link aieo-comp-image-remove" style="display:none;">' . esc_html__('Remove', 'ai-eshop-optimizer') . '</button>';
        echo '</div>';
    }

    public function ajax_save() {
        if (!check_ajax_referer(self::NONCE, 'nonce', false)) {
            wp_send_json_error(array('message' => __('Security check failed.', 'ai-eshop-optimizer')));
        }
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('You are not allowed to do this.', 'ai-eshop-optimizer')));
        }
        if (!class_exists('AIEO_Competition_CPT')) {
            wp_send_json_error(array('message' => __('Competitions are unavailable.', 'ai-eshop-optimizer')));
        }
        $post_id = isset($_POST['post_id']) ? (int) $_POST['post_id'] : 0;
        $name    = isset($_POST['name']) ? sanitize_text_field(wp_unslash($_POST['name'])) : '';
        if ($name === '') {
            wp_send_json_error(array('message' => __('Please enter a competition name.', 'ai-eshop-optimizer')));
        }
        $gf    = isset($_POST['gf_id']) ? (int) $_POST['gf_id'] : 0;
        $desc  = isset($_POST['short_desc']) ? sanitize_textarea_field(wp_unslash($_POST['short_desc'])) : '';
        $img_d = isset($_POST['img_desktop']) ? (int) $_POST['img_desktop'] : 0;
        $img_m = isset($_POST['img_mobile']) ? (int) $_POST['img_mobile'] : 0;
        $start = isset($_POST['start']) ? sanitize_text_field(wp_unslash($_POST['start'])) : '';
        $end   = isset($_POST['end'])   ? sanitize_text_field(wp_unslash($_POST['end']))   : '';
        $announce = isset($_POST['announce']) ? sanitize_text_field(wp_unslash($_POST['announce'])) : '';

        $brands     = isset($_POST['brands'])     ? array_map('intval', (array) wp_unslash($_POST['brands']))     : array();
        $categories = isset($_POST['categories']) ? array_map('intval', (array) wp_unslash($_POST['categories'])) : array();
        $products   = class_exists('AIEO_DMM_Product_Picker')
            ? AIEO_DMM_Product_Picker::roll_up_to_parents(AIEO_DMM_Product_Picker::collect_ids('comp_products'))
            : (isset($_POST['comp_products']) ? array_map('intval', (array) wp_unslash($_POST['comp_products'])) : array());
        $winners    = isset($_POST['winners_count']) ? (int) $_POST['winners_count'] : 0;
        $prize      = isset($_POST['prize_value'])   ? (float) $_POST['prize_value']   : 0;

        $args = array(
            'post_type'   => AIEO_Competition_CPT::POST_TYPE,
            'post_title'  => $name,
            'post_status' => 'publish',
        );
        if ($post_id > 0) {
            $args['ID'] = $post_id;
            $res = wp_update_post($args, true);
        } else {
            $res = wp_insert_post($args, true);
        }
        if (is_wp_error($res)) {
            wp_send_json_error(array('message' => $res->get_error_message()));
        }
        $post_id = (int) $res;
        AIEO_Competition_CPT::persist_fields($post_id, $gf, $desc, $img_d, $img_m, $start, $end, $brands, $categories, $products, $winners, $prize, $announce);

        wp_send_json_success(array(
            'post_id'  => $post_id,
            'title'    => get_the_title($post_id),
            'edit_url' => get_edit_post_link($post_id, 'raw'),
            'view_url' => get_permalink($post_id),
            'gf_id'    => $gf,
            'status'   => get_post_status($post_id),
            'share'    => AIEO_Competition_CPT::share_links($post_id),
        ));
    }
}
