<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /includes/class-admin-page.php
// Description: Admin page class — menus, enqueues, AJAX handlers, render dispatcher - NUCLEAR+++
// Last Edited: 2026-04-22
// ==================================================
namespace AutoMarketerAI;

if (!defined('ABSPATH')) {
    exit('No direct script access allowed.');
}

require_once AMAI_PLUGIN_DIR . '/includes/module-interface.php';

class AdminPage
{
    private static ?self $instance = null;

    public static function init(): self
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct()
    {
        add_action('admin_menu',                           [$this, 'add_menu']);
        add_action('admin_enqueue_scripts',                [$this, 'enqueue_admin_assets']);
        add_action('admin_post_amai_module_toggle',        [$this, 'handle_toggle']);
        add_action('wp_ajax_amai_module_toggle',           [$this, 'handle_toggle']);
        add_action('wp_ajax_amai_activate_provider',       [$this, 'handle_activate_provider']);
        add_action('wp_ajax_amai_get_provider_data',       [$this, 'handle_get_provider_data']);
        add_action('wp_ajax_amai_update_model',            [$this, 'handle_update_model']);
        add_action('admin_post_amai_update_model',         [$this, 'handle_update_model']);
        add_action('admin_notices',                        [$this, 'admin_notices']);
        add_action('wp_ajax_amai_dismiss_credit_warning',  [$this, 'handle_dismiss_credit_warning']);
        add_action('wp_ajax_amai_create_checkout_session', [$this, 'handle_create_checkout_session']);
        add_action('wp_ajax_amai_dashboard_subscription',  [$this, 'handle_dashboard_subscription']);
        add_action('wp_ajax_amai_set_business_type',        [$this, 'handle_set_business_type']);
    }

    public function add_menu(): void
    {
        $unread_count = 0;
        global $wpdb;
        if (in_array('comment-manager', (array) get_option('amai_active_modules', []), true)) {
            $unread_count += (int) $wpdb->get_var(
                "SELECT COUNT(*) FROM {$wpdb->prefix}amai_social_comments WHERE status IN ('new', 'pending_review')"
            );
        }
        if (in_array('review-responder', (array) get_option('amai_active_modules', []), true)) {
            $unread_count += (int) $wpdb->get_var(
                "SELECT COUNT(*) FROM {$wpdb->prefix}amai_reviews WHERE status IN ('new', 'pending_review')"
            );
        }
        $badge           = $unread_count > 0 ? ' <span class="awaiting-mod count-' . $unread_count . '">' . $unread_count . '</span>' : '';
        $menu_title      = __('AutoMarketer AI', 'automarketer-ai') . $badge;
        $reputation_title = __('Reputation', 'automarketer-ai') . $badge;
        add_menu_page(
            __('AutoMarketer AI', 'automarketer-ai'),
            $menu_title,
            'manage_automarketer_ai',
            'automarketer-ai',
            [$this, 'render_page'],
            'dashicons-analytics',
            58
        );

        add_submenu_page(
            'automarketer-ai',
            __('Dashboard', 'automarketer-ai'),
            __('Dashboard', 'automarketer-ai'),
            'manage_automarketer_ai',
            'automarketer-ai',
            [$this, 'render_page']
        );
        add_submenu_page(
            null,
            __('Setup', 'automarketer-ai'),
            __('Setup', 'automarketer-ai'),
            'manage_automarketer_ai',
            'automarketer-ai-setup',
            [$this, 'render_page']
        );
        add_submenu_page(
            null,
            __('Modules', 'automarketer-ai'),
            __('Modules', 'automarketer-ai'),
            'manage_automarketer_ai',
            'automarketer-ai-modules',
            [$this, 'render_page']
        );

        add_submenu_page(
            'automarketer-ai',
            __('Results', 'automarketer-ai'),
            __('Results', 'automarketer-ai'),
            'manage_automarketer_ai',
            'automarketer-ai-results',
            static function (): void {
                include AMAI_PLUGIN_DIR . 'templates/results.php';
            }
        );

        add_submenu_page(
            'automarketer-ai',
            __('Content', 'automarketer-ai'),
            __('Content', 'automarketer-ai'),
            'manage_automarketer_ai',
            'automarketer-ai-content',
            static function (): void {
                include AMAI_PLUGIN_DIR . 'templates/content.php';
            }
        );
        $reputation_active = in_array('comment-manager', (array) get_option('amai_active_modules', []), true)
            || in_array('review-responder', (array) get_option('amai_active_modules', []), true);
        if ($reputation_active) {
            add_submenu_page(
                'automarketer-ai',
                __('Reputation', 'automarketer-ai'),
                $reputation_title,
                'manage_automarketer_ai',
                'automarketer-ai-reputation',
                static function (): void {
                    include AMAI_PLUGIN_DIR . 'templates/reputation.php';
                }
            );
        }
        // Legacy slug -- hidden from sidebar, keeps old bookmarks working
        add_submenu_page(
            null,
            __('Comment Inbox', 'automarketer-ai'),
            '',
            'manage_automarketer_ai',
            'automarketer-ai-comments',
            static function (): void {
                wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-reputation&tab=comments'));
                exit;
            }
        );

        if (get_option('amai_abandoned_cart_active', '0') === '1') {
            add_submenu_page(
                'automarketer-ai',
                __('WooCommerce', 'automarketer-ai'),
                __('WooCommerce', 'automarketer-ai'),
                'manage_automarketer_ai',
                'automarketer-ai-woocommerce',
                static function (): void {
                    include AMAI_PLUGIN_DIR . 'templates/woocommerce.php';
                }
            );
        }
    }

