<?php
/**
 * AI Provider Settings UI - Unified Settings
 * Tích hợp quản lý API keys và provider selection trong một UI thống nhất
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp

if (!class_exists('AIAutotool_AI_Provider_Settings_UI')) {
    class AIAutotool_AI_Provider_Settings_UI extends rendersetting {
        
        private $active_option_name = 'aiautotool_ai_provider_active';
        private $execution_mode_option_name = 'aiautotool_ai_execution_mode';
        private $active = 'true';
        private $api_keys_manager;
        
        public function __construct() {
            $this->active = get_option($this->active_option_name, 'true');
            $this->api_keys_manager = AIAutotool_AI_Provider_API_Keys::get_instance();
            
            // Register settings
            add_action('admin_init', array($this, 'register_settings'));
            
            // AJAX handlers for API keys management
            add_action('wp_ajax_aiautotool_add_api_key', array($this, 'ajax_add_api_key'));
            add_action('wp_ajax_aiautotool_remove_api_key', array($this, 'ajax_remove_api_key'));
            add_action('wp_ajax_aiautotool_test_specific_key', array($this, 'ajax_test_specific_key'));
            add_action('wp_ajax_aiautotool_toggle_key_status', array($this, 'ajax_toggle_key_status'));
            
            // Existing AJAX handlers for provider settings
            add_action('wp_ajax_save_ai_provider_settings', array($this, 'ajax_save_provider_settings'));
            add_action('wp_ajax_test_ai_provider', array($this, 'ajax_test_provider'));
            
            add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        }
        
        /**
         * Register settings for multiple keys
         */
        public function register_settings() {
            register_setting('aiautotool_ai_provider_settings', 'aiautotool_openai_api_keys', array(
                'type' => 'array',
                'sanitize_callback' => array($this, 'sanitize_api_keys_setting'),
            ));
            register_setting('aiautotool_ai_provider_settings', 'aiautotool_gemini_api_keys', array(
                'type' => 'array',
                'sanitize_callback' => array($this, 'sanitize_api_keys_setting'),
            ));
            register_setting('aiautotool_ai_provider_settings', 'aiautotool_pollinations_api_keys', array(
                'type' => 'array',
                'sanitize_callback' => array($this, 'sanitize_api_keys_setting'),
            ));
            register_setting('aiautotool_ai_provider_settings', 'aiautotool_huggingface_api_keys', array(
                'type' => 'array',
                'sanitize_callback' => array($this, 'sanitize_api_keys_setting'),
            ));
            register_setting('aiautotool_ai_provider_settings', 'aiautotool_cloudflare_api_keys', array(
                'type' => 'array',
                'sanitize_callback' => array($this, 'sanitize_api_keys_setting'),
            ));
            register_setting('aiautotool_ai_provider_settings', 'aiautotool_llm7_api_keys', array(
                'type' => 'array',
                'sanitize_callback' => array($this, 'sanitize_api_keys_setting'),
            ));
            register_setting('aiautotool_ai_provider_settings', $this->execution_mode_option_name, array(
                'type' => 'string',
                'sanitize_callback' => array($this, 'sanitize_execution_mode'),
                'default' => 'agent',
            ));

            foreach ($this->get_openai_compatible_key_providers() as $provider_id => $provider) {
                register_setting('aiautotool_ai_provider_settings', 'aiautotool_' . $provider_id . '_api_keys', array(
                    'type' => 'array',
                    'sanitize_callback' => array($this, 'sanitize_api_keys_setting'),
                ));
            }

            foreach ($this->get_tts_key_providers() as $provider_id => $provider) {
                register_setting('aiautotool_ai_provider_settings', 'aiautotool_' . $provider_id . '_api_keys', array(
                    'type' => 'array',
                    'sanitize_callback' => array($this, 'sanitize_api_keys_setting'),
                ));
            }
        }

        public function sanitize_execution_mode($mode) {
            $mode = is_string($mode) ? sanitize_key($mode) : 'agent';
            return in_array($mode, array('agent', 'direct_api'), true) ? $mode : 'agent';
        }

        private function get_openai_compatible_key_providers() {
            return array(
                'openrouter' => array('icon' => 'fa-solid fa-route', 'title' => 'OpenRouter', 'url' => 'https://openrouter.ai/keys'),
                '9router' => array('icon' => 'fa-solid fa-route', 'title' => '9Router', 'url' => 'https://9router.com/'),
                'groq' => array('icon' => 'fa-solid fa-bolt', 'title' => 'Groq', 'url' => 'https://console.groq.com/keys'),
                'deepseek' => array('icon' => 'fa-solid fa-code', 'title' => 'DeepSeek', 'url' => 'https://platform.deepseek.com/api_keys'),
                'mistral' => array('icon' => 'fa-solid fa-wind', 'title' => 'Mistral AI', 'url' => 'https://console.mistral.ai/api-keys/'),
                'together' => array('icon' => 'fa-solid fa-layer-group', 'title' => 'Together AI', 'url' => 'https://api.together.xyz/settings/api-keys'),
                'fireworks' => array('icon' => 'fa-solid fa-fire', 'title' => 'Fireworks AI', 'url' => 'https://fireworks.ai/account/api-keys'),
                'perplexity' => array('icon' => 'fa-solid fa-magnifying-glass-chart', 'title' => 'Perplexity', 'url' => 'https://www.perplexity.ai/settings/api'),
                'xai' => array('icon' => 'fa-solid fa-xmark', 'title' => 'xAI', 'url' => 'https://console.x.ai/'),
                'ollama' => array('icon' => 'fa-solid fa-laptop-code', 'title' => 'Ollama Local', 'url' => 'https://ollama.com/'),
                'glm_coding' => array('icon' => 'fa-solid fa-code', 'title' => 'GLM Coding', 'url' => 'https://open.bigmodel.cn/'),
                'glm_china' => array('icon' => 'fa-solid fa-z', 'title' => 'GLM China', 'url' => 'https://open.bigmodel.cn/'),
                'kimi' => array('icon' => 'fa-solid fa-moon', 'title' => 'Kimi', 'url' => 'https://platform.moonshot.cn/console/api-keys'),
                'minimax_coding' => array('icon' => 'fa-solid fa-wave-square', 'title' => 'Minimax Coding', 'url' => 'https://platform.minimaxi.com/user-center/basic-information/interface-key'),
                'minimax_china' => array('icon' => 'fa-solid fa-wave-square', 'title' => 'Minimax China', 'url' => 'https://platform.minimaxi.com/user-center/basic-information/interface-key'),
                'alibaba' => array('icon' => 'fa-solid fa-cubes', 'title' => 'Alibaba', 'url' => 'https://dashscope.console.aliyun.com/apiKey'),
                'alibaba_intl' => array('icon' => 'fa-solid fa-globe', 'title' => 'Alibaba Intl', 'url' => 'https://dashscope.console.aliyun.com/apiKey'),
                'volcengine_ark' => array('icon' => 'fa-solid fa-mountain-sun', 'title' => 'Volcengine Ark', 'url' => 'https://console.volcengine.com/ark/'),
                'byteplus_modelark' => array('icon' => 'fa-solid fa-mountain', 'title' => 'BytePlus ModelArk', 'url' => 'https://console.byteplus.com/ark/'),
                'cerebras' => array('icon' => 'fa-solid fa-server', 'title' => 'Cerebras', 'url' => 'https://cloud.cerebras.ai/'),
                'cohere' => array('icon' => 'fa-solid fa-circle-nodes', 'title' => 'Cohere', 'url' => 'https://dashboard.cohere.com/api-keys'),
                'nebius' => array('icon' => 'fa-solid fa-n', 'title' => 'Nebius AI', 'url' => 'https://studio.nebius.com/'),
                'siliconflow' => array('icon' => 'fa-solid fa-water', 'title' => 'SiliconFlow', 'url' => 'https://cloud.siliconflow.cn/account/ak'),
                'hyperbolic' => array('icon' => 'fa-solid fa-arrows-spin', 'title' => 'Hyperbolic', 'url' => 'https://app.hyperbolic.xyz/settings'),
                'chutes' => array('icon' => 'fa-solid fa-paper-plane', 'title' => 'Chutes AI', 'url' => 'https://chutes.ai/app/api'),
                'nvidia_nim' => array('icon' => 'fa-solid fa-microchip', 'title' => 'NVIDIA NIM', 'url' => 'https://build.nvidia.com/'),
                'anthropic' => array('icon' => 'fa-solid fa-comment-dots', 'title' => 'Anthropic Claude', 'url' => 'https://console.anthropic.com/settings/keys'),
                'azure_openai' => array('icon' => 'fa-brands fa-microsoft', 'title' => 'Azure OpenAI', 'url' => 'https://portal.azure.com/'),
            );
        }

        private function get_tts_key_providers() {
            return array(
                'elevenlabs' => array('icon' => 'fa-solid fa-wave-square', 'title' => 'ElevenLabs TTS', 'url' => 'https://elevenlabs.io/app/settings/api-keys', 'type' => 'tts'),
                'google_tts' => array('icon' => 'fa-brands fa-google', 'title' => 'Google TTS', 'url' => 'https://console.cloud.google.com/apis/credentials', 'type' => 'tts', 'planned' => true),
                'azure_speech' => array('icon' => 'fa-brands fa-microsoft', 'title' => 'Azure Speech', 'url' => 'https://portal.azure.com/', 'type' => 'tts', 'planned' => true),
                'amazon_polly' => array('icon' => 'fa-brands fa-aws', 'title' => 'Amazon Polly', 'url' => 'https://aws.amazon.com/polly/', 'type' => 'tts', 'planned' => true),
                'minimax_tts' => array('icon' => 'fa-solid fa-wave-square', 'title' => 'Minimax TTS', 'url' => 'https://platform.minimaxi.com/', 'type' => 'tts', 'planned' => true),
                'fish_audio' => array('icon' => 'fa-solid fa-fish', 'title' => 'Fish Audio', 'url' => 'https://fish.audio/', 'type' => 'tts', 'planned' => true),
                'playht' => array('icon' => 'fa-solid fa-play', 'title' => 'PlayHT', 'url' => 'https://play.ht/', 'type' => 'tts', 'planned' => true),
                'cartesia' => array('icon' => 'fa-solid fa-c', 'title' => 'Cartesia', 'url' => 'https://cartesia.ai/', 'type' => 'tts', 'planned' => true),
                'edge_tts' => array('icon' => 'fa-brands fa-edge', 'title' => 'Edge TTS', 'url' => 'https://github.com/rany2/edge-tts', 'type' => 'tts', 'planned' => true),
                'kokoro' => array('icon' => 'fa-solid fa-volume-high', 'title' => 'Kokoro', 'url' => 'https://github.com/hexgrad/kokoro', 'type' => 'tts', 'planned' => true),
                'xtts_self_hosted' => array('icon' => 'fa-solid fa-server', 'title' => 'XTTS Self Hosted', 'url' => 'https://github.com/coqui-ai/TTS', 'type' => 'tts', 'planned' => true),
            );
        }

        private function get_provider_cost_group($provider_id) {
            $free_or_local = array('pollinations', 'llm7', 'ollama', '9router');
            $free_tier = array('gemini', 'huggingface', 'cloudflare', 'jina', 'openrouter', 'groq', 'nvidia_nim', 'cerebras', 'siliconflow', 'chutes');

            if (in_array($provider_id, $free_or_local, true) || in_array($provider_id, $free_tier, true)) {
                return 'free';
            }

            return 'paid';
        }

        private function get_provider_cost_label($provider_id) {
            $free_or_local = array('pollinations', 'llm7', 'ollama', '9router');

            if (in_array($provider_id, $free_or_local, true)) {
                return __('Free / Local', 'ai-auto-tool');
            }

            if ($this->get_provider_cost_group($provider_id) === 'free') {
                return __('Free tier + Paid', 'ai-auto-tool');
            }

            return __('Paid', 'ai-auto-tool');
        }

        private function group_providers_by_cost($providers_info) {
            $groups = array(
                'free' => array(),
                'paid' => array(),
            );

            foreach ($providers_info as $id => $info) {
                $group = $this->get_provider_cost_group($id);
                $groups[$group][$id] = $info;
            }

            return $groups;
        }

        private function get_provider_capabilities($info) {
            return (isset($info['capabilities']) && is_array($info['capabilities'])) ? $info['capabilities'] : array('text_generation');
        }

        private function group_providers_by_capability($providers_info) {
            $groups = array(
                'text_generation' => array(),
                'image_generation' => array(),
            );

            foreach ($providers_info as $id => $info) {
                $capabilities = $this->get_provider_capabilities($info);

                if (in_array('image_generation', $capabilities, true)) {
                    $groups['image_generation'][$id] = $info;
                } else {
                    $groups['text_generation'][$id] = $info;
                }
            }

            return $groups;
        }

        private function get_provider_capability_label($capability) {
            $labels = array(
                'text_generation' => __('AI Text Generation', 'ai-auto-tool'),
                'image_generation' => __('AI Image Generation', 'ai-auto-tool'),
            );

            return isset($labels[$capability]) ? $labels[$capability] : ucwords(str_replace('_', ' ', $capability));
        }

        private function render_provider_capability_groups($providers_info, $active_provider_id) {
            $groups = $this->group_providers_by_capability($providers_info);
            $group_meta = array(
                'text_generation' => array(
                    'icon' => 'fa-solid fa-pen-nib',
                    'description' => __('Use these providers for writing, rewriting, chat, SEO, and text workflows.', 'ai-auto-tool'),
                    'border' => '#bfdbfe',
                    'background' => '#eff6ff',
                    'accent' => '#1d4ed8',
                ),
                'image_generation' => array(
                    'icon' => 'fa-solid fa-image',
                    'description' => __('Use these providers for AI image generation, thumbnails, and image prompt workflows.', 'ai-auto-tool'),
                    'border' => '#fed7aa',
                    'background' => '#fff7ed',
                    'accent' => '#c2410c',
                ),
            );
            ?>
            <div class="aiautotool-provider-capability-groups" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 14px; margin: 20px 0 26px;">
                <?php foreach ($groups as $capability => $providers): ?>
                    <?php $meta = isset($group_meta[$capability]) ? $group_meta[$capability] : $group_meta['text_generation']; ?>
                    <div style="border: 1px solid <?php echo esc_attr($meta['border']); ?>; background: <?php echo esc_attr($meta['background']); ?>; border-radius: 8px; padding: 16px;">
                        <h4 style="margin: 0 0 6px; color: <?php echo esc_attr($meta['accent']); ?>; display: flex; align-items: center; gap: 8px; font-size: 16px;">
                            <i class="<?php echo esc_attr($meta['icon']); ?>"></i>
                            <?php echo esc_html($this->get_provider_capability_label($capability)); ?>
                        </h4>
                        <p class="description" style="margin: 0 0 12px;"><?php echo esc_html($meta['description']); ?></p>

                        <?php if (empty($providers)): ?>
                            <span style="color: #666;"><?php esc_html_e('No providers in this category yet.', 'ai-auto-tool'); ?></span>
                        <?php else: ?>
                            <div style="display: flex; flex-wrap: wrap; gap: 8px;">
                                <?php foreach ($providers as $id => $info): ?>
                                    <?php
                                    $is_active = ($active_provider_id === $id);
                                    $is_configured = !empty($info['configured']);
                                    $border_color = $is_active ? '#22c55e' : '#e5e7eb';
                                    ?>
                                    <span style="display: inline-flex; align-items: center; gap: 6px; padding: 6px 10px; border-radius: 999px; background: #fff; border: 1px solid <?php echo esc_attr($border_color); ?>; color: <?php echo $is_configured ? '#111827' : '#6b7280'; ?>; font-size: 13px;">
                                        <strong><?php echo esc_html($info['name']); ?></strong>
                                        <?php if ($is_active): ?>
                                            <span style="color: #16a34a;"><?php esc_html_e('Active', 'ai-auto-tool'); ?></span>
                                        <?php elseif ($is_configured): ?>
                                            <span style="color: #16a34a;">✓</span>
                                        <?php else: ?>
                                            <span style="color: #dc2626;"><?php esc_html_e('Not Configured', 'ai-auto-tool'); ?></span>
                                        <?php endif; ?>
                                    </span>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>
            <?php
        }

        private function get_provider_best_for($provider_id) {
            $labels = array(
                'openai' => __('General writing and reliable structured output', 'ai-auto-tool'),
                'gemini' => __('Fast responses and long-context content', 'ai-auto-tool'),
                'pollinations' => __('Free startup usage and model fallback', 'ai-auto-tool'),
                'llm7' => __('Free gateway fallback', 'ai-auto-tool'),
                'huggingface' => __('Open models and experimental workloads', 'ai-auto-tool'),
                'cloudflare' => __('Workers AI and Cloudflare-hosted sites', 'ai-auto-tool'),
                'jina' => __('Search, reader, and content fetching', 'ai-auto-tool'),
                'openrouter' => __('Many commercial models from one API key', 'ai-auto-tool'),
                '9router' => __('Local/OpenAI-compatible model router and provider gateway', 'ai-auto-tool'),
                'groq' => __('Very fast content generation', 'ai-auto-tool'),
                'deepseek' => __('Reasoning, coding, and low-cost generation', 'ai-auto-tool'),
                'mistral' => __('Multilingual writing and EU provider preference', 'ai-auto-tool'),
                'together' => __('Open model selection and high-throughput tasks', 'ai-auto-tool'),
                'fireworks' => __('Open model inference and coding models', 'ai-auto-tool'),
                'perplexity' => __('Search-grounded answers and research content', 'ai-auto-tool'),
                'xai' => __('Grok models and alternative commercial routing', 'ai-auto-tool'),
                'ollama' => __('Local/private model testing', 'ai-auto-tool'),
                'glm_coding' => __('GLM coding and reasoning models', 'ai-auto-tool'),
                'glm_china' => __('GLM China-hosted models', 'ai-auto-tool'),
                'kimi' => __('Kimi long-context writing and research', 'ai-auto-tool'),
                'minimax_coding' => __('Minimax coding and agent workloads', 'ai-auto-tool'),
                'minimax_china' => __('Minimax China-hosted models', 'ai-auto-tool'),
                'alibaba' => __('Qwen/DashScope commercial models', 'ai-auto-tool'),
                'alibaba_intl' => __('Qwen/DashScope international routing', 'ai-auto-tool'),
                'volcengine_ark' => __('Doubao and Ark model routing', 'ai-auto-tool'),
                'byteplus_modelark' => __('BytePlus ModelArk international routing', 'ai-auto-tool'),
                'cerebras' => __('Fast hosted open models', 'ai-auto-tool'),
                'cohere' => __('Command models for business writing', 'ai-auto-tool'),
                'nebius' => __('Hosted open models and GPU inference', 'ai-auto-tool'),
                'siliconflow' => __('China-accessible open model routing', 'ai-auto-tool'),
                'hyperbolic' => __('Open model inference and fallback routing', 'ai-auto-tool'),
                'chutes' => __('Community hosted open models', 'ai-auto-tool'),
                'nvidia_nim' => __('NVIDIA hosted model endpoints', 'ai-auto-tool'),
                'anthropic' => __('Claude writing, analysis, and agent tasks', 'ai-auto-tool'),
                'azure_openai' => __('Enterprise Azure deployments', 'ai-auto-tool'),
            );

            return isset($labels[$provider_id]) ? $labels[$provider_id] : __('General AI generation', 'ai-auto-tool');
        }
        
        /**
         * Sanitize API keys setting
         * 
         * @param mixed $value Input value
         * @return array Sanitized array
         */
        public function sanitize_api_keys_setting($value) {
            if (!is_array($value)) {
                return array();
            }
            return map_deep($value, 'sanitize_text_field');
        }
        
        /**
         * Enqueue scripts and styles
         */
        public function enqueue_scripts($hook) {
            if ($hook !== 'toplevel_page_ai_auto_tool') {
                return;
            }
            
            // Use AIAUTOTOOL_URI constant for reliable path resolution
            if (defined('AIAUTOTOOL_URI')) {
                $plugin_url = AIAUTOTOOL_URI;
            } else {
                $plugin_url = plugin_dir_url(dirname(dirname(__FILE__)));
            }
            
            // Enqueue common tabs CSS & JS
            wp_enqueue_style(
                'aiautotool-tabs-common-css',
                $plugin_url . 'css/tabs-common.css',
                array(),
                defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0.0'
            );
            
            wp_enqueue_script(
                'aiautotool-tabs-common-js',
                $plugin_url . 'js/tabs-common.js',
                array('jquery'),
                defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0.0',
                true
            );
            
            // Enqueue API Manager CSS (from ai-providers/assets/css/)
            $api_manager_css_path = plugin_dir_path(__FILE__) . 'assets/css/api-manager.css';
            
            if (file_exists($api_manager_css_path)) {
                wp_enqueue_style(
                    'aiautotool-api-manager-css',
                    plugins_url('assets/css/api-manager.css', __FILE__),
                    array('aiautotool-tabs-common-css'),
                    defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0.0'
                );
            }
            
            // Enqueue API Manager JS (from ai-providers/assets/js/)
            $api_manager_js_path = plugin_dir_path(__FILE__) . 'assets/js/api-manager.js';
            
            if (file_exists($api_manager_js_path)) {
                wp_enqueue_script(
                    'aiautotool-api-manager-js',
                    plugins_url('assets/js/api-manager.js', __FILE__),
                    array('jquery', 'aiautotool-tabs-common-js'),
                    defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0.0',
                    true
                );
            }
            
            // Only localize if script exists (to prevent errors)
            if (wp_script_is('aiautotool-api-manager-js', 'enqueued')) {
                wp_localize_script('aiautotool-api-manager-js', 'aiautotool_api_manager', array(
                    'ajax_url' => admin_url('admin-ajax.php'),
                    'nonce' => wp_create_nonce('aiautotool_api_manager_nonce'),
                    'strings' => array(
                        'testing' => __('Testing connection...', 'ai-auto-tool'),
                        'success' => __('Success!', 'ai-auto-tool'),
                        'error' => __('Error!', 'ai-auto-tool'),
                    )
                ));
            }
        }
        
        /**
         * Render tab button
         */
        public function render_tab_setting() {
            echo '<button href="#tab-ai-provider" class="nav-tab sotab"><i class="fa-solid fa-brain"></i> ' . esc_html__('AI Provider', 'ai-auto-tool') . '</button>';
        }
        
        /**
         * Render unified settings page
         */
        public function render_setting() {
            $manager = AIAutotool_AI_Provider_Manager::get_instance();
            $providers_info = $manager->get_providers_info();
            $active_provider = $manager->get_active_provider();
            $active_provider_id = $active_provider ? $active_provider->get_id() : '';
            $active_model = $manager->get_active_model();
            $routing_mode = method_exists($manager, 'get_provider_routing_mode') ? $manager->get_provider_routing_mode() : 'single';
            
            // Get keys count for each provider
            $openai_keys = $this->api_keys_manager->get_all_keys('openai');
            $gemini_keys = $this->api_keys_manager->get_all_keys('gemini');
            $llm7_keys = $this->api_keys_manager->get_all_keys('llm7');
            $pollinations_keys = $this->api_keys_manager->get_all_keys('pollinations');
            $huggingface_keys = $this->api_keys_manager->get_all_keys('huggingface');
            $jina_keys = $this->api_keys_manager->get_all_keys('jina');
            
            $openai_active = $this->api_keys_manager->get_active_keys('openai');
            $gemini_active = $this->api_keys_manager->get_active_keys('gemini');
            $llm7_active = $this->api_keys_manager->get_active_keys('llm7');
            $pollinations_active = $this->api_keys_manager->get_active_keys('pollinations');
            $huggingface_active = $this->api_keys_manager->get_active_keys('huggingface');
            $cloudflare_active = $this->api_keys_manager->get_active_keys('cloudflare');
            $jina_active = $this->api_keys_manager->get_active_keys('jina');
            $openai_compatible_key_providers = $this->get_openai_compatible_key_providers();
            $tts_key_providers = $this->get_tts_key_providers();
            $additional_key_providers = array_merge($openai_compatible_key_providers, $tts_key_providers);
            
            ?>
            <div id="tab-ai-provider" class="tab-content sotab-box ftbox" style="display:none; width: 100%; box-sizing: border-box;">
                <h2><i class="fa-solid fa-brain"></i> <?php esc_html_e('AI Provider Settings', 'ai-auto-tool'); ?></h2>
                
                <div class="aiautotool-tabs-nav aiautotool-provider-nav">
                    <button class="aiautotool-tab-btn active" data-tab="provider-selection-section">
                        <i class="fa-solid fa-sliders"></i>
                        <span><?php esc_html_e('AI Provider', 'ai-auto-tool'); ?></span>
                    </button>
                    <button class="aiautotool-tab-btn" data-tab="keys-openai">
                        <i class="fa-brands fa-openai"></i>
                        <span><?php esc_html_e('OpenAI', 'ai-auto-tool'); ?></span>
                        <?php if (count($openai_active) > 0): ?>
                            <span class="aiautotool-tab-badge"><?php echo count($openai_active); ?></span>
                        <?php endif; ?>
                    </button>
                    <button class="aiautotool-tab-btn" data-tab="keys-gemini">
                        <i class="fa-brands fa-google"></i>
                        <span><?php esc_html_e('Gemini', 'ai-auto-tool'); ?></span>
                        <?php if (count($gemini_active) > 0): ?>
                            <span class="aiautotool-tab-badge"><?php echo count($gemini_active); ?></span>
                        <?php endif; ?>
                    </button>
                    <button class="aiautotool-tab-btn" data-tab="keys-llm7">
                        <i class="fa-solid fa-robot"></i>
                        <span><?php esc_html_e('LLM7.io', 'ai-auto-tool'); ?></span>
                        <?php if (count($llm7_active) > 0): ?>
                            <span class="aiautotool-tab-badge"><?php echo count($llm7_active); ?></span>
                        <?php endif; ?>
                    </button>
                    <button class="aiautotool-tab-btn" data-tab="keys-pollinations">
                        <i class="fa-solid fa-brain"></i>
                        <span><?php esc_html_e('Pollinations.ai', 'ai-auto-tool'); ?></span>
                        <?php if (count($pollinations_active) > 0): ?>
                            <span class="aiautotool-tab-badge"><?php echo count($pollinations_active); ?></span>
                        <?php endif; ?>
                    </button>
                    <button class="aiautotool-tab-btn" data-tab="keys-huggingface">
                        <i class="fa-solid fa-robot"></i>
                        <span><?php esc_html_e('HuggingFace', 'ai-auto-tool'); ?></span>
                        <?php if (count($huggingface_active) > 0): ?>
                            <span class="aiautotool-tab-badge"><?php echo count($huggingface_active); ?></span>
                        <?php endif; ?>
                    </button>
                    <button class="aiautotool-tab-btn" data-tab="keys-cloudflare">
                        <i class="fa-solid fa-cloud"></i>
                        <span><?php esc_html_e('Cloudflare', 'ai-auto-tool'); ?></span>
                        <?php if (count($cloudflare_active) > 0): ?>
                            <span class="aiautotool-tab-badge"><?php echo count($cloudflare_active); ?></span>
                        <?php endif; ?>
                    </button>
                    <button class="aiautotool-tab-btn" data-tab="keys-jina">
                        <i class="fa-solid fa-search"></i>
                        <span><?php esc_html_e('Jina AI', 'ai-auto-tool'); ?></span>
                        <?php if (count($jina_active) > 0): ?>
                            <span class="aiautotool-tab-badge"><?php echo count($jina_active); ?></span>
                        <?php endif; ?>
                    </button>
                    <?php foreach ($additional_key_providers as $provider_id => $provider): 
                        $active_keys = $this->api_keys_manager->get_active_keys($provider_id);
                        ?>
                        <button class="aiautotool-tab-btn" data-tab="keys-<?php echo esc_attr($provider_id); ?>">
                            <i class="<?php echo esc_attr($provider['icon']); ?>"></i>
                            <span><?php echo esc_html($provider['title']); ?></span>
                            <?php if (count($active_keys) > 0): ?>
                                <span class="aiautotool-tab-badge"><?php echo count($active_keys); ?></span>
                            <?php endif; ?>
                        </button>
                    <?php endforeach; ?>
                </div>
                
                <!-- AI Provider Selection Tab (First Tab) -->
                <div id="provider-selection-section" class="aiautotool-tab-content active" style="display: block;">
                    <?php $this->render_provider_selection($providers_info, $active_provider_id, $active_model, $active_provider, $routing_mode); ?>
                </div>
                
                <!-- OpenAI Keys Tab (Second Tab) -->
                <div id="keys-openai" class="aiautotool-tab-content" style="display: none;">
                    <?php $this->render_keys_manager('openai', 'fa-brands fa-openai', 'OpenAI', 'https://platform.openai.com/api-keys'); ?>
                </div>
                
                <!-- Gemini Keys Tab (Third Tab) -->
                <div id="keys-gemini" class="aiautotool-tab-content" style="display: none;">
                    <?php $this->render_keys_manager('gemini', 'fa-brands fa-google', 'Gemini', 'https://makersuite.google.com/app/apikey'); ?>
                </div>
                
                <!-- LLM7.io Keys Tab -->
                <div id="keys-llm7" class="aiautotool-tab-content" style="display: none;">
                    <div style="margin-bottom: 15px; padding: 12px; background: #e7f3ff; border-left: 4px solid #2196F3; border-radius: 4px;">
                        <i class="fa-solid fa-info-circle" style="color: #2196F3;"></i>
                        <strong><?php esc_html_e('LLM7.io AI Gateway:', 'ai-auto-tool'); ?></strong>
                        <?php esc_html_e('Access to multiple AI models through a unified API. Get your API key from LLM7.io dashboard.', 'ai-auto-tool'); ?>
                    </div>
                    
                    <?php $this->render_keys_manager('llm7', 'fa-solid fa-robot', 'LLM7.io', 'https://llm7.io/'); ?>
                    
                    <!-- Available Models -->
                    <div style="margin-top: 15px; padding: 15px; background: #f0f9ff; border-left: 4px solid #0ea5e9; border-radius: 4px;">
                        <p style="margin: 0 0 10px;"><strong><i class="fa-solid fa-server"></i> <?php esc_html_e('Available Models:', 'ai-auto-tool'); ?></strong></p>
                        <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 8px; font-size: 13px;">
                            <div>• <strong>default</strong> - AgentRouter auto-select (Recommended)</div>
                            <div>• <strong>fast</strong> - Quick responses</div>
                            <div>• <strong>pro</strong> - Best quality</div>
                        </div>
                        <p style="margin: 10px 0 0; font-size: 12px; color: #666;">
                            <i class="fa-solid fa-info-circle"></i> 
                            <?php esc_html_e('The AgentRouter automatically selects the best model for your request.', 'ai-auto-tool'); ?>
                        </p>
                    </div>
                </div>
                
                <!-- Pollinations.ai Keys Tab (Fourth Tab) -->
                <div id="keys-pollinations" class="aiautotool-tab-content" style="display: none;">
                    <div style="margin-bottom: 15px; padding: 12px; background: #fff3cd; border-left: 4px solid #ffc107; border-radius: 4px;">
                        <i class="fa-solid fa-star" style="color: #ffc107;"></i>
                        <strong><?php esc_html_e('Pollinations.ai Free AI Models:', 'ai-auto-tool'); ?></strong>
                        <?php esc_html_e('Compatible with OpenAI API. Use "unused" for free tier or get a custom key for higher rate limits.', 'ai-auto-tool'); ?>
                    </div>
                    
                    <?php $this->render_keys_manager('pollinations', 'fa-solid fa-brain', 'Pollinations.ai', 'https://enter.pollinations.ai/'); ?>
                    
                    <!-- Available Models -->
                    <div style="margin-top: 15px; padding: 15px; background: #e7f3ff; border-left: 4px solid #2271b1; border-radius: 4px;">
                        <p style="margin: 0 0 10px;"><strong><i class="fa-solid fa-server"></i> <?php esc_html_e('Available Models:', 'ai-auto-tool'); ?></strong></p>
                        <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 8px; font-size: 13px;">
                            <div>• deepseek-v3.1</div>
                            <div>• gemini-2.5-flash-lite</div>
                            <div>• mistral-small-3.1-24b-instruct</div>
                            <div>• gpt-5-mini, gpt-5-nano</div>
                            <div>• codestral-2405, codestral-2501</div>
                            <div>• qwen2.5-coder-32b-instruct</div>
                        </div>
                    </div>
                </div>
                
                <!-- HuggingFace Keys Tab (Fifth Tab) -->
                <div id="keys-huggingface" class="aiautotool-tab-content" style="display: none;">
                    <?php $this->render_keys_manager('huggingface', 'fa-solid fa-robot', 'HuggingFace', 'https://huggingface.co/settings/tokens'); ?>
                </div>
                
                <!-- Cloudflare Keys Tab (Sixth Tab) -->
                <div id="keys-cloudflare" class="aiautotool-tab-content" style="display: none;">
                    <div style="margin-bottom: 15px; padding: 12px; background: #f0f9ff; border-left: 4px solid #f97316; border-radius: 4px;">
                        <i class="fa-solid fa-info-circle" style="color: #f97316;"></i>
                        <strong><?php esc_html_e('Cloudflare AI Workers:', 'ai-auto-tool'); ?></strong>
                        <?php esc_html_e('Enter credentials in format: account_id|api_token', 'ai-auto-tool'); ?>
                    </div>
                    <?php $this->render_keys_manager('cloudflare', 'fa-solid fa-cloud', 'Cloudflare', 'https://dash.cloudflare.com/profile/api-tokens'); ?>
                </div>
                
                <!-- Jina AI Keys Tab (Seventh Tab) -->
                <div id="keys-jina" class="aiautotool-tab-content" style="display: none;">
                    <div style="margin-bottom: 15px; padding: 12px; background: #e7f3ff; border-left: 4px solid #2271b1; border-radius: 4px;">
                        <i class="fa-solid fa-info-circle" style="color: #2271b1;"></i>
                        <strong><?php esc_html_e('Jina AI Search & Reader:', 'ai-auto-tool'); ?></strong>
                        <?php esc_html_e('Used for Google Search fallback and content fetching. Get your API key from Jina AI.', 'ai-auto-tool'); ?>
                    </div>
                    
                    <?php $this->render_keys_manager('jina', 'fa-solid fa-search', 'Jina AI', 'https://jina.ai/'); ?>
                    
                    <!-- Jina AI Features -->
                    <div style="margin-top: 15px; padding: 15px; background: #f0f9ff; border-left: 4px solid #0ea5e9; border-radius: 4px;">
                        <p style="margin: 0 0 10px;"><strong><i class="fa-solid fa-list"></i> <?php esc_html_e('Jina AI Features:', 'ai-auto-tool'); ?></strong></p>
                        <ul style="margin: 0; padding-left: 20px; font-size: 13px;">
                            <li><?php esc_html_e('Search API: Fallback when Google Search is blocked', 'ai-auto-tool'); ?></li>
                            <li><?php esc_html_e('Reader API: Fetch and parse content from URLs', 'ai-auto-tool'); ?></li>
                            <li><?php esc_html_e('Supports multiple formats: Markdown, Plain Text, JSON', 'ai-auto-tool'); ?></li>
                        </ul>
                    </div>
                </div>
                
                <?php foreach ($additional_key_providers as $provider_id => $provider): ?>
                    <div id="keys-<?php echo esc_attr($provider_id); ?>" class="aiautotool-tab-content" style="display: none;">
                        <div style="margin-bottom: 15px; padding: 12px; background: #eef6ff; border-left: 4px solid #2271b1; border-radius: 4px;">
                            <i class="fa-solid fa-circle-info" style="color: #2271b1;"></i>
                            <strong><?php echo esc_html($provider['title']); ?>:</strong>
                            <?php if (!empty($provider['type']) && $provider['type'] === 'tts'): ?>
                                <?php if (!empty($provider['planned'])): ?>
                                    <?php esc_html_e('Voice provider planned for the next implementation phase. API key storage is prepared, but generation is not enabled yet.', 'ai-auto-tool'); ?>
                                <?php else: ?>
                                    <?php esc_html_e('AI voice/TTS provider. Add API key to generate MP3 narration from posts.', 'ai-auto-tool'); ?>
                                <?php endif; ?>
                            <?php elseif ($provider_id === 'anthropic'): ?>
                                <?php esc_html_e('Claude Messages API provider. Add one or more API keys for round-robin rotation.', 'ai-auto-tool'); ?>
                            <?php elseif ($provider_id === 'azure_openai'): ?>
                                <?php esc_html_e('Enter credentials in format: endpoint|deployment|api_key.', 'ai-auto-tool'); ?>
                            <?php elseif ($provider_id === '9router'): ?>
                                <?php esc_html_e('OpenAI-compatible router. Default endpoint: https://api9.aiautotool.com/v1. Use "unused" for no-auth mode, an API key for the default endpoint, endpoint only for a no-auth custom router, or endpoint|api_key for a secured custom router.', 'ai-auto-tool'); ?>
                            <?php else: ?>
                                <?php esc_html_e('OpenAI-compatible Chat Completions provider. Add one or more API keys for round-robin rotation.', 'ai-auto-tool'); ?>
                            <?php endif; ?>
                            <?php if ($provider_id === 'ollama'): ?>
                                <?php esc_html_e(' Use "ollama" as the key value for local testing.', 'ai-auto-tool'); ?>
                            <?php endif; ?>
                        </div>
                        <?php $this->render_keys_manager($provider_id, $provider['icon'], $provider['title'], $provider['url']); ?>
                    </div>
                <?php endforeach; ?>
            </div>
            
            <?php
        }
        
        /**
         * Render provider selection UI
         */
        private function render_provider_selection($providers_info, $active_provider_id, $active_model, $active_provider, $routing_mode = 'single') {
            $provider_groups = $this->group_providers_by_cost($providers_info);
            $execution_mode = $this->sanitize_execution_mode(get_option($this->execution_mode_option_name, 'agent'));
            $voice_config = array(
                'provider' => get_option('aiautotool_tts_provider', 'openai'),
                'model' => get_option('aiautotool_tts_model', 'tts-1'),
                'voice' => get_option('aiautotool_tts_voice', 'alloy'),
                'auto_publish' => get_option('aiautotool_tts_auto_generate_on_publish', '0'),
            );
            $voice_provider_choices = array();
            if (class_exists('AIAutotool_AI_Voice_Manager')) {
                $voice_provider_choices = AIAutotool_AI_Voice_Manager::get_instance()->get_supported_providers();
            } else {
                $voice_manager_file = dirname(__FILE__) . '/aiautotool_ai_voice_manager.php';
                if (file_exists($voice_manager_file)) {
                    require_once $voice_manager_file;
                    if (class_exists('AIAutotool_AI_Voice_Manager')) {
                        $voice_provider_choices = AIAutotool_AI_Voice_Manager::get_instance()->get_supported_providers();
                    }
                }
            }
            ?>
            <h3><i class="fa-solid fa-sliders"></i> <?php esc_html_e('Provider & Model Selection', 'ai-auto-tool'); ?></h3>
            <p class="description">
                <?php esc_html_e('Choose which AI provider and model to use across the entire plugin. This ensures consistent AI responses throughout all features.', 'ai-auto-tool'); ?>
            </p>

            <?php $this->render_provider_capability_groups($providers_info, $active_provider_id); ?>
            
            <table class="form-table">
                <tr>
                    <th scope="row">
                        <?php esc_html_e('Provider Routing', 'ai-auto-tool'); ?>
                    </th>
                    <td>
                        <fieldset class="aiautotool-provider-routing">
                            <label>
                                <input type="radio" name="aiautotool_ai_provider_routing_mode" value="single" <?php checked($routing_mode, 'single'); ?>>
                                <strong><?php esc_html_e('Use selected provider', 'ai-auto-tool'); ?></strong>
                                <span><?php esc_html_e('Always use the provider and model selected below.', 'ai-auto-tool'); ?></span>
                            </label>
                            <label>
                                <input type="radio" name="aiautotool_ai_provider_routing_mode" value="rotate" <?php checked($routing_mode, 'rotate'); ?>>
                                <strong><?php esc_html_e('Rotate available providers', 'ai-auto-tool'); ?></strong>
                                <span><?php esc_html_e('Round-robin across configured providers with active API keys. Each provider still rotates its own keys.', 'ai-auto-tool'); ?></span>
                            </label>
                        </fieldset>
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <?php esc_html_e('Execution Mode', 'ai-auto-tool'); ?>
                    </th>
                    <td>
                        <fieldset class="aiautotool-provider-routing">
                            <label>
                                <input type="radio" name="aiautotool_ai_execution_mode" value="agent" <?php checked($execution_mode, 'agent'); ?>>
                                <strong><?php esc_html_e('Agent workflow', 'ai-auto-tool'); ?></strong>
                                <span><?php esc_html_e('Use the AI Auto Tool agent for planning, provider fallback, verification, and tool/action execution when the workflow needs it.', 'ai-auto-tool'); ?></span>
                            </label>
                            <label>
                                <input type="radio" name="aiautotool_ai_execution_mode" value="direct_api" <?php checked($execution_mode, 'direct_api'); ?>>
                                <strong><?php esc_html_e('Direct provider API', 'ai-auto-tool'); ?></strong>
                                <span><?php esc_html_e('Send generation requests straight to the selected provider/model without the agent planning and tool layer.', 'ai-auto-tool'); ?></span>
                            </label>
                        </fieldset>
                        <p class="description">
                            <?php esc_html_e('Agent mode can call registered tools such as writing posts, creating images, reading posts, searching posts, listing terms, and replying to comments during agent execution.', 'ai-auto-tool'); ?>
                        </p>
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <?php esc_html_e('AI Provider', 'ai-auto-tool'); ?>
                    </th>
                    <td>
                        <select id="aiautotool_ai_provider" name="aiautotool_ai_provider" class="regular-text" style="min-width: 300px;">
                            <option value=""><?php esc_html_e('-- Select Provider --', 'ai-auto-tool'); ?></option>
                            <?php if (!empty($provider_groups['free'])): ?>
                                <optgroup label="<?php esc_attr_e('Free / Free tier / Local providers', 'ai-auto-tool'); ?>">
                                    <?php foreach ($provider_groups['free'] as $id => $info): ?>
                                        <option value="<?php echo esc_attr($id); ?>" 
                                                <?php selected($active_provider_id, $id); ?>
                                                <?php echo $info['configured'] ? '' : 'disabled'; ?>>
                                            <?php echo esc_html($info['name']); ?> - <?php echo esc_html($this->get_provider_cost_label($id)); ?>
                                            <?php if (!$info['configured']): ?>
                                                (<?php esc_html_e('Not Configured', 'ai-auto-tool'); ?>)
                                            <?php else: ?>
                                                ✓
                                            <?php endif; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </optgroup>
                            <?php endif; ?>
                            <?php if (!empty($provider_groups['paid'])): ?>
                                <optgroup label="<?php esc_attr_e('Paid providers', 'ai-auto-tool'); ?>">
                                    <?php foreach ($provider_groups['paid'] as $id => $info): ?>
                                        <option value="<?php echo esc_attr($id); ?>" 
                                                <?php selected($active_provider_id, $id); ?>
                                                <?php echo $info['configured'] ? '' : 'disabled'; ?>>
                                            <?php echo esc_html($info['name']); ?> - <?php echo esc_html($this->get_provider_cost_label($id)); ?>
                                            <?php if (!$info['configured']): ?>
                                                (<?php esc_html_e('Not Configured', 'ai-auto-tool'); ?>)
                                            <?php else: ?>
                                                ✓
                                            <?php endif; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </optgroup>
                            <?php endif; ?>
                        </select>
                        
                        <button type="button" id="test_ai_provider" class="button button-secondary" style="margin-left: 10px;">
                            🔌 <?php esc_html_e('Test Model', 'ai-auto-tool'); ?>
                        </button>
                        
                        <p class="description">
                            <?php esc_html_e('Only configured providers can be selected. Add API keys from the provider tabs above, then return here to choose the active provider and model.', 'ai-auto-tool'); ?>
                        </p>
                        
                        <div id="provider_status" style="margin-top: 10px;">
                            <?php if ($active_provider): ?>
                                <span style="color: green;">
                                    ✓ <?php echo sprintf(esc_html__('Active: %s', 'ai-auto-tool'), esc_html($active_provider->get_name())); ?>
                                </span>
                            <?php else: ?>
                                <span style="color: orange;">
                                    ⚠️ <?php esc_html_e('No active provider. Please select and configure one.', 'ai-auto-tool'); ?>
                                </span>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Test Results Container -->
                        <div id="test_results_container" style="margin-top: 15px; display: none;">
                            <div class="test-results-box" style="padding: 15px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px;">
                                <h4 style="margin-top: 0; margin-bottom: 10px;">
                                    <i class="fa-solid fa-vial"></i> <?php esc_html_e('Test Results', 'ai-auto-tool'); ?>
                                </h4>
                                <div id="test_results_content"></div>
                            </div>
                        </div>
                    </td>
                </tr>
                
                <tr>
                    <th scope="row">
                        <?php esc_html_e('AI Model', 'ai-auto-tool'); ?>
                    </th>
                    <td>
                        <select id="aiautotool_ai_model" name="aiautotool_ai_model" class="regular-text" style="min-width: 300px;">
                            <option value=""><?php esc_html_e('-- Select Model --', 'ai-auto-tool'); ?></option>
                        </select>
                        
                        <p class="description" id="model_description">
                            <?php esc_html_e('Select the AI model to use. Different models have different capabilities and speeds.', 'ai-auto-tool'); ?>
                        </p>
                        
                        <div id="model_recommendations" style="margin-top: 10px; padding: 10px; background: #f0f8ff; border-left: 3px solid #2196F3; display: none;">
                            <p style="margin: 0; font-size: 13px;"></p>
                        </div>
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <?php esc_html_e('AI Voice Studio', 'ai-auto-tool'); ?>
                    </th>
                    <td>
                        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px;max-width:860px;">
                            <label>
                                <strong><?php esc_html_e('TTS Provider', 'ai-auto-tool'); ?></strong>
                                <select id="aiautotool_tts_provider" class="regular-text" style="width:100%;margin-top:6px;">
                                    <option value="openai" <?php selected($voice_config['provider'], 'openai'); ?>>OpenAI TTS</option>
                                    <option value="elevenlabs" <?php selected($voice_config['provider'], 'elevenlabs'); ?>>ElevenLabs</option>
                                </select>
                            </label>
                            <label>
                                <strong><?php esc_html_e('TTS Model', 'ai-auto-tool'); ?></strong>
                                <select id="aiautotool_tts_model" class="regular-text" style="width:100%;margin-top:6px;">
                                    <option value="<?php echo esc_attr($voice_config['model']); ?>"><?php echo esc_html($voice_config['model']); ?></option>
                                </select>
                            </label>
                            <label>
                                <strong><?php esc_html_e('Voice ID', 'ai-auto-tool'); ?></strong>
                                <select id="aiautotool_tts_voice" class="regular-text" style="width:100%;margin-top:6px;">
                                    <option value="<?php echo esc_attr($voice_config['voice']); ?>"><?php echo esc_html($voice_config['voice']); ?></option>
                                </select>
                            </label>
                        </div>
                        <label style="display:inline-flex;align-items:center;gap:8px;margin-top:12px;">
                            <input type="checkbox" id="aiautotool_tts_auto_publish" value="1" <?php checked($voice_config['auto_publish'], '1'); ?>>
                            <span><?php esc_html_e('Automatically generate MP3 when a post is published', 'ai-auto-tool'); ?></span>
                        </label>
                        <p class="description">
                            <?php esc_html_e('OpenAI uses the existing OpenAI API key. ElevenLabs uses its own ElevenLabs TTS API key tab. MP3 files are saved to wp-content/uploads/aitool/audio/.', 'ai-auto-tool'); ?>
                        </p>
                    </td>
                </tr>
            </table>
            
            <p class="submit">
                <button type="button" id="save_ai_provider_settings" class="button button-primary">
                    💾 <?php esc_html_e('Save AI Provider Settings', 'ai-auto-tool'); ?>
                </button>
                <span class="spinner" style="float: none; margin: 0 10px;"></span>
                <span class="save-message-provider"></span>
            </p>
            
            <div class="aiautotool-provider-groups">
                <?php
                $provider_group_labels = array(
                    'free' => array(
                        'icon' => 'fa-solid fa-seedling',
                        'title' => __('Free / Free tier / Local', 'ai-auto-tool'),
                        'description' => __('Providers that offer free models, a free tier, or local runtime. Good for testing and low-volume workflows.', 'ai-auto-tool'),
                    ),
                    'paid' => array(
                        'icon' => 'fa-solid fa-credit-card',
                        'title' => __('Paid providers', 'ai-auto-tool'),
                        'description' => __('Providers that normally require billing, prepaid credits, or an enterprise deployment.', 'ai-auto-tool'),
                    ),
                );
                ?>
                <?php foreach ($provider_group_labels as $group_key => $group_label): ?>
                    <?php if (empty($provider_groups[$group_key])) continue; ?>
                    <section class="aiautotool-provider-group aiautotool-provider-group-<?php echo esc_attr($group_key); ?>">
                        <div class="aiautotool-provider-group-header">
                            <div>
                                <h4>
                                    <i class="<?php echo esc_attr($group_label['icon']); ?>"></i>
                                    <?php echo esc_html($group_label['title']); ?>
                                </h4>
                                <p><?php echo esc_html($group_label['description']); ?></p>
                            </div>
                            <span class="aiautotool-provider-group-count">
                                <?php echo esc_html(sprintf(_n('%d provider', '%d providers', count($provider_groups[$group_key]), 'ai-auto-tool'), count($provider_groups[$group_key]))); ?>
                            </span>
                        </div>
                        <div class="aiautotool-provider-catalog">
                            <?php foreach ($provider_groups[$group_key] as $id => $info): ?>
                                <div class="aiautotool-provider-card <?php echo $info['configured'] ? 'is-configured' : 'is-not-configured'; ?>">
                                    <div class="aiautotool-provider-card-main">
                                        <strong><?php echo esc_html($info['name']); ?></strong>
                                        <span class="aiautotool-provider-status">
                                            <?php echo $info['configured'] ? esc_html__('Configured', 'ai-auto-tool') : esc_html__('Not Configured', 'ai-auto-tool'); ?>
                                        </span>
                                    </div>
                                    <div class="aiautotool-provider-meta">
                                        <span><?php echo esc_html(sprintf(_n('%d model', '%d models', count($info['models']), 'ai-auto-tool'), count($info['models']))); ?></span>
                                        <span><?php echo esc_html($this->get_provider_cost_label($id)); ?></span>
                                    </div>
                                    <div class="aiautotool-provider-best-for">
                                        <?php echo esc_html($this->get_provider_best_for($id)); ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </section>
                <?php endforeach; ?>
            </div>
            
            <script>
            jQuery(document).ready(function($) {
                // Handle tab switching for AI Provider Settings
                function initAIProviderTabs() {
                    // Initialize: show first tab, hide others
                    var $firstTab = $('#tab-ai-provider .aiautotool-tab-btn.active');
                    if ($firstTab.length) {
                        var firstTabId = $firstTab.data('tab');
                        if (firstTabId) {
                            $('#tab-ai-provider .aiautotool-tab-content').removeClass('active').hide();
                            $('#' + firstTabId).addClass('active').show();
                        }
                    }
                }
                
                // Initialize tabs when page loads
                initAIProviderTabs();
                
                // Re-initialize when AI Provider tab becomes visible
                $('.nav-tab[href="#tab-ai-provider"]').on('click', function() {
                    setTimeout(function() {
                        initAIProviderTabs();
                        // Re-initialize API keys manager if available
                        if (typeof APIKeysManager !== 'undefined') {
                            APIKeysManager.init();
                        }
                    }, 100);
                });
                
                // Handle tab button clicks
                $(document).on('click', '#tab-ai-provider .aiautotool-tab-btn', function(e) {
                    e.preventDefault();
                    var $btn = $(this);
                    var tabId = $btn.data('tab');
                    
                    if (!tabId) return;
                    
                    // Update buttons
                    $('#tab-ai-provider .aiautotool-tab-btn').removeClass('active');
                    $btn.addClass('active');
                    
                    // Update content
                    $('#tab-ai-provider .aiautotool-tab-content').removeClass('active').hide();
                    $('#' + tabId).addClass('active').show();
                });
                
                // Initialize API Keys Manager when tab is visible
                $(document).on('aiautotool:tabChanged', function(e, containerId, tabId) {
                    if (containerId === 'tab-ai-provider') {
                        setTimeout(function() {
                            if (typeof APIKeysManager !== 'undefined') {
                                APIKeysManager.init();
                            }
                        }, 50);
                    }
                });
                
                var providersData = <?php echo json_encode($providers_info); ?>;
                var currentProvider = '<?php echo esc_js($active_provider_id); ?>';
                var currentModel = '<?php echo esc_js($active_model); ?>';
                var currentRoutingMode = '<?php echo esc_js($routing_mode); ?>';
                var voiceProvidersData = <?php echo wp_json_encode($voice_provider_choices); ?>;
                var currentTtsProvider = '<?php echo esc_js($voice_config['provider']); ?>';
                var currentTtsModel = '<?php echo esc_js($voice_config['model']); ?>';
                var currentTtsVoice = '<?php echo esc_js($voice_config['voice']); ?>';
                
                var modelRecommendations = {
                    'openai': '💡 GPT-4o-mini is recommended for most tasks - fast and cost-effective.',
                    'gemini': '💡 Gemini 1.5 Flash is recommended for speed. Use Pro for complex tasks.',
                    'pollinations': '💡 DeepSeek v3.1 is recommended for reasoning tasks. Use Codestral for coding.'
                };
                
                function updateModelsDropdown(providerId) {
                    var $modelSelect = $('#aiautotool_ai_model');
                    $modelSelect.html('<option value="">-- Select Model --</option>');
                    
                    if (!providerId || !providersData[providerId]) {
                        return;
                    }
                    
                    var provider = providersData[providerId];
                    var models = provider.models;
                    
                    // Determine which model should be selected
                    // Priority: currentModel (if it exists in this provider) > provider default
                    var selectedModel = null;
                    if (currentModel && models[currentModel]) {
                        selectedModel = currentModel;
                    } else if (provider.default_model) {
                        selectedModel = provider.default_model;
                    }
                    
                    $.each(models, function(modelId, modelName) {
                        var isSelected = (modelId === selectedModel);
                        $modelSelect.append(
                            $('<option></option>')
                                .val(modelId)
                                .text(modelName)
                                .prop('selected', isSelected)
                        );
                    });
                    
                    // Update currentModel to the selected model
                    if (selectedModel) {
                        currentModel = selectedModel;
                    }
                    
                    if (modelRecommendations[providerId]) {
                        $('#model_recommendations p').text(modelRecommendations[providerId]);
                        $('#model_recommendations').show();
                    } else {
                        $('#model_recommendations').hide();
                    }
                }
                
                if (currentProvider) {
                    updateModelsDropdown(currentProvider);
                }

                function updateTtsDropdowns(providerId) {
                    var provider = voiceProvidersData[providerId] || {};
                    var models = provider.models || {};
                    var voices = provider.voices || {};
                    var defaultModel = provider.default_model || '';
                    var defaultVoice = provider.default_voice || '';
                    var $modelSelect = $('#aiautotool_tts_model');
                    var $voiceSelect = $('#aiautotool_tts_voice');

                    $modelSelect.empty();
                    $voiceSelect.empty();

                    var selectedModel = models[currentTtsModel] ? currentTtsModel : defaultModel;
                    var selectedVoice = voices[currentTtsVoice] ? currentTtsVoice : defaultVoice;

                    if ($.isEmptyObject(models)) {
                        $modelSelect.append($('<option></option>').val('').text('<?php echo esc_js(__('No model choices available', 'ai-auto-tool')); ?>'));
                    } else {
                        $.each(models, function(modelId, modelName) {
                            $modelSelect.append(
                                $('<option></option>')
                                    .val(modelId)
                                    .text(modelName + ' (' + modelId + ')')
                                    .prop('selected', modelId === selectedModel)
                            );
                        });
                    }

                    if ($.isEmptyObject(voices)) {
                        $voiceSelect.append($('<option></option>').val('').text('<?php echo esc_js(__('No voice choices available', 'ai-auto-tool')); ?>'));
                    } else {
                        $.each(voices, function(voiceId, voiceName) {
                            $voiceSelect.append(
                                $('<option></option>')
                                    .val(voiceId)
                                    .text(voiceName + ' (' + voiceId + ')')
                                    .prop('selected', voiceId === selectedVoice)
                            );
                        });
                    }

                    currentTtsModel = $modelSelect.val() || selectedModel || '';
                    currentTtsVoice = $voiceSelect.val() || selectedVoice || '';
                }

                updateTtsDropdowns(currentTtsProvider || 'openai');

                $('#aiautotool_tts_provider').on('change', function() {
                    currentTtsProvider = $(this).val() || 'openai';
                    currentTtsModel = '';
                    currentTtsVoice = '';
                    updateTtsDropdowns(currentTtsProvider);
                });

                $('#aiautotool_tts_model').on('change', function() {
                    currentTtsModel = $(this).val() || '';
                });

                $('#aiautotool_tts_voice').on('change', function() {
                    currentTtsVoice = $(this).val() || '';
                });

                function updateRoutingModeUi() {
                    currentRoutingMode = $('input[name="aiautotool_ai_provider_routing_mode"]:checked').val() || 'single';
                    var isRotate = currentRoutingMode === 'rotate';
                    $('#aiautotool_ai_provider, #aiautotool_ai_model').prop('disabled', false);
                    if (isRotate) {
                        $('#model_description').text('<?php echo esc_js(__('Rotate mode uses each provider default model, except the selected provider keeps the selected model.', 'ai-auto-tool')); ?>');
                    } else {
                        $('#model_description').text('<?php echo esc_js(__('Select the AI model to use. Different models have different capabilities and speeds.', 'ai-auto-tool')); ?>');
                    }
                }

                updateRoutingModeUi();

                $('input[name="aiautotool_ai_provider_routing_mode"]').on('change', updateRoutingModeUi);
                
                $('#aiautotool_ai_provider').on('change', function() {
                    var providerId = $(this).val();
                    updateModelsDropdown(providerId);
                    currentProvider = providerId;
                    // Update currentModel when provider changes
                    currentModel = $('#aiautotool_ai_model').val();
                });
                
                // Update currentModel when user manually selects a model
                $('#aiautotool_ai_model').on('change', function() {
                    currentModel = $(this).val();
                });
                
                $('#save_ai_provider_settings').on('click', function() {
                    var $button = $(this);
                    var $spinner = $button.next('.spinner');
                    var $message = $('.save-message-provider');
                    
                    var providerId = $('#aiautotool_ai_provider').val();
                    var model = $('#aiautotool_ai_model').val();
                    var routingMode = $('input[name="aiautotool_ai_provider_routing_mode"]:checked').val() || 'single';
                    var executionMode = $('input[name="aiautotool_ai_execution_mode"]:checked').val() || 'agent';
                    var ttsProvider = $('#aiautotool_tts_provider').val() || 'openai';
                    var ttsModel = $('#aiautotool_tts_model').val() || '';
                    var ttsVoice = $('#aiautotool_tts_voice').val() || '';
                    var ttsAutoPublish = $('#aiautotool_tts_auto_publish').is(':checked') ? '1' : '0';
                    
                    if (routingMode === 'single' && !providerId) {
                        alert('Please select a provider');
                        return;
                    }
                    
                    // If no model is selected, use the provider's default
                    if (!model && providersData[providerId] && providersData[providerId].default_model) {
                        model = providersData[providerId].default_model;
                    }
                    
                    $button.prop('disabled', true);
                    $spinner.addClass('is-active');
                    $message.html('');
                    
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'save_ai_provider_settings',
                            nonce: '<?php echo wp_create_nonce('ai_provider_settings'); ?>',
                            provider_id: providerId,
                            model: model,
                            routing_mode: routingMode,
                            execution_mode: executionMode,
                            tts_provider: ttsProvider,
                            tts_model: ttsModel,
                            tts_voice: ttsVoice,
                            tts_auto_publish: ttsAutoPublish
                        },
                        success: function(response) {
                            $spinner.removeClass('is-active');
                            $button.prop('disabled', false);
                            
                            if (response.success) {
                                $message.html('<span style="color: green;">✓ ' + response.data.message + '</span>');
                                if (routingMode === 'rotate') {
                                    $('#provider_status').html('<span style="color: green;">✓ Active routing: Rotate available providers</span>');
                                } else {
                                    var providerName = providersData[providerId].name;
                                    $('#provider_status').html('<span style="color: green;">✓ Active: ' + providerName + '</span>');
                                }
                                // Update currentModel to the saved model
                                if (response.data.model) {
                                    currentModel = response.data.model;
                                }
                            } else {
                                $message.html('<span style="color: red;">✗ ' + response.data.message + '</span>');
                            }
                            
                            setTimeout(function() { $message.html(''); }, 5000);
                        },
                        error: function() {
                            $spinner.removeClass('is-active');
                            $button.prop('disabled', false);
                            $message.html('<span style="color: red;">✗ Error saving settings</span>');
                        }
                    });
                });
                
                $('#test_ai_provider').on('click', function() {
                    var $button = $(this);
                    var $resultsContainer = $('#test_results_container');
                    var $resultsContent = $('#test_results_content');
                    var providerId = $('#aiautotool_ai_provider').val();
                    
                    if (!providerId) {
                        alert('<?php esc_html_e('Please select a provider first', 'ai-auto-tool'); ?>');
                        return;
                    }
                    
                    $button.prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin"></i> <?php esc_html_e('Testing...', 'ai-auto-tool'); ?>');
                    $resultsContainer.hide();
                    $resultsContent.html('<p><i class="fa-solid fa-spinner fa-spin"></i> <?php esc_html_e('Đang kiểm tra model...', 'ai-auto-tool'); ?></p>');
                    
                    var selectedModel = $('#aiautotool_ai_model').val();
                    
                    // Store values for use in callbacks
                    var testProviderId = providerId;
                    
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'test_ai_provider',
                            nonce: '<?php echo wp_create_nonce('ai_provider_settings'); ?>',
                            provider_id: providerId,
                            model: selectedModel || ''
                        },
                        success: function(response) {
                            $button.prop('disabled', false).html('🔌 <?php esc_html_e('Test Model', 'ai-auto-tool'); ?>');
                            
                            if (response.success) {
                                var data = response.data || {};
                                
                                // Debug: log data to console for troubleshooting
                                console.log('Test result data:', data);
                                console.log('Provider ID:', testProviderId);
                                
                                var html = '<div style="color: green; margin-bottom: 15px;">';
                                html += '<strong><i class="fa-solid fa-check-circle"></i> <?php esc_html_e('Test thành công!', 'ai-auto-tool'); ?></strong>';
                                html += '</div>';
                                
                                // Model Information - Always show, even if some values are missing
                                html += '<div style="margin-bottom: 15px; padding: 10px; background: #e7f3ff; border-left: 3px solid #2196F3; border-radius: 3px;">';
                                html += '<strong><i class="fa-solid fa-info-circle"></i> <?php esc_html_e('Thông tin Model:', 'ai-auto-tool'); ?></strong><br>';
                                html += '<span style="font-size: 13px;">';
                                
                                // Provider name - use data first, fallback to providerId
                                var providerName = (data.provider_name && data.provider_name !== '') 
                                    ? data.provider_name 
                                    : (testProviderId ? testProviderId.charAt(0).toUpperCase() + testProviderId.slice(1) : '<?php esc_html_e('Unknown', 'ai-auto-tool'); ?>');
                                html += '<strong><?php esc_html_e('Provider:', 'ai-auto-tool'); ?></strong> ' + providerName + '<br>';
                                
                                // Model ID
                                var modelId = (data.model_id && data.model_id !== '') 
                                    ? data.model_id 
                                    : '<?php esc_html_e('Not specified', 'ai-auto-tool'); ?>';
                                html += '<strong><?php esc_html_e('Model ID:', 'ai-auto-tool'); ?></strong> <code>' + modelId + '</code><br>';
                                
                                // Model Name
                                var modelName = (data.model_name && data.model_name !== '') 
                                    ? data.model_name 
                                    : (modelId !== '<?php esc_html_e('Not specified', 'ai-auto-tool'); ?>' ? modelId : '<?php esc_html_e('Not specified', 'ai-auto-tool'); ?>');
                                html += '<strong><?php esc_html_e('Model Name:', 'ai-auto-tool'); ?></strong> ' + modelName + '<br>';
                                
                                // Response Model (if different from requested)
                                if (data.response_model && data.response_model !== data.model_id) {
                                    html += '<strong><?php esc_html_e('Response Model:', 'ai-auto-tool'); ?></strong> <code>' + data.response_model + '</code><br>';
                                }
                                
                                // Test Time
                                if (data.test_time) {
                                    html += '<strong><?php esc_html_e('Test Time:', 'ai-auto-tool'); ?></strong> ' + data.test_time + '<br>';
                                }
                                
                                html += '</span>';
                                html += '</div>';
                                
                                // Usage Information
                                if (data.usage) {
                                    html += '<div style="margin-bottom: 15px; padding: 10px; background: #fff3cd; border-left: 3px solid #ffc107; border-radius: 3px; font-size: 13px;">';
                                    html += '<strong><i class="fa-solid fa-chart-bar"></i> <?php esc_html_e('Token Usage:', 'ai-auto-tool'); ?></strong><br>';
                                    if (data.usage.prompt_tokens) {
                                        html += '<?php esc_html_e('Prompt:', 'ai-auto-tool'); ?> ' + data.usage.prompt_tokens + ' tokens<br>';
                                    }
                                    if (data.usage.completion_tokens) {
                                        html += '<?php esc_html_e('Completion:', 'ai-auto-tool'); ?> ' + data.usage.completion_tokens + ' tokens<br>';
                                    }
                                    if (data.usage.total_tokens) {
                                        html += '<strong><?php esc_html_e('Total:', 'ai-auto-tool'); ?> ' + data.usage.total_tokens + ' tokens</strong>';
                                    }
                                    html += '</div>';
                                }
                                
                                // Model Response - Always show if test is successful
                                html += '<div style="margin-bottom: 10px;">';
                                html += '<strong><i class="fa-solid fa-comment-dots"></i> <?php esc_html_e('Response từ Model:', 'ai-auto-tool'); ?></strong>';
                                html += '<div style="margin-top: 10px; padding: 12px; background: white; border: 1px solid #ddd; border-radius: 4px; max-height: 300px; overflow-y: auto; font-size: 14px; line-height: 1.6;">';
                                if (data.response && data.response !== '') {
                                    html += '<pre style="white-space: pre-wrap; word-wrap: break-word; margin: 0; font-family: inherit;">' + $('<div>').text(data.response).html() + '</pre>';
                                } else {
                                    html += '<p style="color: #999; font-style: italic; margin: 0;"><?php esc_html_e('Không có response từ model. Model có thể đã test thành công nhưng không trả về nội dung.', 'ai-auto-tool'); ?></p>';
                                }
                                html += '</div>';
                                html += '</div>';
                                
                                $resultsContent.html(html);
                                $resultsContainer.slideDown();
                            } else {
                                var data = response.data || {};
                                var html = '<div style="color: red; margin-bottom: 15px;">';
                                html += '<strong><i class="fa-solid fa-times-circle"></i> <?php esc_html_e('Test thất bại!', 'ai-auto-tool'); ?></strong>';
                                html += '</div>';
                                
                                if (data.provider_name || data.model_id) {
                                    html += '<div style="margin-bottom: 15px; padding: 10px; background: #f8d7da; border-left: 3px solid #dc3545; border-radius: 3px; font-size: 13px;">';
                                    html += '<strong><i class="fa-solid fa-exclamation-triangle"></i> <?php esc_html_e('Thông tin:', 'ai-auto-tool'); ?></strong><br>';
                                    if (data.provider_name) {
                                        html += '<strong><?php esc_html_e('Provider:', 'ai-auto-tool'); ?></strong> ' + data.provider_name + '<br>';
                                    }
                                    if (data.model_id) {
                                        html += '<strong><?php esc_html_e('Model ID:', 'ai-auto-tool'); ?></strong> <code>' + data.model_id + '</code><br>';
                                    }
                                    if (data.error) {
                                        html += '<strong><?php esc_html_e('Error:', 'ai-auto-tool'); ?></strong> ' + data.error;
                                    }
                                    html += '</div>';
                                }
                                
                                if (data.message) {
                                    html += '<div style="padding: 10px; background: #fff3cd; border-left: 3px solid #ffc107; border-radius: 3px; font-size: 13px;">';
                                    html += data.message;
                                    html += '</div>';
                                }
                                
                                $resultsContent.html(html);
                                $resultsContainer.slideDown();
                            }
                        },
                        error: function(xhr, status, error) {
                            $button.prop('disabled', false).html('🔌 <?php esc_html_e('Test Model', 'ai-auto-tool'); ?>');
                            
                            var html = '<div style="color: red;">';
                            html += '<strong><i class="fa-solid fa-times-circle"></i> <?php esc_html_e('Lỗi kết nối:', 'ai-auto-tool'); ?></strong><br>';
                            html += '<span style="font-size: 13px;"><?php esc_html_e('Không thể kết nối đến server. Vui lòng thử lại.', 'ai-auto-tool'); ?></span>';
                            html += '</div>';
                            
                            $resultsContent.html(html);
                            $resultsContainer.slideDown();
                        }
                    });
                });
            });
            </script>
            
            <style>
            .aiautotool-ai-provider-settings select {
                font-size: 14px;
            }
            .aiautotool-ai-provider-settings .wp-list-table th {
                font-weight: 600;
            }
            </style>
            <?php
        }
        
        /**
         * Render keys manager for a provider
         */
        private function render_keys_manager($provider, $icon, $title, $get_key_url) {
            $keys = $this->api_keys_manager->get_all_keys($provider);
            $active_keys = $this->api_keys_manager->get_active_keys($provider);
            
            ?>
            <div class="api-keys-manager">
                <div class="rotation-info">
                    <p>
                        <i class="fa-solid fa-rotate"></i>
                        <strong><?php esc_html_e('Round-Robin Rotation:', 'ai-auto-tool'); ?></strong>
                        <?php 
                        printf(
                            esc_html__('You have %d active key(s) out of %d total. The system will automatically rotate between active keys to distribute load and avoid rate limits.', 'ai-auto-tool'),
                            count($active_keys),
                            count($keys)
                        );
                        ?>
                    </p>
                </div>
                
                <!-- Add New Key Form -->
                <div class="add-key-form" data-provider="<?php echo esc_attr($provider); ?>">
                    <h4><i class="fa-solid fa-plus-circle"></i> <?php esc_html_e('Add New API Key', 'ai-auto-tool'); ?></h4>
                    <div class="form-row">
                        <div class="form-group" style="flex: 2;">
                            <label><?php esc_html_e('API Key:', 'ai-auto-tool'); ?></label>
                            <input type="text" class="input-api-key" placeholder="<?php echo esc_attr($provider === 'openai' ? 'sk-...' : ($provider === 'pollinations' ? 'unused or custom key' : ($provider === 'cloudflare' ? 'account_id|api_token' : ($provider === 'azure_openai' ? 'https://resource.openai.azure.com|deployment|api_key' : ($provider === '9router' ? 'api_key, https://api9.aiautotool.com/v1, or endpoint|api_key' : ($provider === 'jina' ? 'jina_...' : 'Enter API key')))))); ?>" />
                        </div>
                        <div class="form-group" style="flex: 1;">
                            <label><?php esc_html_e('Key Name (Optional):', 'ai-auto-tool'); ?></label>
                            <input type="text" class="input-key-name" placeholder="<?php esc_attr_e('e.g., Production Key', 'ai-auto-tool'); ?>" />
                        </div>
                        <button type="button" class="btn-add-key btn-add-api-key">
                            <i class="fa-solid fa-plus"></i> <?php esc_html_e('Add Key', 'ai-auto-tool'); ?>
                        </button>
                    </div>
                    <p style="margin: 10px 0 0; font-size: 12px; color: #666;">
                        <i class="fa-solid fa-circle-info"></i>
                        <?php esc_html_e('Get your API key from:', 'ai-auto-tool'); ?>
                        <a href="<?php echo esc_url($get_key_url); ?>" target="_blank"><?php echo esc_html($get_key_url); ?></a>
                    </p>
                </div>
                
                <!-- Keys List -->
                <div class="api-keys-list" data-provider="<?php echo esc_attr($provider); ?>">
                    <?php if (empty($keys)): ?>
                        <div class="empty-state">
                            <i class="fa-solid fa-key"></i>
                            <p><?php esc_html_e('No API keys added yet. Add your first key above.', 'ai-auto-tool'); ?></p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($keys as $key): 
                            $masked_key = strlen($key['key']) > 15 
                                ? substr($key['key'], 0, 7) . '...' . substr($key['key'], -4) 
                                : str_repeat('*', strlen($key['key']) - 4) . substr($key['key'], -4);
                            $is_enabled = $key['enabled'] ?? true;
                            ?>
                            <div class="api-key-item <?php echo !$is_enabled ? 'disabled' : ''; ?>">
                                <div class="api-key-info">
                                    <div class="api-key-header">
                                        <span class="api-key-name">
                                            <?php echo esc_html($key['name'] ?: __('Unnamed Key', 'ai-auto-tool')); ?>
                                        </span>
                                        <span class="api-key-status-badge <?php echo $is_enabled ? 'active' : 'disabled'; ?>">
                                            <?php echo $is_enabled ? esc_html__('Active', 'ai-auto-tool') : esc_html__('Disabled', 'ai-auto-tool'); ?>
                                        </span>
                                    </div>
                                    <code class="api-key-value"><?php echo esc_html($masked_key); ?></code>
                                    <div class="api-key-stats">
                                        <div class="api-key-stat">
                                            <i class="fa-solid fa-calendar-plus"></i>
                                            <span><?php echo esc_html(sprintf(__('Added: %s', 'ai-auto-tool'), date_i18n(get_option('date_format'), strtotime($key['added_at'])))); ?></span>
                                        </div>
                                        <?php if (!empty($key['last_used'])): ?>
                                        <div class="api-key-stat">
                                            <i class="fa-solid fa-clock"></i>
                                            <span><?php echo esc_html(sprintf(__('Last used: %s', 'ai-auto-tool'), human_time_diff(strtotime($key['last_used']), current_time('timestamp')) . ' ago')); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        <div class="api-key-stat">
                                            <i class="fa-solid fa-chart-line"></i>
                                            <span><?php echo esc_html(sprintf(__('Usage: %d', 'ai-auto-tool'), $key['usage_count'] ?? 0)); ?></span>
                                        </div>
                                        <?php if (($key['error_count'] ?? 0) > 0): ?>
                                        <div class="api-key-stat" style="color: #dc3545;">
                                            <i class="fa-solid fa-exclamation-triangle"></i>
                                            <span><?php echo esc_html(sprintf(__('Errors: %d', 'ai-auto-tool'), $key['error_count'])); ?></span>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="api-key-actions">
                                    <button 
                                        type="button" 
                                        class="btn-test btn-test-key" 
                                        data-provider="<?php echo esc_attr($provider); ?>"
                                        data-api-key="<?php echo esc_attr($key['key']); ?>"
                                        title="<?php esc_attr_e('Test this key', 'ai-auto-tool'); ?>">
                                        <i class="fa-solid fa-plug"></i>
                                    </button>
                                    <button 
                                        type="button" 
                                        class="btn-toggle btn-toggle-key" 
                                        data-provider="<?php echo esc_attr($provider); ?>"
                                        data-key-id="<?php echo esc_attr($key['id']); ?>"
                                        title="<?php echo $is_enabled ? esc_attr__('Disable this key', 'ai-auto-tool') : esc_attr__('Enable this key', 'ai-auto-tool'); ?>">
                                        <?php if ($is_enabled): ?>
                                            <i class="fa-solid fa-ban"></i> <?php esc_html_e('Disable', 'ai-auto-tool'); ?>
                                        <?php else: ?>
                                            <i class="fa-solid fa-check"></i> <?php esc_html_e('Enable', 'ai-auto-tool'); ?>
                                        <?php endif; ?>
                                    </button>
                                    <button 
                                        type="button" 
                                        class="btn-remove btn-remove-key" 
                                        data-provider="<?php echo esc_attr($provider); ?>"
                                        data-key-id="<?php echo esc_attr($key['id']); ?>"
                                        title="<?php esc_attr_e('Remove this key', 'ai-auto-tool'); ?>">
                                        <i class="fa-solid fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
            <?php
        }
        
        /**
         * AJAX handlers
         */
        public function ajax_add_api_key() {
            check_ajax_referer('aiautotool_api_manager_nonce', 'nonce');
            
            if (!current_user_can('manage_options')) {
                wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
            }
            
            $provider = sanitize_text_field($_POST['provider'] ?? '');
            $api_key = sanitize_text_field($_POST['api_key'] ?? '');
            $name = sanitize_text_field($_POST['name'] ?? '');
            
            if (empty($provider) || empty($api_key)) {
                wp_send_json_error(array('message' => __('Provider and API key are required', 'ai-auto-tool')));
            }
            
            // Validate provider ID
            $valid_providers = array_merge(
                array('openai', 'gemini', 'llm7', 'pollinations', 'huggingface', 'cloudflare', 'jina'),
                array_keys($this->get_openai_compatible_key_providers()),
                array_keys($this->get_tts_key_providers())
            );

            if (!in_array($provider, $valid_providers, true)) {
                wp_send_json_error(array('message' => __('Invalid provider', 'ai-auto-tool')));
            }
            
            $validate_method = 'validate_' . $provider . '_key';
            if (method_exists($this->api_keys_manager, $validate_method)) {
                $validation = $this->api_keys_manager->$validate_method($api_key);
            } elseif (isset($this->get_openai_compatible_key_providers()[$provider]) || isset($this->get_tts_key_providers()[$provider])) {
                $validation = $this->api_keys_manager->validate_openai_compatible_key($api_key);
            } else {
                wp_send_json_error(array('message' => __('Unsupported provider validation', 'ai-auto-tool')));
            }
            
            if (!$validation['valid']) {
                wp_send_json_error(array('message' => $validation['message']));
            }
            
            $result = $this->api_keys_manager->add_key($provider, $api_key, $name);
            
            if ($result['success']) {
                // Auto-detect and activate provider if no provider is currently active
                $manager = AIAutotool_AI_Provider_Manager::get_instance();
                $current_provider = $manager->get_active_provider();
                
                // If no provider is active, try to auto-detect
                if (!$current_provider) {
                    $auto_detected = $manager->auto_detect_provider();
                    if ($auto_detected) {
                        $active_provider = $manager->get_active_provider();
                        $result['message'] .= ' ' . sprintf(__('AI Provider "%s" has been automatically activated.', 'ai-auto-tool'), $active_provider->get_name());
                    }
                } else {
                    // If current provider is the one we just added key for, refresh it
                    if ($current_provider->get_id() === $provider) {
                        $manager->refresh_providers();
                    }
                }
                
                wp_send_json_success(array('message' => $result['message'], 'key' => $result['key']));
            } else {
                wp_send_json_error(array('message' => $result['message']));
            }
        }
        
        public function ajax_remove_api_key() {
            check_ajax_referer('aiautotool_api_manager_nonce', 'nonce');
            
            if (!current_user_can('manage_options')) {
                wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
            }
            
            $provider = sanitize_text_field($_POST['provider'] ?? '');
            $key_id = sanitize_text_field($_POST['key_id'] ?? '');
            
            if (empty($provider) || empty($key_id)) {
                wp_send_json_error(array('message' => __('Provider and key ID are required', 'ai-auto-tool')));
            }
            
            $result = $this->api_keys_manager->remove_key($provider, $key_id);
            
            if ($result['success']) {
                wp_send_json_success(array('message' => $result['message']));
            } else {
                wp_send_json_error(array('message' => $result['message']));
            }
        }
        
        public function ajax_test_specific_key() {
            check_ajax_referer('aiautotool_api_manager_nonce', 'nonce');
            
            if (!current_user_can('manage_options')) {
                wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
            }
            
            $provider = sanitize_text_field($_POST['provider'] ?? '');
            $api_key = sanitize_text_field($_POST['api_key'] ?? '');
            
            if (empty($provider) || empty($api_key)) {
                wp_send_json_error(array('message' => __('Provider and API key are required', 'ai-auto-tool')));
            }
            
            $test_method = 'test_' . $provider . '_connection';
            if (method_exists($this->api_keys_manager, $test_method)) {
                $result = $this->api_keys_manager->$test_method($api_key);
            } elseif (isset($this->get_openai_compatible_key_providers()[$provider]) && method_exists($this->api_keys_manager, 'test_compatible_provider_connection')) {
                $result = $this->api_keys_manager->test_compatible_provider_connection($provider, $api_key);
            } elseif (isset($this->get_tts_key_providers()[$provider])) {
                $result = array(
                    'success' => false,
                    'message' => __('Connection test for this TTS provider is not implemented yet. Key storage is available.', 'ai-auto-tool')
                );
            } else {
                wp_send_json_error(array('message' => __('Unsupported provider test', 'ai-auto-tool')));
            }
            
            if ($result['success']) {
                wp_send_json_success(array('message' => $result['message']));
            } else {
                wp_send_json_error(array('message' => $result['message']));
            }
        }
        
        public function ajax_toggle_key_status() {
            check_ajax_referer('aiautotool_api_manager_nonce', 'nonce');
            
            if (!current_user_can('manage_options')) {
                wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
            }
            
            $provider = sanitize_text_field($_POST['provider'] ?? '');
            $key_id = sanitize_text_field($_POST['key_id'] ?? '');
            
            if (empty($provider) || empty($key_id)) {
                wp_send_json_error(array('message' => __('Provider and key ID are required', 'ai-auto-tool')));
            }
            
            $result = $this->api_keys_manager->toggle_key_status($provider, $key_id);
            
            if ($result['success']) {
                wp_send_json_success(array('message' => $result['message']));
            } else {
                wp_send_json_error(array('message' => $result['message']));
            }
        }
        
        public function ajax_save_provider_settings() {
            check_ajax_referer('ai_provider_settings', 'nonce');
            
            if (!current_user_can('manage_options')) {
                wp_send_json_error(array('message' => 'Permission denied'));
            }
            
            $provider_id = isset($_POST['provider_id']) ? sanitize_text_field($_POST['provider_id']) : '';
            $model = isset($_POST['model']) ? sanitize_text_field($_POST['model']) : '';
            $routing_mode = isset($_POST['routing_mode']) ? sanitize_text_field($_POST['routing_mode']) : 'single';
            $routing_mode = in_array($routing_mode, array('single', 'rotate'), true) ? $routing_mode : 'single';
            $execution_mode = isset($_POST['execution_mode']) ? $this->sanitize_execution_mode(wp_unslash($_POST['execution_mode'])) : 'agent';
            $tts_provider = isset($_POST['tts_provider']) ? sanitize_key($_POST['tts_provider']) : 'openai';
            $tts_model = isset($_POST['tts_model']) ? sanitize_text_field($_POST['tts_model']) : '';
            $tts_voice = isset($_POST['tts_voice']) ? sanitize_text_field($_POST['tts_voice']) : '';
            $tts_auto_publish = !empty($_POST['tts_auto_publish']) && $_POST['tts_auto_publish'] === '1' ? '1' : '0';
            
            if ($routing_mode === 'single' && empty($provider_id)) {
                wp_send_json_error(array('message' => 'Provider ID is required'));
            }
            
            $manager = AIAutotool_AI_Provider_Manager::get_instance();
            if (method_exists($manager, 'set_provider_routing_mode')) {
                $manager->set_provider_routing_mode($routing_mode);
            }

            $provider = !empty($provider_id) ? $manager->get_provider($provider_id) : null;
            
            if ($routing_mode === 'single' && !$provider) {
                wp_send_json_error(array('message' => 'Invalid provider'));
            }
            
            if ($provider) {
                // Set active provider first
                if (!$manager->set_active_provider($provider_id)) {
                    wp_send_json_error(array('message' => 'Failed to set active provider'));
                }
                
                // Set model - use provided model or provider's default
                if (!empty($model)) {
                    // Validate that the model exists for this provider
                    $available_models = $provider->get_available_models();
                    if (isset($available_models[$model])) {
                        $manager->set_active_model($model);
                    } else {
                        // Model not found, use provider's default
                        $model = $provider->get_default_model();
                        $manager->set_active_model($model);
                    }
                } else {
                    // No model provided, use provider's default
                    $model = $provider->get_default_model();
                    $manager->set_active_model($model);
                }
            }

            $allowed_tts_providers = array('openai', 'elevenlabs');
            if (!in_array($tts_provider, $allowed_tts_providers, true)) {
                $tts_provider = 'openai';
            }

            if ($tts_model === '') {
                $tts_model = $tts_provider === 'elevenlabs' ? 'eleven_multilingual_v2' : 'tts-1';
            }

            if ($tts_voice === '') {
                $tts_voice = $tts_provider === 'elevenlabs' ? '21m00Tcm4TlvDq8ikWAM' : 'alloy';
            }

            update_option('aiautotool_tts_provider', $tts_provider, false);
            update_option('aiautotool_tts_model', $tts_model, false);
            update_option('aiautotool_tts_voice', $tts_voice, false);
            update_option('aiautotool_tts_auto_generate_on_publish', $tts_auto_publish, false);
            update_option($this->execution_mode_option_name, $execution_mode, false);
            
            
            wp_send_json_success(array(
                'message' => $routing_mode === 'rotate' ? 'AI Provider routing set to rotate available providers.' : 'AI Provider settings saved successfully!',
                'provider_id' => $provider_id,
                'model' => $model,
                'routing_mode' => $routing_mode,
                'execution_mode' => $execution_mode,
                'tts_provider' => $tts_provider,
                'tts_model' => $tts_model,
                'tts_voice' => $tts_voice,
                'tts_auto_publish' => $tts_auto_publish
            ));
        }
        
        public function ajax_test_provider() {
            check_ajax_referer('ai_provider_settings', 'nonce');
            
            if (!current_user_can('manage_options')) {
                wp_send_json_error(array('message' => 'Permission denied'));
            }
            
            $provider_id = isset($_POST['provider_id']) ? sanitize_text_field($_POST['provider_id']) : '';
            
            if (empty($provider_id)) {
                wp_send_json_error(array('message' => 'Provider ID is required'));
            }
            
            $manager = AIAutotool_AI_Provider_Manager::get_instance();
            $provider = $manager->get_provider($provider_id);
            
            if (!$provider) {
                wp_send_json_error(array('message' => 'Provider not found'));
            }
            
            if (!$provider->is_configured()) {
                wp_send_json_error(array('message' => 'Provider not configured. Please set API key first.'));
            }
            
            // Get model from POST (if selected in dropdown) or use active model or default
            $model = isset($_POST['model']) ? sanitize_text_field($_POST['model']) : '';
            if (empty($model)) {
                // Check if provider is active, get its model
                $active_provider = $manager->get_active_provider();
                if ($active_provider && $active_provider->get_id() === $provider_id) {
                    $model = $manager->get_active_model();
                }
            }
            if (empty($model)) {
                $model = $provider->get_default_model();
            }
            
            // Ensure model is not empty
            if (empty($model)) {
                wp_send_json_error(array(
                    'message' => __('No model available for testing. Please select a model first.', 'ai-auto-tool'),
                    'provider_name' => $provider->get_name() ?: $provider_id,
                    'model_id' => '',
                    'model_name' => ''
                ));
                return;
            }
            
            // Get model info
            $available_models = $provider->get_available_models();
            $model_name = isset($available_models[$model]) ? $available_models[$model] : $model;
            
            // Get provider name
            $provider_name = $provider->get_name();
            if (empty($provider_name)) {
                $provider_name = ucfirst($provider_id);
            }
            
            // Use test_connection method if available (for providers that support it with model parameter)
            // Otherwise, use chat_completion directly
            if (method_exists($provider, 'test_connection')) {
                // Try to call test_connection with model parameter
                $reflection = new ReflectionMethod($provider, 'test_connection');
                $params = $reflection->getParameters();
                
                if (count($params) > 0) {
                    // Method accepts parameters, pass model
                    $test_result = $provider->test_connection($model);
                } else {
                    // Method doesn't accept parameters, call without
                    $test_result = $provider->test_connection();
                }
                
                // If test_connection returns success, use it (even if no response field)
                if ($test_result['success']) {
                    // Get response - test_connection() returns 'response' key, but check 'content' as fallback
                    $response_content = '';
                    if (isset($test_result['response'])) {
                        $response_content = is_string($test_result['response']) ? trim($test_result['response']) : (string)$test_result['response'];
                    } elseif (isset($test_result['content'])) {
                        $response_content = is_string($test_result['content']) ? trim($test_result['content']) : (string)$test_result['content'];
                    }
                    
                    // Log for debugging
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                        if (!empty($response_content)) {
                        } else {
                        }
                    }
                    
                    $response_data = array(
                        'message' => isset($test_result['message']) ? $test_result['message'] : __('Model test thành công!', 'ai-auto-tool'),
                        'provider_name' => $provider_name,
                        'model_id' => isset($test_result['model']) && !empty($test_result['model']) ? $test_result['model'] : $model,
                        'model_name' => isset($test_result['model_name']) && !empty($test_result['model_name']) ? $test_result['model_name'] : $model_name,
                        'response' => $response_content, // Always include, even if empty
                        'usage' => isset($test_result['usage']) ? $test_result['usage'] : null,
                        'response_model' => isset($test_result['model']) && !empty($test_result['model']) ? $test_result['model'] : $model,
                        'test_time' => current_time('mysql')
                    );
                    
                    // Log final response data before sending
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                    
                    wp_send_json_success($response_data);
                    return;
                } else {
                    // Test failed, return error
                    wp_send_json_error(array(
                        'message' => isset($test_result['message']) ? $test_result['message'] : __('Model test thất bại', 'ai-auto-tool'),
                        'provider_name' => $provider_name,
                        'model_id' => isset($test_result['model']) ? $test_result['model'] : $model,
                        'model_name' => isset($test_result['model_name']) ? $test_result['model_name'] : $model_name,
                        'error' => isset($test_result['message']) ? $test_result['message'] : __('Unknown error', 'ai-auto-tool')
                    ));
                    return;
                }
            }
            
            // Fallback: Use chat_completion with custom prompt
            $test_prompt = sprintf(
                __('Hãy giới thiệu về bạn (model AI) cùng tên model (%s) và ngày cuối cùng cập nhật dữ liệu của bạn. Trả lời bằng tiếng Việt.', 'ai-auto-tool'),
                $model_name
            );
            
            $test_messages = array(
                array(
                    'role' => 'user',
                    'content' => $test_prompt
                )
            );
            
            // Perform actual chat completion test
            $test_result = $provider->chat_completion($test_messages, array('model' => $model));
            
            if ($test_result['success']) {
                $response_data = array(
                    'message' => __('Model test thành công!', 'ai-auto-tool'),
                    'provider_name' => $provider_name,
                    'model_id' => $model,
                    'model_name' => $model_name,
                    'response' => isset($test_result['content']) ? $test_result['content'] : '',
                    'usage' => isset($test_result['usage']) ? $test_result['usage'] : null,
                    'response_model' => isset($test_result['model']) ? $test_result['model'] : $model,
                    'test_time' => current_time('mysql')
                );
                
                wp_send_json_success($response_data);
            } else {
                $error_message = isset($test_result['error']) ? $test_result['error'] : __('Unknown error', 'ai-auto-tool');
                wp_send_json_error(array(
                    'message' => sprintf(__('Model test thất bại: %s', 'ai-auto-tool'), $error_message),
                    'provider_name' => $provider_name,
                    'model_id' => $model,
                    'model_name' => $model_name,
                    'error' => $error_message
                ));
            }
        }
        
        /**
         * Render feature box
         */
        public function render_feature() {
            require_once plugin_dir_path(dirname(__FILE__)) . '../lib/feature-descriptions.php';
            
            $autoToolBox = new AutoToolBox(
                "<i class=\"fa-solid fa-brain\"></i> " . esc_html__('AI Provider', 'ai-auto-tool'),
                __('Unified AI Provider management with API keys and model selection', 'ai-auto-tool'),
                "https://doc.aiautotool.com/features/ai-provider",
                $this->active_option_name,
                $this->active,
                plugins_url('../../images/logo.svg', __FILE__)
            );
            echo $autoToolBox->generateHTML();
        }
    }
}
