<?php
if (!defined('ABSPATH')) die('Restricted Access');

/**
 * World-class growth and safety tools for AI Flash Tune.
 *
 * This layer provides the foundations for setup/onboarding, weekly summaries,
 * client reports, safe apply/rollback, product copy revision history, agency
 * mode, WooCommerce email integration, and A/B test idea generation.
 */
class AIFLT_World_Class_Tools {

    const SETTINGS_OPTION = 'aiflt_world_class_settings';
    const CRON_HOOK = 'aiflt_weekly_summary_email_event';

    public static function init() {
        add_action('admin_post_aiflt_save_world_class_settings', [__CLASS__, 'handle_save_settings']);
        add_action('admin_post_aiflt_export_client_report', [__CLASS__, 'handle_export_client_report']);
        add_action('admin_post_aiflt_send_test_weekly_summary', [__CLASS__, 'handle_send_test_weekly_summary']);
        add_action('admin_post_aiflt_generate_ab_test_ideas', [__CLASS__, 'handle_generate_ab_test_ideas']);
        add_action('admin_post_aiflt_mark_setup_step', [__CLASS__, 'handle_mark_setup_step']);
        add_action('admin_post_aiflt_rollback_change', [__CLASS__, 'handle_rollback_change']);
        add_action('admin_post_aiflt_restore_product_revision', [__CLASS__, 'handle_restore_product_revision']);
        add_action(self::CRON_HOOK, [__CLASS__, 'send_weekly_summary_email']);
    }

    public static function maybe_create_tables() {
        global $wpdb;
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        $charset_collate = $wpdb->get_charset_collate();

        $change_table = $wpdb->prefix . 'aiflt_change_log';
        $sql_change = "CREATE TABLE {$change_table} (
            id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            change_type VARCHAR(80) NOT NULL,
            object_type VARCHAR(80) DEFAULT NULL,
            object_id BIGINT(20) DEFAULT NULL,
            label VARCHAR(255) DEFAULT NULL,
            before_data LONGTEXT NULL,
            after_data LONGTEXT NULL,
            source VARCHAR(80) DEFAULT 'manual',
            status VARCHAR(30) DEFAULT 'applied',
            created_by BIGINT(20) DEFAULT NULL,
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            reverted_at DATETIME NULL,
            PRIMARY KEY (id),
            KEY change_type (change_type),
            KEY object_type (object_type),
            KEY object_id (object_id),
            KEY status (status),
            KEY created_at (created_at)
        ) {$charset_collate};";
        dbDelta($sql_change);