    public function enqueue_admin_assets(string $hook): void
    {
        if (strpos($hook, 'automarketer-ai') === false) {
            return;
        }

        $page = sanitize_key((string) ($_GET['page'] ?? ''));

                // ── Nudge ─────────────────────────────────────────────────
        $nudge_pages = ['automarketer-ai', 'automarketer-ai-modules', 'automarketer-ai-social'];
        if (in_array($page, $nudge_pages, true)) {
            wp_enqueue_style(
                'amai-nudge',
                AMAI_PLUGIN_URL . 'assets/css/nudge.css',
                [],
                (string) filemtime(AMAI_PLUGIN_DIR . 'assets/css/nudge.css')
            );
        }

        // ── Dashboard ──────────────────────────────────────────
        if ($page === 'automarketer-ai') {
            wp_enqueue_style(
                'amai-dashboard',
                AMAI_PLUGIN_URL . 'assets/css/dashboard.css',
                [],
                (string) filemtime(AMAI_PLUGIN_DIR . 'assets/css/dashboard.css')
            );
            wp_enqueue_script(
                'amai-dashboard',
                AMAI_PLUGIN_URL . 'assets/js/amai-dashboard.js',
                [],
                (string) filemtime(AMAI_PLUGIN_DIR . 'assets/js/amai-dashboard.js'),
                true
            );
        }

        // ── Setup ──────────────────────────────────────────────
        if ($page === 'automarketer-ai-setup') {
            wp_enqueue_style(
                'amai-setup',
                AMAI_PLUGIN_URL . 'assets/css/setup.css',
                [],
                (string) filemtime(AMAI_PLUGIN_DIR . 'assets/css/setup.css')
            );
            // Setup page JS reuses the overview script for the license modal
            wp_enqueue_script(
                'amai-setup',
                AMAI_PLUGIN_URL . 'assets/js/amai-setup.js',
                [],
                (string) filemtime(AMAI_PLUGIN_DIR . 'assets/js/amai-setup.js'),
                true
            );
            wp_localize_script('amai-setup', 'amaiSetup', [
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce'   => wp_create_nonce('amai_nudge_actions'),
            ]);
            wp_enqueue_script(
                'amai-overview',
                AMAI_PLUGIN_URL . 'assets/js/amai-overview.js',
                ['jquery'],
                AMAI_VERSION,
                true
            );
        }

        // ── Modules ────────────────────────────────────────────
        if ($page === 'automarketer-ai-modules') {
            wp_enqueue_style(
                'amai-modules',
                AMAI_PLUGIN_URL . 'assets/css/modules.css',
                [],
                AMAI_VERSION
            );

            $help_steps_path = AMAI_PLUGIN_DIR . 'includes/provider-help-steps.php';
            $help_steps_map  = is_file($help_steps_path)
                ? (require $help_steps_path)
                : [];

            $modules   = $this->load_modules();
            $prov_meta = [];
            foreach ($modules as $pid => $module) {
                $prov_meta[$pid] = [
                    'prefix'        => method_exists($module, 'get_api_key_prefix') ? $module->get_api_key_prefix() : '',
                    'default_model' => method_exists($module, 'get_default_model')  ? $module->get_default_model()  : '',
                    'help_steps'    => $help_steps_map[$pid] ?? [],
                ];
            }

            wp_enqueue_script(
                'amai-modules',
                AMAI_PLUGIN_URL . 'assets/js/amai-modules.js',
                ['jquery'],
                (string) filemtime(AMAI_PLUGIN_DIR . 'assets/js/amai-modules.js'),
                true
            );

            wp_localize_script('amai-modules', 'amaiModules', [
                'provMeta'   => $prov_meta,
                'ajaxNonce'  => wp_create_nonce('amai_provider_actions'),
                'ajaxUrl'    => admin_url('admin-ajax.php'),
            ]);
        }

        // ── Plans / Billing ────────────────────────────────────
        if ($page === 'automarketer-ai-billing') {
            wp_enqueue_style(
                'amai-plans',
                AMAI_PLUGIN_URL . 'assets/css/plans.css',
                [],
                AMAI_VERSION
            );
            wp_enqueue_script('stripe-js', 'https://js.stripe.com/v3/', [], null, true);
            wp_enqueue_script(
                'amai-billing-js',
                AMAI_PLUGIN_URL . 'assets/js/amai-billing.js',
                ['jquery', 'stripe-js'],
                AMAI_VERSION,
                true
            );
            wp_localize_script('amai-billing-js', 'amaiBilling', [
                'stripePk'   => 'pk_live_51RyD2VJfH56oJEdkckKdofuFryOeckoxICkrQl2x1fgEuYLeJI0VWUjbJswBMM0UnJ338TwGiYddcTgG1DbE7dQr006PxMqIhh',
                'ajaxurl'    => admin_url('admin-ajax.php'),
                'restUrl'    => rest_url(),
                'billingUrl' => admin_url('admin.php?page=automarketer-ai-billing'),
                'nonce'      => wp_create_nonce('amai_create_checkout'),
                'successUrl' => admin_url('admin.php?page=automarketer-ai-billing&upgrade=success'),
                'cancelUrl'  => admin_url('admin.php?page=automarketer-ai-billing&upgrade=cancel'),
            ]);
        }

        // -- Content (Health / Link Checker / Outbound Links)
        if ($page === 'automarketer-ai-content') {
            wp_enqueue_style(
                'amai-content',
                AMAI_PLUGIN_URL . 'assets/css/content.css',
                [],
                (string) filemtime(AMAI_PLUGIN_DIR . 'assets/css/content.css')
            );
            $tab = sanitize_key((string) ($_GET['tab'] ?? 'health'));
            if ($tab === 'health') {
                wp_enqueue_style(
                    'amai-content-freshness',
                    AMAI_PLUGIN_URL . 'assets/css/content-freshness.css',
                    [],
                    (string) filemtime(AMAI_PLUGIN_DIR . 'assets/css/content-freshness.css')
                );
                wp_enqueue_script(
                    'amai-content-freshness',
                    AMAI_PLUGIN_URL . 'assets/js/amai-content-freshness.js',
                    [],
                    (string) filemtime(AMAI_PLUGIN_DIR . 'assets/js/amai-content-freshness.js'),
                    true
                );
                wp_localize_script('amai-content-freshness', 'amaiContentHealth', [
                    'ajaxurl' => admin_url('admin-ajax.php'),
                    'nonce'   => wp_create_nonce('amai_content_health'),
                ]);
            }
            if ($tab === 'links') {
                wp_enqueue_style(
                    'amai-link-checker',
                    AMAI_PLUGIN_URL . 'assets/css/link-checker.css',
                    [],
                    (string) filemtime(AMAI_PLUGIN_DIR . 'assets/css/link-checker.css')
                );
                wp_enqueue_script(
                    'amai-link-checker',
                    AMAI_PLUGIN_URL . 'assets/js/amai-link-checker.js',
                    [],
                    (string) filemtime(AMAI_PLUGIN_DIR . 'assets/js/amai-link-checker.js'),
                    true
                );
                wp_localize_script('amai-link-checker', 'amaiLinkChecker', [
                    'ajaxurl'  => admin_url('admin-ajax.php'),
                    'nonce'    => wp_create_nonce('amai_link_checker'),
                    'adminUrl' => admin_url(),
                ]);
            }
            if ($tab === 'outbound') {
            }
        }



        // ── WooCommerce (Cart Stats + Settings tabs) ──────────
        // -- Results
        if ($page === 'automarketer-ai-results') {
            wp_enqueue_style(
                'amai-results',
                AMAI_PLUGIN_URL . 'assets/css/results.css',
                [],
                (string) filemtime(AMAI_PLUGIN_DIR . 'assets/css/results.css')
            );
            wp_enqueue_script(
                'amai-results',
                AMAI_PLUGIN_URL . 'assets/js/amai-results.js',
                [],
                (string) filemtime(AMAI_PLUGIN_DIR . 'assets/js/amai-results.js'),
                true
            );
        }

        if ($page === 'automarketer-ai-woocommerce') {
            $tab = sanitize_key((string) ($_GET['tab'] ?? 'stats'));
            wp_enqueue_style(
                'amai-woocommerce',
                AMAI_PLUGIN_URL . 'assets/css/woocommerce.css',
                [],
                (string) filemtime(AMAI_PLUGIN_DIR . 'assets/css/woocommerce.css')
            );
            if ($tab === 'stats') {
                wp_enqueue_style(
                    'amai-abandoned-cart-stats',
                    AMAI_PLUGIN_URL . 'assets/css/abandoned-cart-stats.css',
                    [],
                    (string) filemtime(AMAI_PLUGIN_DIR . 'assets/css/abandoned-cart-stats.css')
                );
            }
            if ($tab === 'settings') {
                wp_enqueue_style(
                    'amai-settings',
                    AMAI_PLUGIN_URL . 'assets/css/settings.css',
                    [],
                    (string) filemtime(AMAI_PLUGIN_DIR . 'assets/css/settings.css')
                );
                wp_enqueue_script(
                    'amai-settings',
                    AMAI_PLUGIN_URL . 'assets/js/amai-settings.js',
                    [],
                    (string) filemtime(AMAI_PLUGIN_DIR . 'assets/js/amai-settings.js'),
                    true
                );
                wp_localize_script('amai-settings', 'amaiSettings', [
                    'ajaxUrl' => admin_url('admin-ajax.php'),
                    'nonce'   => wp_create_nonce('amai_settings_actions'),
                ]);
            }
        }
        // -- Comments inbox
        if ($page === 'automarketer-ai-reputation' || $page === 'automarketer-ai-comments') {
            wp_enqueue_style(
                'amai-comments',
                AMAI_PLUGIN_URL . 'assets/css/comments.css',
                [],
                (string) filemtime(AMAI_PLUGIN_DIR . 'assets/css/comments.css')
            );
            wp_enqueue_script(
                'amai-comments',
                AMAI_PLUGIN_URL . 'assets/js/amai-comments.js',
                [],
                (string) filemtime(AMAI_PLUGIN_DIR . 'assets/js/amai-comments.js'),
                true
            );
            wp_localize_script('amai-comments', 'amaiComments', [
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce'   => wp_create_nonce('amai_comment_actions'),
            ]);
            if ($page === 'automarketer-ai-reputation') {
                wp_enqueue_style(
                    'amai-reputation',
                    AMAI_PLUGIN_URL . 'assets/css/reputation.css',
                    [],
                    (string) filemtime(AMAI_PLUGIN_DIR . 'assets/css/reputation.css')
                );
            }
        }
    }

