<?php

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

class AIEO_DMM_Exit_Intent extends AIEO_DMM_Module_Base {

    const OPTION_KEY = 'aieo_dmm_exit_intent';

    public function get_id()       { return 'exit_intent'; }
    public function get_label()    { return __('Exit Intent', 'ai-eshop-optimizer'); }
    public function get_priority() { return 60; }
    public function get_group()    { return 'special_pricing_offers'; }

    public function register_hooks() {
        add_action('wp_ajax_aieo_dmm_exit_intent_save', array($this, 'ajax_save'));

        $s = $this->get_settings();
        if ($s['enabled'] !== 'yes') { return; }
        if ((string) $s['content'] === '' && (string) $s['checkout_content'] === '') { return; }

        
        
        add_action('wp_footer', array($this, 'inject_modal'), 30);
    }

    
    public function get_settings() {
        $stored = get_option(self::OPTION_KEY, null);
        if (!is_array($stored)) {
            $stored = $this->migrate_from_legacy();
        }
        return array_merge(array(
            'enabled'               => 'no',
            'only_checkout'         => 'no',
            'anonymous_only'        => 'no',
            'minimum_time'          => 120,
            'checkout_minimum_time' => 120,
            'data_driven_delay'     => 'no',
            'content'               => '',
            'checkout_content'      => '',
            
            
            
            
            
            'coupon_default'        => '',
            'coupon_checkout'       => '',
            
            
            
            'close_bg'              => '#ffffff',
            'close_text'            => '#1f2937',
            'close_border_color'    => '#d1d5db',
            'close_border_width'    => 1,
            'close_border_radius'   => 4,
        ), $stored);
    }

    
    public static function configured_coupon_codes() {
        $stored = get_option(self::OPTION_KEY, null);
        if (!is_array($stored)) { return array(); }
        $codes = array();
        foreach (array('coupon_default', 'coupon_checkout') as $k) {
            $code = isset($stored[$k]) ? trim(strtolower((string) $stored[$k])) : '';
            if ($code !== '') { $codes[$code] = true; }
        }
        return array_keys($codes);
    }

    
    private function migrate_from_legacy() {
        $patch = array(
            'enabled'               => get_option('exit_intent_offer_active') ? 'yes' : 'no',
            'only_checkout'         => get_option('exit_intent_offer_only_checkout') ? 'yes' : 'no',
            'anonymous_only'        => get_option('exit_intent_offer_anonymous_only') ? 'yes' : 'no',
            'minimum_time'          => max(0, (int) get_option('exit_intent_offer_minimum_time', 120)),
            'checkout_minimum_time' => max(0, (int) get_option('exit_intent_offer_checkout_minimum_time', 120)),
            'content'               => (string) get_option('exit_intent_offer_content', ''),
            'checkout_content'      => (string) get_option('exit_intent_offer_checkout_content', ''),
            
            
            'coupon_default'        => '',
            'coupon_checkout'       => '',
        );
        update_option(self::OPTION_KEY, $patch, false);
        return $patch;
    }

