<?php
/**
 * Admin Controller
 * Fixes: #10 nonce on AJAX, #11 capability checks everywhere,
 *        #16 full escaping audit, #18 asset versioning, #20 schema validation
 *
 * @package EPWF\Admin
 */
namespace EPWF\Admin;

use EPWF\Includes\Settings;
use EPWF\Includes\FAQ_Manager;

defined( 'ABSPATH' ) || exit;

class Admin {

    /** @var Settings */
    private $s;
    /** @var FAQ_Manager */
    private $m;

    const PAGE = 'exertpro-faq-ai';
    const CAP  = 'manage_woocommerce';

    public function __construct( Settings $s, FAQ_Manager $m ) {
        $this->s = $s;
        $this->m = $m;
    }

    // ── Menu ───────────────────────────────────────────────────────────────────

    public function menu() {
        add_submenu_page(
            'woocommerce',
            esc_html__( 'ExertPro FAQ AI for WooCommerce', 'exertpro-faq-ai' ),
            esc_html__( 'ExertPro FAQ AI for WooCommerce', 'exertpro-faq-ai' ),
            self::CAP,
            self::PAGE,
            [ $this, 'page' ]
        );
    }

    public function register_settings() {
        register_setting( 'epwf_group', EPWF_OPTION_KEY, [
            'type'              => 'array',
            'sanitize_callback' => [ $this->s, 'sanitize' ],
        ] );
    }

    // ── Assets — Fix #18: file-based versioning ────────────────────────────────

    public function assets( $hook ) {
        $screen   = get_current_screen();
        $on_page  = 'woocommerce_page_' . self::PAGE === $hook;
        $on_prod  = in_array( $hook, [ 'post.php', 'post-new.php' ], true )
                    && $screen && 'product' === $screen->post_type;

        if ( ! $on_page && ! $on_prod ) return;

        // Fix #18: file-mtime versioning so browsers auto-bust cache on deploy
        $admin_css = EPWF_PATH . 'assets/css/admin.css';
        $admin_js  = EPWF_PATH . 'assets/js/admin.js';
        $css_ver   = file_exists( $admin_css ) ? filemtime( $admin_css ) : EPWF_VERSION;
        $js_ver    = file_exists( $admin_js )  ? filemtime( $admin_js )  : EPWF_VERSION;

        wp_enqueue_style( 'epwf-admin', EPWF_ASSETS_URL . 'css/admin.css', [], $css_ver );
        wp_enqueue_script( 'epwf-admin', EPWF_ASSETS_URL . 'js/admin.js', [ 'jquery' ], $js_ver, true );
        wp_enqueue_style( 'wp-color-picker' );
        wp_enqueue_script( 'wp-color-picker' );

        // Fix #10: nonce passed to JS
        wp_localize_script( 'epwf-admin', 'epwfAdmin', [
            'ajax'        => admin_url( 'admin-ajax.php' ),
            'nonce'       => wp_create_nonce( 'epwf_ajax_nonce' ),
            'generating'  => esc_html__( 'Generating FAQs…', 'exertpro-faq-ai' ),
            'err'         => esc_html__( 'Generation failed. Check your API key and try again.', 'exertpro-faq-ai' ),
            'confirm_del' => esc_html__( 'Remove this FAQ?', 'exertpro-faq-ai' ),
        ] );
    }

    // ── Settings Page — Fix #11 cap check, #16 full escaping ──────────────────

