<?php

namespace AIFI;

/**
 * Handles plugin settings and settings page.
 *
 * @package AIFI
 */
class Settings {
    // All sizes supported by gpt-image-2. The first 3 are also accepted by older OpenAI models.
    const OPENAI_SIZES = array(
        '1024x1024' => '1024x1024 (Square, 1:1)',
        '1024x1536' => '1024x1536 (Portrait, 2:3)',
        '1536x1024' => '1536x1024 (Landscape, 3:2)',
        '1792x1024' => '1792x1024 (Widescreen, 16:9)',
        '1024x1792' => '1024x1792 (Vertical, 9:16)',
        '1920x640'  => '1920x640 (Ultra-wide, 3:1)',
        '640x1920'  => '640x1920 (Tall Banner, 1:3)',
    );

    // Sizes available to older OpenAI models (gpt-image-1, gpt-image-1.5, gpt-image-1-mini).
    const OPENAI_LEGACY_SIZES = array(
        '1024x1024' => '1024x1024 (Square, 1:1)',
        '1024x1536' => '1024x1536 (Portrait, 2:3)',
        '1536x1024' => '1536x1024 (Landscape, 3:2)',
    );

    /**
     * Settings page slug.
     *
     * @var string
     */
    private $page = 'ai-featured-image-generator';

    /**
     * Settings option name.
     *
     * @var string
     */
    private $option = 'aifi_settings';

    /**
     * Initialize settings.
     */
    public function __construct() {
        add_action( 'admin_menu', array($this, 'add_settings_page') );
        add_action( 'admin_init', array($this, 'register_settings') );
        add_action( 'admin_init', array($this, 'redirect_after_save') );
        add_action( 'admin_enqueue_scripts', array($this, 'enqueue_scripts') );
    }

    /**
     * Redirect back to the correct tab after settings save.
     */
    public function redirect_after_save() {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if ( isset( $_POST['aifi_active_tab'] ) && isset( $_POST['option_page'] ) && $_POST['option_page'] === $this->page ) {
            $tab = sanitize_key( $_POST['aifi_active_tab'] );
            if ( in_array( $tab, array(
                'general',
                'featured',
                'inline',
                'bulk'
            ), true ) ) {
                add_filter( 'wp_redirect', function ( $location ) use($tab) {
                    if ( strpos( $location, 'page=' . $this->page ) !== false && strpos( $location, 'settings-updated=1' ) !== false ) {
                        return add_query_arg( 'tab', $tab, $location );
                    }
                    return $location;
                } );
            }
        }
    }