        $revision_table = $wpdb->prefix . 'aiflt_product_copy_revisions';
        $sql_revision = "CREATE TABLE {$revision_table} (
            id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            product_id BIGINT(20) NOT NULL,
            revision_label VARCHAR(255) DEFAULT NULL,
            before_title TEXT NULL,
            before_short_description LONGTEXT NULL,
            before_description LONGTEXT NULL,
            after_title TEXT NULL,
            after_short_description LONGTEXT NULL,
            after_description LONGTEXT NULL,
            ai_action_key VARCHAR(120) DEFAULT NULL,
            source VARCHAR(80) DEFAULT 'manual',
            status VARCHAR(30) DEFAULT 'draft',
            created_by BIGINT(20) DEFAULT NULL,
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            applied_at DATETIME NULL,
            reverted_at DATETIME NULL,
            PRIMARY KEY (id),
            KEY product_id (product_id),
            KEY status (status),
            KEY created_at (created_at)
        ) {$charset_collate};";
        dbDelta($sql_revision);

        $ideas_table = $wpdb->prefix . 'aiflt_ab_test_ideas';
        $sql_ideas = "CREATE TABLE {$ideas_table} (
            id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            area VARCHAR(80) NOT NULL,
            title VARCHAR(255) NOT NULL,
            hypothesis TEXT NULL,
            metric VARCHAR(255) DEFAULT NULL,
            impact VARCHAR(30) DEFAULT 'medium',
            confidence VARCHAR(30) DEFAULT 'medium',
            effort VARCHAR(30) DEFAULT 'medium',
            status VARCHAR(30) DEFAULT 'idea',
            source VARCHAR(80) DEFAULT 'local',
            created_by BIGINT(20) DEFAULT NULL,
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY area (area),
            KEY status (status),
            KEY created_at (created_at)
        ) {$charset_collate};";
        dbDelta($sql_ideas);
    }

    public static function get_settings() {
        $defaults = [
            'setup_complete' => '0',
            'agency_mode' => '0',
            'white_label_enabled' => '0',
            'agency_name' => '',
            'client_name' => '',
            'report_logo_url' => '',
            'weekly_email_enabled' => '0',
            'weekly_email_to' => get_option('admin_email'),
            'weekly_email_day' => 'monday',
            'weekly_email_hour' => '9',
            'woocommerce_email_style' => '1',
            'auto_capture_before_after' => '1',
            'safe_apply_required' => '1',
            'client_report_sections' => ['summary', 'funnel', 'products', 'carts', 'checkout', 'next_steps'],
        ];
        $saved = get_option(self::SETTINGS_OPTION, []);
        if (!is_array($saved)) {
            $saved = [];
        }
        return wp_parse_args($saved, $defaults);
    }

    public static function update_settings($input) {
        $current = self::get_settings();
        $sections = isset($input['client_report_sections']) && is_array($input['client_report_sections'])
            ? array_map('sanitize_key', wp_unslash($input['client_report_sections']))
            : [];

        $settings = [
            'setup_complete' => isset($input['setup_complete']) ? '1' : ($current['setup_complete'] ?? '0'),
            'agency_mode' => isset($input['agency_mode']) ? '1' : '0',
            'white_label_enabled' => isset($input['white_label_enabled']) ? '1' : '0',
            'agency_name' => sanitize_text_field(wp_unslash($input['agency_name'] ?? '')),
            'client_name' => sanitize_text_field(wp_unslash($input['client_name'] ?? '')),
            'report_logo_url' => esc_url_raw(wp_unslash($input['report_logo_url'] ?? '')),
            'weekly_email_enabled' => isset($input['weekly_email_enabled']) ? '1' : '0',
            'weekly_email_to' => sanitize_email(wp_unslash($input['weekly_email_to'] ?? get_option('admin_email'))),
            'weekly_email_day' => sanitize_key(wp_unslash($input['weekly_email_day'] ?? 'monday')),
            'weekly_email_hour' => (string) min(23, max(0, intval($input['weekly_email_hour'] ?? 9))),
            'woocommerce_email_style' => isset($input['woocommerce_email_style']) ? '1' : '0',
            'auto_capture_before_after' => isset($input['auto_capture_before_after']) ? '1' : '0',
            'safe_apply_required' => isset($input['safe_apply_required']) ? '1' : '0',
            'client_report_sections' => $sections ?: ['summary', 'funnel', 'products', 'carts', 'checkout', 'next_steps'],
        ];

        update_option(self::SETTINGS_OPTION, $settings);
        self::reschedule_weekly_email($settings);
        return $settings;
    }

    public static function handle_save_settings() {
        self::require_admin_and_nonce('aiflt_world_class_settings');
        self::update_settings($_POST);
        wp_safe_redirect(add_query_arg(['page' => 'aiflt-growth-tools', 'aiflt_saved' => '1'], admin_url('admin.php')));
        exit;
    }

    public static function handle_mark_setup_step() {
        self::require_admin_and_nonce('aiflt_mark_setup_step');
        $step = sanitize_key(wp_unslash($_POST['step'] ?? ''));
        $completed = get_option('aiflt_setup_completed_steps', []);
        if (!is_array($completed)) $completed = [];
        if ($step && !in_array($step, $completed, true)) {
            $completed[] = $step;
        }
        update_option('aiflt_setup_completed_steps', array_values(array_unique($completed)));
        wp_safe_redirect(wp_get_referer() ?: admin_url('admin.php?page=aiflt-setup-wizard'));
        exit;
    }

    public static function require_admin_and_nonce($action) {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Permission denied.', 'ai-flash-tune'));
        }
        check_admin_referer($action);
    }

    public static function reschedule_weekly_email($settings = null) {
        $settings = $settings ?: self::get_settings();
        $timestamp = wp_next_scheduled(self::CRON_HOOK);
        if ($timestamp) {
            wp_unschedule_event($timestamp, self::CRON_HOOK);
        }
        if (($settings['weekly_email_enabled'] ?? '0') !== '1') {
            return;
        }
        $hour = min(23, max(0, intval($settings['weekly_email_hour'] ?? 9)));
        $day = sanitize_key($settings['weekly_email_day'] ?? 'monday');
        $allowed_days = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday'];
        if (!in_array($day, $allowed_days, true)) $day = 'monday';
        $next = strtotime('next ' . $day . ' ' . $hour . ':00:00');
        if (!$next) $next = time() + WEEK_IN_SECONDS;
        wp_schedule_event($next, 'weekly', self::CRON_HOOK);
    }

    public static function get_setup_steps() {
        $completed = get_option('aiflt_setup_completed_steps', []);
        if (!is_array($completed)) $completed = [];
        $settings = self::get_settings();
        $has_ai = (get_option('aiflt_ai_mode', 'local') === 'local') || !empty(get_option('aiflt_ai_api_key')) || !empty(get_option('aiflt_zywrap_api_key'));
        $steps = [
            'woocommerce' => [
                'label' => __('WooCommerce detected', 'ai-flash-tune'),
                'description' => __('Confirm WooCommerce is installed and active before trusting funnel data.', 'ai-flash-tune'),
                'complete' => function_exists('aiflt_is_woocommerce_active') && aiflt_is_woocommerce_active(),
            ],
            'tracking' => [
                'label' => __('Tracking enabled', 'ai-flash-tune'),
                'description' => __('Frontend tracking must be enabled to collect product, cart, checkout, and behavior events.', 'ai-flash-tune'),
                'complete' => get_option('aiflt_enable_tracking', '1') === '1',
            ],
            'privacy' => [
                'label' => __('Privacy controls reviewed', 'ai-flash-tune'),
                'description' => __('Review data retention, IP anonymization, excluded roles, and AI data-sharing consent.', 'ai-flash-tune'),
                'complete' => in_array('privacy', $completed, true),
                'manual' => true,
            ],
            'tracking_test' => [
                'label' => __('Tracking test completed', 'ai-flash-tune'),
                'description' => __('Visit product → add to cart → cart → checkout → purchase in a guest browser and confirm data appears.', 'ai-flash-tune'),
                'complete' => in_array('tracking_test', $completed, true),
                'manual' => true,
            ],
            'ai_mode' => [
                'label' => __('AI mode reviewed', 'ai-flash-tune'),
                'description' => __('Local mode works without external AI. OpenAI/Zywrap require keys and consent.', 'ai-flash-tune'),
                'complete' => $has_ai || in_array('ai_mode', $completed, true),
            ],
            'weekly_summary' => [
                'label' => __('Weekly summary configured', 'ai-flash-tune'),
                'description' => __('Optional, but recommended for store owners and agencies.', 'ai-flash-tune'),
                'complete' => ($settings['weekly_email_enabled'] ?? '0') === '1' || in_array('weekly_summary', $completed, true),
                'manual' => true,
            ],
        ];
        $done = 0;
        foreach ($steps as $step) {
            if (!empty($step['complete'])) $done++;
        }
        return ['steps' => $steps, 'done' => $done, 'total' => count($steps), 'percent' => round(($done / max(1, count($steps))) * 100)];
    }

    public static function get_report_data($days = 7) {
        $context = class_exists('AIFLT_AI_Service') ? AIFLT_AI_Service::compact_store_context(['days' => $days]) : [];
        $metrics = $context['metrics'] ?? [];
        $top_products = [];
        if (class_exists('AIFLT_Products_Logic')) {
            $top_products = AIFLT_Products_Logic::get_low_performing_products_for_dashboard(5);
        }
        $top_carts = [];
        if (class_exists('AIFLT_Free_Insights_Logic')) {
            $top_carts = AIFLT_Free_Insights_Logic::get_top_abandoned_products(5);
        }
        return [
            'generated_at' => current_time('mysql'),
            'days' => $days,
            'settings' => self::get_settings(),
            'context' => $context,
            'metrics' => $metrics,
            'low_performing_products' => $top_products,
            'top_abandoned_products' => $top_carts,
            'next_steps' => self::get_local_next_steps($context),
        ];
    }

    public static function get_local_next_steps($context) {
        $metrics = $context['metrics'] ?? [];
        $steps = [];
        $sessions = intval($metrics['sessions'] ?? $metrics['total_sessions'] ?? 0);
        $carts = intval($metrics['add_to_carts'] ?? $metrics['carts'] ?? 0);
        $checkouts = intval($metrics['checkouts'] ?? $metrics['checkout_visits'] ?? 0);
        $sales = intval($metrics['sales'] ?? $metrics['purchases'] ?? 0);
        if ($sessions < 20) {
            $steps[] = __('Collect at least 20 sessions before making conversion decisions.', 'ai-flash-tune');
        }
        if ($carts > 0 && $checkouts === 0) {
            $steps[] = __('Review cart-to-checkout friction such as shipping expectations, cart CTA visibility, and coupon distractions.', 'ai-flash-tune');
        }
        if ($checkouts > 0 && $sales === 0) {
            $steps[] = __('Audit checkout fields, payment options, trust signals, and unexpected fees.', 'ai-flash-tune');
        }
        if (empty($steps)) {
            $steps[] = __('Review the highest-traffic product pages first and check whether users reach cart and checkout.', 'ai-flash-tune');
            $steps[] = __('Use the Product Optimizer and Checkout Optimizer to prioritize changes before applying them.', 'ai-flash-tune');
        }
        return $steps;
    }

    public static function handle_export_client_report() {
        self::require_admin_and_nonce('aiflt_export_client_report');
        $format = sanitize_key(wp_unslash($_GET['format'] ?? 'html'));
        $days = min(90, max(1, intval(wp_unslash($_GET['days'] ?? 7))));
        $data = self::get_report_data($days);
        if ($format === 'csv') {
            self::stream_client_report_csv($data);
        }
        self::stream_client_report_html($data);
    }

    public static function stream_client_report_html($data) {
        $settings = $data['settings'];
        $client = $settings['client_name'] ?: get_bloginfo('name');
        $agency = $settings['white_label_enabled'] === '1' && !empty($settings['agency_name']) ? $settings['agency_name'] : __('AI Flash Tune', 'ai-flash-tune');
        $logo = !empty($settings['report_logo_url']) ? esc_url($settings['report_logo_url']) : '';
        $metrics = is_array($data['metrics'] ?? null) ? $data['metrics'] : [];
        $sections = is_array($settings['client_report_sections'] ?? null) ? $settings['client_report_sections'] : ['summary', 'funnel', 'products', 'carts', 'checkout', 'next_steps'];
        $metric = function($keys, $fallback = 0) use ($metrics) {
            foreach ((array) $keys as $key) {
                if (isset($metrics[$key]) && $metrics[$key] !== '') return $metrics[$key];
            }
            return $fallback;
        };
        $cards = [
            __('Sessions', 'ai-flash-tune') => $metric(['sessions', 'total_sessions']),
            __('Product views', 'ai-flash-tune') => $metric(['product_views']),
            __('Add to carts', 'ai-flash-tune') => $metric(['add_to_carts', 'carts']),
            __('Checkouts', 'ai-flash-tune') => $metric(['checkouts', 'checkout_visits']),
            __('Sales', 'ai-flash-tune') => $metric(['sales', 'purchases']),
            __('Abandoned carts', 'ai-flash-tune') => $metric(['abandoned_carts']),
            __('Conversion rate', 'ai-flash-tune') => is_numeric($metric(['conversion_rate'])) ? $metric(['conversion_rate']) . '%' : $metric(['conversion_rate']),
        ];
        header('Content-Type: text/html; charset=utf-8');
        header('Content-Disposition: attachment; filename="ai-flash-tune-client-report.html"');
        echo '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>' . esc_html($client) . ' - AI Flash Tune Report</title>';
        echo '<style>:root{--ink:#0f172a;--muted:#64748b;--line:#e2e8f0;--blue:#2563eb;--soft:#f8fafc;--green:#059669;--red:#dc2626}.wrap{max-width:1120px;margin:0 auto;padding:34px 22px 48px}body{margin:0;background:#eef2f7;color:var(--ink);font-family:Inter,-apple-system,BlinkMacSystemFont,"Segoe UI",Arial,sans-serif;line-height:1.55}.hero{background:linear-gradient(135deg,#111827,#1e3a8a 65%,#2563eb);color:#fff;border-radius:30px;padding:34px;box-shadow:0 24px 70px rgba(15,23,42,.22);display:flex;justify-content:space-between;gap:28px}.logo{max-height:54px;max-width:220px;background:#fff;border-radius:14px;padding:8px}.eyebrow{text-transform:uppercase;letter-spacing:.13em;font-size:12px;font-weight:800;opacity:.84}.hero h1{font-size:34px;line-height:1.1;margin:10px 0}.hero p{margin:0;color:#dbeafe}.badge{display:inline-flex;padding:8px 12px;border-radius:999px;background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.2);font-size:12px;font-weight:800}.grid{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin:20px 0}.metric{background:#fff;border:1px solid var(--line);border-radius:20px;padding:18px;box-shadow:0 12px 32px rgba(15,23,42,.07)}.metric span{display:block;color:var(--muted);font-size:12px;text-transform:uppercase;letter-spacing:.08em;font-weight:800}.metric strong{display:block;font-size:28px;margin-top:8px}.card{background:#fff;border:1px solid var(--line);border-radius:24px;padding:24px;margin-top:18px;box-shadow:0 12px 32px rgba(15,23,42,.07)}.card h2{margin:0 0 12px;font-size:22px}.muted{color:var(--muted)}.pill{display:inline-flex;margin:0 8px 8px 0;padding:8px 12px;border-radius:999px;background:#eef2ff;color:#3730a3;font-size:12px;font-weight:800}.risk{border-left:5px solid var(--red)}.safe{border-left:5px solid var(--green)}ol,ul{padding-left:22px}li{margin:8px 0}table{width:100%;border-collapse:collapse;margin-top:12px}th,td{text-align:left;border-bottom:1px solid var(--line);padding:12px 10px;font-size:14px}th{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);background:var(--soft)}.footer{color:var(--muted);font-size:12px;text-align:center;margin-top:24px}.two{display:grid;grid-template-columns:1fr 1fr;gap:18px}@media(max-width:900px){.grid,.two{grid-template-columns:1fr}.hero{display:block}.logo{margin-top:18px}}</style></head><body><div class="wrap">';
        echo '<div class="hero"><div><div class="eyebrow">' . esc_html__('Client-ready WooCommerce intelligence', 'ai-flash-tune') . '</div><h1>' . esc_html__('Sales Leak & Conversion Report', 'ai-flash-tune') . '</h1><p>' . esc_html($client) . ' · ' . esc_html($agency) . ' · ' . esc_html($data['generated_at']) . '</p></div><div>' . ($logo ? '<img class="logo" src="' . esc_url($logo) . '" alt="Report logo">' : '<span class="badge">AI Flash Tune</span>') . '</div></div>';
        echo '<div class="grid">'; foreach ($cards as $label => $value) echo '<div class="metric"><span>' . esc_html($label) . '</span><strong>' . esc_html(is_scalar($value) ? (string) $value : '0') . '</strong></div>'; echo '</div>';
        if (in_array('summary', $sections, true)) echo '<div class="card safe"><h2>' . esc_html__('Executive summary', 'ai-flash-tune') . '</h2><p>' . esc_html__('This report highlights the most important conversion risks, local tracking signals, and safe next actions. Treat the figures as operational guidance, then validate each fix with fresh traffic before making another major change.', 'ai-flash-tune') . '</p><span class="pill">' . esc_html__('Local data first', 'ai-flash-tune') . '</span><span class="pill">' . esc_html__('Safe review required', 'ai-flash-tune') . '</span><span class="pill">' . esc_html__('Client-ready', 'ai-flash-tune') . '</span></div>';
        if (in_array('next_steps', $sections, true)) { echo '<div class="card risk"><h2>' . esc_html__('Recommended next actions', 'ai-flash-tune') . '</h2><ol>'; foreach ($data['next_steps'] as $step) echo '<li>' . esc_html($step) . '</li>'; echo '</ol></div>'; }
        echo '<div class="two">';
        if (in_array('products', $sections, true)) { echo '<div class="card"><h2>' . esc_html__('Product opportunities', 'ai-flash-tune') . '</h2>'; if (!empty($data['low_performing_products'])) { echo '<table><thead><tr><th>' . esc_html__('Product', 'ai-flash-tune') . '</th><th>' . esc_html__('Signal', 'ai-flash-tune') . '</th></tr></thead><tbody>'; foreach ($data['low_performing_products'] as $p) echo '<tr><td>' . esc_html($p['product_name'] ?? $p['name'] ?? __('Product', 'ai-flash-tune')) . '</td><td>' . esc_html__('Review copy, CTA, trust, and offer clarity.', 'ai-flash-tune') . '</td></tr>'; echo '</tbody></table>'; } else echo '<p class="muted">' . esc_html__('No critical low-performing product pattern is visible yet.', 'ai-flash-tune') . '</p>'; echo '</div>'; }
        if (in_array('carts', $sections, true)) { echo '<div class="card"><h2>' . esc_html__('Abandoned cart patterns', 'ai-flash-tune') . '</h2>'; if (!empty($data['top_abandoned_products'])) { echo '<table><thead><tr><th>' . esc_html__('Product', 'ai-flash-tune') . '</th><th>' . esc_html__('Abandoned', 'ai-flash-tune') . '</th></tr></thead><tbody>'; foreach ($data['top_abandoned_products'] as $p) echo '<tr><td>' . esc_html($p['name'] ?? __('Product', 'ai-flash-tune')) . '</td><td>' . esc_html($p['abandoned_count'] ?? '0') . '</td></tr>'; echo '</tbody></table>'; } else echo '<p class="muted">' . esc_html__('No repeated abandoned-cart product pattern is available yet.', 'ai-flash-tune') . '</p>'; echo '</div>'; }
        echo '</div><div class="card"><h2>' . esc_html__('Safe-change policy', 'ai-flash-tune') . '</h2><ul><li>' . esc_html__('Preview every AI-assisted change before applying it.', 'ai-flash-tune') . '</li><li>' . esc_html__('Capture before/after snapshots for product copy, checkout options, and future automation.', 'ai-flash-tune') . '</li><li>' . esc_html__('Change one thing at a time and compare results after fresh traffic is collected.', 'ai-flash-tune') . '</li></ul></div><div class="footer">' . esc_html__('Generated by AI Flash Tune. No client report should be treated as financial, legal, or tax advice.', 'ai-flash-tune') . '</div></div></body></html>';
        exit;
    }


    public static function stream_client_report_csv($data) {
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="ai-flash-tune-client-report.csv"');
        $out = fopen('php://output', 'w');
        fputcsv($out, ['Section', 'Metric', 'Value']);
        foreach (($data['metrics'] ?? []) as $key => $value) {
            fputcsv($out, ['Metrics', $key, is_scalar($value) ? $value : wp_json_encode($value)]);
        }
        foreach ($data['next_steps'] as $step) {
            fputcsv($out, ['Next Step', 'Recommendation', $step]);
        }
        // Output stream is closed automatically at script termination.
        exit;
    }

    public static function handle_send_test_weekly_summary() {
        self::require_admin_and_nonce('aiflt_send_test_weekly_summary');
        $sent = self::send_weekly_summary_email(true);
        wp_safe_redirect(add_query_arg(['page' => 'aiflt-growth-tools', 'aiflt_email_test' => $sent ? 'sent' : 'failed'], admin_url('admin.php')));
        exit;
    }

    public static function send_weekly_summary_email($test = false) {
        $settings = self::get_settings();
        if (!$test && ($settings['weekly_email_enabled'] ?? '0') !== '1') return false;
        $to = sanitize_email($settings['weekly_email_to'] ?? get_option('admin_email'));
        if (!$to) return false;
        $data = self::get_report_data(7);
        $subject = sprintf(
            /* translators: %s: site name. */
            __('Weekly WooCommerce sales-leak summary for %s', 'ai-flash-tune'),
            get_bloginfo('name')
        );
        $body = self::render_weekly_email_body($data);
        $headers = ['Content-Type: text/html; charset=UTF-8'];
        return wp_mail($to, $subject, $body, $headers);
    }

    public static function render_weekly_email_body($data) {
        $metrics = $data['metrics'] ?? [];
        ob_start();
        ?>
        <div style="font-family:Arial,sans-serif;color:#111827;line-height:1.5;max-width:680px;margin:0 auto;">
            <h2><?php echo esc_html__('AI Flash Tune weekly summary', 'ai-flash-tune'); ?></h2>
            <p style="color:#6b7280;"><?php echo esc_html__('A quick view of store activity and recommended checks from the last 7 days.', 'ai-flash-tune'); ?></p>
            <table width="100%" cellpadding="8" cellspacing="0" style="border-collapse:collapse;background:#f9fafb;border-radius:12px;overflow:hidden;">
                <tr>
                    <td><strong><?php echo esc_html__('Sessions', 'ai-flash-tune'); ?></strong><br><?php echo esc_html($metrics['sessions'] ?? $metrics['total_sessions'] ?? 0); ?></td>
                    <td><strong><?php echo esc_html__('Carts', 'ai-flash-tune'); ?></strong><br><?php echo esc_html($metrics['add_to_carts'] ?? 0); ?></td>
                    <td><strong><?php echo esc_html__('Checkouts', 'ai-flash-tune'); ?></strong><br><?php echo esc_html($metrics['checkouts'] ?? 0); ?></td>
                    <td><strong><?php echo esc_html__('Sales', 'ai-flash-tune'); ?></strong><br><?php echo esc_html($metrics['sales'] ?? 0); ?></td>
                </tr>
            </table>
            <h3><?php echo esc_html__('Recommended next checks', 'ai-flash-tune'); ?></h3>
            <ol>
                <?php foreach ($data['next_steps'] as $step) : ?><li><?php echo esc_html($step); ?></li><?php endforeach; ?>
            </ol>
            <p><a href="<?php echo esc_url(admin_url('admin.php?page=ai_flash_tune')); ?>" style="background:#2563eb;color:#fff;padding:10px 14px;border-radius:8px;text-decoration:none;display:inline-block;"><?php echo esc_html__('Open AI Flash Tune', 'ai-flash-tune'); ?></a></p>
        </div>
        <?php
        return ob_get_clean();
    }

    public static function log_change($change_type, $args = []) {
        global $wpdb;
        self::maybe_create_tables();
        $table = $wpdb->prefix . 'aiflt_change_log';
        $wpdb->insert($table, [
            'change_type' => sanitize_key($change_type),
            'object_type' => sanitize_key($args['object_type'] ?? ''),
            'object_id' => intval($args['object_id'] ?? 0),
            'label' => sanitize_text_field($args['label'] ?? ''),
            'before_data' => wp_json_encode($args['before_data'] ?? []),
            'after_data' => wp_json_encode($args['after_data'] ?? []),
            'source' => sanitize_key($args['source'] ?? 'manual'),
            'status' => sanitize_key($args['status'] ?? 'applied'),
            'created_by' => get_current_user_id(),
            'created_at' => current_time('mysql'),
        ]);
        return $wpdb->insert_id;
    }

    public static function get_change_log($limit = 20) {
        global $wpdb;
        self::maybe_create_tables();
        $table = $wpdb->prefix . 'aiflt_change_log';
        return $wpdb->get_results($wpdb->prepare("SELECT * FROM {$table} ORDER BY created_at DESC LIMIT %d", $limit), ARRAY_A);
    }

    public static function handle_rollback_change() {
        self::require_admin_and_nonce('aiflt_rollback_change');
        $change_id = intval($_POST['change_id'] ?? 0);
        self::rollback_change($change_id);
        wp_safe_redirect(add_query_arg(['page' => 'aiflt-growth-tools', 'aiflt_rollback' => '1'], admin_url('admin.php')));
        exit;
    }

    public static function rollback_change($change_id) {
        global $wpdb;
        self::maybe_create_tables();
        $table = $wpdb->prefix . 'aiflt_change_log';
        $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table} WHERE id = %d", $change_id), ARRAY_A);
        if (!$row || $row['status'] === 'reverted') return false;
        $before = json_decode($row['before_data'] ?: '{}', true);
        if ($row['object_type'] === 'option' && !empty($before['option_name'])) {
            update_option(sanitize_key($before['option_name']), $before['option_value'] ?? null);
        }
        if ($row['object_type'] === 'product' && !empty($row['object_id']) && function_exists('wc_get_product')) {
            $product_id = intval($row['object_id']);
            $post_update = ['ID' => $product_id];
            if (isset($before['post_title'])) $post_update['post_title'] = wp_kses_post($before['post_title']);
            if (isset($before['post_content'])) $post_update['post_content'] = wp_kses_post($before['post_content']);
            if (isset($before['post_excerpt'])) $post_update['post_excerpt'] = wp_kses_post($before['post_excerpt']);
            if (count($post_update) > 1) wp_update_post($post_update);
        }
        $wpdb->update($table, ['status' => 'reverted', 'reverted_at' => current_time('mysql')], ['id' => $change_id]);
        return true;
    }

    public static function save_product_copy_revision($product_id, $after = [], $label = '') {
        global $wpdb;
        self::maybe_create_tables();
        $product_id = intval($product_id);
        $post = get_post($product_id);
        if (!$post || $post->post_type !== 'product') return false;
        $table = $wpdb->prefix . 'aiflt_product_copy_revisions';
        $wpdb->insert($table, [
            'product_id' => $product_id,
            'revision_label' => sanitize_text_field($label ?: __('AI copy revision', 'ai-flash-tune')),
            'before_title' => $post->post_title,
            'before_short_description' => $post->post_excerpt,
            'before_description' => $post->post_content,
            'after_title' => sanitize_text_field($after['title'] ?? ''),
            'after_short_description' => wp_kses_post($after['short_description'] ?? ''),
            'after_description' => wp_kses_post($after['description'] ?? ''),
            'ai_action_key' => sanitize_key($after['ai_action_key'] ?? 'woocommerce_product_copy_optimizer'),
            'source' => sanitize_key($after['source'] ?? 'ai'),
            'status' => sanitize_key($after['status'] ?? 'draft'),
            'created_by' => get_current_user_id(),
            'created_at' => current_time('mysql'),
        ]);
        return $wpdb->insert_id;
    }

    public static function get_product_copy_revisions($limit = 20) {
        global $wpdb;
        self::maybe_create_tables();
        $table = $wpdb->prefix . 'aiflt_product_copy_revisions';
        return $wpdb->get_results($wpdb->prepare("SELECT r.*, p.post_title AS current_title FROM {$table} r LEFT JOIN {$wpdb->posts} p ON p.ID = r.product_id ORDER BY r.created_at DESC LIMIT %d", $limit), ARRAY_A);
    }

    public static function get_ab_test_ideas($limit = 20) {
        global $wpdb;
        self::maybe_create_tables();
        $table = esc_sql($wpdb->prefix . 'aiflt_ab_test_ideas');
        return $wpdb->get_results($wpdb->prepare("SELECT * FROM {$table} ORDER BY created_at DESC LIMIT %d", $limit), ARRAY_A);
    }

    public static function handle_generate_ab_test_ideas() {
        self::require_admin_and_nonce('aiflt_generate_ab_test_ideas');
        $area = sanitize_key(wp_unslash($_POST['area'] ?? 'funnel'));
        self::generate_ab_test_ideas($area);
        wp_safe_redirect(add_query_arg(['page' => 'aiflt-growth-tools', 'aiflt_ab_generated' => '1'], admin_url('admin.php')));
        exit;
    }

    public static function generate_ab_test_ideas($area = 'funnel') {
        global $wpdb;
        self::maybe_create_tables();
        $table = esc_sql($wpdb->prefix . 'aiflt_ab_test_ideas');
        $context = class_exists('AIFLT_AI_Service') ? AIFLT_AI_Service::compact_store_context(['days' => 30]) : [];
        $ideas = self::local_ab_test_ideas($area, $context);
        if (class_exists('AIFLT_AI_Service')) {
            $ai = AIFLT_AI_Service::run_action('woocommerce_ab_test_idea_generator', [
                'area' => $area,
                'store_context' => $context,
                'instruction' => implode("\n", [
                    'Generate practical WooCommerce safe test ideas from the supplied aggregate store context.',
                    'For low traffic stores, call them validation checks instead of statistically valid A/B tests.',
                    'Each idea must include title, hypothesis, primary metric, expected impact, confidence, effort, guardrails, and stop condition.',
                    'Do not recommend discounts, free shipping, urgency, new payment gateways, trust badges, testimonials, or broad redesigns unless data supports the exact idea.',
                ]),
            ]);
            if (!empty($ai['content']) && is_string($ai['content'])) {
                $ideas[] = [
                    'title' => __('AI-generated experiment backlog', 'ai-flash-tune'),
                    'hypothesis' => wp_strip_all_tags($ai['content']),
                    'metric' => __('See AI output', 'ai-flash-tune'),
                    'impact' => 'medium',
                    'confidence' => 'medium',
                    'effort' => 'medium',
                    'source' => 'ai',
                ];
            }
        }
        foreach ($ideas as $idea) {
            $wpdb->insert($table, [
                'area' => sanitize_key($area),
                'title' => sanitize_text_field($idea['title']),
                'hypothesis' => sanitize_textarea_field($idea['hypothesis']),
                'metric' => sanitize_text_field($idea['metric']),
                'impact' => sanitize_key($idea['impact']),
                'confidence' => sanitize_key($idea['confidence']),
                'effort' => sanitize_key($idea['effort']),
                'status' => 'idea',
                'source' => sanitize_key($idea['source'] ?? 'local'),
                'created_by' => get_current_user_id(),
                'created_at' => current_time('mysql'),
            ]);
        }
        return count($ideas);
    }

    public static function local_ab_test_ideas($area, $context = []) {
        $map = [
            'funnel' => [
                ['title' => __('Cart CTA clarity test', 'ai-flash-tune'), 'hypothesis' => __('A clearer cart CTA will increase cart-to-checkout progression.', 'ai-flash-tune'), 'metric' => __('Cart to checkout rate', 'ai-flash-tune'), 'impact' => 'high', 'confidence' => 'medium', 'effort' => 'low'],
                ['title' => __('Product benefit-first layout test', 'ai-flash-tune'), 'hypothesis' => __('Moving core benefits above detailed specs will increase add-to-cart rate.', 'ai-flash-tune'), 'metric' => __('Product view to cart rate', 'ai-flash-tune'), 'impact' => 'medium', 'confidence' => 'medium', 'effort' => 'medium'],
            ],
            'checkout' => [
                ['title' => __('Checkout field pressure validation', 'ai-flash-tune'), 'hypothesis' => __('Reviewing low-risk optional fields and keeping core billing/shipping fields unchanged will reduce checkout friction without harming fulfillment quality.', 'ai-flash-tune'), 'metric' => __('Checkout completion rate', 'ai-flash-tune'), 'impact' => 'high', 'confidence' => 'medium', 'effort' => 'low'],
                ['title' => __('Checkout reassurance clarity validation', 'ai-flash-tune'), 'hypothesis' => __('Clear reassurance text about secure checkout, returns/support visibility, and guest checkout clarity may reduce hesitation without changing payment providers.', 'ai-flash-tune'), 'metric' => __('Checkout completion rate', 'ai-flash-tune'), 'impact' => 'medium', 'confidence' => 'medium', 'effort' => 'low'],
            ],
            'cart' => [
                ['title' => __('Cart-to-checkout clarity validation', 'ai-flash-tune'), 'hypothesis' => __('Clarifying cart totals, variation details, shipping/tax expectations, and the checkout CTA may improve cart-to-checkout progression.', 'ai-flash-tune'), 'metric' => __('Cart to checkout rate', 'ai-flash-tune'), 'impact' => 'high', 'confidence' => 'medium', 'effort' => 'low'],
            ],
        ];
        return $map[$area] ?? $map['funnel'];
    }
}

AIFLT_World_Class_Tools::init();