    public function page() {
        // Fix #11: capability check at render time
        if ( ! current_user_can( self::CAP ) ) {
            wp_die( esc_html__( 'You do not have permission to access this page.', 'exertpro-faq-ai' ) );
        }

        $o      = $this->s->get_all();
        $models = Settings::$AI_MODELS;
        $hooks  = Settings::$HOOK_LABELS;

        $provider_meta = [
            'openai'    => [ 'icon' => '🟢', 'name' => 'OpenAI',          'color' => '#10a37f' ],
            'gemini'    => [ 'icon' => '🔵', 'name' => 'Google Gemini',    'color' => '#4285f4' ],
            'anthropic' => [ 'icon' => '🟠', 'name' => 'Anthropic Claude', 'color' => '#d4562f' ],
            'grok'      => [ 'icon' => '⚡',  'name' => 'xAI Grok',         'color' => '#1a1a1a' ],
            'kimi'      => [ 'icon' => '🌙', 'name' => 'Moonshot Kimi',    'color' => '#7c3aed' ],
        ];

        // Fix #5 + #6: Privacy disclosure link in admin
        $privacy_url  = get_privacy_policy_url();
        $api_fields   = [
            'openai_key'    => [ 'label' => 'OpenAI API Key',          'ph' => 'sk-…',     'link' => 'https://platform.openai.com/api-keys' ],
            'gemini_key'    => [ 'label' => 'Google Gemini API Key',   'ph' => 'AIza…',    'link' => 'https://aistudio.google.com/app/apikey' ],
            'anthropic_key' => [ 'label' => 'Anthropic (Claude) Key',  'ph' => 'sk-ant-…', 'link' => 'https://console.anthropic.com/keys' ],
            'grok_key'      => [ 'label' => 'xAI Grok API Key',        'ph' => 'xai-…',    'link' => 'https://console.x.ai/' ],
            'kimi_key'      => [ 'label' => 'Moonshot Kimi API Key',   'ph' => 'sk-…',     'link' => 'https://platform.moonshot.cn/console/api-keys' ],
        ];

        // Group models by provider
        $groups = [];
        foreach ( $models as $mid => $info ) {
            $groups[ $info['provider'] ][ $mid ] = $info;
        }

        $styles = [
            'modern'  => [ 'name' => 'Modern',  'desc' => 'Gradient left border + card shadow' ],
            'minimal' => [ 'name' => 'Minimal', 'desc' => 'Clean, borderless lines' ],
            'boxed'   => [ 'name' => 'Boxed',   'desc' => 'Each FAQ in its own card' ],
        ];
        ?>
        <div class="epwf-header">
            <div class="epwf-header-inner">
                <div class="epwf-logo">
                    <span class="epwf-logo-icon" aria-hidden="true">🤖</span>
                    <div>
                        <h1><?php esc_html_e( 'ExertPro FAQ AI for WooCommerce', 'exertpro-faq-ai' ); ?></h1>
                        <p><?php esc_html_e( 'AI FAQ Generator & FAQ Schema for WooCommerce Products', 'exertpro-faq-ai' ); ?></p>
                    </div>
                </div>
                <span class="epwf-version-badge">v<?php echo esc_html( EPWF_VERSION ); ?></span>
            </div>
        </div>

        <div class="wrap epwf-admin-wrap">

            <!-- Fix #5: External API disclosure notice -->
            <div class="epwf-disclosure-notice notice notice-info inline">
                <p>
                    <strong><?php esc_html_e( 'External Service Disclosure:', 'exertpro-faq-ai' ); ?></strong>
                    <?php esc_html_e( 'This plugin transmits product titles and descriptions to your selected AI provider to generate FAQs. No customer or order data is transmitted.', 'exertpro-faq-ai' ); ?>
                    <?php if ( $privacy_url ) : ?>
                        <a href="<?php echo esc_url( $privacy_url ); ?>"><?php esc_html_e( 'View Privacy Policy →', 'exertpro-faq-ai' ); ?></a>
                    <?php endif; ?>
                </p>
            </div>

            <?php settings_errors( 'epwf_group' ); ?>

            <form method="post" action="options.php" id="epwf-form">
                <?php settings_fields( 'epwf_group' ); ?>

                <div class="epwf-tabs-wrap">

                    <div class="epwf-tab-nav" role="tablist">
                        <?php
                        $tabs = [
                            'ai'      => [ 'icon' => '🤖', 'label' => __( 'AI Configuration',   'exertpro-faq-ai' ) ],
                            'hook'    => [ 'icon' => '📌', 'label' => __( 'Hook Position',       'exertpro-faq-ai' ) ],
                            'style'   => [ 'icon' => '🎨', 'label' => __( 'Style Customization', 'exertpro-faq-ai' ) ],
                            'display' => [ 'icon' => '⚙️', 'label' => __( 'Display Options',     'exertpro-faq-ai' ) ],
                        ];
                        foreach ( $tabs as $tid => $tab ) : ?>
                        <button type="button"
                            class="epwf-tab-btn <?php echo esc_attr( 'ai' === $tid ? 'is-active' : '' ); ?>"
                            data-tab="<?php echo esc_attr( $tid ); ?>"
                            role="tab"
                            aria-selected="<?php echo esc_attr( 'ai' === $tid ? 'true' : 'false' ); ?>"
                            aria-controls="epwf-tab-<?php echo esc_attr( $tid ); ?>">
                            <span class="tab-icon" aria-hidden="true"><?php echo esc_html( $tab['icon'] ); ?></span>
                            <?php echo esc_html( $tab['label'] ); ?>
                        </button>
                        <?php endforeach; ?>
                    </div>

                    <!-- ══ TAB 1: AI Configuration ═════════════════════════════ -->
                    <div class="epwf-tab-panel is-active" id="epwf-tab-ai" role="tabpanel">

                        <div class="epwf-card">
                            <h2 class="epwf-card-title"><?php esc_html_e( 'General Settings', 'exertpro-faq-ai' ); ?></h2>

                            <?php $this->field_row(
                                __( 'Enable Plugin', 'exertpro-faq-ai' ),
                                $this->toggle( 'enabled', ! empty( $o['enabled'] ) ),
                                __( 'Show AI-generated FAQs on product pages.', 'exertpro-faq-ai' )
                            ); ?>

                            <?php $this->field_row(
                                __( 'Auto-Generate on Save', 'exertpro-faq-ai' ),
                                $this->toggle( 'auto_generate', ! empty( $o['auto_generate'] ) ),
                                __( 'Auto-call AI when product title or description changes.', 'exertpro-faq-ai' )
                            ); ?>

                            <?php $this->field_row(
                                __( 'FAQs per Generation', 'exertpro-faq-ai' ),
                                '<input type="number" name="' . esc_attr( EPWF_OPTION_KEY ) . '[faq_count]" value="' . absint( $o['faq_count'] ) . '" min="1" max="20" class="epwf-input-sm">',
                                __( '1–20 FAQs per AI call. Default: 5.', 'exertpro-faq-ai' )
                            ); ?>

                            <?php $this->field_row(
                                __( 'Additive Mode', 'exertpro-faq-ai' ),
                                $this->toggle( 'additive_mode', ! empty( $o['additive_mode'] ) ),
                                __( 'Re-generating <strong>appends</strong> new FAQs to existing ones. Duplicate questions are skipped automatically.', 'exertpro-faq-ai' )
                            ); ?>
                        </div>

                        <div class="epwf-ai-two-col">

                            <!-- LEFT: Provider + Model dropdowns -->
                            <div class="epwf-ai-col">
                                <div class="epwf-card">
                                    <h2 class="epwf-card-title"><?php esc_html_e( 'Select AI Provider & Model', 'exertpro-faq-ai' ); ?></h2>
                                    <p class="epwf-card-desc"><?php esc_html_e( 'Choose your AI provider then pick a model.', 'exertpro-faq-ai' ); ?></p>

                                    <?php
                                    // Derive active provider from saved model
                                    $active_provider = '';
                                    foreach ( $groups as $prov => $pmodels ) {
                                        if ( isset( $pmodels[ $o['ai_model'] ] ) ) { $active_provider = $prov; break; }
                                    }
                                    ?>

                                    <?php $this->field_row(
                                        __( 'AI Provider', 'exertpro-faq-ai' ),
                                        '<select id="epwf-provider-select" class="epwf-select">'
                                        . implode( '', array_map( function( $prov, $pm ) use ( $active_provider ) {
                                            return '<option value="' . esc_attr( $prov ) . '"'
                                                . ( $active_provider === $prov ? ' selected' : '' )
                                                . '>' . esc_html( $pm['icon'] . ' ' . $pm['name'] ) . '</option>';
                                        }, array_keys( $provider_meta ), $provider_meta ) )
                                        . '</select>',
                                        __( 'Select the AI service you want to use.', 'exertpro-faq-ai' )
                                    ); ?>

                                    <?php $this->field_row(
                                        __( 'AI Model', 'exertpro-faq-ai' ),
                                        '<select id="epwf-model-select" name="' . esc_attr( EPWF_OPTION_KEY ) . '[ai_model]" class="epwf-select">'
                                        . implode( '', array_map( function( $mid, $info ) use ( $o ) {
                                            return '<option value="' . esc_attr( $mid ) . '"'
                                                . ' data-provider="' . esc_attr( $info['provider'] ) . '"'
                                                . ( $o['ai_model'] === $mid ? ' selected' : '' )
                                                . '>' . esc_html( $info['label'] ) . '</option>';
                                        }, array_keys( $groups[ $active_provider ] ?? array_keys( $models ) ), $active_provider ? $groups[ $active_provider ] : $models ) )
                                        . '</select>',
                                        __( 'Model options update when you change provider.', 'exertpro-faq-ai' )
                                    ); ?>

                                    <div id="epwf-model-options-store" style="display:none;">
                                        <?php foreach ( $groups as $prov => $pmodels ) : ?>
                                        <div data-provider="<?php echo esc_attr( $prov ); ?>">
                                            <?php foreach ( $pmodels as $mid => $info ) : ?>
                                            <option value="<?php echo esc_attr( $mid ); ?>"
                                                data-provider="<?php echo esc_attr( $prov ); ?>"
                                                <?php selected( $o['ai_model'], $mid ); ?>>
                                                <?php echo esc_html( $info['label'] ); ?>
                                            </option>
                                            <?php endforeach; ?>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div><!-- .epwf-ai-col left -->

                            <!-- RIGHT: API Keys -->
                            <div class="epwf-ai-col">
                                <div class="epwf-card">
                                    <h2 class="epwf-card-title"><?php esc_html_e( 'API Keys', 'exertpro-faq-ai' ); ?></h2>
                                    <p class="epwf-card-desc">
                                        <?php esc_html_e( 'Only the key for your selected provider is used. Keys are stored securely.', 'exertpro-faq-ai' ); ?>
                                    </p>
                                    <?php foreach ( $api_fields as $k => $f ) :
                                        $prov_slug = str_replace( '_key', '', $k ); ?>
                                    <div class="epwf-field-row epwf-key-field" data-provider="<?php echo esc_attr( $prov_slug ); ?>">
                                        <label class="epwf-label" for="epwf-<?php echo esc_attr( $k ); ?>"><?php echo esc_html( $f['label'] ); ?></label>
                                        <div class="epwf-field-val">
                                            <div class="epwf-key-row">
                                                <input
                                                    type="password"
                                                    id="epwf-<?php echo esc_attr( $k ); ?>"
                                                    name="<?php echo esc_attr( EPWF_OPTION_KEY ); ?>[<?php echo esc_attr( $k ); ?>]"
                                                    value=""
                                                    placeholder="<?php
                                                        $masked = $this->s->get_masked_key( $k );
                                                        echo $masked ? esc_attr( $masked ) : esc_attr( $f['ph'] );
                                                    ?>"
                                                    class="regular-text epwf-key-input"
                                                    autocomplete="new-password"
                                                    aria-label="<?php echo esc_attr( $f['label'] ); ?>">
                                                <button type="button" class="button epwf-show-key" aria-label="<?php esc_attr_e( 'Show/Hide key', 'exertpro-faq-ai' ); ?>">👁</button>
                                            </div>
                                            <?php if ( $this->s->get_masked_key( $k ) ) : ?>
                                            <span class="epwf-key-saved">✅ <?php esc_html_e( 'Key saved — leave blank to keep.', 'exertpro-faq-ai' ); ?></span>
                                            <?php endif; ?>
                                            <a href="<?php echo esc_url( $f['link'] ); ?>" target="_blank" rel="noopener noreferrer" class="epwf-get-key-link">
                                                <?php esc_html_e( 'Get API key →', 'exertpro-faq-ai' ); ?>
                                            </a>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div><!-- .epwf-ai-col right -->

                        </div><!-- .epwf-ai-two-col -->
                    </div>

                    <!-- ══ TAB 2: Hook Position ═════════════════════════════════ -->
                    <div class="epwf-tab-panel" id="epwf-tab-hook" role="tabpanel">
                        <div class="epwf-hook-layout">
                            <div class="epwf-card epwf-hook-card">
                                <h2 class="epwf-card-title"><?php esc_html_e( 'Display Position', 'exertpro-faq-ai' ); ?></h2>
                                <p class="epwf-card-desc"><?php esc_html_e( 'Choose where the FAQ section appears on the single product page.', 'exertpro-faq-ai' ); ?></p>
                                <div class="epwf-hook-list" role="radiogroup">
                                    <?php foreach ( $hooks as $hk => $hl ) : $sel = $o['hook'] === $hk; ?>
                                    <label class="epwf-hook-item <?php echo esc_attr( $sel ? 'is-active' : '' ); ?>">
                                        <input type="radio" class="epwf-hook-radio"
                                            name="<?php echo esc_attr( EPWF_OPTION_KEY ); ?>[hook]"
                                            value="<?php echo esc_attr( $hk ); ?>"
                                            <?php checked( $o['hook'], $hk ); ?>>
                                        <span class="epwf-hook-dot" aria-hidden="true"></span>
                                        <span class="epwf-hook-label"><?php echo esc_html( $hl ); ?></span>
                                        <?php if ( $sel ) : ?><span class="epwf-active-badge"><?php esc_html_e( 'Active', 'exertpro-faq-ai' ); ?></span><?php endif; ?>
                                    </label>
                                    <?php endforeach; ?>
                                </div>

                                <div class="epwf-field-row" style="margin-top:20px;border-top:1px solid #f0f0f0;padding-top:16px;">
                                    <label class="epwf-label" for="epwf-priority"><?php esc_html_e( 'Priority', 'exertpro-faq-ai' ); ?></label>
                                    <div class="epwf-field-val">
                                        <input type="number" id="epwf-priority"
                                            name="<?php echo esc_attr( EPWF_OPTION_KEY ); ?>[priority]"
                                            value="<?php echo absint( $o['priority'] ); ?>"
                                            min="1" max="999" class="epwf-input-sm">
                                        <span class="epwf-hint"><?php esc_html_e( 'Lower = higher position within hook. Default: 10.', 'exertpro-faq-ai' ); ?></span>
                                    </div>
                                </div>

                                <div class="epwf-code-preview" aria-label="<?php esc_attr_e( 'Hook code preview', 'exertpro-faq-ai' ); ?>">
                                    <code id="epwf-hook-code">add_action( '<?php echo esc_html( $o['hook'] ); ?>', 'render_faq', <?php echo absint( $o['priority'] ); ?> );</code>
                                </div>
                            </div>

                            <div class="epwf-mockup-wrap" aria-hidden="true">
                                <div class="epwf-mockup-title"><?php esc_html_e( 'Position Preview', 'exertpro-faq-ai' ); ?></div>
                                <div class="epwf-mockup">
                                    <div class="epwf-mz" data-hook="woocommerce_before_single_product"><span>① Before Product</span></div>
                                    <div class="epwf-mockup-body">
                                        <div class="epwf-mockup-img"></div>
                                        <div class="epwf-mockup-info">
                                            <div class="epwf-mz" data-hook="woocommerce_before_single_product_summary"><span>② Before Summary</span></div>
                                            <div class="epwf-mockup-bar epwf-mockup-bar--title"></div>
                                            <div class="epwf-mockup-bar epwf-mockup-bar--price"></div>
                                            <div class="epwf-mz" data-hook="woocommerce_single_product_summary"><span>③ Inside Summary</span></div>
                                        </div>
                                    </div>
                                    <div class="epwf-mz epwf-mz--star" data-hook="woocommerce_after_single_product_summary"><span>④ After Summary ★ Default</span></div>
                                    <div class="epwf-mz" data-hook="woocommerce_after_single_product"><span>⑤ After Product</span></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- ══ TAB 3: Style Customization ════════════════════════════ -->
                    <div class="epwf-tab-panel" id="epwf-tab-style" role="tabpanel">

                        <div class="epwf-card">
                            <h2 class="epwf-card-title"><?php esc_html_e( 'Accordion Layout', 'exertpro-faq-ai' ); ?></h2>
                            <div class="epwf-style-picker" role="radiogroup">
                                <?php foreach ( $styles as $sv => $si ) : $sel = $o['accordion_style'] === $sv; ?>
                                <label class="epwf-style-card <?php echo esc_attr( $sel ? 'is-active' : '' ); ?>">
                                    <input type="radio" class="epwf-style-radio"
                                        name="<?php echo esc_attr( EPWF_OPTION_KEY ); ?>[accordion_style]"
                                        value="<?php echo esc_attr( $sv ); ?>"
                                        <?php checked( $o['accordion_style'], $sv ); ?>>
                                    <div class="epwf-style-preview epwf-sp--<?php echo esc_attr( $sv ); ?>" aria-hidden="true">
                                        <div class="epwf-sp-q"><?php esc_html_e( 'Sample Question?', 'exertpro-faq-ai' ); ?> <span>▾</span></div>
                                        <div class="epwf-sp-a"><?php esc_html_e( 'Answer text goes here.', 'exertpro-faq-ai' ); ?></div>
                                    </div>
                                    <div class="epwf-style-info">
                                        <strong><?php echo esc_html( $si['name'] ); ?></strong>
                                        <span><?php echo esc_html( $si['desc'] ); ?></span>
                                    </div>
                                    <?php if ( $sel ) : ?><div class="epwf-style-active"><?php esc_html_e( 'Active', 'exertpro-faq-ai' ); ?></div><?php endif; ?>
                                </label>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <div class="epwf-style-two-col">

                            <!-- LEFT COL: Font Size + Color -->
                            <div class="epwf-style-col">

                                <div class="epwf-card">
                                    <h2 class="epwf-card-title"><?php esc_html_e( 'Font Size', 'exertpro-faq-ai' ); ?></h2>
                                    <?php $this->field_row(
                                        __( 'Question Font Size', 'exertpro-faq-ai' ),
                                        '<div class="epwf-range-wrap">'
                                        . '<input type="range" id="epwf-qfont-range" name="' . esc_attr( EPWF_OPTION_KEY ) . '[question_font_size]" value="' . absint( $o['question_font_size'] ) . '" min="12" max="100" step="1" class="epwf-range" aria-valuemin="12" aria-valuemax="100" aria-valuenow="' . absint( $o['question_font_size'] ) . '">'
                                        . '<output class="epwf-range-val" id="epwf-qfont-val" for="epwf-qfont-range">' . absint( $o['question_font_size'] ) . 'px</output>'
                                        . '</div>',
                                        '12px – 100px'
                                    ); ?>
                                    <?php $this->field_row(
                                        __( 'Answer Font Size', 'exertpro-faq-ai' ),
                                        '<div class="epwf-range-wrap">'
                                        . '<input type="range" id="epwf-afont-range" name="' . esc_attr( EPWF_OPTION_KEY ) . '[answer_font_size]" value="' . absint( $o['answer_font_size'] ) . '" min="12" max="100" step="1" class="epwf-range" aria-valuemin="12" aria-valuemax="100" aria-valuenow="' . absint( $o['answer_font_size'] ) . '">'
                                        . '<output class="epwf-range-val" id="epwf-afont-val" for="epwf-afont-range">' . absint( $o['answer_font_size'] ) . 'px</output>'
                                        . '</div>',
                                        '12px – 100px'
                                    ); ?>
                                </div>

                                <div class="epwf-card">
                                    <h2 class="epwf-card-title"><?php esc_html_e( 'Color Settings', 'exertpro-faq-ai' ); ?></h2>
                                    <div class="epwf-color-list">
                                        <?php
                                        $colors = [
                                            'color_primary'   => [ 'Primary Color',   'Active border &amp; highlight' ],
                                            'color_hover'     => [ 'Hover Color',     'Question on mouse hover' ],
                                            'color_active'    => [ 'Active Color',    'Open/expanded question' ],
                                            'color_text'      => [ 'Text Color',      'Default text color' ],
                                            'color_bg'        => [ 'Background',      'FAQ wrapper background' ],
                                            'color_border'    => [ 'Border Color',    'Dividers between items' ],
                                            'color_answer_bg' => [ 'Answer BG',       'Answer panel background' ],
                                        ];
                                        foreach ( $colors as $ck => [ $cl, $cd ] ) : ?>
                                        <div class="epwf-color-item">
                                            <div class="epwf-color-swatch" style="background:<?php echo esc_attr( $o[ $ck ] ); ?>" id="swatch-<?php echo esc_attr( $ck ); ?>"></div>
                                            <div class="epwf-color-details">
                                                <label class="epwf-color-name" for="color-<?php echo esc_attr( $ck ); ?>"><?php echo esc_html( $cl ); ?></label>
                                                <span class="epwf-color-desc"><?php echo esc_html( $cd ); ?></span>
                                            </div>
                                            <input type="text"
                                                id="color-<?php echo esc_attr( $ck ); ?>"
                                                name="<?php echo esc_attr( EPWF_OPTION_KEY ); ?>[<?php echo esc_attr( $ck ); ?>]"
                                                value="<?php echo esc_attr( $o[ $ck ] ); ?>"
                                                class="epwf-color-picker"
                                                data-key="<?php echo esc_attr( $ck ); ?>"
                                                data-default-color="<?php echo esc_attr( $o[ $ck ] ); ?>">
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>

                            </div><!-- .epwf-style-col left -->

                            <!-- RIGHT COL: Spacing -->
                            <div class="epwf-style-col">

                                <div class="epwf-card">
                                    <h2 class="epwf-card-title"><?php esc_html_e( 'Spacing — Margin &amp; Padding', 'exertpro-faq-ai' ); ?></h2>
                                    <?php
                                    $spacing_fields = [
                                        'item_margin_bottom' => [ __( 'Item Gap',                    'exertpro-faq-ai' ), __( 'Space between each FAQ item',                    'exertpro-faq-ai' ), 0, 60  ],
                                        'wrap_margin_top'    => [ __( 'Section Margin Top',           'exertpro-faq-ai' ), __( 'Space above the FAQ section',                   'exertpro-faq-ai' ), 0, 100 ],
                                        'wrap_margin_bottom' => [ __( 'Section Margin Bottom',        'exertpro-faq-ai' ), __( 'Space below the FAQ section',                   'exertpro-faq-ai' ), 0, 100 ],
                                        'item_padding_v'     => [ __( 'Question Padding Top/Bottom',  'exertpro-faq-ai' ), __( 'Vertical padding inside each question button',   'exertpro-faq-ai' ), 0, 60  ],
                                        'item_padding_h'     => [ __( 'Question Padding Left/Right',  'exertpro-faq-ai' ), __( 'Horizontal padding inside each question button', 'exertpro-faq-ai' ), 0, 60  ],
                                        'answer_padding_v'   => [ __( 'Answer Padding Top/Bottom',    'exertpro-faq-ai' ), __( 'Vertical padding inside the answer panel',       'exertpro-faq-ai' ), 0, 60  ],
                                        'answer_padding_h'   => [ __( 'Answer Padding Left/Right',    'exertpro-faq-ai' ), __( 'Horizontal padding inside the answer panel',     'exertpro-faq-ai' ), 0, 60  ],
                                    ];
                                    foreach ( $spacing_fields as $sk => [ $slabel, $sdesc, $smin, $smax ] ) :
                                        $sid = 'epwf-' . str_replace( '_', '-', $sk );
                                    ?>
                                    <?php $this->field_row(
                                        $slabel,
                                        '<div class="epwf-range-wrap">'
                                        . '<input type="range" id="' . esc_attr( $sid ) . '" name="' . esc_attr( EPWF_OPTION_KEY ) . '[' . esc_attr( $sk ) . ']" value="' . absint( $o[ $sk ] ) . '" min="' . absint( $smin ) . '" max="' . absint( $smax ) . '" step="1" class="epwf-range epwf-spacing-range" data-out="' . esc_attr( $sid ) . '-val" aria-valuemin="' . absint( $smin ) . '" aria-valuemax="' . absint( $smax ) . '" aria-valuenow="' . absint( $o[ $sk ] ) . '">'
                                        . '<output class="epwf-range-val" id="' . esc_attr( $sid ) . '-val" for="' . esc_attr( $sid ) . '">' . absint( $o[ $sk ] ) . 'px</output>'
                                        . '</div>',
                                        $sdesc
                                    ); ?>
                                    <?php endforeach; ?>
                                </div>

                            </div><!-- .epwf-style-col right -->

                        </div><!-- .epwf-style-two-col -->

                    </div>

                    <!-- ══ TAB 4: Display Options ═══════════════════════════════ -->
                    <div class="epwf-tab-panel" id="epwf-tab-display" role="tabpanel">
                        <div class="epwf-card">
                            <h2 class="epwf-card-title"><?php esc_html_e( 'FAQ Section Title', 'exertpro-faq-ai' ); ?></h2>
                            <?php $this->field_row(
                                __( 'Heading Text', 'exertpro-faq-ai' ),
                                '<input type="text" name="' . esc_attr( EPWF_OPTION_KEY ) . '[section_title]" value="' . esc_attr( $o['section_title'] ) . '" class="regular-text" placeholder="Frequently Asked Questions">',
                                __( 'The h2 heading shown above your FAQ accordion.', 'exertpro-faq-ai' )
                            ); ?>
                        </div>
                        <div class="epwf-card">
                            <h2 class="epwf-card-title"><?php esc_html_e( 'JSON-LD FAQ Schema', 'exertpro-faq-ai' ); ?></h2>
                            <?php $this->field_row(
                                __( 'Enable FAQ Schema', 'exertpro-faq-ai' ),
                                $this->toggle( 'enable_schema', ! empty( $o['enable_schema'] ) ),
                                __( 'Output FAQPage JSON-LD structured data on product pages. Disable if another SEO plugin (Yoast, RankMath, AIOSEO) already handles FAQ schema to avoid duplicates.', 'exertpro-faq-ai' )
                            ); ?>
                            <?php if ( ! empty( $o['enable_schema'] ) ) : ?>
                            <div class="epwf-schema-info epwf-schema-active">
                                <span aria-hidden="true">✅</span>
                                <div>
                                    <strong><?php esc_html_e( 'Schema Active', 'exertpro-faq-ai' ); ?></strong>
                                    <p><?php esc_html_e( 'FAQPage JSON-LD is being output. Google may show rich results in search.', 'exertpro-faq-ai' ); ?></p>
                                </div>
                            </div>
                            <?php else : ?>
                            <div class="epwf-schema-info epwf-schema-disabled">
                                <span aria-hidden="true">⏸️</span>
                                <div>
                                    <strong><?php esc_html_e( 'Schema Disabled', 'exertpro-faq-ai' ); ?></strong>
                                    <p><?php esc_html_e( 'No FAQ schema is being output. Use this if your SEO plugin handles schema already.', 'exertpro-faq-ai' ); ?></p>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                </div><!-- .epwf-tabs-wrap -->

                <div class="epwf-save-bar">
                    <?php submit_button( __( 'Save Settings', 'exertpro-faq-ai' ), 'primary epwf-save-btn', 'submit', false ); ?>
                </div>
            </form>
        </div>
        <?php
    }