    public function render_page(): void
    {
        $active_modules   = (array) get_option('amai_active_modules', []);
        $license_status   = get_option('automarketer_ai_license_status', 'inactive');
        $license_key      = get_option('automarketer_ai_license_key', '');

        $current_tab = 'dashboard';
        $page        = sanitize_key((string) ($_GET['page'] ?? ''));

        if ($page === 'automarketer-ai-billing') {
            $current_tab = 'billing';
        }
        if ($page === 'automarketer-ai-modules') {
            $current_tab = 'modules';
        }
        if ($page === 'automarketer-ai-setup') {
            $current_tab = 'setup';
        }

        $is_free         = ($license_status === 'free' || $license_status === 'inactive');
        $active_ai_count = 0;

        foreach ($active_modules as $mod_id) {
            if (is_string($mod_id) && str_starts_with($mod_id, 'ai-')) {
                $active_ai_count++;
            }
        }

        $free_limit_reached = $is_free && $active_ai_count >= 1;
        $modules            = $this->load_modules();
        $ai_providers       = $this->filter_ai_providers($modules);
        $image_providers    = $this->filter_image_providers($modules);
        $email_providers    = $this->filter_email_providers($modules);
        $sms_providers         = $this->filter_sms_providers($modules);
        $analytics_providers   = $this->filter_analytics_providers($modules);
        $other_modules         = array_diff_key($modules, $ai_providers, $image_providers, $email_providers, $sms_providers, $analytics_providers);

        usort($ai_providers,    static fn($a, $b) => strcasecmp($a->get_name(), $b->get_name()));
        usort($image_providers, static fn($a, $b) => strcasecmp($a->get_name(), $b->get_name()));
        usort($email_providers, static fn($a, $b) => strcasecmp($a->get_name(), $b->get_name()));
        usort($sms_providers,   static fn($a, $b) => strcasecmp($a->get_name(), $b->get_name()));
        usort($other_modules,   static fn($a, $b) => strcasecmp($a->get_name(), $b->get_name()));

        $connected_channel_count = 0;
        if (FacebookAuth::getConnection() !== null) {
            $connected_channel_count++;
        }
        if (FacebookAuth::getInstagramAccountId() !== null) {
            $connected_channel_count++;
        }

        $total_provider_count = count($ai_providers) + count($image_providers);

        // Stat queries used by setup page and legacy references
        global $wpdb;
        $monday_utc = gmdate('Y-m-d', strtotime('monday this week')) . ' 00:00:00';
        $now_utc    = gmdate('Y-m-d H:i:s');

        $posts_this_week = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$wpdb->prefix}amai_scheduled_posts WHERE status = 'posted' AND scheduled_utc >= %s",
            $monday_utc
        ));
        $pending_approval = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->prefix}amai_scheduled_posts WHERE status = 'draft'"
        );
        $next_post_utc = $wpdb->get_var($wpdb->prepare(
            "SELECT scheduled_utc FROM {$wpdb->prefix}amai_scheduled_posts WHERE status = 'approved' AND scheduled_utc > %s ORDER BY scheduled_utc ASC LIMIT 1",
            $now_utc
        ));
        $next_post_label = 'None scheduled';
        if ($next_post_utc !== null) {
            $diff_seconds = strtotime($next_post_utc) - time();
            if ($diff_seconds < 3600) {
                $next_post_label = '< 1 hour';
            } elseif ($diff_seconds < 86400) {
                $next_post_label = 'Today';
            } elseif ($diff_seconds < 172800) {
                $next_post_label = 'Tomorrow';
            } else {
                $next_post_label = gmdate('D M j', strtotime($next_post_utc));
            }
        }

        $data = compact(
            'license_status', 'license_key', 'current_tab', 'is_free',
            'free_limit_reached', 'active_ai_count', 'active_modules',
            'ai_providers', 'image_providers', 'email_providers', 'sms_providers', 'analytics_providers', 'other_modules', 'connected_channel_count',
            'total_provider_count', 'posts_this_week', 'pending_approval', 'next_post_label'
        );
        extract($data);
        ?>
        <div class="wrap" id="automarketer-ai-dashboard">
            <?php if ($current_tab === 'dashboard'): ?>
                <?php include AMAI_PLUGIN_DIR . 'templates/dashboard.php'; ?>
            <?php endif; ?>

            <?php if ($current_tab === 'setup'): ?>
                <?php include AMAI_PLUGIN_DIR . 'templates/setup.php'; ?>
            <?php endif; ?>

            <?php if ($current_tab === 'modules'): ?>
                <?php include AMAI_PLUGIN_DIR . 'templates/modules.php'; ?>
            <?php endif; ?>

            <?php if ($current_tab === 'billing'): ?>
                <?php
                $plans        = \amai_get_plans();
                $current_plan = get_option('automarketer_ai_plan_id', 'free');
                include AMAI_PLUGIN_DIR . 'templates/billing.php';
                ?>
            <?php endif; ?>
        </div>
        <?php
    }

    // ── AJAX: proxy subscription summary to Core ──────────────────────
    public function handle_dashboard_subscription(): void
    {
        check_ajax_referer('amai_dashboard_subscription', '_ajax_nonce');

        if (!current_user_can('manage_automarketer_ai')) {
            wp_send_json_error(['message' => 'Unauthorized']);
            return;
        }

        $sub_id  = sanitize_text_field((string) ($_POST['sub_id']  ?? ''));
        $cust_id = sanitize_text_field((string) ($_POST['cust_id'] ?? ''));

        if ($sub_id === '' && $cust_id === '') {
            wp_send_json_error(['message' => 'No subscription identifier']);
            return;
        }

        if ($sub_id !== '' && !str_starts_with($sub_id, 'sub_')) {
            wp_send_json_error(['message' => 'Invalid sub_id']);
            return;
        }

        if ($cust_id !== '' && !str_starts_with($cust_id, 'cus_')) {
            wp_send_json_error(['message' => 'Invalid cust_id']);
            return;
        }

        $query_params = [];
        if ($sub_id !== '') {
            $query_params['sub_id'] = $sub_id;
        } elseif ($cust_id !== '') {
            $query_params['cust_id'] = $cust_id;
        }

        $query_string = http_build_query($query_params);
        $path         = '/api/stripe/subscription-summary';
        $core_url     = 'https://core.automarketer-ai.com' . $path . '?' . $query_string;

        $method    = 'GET';
        $timestamp = (string) time();
        $nonce     = bin2hex(random_bytes(16));
        $tenant    = amai_tenant_id();
        $key_id    = 'WP_PROXY';
        $body      = '';

        $raw_secret = (string) get_option('amai_tenant_hmac_secret', '');
        if ($raw_secret === '') {
            return;
        }
        $secret    = hex2bin($raw_secret);
        $body_b64  = base64_encode(hash('sha256', $body, true));
        $canonical = implode('|', [$method, $path, $timestamp, $nonce, $tenant, $key_id, $body_b64]);
        $signature = rtrim(base64_encode(hash_hmac('sha256', $canonical, $secret, true)), "\n");

        $core_response = wp_remote_get($core_url, [
            'timeout' => 15,
            'headers' => [
                'X-Amai-Tenant'      => $tenant,
                'X-Amai-Key-Id'      => $key_id,
                'X-Amai-Timestamp'   => $timestamp,
                'X-Amai-Nonce'       => $nonce,
                'X-Amai-Body-SHA256' => $body_b64,
                'X-Amai-Signature'   => $signature,
            ],
        ]);

        if (is_wp_error($core_response)) {
            wp_send_json_error(['message' => 'Core connection failed']);
            return;
        }

        $code = wp_remote_retrieve_response_code($core_response);
        $raw  = wp_remote_retrieve_body($core_response);
        $body = json_decode($raw, true);

        if ($code !== 200 || !is_array($body)) {
            wp_send_json_error(['message' => 'Subscription fetch failed']);
            return;
        }

        wp_send_json_success($body);
    }

    public function handle_toggle(): void
    {
        $is_ajax = defined('DOING_AJAX') && DOING_AJAX;

        if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['_wpnonce'])),
            'amai_module_toggle'
        )) {
            if ($is_ajax) { wp_send_json_error(['message' => 'Nonce failed']); }
            wp_die('Nonce failed.');
        }

        $module_action = sanitize_key((string) ($_POST['module_action'] ?? ''));
        $module_id     = sanitize_key((string) ($_POST['module_id']     ?? ''));

        if (empty($module_id)) { wp_die('Invalid request.'); }
        if (!current_user_can('manage_automarketer_ai')) { wp_die('Unauthorized'); }

        $active_modules = (array) get_option('amai_active_modules', []);
        $changed        = false;

        if ($module_action === 'activate' && !in_array($module_id, $active_modules, true)) {
            $current_plan = (string) get_option('automarketer_ai_plan_id', 'free');
            if (PlanEnforcer::isPremium($module_id) && !in_array($current_plan, ['unlimited_ai', 'agency'], true)) {
                if ($is_ajax) { wp_send_json_error(['message' => 'This module requires an Unlimited AI plan or above.']); }
                wp_die('This module requires an Unlimited AI plan or above.');
            }
            if (in_array($current_plan, ['starter', 'starter_pro'], true)
                && !str_starts_with($module_id, 'ai-')
                && !str_starts_with($module_id, 'img-')
                && !in_array($module_id, ['facebook', 'instagram'], true)
                && PlanEnforcer::starterSlotsFull($active_modules)
            ) {
                if ($is_ajax) { wp_send_json_error(['message' => 'You have reached the 5-module limit for your Starter plan. Deactivate a module first.']); }
                wp_die('You have reached the 5-module limit for your Starter plan. Deactivate a module first.');
            }
            $active_modules[] = $module_id;
            $changed          = true;
        } elseif ($module_action === 'deactivate') {
            $key = array_search($module_id, $active_modules, true);
            if ($key !== false) {
                unset($active_modules[$key]);
                $changed = true;

                if (str_starts_with($module_id, 'ai-')) {
                    AiProviderSync::remove($module_id);
                }
            }
        }

        if ($changed) {
            update_option('amai_active_modules', array_unique(array_values($active_modules)));
        }

        if ($is_ajax) {
            wp_send_json_success(['active' => in_array($module_id, $active_modules, true)]);
        }

        wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-modules'));
        exit;
    }

    public function handle_activate_provider(): void
    {
        if (!current_user_can('manage_automarketer_ai')) {
            wp_send_json_error(['message' => 'Unauthorized']);
            return;
        }

        check_ajax_referer('amai_provider_actions', '_ajax_nonce');

        $provider_id = sanitize_text_field((string) ($_POST['provider_id'] ?? ''));
        $api_key     = sanitize_text_field((string) ($_POST['api_key']     ?? ''));
        $model       = sanitize_text_field((string) ($_POST['model']       ?? ''));

        if (empty($provider_id) || empty($api_key)) {
            wp_send_json_error(['message' => 'Missing provider or API key.']);
            return;
        }

        $modules = $this->load_modules();
        $module  = $modules[$provider_id] ?? null;

        if (!$module) {
            wp_send_json_error(['message' => 'Provider not found.']);
            return;
        }

        if (!$module->validate_api_key($api_key)) {
            wp_send_json_error(['message' => 'Invalid API key for ' . $module->get_name() . '. Please check your key and try again.']);
            return;
        }

        update_option('amai_api_key_' . $provider_id, KeyVault::encrypt($api_key));

        if (!empty($model)) {
            update_option('amai_model_' . $provider_id, $model);
        }

        $active_modules = (array) get_option('amai_active_modules', []);

        if (!in_array($provider_id, $active_modules, true)) {
            $active_modules[] = $provider_id;
            update_option('amai_active_modules', array_unique(array_values($active_modules)));
        }

        $resolved_model = !empty($model) ? $model : (string) get_option('amai_model_' . $provider_id, '');
        AiProviderSync::store($provider_id, $api_key, $resolved_model);

        wp_send_json_success(['message' => 'Activated successfully']);
    }

    public function handle_get_provider_data(): void
    {
        if (!current_user_can('manage_automarketer_ai')) {
            wp_send_json_error(['message' => 'Unauthorized']);
            return;
        }

        if (!isset($_POST['_ajax_nonce']) || !wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['_ajax_nonce'])),
            'amai_provider_actions'
        )) {
            wp_send_json_error(['message' => 'Nonce verification failed']);
            return;
        }

        $provider_id = sanitize_text_field((string) ($_POST['provider_id'] ?? ''));

        if (empty($provider_id)) {
            wp_send_json_error(['message' => 'Missing provider ID']);
            return;
        }

        $modules = $this->load_modules();
        $module  = $modules[$provider_id] ?? null;

        if (!$module) {
            wp_send_json_error(['message' => 'Provider not found']);
            return;
        }

        $api_key = sanitize_text_field((string) ($_POST['api_key'] ?? ''));
        if ($api_key === '') {
            $api_key = KeyVault::decrypt((string) get_option('amai_api_key_' . $provider_id, ''));
        }

        // Try Core registry first (1-hour transient). Falls back to live or local models.
        $core_registry    = get_transient('amai_core_models_registry');
        if ($core_registry === false) {
            $core_registry = AiProviderSync::fetchModels();
            if (!empty($core_registry)) {
                set_transient('amai_core_models_registry', $core_registry, HOUR_IN_SECONDS);
            }
        }
        // Map WP provider ID to Core provider key to look up in registry.
        $core_provider_map = [
            'ai-claude'  => 'claude',
            'ai-openai'  => 'openai',
            'ai-gemini'  => 'gemini',
            'ai-grok'    => 'grok',
            'ai-mistral' => 'mistral',
        ];
        $core_key = $core_provider_map[$provider_id] ?? '';

        // Try Core image registry first (1-hour transient). Falls back to local module data.
        $image_provider_map = [
            'img-imagen' => 'imagen',
            'img-aurora' => 'aurora',
            'img-dalle'  => 'dalle',
            'img-flux'   => 'flux',
            'img-sd'     => 'sd',
        ];
        $image_core_key = $image_provider_map[$provider_id] ?? '';
        $image_registry = [];
        if ($image_core_key !== '') {
            $image_registry = get_transient('amai_core_image_models_registry');
            if ($image_registry === false) {
                $image_registry = AiProviderSync::fetchImageModels();
                if (!empty($image_registry)) {
                    set_transient('amai_core_image_models_registry', $image_registry, HOUR_IN_SECONDS);
                }
            }
        }
        if ($image_core_key !== '' && !empty($image_registry[$image_core_key]['models'])) {
            $models = $image_registry[$image_core_key]['models'];
        } elseif ($core_key !== '' && !empty($core_registry[$core_key]['models'])) {
            $models = $core_registry[$core_key]['models'];
        } elseif ($api_key !== '' && method_exists($module, 'fetch_live_models')) {
            $models = $module->fetch_live_models($api_key);
        } else {
            $models = $module->get_available_models();
        }

        $formatted = [];
        foreach ($models as $value => $label) {
            $formatted[] = ['value' => $value, 'label' => $label];
        }

        $model_costs = method_exists($module, 'get_model_costs') ? $module->get_model_costs() : [];

        $saved_model = (string) get_option('amai_model_' . $provider_id, '');
        if ($saved_model !== '') {
            $recommended_model = $saved_model;
        } elseif (method_exists($module, 'get_default_model')) {
            $recommended_model = $module->get_default_model();
        } elseif (!empty($formatted)) {
            $recommended_model = $formatted[0]['value'];
        } else {
            $recommended_model = '';
        }

        ModelWatcher::clearNewModels($provider_id);

        wp_send_json_success([
            'prefix'             => $module->get_api_key_prefix(),
            'models'             => $formatted,
            'current_model'      => $saved_model,
            'recommended_model'  => $recommended_model,
            'model_costs'        => !empty($image_registry[$image_core_key]['costs'])
                ? $image_registry[$image_core_key]['costs']
                : $model_costs,
            'model_descriptions' => !empty($image_registry[$image_core_key]['descriptions'])
                ? $image_registry[$image_core_key]['descriptions']
                : (!empty($core_registry[$core_key]['descriptions'])
                    ? $core_registry[$core_key]['descriptions']
                    : (method_exists($module, 'get_model_descriptions') ? $module->get_model_descriptions() : [])),
        ]);
    }

    public function handle_update_model(): void
    {
        if (!current_user_can('manage_automarketer_ai')) {
            wp_send_json_error(['message' => 'Unauthorized']);
            return;
        }

        if (!isset($_POST['_ajax_nonce']) || !wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['_ajax_nonce'])),
            'amai_provider_actions'
        )) {
            wp_send_json_error(['message' => 'Nonce verification failed']);
            return;
        }

        $provider_id = sanitize_key((string)        ($_POST['provider_id'] ?? ''));
        $model       = sanitize_text_field((string) ($_POST['model']       ?? ''));
        $model_label = sanitize_text_field((string) ($_POST['model_label'] ?? ''));

        if (empty($provider_id) || empty($model)) {
            wp_send_json_error(['message' => 'Missing provider or model']);
            return;
        }

        update_option('amai_model_' . $provider_id, $model);
        if ($model_label !== '') {
            update_option('amai_model_label_' . $provider_id, $model_label);
        }

        $api_key = KeyVault::decrypt((string) get_option('amai_api_key_' . $provider_id, ''));
        if ($api_key !== '') {
            AiProviderSync::store($provider_id, $api_key, $model);
        }

        wp_send_json_success(['message' => 'Model updated successfully']);
    }

    public function admin_notices(): void
    {
        if (isset($_GET['message']) && $_GET['message'] === 'provider_activated') {
            echo '<div class="notice notice-success is-dismissible"><p>Activated successfully!</p></div>';
        }

        $provider_id = get_transient('amai_provider_credit_warning');
        if ($provider_id && get_transient('amai_credit_warning_dismissed')) {
            $provider_id = false;
        }
        if ($provider_id) {
        $billing_urls = [
            'ai-claude'   => 'https://console.anthropic.com/settings/billing',
            'ai-openai'   => 'https://platform.openai.com/settings/organization/billing/overview',
            'ai-gemini'   => 'https://console.cloud.google.com/billing',
            'ai-grok'     => 'https://console.x.ai',
            'ai-mistral'  => 'https://console.mistral.ai/billing',
        ];
            $billing_url  = $billing_urls[$provider_id] ?? '';
            $provider_name = ucfirst(str_replace('ai-', '', $provider_id));
            $nonce        = wp_create_nonce('amai_dismiss_credit_warning');
            $dismiss_url  = admin_url('admin-ajax.php?action=amai_dismiss_credit_warning&_wpnonce=' . $nonce);
            echo '<div id="amai-credit-warning-wrap" style="margin:16px 0 0;">';
            echo '<div id="amai-credit-warning" style="display:inline-flex;align-items:center;gap:10px;max-width:620px;border-left:4px solid #D97757;border-top:1px solid #D97757;border-right:1px solid #D97757;border-bottom:1px solid #D97757;background:#fff;border-radius:0 6px 6px 0;padding:11px 16px;">';
            echo '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" style="flex-shrink:0;color:#D97757;" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>';
            echo '<p style="margin:0;font-size:13.5px;color:#1c1917;">';
            echo 'Your <strong>' . esc_html($provider_name) . '</strong> API key returned an authentication or quota error. ';
            if ($billing_url) {
                echo '<a href="' . esc_url($billing_url) . '" target="_blank" rel="noopener noreferrer" style="color:#D97757;font-weight:500;">Check your billing account</a> to make sure credits are available.';
            } else {
                echo 'Check your API provider account to make sure credits are available.';
            }
            echo '</p>';
            echo '<a href="' . esc_url($dismiss_url) . '" id="amai-credit-warning-dismiss" style="margin-left:12px;white-space:nowrap;font-size:12px;color:#a8a29e!important;text-decoration:none!important;flex-shrink:0;background:none!important;border:none!important;padding:0!important;cursor:pointer;font-family:inherit;box-shadow:none!important;">Dismiss</a>';
            echo '</div></div>';
            echo '<script>document.getElementById("amai-credit-warning-dismiss").addEventListener("click",function(e){e.preventDefault();var wrap=document.getElementById("amai-credit-warning-wrap");wrap.style.transition="all 0.2s ease";wrap.style.overflow="hidden";wrap.style.maxHeight=wrap.offsetHeight+"px";requestAnimationFrame(function(){wrap.style.maxHeight="0";wrap.style.marginTop="0";});setTimeout(function(){wrap.remove();},220);fetch(e.target.href);});</script>';
        }
    }


    public function handle_dismiss_credit_warning(): void
    {
        check_ajax_referer('amai_dismiss_credit_warning');
        set_transient('amai_credit_warning_dismissed', '1', HOUR_IN_SECONDS);
        wp_send_json_success();
    }

    private function load_modules(): array
    {
        $modules    = [];
        $module_dir = AMAI_PLUGIN_DIR . '/modules';

        if (!is_dir($module_dir)) {
            return $modules;
        }

        $iterator = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($module_dir)
        );

        foreach ($iterator as $file) {
            if (
                $file->isDir() ||
                $file->getExtension() !== 'php' ||
                $file->getFilename() === 'index.php'
            ) {
                continue;
            }

            require_once $file->getPathname();

            $basename = $file->getBasename('.php');
            if (str_starts_with($basename, 'img-')) {
                $clean = 'Img' . ucfirst(str_replace('-', '', substr($basename, 4)));
            } elseif (str_starts_with($basename, 'email-')) {
                $clean = 'Email' . ucfirst(str_replace('-', '', substr($basename, 6)));
            } elseif (str_starts_with($basename, 'sms-')) {
                $clean = 'Sms' . ucfirst(str_replace('-', '', substr($basename, 4)));
            } elseif (str_starts_with($basename, 'analytics-')) {
                $clean = 'Analytics' . ucfirst(str_replace('-', '', substr($basename, 10)));
            } else {
                $clean = str_replace(['ai-', '-'], ['', ''], $basename);
            }
            $class = '\\AutoMarketerAI\\Modules\\' . ucfirst($clean);
            if (
                class_exists($class) &&
                is_subclass_of($class, '\AutoMarketerAI\ModuleInterface')
            ) {
                $m                     = new $class();
                $modules[$m->get_id()] = $m;
                $m->register();
            }
        }

        return $modules;
    }

    private function filter_ai_providers(array $modules): array
    {
        return array_filter(
            $modules,
            static fn($id) => str_starts_with($id, 'ai-'),
            ARRAY_FILTER_USE_KEY
        );
    }

    private function filter_image_providers(array $modules): array
    {
        return array_filter(
            $modules,
            static fn($id) => str_starts_with($id, 'img-'),
            ARRAY_FILTER_USE_KEY
        );
    }
    private function filter_analytics_providers(array $modules): array
    {
        return array_filter(
            $modules,
            static fn($id) => str_starts_with($id, 'analytics-'),
            ARRAY_FILTER_USE_KEY
        );
    }
    private function filter_email_providers(array $modules): array
    {
        return array_filter(
            $modules,
            static fn($id) => str_starts_with($id, 'email-'),
            ARRAY_FILTER_USE_KEY
        );
    }
    private function filter_sms_providers(array $modules): array
    {
        return array_filter(
            $modules,
            static fn($id) => str_starts_with($id, 'sms-'),
            ARRAY_FILTER_USE_KEY
        );
    }

    public function handle_create_checkout_session(): void
    {
        check_ajax_referer('amai_create_checkout', '_ajax_nonce');

        if (!current_user_can('manage_automarketer_ai')) {
            wp_send_json_error(['message' => 'Unauthorized']);
            return;
        }

        $plan_id  = sanitize_text_field((string) ($_POST['plan_id']  ?? ''));
        $addon_id = sanitize_text_field((string) ($_POST['addon_id'] ?? ''));

        if (empty($plan_id)) {
            wp_send_json_error(['message' => 'Missing plan ID']);
            return;
        }

        $core_url  = 'https://core.automarketer-ai.com/api/stripe/create-checkout';
        $body_data = [
            'plan_id' => $plan_id,
            'user_id' => get_current_user_id(),
            'email'   => wp_get_current_user()->user_email,
        ];

        if ($addon_id !== '') {
            $body_data['addon_id'] = $addon_id;
        }

        $body      = (string) json_encode($body_data);
        $method    = 'POST';
        $path      = '/api/stripe/create-checkout';
        $timestamp = (string) time();
        $nonce     = bin2hex(random_bytes(16));
        $tenant    = amai_tenant_id();
        $key_id    = 'WP_PROXY';

        $raw_secret = (string) get_option('amai_tenant_hmac_secret', '');
        if ($raw_secret === '') {
            return;
        }
        $secret    = hex2bin($raw_secret);
        $body_b64  = base64_encode(hash('sha256', $body, true));
        $canonical = implode('|', [$method, $path, $timestamp, $nonce, $tenant, $key_id, $body_b64]);
        $signature = rtrim(base64_encode(hash_hmac('sha256', $canonical, $secret, true)), "\n");

        $core_response = wp_remote_post($core_url, [
            'timeout' => 45,
            'headers' => [
                'Content-Type'       => 'application/json',
                'X-Amai-Tenant'      => $tenant,
                'X-Amai-Key-Id'      => $key_id,
                'X-Amai-Timestamp'   => $timestamp,
                'X-Amai-Nonce'       => $nonce,
                'X-Amai-Body-SHA256' => $body_b64,
                'X-Amai-Signature'   => $signature,
            ],
            'body' => $body,
        ]);

        if (is_wp_error($core_response)) {
            wp_send_json_error(['message' => 'Core connection failed: ' . $core_response->get_error_message()]);
            return;
        }

        $response_code = wp_remote_retrieve_response_code($core_response);
        $raw_body      = wp_remote_retrieve_body($core_response);
        $response_body = json_decode($raw_body, true);

        if (
            $response_code === 200 &&
            isset($response_body['session_id']) &&
            $response_body['session_id'] !== ''
        ) {
            wp_send_json_success(['session_id' => $response_body['session_id']]);
            return;
        }

        $error_msg = is_array($response_body) && isset($response_body['error'])
            ? $response_body['error']
            : 'Unknown error from Core (code: ' . $response_code . ')';

        wp_send_json_error(['message' => $error_msg]);
    }

    // ── AJAX: set business type override ─────────────────────────────
    public function handle_set_business_type(): void
    {
        check_ajax_referer('amai_set_business_type', '_ajax_nonce');
        if (!current_user_can('manage_automarketer_ai')) {
            wp_send_json_error(['message' => 'Unauthorized']);
            return;
        }
        $type = sanitize_key((string) ($_POST['business_type'] ?? ''));
        $allowed = ['saas', 'service', 'local', 'product', 'mixed', 'auto'];
        if (!in_array($type, $allowed, true)) {
            wp_send_json_error(['message' => 'Invalid business type']);
            return;
        }
        if ($type === 'auto') {
            delete_option('amai_business_type_override');
        } else {
            update_option('amai_business_type_override', $type);
        }
        wp_send_json_success(['business_type' => $type]);
    }

}