    /**
     * Enqueue scripts and styles for settings pages.
     *
     * @param string $hook Current admin page hook.
     */
    public function enqueue_scripts( $hook ) {
        // Settings page
        if ( $hook === 'toplevel_page_ai-featured-image-generator' ) {
            wp_enqueue_style(
                'aifi-settings',
                AIFI_PLUGIN_URL . 'assets/css/settings.css',
                array(),
                AIFI_VERSION
            );
            wp_enqueue_script(
                'aifi-settings',
                AIFI_PLUGIN_URL . 'assets/js/settings.js',
                array('jquery'),
                AIFI_VERSION,
                true
            );
            $settings = $this->get_settings();
            wp_localize_script( 'aifi-settings', 'aifiSettingsData', array(
                'currentProvider' => $settings['ai_provider'] ?? 'openai',
                'currentModel'    => $settings['ai_model'] ?? 'gpt-image-2',
                'optionName'      => $this->option,
                'restUrl'         => rest_url( 'aifi/v1' ),
                'nonce'           => wp_create_nonce( 'wp_rest' ),
                'i18n'            => array(
                    'outputSettings'   => __( 'Output Settings', 'ai-featured-image-generator' ),
                    'aspectRatioFlash' => __( 'Controls the Gemini canvas shape. All aspect ratios use 1290 tokens for Gemini 2.5 Flash.', 'ai-featured-image-generator' ),
                    'aspectRatioOther' => __( 'Controls the Gemini canvas shape. Choose the resolution with the Image Size setting below.', 'ai-featured-image-generator' ),
                    'testing'          => __( 'Testing...', 'ai-featured-image-generator' ),
                    'keyValid'         => __( 'API key is valid!', 'ai-featured-image-generator' ),
                    'keyInvalid'       => __( 'Invalid API key.', 'ai-featured-image-generator' ),
                ),
            ) );
            // Enqueue bulk generate assets (for the Bulk Generate tab)
            $is_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
            wp_enqueue_style(
                'aifi-bulk',
                AIFI_PLUGIN_URL . 'assets/css/bulk.css',
                array('aifi-settings'),
                AIFI_VERSION
            );
            wp_enqueue_script(
                'aifi-bulk',
                AIFI_PLUGIN_URL . 'assets/js/bulk.js',
                array('jquery', 'aifi-settings'),
                AIFI_VERSION,
                true
            );
            // Check for auto-start from bulk action redirect
            $auto_start = false;
            $post_ids = array();
            $overwrite = false;
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            if ( isset( $_GET['action'] ) && $_GET['action'] === 'generate' && isset( $_GET['post_ids'] ) ) {
                if ( isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'aifi_bulk_generate' ) ) {
                    $auto_start = true;
                    $post_ids = array_map( 'absint', explode( ',', sanitize_text_field( wp_unslash( $_GET['post_ids'] ) ) ) );
                    $post_ids = array_filter( $post_ids );
                }
            }
            $enabled_post_types = $this->get_enabled_post_types();
            $post_type_options = array();
            foreach ( $enabled_post_types as $pt ) {
                $obj = get_post_type_object( $pt );
                if ( $obj ) {
                    $post_type_options[] = array(
                        'value' => $pt,
                        'label' => $obj->labels->name,
                    );
                }
            }
            $bulk_usage = (int) get_option( 'aifi_bulk_usage_count', 0 );
            $upgrade_url = ( function_exists( 'afig_fs' ) ? afig_fs()->get_upgrade_url() : '#' );
            $bulk_settings = $this->get_settings();
            $bulk_provider = ( isset( $bulk_settings['ai_provider'] ) ? $bulk_settings['ai_provider'] : 'openai' );
            wp_localize_script( 'aifi-bulk', 'aifiBulkData', array(
                'restUrl'    => rest_url( 'aifi/v1' ),
                'nonce'      => wp_create_nonce( 'wp_rest' ),
                'autoStart'  => $auto_start,
                'postIds'    => $post_ids,
                'overwrite'  => $overwrite,
                'postTypes'  => $post_type_options,
                'isPremium'  => $is_premium,
                'bulkUsage'  => $bulk_usage,
                'batchLimit' => \AIFI\Bulk::FREE_BATCH_LIMIT,
                'postLimit'  => \AIFI\Bulk::FREE_POST_LIMIT,
                'upgradeUrl' => $upgrade_url,
                'provider'   => $bulk_provider,
                'i18n'       => array(
                    'processing'    => __( 'Processing', 'ai-featured-image-generator' ),
                    'of'            => __( 'of', 'ai-featured-image-generator' ),
                    'success'       => __( 'Success', 'ai-featured-image-generator' ),
                    'skipped'       => __( 'Skipped', 'ai-featured-image-generator' ),
                    'error'         => __( 'Error', 'ai-featured-image-generator' ),
                    'cancelled'     => __( 'Cancelled', 'ai-featured-image-generator' ),
                    'completed'     => __( 'Completed!', 'ai-featured-image-generator' ),
                    'succeeded'     => __( 'succeeded', 'ai-featured-image-generator' ),
                    'failed'        => __( 'failed', 'ai-featured-image-generator' ),
                    'noPostsFound'  => __( 'No posts found matching your filters.', 'ai-featured-image-generator' ),
                    'selectPosts'   => __( 'Please select at least one post.', 'ai-featured-image-generator' ),
                    'confirmCancel' => __( 'Are you sure you want to cancel? The current image will finish generating.', 'ai-featured-image-generator' ),
                    'loadingPosts'  => __( 'Loading posts...', 'ai-featured-image-generator' ),
                ),
            ) );
        }
    }

    /**
     * Add settings page to WordPress admin.
     */
    public function add_settings_page() {
        add_menu_page(
            __( 'AI Images', 'ai-featured-image-generator' ),
            __( 'AI Images', 'ai-featured-image-generator' ),
            'manage_options',
            $this->page,
            array($this, 'render_settings_page'),
            'dashicons-format-image',
            80
        );
        // Add Settings submenu (points to same page, replaces default submenu)
        add_submenu_page(
            $this->page,
            __( 'Settings', 'ai-featured-image-generator' ),
            __( 'Settings', 'ai-featured-image-generator' ),
            'manage_options',
            $this->page,
            array($this, 'render_settings_page')
        );
    }

    /**
     * Register settings.
     */
    public function register_settings() {
        register_setting( $this->page, $this->option, array(
            'sanitize_callback' => array($this, 'sanitize_settings'),
        ) );
        // =====================
        // General Tab
        // =====================
        add_settings_section(
            'aifi_general_api_section',
            __( 'API Configuration', 'ai-featured-image-generator' ),
            array($this, 'render_general_api_section'),
            $this->page . '-general'
        );
        // AI Provider
        add_settings_field(
            'ai_provider',
            __( 'AI Provider', 'ai-featured-image-generator' ),
            array($this, 'render_provider_field'),
            $this->page . '-general',
            'aifi_general_api_section'
        );
        // AI Model
        add_settings_field(
            'ai_model',
            __( 'AI Model', 'ai-featured-image-generator' ),
            array($this, 'render_model_field'),
            $this->page . '-general',
            'aifi_general_api_section'
        );
        // OpenAI API Key
        add_settings_field(
            'openai_api_key',
            __( 'OpenAI API Key', 'ai-featured-image-generator' ),
            array($this, 'render_openai_api_key_field'),
            $this->page . '-general',
            'aifi_general_api_section',
            array(
                'class' => 'aifi-field-row aifi-openai-only',
            )
        );
        // Gemini API Key - Only for premium users
        if ( function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code() ) {
            add_settings_field(
                'gemini_api_key',
                __( 'Gemini API Key', 'ai-featured-image-generator' ),
                array($this, 'render_gemini_api_key_field'),
                $this->page . '-general',
                'aifi_general_api_section',
                array(
                    'class' => 'aifi-field-row aifi-gemini-only',
                )
            );
        }
        // Stability AI API Key
        add_settings_field(
            'stability_api_key',
            __( 'Stability AI API Key', 'ai-featured-image-generator' ),
            array($this, 'render_stability_api_key_field'),
            $this->page . '-general',
            'aifi_general_api_section',
            array(
                'class' => 'aifi-field-row aifi-stability-only',
            )
        );
        // Grok API Key
        add_settings_field(
            'grok_api_key',
            __( 'Grok / xAI API Key', 'ai-featured-image-generator' ),
            array($this, 'render_grok_api_key_field'),
            $this->page . '-general',
            'aifi_general_api_section',
            array(
                'class' => 'aifi-field-row aifi-grok-only',
            )
        );
        // Alt Text Section
        add_settings_section(
            'aifi_general_alt_text_section',
            __( 'Alt Text', 'ai-featured-image-generator' ),
            array($this, 'render_general_alt_text_section'),
            $this->page . '-general'
        );
        // Auto Alt Text toggle
        add_settings_field(
            'auto_alt_text',
            __( 'Auto Alt Text', 'ai-featured-image-generator' ),
            array($this, 'render_auto_alt_text_field'),
            $this->page . '-general',
            'aifi_general_alt_text_section'
        );
        // Alt Text Source
        add_settings_field(
            'alt_text_source',
            __( 'Alt Text Source', 'ai-featured-image-generator' ),
            array($this, 'render_alt_text_source_field'),
            $this->page . '-general',
            'aifi_general_alt_text_section',
            array(
                'class' => 'aifi-field-row aifi-alt-text-enabled-only',
            )
        );
        // Custom Format
        add_settings_field(
            'alt_text_custom_format',
            __( 'Custom Format', 'ai-featured-image-generator' ),
            array($this, 'render_alt_text_custom_format_field'),
            $this->page . '-general',
            'aifi_general_alt_text_section',
            array(
                'class' => 'aifi-field-row aifi-alt-text-enabled-only aifi-alt-text-custom-only',
            )
        );
        // Overwrite Alt Text on Regeneration
        add_settings_field(
            'alt_text_overwrite',
            __( 'Overwrite Alt Text on Regeneration', 'ai-featured-image-generator' ),
            array($this, 'render_alt_text_overwrite_field'),
            $this->page . '-general',
            'aifi_general_alt_text_section',
            array(
                'class' => 'aifi-field-row aifi-alt-text-enabled-only',
            )
        );
        // Availability Section
        add_settings_section(
            'aifi_general_availability_section',
            __( 'Availability', 'ai-featured-image-generator' ),
            array($this, 'render_general_availability_section'),
            $this->page . '-general'
        );
        // Enabled Post Types
        add_settings_field(
            'enabled_post_types',
            __( 'Enabled Post Types', 'ai-featured-image-generator' ),
            array($this, 'render_enabled_post_types_field'),
            $this->page . '-general',
            'aifi_general_availability_section'
        );
        // =====================
        // Featured Images Tab
        // =====================
        add_settings_section(
            'aifi_featured_section',
            __( 'Generation Defaults', 'ai-featured-image-generator' ),
            array($this, 'render_featured_section'),
            $this->page . '-featured'
        );
        // Default Size (OpenAI)
        add_settings_field(
            'default_size',
            __( 'Default Aspect Ratio', 'ai-featured-image-generator' ),
            array($this, 'render_size_field'),
            $this->page . '-featured',
            'aifi_featured_section',
            array(
                'class' => 'aifi-field-row aifi-openai-only',
            )
        );
        // Gemini Aspect Ratio - Only for premium users
        if ( function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code() ) {
            add_settings_field(
                'gemini_aspect_ratio',
                __( 'Default Aspect Ratio', 'ai-featured-image-generator' ),
                array($this, 'render_gemini_aspect_ratio_field'),
                $this->page . '-featured',
                'aifi_featured_section',
                array(
                    'class' => 'aifi-field-row aifi-gemini-only',
                )
            );
            // Gemini Image Size
            add_settings_field(
                'gemini_image_size',
                __( 'Default Image Quality', 'ai-featured-image-generator' ),
                array($this, 'render_gemini_image_size_field'),
                $this->page . '-featured',
                'aifi_featured_section',
                array(
                    'class' => 'aifi-field-row aifi-gemini-only aifi-gemini-3-pro-only',
                )
            );
        }
        // Stability AI Aspect Ratio
        add_settings_field(
            'stability_aspect_ratio',
            __( 'Default Aspect Ratio', 'ai-featured-image-generator' ),
            array($this, 'render_stability_aspect_ratio_field'),
            $this->page . '-featured',
            'aifi_featured_section',
            array(
                'class' => 'aifi-field-row aifi-stability-only',
            )
        );
        // Stability AI Style Preset
        add_settings_field(
            'stability_style_preset',
            __( 'Style Preset', 'ai-featured-image-generator' ),
            array($this, 'render_stability_style_preset_field'),
            $this->page . '-featured',
            'aifi_featured_section',
            array(
                'class' => 'aifi-field-row aifi-stability-only',
            )
        );
        // Stability AI Output Format (Pro only)
        if ( function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code() ) {
            add_settings_field(
                'stability_output_format',
                __( 'Output Format', 'ai-featured-image-generator' ),
                array($this, 'render_stability_output_format_field'),
                $this->page . '-featured',
                'aifi_featured_section',
                array(
                    'class' => 'aifi-field-row aifi-stability-only',
                )
            );
        }
        // Stability AI Negative Prompt (Pro only)
        if ( function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code() ) {
            add_settings_field(
                'stability_negative_prompt',
                __( 'Negative Prompt', 'ai-featured-image-generator' ),
                array($this, 'render_stability_negative_prompt_field'),
                $this->page . '-featured',
                'aifi_featured_section',
                array(
                    'class' => 'aifi-field-row aifi-stability-only',
                )
            );
        }
        // Grok Aspect Ratio
        add_settings_field(
            'grok_aspect_ratio',
            __( 'Aspect Ratio', 'ai-featured-image-generator' ),
            array($this, 'render_grok_aspect_ratio_field'),
            $this->page . '-featured',
            'aifi_featured_section',
            array(
                'class' => 'aifi-field-row aifi-grok-only',
            )
        );
        // Grok Resolution
        add_settings_field(
            'grok_resolution',
            __( 'Resolution', 'ai-featured-image-generator' ),
            array($this, 'render_grok_resolution_field'),
            $this->page . '-featured',
            'aifi_featured_section',
            array(
                'class' => 'aifi-field-row aifi-grok-only',
            )
        );
        // Default Style
        add_settings_field(
            'default_style',
            __( 'Default Style', 'ai-featured-image-generator' ),
            array($this, 'render_style_field'),
            $this->page . '-featured',
            'aifi_featured_section'
        );
        // Allow Text on Image
        add_settings_field(
            'allow_text',
            __( 'Allow text on generated image', 'ai-featured-image-generator' ),
            array($this, 'render_allow_text_field'),
            $this->page . '-featured',
            'aifi_featured_section'
        );
        // Custom Styles (Pro)
        add_settings_field(
            'custom_styles',
            __( 'Custom Styles', 'ai-featured-image-generator' ),
            array($this, 'render_custom_styles_field'),
            $this->page . '-featured',
            'aifi_featured_section'
        );
        // Output Settings Section
        add_settings_section(
            'aifi_featured_output_section',
            __( 'Output Settings', 'ai-featured-image-generator' ),
            array($this, 'render_featured_output_section'),
            $this->page . '-featured'
        );
        // Output Format
        add_settings_field(
            'output_format',
            __( 'Output Format', 'ai-featured-image-generator' ),
            array($this, 'render_output_format_field'),
            $this->page . '-featured',
            'aifi_featured_output_section',
            array(
                'class' => 'aifi-field-row aifi-openai-only',
            )
        );
        // Image Quality (only for lossy formats: WebP, JPEG)
        add_settings_field(
            'image_quality',
            __( 'Output Compression (WebP/JPEG)', 'ai-featured-image-generator' ),
            array($this, 'render_quality_field'),
            $this->page . '-featured',
            'aifi_featured_output_section',
            array(
                'class' => 'aifi-field-row aifi-openai-only aifi-lossy-format-only',
            )
        );
        // Generation Quality (OpenAI — all GPT Image models)
        add_settings_field(
            'openai_quality',
            __( 'Generation Quality', 'ai-featured-image-generator' ),
            array($this, 'render_openai_quality_field'),
            $this->page . '-featured',
            'aifi_featured_output_section',
            array(
                'class' => 'aifi-field-row aifi-openai-only',
            )
        );
        // Background (gpt-image-2 only)
        add_settings_field(
            'openai_background',
            __( 'Background', 'ai-featured-image-generator' ),
            array($this, 'render_openai_background_field'),
            $this->page . '-featured',
            'aifi_featured_output_section',
            array(
                'class' => 'aifi-field-row aifi-openai-only aifi-openai-gpt2-field',
            )
        );
        // Moderation (gpt-image-2 only)
        add_settings_field(
            'openai_moderation',
            __( 'Moderation', 'ai-featured-image-generator' ),
            array($this, 'render_openai_moderation_field'),
            $this->page . '-featured',
            'aifi_featured_output_section',
            array(
                'class' => 'aifi-field-row aifi-openai-only aifi-openai-gpt2-field',
            )
        );
        // =====================
        // Inline Images Tab (Pro)
        // =====================
        add_settings_section(
            'aifi_inline_section',
            __( 'Generation Defaults', 'ai-featured-image-generator' ),
            array($this, 'render_inline_section'),
            $this->page . '-inline'
        );
        // Inline Default Style
        add_settings_field(
            'inline_default_style',
            __( 'Default Style', 'ai-featured-image-generator' ),
            array($this, 'render_inline_style_field'),
            $this->page . '-inline',
            'aifi_inline_section'
        );
        // Inline Default Aspect Ratio / Size (provider-specific, matching Featured tab pattern)
        add_settings_field(
            'inline_default_size',
            __( 'Default Aspect Ratio', 'ai-featured-image-generator' ),
            array($this, 'render_inline_size_field'),
            $this->page . '-inline',
            'aifi_inline_section',
            array(
                'class' => 'aifi-field-row aifi-openai-only',
            )
        );
        if ( function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code() ) {
            add_settings_field(
                'inline_gemini_aspect_ratio',
                __( 'Default Aspect Ratio', 'ai-featured-image-generator' ),
                array($this, 'render_inline_gemini_aspect_ratio_field'),
                $this->page . '-inline',
                'aifi_inline_section',
                array(
                    'class' => 'aifi-field-row aifi-gemini-only',
                )
            );
        }
        add_settings_field(
            'inline_stability_aspect_ratio',
            __( 'Default Aspect Ratio', 'ai-featured-image-generator' ),
            array($this, 'render_inline_stability_aspect_ratio_field'),
            $this->page . '-inline',
            'aifi_inline_section',
            array(
                'class' => 'aifi-field-row aifi-stability-only',
            )
        );
        add_settings_field(
            'inline_grok_aspect_ratio',
            __( 'Default Aspect Ratio', 'ai-featured-image-generator' ),
            array($this, 'render_inline_grok_aspect_ratio_field'),
            $this->page . '-inline',
            'aifi_inline_section',
            array(
                'class' => 'aifi-field-row aifi-grok-only',
            )
        );
        // Inline Output Settings Section
        add_settings_section(
            'aifi_inline_output_section',
            __( 'Output Settings', 'ai-featured-image-generator' ),
            array($this, 'render_inline_output_section'),
            $this->page . '-inline'
        );
        // Inline Output Format (OpenAI only)
        add_settings_field(
            'inline_output_format',
            __( 'Output Format', 'ai-featured-image-generator' ),
            array($this, 'render_inline_output_format_field'),
            $this->page . '-inline',
            'aifi_inline_output_section',
            array(
                'class' => 'aifi-field-row aifi-openai-only',
            )
        );
        // Inline Stability Output Format (Pro only)
        if ( function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code() ) {
            add_settings_field(
                'inline_stability_output_format',
                __( 'Output Format', 'ai-featured-image-generator' ),
                array($this, 'render_inline_stability_output_format_field'),
                $this->page . '-inline',
                'aifi_inline_output_section',
                array(
                    'class' => 'aifi-field-row aifi-stability-only',
                )
            );
        }
        // Inline Stability Negative Prompt (Pro only)
        if ( function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code() ) {
            add_settings_field(
                'inline_stability_negative_prompt',
                __( 'Negative Prompt', 'ai-featured-image-generator' ),
                array($this, 'render_inline_stability_negative_prompt_field'),
                $this->page . '-inline',
                'aifi_inline_output_section',
                array(
                    'class' => 'aifi-field-row aifi-stability-only',
                )
            );
        }
    }

    /**
     * Render settings page.
     */
    public function render_settings_page() {
        if ( !current_user_can( 'manage_options' ) ) {
            return;
        }
        $is_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
        $settings = $this->get_settings();
        $has_api_key = !empty( $settings['openai_api_key'] ) || !empty( $settings['gemini_api_key'] ) && $is_premium || !empty( $settings['stability_api_key'] ) || !empty( $settings['grok_api_key'] );
        // Determine active tab (default to 'general')
        $active_tab = ( isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'general' );
        ?>
        <div class="wrap aifi-settings-page">
            <!-- Header -->
            <div class="aifi-settings-header">
                <div class="aifi-settings-header-content">
                    <h1><span class="dashicons dashicons-format-image"></span> <?php 
        esc_html_e( 'AI Featured Image Generator', 'ai-featured-image-generator' );
        ?></h1>
                </div>
                <?php 
        if ( $is_premium ) {
            ?>
                <div class="aifi-pro-badge-header">
                    <span class="dashicons dashicons-star-filled"></span> <?php 
            esc_html_e( 'Pro', 'ai-featured-image-generator' );
            ?>
                </div>
                <?php 
        }
        ?>
            </div>

            <?php 
        if ( isset( $_GET['settings-updated'] ) && $_GET['settings-updated'] === '1' ) {
            ?>
            <!-- Save Confirmation -->
            <div class="aifi-save-notice">
                <span class="dashicons dashicons-yes-alt"></span>
                <?php 
            esc_html_e( 'Settings saved successfully.', 'ai-featured-image-generator' );
            ?>
            </div>
            <?php 
        }
        ?>

            <?php 
        if ( !$has_api_key && $active_tab === 'general' ) {
            ?>
            <!-- Setup Notice -->
            <div class="aifi-setup-notice">
                <span class="dashicons dashicons-warning"></span>
                <div class="aifi-setup-notice-content">
                    <strong><?php 
            esc_html_e( 'Setup Required', 'ai-featured-image-generator' );
            ?></strong>
                    <p><?php 
            esc_html_e( 'Add your API key below to start generating AI images. Need help?', 'ai-featured-image-generator' );
            ?>
                    <a href="https://wordpress.org/support/plugin/ai-featured-image-generator/" target="_blank" rel="noopener"><?php 
            esc_html_e( 'Visit the Support Forum →', 'ai-featured-image-generator' );
            ?></a></p>
                </div>
            </div>
            <?php 
        }
        ?>

            <!-- Tab Navigation -->
            <nav class="aifi-tabs-nav">
                <a href="#general" data-tab="general"
                   class="aifi-tab <?php 
        echo ( $active_tab === 'general' ? 'aifi-tab-active' : '' );
        ?>">
                    <span class="dashicons dashicons-admin-generic"></span>
                    <?php 
        esc_html_e( 'General', 'ai-featured-image-generator' );
        ?>
                </a>
                <a href="#featured" data-tab="featured"
                   class="aifi-tab <?php 
        echo ( $active_tab === 'featured' ? 'aifi-tab-active' : '' );
        ?>">
                    <span class="dashicons dashicons-format-image"></span>
                    <?php 
        esc_html_e( 'Featured Images', 'ai-featured-image-generator' );
        ?>
                </a>
                <a href="#bulk" data-tab="bulk"
                   class="aifi-tab <?php 
        echo ( $active_tab === 'bulk' ? 'aifi-tab-active' : '' );
        ?>">
                    <span class="dashicons dashicons-images-alt2"></span>
                    <?php 
        esc_html_e( 'Bulk Generate', 'ai-featured-image-generator' );
        ?>
                </a>
                <a href="#inline" data-tab="inline"
                   class="aifi-tab <?php 
        echo ( $active_tab === 'inline' ? 'aifi-tab-active' : '' );
        ?>">
                    <span class="dashicons dashicons-align-center"></span>
                    <?php 
        esc_html_e( 'Inline Images', 'ai-featured-image-generator' );
        ?>
                    <span class="aifi-pro-badge-tab"><?php 
        esc_html_e( 'Pro', 'ai-featured-image-generator' );
        ?></span>
                </a>
            </nav>

            <div class="aifi-settings-layout">
                <!-- Main Content -->
                <div class="aifi-settings-main">
                    <div class="aifi-settings-card">
                        <form action="options.php" method="post" class="aifi-settings-form">
                            <input type="hidden" name="aifi_active_tab" id="aifi-active-tab" value="<?php 
        echo esc_attr( $active_tab );
        ?>" />
                            <?php 
        settings_fields( $this->page );
        ?>

                            <div class="aifi-tab-panel" data-panel="general" <?php 
        echo ( $active_tab !== 'general' ? 'style="display:none;"' : '' );
        ?>>
                                <?php 
        do_settings_sections( $this->page . '-general' );
        ?>
                            </div>

                            <div class="aifi-tab-panel" data-panel="featured" <?php 
        echo ( $active_tab !== 'featured' ? 'style="display:none;"' : '' );
        ?>>
                                <?php 
        do_settings_sections( $this->page . '-featured' );
        ?>
                            </div>

                            <div class="aifi-tab-panel" data-panel="inline" <?php 
        echo ( $active_tab !== 'inline' ? 'style="display:none;"' : '' );
        ?>>
                                <?php 
        do_settings_sections( $this->page . '-inline' );
        ?>
                            </div>
                            <?php 
        // Backwards-compatible: keep old conditional rendering path as a no-op
        // since all sections are now rendered above
        if ( false ) {
        }
        ?>
                            <div class="aifi-settings-submit">
                                <?php 
        submit_button(
            __( 'Save Settings', 'ai-featured-image-generator' ),
            'primary large',
            'submit',
            false
        );
        ?>
                            </div>
                        </form>
                    </div>

                    <!-- Bulk Generate Tab Panel (outside form - no settings to save) -->
                    <div class="aifi-tab-panel aifi-bulk-tab-panel" data-panel="bulk" <?php 
        echo ( $active_tab !== 'bulk' ? 'style="display:none;"' : '' );
        ?>>
                        <?php 
        $this->render_bulk_panel();
        ?>
                    </div>
                </div>

                <!-- Sidebar -->
                <div class="aifi-settings-sidebar">
                    <!-- Quick Tips -->
                    <div class="aifi-sidebar-card">
                        <h3><span class="dashicons dashicons-lightbulb"></span> <?php 
        esc_html_e( 'Quick Tips', 'ai-featured-image-generator' );
        ?></h3>

                        <ul class="aifi-tips-list" data-tips-for="general" <?php 
        echo ( $active_tab !== 'general' ? 'style="display:none;"' : '' );
        ?>>
                            <li>
                                <span class="dashicons dashicons-yes-alt"></span>
                                <?php 
        esc_html_e( 'Configure your API key and click Test Connection to verify it works.', 'ai-featured-image-generator' );
        ?>
                            </li>
                            <li>
                                <span class="dashicons dashicons-yes-alt"></span>
                                <?php 
        esc_html_e( 'Enable auto alt text for better SEO and accessibility.', 'ai-featured-image-generator' );
        ?>
                            </li>
                            <li>
                                <span class="dashicons dashicons-info"></span>
                                <?php 
        esc_html_e( 'Output formats: OpenAI (PNG, JPEG, WebP) · Gemini (PNG) · Stability (PNG, JPEG, WebP) · Grok (JPG).', 'ai-featured-image-generator' );
        ?>
                            </li>
                            <li>
                                <span class="dashicons dashicons-format-chat"></span>
                                <a href="https://wordpress.org/support/plugin/ai-featured-image-generator/" target="_blank" rel="noopener"><?php 
        esc_html_e( 'Need help? Visit the Support Forum', 'ai-featured-image-generator' );
        ?></a>
                            </li>
                        </ul>

                        <ul class="aifi-tips-list" data-tips-for="featured" <?php 
        echo ( $active_tab !== 'featured' ? 'style="display:none;"' : '' );
        ?>>
                            <li>
                                <span class="dashicons dashicons-yes-alt"></span>
                                <?php 
        esc_html_e( 'Use descriptive post titles for better AI-generated images.', 'ai-featured-image-generator' );
        ?>
                            </li>
                            <li>
                                <span class="dashicons dashicons-yes-alt"></span>
                                <?php 
        esc_html_e( 'Use 16:9 aspect ratio for blog headers and social sharing.', 'ai-featured-image-generator' );
        ?>
                            </li>
                            <li>
                                <span class="dashicons dashicons-yes-alt"></span>
                                <?php 
        esc_html_e( 'Create custom styles to maintain a consistent visual brand across posts.', 'ai-featured-image-generator' );
        ?>
                            </li>
                            <li>
                                <span class="dashicons dashicons-format-chat"></span>
                                <a href="https://wordpress.org/support/plugin/ai-featured-image-generator/" target="_blank" rel="noopener"><?php 
        esc_html_e( 'Need help? Visit the Support Forum', 'ai-featured-image-generator' );
        ?></a>
                            </li>
                        </ul>

                        <ul class="aifi-tips-list" data-tips-for="bulk" <?php 
        echo ( $active_tab !== 'bulk' ? 'style="display:none;"' : '' );
        ?>>
                            <li>
                                <span class="dashicons dashicons-yes-alt"></span>
                                <?php 
        esc_html_e( 'Start with a small batch to preview quality before processing many posts.', 'ai-featured-image-generator' );
        ?>
                            </li>
                            <li>
                                <span class="dashicons dashicons-yes-alt"></span>
                                <?php 
        esc_html_e( 'Bulk runs can add up — monitor your API usage and costs.', 'ai-featured-image-generator' );
        ?>
                            </li>
                            <li>
                                <span class="dashicons dashicons-yes-alt"></span>
                                <?php 
        esc_html_e( 'Use filters to target specific post types or statuses.', 'ai-featured-image-generator' );
        ?>
                            </li>
                            <li>
                                <span class="dashicons dashicons-format-chat"></span>
                                <a href="https://wordpress.org/support/plugin/ai-featured-image-generator/" target="_blank" rel="noopener"><?php 
        esc_html_e( 'Need help? Visit the Support Forum', 'ai-featured-image-generator' );
        ?></a>
                            </li>
                        </ul>

                        <ul class="aifi-tips-list" data-tips-for="inline" <?php 
        echo ( $active_tab !== 'inline' ? 'style="display:none;"' : '' );
        ?>>
                            <li>
                                <span class="dashicons dashicons-yes-alt"></span>
                                <?php 
        esc_html_e( 'Insert AI-generated images directly inside the Gutenberg editor.', 'ai-featured-image-generator' );
        ?>
                            </li>
                            <li>
                                <span class="dashicons dashicons-yes-alt"></span>
                                <?php 
        esc_html_e( 'Experiment with different styles to find what works best.', 'ai-featured-image-generator' );
        ?>
                            </li>
                            <li>
                                <span class="dashicons dashicons-yes-alt"></span>
                                <?php 
        esc_html_e( 'WebP format offers the best balance of quality and file size.', 'ai-featured-image-generator' );
        ?>
                            </li>
                            <li>
                                <span class="dashicons dashicons-format-chat"></span>
                                <a href="https://wordpress.org/support/plugin/ai-featured-image-generator/" target="_blank" rel="noopener"><?php 
        esc_html_e( 'Need help? Visit the Support Forum', 'ai-featured-image-generator' );
        ?></a>
                            </li>
                        </ul>
                    </div>

                    <?php 
        if ( !$is_premium && function_exists( 'afig_fs' ) ) {
            ?>
                    <!-- Upgrade Card -->
                    <div class="aifi-sidebar-card aifi-sidebar-upgrade">
                        <div class="aifi-upgrade-icon">⚡</div>
                        <h3><?php 
            esc_html_e( 'Unlock More Power', 'ai-featured-image-generator' );
            ?></h3>
                        <p>
                            <?php 
            esc_html_e( 'Upgrade to Pro to access Google Gemini, all Stability AI models, Grok Pro model, image upscaling, background removal, 4K output, and more. You also get the AI Image Generator inside the Gutenberg editor.', 'ai-featured-image-generator' );
            ?>
                        </p>
                        <a href="<?php 
            echo esc_url( afig_fs()->get_upgrade_url() );
            ?>" class="button button-primary">
                            <?php 
            esc_html_e( 'Upgrade to Pro', 'ai-featured-image-generator' );
            ?>
                        </a>
                    </div>
                    <?php 
        }
        ?>
                </div>
            </div>
        </div>

        <?php 
    }

    /**
     * Render the Bulk Generate tab panel content.
     */
    private function render_bulk_panel() {
        $is_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
        $upgrade_url = ( function_exists( 'afig_fs' ) ? afig_fs()->get_upgrade_url() : '#' );
        $enabled_post_types = $this->get_enabled_post_types();
        ?>
        <div class="aifi-bulk-content">
            <!-- Filters Card -->
            <div class="aifi-settings-card aifi-bulk-filters-card">
                <h2 class="aifi-bulk-card-title">
                    <?php 
        esc_html_e( 'Filter Posts', 'ai-featured-image-generator' );
        ?>
                </h2>
                <div class="aifi-bulk-filters">
                    <!-- Filter Grid -->
                    <div class="aifi-bulk-filter-grid">
                        <div class="aifi-bulk-filter-group">
                            <label for="aifi-bulk-post-status"><?php 
        esc_html_e( 'Post Status', 'ai-featured-image-generator' );
        ?></label>
                            <select id="aifi-bulk-post-status" class="aifi-bulk-select">
                                <option value="any"><?php 
        esc_html_e( 'Any', 'ai-featured-image-generator' );
        ?></option>
                                <option value="publish" selected><?php 
        esc_html_e( 'Published', 'ai-featured-image-generator' );
        ?></option>
                                <option value="draft"><?php 
        esc_html_e( 'Draft', 'ai-featured-image-generator' );
        ?></option>
                            </select>
                        </div>
                        <div class="aifi-bulk-filter-group<?php 
        echo ( !$is_premium ? ' aifi-pro-locked' : '' );
        ?>">
                            <label for="aifi-bulk-post-type">
                                <?php 
        esc_html_e( 'Post Type', 'ai-featured-image-generator' );
        ?>
                                <?php 
        if ( !$is_premium ) {
            ?><span class="aifi-pro-badge">Pro</span><?php 
        }
        ?>
                            </label>
                            <select id="aifi-bulk-post-type" class="aifi-bulk-select">
                                <?php 
        foreach ( $enabled_post_types as $pt ) {
            $obj = get_post_type_object( $pt );
            if ( !$obj ) {
                continue;
            }
            ?>
                                <option value="<?php 
            echo esc_attr( $pt );
            ?>"><?php 
            echo esc_html( $obj->labels->name );
            ?></option>
                                <?php 
        }
        ?>
                            </select>
                        </div>
                        <div class="aifi-bulk-filter-group<?php 
        echo ( !$is_premium ? ' aifi-pro-locked' : '' );
        ?>">
                            <label for="aifi-bulk-thumbnail-filter">
                                <?php 
        esc_html_e( 'Featured Image', 'ai-featured-image-generator' );
        ?>
                                <?php 
        if ( !$is_premium ) {
            ?><span class="aifi-pro-badge">Pro</span><?php 
        }
        ?>
                            </label>
                            <select id="aifi-bulk-thumbnail-filter" class="aifi-bulk-select">
                                <option value="any" selected><?php 
        esc_html_e( 'Any', 'ai-featured-image-generator' );
        ?></option>
                                <option value="no"><?php 
        esc_html_e( 'Without featured image', 'ai-featured-image-generator' );
        ?></option>
                                <option value="yes"><?php 
        esc_html_e( 'With featured image', 'ai-featured-image-generator' );
        ?></option>
                            </select>
                        </div>
                        <div class="aifi-bulk-filter-group<?php 
        echo ( !$is_premium ? ' aifi-pro-locked' : '' );
        ?>">
                            <label for="aifi-bulk-date-from">
                                <?php 
        esc_html_e( 'Date From', 'ai-featured-image-generator' );
        ?>
                                <?php 
        if ( !$is_premium ) {
            ?><span class="aifi-pro-badge">Pro</span><?php 
        }
        ?>
                            </label>
                            <input type="date" id="aifi-bulk-date-from" class="aifi-bulk-input">
                        </div>
                        <div class="aifi-bulk-filter-group<?php 
        echo ( !$is_premium ? ' aifi-pro-locked' : '' );
        ?>">
                            <label for="aifi-bulk-date-to">
                                <?php 
        esc_html_e( 'Date To', 'ai-featured-image-generator' );
        ?>
                                <?php 
        if ( !$is_premium ) {
            ?><span class="aifi-pro-badge">Pro</span><?php 
        }
        ?>
                            </label>
                            <input type="date" id="aifi-bulk-date-to" class="aifi-bulk-input">
                        </div>
                    </div>

                    <!-- Options Row -->
                    <div class="aifi-bulk-options-row">
                        <div class="aifi-bulk-filter-group<?php 
        echo ( !$is_premium ? ' aifi-pro-locked' : '' );
        ?>">
                            <label class="aifi-bulk-checkbox-label">
                                <input type="checkbox" id="aifi-bulk-overwrite"<?php 
        echo ( !$is_premium ? ' disabled' : '' );
        ?>>
                                <?php 
        esc_html_e( 'Overwrite existing featured images', 'ai-featured-image-generator' );
        ?>
                                <?php 
        if ( !$is_premium ) {
            ?><span class="aifi-pro-badge">Pro</span><?php 
        }
        ?>
                            </label>
                        </div>
                        <div class="aifi-bulk-filter-group">
                            <label class="aifi-bulk-checkbox-label">
                                <input type="checkbox" id="aifi-bulk-generate-prompt">
                                <?php 
        esc_html_e( 'Generate prompt from post content (leave unchecked to use Title only)', 'ai-featured-image-generator' );
        ?>
                            </label>
                            <p class="description" style="margin:4px 0 0; font-size:12px; color:#666;">
                                <?php 
        esc_html_e( 'Uses AI to analyze each post\'s content and generate a tailored image prompt. The generated prompt is saved to each post for later review. Not available with Stability AI.', 'ai-featured-image-generator' );
        ?>
                            </p>
                        </div>
                    </div>

                    <!-- Action -->
                    <div class="aifi-bulk-filter-actions">
                        <button type="button" id="aifi-bulk-load-posts" class="button button-primary button-large aifi-bulk-load-btn">
                            <span class="dashicons dashicons-search"></span>
                            <?php 
        esc_html_e( 'Load Posts', 'ai-featured-image-generator' );
        ?>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Posts Table Card -->
            <div class="aifi-settings-card aifi-bulk-posts-card" style="display: none;">
                <h2 class="aifi-bulk-card-title">
                    <span class="dashicons dashicons-editor-ul"></span>
                    <?php 
        esc_html_e( 'Select Posts', 'ai-featured-image-generator' );
        ?>
                    <span id="aifi-bulk-post-count" class="aifi-bulk-count"></span>
                </h2>
                <div class="aifi-bulk-posts-header">
                    <label class="aifi-bulk-checkbox-label">
                        <input type="checkbox" id="aifi-bulk-select-all" checked>
                        <?php 
        esc_html_e( 'Select All', 'ai-featured-image-generator' );
        ?>
                    </label>
                    <span id="aifi-bulk-selected-count"></span>
                </div>
                <div id="aifi-bulk-posts-list" class="aifi-bulk-posts-list"></div>
                <div class="aifi-bulk-posts-pagination" id="aifi-bulk-pagination"></div>
                <div class="aifi-bulk-posts-actions">
                    <button type="button" id="aifi-bulk-start" class="button button-primary button-large">
                        <span class="dashicons dashicons-format-image"></span>
                        <?php 
        esc_html_e( 'Generate Images for Selected Posts', 'ai-featured-image-generator' );
        ?>
                    </button>
                </div>
            </div>

            <!-- Progress Card -->
            <div class="aifi-settings-card aifi-bulk-progress-card" style="display: none;">
                <h2 class="aifi-bulk-card-title">
                    <span class="dashicons dashicons-update"></span>
                    <?php 
        esc_html_e( 'Progress', 'ai-featured-image-generator' );
        ?>
                </h2>
                <div class="aifi-bulk-progress">
                    <div id="aifi-bulk-progress-text" class="aifi-bulk-progress-text"></div>
                    <div class="aifi-bulk-progress-bar-wrap">
                        <div id="aifi-bulk-progress-bar" class="aifi-bulk-progress-bar" style="width: 0%"></div>
                    </div>
                    <div id="aifi-bulk-results-log" class="aifi-bulk-results-log"></div>
                    <p id="aifi-bulk-page-warning" class="aifi-bulk-page-warning" style="display: none;">
                        <span class="dashicons dashicons-warning"></span>
                        <?php 
        esc_html_e( 'Do not close or navigate away from this page until generation is complete.', 'ai-featured-image-generator' );
        ?>
                    </p>
                    <div class="aifi-bulk-progress-actions">
                        <button type="button" id="aifi-bulk-cancel" class="button">
                            <?php 
        esc_html_e( 'Cancel', 'ai-featured-image-generator' );
        ?>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Summary Card -->
            <div class="aifi-settings-card aifi-bulk-summary-card" style="display: none;">
                <h2 class="aifi-bulk-card-title">
                    <span class="dashicons dashicons-yes-alt"></span>
                    <?php 
        esc_html_e( 'Summary', 'ai-featured-image-generator' );
        ?>
                </h2>
                <div id="aifi-bulk-summary" class="aifi-bulk-summary"></div>
            </div>
        </div>
        <?php 
    }

    /**
     * Render section description.
     */
    public function render_section() {
        // Section description removed - header now provides context
    }

    /**
     * Render General API section description.
     */
    public function render_general_api_section() {
        ?>
        <p><?php 
        esc_html_e( 'Configure your AI provider and API credentials. These settings apply to all image generation features.', 'ai-featured-image-generator' );
        ?></p>
        <?php 
    }

    /**
     * Render General Availability section description.
     */
    public function render_general_availability_section() {
        ?>
        <p><?php 
        esc_html_e( 'Control which post types have access to AI image generation features.', 'ai-featured-image-generator' );
        ?></p>
        <?php 
    }

    /**
     * Render Alt Text section description.
     */
    public function render_general_alt_text_section() {
        ?>
        <p><?php 
        esc_html_e( 'Automatically set alt text on AI-generated images for better SEO and accessibility.', 'ai-featured-image-generator' );
        ?></p>
        <?php 
    }

    /**
     * Render auto alt text toggle field.
     */
    public function render_auto_alt_text_field() {
        $settings = $this->get_settings();
        $auto_alt_text = ( isset( $settings['auto_alt_text'] ) ? (bool) $settings['auto_alt_text'] : true );
        ?>
        <label>
            <input type="checkbox"
                   name="<?php 
        echo esc_attr( $this->option );
        ?>[auto_alt_text]"
                   id="aifi-auto-alt-text"
                   value="1"
                   <?php 
        checked( $auto_alt_text, true );
        ?>>
            <?php 
        esc_html_e( 'Automatically set alt text when generating images (Recommended)', 'ai-featured-image-generator' );
        ?>
        </label>
        <p class="description">
            <?php 
        esc_html_e( 'When enabled, alt text will be added to all AI-generated images (featured, inline, and bulk). This improves SEO and accessibility.', 'ai-featured-image-generator' );
        ?>
        </p>
        <?php 
    }

    /**
     * Render alt text source field.
     */
    public function render_alt_text_source_field() {
        $settings = $this->get_settings();
        $source = ( isset( $settings['alt_text_source'] ) ? $settings['alt_text_source'] : 'post_title' );
        $sources = array(
            'post_title' => __( 'Post Title', 'ai-featured-image-generator' ),
            'prompt'     => __( 'Image Prompt', 'ai-featured-image-generator' ),
            'custom'     => __( 'Custom Format', 'ai-featured-image-generator' ),
        );
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[alt_text_source]" id="aifi-alt-text-source">
            <?php 
        foreach ( $sources as $value => $label ) {
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $source, $value );
            ?>>
                    <?php 
            echo esc_html( $label );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description">
            <?php 
        esc_html_e( 'Choose what to use as alt text. "Post Title" uses the post title for featured/bulk images and the prompt for inline images. "Image Prompt" uses the generation prompt. "Custom Format" lets you define your own template.', 'ai-featured-image-generator' );
        ?>
        </p>
        <?php 
    }

    /**
     * Render alt text custom format field.
     */
    public function render_alt_text_custom_format_field() {
        $settings = $this->get_settings();
        $format = ( isset( $settings['alt_text_custom_format'] ) ? $settings['alt_text_custom_format'] : '{title}' );
        ?>
        <input type="text"
               name="<?php 
        echo esc_attr( $this->option );
        ?>[alt_text_custom_format]"
               id="aifi-alt-text-custom-format"
               value="<?php 
        echo esc_attr( $format );
        ?>"
               class="regular-text"
               placeholder="{title}">
        <p class="description">
            <?php 
        esc_html_e( 'Available placeholders:', 'ai-featured-image-generator' );
        ?>
            <code>{title}</code> — <?php 
        esc_html_e( 'post title', 'ai-featured-image-generator' );
        ?>,
            <code>{prompt}</code> — <?php 
        esc_html_e( 'generation prompt', 'ai-featured-image-generator' );
        ?>,
            <code>{style}</code> — <?php 
        esc_html_e( 'image style (e.g. Realistic)', 'ai-featured-image-generator' );
        ?>,
            <code>{site_name}</code> — <?php 
        esc_html_e( 'your site name', 'ai-featured-image-generator' );
        ?>
        </p>
        <p class="description">
            <?php 
        printf( 
            /* translators: %s: example format string */
            esc_html__( 'Example: %s', 'ai-featured-image-generator' ),
            '<code>' . esc_html( '{title} - {style} style - {site_name}' ) . '</code>'
         );
        ?>
        </p>
        <?php 
    }

    /**
     * Render alt text overwrite field.
     */
    public function render_alt_text_overwrite_field() {
        $settings = $this->get_settings();
        $overwrite = ( isset( $settings['alt_text_overwrite'] ) ? (bool) $settings['alt_text_overwrite'] : true );
        ?>
        <label>
            <input type="checkbox"
                   name="<?php 
        echo esc_attr( $this->option );
        ?>[alt_text_overwrite]"
                   id="aifi-alt-text-overwrite"
                   value="1"
                   <?php 
        checked( $overwrite, true );
        ?>>
            <?php 
        esc_html_e( 'Overwrite existing alt text when regenerating images', 'ai-featured-image-generator' );
        ?>
        </label>
        <p class="description">
            <?php 
        esc_html_e( 'When enabled, alt text is auto-generated each time an image is regenerated. When disabled, existing alt text from the previous featured image is preserved.', 'ai-featured-image-generator' );
        ?>
        </p>
        <?php 
    }

    /**
     * Render Featured Images section description.
     */
    public function render_featured_section() {
        $settings = $this->get_settings();
        $current_provider = ( isset( $settings['ai_provider'] ) ? $settings['ai_provider'] : 'openai' );
        // Provider capabilities data
        $capabilities = array(
            'openai'    => array(
                'formats' => 'PNG, JPEG, WebP',
                'sizes'   => '3 sizes (Square, Landscape, Portrait)',
                'quality' => true,
                'styles'  => 'Plugin styles + Custom styles',
                'models'  => '4 models',
            ),
            'gemini'    => array(
                'formats' => 'PNG (fixed)',
                'sizes'   => '7 aspect ratios',
                'quality' => false,
                'styles'  => 'Plugin styles + Custom styles',
                'models'  => '3 models',
            ),
            'stability' => array(
                'formats' => 'PNG (Free) · PNG, JPEG, WebP (Pro)',
                'sizes'   => '3 aspect ratios (Free) · 9 aspect ratios (Pro)',
                'quality' => false,
                'styles'  => 'Plugin styles + 16 Stability presets + Custom styles',
                'models'  => '1 model (Free) · 10 models (Pro)',
            ),
            'grok'      => array(
                'formats' => 'JPG (fixed)',
                'sizes'   => '3 aspect ratios (Free) · 9 aspect ratios (Pro) · 1K (Free) · 2K (Pro)',
                'quality' => false,
                'styles'  => 'Plugin styles + Custom styles',
                'models'  => '1 model (Free) · 2 models (Pro)',
            ),
        );
        $cap = ( isset( $capabilities[$current_provider] ) ? $capabilities[$current_provider] : $capabilities['openai'] );
        ?>
        <p>
            <?php 
        esc_html_e( 'Configure default settings for featured image generation.', 'ai-featured-image-generator' );
        ?>
            <?php 
        printf( 
            /* translators: %s: current provider name */
            esc_html__( 'Currently using: %s', 'ai-featured-image-generator' ),
            '<strong>' . esc_html( $this->get_provider_label( $current_provider ) ) . '</strong>'
         );
        ?>
        </p>

        <?php 
        // Provider capabilities notice — hidden per-provider, shown via JS
        ?>
        <div class="aifi-provider-capabilities" id="aifi-provider-capabilities">
            <?php 
        foreach ( $capabilities as $provider_key => $provider_cap ) {
            ?>
            <div class="aifi-cap-<?php 
            echo esc_attr( $provider_key );
            ?>" style="<?php 
            echo ( $provider_key !== $current_provider ? 'display:none;' : '' );
            ?>">
                <div class="aifi-capabilities-notice">
                    <span class="dashicons dashicons-info-outline"></span>
                    <strong><?php 
            echo esc_html( $this->get_provider_label( $provider_key ) );
            ?></strong> —
                    <?php 
            /* translators: %s: supported output formats */
            printf( esc_html__( 'Formats: %s', 'ai-featured-image-generator' ), esc_html( $provider_cap['formats'] ) );
            ?> ·
                    <?php 
            echo esc_html( $provider_cap['sizes'] );
            ?> ·
                    <?php 
            echo esc_html( $provider_cap['styles'] );
            ?> ·
                    <?php 
            echo esc_html( $provider_cap['models'] );
            ?>
                    <?php 
            if ( $provider_cap['quality'] ) {
                ?>
                        · <?php 
                esc_html_e( 'Quality slider available', 'ai-featured-image-generator' );
                ?>
                    <?php 
            }
            ?>
                </div>
            </div>
            <?php 
        }
        ?>
        </div>
        <?php 
    }

    /**
     * Render Featured Images Output section description.
     */
    public function render_featured_output_section() {
        ?>
        <p><?php 
        esc_html_e( 'Configure output format and quality settings for generated images.', 'ai-featured-image-generator' );
        ?></p>
        <?php 
    }

    /**
     * Render inline section description.
     */
    public function render_inline_section() {
        $is_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
        if ( !$is_premium ) {
            ?>
            <div class="aifi-inline-upsell">
                <div class="aifi-inline-upsell-icon">
                    <span class="dashicons dashicons-block-default"></span>
                </div>
                <h3><?php 
            esc_html_e( 'AI Image Generator Block', 'ai-featured-image-generator' );
            ?></h3>
                <p><?php 
            esc_html_e( 'Create AI-generated images directly inside the Gutenberg editor. Insert the block anywhere in your posts, pages, or custom post types.', 'ai-featured-image-generator' );
            ?></p>
                <ul class="aifi-inline-upsell-features">
                    <li><span class="dashicons dashicons-yes-alt"></span> <?php 
            esc_html_e( 'Generate inline images within your content', 'ai-featured-image-generator' );
            ?></li>
                    <li><span class="dashicons dashicons-yes-alt"></span> <?php 
            esc_html_e( 'All 13 style presets available', 'ai-featured-image-generator' );
            ?></li>
                    <li><span class="dashicons dashicons-yes-alt"></span> <?php 
            esc_html_e( 'Multiple aspect ratios', 'ai-featured-image-generator' );
            ?></li>
                    <li><span class="dashicons dashicons-yes-alt"></span> <?php 
            esc_html_e( 'Google Gemini support with 4K output', 'ai-featured-image-generator' );
            ?></li>
                </ul>
                <a href="<?php 
            echo esc_url( afig_fs()->get_upgrade_url() );
            ?>" class="button button-primary button-hero">
                    <?php 
            esc_html_e( 'Upgrade to Pro', 'ai-featured-image-generator' );
            ?>
                </a>
            </div>
            <style>
                /* Hide the form table for the inline tab when showing upsell */
                .aifi-inline-upsell ~ .form-table,
                .aifi-inline-upsell ~ h2,
                .aifi-inline-upsell ~ p { display: none !important; }
            </style>
            <?php 
        } else {
            ?>
            <p>
                <?php 
            esc_html_e( 'Configure default settings for the AI Image Generator block. These apply when users don\'t customize settings per-block.', 'ai-featured-image-generator' );
            ?>
                <?php 
            esc_html_e( 'To use the block: open any post or page in the Gutenberg editor, click the', 'ai-featured-image-generator' );
            ?>
                <strong>+</strong>
                <?php 
            esc_html_e( 'button to add a block, search for', 'ai-featured-image-generator' );
            ?>
                <strong>&ldquo;<?php 
            esc_html_e( 'AI Image Generator', 'ai-featured-image-generator' );
            ?>&rdquo;</strong>,
                <?php 
            esc_html_e( 'and select it. Fill in an optional prompt, choose a style, and click Generate.', 'ai-featured-image-generator' );
            ?>
            </p>
            <?php 
        }
    }

    /**
     * Render inline default style field.
     */
    public function render_inline_style_field() {
        $is_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
        $settings = $this->get_settings();
        $style = ( isset( $settings['inline_default_style'] ) ? $settings['inline_default_style'] : 'realistic' );
        $common_styles = array(
            'none'       => __( 'None (No Style)', 'ai-featured-image-generator' ),
            'realistic'  => __( 'Realistic', 'ai-featured-image-generator' ),
            'artistic'   => __( 'Artistic', 'ai-featured-image-generator' ),
            'cartoon'    => __( 'Cartoon', 'ai-featured-image-generator' ),
            'minimalist' => __( 'Minimalist', 'ai-featured-image-generator' ),
        );
        $creative_styles = array(
            'sketch'      => __( 'Sketch', 'ai-featured-image-generator' ),
            'watercolor'  => __( 'Watercolor', 'ai-featured-image-generator' ),
            '3d'          => __( '3D Render', 'ai-featured-image-generator' ),
            'pixel'       => __( 'Pixel Art', 'ai-featured-image-generator' ),
            'cyberpunk'   => __( 'Cyberpunk', 'ai-featured-image-generator' ),
            'fantasy'     => __( 'Fantasy', 'ai-featured-image-generator' ),
            'anime'       => __( 'Anime', 'ai-featured-image-generator' ),
            'technicolor' => __( 'Technicolor', 'ai-featured-image-generator' ),
        );
        $disabled = ( !$is_premium ? 'disabled' : '' );
        ?>
        <?php 
        $custom_styles_list = $this->get_custom_styles();
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[inline_default_style]" <?php 
        echo $disabled;
        ?>>
            <optgroup label="<?php 
        esc_attr_e( 'Common', 'ai-featured-image-generator' );
        ?>">
                <?php 
        foreach ( $common_styles as $value => $label ) {
            ?>
                    <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $style, $value );
            ?>>
                        <?php 
            echo esc_html( $label );
            ?>
                    </option>
                <?php 
        }
        ?>
            </optgroup>
            <optgroup label="<?php 
        esc_attr_e( 'Creative', 'ai-featured-image-generator' );
        ?>">
                <?php 
        foreach ( $creative_styles as $value => $label ) {
            ?>
                    <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $style, $value );
            ?>>
                        <?php 
            echo esc_html( $label );
            ?>
                    </option>
                <?php 
        }
        ?>
            </optgroup>
            <?php 
        if ( !empty( $custom_styles_list ) ) {
            ?>
            <optgroup label="<?php 
            esc_attr_e( 'Custom', 'ai-featured-image-generator' );
            ?>">
                <?php 
            foreach ( $custom_styles_list as $i => $cs ) {
                ?>
                    <option value="custom_<?php 
                echo $i;
                ?>" <?php 
                selected( $style, 'custom_' . $i );
                ?>>
                        <?php 
                echo esc_html( $cs['name'] );
                ?>
                    </option>
                <?php 
            }
            ?>
            </optgroup>
            <?php 
        }
        ?>
        </select>
        <p class="description"><?php 
        esc_html_e( 'Default style for AI Image Generator block.', 'ai-featured-image-generator' );
        ?></p>
        <?php 
    }

    /**
     * Render inline OpenAI size field.
     */
    public function render_inline_size_field() {
        $settings = $this->get_settings();
        $size = ( isset( $settings['inline_default_size'] ) ? $settings['inline_default_size'] : '1024x1024' );
        $gpt2_only_sizes = array(
            '1792x1024',
            '1024x1792',
            '1920x640',
            '640x1920'
        );
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[inline_default_size]" id="aifi-inline-default-size">
            <?php 
        foreach ( self::OPENAI_SIZES as $value => $label ) {
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>"
                    <?php 
            selected( $size, $value );
            ?>
                    <?php 
            if ( in_array( $value, $gpt2_only_sizes, true ) ) {
                ?>data-gpt2-only="1"<?php 
            }
            ?>>
                    <?php 
            echo esc_html( $label );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description">
            <?php 
        esc_html_e( 'Choose the default image size for OpenAI inline images. GPT Image 2 unlocks four additional aspect ratios (16:9, 9:16, 3:1, 1:3). Older OpenAI models support only 1:1, 2:3, and 3:2.', 'ai-featured-image-generator' );
        ?>
        </p>
        <?php 
    }

    /**
     * Render inline Gemini aspect ratio field.
     */
    public function render_inline_gemini_aspect_ratio_field() {
        $settings = $this->get_settings();
        $aspect_ratio = ( isset( $settings['inline_gemini_aspect_ratio'] ) ? $settings['inline_gemini_aspect_ratio'] : '16:9' );
        $ratios = array(
            '1:1'  => __( '1:1 (Square)', 'ai-featured-image-generator' ),
            '16:9' => __( '16:9 (Wide)', 'ai-featured-image-generator' ),
            '9:16' => __( '9:16 (Vertical)', 'ai-featured-image-generator' ),
            '3:2'  => __( '3:2 (Landscape)', 'ai-featured-image-generator' ),
            '2:3'  => __( '2:3 (Portrait)', 'ai-featured-image-generator' ),
            '4:3'  => __( '4:3 (Landscape)', 'ai-featured-image-generator' ),
            '3:4'  => __( '3:4 (Portrait)', 'ai-featured-image-generator' ),
            '5:4'  => __( '5:4 (Landscape)', 'ai-featured-image-generator' ),
            '4:5'  => __( '4:5 (Portrait)', 'ai-featured-image-generator' ),
            '21:9' => __( '21:9 (Cinematic)', 'ai-featured-image-generator' ),
        );
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[inline_gemini_aspect_ratio]">
            <?php 
        foreach ( $ratios as $value => $label ) {
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $aspect_ratio, $value );
            ?>>
                    <?php 
            echo esc_html( $label );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description">
            <?php 
        esc_html_e( 'Choose the default aspect ratio for Gemini inline images.', 'ai-featured-image-generator' );
        ?>
        </p>
        <?php 
    }

    /**
     * Render inline Stability AI aspect ratio field.
     */
    public function render_inline_stability_aspect_ratio_field() {
        $settings = $this->get_settings();
        $aspect_ratio = ( isset( $settings['inline_stability_aspect_ratio'] ) ? $settings['inline_stability_aspect_ratio'] : '16:9' );
        $is_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
        $free_ratios = array('1:1', '16:9', '9:16');
        $ratios = array(
            '1:1'  => __( '1:1 (Square)', 'ai-featured-image-generator' ),
            '16:9' => __( '16:9 (Landscape)', 'ai-featured-image-generator' ),
            '21:9' => __( '21:9 (Cinematic)', 'ai-featured-image-generator' ),
            '2:3'  => __( '2:3 (Portrait)', 'ai-featured-image-generator' ),
            '3:2'  => __( '3:2 (Landscape)', 'ai-featured-image-generator' ),
            '4:5'  => __( '4:5 (Portrait)', 'ai-featured-image-generator' ),
            '5:4'  => __( '5:4 (Landscape)', 'ai-featured-image-generator' ),
            '9:16' => __( '9:16 (Tall)', 'ai-featured-image-generator' ),
            '9:21' => __( '9:21 (Ultra Tall)', 'ai-featured-image-generator' ),
        );
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[inline_stability_aspect_ratio]">
            <?php 
        foreach ( $ratios as $value => $label ) {
            $is_disabled = !$is_premium && !in_array( $value, $free_ratios, true );
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $aspect_ratio, $value );
            ?> <?php 
            disabled( $is_disabled );
            ?>>
                    <?php 
            echo esc_html( ( $is_disabled ? $label . ' (Pro)' : $label ) );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description">
            <?php 
        esc_html_e( 'Choose the default aspect ratio for Stability AI inline images.', 'ai-featured-image-generator' );
        ?>
            <?php 
        if ( !$is_premium ) {
            ?>
                <br><span class="dashicons dashicons-star-filled" style="color: #f0ad4e; font-size: 14px;"></span>
                <?php 
            printf( esc_html__( '%s to unlock all 9 aspect ratios.', 'ai-featured-image-generator' ), '<a href="' . esc_url( afig_fs()->get_upgrade_url() ) . '">' . esc_html__( 'Upgrade to Pro', 'ai-featured-image-generator' ) . '</a>' );
            ?>
            <?php 
        }
        ?>
        </p>
        <?php 
    }

    /**
     * Render inline Grok aspect ratio field.
     */
    public function render_inline_grok_aspect_ratio_field() {
        $settings = $this->get_settings();
        $current = ( isset( $settings['inline_grok_aspect_ratio'] ) ? $settings['inline_grok_aspect_ratio'] : '1:1' );
        $is_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
        $free_ratios = array('1:1', '16:9', '9:16');
        $ratios = array(
            '1:1'  => __( 'Square (1:1)', 'ai-featured-image-generator' ),
            '16:9' => __( 'Landscape (16:9)', 'ai-featured-image-generator' ),
            '9:16' => __( 'Portrait (9:16)', 'ai-featured-image-generator' ),
            '4:3'  => __( 'Landscape (4:3)', 'ai-featured-image-generator' ),
            '3:4'  => __( 'Portrait (3:4)', 'ai-featured-image-generator' ),
            '3:2'  => __( 'Landscape (3:2)', 'ai-featured-image-generator' ),
            '2:3'  => __( 'Portrait (2:3)', 'ai-featured-image-generator' ),
            '2:1'  => __( 'Wide (2:1)', 'ai-featured-image-generator' ),
            '1:2'  => __( 'Tall (1:2)', 'ai-featured-image-generator' ),
        );
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[inline_grok_aspect_ratio]">
            <?php 
        foreach ( $ratios as $value => $label ) {
            $is_disabled = !$is_premium && !in_array( $value, $free_ratios, true );
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $current, $value );
            ?> <?php 
            disabled( $is_disabled );
            ?>>
                    <?php 
            echo esc_html( ( $is_disabled ? $label . ' (Pro)' : $label ) );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description">
            <?php 
        esc_html_e( 'Choose the default aspect ratio for Grok inline images.', 'ai-featured-image-generator' );
        ?>
            <?php 
        if ( !$is_premium ) {
            ?>
                <br><span class="dashicons dashicons-star-filled" style="color: #f0ad4e; font-size: 14px;"></span>
                <?php 
            printf( esc_html__( '%s to unlock all 9 aspect ratios.', 'ai-featured-image-generator' ), '<a href="' . esc_url( afig_fs()->get_upgrade_url() ) . '">' . esc_html__( 'Upgrade to Pro', 'ai-featured-image-generator' ) . '</a>' );
            ?>
            <?php 
        }
        ?>
        </p>
        <?php 
    }

    /**
     * Render inline output section description.
     */
    public function render_inline_output_section() {
        $is_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
        if ( !$is_premium ) {
            return;
        }
        ?>
        <p><?php 
        esc_html_e( 'Configure output settings for inline images generated with the AI Image Generator block.', 'ai-featured-image-generator' );
        ?></p>
        <div class="aifi-auto-optimize-notice">
            <span class="dashicons dashicons-performance"></span>
            <div>
                <strong><?php 
        esc_html_e( 'Automatic Quality Optimization', 'ai-featured-image-generator' );
        ?></strong>
                <p><?php 
        esc_html_e( 'Image quality and resolution are automatically adjusted based on the display size of the image in your content. Smaller images use lighter settings for faster page loading, while larger images use higher quality to stay sharp. No manual quality slider is needed.', 'ai-featured-image-generator' );
        ?></p>
                <details style="margin-top: 6px;">
                    <summary style="cursor: pointer; font-size: 12px; color: #6b7280;"><?php 
        esc_html_e( 'View optimization details', 'ai-featured-image-generator' );
        ?></summary>
                    <ul style="margin: 6px 0 0 18px; font-size: 12px; color: #6b7280;">
                        <li><?php 
        esc_html_e( 'Small (under 600px): 75% quality, 1K resolution', 'ai-featured-image-generator' );
        ?></li>
                        <li><?php 
        esc_html_e( 'Medium (600–1000px): 85% quality, 1K resolution', 'ai-featured-image-generator' );
        ?></li>
                        <li><?php 
        esc_html_e( 'Large (1000–1600px): 90% quality, 2K resolution', 'ai-featured-image-generator' );
        ?></li>
                        <li><?php 
        esc_html_e( 'Extra large (over 1600px): 95% quality, 4K resolution', 'ai-featured-image-generator' );
        ?></li>
                    </ul>
                </details>
            </div>
        </div>
        <?php 
    }

    /**
     * Render inline output format field.
     */
    public function render_inline_output_format_field() {
        $is_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
        $settings = $this->get_settings();
        $output_format = ( isset( $settings['inline_output_format'] ) ? $settings['inline_output_format'] : 'webp' );
        $formats = array(
            'webp' => 'WebP (Recommended)',
            'png'  => 'PNG',
            'jpeg' => 'JPEG',
        );
        $disabled = ( !$is_premium ? 'disabled' : '' );
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[inline_output_format]" <?php 
        echo $disabled;
        ?>>
            <?php 
        foreach ( $formats as $value => $label ) {
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $output_format, $value );
            ?>>
                    <?php 
            echo esc_html( $label );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description">
            <?php 
        esc_html_e( 'Choose the output format for inline images. WebP provides the best compression and quality. PNG is lossless (no compression). This setting only applies when using OpenAI.', 'ai-featured-image-generator' );
        ?>
        </p>
        <?php 
    }

    /**
     * Render inline Stability AI output format field (Pro only).
     */
    public function render_inline_stability_output_format_field() {
        if ( !function_exists( 'afig_fs' ) || !afig_fs()->is__premium_only() ) {
            return;
        }
        $settings = $this->get_settings();
        $output_format = ( isset( $settings['inline_stability_output_format'] ) ? $settings['inline_stability_output_format'] : 'png' );
        $formats = array(
            'png'  => 'PNG',
            'jpeg' => 'JPEG',
            'webp' => 'WebP',
        );
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[inline_stability_output_format]">
            <?php 
        foreach ( $formats as $value => $label ) {
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $output_format, $value );
            ?>>
                    <?php 
            echo esc_html( $label );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description">
            <?php 
        esc_html_e( 'Choose the output format for Stability AI inline images.', 'ai-featured-image-generator' );
        ?>
        </p>
        <?php 
    }

    /**
     * Render inline Stability AI negative prompt field (Pro only).
     */
    public function render_inline_stability_negative_prompt_field() {
        if ( !function_exists( 'afig_fs' ) || !afig_fs()->is__premium_only() ) {
            return;
        }
        $settings = $this->get_settings();
        $negative_prompt = ( isset( $settings['inline_stability_negative_prompt'] ) ? $settings['inline_stability_negative_prompt'] : '' );
        ?>
        <textarea name="<?php 
        echo esc_attr( $this->option );
        ?>[inline_stability_negative_prompt]"
                  rows="3"
                  class="large-text"
                  placeholder="<?php 
        esc_attr_e( 'e.g. blurry, text, watermark, low quality', 'ai-featured-image-generator' );
        ?>"><?php 
        echo esc_textarea( $negative_prompt );
        ?></textarea>
        <p class="description">
            <?php 
        esc_html_e( 'Describe elements to exclude from inline images. Leave empty for no restrictions.', 'ai-featured-image-generator' );
        ?>
        </p>
        <?php 
    }

    /**
     * Render provider field.
     */
    public function render_provider_field() {
        $settings = $this->get_settings();
        $provider = ( isset( $settings['ai_provider'] ) ? $settings['ai_provider'] : 'openai' );
        $can_use_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
        $providers = array(
            'openai'    => array(
                'label'    => 'OpenAI',
                'disabled' => false,
            ),
            'gemini'    => array(
                'label'    => ( $can_use_premium ? 'Google Gemini (Pro)' : 'Google Gemini (Pro only)' ),
                'disabled' => !$can_use_premium,
            ),
            'stability' => array(
                'label'    => 'Stability AI',
                'disabled' => false,
            ),
            'grok'      => array(
                'label'    => 'Grok / xAI',
                'disabled' => false,
            ),
        );
        // If non-premium user has Gemini selected, force to OpenAI
        if ( !$can_use_premium && $provider === 'gemini' ) {
            $provider = 'openai';
        }
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[ai_provider]" id="aifi-provider">
            <?php 
        foreach ( $providers as $value => $data ) {
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>"
                        <?php 
            selected( $provider, $value );
            ?>
                        <?php 
            echo ( !empty( $data['disabled'] ) ? 'disabled aria-disabled="true"' : '' );
            ?>>
                    <?php 
            echo esc_html( $data['label'] );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description"><?php 
        esc_html_e( 'Select which AI provider to use for image generation.', 'ai-featured-image-generator' );
        ?></p>
        <?php 
        // Show upgrade notice for free users
        if ( !function_exists( 'afig_fs' ) || !afig_fs()->is__premium_only() ) {
            ?>
            <p class="description aifi-upgrade-notice">
                <span class="dashicons dashicons-star-filled" style="color: #f0ad4e;"></span>
                <?php 
            printf( 
                /* translators: %s: upgrade link */
                esc_html__( 'Want more features? %s to unlock Google Gemini, advanced Stability AI models, Grok Pro features, upscaling, background removal, and more.', 'ai-featured-image-generator' ),
                '<a href="' . esc_url( afig_fs()->get_upgrade_url() ) . '">' . esc_html__( 'Upgrade to Pro', 'ai-featured-image-generator' ) . '</a>'
             );
            ?>
            </p>
            <?php 
        }
    }

    /**
     * Render OpenAI API key field.
     */
    public function render_openai_api_key_field() {
        $settings = $this->get_settings();
        // Support legacy 'api_key' field for backward compatibility
        $api_key = ( isset( $settings['openai_api_key'] ) ? $settings['openai_api_key'] : (( isset( $settings['api_key'] ) ? $settings['api_key'] : '' )) );
        ?>
        <input type="password"
               name="<?php 
        echo esc_attr( $this->option );
        ?>[openai_api_key]"
               id="aifi-openai-api-key"
               value="<?php 
        echo esc_attr( $api_key );
        ?>"
               class="regular-text"
               aria-describedby="aifi-openai-api-key-help">
        <button type="button" class="button aifi-test-key-btn" data-provider="openai" data-input="aifi-openai-api-key">
            <span class="dashicons dashicons-yes-alt"></span> <?php 
        esc_html_e( 'Test Connection', 'ai-featured-image-generator' );
        ?>
        </button>
        <span class="aifi-test-key-result" style="display:none; margin-left:8px;"></span>
        <p id="aifi-openai-api-key-help" class="description">
            <?php 
        echo sprintf( 
            /* translators: %s: OpenAI API keys page URL */
            esc_html__( 'To get your API key, sign in at %s, verify your organization if needed, click Create new secret key, copy it, then paste it into the API Key field above and click Save Changes.', 'ai-featured-image-generator' ),
            '<a href="https://platform.openai.com/api-keys" target="_blank" rel="noopener">platform.openai.com/api-keys</a>'
         );
        ?>
            <br>
            <a href="https://platform.openai.com/usage" target="_blank" rel="noopener"><?php 
        esc_html_e( 'View API Usage', 'ai-featured-image-generator' );
        ?> &rarr;</a>
        </p>
        <?php 
    }

    /**
     * Render Gemini API key field.
     */
    public function render_gemini_api_key_field() {
        return;
    }

    /**
     * Get human-readable provider label.
     *
     * @param string $provider Provider slug.
     * @return string
     */
    private function get_provider_label( $provider ) {
        $labels = array(
            'openai'    => 'OpenAI',
            'gemini'    => 'Google Gemini',
            'stability' => 'Stability AI',
            'grok'      => 'Grok / xAI',
        );
        return ( isset( $labels[$provider] ) ? $labels[$provider] : 'OpenAI' );
    }

    /**
     * Render Stability AI API key field.
     */
    public function render_stability_api_key_field() {
        $settings = $this->get_settings();
        $api_key = ( isset( $settings['stability_api_key'] ) ? $settings['stability_api_key'] : '' );
        ?>
        <input type="password"
               name="<?php 
        echo esc_attr( $this->option );
        ?>[stability_api_key]"
               id="aifi-stability-api-key"
               value="<?php 
        echo esc_attr( $api_key );
        ?>"
               class="regular-text"
               aria-describedby="aifi-stability-api-key-help">
        <button type="button" class="button aifi-test-key-btn" data-provider="stability" data-input="aifi-stability-api-key">
            <span class="dashicons dashicons-yes-alt"></span> <?php 
        esc_html_e( 'Test Connection', 'ai-featured-image-generator' );
        ?>
        </button>
        <span class="aifi-test-key-result" style="display:none; margin-left:8px;"></span>
        <p id="aifi-stability-api-key-help" class="description">
            <?php 
        echo sprintf( 
            /* translators: %s: Stability AI API keys page URL */
            esc_html__( 'To get your API key, sign in at %s, navigate to your API keys, create a new key, copy it, then paste it above and click Save Changes.', 'ai-featured-image-generator' ),
            '<a href="https://platform.stability.ai/account/keys" target="_blank" rel="noopener">platform.stability.ai/account/keys</a>'
         );
        ?>
        </p>
        <?php 
    }

    /**
     * Render Grok / xAI API key field.
     */
    public function render_grok_api_key_field() {
        $settings = $this->get_settings();
        $api_key = ( isset( $settings['grok_api_key'] ) ? $settings['grok_api_key'] : '' );
        ?>
        <input type="password"
               name="<?php 
        echo esc_attr( $this->option );
        ?>[grok_api_key]"
               id="aifi-grok-api-key"
               value="<?php 
        echo esc_attr( $api_key );
        ?>"
               class="regular-text"
               aria-describedby="aifi-grok-api-key-help">
        <button type="button" class="button aifi-test-key-btn" data-provider="grok" data-input="aifi-grok-api-key">
            <span class="dashicons dashicons-yes-alt"></span> <?php 
        esc_html_e( 'Test Connection', 'ai-featured-image-generator' );
        ?>
        </button>
        <span class="aifi-test-key-result" style="display:none; margin-left:8px;"></span>
        <p id="aifi-grok-api-key-help" class="description">
            <?php 
        echo sprintf( 
            /* translators: %s: xAI console URL */
            esc_html__( 'To get your API key, sign in at %s, create a new API key, copy it, then paste it above and click Save Changes.', 'ai-featured-image-generator' ),
            '<a href="https://console.x.ai/" target="_blank" rel="noopener">console.x.ai</a>'
         );
        ?>
        </p>
        <?php 
    }

    /**
     * Render Stability AI aspect ratio field.
     */
    public function render_stability_aspect_ratio_field() {
        $settings = $this->get_settings();
        $aspect_ratio = ( isset( $settings['stability_aspect_ratio'] ) ? $settings['stability_aspect_ratio'] : '16:9' );
        $is_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
        $free_ratios = array('1:1', '16:9', '9:16');
        $ratios = array(
            '1:1'  => __( '1:1 (Square)', 'ai-featured-image-generator' ),
            '16:9' => __( '16:9 (Landscape)', 'ai-featured-image-generator' ),
            '21:9' => __( '21:9 (Cinematic)', 'ai-featured-image-generator' ),
            '2:3'  => __( '2:3 (Portrait)', 'ai-featured-image-generator' ),
            '3:2'  => __( '3:2 (Landscape)', 'ai-featured-image-generator' ),
            '4:5'  => __( '4:5 (Portrait)', 'ai-featured-image-generator' ),
            '5:4'  => __( '5:4 (Landscape)', 'ai-featured-image-generator' ),
            '9:16' => __( '9:16 (Tall)', 'ai-featured-image-generator' ),
            '9:21' => __( '9:21 (Ultra Tall)', 'ai-featured-image-generator' ),
        );
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[stability_aspect_ratio]">
            <?php 
        foreach ( $ratios as $value => $label ) {
            $is_disabled = !$is_premium && !in_array( $value, $free_ratios, true );
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $aspect_ratio, $value );
            ?> <?php 
            disabled( $is_disabled );
            ?>>
                    <?php 
            echo esc_html( ( $is_disabled ? $label . ' (Pro)' : $label ) );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description">
            <?php 
        esc_html_e( 'Choose the aspect ratio for Stability AI generated images.', 'ai-featured-image-generator' );
        ?>
            <?php 
        if ( !$is_premium ) {
            ?>
                <br><span class="dashicons dashicons-star-filled" style="color: #f0ad4e; font-size: 14px;"></span>
                <?php 
            printf( esc_html__( '%s to unlock all 9 aspect ratios.', 'ai-featured-image-generator' ), '<a href="' . esc_url( afig_fs()->get_upgrade_url() ) . '">' . esc_html__( 'Upgrade to Pro', 'ai-featured-image-generator' ) . '</a>' );
            ?>
            <?php 
        }
        ?>
        </p>
        <?php 
    }

    /**
     * Render Stability AI style preset field.
     */
    public function render_stability_style_preset_field() {
        $settings = $this->get_settings();
        $style_preset = ( isset( $settings['stability_style_preset'] ) ? $settings['stability_style_preset'] : '' );
        $presets = array(
            ''             => __( 'None (No Preset)', 'ai-featured-image-generator' ),
            'photographic' => __( 'Photographic', 'ai-featured-image-generator' ),
            'anime'        => __( 'Anime', 'ai-featured-image-generator' ),
            'digital-art'  => __( 'Digital Art', 'ai-featured-image-generator' ),
            'cinematic'    => __( 'Cinematic', 'ai-featured-image-generator' ),
            'comic-book'   => __( 'Comic Book', 'ai-featured-image-generator' ),
            'fantasy-art'  => __( 'Fantasy Art', 'ai-featured-image-generator' ),
            '3d-model'     => __( '3D Model', 'ai-featured-image-generator' ),
            'analog-film'  => __( 'Analog Film', 'ai-featured-image-generator' ),
            'enhance'      => __( 'Enhance', 'ai-featured-image-generator' ),
            'isometric'    => __( 'Isometric', 'ai-featured-image-generator' ),
            'line-art'     => __( 'Line Art', 'ai-featured-image-generator' ),
            'low-poly'     => __( 'Low Poly', 'ai-featured-image-generator' ),
            'neon-punk'    => __( 'Neon Punk', 'ai-featured-image-generator' ),
            'origami'      => __( 'Origami', 'ai-featured-image-generator' ),
            'pixel-art'    => __( 'Pixel Art', 'ai-featured-image-generator' ),
            'tile-texture' => __( 'Tile Texture', 'ai-featured-image-generator' ),
        );
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[stability_style_preset]">
            <?php 
        foreach ( $presets as $value => $label ) {
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $style_preset, $value );
            ?>>
                    <?php 
            echo esc_html( $label );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description">
            <?php 
        esc_html_e( 'Stability AI native style preset. This is applied at the API level in addition to the plugin style above.', 'ai-featured-image-generator' );
        ?>
        </p>
        <?php 
    }

    /**
     * Render Stability AI output format field (Pro only).
     */
    public function render_stability_output_format_field() {
        if ( !function_exists( 'afig_fs' ) || !afig_fs()->is__premium_only() ) {
            return;
        }
        $settings = $this->get_settings();
        $output_format = ( isset( $settings['stability_output_format'] ) ? $settings['stability_output_format'] : 'png' );
        $formats = array(
            'png'  => 'PNG',
            'jpeg' => 'JPEG',
            'webp' => 'WebP',
        );
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[stability_output_format]">
            <?php 
        foreach ( $formats as $value => $label ) {
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $output_format, $value );
            ?>>
                    <?php 
            echo esc_html( $label );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description">
            <?php 
        esc_html_e( 'Choose the output format for Stability AI generated images.', 'ai-featured-image-generator' );
        ?>
        </p>
        <?php 
    }

    /**
     * Render Stability AI negative prompt field (Pro only).
     */
    public function render_stability_negative_prompt_field() {
        if ( !function_exists( 'afig_fs' ) || !afig_fs()->is__premium_only() ) {
            return;
        }
        $settings = $this->get_settings();
        $negative_prompt = ( isset( $settings['stability_negative_prompt'] ) ? $settings['stability_negative_prompt'] : '' );
        ?>
        <textarea name="<?php 
        echo esc_attr( $this->option );
        ?>[stability_negative_prompt]"
                  rows="3"
                  class="large-text"
                  placeholder="<?php 
        esc_attr_e( 'e.g. blurry, text, watermark, low quality', 'ai-featured-image-generator' );
        ?>"><?php 
        echo esc_textarea( $negative_prompt );
        ?></textarea>
        <p class="description">
            <?php 
        esc_html_e( 'Describe elements to exclude from generated images. Leave empty for no restrictions.', 'ai-featured-image-generator' );
        ?>
        </p>
        <?php 
    }

    /**
     * Render Grok aspect ratio field.
     */
    public function render_grok_aspect_ratio_field() {
        $settings = $this->get_settings();
        $current = ( isset( $settings['grok_aspect_ratio'] ) ? $settings['grok_aspect_ratio'] : '1:1' );
        $is_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
        $free_ratios = array('1:1', '16:9', '9:16');
        $ratios = array(
            '1:1'  => __( 'Square (1:1)', 'ai-featured-image-generator' ),
            '16:9' => __( 'Landscape (16:9)', 'ai-featured-image-generator' ),
            '9:16' => __( 'Portrait (9:16)', 'ai-featured-image-generator' ),
            '4:3'  => __( 'Landscape (4:3)', 'ai-featured-image-generator' ),
            '3:4'  => __( 'Portrait (3:4)', 'ai-featured-image-generator' ),
            '3:2'  => __( 'Landscape (3:2)', 'ai-featured-image-generator' ),
            '2:3'  => __( 'Portrait (2:3)', 'ai-featured-image-generator' ),
            '2:1'  => __( 'Wide (2:1)', 'ai-featured-image-generator' ),
            '1:2'  => __( 'Tall (1:2)', 'ai-featured-image-generator' ),
        );
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[grok_aspect_ratio]">
            <?php 
        foreach ( $ratios as $value => $label ) {
            $is_disabled = !$is_premium && !in_array( $value, $free_ratios, true );
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $current, $value );
            ?> <?php 
            disabled( $is_disabled );
            ?>>
                    <?php 
            echo esc_html( ( $is_disabled ? $label . ' (Pro)' : $label ) );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description">
            <?php 
        esc_html_e( 'Choose the default aspect ratio for Grok generated images.', 'ai-featured-image-generator' );
        ?>
            <?php 
        if ( !$is_premium ) {
            ?>
                <br><span class="dashicons dashicons-star-filled" style="color: #f0ad4e; font-size: 14px;"></span>
                <?php 
            printf( esc_html__( '%s to unlock all 9 aspect ratios.', 'ai-featured-image-generator' ), '<a href="' . esc_url( afig_fs()->get_upgrade_url() ) . '">' . esc_html__( 'Upgrade to Pro', 'ai-featured-image-generator' ) . '</a>' );
            ?>
            <?php 
        }
        ?>
        </p>
        <?php 
    }

    /**
     * Render Grok resolution field.
     */
    public function render_grok_resolution_field() {
        $settings = $this->get_settings();
        $current = ( isset( $settings['grok_resolution'] ) ? $settings['grok_resolution'] : '1k' );
        $is_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[grok_resolution]">
            <option value="1k" <?php 
        selected( $current, '1k' );
        ?>><?php 
        esc_html_e( '1K (Standard)', 'ai-featured-image-generator' );
        ?></option>
            <option value="2k" <?php 
        selected( $current, '2k' );
        ?> <?php 
        disabled( !$is_premium );
        ?>>
                <?php 
        echo ( $is_premium ? esc_html__( '2K (High Quality)', 'ai-featured-image-generator' ) : esc_html__( '2K (High Quality) (Pro)', 'ai-featured-image-generator' ) );
        ?>
            </option>
        </select>
        <p class="description">
            <?php 
        if ( $is_premium ) {
            ?>
                <?php 
            esc_html_e( '2K offers sharper, more detailed images but results in larger file sizes which may affect page load speed.', 'ai-featured-image-generator' );
            ?>
            <?php 
        } else {
            ?>
                <?php 
            esc_html_e( '1K resolution is included with the free plan.', 'ai-featured-image-generator' );
            ?>
                <br><span class="dashicons dashicons-star-filled" style="color: #f0ad4e; font-size: 14px;"></span>
                <?php 
            printf( esc_html__( '%s to unlock 2K high quality resolution.', 'ai-featured-image-generator' ), '<a href="' . esc_url( afig_fs()->get_upgrade_url() ) . '">' . esc_html__( 'Upgrade to Pro', 'ai-featured-image-generator' ) . '</a>' );
            ?>
            <?php 
        }
        ?>
        </p>
        <?php 
    }

    /**
     * Render size field.
     */
    public function render_size_field() {
        $settings = $this->get_settings();
        $size = ( isset( $settings['default_size'] ) ? $settings['default_size'] : '1024x1024' );
        $gpt2_only_sizes = array(
            '1792x1024',
            '1024x1792',
            '1920x640',
            '640x1920'
        );
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[default_size]" id="aifi-default-size">
            <?php 
        foreach ( self::OPENAI_SIZES as $value => $label ) {
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>"
                    <?php 
            selected( $size, $value );
            ?>
                    <?php 
            if ( in_array( $value, $gpt2_only_sizes, true ) ) {
                ?>data-gpt2-only="1"<?php 
            }
            ?>>
                    <?php 
            echo esc_html( $label );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description">
            <?php 
        esc_html_e( 'Choose the default image size. GPT Image 2 unlocks four additional aspect ratios (16:9 widescreen, 9:16 vertical, 3:1 ultra-wide, 1:3 tall banner). Older OpenAI models support only 1:1, 2:3, and 3:2.', 'ai-featured-image-generator' );
        ?>
        </p>
        <?php 
    }

    /**
     * Render Gemini aspect ratio field.
     */
    public function render_gemini_aspect_ratio_field() {
        return;
    }

    /**
     * Render Gemini image size field.
     */
    public function render_gemini_image_size_field() {
        return;
    }

    /**
     * Get custom styles saved by pro users.
     *
     * @return array
     */
    public function get_custom_styles() {
        if ( !function_exists( 'afig_fs' ) || !afig_fs()->can_use_premium_code() ) {
            return array();
        }
        $settings = $this->get_settings();
        return ( isset( $settings['custom_styles'] ) ? (array) $settings['custom_styles'] : array() );
    }

    /**
     * Render custom styles field (Pro only).
     */
    public function render_custom_styles_field() {
        $is_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
        if ( !$is_premium ) {
            $upgrade_url = ( function_exists( 'afig_fs' ) ? afig_fs()->get_upgrade_url() : '#' );
            printf(
                '<p><span class="dashicons dashicons-star-filled" style="color:#f0ad4e;"></span> %s <a href="%s">%s</a></p>',
                esc_html__( 'Custom Styles let you create your own image style names and prompts. Available with Pro.', 'ai-featured-image-generator' ),
                esc_url( $upgrade_url ),
                esc_html__( 'Upgrade to Pro', 'ai-featured-image-generator' )
            );
            return;
        }
        $custom_styles = $this->get_custom_styles();
        ?>
        <div class="aifi-custom-styles-wrap">
            <table class="aifi-custom-styles-table widefat" id="aifi-custom-styles-table">
                <thead>
                    <tr>
                        <th><?php 
        esc_html_e( 'Style Name', 'ai-featured-image-generator' );
        ?></th>
                        <th><?php 
        esc_html_e( 'Prompt Description', 'ai-featured-image-generator' );
        ?></th>
                        <th style="width:60px;"></th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
        foreach ( $custom_styles as $i => $cs ) {
            ?>
                    <tr class="aifi-custom-style-row">
                        <td>
                            <input type="text"
                                   name="<?php 
            echo esc_attr( $this->option );
            ?>[custom_styles][<?php 
            echo $i;
            ?>][name]"
                                   value="<?php 
            echo esc_attr( $cs['name'] );
            ?>"
                                   class="regular-text"
                                   placeholder="<?php 
            esc_attr_e( 'e.g. Dreamy', 'ai-featured-image-generator' );
            ?>">
                        </td>
                        <td>
                            <input type="text"
                                   name="<?php 
            echo esc_attr( $this->option );
            ?>[custom_styles][<?php 
            echo $i;
            ?>][prompt]"
                                   value="<?php 
            echo esc_attr( $cs['prompt'] );
            ?>"
                                   class="large-text"
                                   placeholder="<?php 
            esc_attr_e( 'e.g. in a dreamy impressionist style', 'ai-featured-image-generator' );
            ?>">
                        </td>
                        <td>
                            <button type="button" class="button aifi-remove-custom-style" aria-label="<?php 
            esc_attr_e( 'Remove style', 'ai-featured-image-generator' );
            ?>">
                                <span class="dashicons dashicons-trash"></span>
                            </button>
                        </td>
                    </tr>
                    <?php 
        }
        ?>
                </tbody>
            </table>
            <p>
                <button type="button" class="button" id="aifi-add-custom-style">
                    <span class="dashicons dashicons-plus-alt2" style="margin-top:3px;"></span>
                    <?php 
        esc_html_e( 'Add Style', 'ai-featured-image-generator' );
        ?>
                </button>
            </p>
            <p class="description"><?php 
        esc_html_e( 'Add custom image styles with a name and a prompt fragment (e.g. "in a dreamy impressionist style"). Custom styles appear in all style dropdowns.', 'ai-featured-image-generator' );
        ?></p>
        </div>
        <?php 
    }

    /**
     * Render style field.
     */
    public function render_style_field() {
        $settings = $this->get_settings();
        $style = ( isset( $settings['default_style'] ) ? $settings['default_style'] : 'realistic' );
        $common_styles = array(
            'none'       => __( 'None (No Style)', 'ai-featured-image-generator' ),
            'realistic'  => __( 'Realistic', 'ai-featured-image-generator' ),
            'artistic'   => __( 'Artistic', 'ai-featured-image-generator' ),
            'cartoon'    => __( 'Cartoon', 'ai-featured-image-generator' ),
            'minimalist' => __( 'Minimalist', 'ai-featured-image-generator' ),
        );
        $creative_styles = array(
            'sketch'      => __( 'Sketch', 'ai-featured-image-generator' ),
            'watercolor'  => __( 'Watercolor', 'ai-featured-image-generator' ),
            '3d'          => __( '3D Render', 'ai-featured-image-generator' ),
            'pixel'       => __( 'Pixel Art', 'ai-featured-image-generator' ),
            'cyberpunk'   => __( 'Cyberpunk', 'ai-featured-image-generator' ),
            'fantasy'     => __( 'Fantasy', 'ai-featured-image-generator' ),
            'anime'       => __( 'Anime', 'ai-featured-image-generator' ),
            'technicolor' => __( 'Technicolor', 'ai-featured-image-generator' ),
        );
        ?>
        <?php 
        $custom_styles_list = $this->get_custom_styles();
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[default_style]">
            <optgroup label="<?php 
        esc_attr_e( 'Common', 'ai-featured-image-generator' );
        ?>">
                <?php 
        foreach ( $common_styles as $value => $label ) {
            ?>
                    <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $style, $value );
            ?>>
                        <?php 
            echo esc_html( $label );
            ?>
                    </option>
                <?php 
        }
        ?>
            </optgroup>
            <optgroup label="<?php 
        esc_attr_e( 'Creative', 'ai-featured-image-generator' );
        ?>">
                <?php 
        foreach ( $creative_styles as $value => $label ) {
            ?>
                    <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $style, $value );
            ?>>
                        <?php 
            echo esc_html( $label );
            ?>
                    </option>
                <?php 
        }
        ?>
            </optgroup>
            <?php 
        if ( !empty( $custom_styles_list ) ) {
            ?>
            <optgroup label="<?php 
            esc_attr_e( 'Custom', 'ai-featured-image-generator' );
            ?>">
                <?php 
            foreach ( $custom_styles_list as $i => $cs ) {
                ?>
                    <option value="custom_<?php 
                echo $i;
                ?>" <?php 
                selected( $style, 'custom_' . $i );
                ?>>
                        <?php 
                echo esc_html( $cs['name'] );
                ?>
                    </option>
                <?php 
            }
            ?>
            </optgroup>
            <?php 
        }
        ?>
        </select>
        <?php 
    }

    /**
     * Render allow text field.
     */
    public function render_allow_text_field() {
        $settings = $this->get_settings();
        $allow_text = ( isset( $settings['allow_text'] ) ? (bool) $settings['allow_text'] : false );
        ?>
        <label>
            <input type="checkbox" name="<?php 
        echo esc_attr( $this->option );
        ?>[allow_text]" value="1" <?php 
        checked( $allow_text, true );
        ?>>
            <?php 
        esc_html_e( 'Allow text, captions, or words to appear in generated images', 'ai-featured-image-generator' );
        ?>
        </label>
        <p class="description">
            <?php 
        esc_html_e( 'If checked, you can enter custom text to appear in the image; if you leave the text field empty, the post title will be used instead. If unchecked, the AI will avoid adding any text, captions, or words.', 'ai-featured-image-generator' );
        ?>
        </p>
        <p class="description aifi-stability-only aifi-stability-text-warning" style="margin-top: 8px; color: #b45309; font-style: normal;">
            <span class="dashicons dashicons-warning" style="font-size: 14px; width: 14px; height: 14px; vertical-align: middle; margin-right: 2px; color: #d97706;"></span>
            <?php 
        esc_html_e( 'Stability AI models have limited text rendering capabilities. Text in generated images may appear distorted or unreadable. For reliable text on images, consider using OpenAI or Gemini or Grok instead.', 'ai-featured-image-generator' );
        ?>
        </p>
        <?php 
    }

    /**
     * Render output format field.
     */
    public function render_output_format_field() {
        $settings = $this->get_settings();
        $output_format = ( isset( $settings['output_format'] ) ? $settings['output_format'] : 'webp' );
        $formats = array(
            'webp' => 'WebP (Recommended)',
            'png'  => 'PNG',
            'jpeg' => 'JPEG',
        );
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[output_format]">
            <?php 
        foreach ( $formats as $value => $label ) {
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $output_format, $value );
            ?>>
                    <?php 
            echo esc_html( $label );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description">
            <?php 
        esc_html_e( 'Choose the output format for generated images. WebP provides the best compression and quality. The Output Compression slider only applies to WebP and JPEG (PNG is lossless). For transparent backgrounds on GPT Image 2, pick PNG.', 'ai-featured-image-generator' );
        ?>
        </p>
        <?php 
    }

    /**
     * Render quality field.
     */
    public function render_quality_field() {
        $settings = $this->get_settings();
        $quality = ( isset( $settings['image_quality'] ) ? intval( $settings['image_quality'] ) : 90 );
        if ( $quality <= 25 ) {
            $label = __( 'Max compression', 'ai-featured-image-generator' );
        } elseif ( $quality <= 50 ) {
            $label = __( 'Balanced', 'ai-featured-image-generator' );
        } elseif ( $quality <= 75 ) {
            $label = __( 'Light compression', 'ai-featured-image-generator' );
        } else {
            $label = __( 'Near-lossless', 'ai-featured-image-generator' );
        }
        ?>
        <input type="range"
               name="<?php 
        echo esc_attr( $this->option );
        ?>[image_quality]"
               value="<?php 
        echo esc_attr( $quality );
        ?>"
               min="1"
               max="100"
               class="regular-text"
               id="aifi-quality-slider"
               oninput="document.getElementById('aifi-settings-quality-value').textContent = this.value; document.getElementById('aifi-settings-quality-label').textContent = aifiGetQualityLabel(this.value);">
        <span id="aifi-settings-quality-value"><?php 
        echo esc_html( $quality );
        ?></span>
        <span id="aifi-settings-quality-label" class="aifi-quality-label"><?php 
        echo esc_html( $label );
        ?></span>
        <p class="description">
            <?php 
        esc_html_e( 'Controls file-size compression for WebP and JPEG output (1–100). Higher values mean larger files; lower values reduce file size and costs. PNG is lossless and ignores this setting. This is separate from the Generation Quality tier.', 'ai-featured-image-generator' );
        ?>
        </p>
        <script>
        if (typeof aifiGetQualityLabel === 'undefined') {
            function aifiGetQualityLabel(v) {
                v = parseInt(v);
                if (v <= 25) return '<?php 
        echo esc_js( __( 'Max compression', 'ai-featured-image-generator' ) );
        ?>';
                if (v <= 50) return '<?php 
        echo esc_js( __( 'Balanced', 'ai-featured-image-generator' ) );
        ?>';
                if (v <= 75) return '<?php 
        echo esc_js( __( 'Light compression', 'ai-featured-image-generator' ) );
        ?>';
                return '<?php 
        echo esc_js( __( 'Near-lossless', 'ai-featured-image-generator' ) );
        ?>';
            }
        }
        </script>
        <?php 
    }

    /**
     * Render OpenAI generation quality field (low / medium / high content tier).
     */
    public function render_openai_quality_field() {
        $settings = $this->get_settings();
        $quality = ( isset( $settings['openai_quality'] ) ? $settings['openai_quality'] : 'high' );
        $options = array(
            'high'   => __( 'High (Default — best results)', 'ai-featured-image-generator' ),
            'medium' => __( 'Medium (Faster, moderate detail)', 'ai-featured-image-generator' ),
            'low'    => __( 'Low (Fastest, cheapest — good for drafts)', 'ai-featured-image-generator' ),
        );
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[openai_quality]">
            <?php 
        foreach ( $options as $value => $label ) {
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $quality, $value );
            ?>>
                    <?php 
            echo esc_html( $label );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description">
            <?php 
        esc_html_e( "Controls how much compute GPT Image models spend on each generation. 'High' (default) gives the best-looking results. 'Medium' and 'Low' are faster and cheaper — useful for drafts, thumbnails, and iterating on prompts.", 'ai-featured-image-generator' );
        ?>
        </p>
        <?php 
    }

    /**
     * Render OpenAI background field (gpt-image-2 only).
     */
    public function render_openai_background_field() {
        $settings = $this->get_settings();
        $background = ( isset( $settings['openai_background'] ) ? $settings['openai_background'] : 'auto' );
        $options = array(
            'auto'        => __( 'Auto (Model decides)', 'ai-featured-image-generator' ),
            'transparent' => __( 'Transparent cutout (subject only, saved as PNG)', 'ai-featured-image-generator' ),
            'opaque'      => __( 'Solid background (standard framing)', 'ai-featured-image-generator' ),
        );
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[openai_background]" id="aifi-openai-background">
            <?php 
        foreach ( $options as $value => $label ) {
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $background, $value );
            ?>>
                    <?php 
            echo esc_html( $label );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description">
            <?php 
        esc_html_e( "Only applies to GPT Image 2. 'Auto' lets the model decide. 'Transparent cutout' isolates the subject on a transparent background — great for logos, product shots, and compositing. 'Solid background' keeps the standard framing.", 'ai-featured-image-generator' );
        ?>
            <br>
            <em><?php 
        esc_html_e( 'Note: Choosing Transparent cutout automatically saves the image as PNG, even if your Output Format is set to WebP or JPEG.', 'ai-featured-image-generator' );
        ?></em>
        </p>
        <?php 
    }

    /**
     * Render OpenAI moderation field (gpt-image-2 only).
     */
    public function render_openai_moderation_field() {
        $settings = $this->get_settings();
        $moderation = ( isset( $settings['openai_moderation'] ) ? $settings['openai_moderation'] : 'auto' );
        $options = array(
            'auto' => __( 'Auto (Standard filtering)', 'ai-featured-image-generator' ),
            'low'  => __( 'Low (More permissive — approved accounts only)', 'ai-featured-image-generator' ),
        );
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[openai_moderation]">
            <?php 
        foreach ( $options as $value => $label ) {
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $moderation, $value );
            ?>>
                    <?php 
            echo esc_html( $label );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description">
            <?php 
        esc_html_e( "Only applies to GPT Image 2. 'Auto' uses OpenAI's standard filters. 'Low' is more permissive; use only if your workflow requires it and your OpenAI account is approved for relaxed moderation.", 'ai-featured-image-generator' );
        ?>
        </p>
        <?php 
    }

    /**
     * Render enabled post types field.
     * Pro users: Full control over all post types
     * Free users: Post and Page only, other types shown as disabled with Pro badge
     */
    public function render_enabled_post_types_field() {
        $is_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
        $settings = $this->get_settings();
        $enabled_post_types = ( isset( $settings['enabled_post_types'] ) ? (array) $settings['enabled_post_types'] : array('post', 'page') );
        // Free users always have post and page enabled
        $free_post_types = array('post', 'page');
        // Get all public post types
        $post_types = get_post_types( array(
            'public' => true,
        ), 'objects' );
        // Remove attachment from the list (media library items)
        unset($post_types['attachment']);
        ?>
        <fieldset>
            <legend class="screen-reader-text"><span><?php 
        esc_html_e( 'Enabled Post Types', 'ai-featured-image-generator' );
        ?></span></legend>
            <?php 
        foreach ( $post_types as $post_type ) {
            $is_free_type = in_array( $post_type->name, $free_post_types, true );
            $is_disabled_cpt = !$is_premium && !$is_free_type;
            // Custom post types disabled for free users
            $is_checked = ( $is_premium ? in_array( $post_type->name, $enabled_post_types, true ) : $is_free_type );
            ?>
                <label style="display: block; margin-bottom: 8px;<?php 
            echo ( $is_disabled_cpt ? ' opacity: 0.5; cursor: not-allowed; pointer-events: none;' : '' );
            ?>">
                    <input type="checkbox"
                           <?php 
            if ( $is_premium ) {
                ?>
                           name="<?php 
                echo esc_attr( $this->option );
                ?>[enabled_post_types][]"
                           <?php 
            }
            ?>
                           value="<?php 
            echo esc_attr( $post_type->name );
            ?>"
                           <?php 
            checked( $is_checked );
            ?>
                           <?php 
            disabled( !$is_premium );
            ?>>
                    <?php 
            echo esc_html( $post_type->labels->singular_name );
            ?>
                    <span style="color: #6b7280; font-size: 12px;">(<?php 
            echo esc_html( $post_type->name );
            ?>)</span>
                    <?php 
            if ( $is_disabled_cpt ) {
                ?>
                        <span style="background: linear-gradient(135deg, #f0ad4e 0%, #ec971f 100%); color: #1a1a2e; font-size: 10px; font-weight: 600; padding: 2px 6px; border-radius: 3px; margin-left: 6px; text-transform: uppercase;"><?php 
                esc_html_e( 'Pro', 'ai-featured-image-generator' );
                ?></span>
                    <?php 
            }
            ?>
                </label>
            <?php 
        }
        ?>
        </fieldset>
        <p class="description">
            <span class="dashicons dashicons-star-filled" style="color: #f0ad4e; font-size: 14px; width: 14px; height: 14px; vertical-align: middle;"></span>
            <?php 
        if ( $is_premium ) {
            ?>
                <?php 
            esc_html_e( 'Pro Feature: Select which post types should have the AI Featured Image Generator panel. Uncheck a post type to hide the generator from that editor.', 'ai-featured-image-generator' );
            ?>
            <?php 
        } else {
            ?>
                <?php 
            esc_html_e( 'Free version supports Posts and Pages.', 'ai-featured-image-generator' );
            ?>
                <a href="<?php 
            echo esc_url( afig_fs()->get_upgrade_url() );
            ?>"><?php 
            esc_html_e( 'Upgrade to Pro', 'ai-featured-image-generator' );
            ?></a>
                <?php 
            esc_html_e( 'to enable custom post types like Products, Movies, and more.', 'ai-featured-image-generator' );
            ?>
            <?php 
        }
        ?>
        </p>
        <?php 
    }

    /**
     * Render model field.
     */
    public function render_model_field() {
        $settings = $this->get_settings();
        $model = ( isset( $settings['ai_model'] ) ? $settings['ai_model'] : 'gpt-image-2' );
        $provider = ( isset( $settings['ai_provider'] ) ? $settings['ai_provider'] : 'openai' );
        $openai_models = array(
            'chatgpt-image-latest' => 'ChatGPT Image Latest (Auto-updated)',
            'gpt-image-2'          => 'GPT Image 2 (Most Accurate)',
            'gpt-image-1.5'        => 'GPT Image 1.5',
            'gpt-image-1'          => 'GPT Image 1 (Standard)',
            'gpt-image-1-mini'     => 'GPT Image 1 Mini (Cheaper)',
        );
        // Gemini models only available for premium users
        $gemini_models = array();
        if ( function_exists( 'afig_fs' ) && afig_fs()->is__premium_only() ) {
            $gemini_models = array(
                'gemini-2.5-flash-image'         => 'Nano Banana (Gemini 2.5 Flash Image)',
                'gemini-3.1-flash-image-preview' => 'Nano Banana 2 (Gemini 3.1 Flash)',
                'gemini-3-pro-image-preview'     => 'Nana Banana Pro (Gemini 3 Pro)',
            );
        }
        $can_use_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
        // Stability AI models - always show all, Pro-only ones are disabled for free users
        $stability_models = array(
            'ultra'             => 'Stable Image Ultra (Best Quality)',
            'core'              => 'Stable Image Core',
            'sd3.5-large'       => 'Stable Diffusion 3.5 Large',
            'sd3.5-large-turbo' => 'SD 3.5 Large Turbo (Fast)',
            'sd3.5-medium'      => 'SD 3.5 Medium',
            'sd3.5-flash'       => 'SD 3.5 Flash',
            'sd3-large'         => 'SD 3 Large',
            'sd3-large-turbo'   => 'SD 3 Large Turbo',
            'sd3-medium'        => 'SD 3 Medium',
            'sdxl-1.0'          => 'SDXL 1.0 (Legacy)',
        );
        $stability_free_models = array('core');
        // Grok models - always show all, Pro-only ones are disabled for free users
        $grok_models = array(
            'grok-imagine-image-pro' => 'Grok Imagine Image Pro ($0.07/image)',
            'grok-imagine-image'     => 'Grok Imagine Image ($0.02/image)',
        );
        $grok_free_models = array('grok-imagine-image');
        // If non-premium user has Gemini provider selected, force to OpenAI
        if ( (!function_exists( 'afig_fs' ) || !afig_fs()->is__premium_only()) && $provider === 'gemini' ) {
            $provider = 'openai';
            $model = 'gpt-image-2';
        }
        // If Gemini provider and no Gemini model is set, default to Nano Banana 2
        if ( $provider === 'gemini' && !isset( $gemini_models[$model] ) ) {
            $model = 'gemini-3.1-flash-image-preview';
        }
        // If Stability provider and no valid model is set, default to core
        if ( $provider === 'stability' && !isset( $stability_models[$model] ) ) {
            $model = 'core';
        }
        // Free users with a Pro-only Stability model saved get forced to core
        if ( $provider === 'stability' && !$can_use_premium && !in_array( $model, $stability_free_models, true ) ) {
            $model = 'core';
        }
        // If Grok provider and no valid model is set, default
        if ( $provider === 'grok' && !isset( $grok_models[$model] ) ) {
            $model = 'grok-imagine-image';
        }
        // Free users with a Pro-only Grok model saved get forced to standard
        if ( $provider === 'grok' && !$can_use_premium && !in_array( $model, $grok_free_models, true ) ) {
            $model = 'grok-imagine-image';
        }
        // Store models data for JavaScript
        $models_data = array(
            'openai'    => $openai_models,
            'stability' => $stability_models,
            'grok'      => $grok_models,
        );
        // Only include Gemini models for premium users
        if ( function_exists( 'afig_fs' ) && afig_fs()->is__premium_only() ) {
            $models_data['gemini'] = $gemini_models;
        }
        // Build disabled-models map for JS (Pro-only models that free users can see but not select)
        $disabled_models = array();
        if ( !$can_use_premium ) {
            $disabled_models['stability'] = array_values( array_diff( array_keys( $stability_models ), $stability_free_models ) );
            $disabled_models['grok'] = array_values( array_diff( array_keys( $grok_models ), $grok_free_models ) );
        }
        ?>
        <?php 
        // Determine which models to show and which are disabled
        if ( $provider === 'gemini' && function_exists( 'afig_fs' ) && afig_fs()->is__premium_only() ) {
            $current_models = $gemini_models;
            $current_disabled = array();
        } elseif ( $provider === 'stability' ) {
            $current_models = $stability_models;
            $current_disabled = ( $can_use_premium ? array() : array_diff( array_keys( $stability_models ), $stability_free_models ) );
        } elseif ( $provider === 'grok' ) {
            $current_models = $grok_models;
            $current_disabled = ( $can_use_premium ? array() : array_diff( array_keys( $grok_models ), $grok_free_models ) );
        } else {
            $current_models = $openai_models;
            $current_disabled = array();
        }
        ?>
        <select name="<?php 
        echo esc_attr( $this->option );
        ?>[ai_model]" id="aifi-model">
            <?php 
        foreach ( $current_models as $value => $label ) {
            $is_disabled = in_array( $value, $current_disabled, true );
            ?>
                <option value="<?php 
            echo esc_attr( $value );
            ?>" <?php 
            selected( $model, $value );
            ?> <?php 
            disabled( $is_disabled );
            ?>>
                    <?php 
            echo esc_html( ( $is_disabled ? $label . ' (Pro)' : $label ) );
            ?>
                </option>
            <?php 
        }
        ?>
        </select>
        <p class="description aifi-openai-field" style="<?php 
        echo ( $provider !== 'openai' ? 'display:none;' : '' );
        ?>">
            <strong><?php 
        esc_html_e( 'GPT Image 2', 'ai-featured-image-generator' );
        ?></strong>
            <?php 
        esc_html_e( '(default, newest) — text rendering in multiple languages, visual reasoning, multi-object scenes, mask-based editing, up to 4K output with 7 aspect ratios, transparent backgrounds, quality tiers, and moderation control.', 'ai-featured-image-generator' );
        ?>
            <br>
            <strong><?php 
        esc_html_e( 'ChatGPT Image Latest', 'ai-featured-image-generator' );
        ?></strong>
            <?php 
        esc_html_e( '— auto-updates to the newest ChatGPT image model.', 'ai-featured-image-generator' );
        ?>
            <br>
            <strong><?php 
        esc_html_e( 'GPT Image 1.5', 'ai-featured-image-generator' );
        ?></strong>
            <?php 
        esc_html_e( '— cheaper and 4× faster than GPT Image 1, accurate text.', 'ai-featured-image-generator' );
        ?>
            <br>
            <strong><?php 
        esc_html_e( 'GPT Image 1', 'ai-featured-image-generator' );
        ?></strong>
            <?php 
        esc_html_e( '— legacy premium option for finer style control.', 'ai-featured-image-generator' );
        ?>
            <br>
            <strong><?php 
        esc_html_e( 'GPT Image 1 Mini', 'ai-featured-image-generator' );
        ?></strong>
            <?php 
        esc_html_e( '— cheapest legacy option.', 'ai-featured-image-generator' );
        ?>
        </p>
        <?php 
        if ( function_exists( 'afig_fs' ) && afig_fs()->is__premium_only() ) {
            ?>
        <p class="description aifi-gemini-field" style="<?php 
            echo ( $provider !== 'gemini' ? 'display:none;' : '' );
            ?>">
            <?php 
            esc_html_e( 'Nano Banana (Gemini 2.5 Flash) is fast and affordable. Nano Banana 2 Preview (Gemini 3.1 Flash) adds higher resolution support. Nana Banana Pro (Gemini 3 Pro) offers the best quality.', 'ai-featured-image-generator' );
            ?>
        </p>
        <?php 
        }
        ?>
        <p class="description aifi-stability-field" style="<?php 
        echo ( $provider !== 'stability' ? 'display:none;' : '' );
        ?>">
            <?php 
        esc_html_e( 'Stable Image Ultra delivers the highest quality. Stable Image Core is fast and accessible. SD 3.5 Large offers fine detail, while Turbo variants are faster.', 'ai-featured-image-generator' );
        ?>
            <?php 
        if ( !$can_use_premium ) {
            ?>
                <br><span class="dashicons dashicons-star-filled" style="color: #f0ad4e; font-size: 14px;"></span>
                <?php 
            printf( esc_html__( '%s to unlock all 10 Stability AI models.', 'ai-featured-image-generator' ), '<a href="' . esc_url( afig_fs()->get_upgrade_url() ) . '">' . esc_html__( 'Upgrade to Pro', 'ai-featured-image-generator' ) . '</a>' );
            ?>
            <?php 
        }
        ?>
        </p>
        <p class="description aifi-grok-field" style="<?php 
        echo ( $provider !== 'grok' ? 'display:none;' : '' );
        ?>">
            <?php 
        esc_html_e( 'Grok Imagine Image is the standard model ($0.02/image, 300 RPM). Grok Imagine Image Pro offers higher quality output ($0.07/image, 30 RPM).', 'ai-featured-image-generator' );
        ?>
            <?php 
        if ( !$can_use_premium ) {
            ?>
                <br><span class="dashicons dashicons-star-filled" style="color: #f0ad4e; font-size: 14px;"></span>
                <?php 
            printf( esc_html__( '%s to unlock Grok Imagine Image Pro.', 'ai-featured-image-generator' ), '<a href="' . esc_url( afig_fs()->get_upgrade_url() ) . '">' . esc_html__( 'Upgrade to Pro', 'ai-featured-image-generator' ) . '</a>' );
            ?>
            <?php 
        }
        ?>
        </p>
        <script type="text/javascript">
        var aifiModelsData = <?php 
        echo wp_json_encode( $models_data );
        ?>;
        var aifiCanUsePremium = <?php 
        echo ( function_exists( 'afig_fs' ) && afig_fs()->is__premium_only() ? 'true' : 'false' );
        ?>;
        var aifiDisabledModels = <?php 
        echo wp_json_encode( $disabled_models );
        ?>;
        </script>
        <?php 
    }

    /**
     * Sanitize settings.
     *
     * @param array $input Settings input.
     * @return array
     */
    public function sanitize_settings( $input ) {
        // Start with existing settings to preserve values from other tabs
        $existing = $this->get_settings();
        $sanitized = ( is_array( $existing ) ? $existing : array() );
        // AI Provider - Gemini only allowed for premium users
        // Only update if present in form input (not all tabs include the provider field)
        if ( isset( $input['ai_provider'] ) ) {
            $allowed_providers = array('openai', 'stability', 'grok');
            // Only allow Gemini for premium users
            if ( function_exists( 'afig_fs' ) && afig_fs()->is__premium_only() ) {
                $allowed_providers[] = 'gemini';
            }
            $sanitized['ai_provider'] = ( in_array( $input['ai_provider'], $allowed_providers ) ? $input['ai_provider'] : 'openai' );
        }
        // If ai_provider is not in input, keep the existing value from $sanitized (copied from $existing)
        // API Keys
        if ( isset( $input['openai_api_key'] ) ) {
            $sanitized['openai_api_key'] = sanitize_text_field( $input['openai_api_key'] );
        }
        // Gemini API Key - Only save for premium users
        if ( function_exists( 'afig_fs' ) && afig_fs()->is__premium_only() && isset( $input['gemini_api_key'] ) ) {
            $sanitized['gemini_api_key'] = sanitize_text_field( $input['gemini_api_key'] );
        }
        // Stability AI API Key
        if ( isset( $input['stability_api_key'] ) ) {
            $sanitized['stability_api_key'] = sanitize_text_field( $input['stability_api_key'] );
        }
        // Grok API Key
        if ( isset( $input['grok_api_key'] ) ) {
            $sanitized['grok_api_key'] = sanitize_text_field( $input['grok_api_key'] );
        }
        // Legacy support: if old 'api_key' field exists, migrate it to openai_api_key
        if ( isset( $input['api_key'] ) && !isset( $input['openai_api_key'] ) ) {
            $sanitized['openai_api_key'] = sanitize_text_field( $input['api_key'] );
        }
        if ( isset( $input['default_size'] ) ) {
            $all_sizes = array_keys( self::OPENAI_SIZES );
            $legacy_sizes = array_keys( self::OPENAI_LEGACY_SIZES );
            $requested = sanitize_text_field( $input['default_size'] );
            $model_for_size = $sanitized['ai_model'] ?? 'gpt-image-2';
            $is_legacy_model = in_array( $model_for_size, array('gpt-image-1', 'gpt-image-1-mini', 'gpt-image-1.5'), true );
            if ( $is_legacy_model ) {
                $sanitized['default_size'] = ( in_array( $requested, $legacy_sizes, true ) ? $requested : '1024x1024' );
            } else {
                $sanitized['default_size'] = ( in_array( $requested, $all_sizes, true ) ? $requested : '1024x1024' );
            }
        }
        if ( isset( $input['default_style'] ) ) {
            $style_val = sanitize_text_field( $input['default_style'] );
            $valid_builtin = array(
                'none',
                'realistic',
                'artistic',
                'cartoon',
                'sketch',
                'watercolor',
                '3d',
                'pixel',
                'cyberpunk',
                'fantasy',
                'anime',
                'minimalist',
                'technicolor'
            );
            $is_custom_style = (bool) preg_match( '/^custom_\\d+$/', $style_val );
            $sanitized['default_style'] = ( in_array( $style_val, $valid_builtin, true ) || $is_custom_style ? $style_val : 'realistic' );
        }
        // Only update allow_text when saving from Featured Image tab (checkbox only submits when checked)
        // Note: aifi_active_tab is a standalone hidden field, not part of the settings array
        $active_tab = ( isset( $_POST['aifi_active_tab'] ) ? sanitize_key( $_POST['aifi_active_tab'] ) : 'general' );
        if ( $active_tab === 'featured' ) {
            $sanitized['allow_text'] = ( !empty( $input['allow_text'] ) ? 1 : 0 );
        }
        // Alt Text settings (only update when saving from General tab)
        if ( $active_tab === 'general' ) {
            $sanitized['auto_alt_text'] = ( !empty( $input['auto_alt_text'] ) ? 1 : 0 );
            if ( isset( $input['alt_text_source'] ) ) {
                $allowed_sources = array('post_title', 'prompt', 'custom');
                $sanitized['alt_text_source'] = ( in_array( $input['alt_text_source'], $allowed_sources, true ) ? $input['alt_text_source'] : 'post_title' );
            }
            if ( isset( $input['alt_text_custom_format'] ) ) {
                $sanitized['alt_text_custom_format'] = sanitize_text_field( $input['alt_text_custom_format'] );
            }
            $sanitized['alt_text_overwrite'] = ( !empty( $input['alt_text_overwrite'] ) ? 1 : 0 );
        }
        if ( isset( $input['output_format'] ) ) {
            $allowed_formats = array('webp', 'png', 'jpeg');
            $sanitized['output_format'] = ( in_array( $input['output_format'], $allowed_formats ) ? $input['output_format'] : 'webp' );
        }
        if ( isset( $input['image_quality'] ) ) {
            $quality = intval( $input['image_quality'] );
            $sanitized['image_quality'] = max( 1, min( 100, $quality ) );
            // Ensure quality is between 1 and 100
        }
        // OpenAI generation quality (content tier: low / medium / high)
        if ( isset( $input['openai_quality'] ) ) {
            $allowed = array('high', 'medium', 'low');
            $sanitized['openai_quality'] = ( in_array( $input['openai_quality'], $allowed, true ) ? $input['openai_quality'] : 'high' );
        }
        // OpenAI background (gpt-image-2 only)
        if ( isset( $input['openai_background'] ) ) {
            $allowed = array('auto', 'transparent', 'opaque');
            $sanitized['openai_background'] = ( in_array( $input['openai_background'], $allowed, true ) ? $input['openai_background'] : 'auto' );
        }
        // OpenAI moderation (gpt-image-2 only)
        if ( isset( $input['openai_moderation'] ) ) {
            $allowed = array('auto', 'low');
            $sanitized['openai_moderation'] = ( in_array( $input['openai_moderation'], $allowed, true ) ? $input['openai_moderation'] : 'auto' );
        }
        // Gemini-specific settings - Only save for premium users
        if ( function_exists( 'afig_fs' ) && afig_fs()->is__premium_only() ) {
            if ( isset( $input['gemini_aspect_ratio'] ) ) {
                $allowed_ratios = array(
                    '1:1',
                    '2:3',
                    '3:2',
                    '3:4',
                    '4:3',
                    '4:5',
                    '5:4',
                    '9:16',
                    '16:9',
                    '21:9'
                );
                $sanitized['gemini_aspect_ratio'] = ( in_array( $input['gemini_aspect_ratio'], $allowed_ratios ) ? $input['gemini_aspect_ratio'] : '16:9' );
            }
            if ( isset( $input['gemini_image_size'] ) ) {
                $allowed_sizes = array('1K', '2K', '4K');
                $sanitized['gemini_image_size'] = ( in_array( $input['gemini_image_size'], $allowed_sizes ) ? $input['gemini_image_size'] : '1K' );
            }
        }
        // Stability AI settings
        if ( isset( $input['stability_aspect_ratio'] ) ) {
            $allowed_ratios = array(
                '1:1',
                '16:9',
                '21:9',
                '2:3',
                '3:2',
                '4:5',
                '5:4',
                '9:16',
                '9:21'
            );
            $sanitized['stability_aspect_ratio'] = ( in_array( $input['stability_aspect_ratio'], $allowed_ratios ) ? $input['stability_aspect_ratio'] : '16:9' );
        }
        if ( isset( $input['stability_style_preset'] ) ) {
            $allowed_presets = array(
                '',
                'photographic',
                'anime',
                'digital-art',
                'cinematic',
                'comic-book',
                'fantasy-art',
                '3d-model',
                'analog-film',
                'enhance',
                'isometric',
                'line-art',
                'low-poly',
                'neon-punk',
                'origami',
                'pixel-art',
                'tile-texture'
            );
            $sanitized['stability_style_preset'] = ( in_array( $input['stability_style_preset'], $allowed_presets ) ? $input['stability_style_preset'] : '' );
        }
        if ( function_exists( 'afig_fs' ) && afig_fs()->is__premium_only() ) {
            if ( isset( $input['stability_output_format'] ) ) {
                $allowed_formats = array('png', 'jpeg', 'webp');
                $sanitized['stability_output_format'] = ( in_array( $input['stability_output_format'], $allowed_formats ) ? $input['stability_output_format'] : 'png' );
            }
            if ( isset( $input['stability_negative_prompt'] ) ) {
                $sanitized['stability_negative_prompt'] = sanitize_textarea_field( $input['stability_negative_prompt'] );
            }
        }
        // Grok settings
        if ( isset( $input['grok_aspect_ratio'] ) ) {
            $grok_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
            $allowed_ratios = ( $grok_premium ? array(
                '1:1',
                '16:9',
                '9:16',
                '4:3',
                '3:4',
                '3:2',
                '2:3',
                '2:1',
                '1:2'
            ) : array('1:1', '16:9', '9:16') );
            $sanitized['grok_aspect_ratio'] = ( in_array( $input['grok_aspect_ratio'], $allowed_ratios ) ? $input['grok_aspect_ratio'] : '1:1' );
        }
        if ( isset( $input['grok_resolution'] ) ) {
            $grok_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
            $allowed_resolutions = ( $grok_premium ? array('1k', '2k') : array('1k') );
            $sanitized['grok_resolution'] = ( in_array( $input['grok_resolution'], $allowed_resolutions ) ? $input['grok_resolution'] : '1k' );
        }
        // AI Model - validate based on provider
        if ( isset( $input['ai_model'] ) ) {
            $provider = $sanitized['ai_provider'];
            $openai_models = array(
                'chatgpt-image-latest',
                'gpt-image-2',
                'gpt-image-1',
                'gpt-image-1-mini',
                'gpt-image-1.5'
            );
            $gemini_models = array('gemini-2.5-flash-image', 'gemini-3.1-flash-image-preview', 'gemini-3-pro-image-preview');
            $stability_models_valid = ( function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code() ? array(
                'ultra',
                'core',
                'sd3.5-large',
                'sd3.5-large-turbo',
                'sd3.5-medium',
                'sd3.5-flash',
                'sd3-large',
                'sd3-large-turbo',
                'sd3-medium',
                'sdxl-1.0'
            ) : array('core') );
            $grok_models_valid = ( function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code() ? array('grok-imagine-image', 'grok-imagine-image-pro') : array('grok-imagine-image') );
            if ( $provider === 'openai' ) {
                $sanitized['ai_model'] = ( in_array( $input['ai_model'], $openai_models ) ? $input['ai_model'] : 'gpt-image-2' );
            } elseif ( $provider === 'gemini' && function_exists( 'afig_fs' ) && afig_fs()->is__premium_only() ) {
                $sanitized['ai_model'] = ( in_array( $input['ai_model'], $gemini_models ) ? $input['ai_model'] : 'gemini-3.1-flash-image-preview' );
            } elseif ( $provider === 'stability' ) {
                $sanitized['ai_model'] = ( in_array( $input['ai_model'], $stability_models_valid ) ? $input['ai_model'] : 'core' );
            } elseif ( $provider === 'grok' ) {
                $sanitized['ai_model'] = ( in_array( $input['ai_model'], $grok_models_valid ) ? $input['ai_model'] : 'grok-imagine-image' );
            } else {
                $sanitized['ai_model'] = 'gpt-image-2';
            }
        }
        // Enabled Post Types - Pro only feature
        // Only update when saving from General tab (checkboxes only submit when checked)
        if ( function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code() && $active_tab === 'general' ) {
            if ( isset( $input['enabled_post_types'] ) && is_array( $input['enabled_post_types'] ) ) {
                // Get all valid public post types
                $valid_post_types = array_keys( get_post_types( array(
                    'public' => true,
                ), 'names' ) );
                // Filter and sanitize the input
                $sanitized['enabled_post_types'] = array_values( array_filter( array_map( 'sanitize_key', $input['enabled_post_types'] ), function ( $pt ) use($valid_post_types) {
                    return in_array( $pt, $valid_post_types, true );
                } ) );
                // Ensure at least one post type is selected
                if ( empty( $sanitized['enabled_post_types'] ) ) {
                    $sanitized['enabled_post_types'] = array('post', 'page');
                }
            } else {
                // If nothing is checked on General tab, default to post and page
                $sanitized['enabled_post_types'] = array('post', 'page');
            }
        }
        // If not on General tab, keep existing value from $sanitized (copied from $existing)
        // Inline Image settings (Pro only)
        if ( function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code() ) {
            if ( isset( $input['inline_default_style'] ) ) {
                $valid_styles = array(
                    'none',
                    'realistic',
                    'artistic',
                    'cartoon',
                    'sketch',
                    'watercolor',
                    '3d',
                    'pixel',
                    'cyberpunk',
                    'fantasy',
                    'anime',
                    'minimalist',
                    'technicolor'
                );
                $inline_style_val = sanitize_text_field( $input['inline_default_style'] );
                $is_inline_custom = (bool) preg_match( '/^custom_\\d+$/', $inline_style_val );
                $sanitized['inline_default_style'] = ( in_array( $inline_style_val, $valid_styles, true ) || $is_inline_custom ? $inline_style_val : 'realistic' );
            }
            if ( isset( $input['inline_default_size'] ) ) {
                $all_sizes = array_keys( self::OPENAI_SIZES );
                $legacy_sizes = array_keys( self::OPENAI_LEGACY_SIZES );
                $requested_inline = sanitize_text_field( $input['inline_default_size'] );
                $inline_model = $sanitized['ai_model'] ?? 'gpt-image-2';
                $is_legacy_inline = in_array( $inline_model, array('gpt-image-1', 'gpt-image-1-mini', 'gpt-image-1.5'), true );
                if ( $is_legacy_inline ) {
                    $sanitized['inline_default_size'] = ( in_array( $requested_inline, $legacy_sizes, true ) ? $requested_inline : '1024x1024' );
                } else {
                    $sanitized['inline_default_size'] = ( in_array( $requested_inline, $all_sizes, true ) ? $requested_inline : '1024x1024' );
                }
            }
            if ( isset( $input['inline_gemini_aspect_ratio'] ) ) {
                $valid_ratios = array(
                    '1:1',
                    '16:9',
                    '9:16',
                    '3:2',
                    '2:3',
                    '4:3',
                    '3:4',
                    '5:4',
                    '4:5',
                    '21:9'
                );
                $sanitized['inline_gemini_aspect_ratio'] = ( in_array( $input['inline_gemini_aspect_ratio'], $valid_ratios, true ) ? $input['inline_gemini_aspect_ratio'] : '16:9' );
            }
            if ( isset( $input['inline_stability_aspect_ratio'] ) ) {
                $valid_ratios = array(
                    '1:1',
                    '16:9',
                    '21:9',
                    '2:3',
                    '3:2',
                    '4:5',
                    '5:4',
                    '9:16',
                    '9:21'
                );
                $sanitized['inline_stability_aspect_ratio'] = ( in_array( $input['inline_stability_aspect_ratio'], $valid_ratios, true ) ? $input['inline_stability_aspect_ratio'] : '16:9' );
            }
            if ( isset( $input['inline_grok_aspect_ratio'] ) ) {
                $valid_ratios = array(
                    '1:1',
                    '16:9',
                    '9:16',
                    '4:3',
                    '3:4',
                    '3:2',
                    '2:3',
                    '2:1',
                    '1:2'
                );
                $sanitized['inline_grok_aspect_ratio'] = ( in_array( $input['inline_grok_aspect_ratio'], $valid_ratios, true ) ? $input['inline_grok_aspect_ratio'] : '1:1' );
            }
            if ( isset( $input['inline_output_format'] ) ) {
                $allowed_formats = array('webp', 'png', 'jpeg');
                $sanitized['inline_output_format'] = ( in_array( $input['inline_output_format'], $allowed_formats, true ) ? $input['inline_output_format'] : 'webp' );
            }
            if ( isset( $input['inline_stability_output_format'] ) ) {
                $allowed_formats = array('png', 'jpeg', 'webp');
                $sanitized['inline_stability_output_format'] = ( in_array( $input['inline_stability_output_format'], $allowed_formats, true ) ? $input['inline_stability_output_format'] : 'png' );
            }
            if ( isset( $input['inline_stability_negative_prompt'] ) ) {
                $sanitized['inline_stability_negative_prompt'] = sanitize_textarea_field( $input['inline_stability_negative_prompt'] );
            }
            // Custom Styles
            if ( $active_tab === 'featured' ) {
                $sanitized['custom_styles'] = array();
                if ( isset( $input['custom_styles'] ) && is_array( $input['custom_styles'] ) ) {
                    foreach ( $input['custom_styles'] as $cs ) {
                        $name = sanitize_text_field( $cs['name'] ?? '' );
                        $prompt = sanitize_text_field( $cs['prompt'] ?? '' );
                        if ( $name !== '' && $prompt !== '' ) {
                            $sanitized['custom_styles'][] = array(
                                'name'   => $name,
                                'prompt' => $prompt,
                            );
                        }
                    }
                }
            }
        }
        return $sanitized;
    }

    /**
     * Get plugin settings.
     *
     * @return array
     */
    public function get_settings() {
        if ( is_multisite() ) {
            $settings = get_network_option( null, $this->option );
        } else {
            $settings = get_option( $this->option );
        }
        if ( isset( $settings['auto_generate'] ) ) {
            unset($settings['auto_generate']);
        }
        // Legacy support: migrate old 'api_key' to 'openai_api_key'
        if ( isset( $settings['api_key'] ) && !isset( $settings['openai_api_key'] ) ) {
            $settings['openai_api_key'] = $settings['api_key'];
            unset($settings['api_key']);
        }
        // Ensure ai_provider is set - force OpenAI for non-premium users
        if ( !isset( $settings['ai_provider'] ) ) {
            $settings['ai_provider'] = 'openai';
        } elseif ( (!function_exists( 'afig_fs' ) || !afig_fs()->is__premium_only()) && $settings['ai_provider'] === 'gemini' ) {
            // Force OpenAI for non-premium users who somehow have Gemini selected
            $settings['ai_provider'] = 'openai';
            $settings['ai_model'] = 'gpt-image-2';
        }
        // Stability AI defaults
        if ( !isset( $settings['stability_aspect_ratio'] ) ) {
            $settings['stability_aspect_ratio'] = '16:9';
        }
        if ( !isset( $settings['stability_style_preset'] ) ) {
            $settings['stability_style_preset'] = '';
        }
        if ( !isset( $settings['stability_output_format'] ) ) {
            $settings['stability_output_format'] = 'png';
        }
        if ( !isset( $settings['stability_negative_prompt'] ) ) {
            $settings['stability_negative_prompt'] = '';
        }
        // Grok defaults
        if ( !isset( $settings['grok_aspect_ratio'] ) ) {
            $settings['grok_aspect_ratio'] = '1:1';
        }
        if ( !isset( $settings['grok_resolution'] ) ) {
            $settings['grok_resolution'] = '1k';
        }
        // OpenAI gpt-image-2 defaults
        if ( !isset( $settings['openai_quality'] ) ) {
            $settings['openai_quality'] = 'high';
        }
        if ( !isset( $settings['openai_background'] ) ) {
            $settings['openai_background'] = 'auto';
        }
        if ( !isset( $settings['openai_moderation'] ) ) {
            $settings['openai_moderation'] = 'auto';
        }
        // Gemini defaults
        if ( !isset( $settings['gemini_aspect_ratio'] ) ) {
            $settings['gemini_aspect_ratio'] = '16:9';
        }
        if ( !isset( $settings['gemini_image_size'] ) ) {
            $settings['gemini_image_size'] = '1K';
        }
        // Inline image defaults
        if ( !isset( $settings['inline_default_style'] ) ) {
            $settings['inline_default_style'] = ( isset( $settings['default_style'] ) ? $settings['default_style'] : 'realistic' );
        }
        if ( !isset( $settings['inline_default_size'] ) ) {
            $settings['inline_default_size'] = ( isset( $settings['default_size'] ) ? $settings['default_size'] : '1024x1024' );
        }
        if ( !isset( $settings['inline_gemini_aspect_ratio'] ) ) {
            $settings['inline_gemini_aspect_ratio'] = ( isset( $settings['gemini_aspect_ratio'] ) ? $settings['gemini_aspect_ratio'] : '16:9' );
        }
        if ( !isset( $settings['inline_stability_aspect_ratio'] ) ) {
            $settings['inline_stability_aspect_ratio'] = ( isset( $settings['stability_aspect_ratio'] ) ? $settings['stability_aspect_ratio'] : '16:9' );
        }
        if ( !isset( $settings['inline_grok_aspect_ratio'] ) ) {
            $settings['inline_grok_aspect_ratio'] = ( isset( $settings['grok_aspect_ratio'] ) ? $settings['grok_aspect_ratio'] : '1:1' );
        }
        if ( !isset( $settings['inline_output_format'] ) ) {
            $settings['inline_output_format'] = ( isset( $settings['output_format'] ) ? $settings['output_format'] : 'webp' );
        }
        if ( !isset( $settings['inline_stability_output_format'] ) ) {
            $settings['inline_stability_output_format'] = ( isset( $settings['stability_output_format'] ) ? $settings['stability_output_format'] : 'png' );
        }
        if ( !isset( $settings['inline_stability_negative_prompt'] ) ) {
            $settings['inline_stability_negative_prompt'] = ( isset( $settings['stability_negative_prompt'] ) ? $settings['stability_negative_prompt'] : '' );
        }
        // Alt text defaults
        if ( !isset( $settings['auto_alt_text'] ) ) {
            $settings['auto_alt_text'] = 1;
        }
        if ( !isset( $settings['alt_text_source'] ) ) {
            $settings['alt_text_source'] = 'post_title';
        }
        if ( !isset( $settings['alt_text_custom_format'] ) ) {
            $settings['alt_text_custom_format'] = '{title}';
        }
        if ( !isset( $settings['alt_text_overwrite'] ) ) {
            $settings['alt_text_overwrite'] = 0;
        }
        return ( is_array( $settings ) ? $settings : array() );
    }

    /**
     * Check if current user can use premium features.
     *
     * @return bool
     */
    public static function can_use_premium() {
        return function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
    }

    /**
     * Get enabled post types for the AI image generator.
     * 
     * Free version: Only 'post' and 'page'
     * Pro version: Custom selection from settings
     *
     * @return array List of enabled post type names.
     */
    public function get_enabled_post_types() {
        // Free version: only post and page
        if ( !function_exists( 'afig_fs' ) || !afig_fs()->can_use_premium_code() ) {
            return array('post', 'page');
        }
        // Pro version: get from settings
        $settings = $this->get_settings();
        if ( isset( $settings['enabled_post_types'] ) && is_array( $settings['enabled_post_types'] ) && !empty( $settings['enabled_post_types'] ) ) {
            return $settings['enabled_post_types'];
        }
        // Default to post and page if not set
        return array('post', 'page');
    }

}