    // ── Meta Box ───────────────────────────────────────────────────────────────

    public function meta_box() {
        add_meta_box(
            'epwf_mb',
            esc_html__( '🤖 ProductFAQ AI', 'exertpro-faq-ai' ),
            [ $this, 'render_meta_box' ],
            'product', 'normal', 'default'
        );
    }

    public function render_meta_box( \WP_Post $post ) {
        // Fix #11: capability check inside meta box render
        if ( ! current_user_can( 'edit_post', $post->ID ) ) return;

        wp_nonce_field( 'epwf_meta_' . $post->ID, 'epwf_nonce' );

        $pid       = $post->ID;
        $enabled   = get_post_meta( $pid, EPWF_META_ENABLED, true );
        if ( '' === $enabled ) $enabled = $this->s->is_enabled() ? '1' : '0';
        $generated = $this->m->get_generated( $pid );
        $override  = $this->m->get_override( $pid );
        $err       = get_post_meta( $pid, '_epwf_last_error', true );
        $display   = ! empty( $override ) ? $override : $generated;
        $mi        = isset( Settings::$AI_MODELS[ $this->s->get_model() ] ) ? Settings::$AI_MODELS[ $this->s->get_model() ] : [];
        ?>
        <div class="epwf-mb">
            <div class="epwf-mb-header">
                <label class="epwf-toggle">
                    <input type="checkbox" name="epwf_enabled" value="1" <?php checked( $enabled, '1' ); ?>>
                    <span class="epwf-toggle-track"><span class="epwf-toggle-thumb"></span></span>
                    <strong><?php esc_html_e( 'Show FAQs on this product page', 'exertpro-faq-ai' ); ?></strong>
                </label>
                <?php if ( $mi ) : ?>
                <span class="epwf-mb-model"><?php echo esc_html( $mi['badge'] . ' · ' . $mi['label'] ); ?></span>
                <?php endif; ?>
            </div>

            <?php if ( ! $this->s->has_key() ) : ?>
            <div class="epwf-mb-alert epwf-mb-alert--warn">
                ⚠️ <?php printf(
                    /* translators: %s: URL to the ProductFAQ AI settings page */
                    wp_kses_post( __( 'No API key set. <a href="%s">Go to Settings →</a>', 'exertpro-faq-ai' ) ),
                    esc_url( admin_url( 'admin.php?page=' . self::PAGE ) )
                ); ?>
            </div>
            <?php endif; ?>

            <?php if ( $err ) : ?>
            <div class="epwf-mb-alert epwf-mb-alert--err">
                <strong><?php esc_html_e( 'Last error:', 'exertpro-faq-ai' ); ?></strong>
                <?php echo esc_html( $err ); ?>
            </div>
            <?php endif; ?>

            <?php if ( $this->s->is_additive() && ! empty( $generated ) ) : ?>
            <div class="epwf-mb-alert epwf-mb-alert--info">
                ➕ <?php printf(
                    /* translators: %d: number of existing FAQs */
                    esc_html__( 'Additive mode — next generation appends to the existing %d FAQ(s).', 'exertpro-faq-ai' ),
                    count( $generated )
                ); ?>
            </div>
            <?php endif; ?>

            <div class="epwf-mb-actions">
                <button type="button" id="epwf-regen" class="button button-primary"
                    data-pid="<?php echo absint( $pid ); ?>"
                    <?php echo ! $this->s->has_key() ? 'disabled="disabled"' : ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- static string ?>
                    🤖 <?php esc_html_e( 'Generate FAQs with AI', 'exertpro-faq-ai' ); ?>
                </button>
                <span class="spinner epwf-spin"></span>
                <span class="epwf-gen-msg" aria-live="polite"></span>
                <?php if ( ! empty( $generated ) ) : ?>
                <span class="epwf-mb-count"><?php echo absint( count( $generated ) ); ?> FAQs</span>
                <?php endif; ?>
            </div>

            <div class="epwf-mb-faqs">
                <div class="epwf-mb-faqs-head">
                    <strong><?php esc_html_e( 'FAQ List', 'exertpro-faq-ai' ); ?></strong>
                    <?php if ( ! empty( $override ) ) : ?>
                        <span class="epwf-pill epwf-pill--manual"><?php esc_html_e( 'Manual', 'exertpro-faq-ai' ); ?></span>
                    <?php elseif ( ! empty( $generated ) ) : ?>
                        <span class="epwf-pill epwf-pill--ai">AI</span>
                    <?php endif; ?>
                </div>
                <div id="epwf-rows">
                    <?php if ( empty( $display ) ) : ?>
                        <p class="epwf-empty-msg"><?php esc_html_e( 'No FAQs yet. Click Generate or save the product.', 'exertpro-faq-ai' ); ?></p>
                    <?php else :
                        foreach ( $display as $i => $faq ) $this->faq_row( $i, $faq );
                    endif; ?>
                </div>
                <button type="button" id="epwf-add-row" class="button">
                    + <?php esc_html_e( 'Add FAQ Manually', 'exertpro-faq-ai' ); ?>
                </button>
                <div id="epwf-row-tpl" style="display:none" aria-hidden="true">
                    <?php $this->faq_row( '__IDX__', [ 'question' => '', 'answer' => '' ] ); ?>
                </div>
                <p class="description" style="margin-top:6px">
                    <?php esc_html_e( 'Editing rows activates Manual Override for this product.', 'exertpro-faq-ai' ); ?>
                </p>
            </div>

            <?php if ( ! empty( $override ) ) : ?>
            <label style="margin-top:8px;display:block">
                <input type="checkbox" name="epwf_clear_override" value="1">
                <?php esc_html_e( 'Clear manual override — revert to AI-generated FAQs', 'exertpro-faq-ai' ); ?>
            </label>
            <?php endif; ?>
        </div>
        <?php
    }