    public function ajax_save() {
        AIEO_DMM::verify_ajax_request();

        $patch = array(
            'enabled'               => !empty($_POST['enabled']) ? 'yes' : 'no',
            'only_checkout'         => !empty($_POST['only_checkout']) ? 'yes' : 'no',
            'anonymous_only'        => !empty($_POST['anonymous_only']) ? 'yes' : 'no',
            'minimum_time'          => isset($_POST['minimum_time']) ? max(0, (int) $_POST['minimum_time']) : 120,
            'checkout_minimum_time' => isset($_POST['checkout_minimum_time']) ? max(0, (int) $_POST['checkout_minimum_time']) : 120,
            'data_driven_delay'     => !empty($_POST['data_driven_delay']) ? 'yes' : 'no',
            'content'               => isset($_POST['content']) ? wp_kses_post(wp_unslash($_POST['content'])) : '',
            'checkout_content'      => isset($_POST['checkout_content']) ? wp_kses_post(wp_unslash($_POST['checkout_content'])) : '',
            'coupon_default'        => isset($_POST['coupon_default'])  ? sanitize_text_field(wp_unslash($_POST['coupon_default']))  : '',
            'coupon_checkout'       => isset($_POST['coupon_checkout']) ? sanitize_text_field(wp_unslash($_POST['coupon_checkout'])) : '',
            'close_bg'              => $this->sanitize_color(wp_unslash($_POST['close_bg']           ?? ''), '#ffffff'),
            'close_text'            => $this->sanitize_color(wp_unslash($_POST['close_text']         ?? ''), '#1f2937'),
            'close_border_color'    => $this->sanitize_color(wp_unslash($_POST['close_border_color'] ?? ''), '#d1d5db'),
            'close_border_width'    => max(0, min(20, (int) (sanitize_text_field( wp_unslash( $_POST['close_border_width'] ) )  ?? 1))),
            'close_border_radius'   => max(0, min(99, (int) (sanitize_text_field( wp_unslash( $_POST['close_border_radius'] ) ) ?? 4))),
        );
        update_option(self::OPTION_KEY, $patch, false);

        wp_send_json_success(array('message' => __('Exit Intent settings saved.', 'ai-eshop-optimizer')));
    }

    
    private function sanitize_color($raw, $default) {
        $raw = trim((string) $raw);
        if ($raw === '') { return $default; }
        if ($raw[0] !== '#') { $raw = '#' . $raw; }
        return preg_match('/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/', $raw) ? $raw : $default;
    }

    
    public function inject_modal() {
        $s = $this->get_settings();

        if (function_exists('is_wc_endpoint_url') && is_wc_endpoint_url('order-received')) { return; }

        $is_checkout = function_exists('is_checkout') && is_checkout();

        if ($s['only_checkout'] === 'yes' && !$is_checkout)             { return; }
        if ($s['anonymous_only'] === 'yes' && is_user_logged_in())      { return; }

        $body = ($is_checkout && (string) $s['checkout_content'] !== '')
            ? (string) $s['checkout_content']
            : (string) $s['content'];
        if ($body === '') { return; }

        $delay_ms = (int) ($is_checkout ? $s['checkout_minimum_time'] : $s['minimum_time']) * 1000;

        
        
        
        
        
        if ( isset( $s['data_driven_delay'] ) && 'yes' === $s['data_driven_delay'] && class_exists( 'AIEO_DMM_Checkout_Timing' ) ) {
            $pid = ( ! $is_checkout && function_exists( 'is_product' ) && is_product() ) ? (int) get_queried_object_id() : 0;
            $rec = (int) AIEO_DMM_Checkout_Timing::recommended_delay_seconds( $pid );
            if ( $rec > 0 ) {
                $delay_ms = max( 10, min( 600, $rec ) ) * 1000;
            }
        }
        
        
        
        $surface = $is_checkout ? 'exit_intent_checkout' : 'exit_intent_default';
        $ajax_url = admin_url('admin-ajax.php');
        ?>
        <style>
            #aieo-exit-intent-modal {
                display: none;
                position: fixed;
                inset: 0;
                width: 100%;
                height: 100%;
                z-index: 100000;
                background-color: rgba(0,0,0,0.7);
            }
            #aieo-exit-intent-modal__panel {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                width: 80%;
                max-width: 500px;
                background: #fff;
                padding: 20px;
                box-shadow: 0 0 10px rgba(0,0,0,0.5);
                box-sizing: border-box;
            }
            #aieo-exit-intent-modal__close {
                text-align: right;
                margin-top: 12px;
            }
            /* Operator-driven close-button skin. Uses high specificity
             * (#id + .class) plus !important on each property so any
             * theme-level button reset still loses to the configured
             * values without us having to ship a separate stylesheet. */
            #aieo-exit-intent-modal #aieo-exit-intent-modal__close-btn {
                background: <?php echo esc_html($s['close_bg']); ?> !important;
                color: <?php echo esc_html($s['close_text']); ?> !important;
                border: <?php echo (int) $s['close_border_width']; ?>px solid <?php echo esc_html($s['close_border_color']); ?> !important;
                border-radius: <?php echo (int) $s['close_border_radius']; ?>px !important;
                padding: 8px 18px;
                font-size: 14px;
                line-height: 1.2;
                cursor: pointer;
            }
        </style>
        <div id="aieo-exit-intent-modal" role="dialog" aria-modal="true" aria-hidden="true">
            <div id="aieo-exit-intent-modal__panel">
                <?php echo wp_kses_post($body); ?>
                <div id="aieo-exit-intent-modal__close">
                    <button type="button" class="button" id="aieo-exit-intent-modal__close-btn"><?php esc_html_e('Close', 'ai-eshop-optimizer'); ?></button>
                </div>
            </div>
        </div>
        <script>
        (function(){
            try { if (sessionStorage.getItem('aieoExitIntentDismissed') === 'true') return; } catch(e) {}
            var minimumTime = <?php echo (int) $delay_ms; ?>;
            var surface     = <?php echo wp_json_encode($surface); ?>;
            var ajaxUrl     = <?php echo wp_json_encode($ajax_url); ?>;

            // Reuse the existing batched reco-events endpoint
            // (`aieo_reco_log_batch`) so exit-intent impressions land in
            // wp_aieo_reco_events alongside product-card impressions —
            // no new ajax handler, no new table. `target_pid:0` is OK
            // for the ei_* event types (validator allows it).
            function logEvent(type){
                try {
                    var fd = new FormData();
                    fd.set('action', 'aieo_reco_log_batch');
                    fd.set('events', JSON.stringify([{
                        type: type,
                        surface: surface,
                        target_pid: 0,
                        anchor_pid: 0,
                        position: 0,
                        ts_offset_ms: 0,
                        event_id: (window.crypto && crypto.randomUUID) ? crypto.randomUUID() : ('ei-' + Date.now() + '-' + Math.random().toString(16).slice(2))
                    }]));
                    if (navigator.sendBeacon) {
                        navigator.sendBeacon(ajaxUrl, fd);
                    } else {
                        fetch(ajaxUrl, { method:'POST', credentials:'same-origin', body: fd, keepalive:true });
                    }
                } catch(e) {}
            }

            function dismiss(){
                var m = document.getElementById('aieo-exit-intent-modal');
                if (m) { m.style.display = 'none'; m.setAttribute('aria-hidden','true'); }
                try { sessionStorage.setItem('aieoExitIntentDismissed','true'); } catch(e) {}
                logEvent('ei_dismiss');
            }

            function arm(){
                setTimeout(function(){
                    var shown = false;
                    document.addEventListener('mouseout', function(event){
                        if (event.toElement === null && event.relatedTarget === null && !shown) {
                            var m = document.getElementById('aieo-exit-intent-modal');
                            if (!m) { return; }
                            m.style.display = 'block';
                            m.setAttribute('aria-hidden','false');
                            shown = true;
                            logEvent('ei_impression');
                        }
                    });
                }, minimumTime);

                var btn = document.getElementById('aieo-exit-intent-modal__close-btn');
                if (btn) { btn.addEventListener('click', dismiss); }
            }

            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', arm);
            } else {
                arm();
            }
        })();
        </script>
        <?php
    }

    public function render_subtab() {
        $s     = $this->get_settings();
        $nonce = wp_create_nonce(AIEO_DMM::NONCE_ACTION);
        $ajax  = admin_url('admin-ajax.php');
        ?>
        <div class="aieo-dmm-section">
            <h2><?php esc_html_e('Exit Intent', 'ai-eshop-optimizer'); ?></h2>
            <p class="description">
                <?php esc_html_e('Show a modal offer when a visitor moves their cursor towards the address bar (exit-intent), after a configurable warm-up delay. Optionally restricted to the checkout page and/or anonymous visitors.', 'ai-eshop-optimizer'); ?>
            </p>

            <form id="aieo-dmm-exit-intent-form" class="aieo-dmm-form aieo-dmm-card">
                <table class="form-table">
                    <tr>
                        <th><?php esc_html_e('Enable', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="enabled" value="1" <?php checked($s['enabled'] === 'yes'); ?>>
                                <?php esc_html_e('Show the exit-intent modal on the storefront.', 'ai-eshop-optimizer'); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e('Only on checkout', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="only_checkout" value="1" <?php checked($s['only_checkout'] === 'yes'); ?>>
                                <?php esc_html_e('Restrict the modal to the checkout page only.', 'ai-eshop-optimizer'); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e('Anonymous visitors only', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="anonymous_only" value="1" <?php checked($s['anonymous_only'] === 'yes'); ?>>
                                <?php esc_html_e('Hide the modal from logged-in customers.', 'ai-eshop-optimizer'); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e('Warm-up delay (storefront)', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <input type="number" name="minimum_time" min="0" step="1" value="<?php echo esc_attr((string) $s['minimum_time']); ?>" style="width:120px;">
                            <span><?php esc_html_e('seconds', 'ai-eshop-optimizer'); ?></span>
                            <p class="description"><?php esc_html_e('Wait this many seconds before arming the exit-intent listener on regular pages.', 'ai-eshop-optimizer'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e('Data-driven delay', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="data_driven_delay" value="1" <?php checked((isset($s['data_driven_delay']) ? $s['data_driven_delay'] : 'no') === 'yes'); ?>>
                                <?php esc_html_e('Override the warm-up with the recommended delay from Checkout Timing (median active time, coupon-excluded) — per product on product pages, overall on checkout. Falls back to the fixed delays above until enough data is collected.', 'ai-eshop-optimizer'); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e('Warm-up delay (checkout)', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <input type="number" name="checkout_minimum_time" min="0" step="1" value="<?php echo esc_attr((string) $s['checkout_minimum_time']); ?>" style="width:120px;">
                            <span><?php esc_html_e('seconds', 'ai-eshop-optimizer'); ?></span>
                            <p class="description"><?php esc_html_e('Same warm-up, but for the checkout page (typically shorter — the customer is already engaged).', 'ai-eshop-optimizer'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e('Default modal content', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <?php
                            wp_editor((string) $s['content'], 'aieo_dmm_exit_intent_content', array(
                                'wpautop'       => true,
                                'media_buttons' => true,
                                'textarea_name' => 'content',
                                'textarea_rows' => 8,
                                'teeny'         => false,
                            ));
                            ?>
                            <p class="description"><?php esc_html_e('Shown on every page where the exit-intent fires (unless overridden by the checkout content below).', 'ai-eshop-optimizer'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e('Default coupon code', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <input type="text" name="coupon_default" value="<?php echo esc_attr((string) $s['coupon_default']); ?>" class="regular-text" autocomplete="off" spellcheck="false">
                            <p class="description"><?php esc_html_e('WooCommerce coupon code embedded in the default modal copy. Required for redemption attribution — leave empty to skip cost tracking on this surface.', 'ai-eshop-optimizer'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e('Checkout modal content', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <?php
                            wp_editor((string) $s['checkout_content'], 'aieo_dmm_exit_intent_checkout_content', array(
                                'wpautop'       => true,
                                'media_buttons' => true,
                                'textarea_name' => 'checkout_content',
                                'textarea_rows' => 8,
                                'teeny'         => false,
                            ));
                            ?>
                            <p class="description"><?php esc_html_e('Optional — overrides the default content when shown on the checkout page.', 'ai-eshop-optimizer'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e('Checkout coupon code', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <input type="text" name="coupon_checkout" value="<?php echo esc_attr((string) $s['coupon_checkout']); ?>" class="regular-text" autocomplete="off" spellcheck="false">
                            <p class="description"><?php esc_html_e('Coupon embedded in the checkout-specific modal. Tracked separately from the default coupon so the report can split storefront vs checkout redemptions.', 'ai-eshop-optimizer'); ?></p>
                        </td>
                    </tr>

                    <tr>
                        <th colspan="2" style="padding-top:24px;">
                            <h3 style="margin:0;"><?php esc_html_e('Close button styling', 'ai-eshop-optimizer'); ?></h3>
                            <p class="description" style="font-weight:400;margin-top:4px;"><?php esc_html_e('Applied via the modal’s inline CSS — overrides any theme button defaults.', 'ai-eshop-optimizer'); ?></p>
                        </th>
                    </tr>
                    <tr>
                        <th><?php esc_html_e('Background colour', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <input type="color" name="close_bg" value="<?php echo esc_attr((string) $s['close_bg']); ?>" style="width:60px;height:32px;padding:0;vertical-align:middle;">
                            <code style="margin-left:8px;"><?php echo esc_html((string) $s['close_bg']); ?></code>
                        </td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e('Text colour', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <input type="color" name="close_text" value="<?php echo esc_attr((string) $s['close_text']); ?>" style="width:60px;height:32px;padding:0;vertical-align:middle;">
                            <code style="margin-left:8px;"><?php echo esc_html((string) $s['close_text']); ?></code>
                        </td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e('Border colour', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <input type="color" name="close_border_color" value="<?php echo esc_attr((string) $s['close_border_color']); ?>" style="width:60px;height:32px;padding:0;vertical-align:middle;">
                            <code style="margin-left:8px;"><?php echo esc_html((string) $s['close_border_color']); ?></code>
                        </td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e('Border width', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <input type="number" name="close_border_width" min="0" max="20" step="1" value="<?php echo esc_attr((string) $s['close_border_width']); ?>" style="width:90px;">
                            <span><?php esc_html_e('px', 'ai-eshop-optimizer'); ?></span>
                            <p class="description"><?php esc_html_e('0 disables the border entirely.', 'ai-eshop-optimizer'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e('Border radius', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <input type="number" name="close_border_radius" min="0" max="99" step="1" value="<?php echo esc_attr((string) $s['close_border_radius']); ?>" style="width:90px;">
                            <span><?php esc_html_e('px', 'ai-eshop-optimizer'); ?></span>
                            <p class="description"><?php esc_html_e('0 = sharp corners; 99 = pill shape.', 'ai-eshop-optimizer'); ?></p>
                        </td>
                    </tr>
                </table>

                <p>
                    <button type="button" class="button button-primary" id="aieo-dmm-ei-save"><?php esc_html_e('Save settings', 'ai-eshop-optimizer'); ?></button>
                    <span id="aieo-dmm-ei-status" style="margin-left:10px;color:#646970;font-size:13px;"></span>
                </p>
            </form>

            <script>
            (function(){
                var btn    = document.getElementById('aieo-dmm-ei-save');
                var form   = document.getElementById('aieo-dmm-exit-intent-form');
                var status = document.getElementById('aieo-dmm-ei-status');
                if (!btn) { return; }
                btn.addEventListener('click', function(){
                    // Push TinyMCE buffer into the underlying <textarea>
                    // before serializing — `wp_editor` content otherwise
                    // lags behind what the operator typed last.
                    if (typeof tinyMCE !== 'undefined' && tinyMCE.triggerSave) { tinyMCE.triggerSave(); }
                    var fd = new FormData(form);
                    fd.set('action', 'aieo_dmm_exit_intent_save');
                    fd.set('nonce',  '<?php echo esc_js($nonce); ?>');
                    status.style.color = '#646970';
                    status.textContent = '<?php echo esc_js(__('Saving…', 'ai-eshop-optimizer')); ?>';
                    fetch('<?php echo esc_js($ajax); ?>', { method:'POST', credentials:'same-origin', body: fd })
                        .then(function(r){ return r.json(); })
                        .then(function(j){
                            if (j && j.success) {
                                status.style.color = '#15803d';
                                status.textContent = j.data.message;
                            } else {
                                status.style.color = '#b91c1c';
                                status.textContent = (j && j.data && j.data.message) || '<?php echo esc_js(__('Save failed.', 'ai-eshop-optimizer')); ?>';
                            }
                        })
                        .catch(function(){
                            status.style.color = '#b91c1c';
                            status.textContent  = '<?php echo esc_js(__('Network error.', 'ai-eshop-optimizer')); ?>';
                        });
                });
            })();
            </script>

            <?php $this->render_report_card(); ?>
        </div>
        <?php
    }

    
    private function render_report_card() {
        global $wpdb;

        $reco_tbl = $wpdb->prefix . 'aieo_reco_events';
        $attr_tbl = $wpdb->prefix . 'aieo_dmm_offer_attributions';

        $window_days = 30;
        $since       = gmdate('Y-m-d H:i:s', time() - $window_days * DAY_IN_SECONDS);

        $by_surface = array(
            'exit_intent_default'  => array('impressions' => 0, 'dismissals' => 0, 'redemptions' => 0, 'cost' => 0.0),
            'exit_intent_checkout' => array('impressions' => 0, 'dismissals' => 0, 'redemptions' => 0, 'cost' => 0.0),
        );

        
        
        $rows = $wpdb->get_results($wpdb->prepare(
            "SELECT surface, event_type, COUNT(*) AS c
             FROM {$reco_tbl}
             WHERE surface IN ('exit_intent_default','exit_intent_checkout')
               AND event_type IN ('ei_impression','ei_dismiss')
               AND ts >= %s
             GROUP BY surface, event_type",
            $since
        ), ARRAY_A);
        if (is_array($rows)) {
            foreach ($rows as $r) {
                $surf = (string) $r['surface'];
                if (!isset($by_surface[$surf])) { continue; }
                $key = $r['event_type'] === 'ei_impression' ? 'impressions' : 'dismissals';
                $by_surface[$surf][$key] = (int) $r['c'];
            }
        }

        
        
        
        
        
        $coupons = self::configured_coupon_codes();
        $coupon_to_surface = array();
        $stored = get_option(self::OPTION_KEY, array());
        $cd = strtolower(trim((string) ($stored['coupon_default']  ?? '')));
        $cc = strtolower(trim((string) ($stored['coupon_checkout'] ?? '')));
        if ($cd !== '') { $coupon_to_surface[$cd] = 'exit_intent_default';  }
        if ($cc !== '') { $coupon_to_surface[$cc] = 'exit_intent_checkout'; }

        if (!empty($coupons)) {
            $placeholders = implode(',', array_fill(0, count($coupons), '%s'));
            $params = array_merge($coupons, array($since));
            
            $sql = "SELECT LOWER(offer_label) AS code,
                           COUNT(*)        AS orders,
                           SUM(actual_cost) AS cost
                    FROM {$attr_tbl}
                    WHERE offer_type = 'exit_intent'
                      AND LOWER(offer_label) IN ({$placeholders})
                      AND fired_at >= %s
                    GROUP BY LOWER(offer_label)";
            $rows = $wpdb->get_results($wpdb->prepare($sql, $params), ARRAY_A);
            if (is_array($rows)) {
                foreach ($rows as $r) {
                    $code = (string) $r['code'];
                    $surf = isset($coupon_to_surface[$code]) ? $coupon_to_surface[$code] : 'exit_intent_default';
                    $by_surface[$surf]['redemptions'] += (int) $r['orders'];
                    $by_surface[$surf]['cost']        += (float) $r['cost'];
                }
            }
        }

        $fmt_money = function($v) {
            return function_exists('wc_price') ? wp_strip_all_tags(wc_price((float) $v)) : number_format((float) $v, 2);
        };
        $rate = function($num, $denom) {
            $denom = (int) $denom;
            return $denom > 0 ? round(($num / $denom) * 100, 1) . '%' : '—';
        };
        ?>
        <div class="aieo-dmm-card" style="margin-top:24px;padding:20px;border:1px solid #c3c4c7;background:#fff;">
            <h3 style="margin-top:0;"><?php esc_html_e('Exit-Intent performance — last 30 days', 'ai-eshop-optimizer'); ?></h3>
            <p class="description" style="margin-top:0;">
                <?php esc_html_e('Impressions and dismissals are read from the shared reco-events table; redemptions + cost from the shared offer-attributions table — same plumbing the rest of AIEO uses, no extra schema.', 'ai-eshop-optimizer'); ?>
            </p>
            <table class="widefat striped" style="max-width:760px;">
                <thead>
                    <tr>
                        <th><?php esc_html_e('Surface', 'ai-eshop-optimizer'); ?></th>
                        <th style="text-align:right;"><?php esc_html_e('Impressions', 'ai-eshop-optimizer'); ?></th>
                        <th style="text-align:right;"><?php esc_html_e('Dismissals', 'ai-eshop-optimizer'); ?></th>
                        <th style="text-align:right;"><?php esc_html_e('Redemptions', 'ai-eshop-optimizer'); ?></th>
                        <th style="text-align:right;"><?php esc_html_e('Conv. rate', 'ai-eshop-optimizer'); ?></th>
                        <th style="text-align:right;"><?php esc_html_e('Total cost', 'ai-eshop-optimizer'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $labels = array(
                        'exit_intent_default'  => __('Storefront', 'ai-eshop-optimizer'),
                        'exit_intent_checkout' => __('Checkout',   'ai-eshop-optimizer'),
                    );
                    $totals = array('impressions' => 0, 'dismissals' => 0, 'redemptions' => 0, 'cost' => 0.0);
                    foreach ($by_surface as $surf => $row) :
                        $totals['impressions'] += $row['impressions'];
                        $totals['dismissals']  += $row['dismissals'];
                        $totals['redemptions'] += $row['redemptions'];
                        $totals['cost']        += $row['cost'];
                    ?>
                        <tr>
                            <td><?php echo esc_html($labels[$surf]); ?></td>
                            <td style="text-align:right;"><?php echo (int) $row['impressions']; ?></td>
                            <td style="text-align:right;"><?php echo (int) $row['dismissals']; ?></td>
                            <td style="text-align:right;"><?php echo (int) $row['redemptions']; ?></td>
                            <td style="text-align:right;"><?php echo esc_html($rate($row['redemptions'], $row['impressions'])); ?></td>
                            <td style="text-align:right;"><?php echo esc_html($fmt_money($row['cost'])); ?></td>
                        </tr>
                    <?php endforeach; ?>
                    <tr style="font-weight:600;background:#f6f7f7;">
                        <td><?php esc_html_e('Total', 'ai-eshop-optimizer'); ?></td>
                        <td style="text-align:right;"><?php echo (int) $totals['impressions']; ?></td>
                        <td style="text-align:right;"><?php echo (int) $totals['dismissals']; ?></td>
                        <td style="text-align:right;"><?php echo (int) $totals['redemptions']; ?></td>
                        <td style="text-align:right;"><?php echo esc_html($rate($totals['redemptions'], $totals['impressions'])); ?></td>
                        <td style="text-align:right;"><?php echo esc_html($fmt_money($totals['cost'])); ?></td>
                    </tr>
                </tbody>
            </table>
            <p class="description" style="margin-top:12px;">
                <?php esc_html_e('“Conv. rate” = redemptions ÷ impressions. Cost is the WC discount each attributed order absorbed (cost_basis = forgone_revenue).', 'ai-eshop-optimizer'); ?>
            </p>

            <?php $this->render_efficacy_timeseries($window_days, $since); ?>
        </div>
        <?php
    }

    
    private function render_efficacy_timeseries($window_days, $since) {
        global $wpdb;

        $reco_tbl = $wpdb->prefix . 'aieo_reco_events';
        $attr_tbl = $wpdb->prefix . 'aieo_dmm_offer_attributions';

        
        
        $buckets = array();
        for ($i = $window_days - 1; $i >= 0; $i--) {
            $buckets[gmdate('Y-m-d', time() - $i * DAY_IN_SECONDS)] = array(
                'impressions' => 0,
                'redemptions' => 0,
            );
        }

        
        
        $rows = $wpdb->get_results($wpdb->prepare(
            "SELECT DATE(ts) AS d, COUNT(*) AS n
             FROM {$reco_tbl}
             WHERE event_type = 'ei_impression'
               AND surface IN ('exit_intent_default','exit_intent_checkout')
               AND ts >= %s
             GROUP BY DATE(ts)",
            $since
        ), ARRAY_A);
        if (is_array($rows)) {
            foreach ($rows as $r) {
                $d = (string) $r['d'];
                if (isset($buckets[$d])) { $buckets[$d]['impressions'] = (int) $r['n']; }
            }
        }

        
        
        $rows = $wpdb->get_results($wpdb->prepare(
            "SELECT DATE(fired_at) AS d, COUNT(*) AS n
             FROM {$attr_tbl}
             WHERE offer_type = 'exit_intent'
               AND fired_at >= %s
             GROUP BY DATE(fired_at)",
            $since
        ), ARRAY_A);
        if (is_array($rows)) {
            foreach ($rows as $r) {
                $d = (string) $r['d'];
                if (isset($buckets[$d])) { $buckets[$d]['redemptions'] = (int) $r['n']; }
            }
        }

        
        
        
        $rates = array();
        foreach ($buckets as $b) {
            $impr = max(0, (int) $b['impressions']);
            $red  = max(0, (int) $b['redemptions']);
            $rates[] = $impr > 0 ? min(100, ($red / $impr) * 100) : 0;
        }

        $sparkline = $this->render_sparkline($rates, 240, 36);
        ?>
        <div class="aieo-dmm-card" style="margin-top:24px;padding:20px;border:1px solid #c3c4c7;background:#fff;">
            <h3 style="margin-top:0;display:flex;align-items:center;gap:16px;flex-wrap:wrap;">
                <span><?php
                    
                    echo esc_html(sprintf(__('Daily efficacy vector — last %d days', 'ai-eshop-optimizer'), $window_days));
                ?></span>
                <span style="font-weight:400;color:#646970;font-size:13px;display:inline-flex;align-items:center;gap:8px;">
                    <?php esc_html_e('Conv. rate trend:', 'ai-eshop-optimizer'); ?>
                    <?php echo $sparkline; ?>
                </span>
            </h3>
            <table class="widefat striped" style="max-width:760px;">
                <thead>
                    <tr>
                        <th><?php esc_html_e('Date', 'ai-eshop-optimizer'); ?></th>
                        <th style="text-align:right;"><?php esc_html_e('Impressions', 'ai-eshop-optimizer'); ?></th>
                        <th style="text-align:right;"><?php esc_html_e('Redemptions', 'ai-eshop-optimizer'); ?></th>
                        <th style="text-align:right;"><?php esc_html_e('Conv. rate', 'ai-eshop-optimizer'); ?></th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($buckets as $date => $b) :
                    $impr = (int) $b['impressions'];
                    $red  = (int) $b['redemptions'];
                    $rate = $impr > 0 ? round(($red / $impr) * 100, 1) . '%' : '—';
                ?>
                    <tr>
                        <td><?php echo esc_html($date); ?></td>
                        <td style="text-align:right;"><?php echo (int) $impr; ?></td>
                        <td style="text-align:right;"><?php echo (int) $red; ?></td>
                        <td style="text-align:right;"><?php echo esc_html($rate); ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <p class="description" style="margin-top:12px;">
                <?php esc_html_e('One row per UTC day. Days with no impressions show conv. rate as “—”. Use this to spot creative fatigue, seasonal swings, and the lift from copy edits.', 'ai-eshop-optimizer'); ?>
            </p>
        </div>
        <?php
    }

    
    private function render_sparkline(array $values, $w = 200, $h = 28) {
        $n = count($values);
        if ($n < 2) {
            return '<svg width="' . (int) $w . '" height="' . (int) $h . '" aria-hidden="true"></svg>';
        }
        $max = 0.0;
        foreach ($values as $v) { if ($v > $max) { $max = (float) $v; } }
        if ($max <= 0) { $max = 1.0; }
        $pad   = 2;
        $iw    = max(1, $w - 2 * $pad);
        $ih    = max(1, $h - 2 * $pad);
        $step  = $iw / ($n - 1);
        $points = array();
        foreach ($values as $i => $v) {
            $x = $pad + $i * $step;
            $y = $pad + $ih - (((float) $v / $max) * $ih);
            $points[] = round($x, 1) . ',' . round($y, 1);
        }
        $polyline = implode(' ', $points);
        return '<svg width="' . (int) $w . '" height="' . (int) $h . '" viewBox="0 0 ' . (int) $w . ' ' . (int) $h . '" aria-hidden="true" style="vertical-align:middle;">'
             . '<polyline fill="none" stroke="#2271b1" stroke-width="1.5" stroke-linejoin="round" stroke-linecap="round" points="' . esc_attr($polyline) . '" />'
             . '</svg>';
    }
}