    // Fix #10 + #11: nonce + capability in save_meta
    public function save_meta( $pid, \WP_Post $post ) {
        if ( ! isset( $_POST['epwf_nonce'] ) ) return;
        if ( ! wp_verify_nonce(
            sanitize_text_field( wp_unslash( $_POST['epwf_nonce'] ) ),
            'epwf_meta_' . $pid
        ) ) return;
        if ( ! current_user_can( 'edit_post', $pid ) ) return;
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
        if ( 'product' !== $post->post_type ) return;

        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by save_post action earlier
        $this->m->save_enabled( $pid, isset( $_POST['epwf_enabled'] ) );

        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if ( ! empty( $_POST['epwf_clear_override'] ) ) {
            delete_post_meta( $pid, EPWF_META_OVERRIDE );
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if ( ! empty( $_POST['epwf_override'] ) && is_array( $_POST['epwf_override'] ) ) {
            $this->m->save_override( $pid, wp_unslash( $_POST['epwf_override'] ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        }
    }

    // Fix #10: nonce + #11: capability in AJAX handler
    public function ajax_regenerate() {
        // Fix #10: verify nonce first
        if ( ! check_ajax_referer( 'epwf_ajax_nonce', 'nonce', false ) ) {
            wp_send_json_error( [ 'msg' => __( 'Security check failed. Refresh the page and try again.', 'exertpro-faq-ai' ) ], 403 );
        }

        // Fix #11: capability check
        if ( ! current_user_can( 'edit_products' ) ) {
            wp_send_json_error( [ 'msg' => __( 'You do not have permission to generate FAQs.', 'exertpro-faq-ai' ) ], 403 );
        }

        $pid = absint( isset( $_POST['pid'] ) ? $_POST['pid'] : 0 );
        if ( ! $pid ) {
            wp_send_json_error( [ 'msg' => __( 'Invalid product ID.', 'exertpro-faq-ai' ) ], 400 );
        }

        // Verify the product actually exists and user can edit it
        if ( ! current_user_can( 'edit_post', $pid ) ) {
            wp_send_json_error( [ 'msg' => __( 'You do not have permission to edit this product.', 'exertpro-faq-ai' ) ], 403 );
        }

        $result = $this->m->force_generate( $pid );

        if ( is_wp_error( $result ) ) {
            $err_code    = $result->get_error_code();
            $err_message = esc_html( $result->get_error_message() );
            // Map error codes to notice types for richer frontend UI
            $notice_map = [
                'epwf_invalid_key'    => 'invalid_key',
                'epwf_quota_exceeded' => 'quota_exceeded',
                'epwf_timeout'        => 'timeout',
                'epwf_malformed'      => 'malformed',
                'epwf_rate_limit'     => 'rate_limit',
            ];
            $notice_type = isset( $notice_map[ $err_code ] ) ? $notice_map[ $err_code ] : 'error';
            wp_send_json_error( [ 'msg' => $err_message, 'notice_type' => $notice_type ] );
        }

        ob_start();
        foreach ( $result as $i => $faq ) $this->faq_row( $i, $faq );
        $html = ob_get_clean();

        wp_send_json_success( [
            'msg'   => sprintf(
                /* translators: %d: number of FAQs generated */
                esc_html__( '✅ %d FAQs generated.', 'exertpro-faq-ai' ),
                count( $result )
            ),
            'html'  => $html,
            'count' => count( $result ),
        ] );
    }

    // ── Helpers ────────────────────────────────────────────────────────────────

    private function faq_row( $i, $faq ) { ?>
        <div class="epwf-faq-row">
            <span class="epwf-drag" aria-hidden="true">⠿</span>
            <div class="epwf-faq-fields">
                <input type="text"
                    name="epwf_override[<?php echo esc_attr( (string) $i ); ?>][question]"
                    value="<?php echo esc_attr( isset( $faq['question'] ) ? $faq['question'] : '' ); ?>"
                    class="large-text"
                    placeholder="<?php esc_attr_e( 'Question…', 'exertpro-faq-ai' ); ?>">
                <textarea
                    name="epwf_override[<?php echo esc_attr( (string) $i ); ?>][answer]"
                    rows="2" class="large-text"
                    placeholder="<?php esc_attr_e( 'Answer…', 'exertpro-faq-ai' ); ?>"><?php echo esc_textarea( isset( $faq['answer'] ) ? $faq['answer'] : '' ); ?></textarea>
            </div>
            <button type="button" class="epwf-del-row" aria-label="<?php esc_attr_e( 'Remove FAQ', 'exertpro-faq-ai' ); ?>">✕</button>
        </div>
    <?php }

    private function toggle( $key, $val ) {
        return '<label class="epwf-toggle">'
            . '<input type="checkbox" name="' . esc_attr( EPWF_OPTION_KEY ) . '[' . esc_attr( $key ) . ']" value="1" ' . checked( $val, true, false ) . '>'
            . '<span class="epwf-toggle-track"><span class="epwf-toggle-thumb"></span></span>'
            . '</label>';
    }

    /**
     * Allowed HTML tags for field_row $field argument.
     * Covers: input, select/option, button, output, div, span, label, a.
     *
     * @return array
     */
    private function field_allowed_html() {
        return [
            'input'    => [ 'type' => true, 'id' => true, 'name' => true, 'value' => true,
                            'class' => true, 'min' => true, 'max' => true, 'step' => true,
                            'placeholder' => true, 'autocomplete' => true, 'disabled' => true,
                            'checked' => true, 'readonly' => true, 'required' => true,
                            'aria-label' => true, 'aria-valuemin' => true, 'aria-valuemax' => true,
                            'aria-valuenow' => true, 'data-key' => true, 'data-out' => true,
                            'data-default-color' => true ],
            'select'   => [ 'id' => true, 'name' => true, 'class' => true, 'disabled' => true,
                            'aria-label' => true ],
            'option'   => [ 'value' => true, 'selected' => true, 'data-provider' => true ],
            'button'   => [ 'type' => true, 'class' => true, 'id' => true,
                            'aria-label' => true, 'disabled' => true ],
            'output'   => [ 'id' => true, 'class' => true, 'for' => true ],
            'div'      => [ 'class' => true, 'id' => true, 'style' => true,
                            'data-provider' => true ],
            'span'     => [ 'class' => true, 'id' => true ],
            'label'    => [ 'class' => true, 'for' => true ],
            'a'        => [ 'href' => true, 'target' => true, 'rel' => true, 'class' => true ],
            'p'        => [ 'class' => true ],
        ];
    }

    private function field_row( $label, $field, $hint = '' ) {
        echo '<div class="epwf-field-row">'
            . '<label class="epwf-label">' . wp_kses_post( $label ) . '</label>'
            . '<div class="epwf-field-val">' . wp_kses( $field, $this->field_allowed_html() )
            . ( $hint ? '<span class="epwf-hint">' . wp_kses_post( $hint ) . '</span>' : '' )
            . '</div></div>';
    }
}
