<?php
/**
 * AI Provider API Keys Manager
 * Quản lý API keys cho tất cả AI providers với hỗ trợ multiple keys và round-robin rotation
 */

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

class AIAutotool_AI_Provider_API_Keys {
    
    /**
     * Instance
     */
    private static $instance = null;
    
    /**
     * Option names for single keys (backward compatibility)
     */
    private $option_name_openai = 'aiautotool_openai_api_key';
    private $option_name_gemini = 'aiautotool_gemini_api_key';
    private $option_name_llm7 = 'aiautotool_llm7_api_key';
    private $option_name_pollinations = 'aiautotool_pollinations_api_key';
    private $option_name_huggingface = 'aiautotool_huggingface_api_key';
    private $option_name_cloudflare = 'aiautotool_cloudflare_api_key';
    private $option_name_jina = 'aiautotool_jina_api_key';
    private $option_name_openrouter = 'aiautotool_openrouter_api_key';
    private $option_name_groq = 'aiautotool_groq_api_key';
    private $option_name_deepseek = 'aiautotool_deepseek_api_key';
    private $option_name_mistral = 'aiautotool_mistral_api_key';
    private $option_name_together = 'aiautotool_together_api_key';
    private $option_name_fireworks = 'aiautotool_fireworks_api_key';
    private $option_name_perplexity = 'aiautotool_perplexity_api_key';
    private $option_name_xai = 'aiautotool_xai_api_key';
    private $option_name_ollama = 'aiautotool_ollama_api_key';
    private $option_name_anthropic = 'aiautotool_anthropic_api_key';
    private $option_name_azure_openai = 'aiautotool_azure_openai_api_key';
    
    /**
     * Option names for multiple keys
     */
    private $option_name_openai_keys = 'aiautotool_openai_api_keys';
    private $option_name_gemini_keys = 'aiautotool_gemini_api_keys';
    private $option_name_llm7_keys = 'aiautotool_llm7_api_keys';
    private $option_name_pollinations_keys = 'aiautotool_pollinations_api_keys';
    private $option_name_huggingface_keys = 'aiautotool_huggingface_api_keys';
    private $option_name_cloudflare_keys = 'aiautotool_cloudflare_api_keys';
    private $option_name_jina_keys = 'aiautotool_jina_api_keys';
    private $option_name_openrouter_keys = 'aiautotool_openrouter_api_keys';
    private $option_name_groq_keys = 'aiautotool_groq_api_keys';
    private $option_name_deepseek_keys = 'aiautotool_deepseek_api_keys';
    private $option_name_mistral_keys = 'aiautotool_mistral_api_keys';
    private $option_name_together_keys = 'aiautotool_together_api_keys';
    private $option_name_fireworks_keys = 'aiautotool_fireworks_api_keys';
    private $option_name_perplexity_keys = 'aiautotool_perplexity_api_keys';
    private $option_name_xai_keys = 'aiautotool_xai_api_keys';
    private $option_name_ollama_keys = 'aiautotool_ollama_api_keys';
    private $option_name_anthropic_keys = 'aiautotool_anthropic_api_keys';
    private $option_name_azure_openai_keys = 'aiautotool_azure_openai_api_keys';
    
    /**
     * Rotation index options
     */
    private $option_name_openai_index = 'aiautotool_openai_rotation_index';
    private $option_name_gemini_index = 'aiautotool_gemini_rotation_index';
    private $option_name_llm7_index = 'aiautotool_llm7_rotation_index';
    private $option_name_pollinations_index = 'aiautotool_pollinations_rotation_index';
    private $option_name_huggingface_index = 'aiautotool_huggingface_rotation_index';
    private $option_name_cloudflare_index = 'aiautotool_cloudflare_rotation_index';
    private $option_name_jina_index = 'aiautotool_jina_rotation_index';
    private $option_name_openrouter_index = 'aiautotool_openrouter_rotation_index';
    private $option_name_groq_index = 'aiautotool_groq_rotation_index';
    private $option_name_deepseek_index = 'aiautotool_deepseek_rotation_index';
    private $option_name_mistral_index = 'aiautotool_mistral_rotation_index';
    private $option_name_together_index = 'aiautotool_together_rotation_index';
    private $option_name_fireworks_index = 'aiautotool_fireworks_rotation_index';
    private $option_name_perplexity_index = 'aiautotool_perplexity_rotation_index';
    private $option_name_xai_index = 'aiautotool_xai_rotation_index';
    private $option_name_ollama_index = 'aiautotool_ollama_rotation_index';
    private $option_name_anthropic_index = 'aiautotool_anthropic_rotation_index';
    private $option_name_azure_openai_index = 'aiautotool_azure_openai_rotation_index';
    
    /**
     * Get instance
     */
    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        // Migrate old single keys to new format if needed
        $this->migrate_old_keys();
    }
    
    /**
     * Migrate old single keys to new multiple keys format
     */
    private function migrate_old_keys() {
        // Migrate OpenAI
        $old_openai = get_option($this->option_name_openai, '');
        $new_openai = get_option($this->option_name_openai_keys, array());
        if (!empty($old_openai) && empty($new_openai)) {
            $this->add_key('openai', $old_openai, 'Primary Key (Migrated)');
        }
        
        // Migrate Gemini
        $old_gemini = get_option($this->option_name_gemini, '');
        $new_gemini = get_option($this->option_name_gemini_keys, array());
        if (!empty($old_gemini) && empty($new_gemini)) {
            $this->add_key('gemini', $old_gemini, 'Primary Key (Migrated)');
        }
        
        // Migrate Pollinations
        $old_pollinations = get_option($this->option_name_pollinations, '');
        $new_pollinations = get_option($this->option_name_pollinations_keys, array());
        if (!empty($old_pollinations) && empty($new_pollinations)) {
            $this->add_key('pollinations', $old_pollinations, 'Primary Key (Migrated)');
        }
        
        // Migrate LLM7 to Pollinations (backward compatibility - one-time migration)
        $old_llm7 = get_option($this->option_name_llm7, '');
        $new_llm7 = get_option($this->option_name_llm7_keys, array());
        if (!empty($old_llm7) && empty($new_pollinations)) {
            // If pollinations is empty but llm7 has a key, migrate it to pollinations
            $this->add_key('pollinations', $old_llm7, 'Primary Key (Migrated from LLM7)');
        }
        // Also migrate llm7 keys array to pollinations if pollinations is empty
        if (!empty($new_llm7) && empty($new_pollinations)) {
            foreach ($new_llm7 as $llm7_key) {
                if (isset($llm7_key['key'])) {
                    $this->add_key('pollinations', $llm7_key['key'], isset($llm7_key['name']) ? $llm7_key['name'] . ' (Migrated from LLM7)' : 'Key (Migrated from LLM7)');
                }
            }
        }
        
        // Migrate HuggingFace
        $old_huggingface = get_option($this->option_name_huggingface, '');
        $new_huggingface = get_option($this->option_name_huggingface_keys, array());
        if (!empty($old_huggingface) && empty($new_huggingface)) {
            $this->add_key('huggingface', $old_huggingface, 'Primary Key (Migrated)');
        }
        
        // Migrate Cloudflare
        $old_cloudflare = get_option($this->option_name_cloudflare, '');
        $new_cloudflare = get_option($this->option_name_cloudflare_keys, array());
        if (!empty($old_cloudflare) && empty($new_cloudflare)) {
            $this->add_key('cloudflare', $old_cloudflare, 'Primary Key (Migrated)');
        }
        
        // Migrate Jina AI
        $old_jina = get_option($this->option_name_jina, '');
        $new_jina = get_option($this->option_name_jina_keys, array());
        if (!empty($old_jina) && empty($new_jina)) {
            $this->add_key('jina', $old_jina, 'Primary Key (Migrated)');
        }
    }

    /**
     * Build option names dynamically so OpenAI-compatible providers can be added
     * without needing a new hard-coded option property for every provider.
     */
    private function get_option_name_for_provider($provider, $type = 'keys') {
        $provider = sanitize_key($provider);
        $property = 'option_name_' . $provider;

        if ($type === 'keys') {
            $property .= '_keys';
            return isset($this->$property) ? $this->$property : 'aiautotool_' . $provider . '_api_keys';
        }

        if ($type === 'index') {
            $property .= '_index';
            return isset($this->$property) ? $this->$property : 'aiautotool_' . $provider . '_rotation_index';
        }

        return isset($this->$property) ? $this->$property : 'aiautotool_' . $provider . '_api_key';
    }
    
    /**
     * Get all keys for a provider
     */
    public function get_all_keys($provider) {
        $option_name = $this->get_option_name_for_provider($provider, 'keys');
        $keys = get_option($option_name, array());
        return is_array($keys) ? $keys : array();
    }
    
    /**
     * Get active keys for a provider (only enabled keys)
     */
    public function get_active_keys($provider) {
        $all_keys = $this->get_all_keys($provider);
        return array_filter($all_keys, function($key) {
            return isset($key['enabled']) && !empty($key['enabled']);
        });
    }
    
    /**
     * Add a new key for a provider
     */
    public function add_key($provider, $api_key, $name = '') {
        $option_name = $this->get_option_name_for_provider($provider, 'keys');
        $keys = $this->get_all_keys($provider);
        
        // Check if key already exists
        foreach ($keys as $existing_key) {
            if ($existing_key['key'] === $api_key) {
                return array('success' => false, 'message' => __('This API key already exists', 'ai-auto-tool'));
            }
        }
        
        $new_key = array(
            'id' => uniqid('key_'),
            'key' => sanitize_text_field($api_key),
            'name' => sanitize_text_field($name),
            'enabled' => true,
            'added_at' => current_time('mysql'),
            'last_used' => null,
            'usage_count' => 0,
            'error_count' => 0,
            'last_error' => null
        );
        
        $keys[] = $new_key;
        update_option($option_name, $keys, false);
        
        return array('success' => true, 'message' => __('API key added successfully', 'ai-auto-tool'), 'key' => $new_key);
    }
    
    /**
     * Remove a key for a provider
     */
    public function remove_key($provider, $key_id) {
        $option_name = $this->get_option_name_for_provider($provider, 'keys');
        $keys = $this->get_all_keys($provider);
        
        $keys = array_filter($keys, function($key) use ($key_id) {
            return $key['id'] !== $key_id;
        });
        
        update_option($option_name, array_values($keys), false);
        return array('success' => true, 'message' => __('API key removed successfully', 'ai-auto-tool'));
    }
    
    /**
     * Toggle key enabled/disabled status
     */
    public function toggle_key_status($provider, $key_id) {
        $option_name = $this->get_option_name_for_provider($provider, 'keys');
        $keys = $this->get_all_keys($provider);
        
        foreach ($keys as &$key) {
            if ($key['id'] === $key_id) {
                $key['enabled'] = !$key['enabled'];
                break;
            }
        }
        
        update_option($option_name, $keys, false);
        return array('success' => true, 'message' => __('Key status updated', 'ai-auto-tool'));
    }
    
    /**
     * Update key statistics (usage, errors)
     */
    public function update_key_stats($provider, $key_id, $success = true, $error_message = null) {
        $option_name = $this->get_option_name_for_provider($provider, 'keys');
        $keys = $this->get_all_keys($provider);
        
        foreach ($keys as &$key) {
            if ($key['id'] === $key_id) {
                $key['last_used'] = current_time('mysql');
                $key['usage_count'] = ($key['usage_count'] ?? 0) + 1;
                
                if (!$success) {
                    $key['error_count'] = ($key['error_count'] ?? 0) + 1;
                    $key['last_error'] = $error_message;
                }
                break;
            }
        }
        
        update_option($option_name, $keys, false);
    }
    
    /**
     * Get next key using round-robin rotation
     */
    public function get_next_key($provider) {
        $active_keys = $this->get_active_keys($provider);
        
        if (empty($active_keys)) {
            // Fallback to old single key method
            $option_name = $this->get_option_name_for_provider($provider, 'single');
            $fallback_key = get_option($option_name, '');
            return $fallback_key;
        }
        
        // Get current rotation index
        $index_option = $this->get_option_name_for_provider($provider, 'index');
        $current_index = get_option($index_option, 0);
        
        // Reset array keys to ensure proper indexing
        $active_keys = array_values($active_keys);
        
        // Get the key at current index
        if (!isset($active_keys[$current_index])) {
            $current_index = 0;
        }
        
        $selected_key = $active_keys[$current_index];
        
        // Update rotation index for next call
        $next_index = ($current_index + 1) % count($active_keys);
        update_option($index_option, $next_index, false);
        
        // Update usage stats
        $this->update_key_stats($provider, $selected_key['id'], true);
        
        return $selected_key['key'];
    }
    
    /**
     * Get OpenAI API Key (with rotation)
     */
    public static function get_openai_key() {
        $instance = self::get_instance();
        return $instance->get_next_key('openai');
    }
    
    /**
     * Get Gemini API Key (with rotation)
     */
    public static function get_gemini_key() {
        $instance = self::get_instance();
        return $instance->get_next_key('gemini');
    }
    
    /**
     * Get LLM7 API Key (with rotation)
     * @deprecated Use get_pollinations_key() instead
     */
    public static function get_llm7_key() {
        return self::get_pollinations_key();
    }
    
    /**
     * Get Pollinations.ai API Key (with rotation)
     */
    public static function get_pollinations_key() {
        $instance = self::get_instance();
        $key = self::get_instance()->get_next_key('pollinations');
        return !empty($key) ? $key : '';
    }
    
    /**
     * Get HuggingFace API Key (with rotation)
     */
    public static function get_huggingface_key() {
        $instance = self::get_instance();
        $key = self::get_instance()->get_next_key('huggingface');
        return !empty($key) ? $key : '';
    }
    
    /**
     * Get Cloudflare API Key (with rotation)
     * Returns format: "account_id|api_token"
     */
    public static function get_cloudflare_key() {
        $instance = self::get_instance();
        $key = self::get_instance()->get_next_key('cloudflare');
        return !empty($key) ? $key : '';
    }
    
    /**
     * Get Jina AI API Key (with rotation)
     */
    public static function get_jina_key() {
        $instance = self::get_instance();
        $key = self::get_instance()->get_next_key('jina');
        return !empty($key) ? $key : '';
    }

    /**
     * Get API Key for an OpenAI-compatible provider.
     */
    public static function get_provider_key($provider) {
        $instance = self::get_instance();
        $key = $instance->get_next_key($provider);
        return !empty($key) ? $key : '';
    }
    
    /**
     * Validate OpenAI API Key format
     */
    public function validate_openai_key($key) {
        if (empty($key)) {
            return array('valid' => false, 'message' => __('API Key cannot be empty', 'ai-auto-tool'));
        }
        
        if (!preg_match('/^sk-[a-zA-Z0-9_\-]{20,}$/', $key)) {
            return array('valid' => false, 'message' => __('Invalid OpenAI API Key format. Should start with "sk-" and have at least 20 characters', 'ai-auto-tool'));
        }
        
        return array('valid' => true, 'message' => __('Valid format', 'ai-auto-tool'));
    }
    
    /**
     * Validate Gemini API Key format
     */
    public function validate_gemini_key($key) {
        if (empty($key)) {
            return array('valid' => false, 'message' => __('API Key cannot be empty', 'ai-auto-tool'));
        }
        
        if (strlen($key) < 20) {
            return array('valid' => false, 'message' => __('Invalid Gemini API Key format', 'ai-auto-tool'));
        }
        
        return array('valid' => true, 'message' => __('Valid format', 'ai-auto-tool'));
    }
    
    /**
     * Validate LLM7 API Key format
     * @deprecated Use validate_pollinations_key() instead. This method is kept for backward compatibility only.
     */
    public function validate_llm7_key($key) {
        // Delegate to pollinations validation
        return $this->validate_pollinations_key($key);
    }
    
    /**
     * Validate Pollinations.ai API Key format
     */
    public function validate_pollinations_key($key) {
        if (empty($key)) {
            return array('valid' => false, 'message' => __('API Key cannot be empty. Use "unused" for free tier or get a key from https://enter.pollinations.ai/', 'ai-auto-tool'));
        }
        
        // Accept "unused" as valid (will use default key)
        if ($key === 'unused') {
            return array('valid' => true, 'message' => __('Valid format (will use default key)', 'ai-auto-tool'));
        }
        
        // Pollinations.ai API keys typically start with "plln_sk_" and have at least 20 characters
        if (preg_match('/^plln_sk_[a-zA-Z0-9_\-]{20,}$/', $key)) {
            return array('valid' => true, 'message' => __('Valid format', 'ai-auto-tool'));
        }
        
        // Also accept keys that are at least 20 characters (for backward compatibility)
        if (strlen($key) >= 20) {
            return array('valid' => true, 'message' => __('Valid format', 'ai-auto-tool'));
        }
        
        return array('valid' => false, 'message' => __('Invalid Pollinations.ai API Key format. Should start with "plln_sk_" and have at least 20 characters, or use "unused" for free tier', 'ai-auto-tool'));
    }
    
    /**
     * Validate HuggingFace API Key format
     */
    public function validate_huggingface_key($key) {
        if (empty($key)) {
            return array('valid' => false, 'message' => __('API Key cannot be empty. Get a key from https://huggingface.co/settings/tokens', 'ai-auto-tool'));
        }
        
        // HuggingFace API keys typically start with "hf_" and have at least 20 characters
        if (preg_match('/^hf_[a-zA-Z0-9_\-]{20,}$/', $key)) {
            return array('valid' => true, 'message' => __('Valid format', 'ai-auto-tool'));
        }
        
        // Also accept keys that are at least 20 characters (for backward compatibility)
        if (strlen($key) >= 20) {
            return array('valid' => true, 'message' => __('Valid format', 'ai-auto-tool'));
        }
        
        return array('valid' => false, 'message' => __('Invalid HuggingFace API Key format. Should start with "hf_" and have at least 20 characters', 'ai-auto-tool'));
    }
    
    /**
     * Validate Cloudflare credentials format
     * Format: "account_id|api_token"
     */
    public function validate_cloudflare_key($key) {
        if (empty($key)) {
            return array('valid' => false, 'message' => __('Credentials cannot be empty. Format: account_id|api_token', 'ai-auto-tool'));
        }
        
        // Check if it's in the format "account_id|api_token"
        if (strpos($key, '|') !== false) {
            $parts = explode('|', $key, 2);
            if (count($parts) === 2) {
                $account_id = trim($parts[0]);
                $api_token = trim($parts[1]);
                
                if (empty($account_id)) {
                    return array('valid' => false, 'message' => __('Account ID cannot be empty', 'ai-auto-tool'));
                }
                
                if (empty($api_token)) {
                    return array('valid' => false, 'message' => __('API Token cannot be empty', 'ai-auto-tool'));
                }
                
                // Cloudflare account IDs are typically 32 characters hex
                if (strlen($account_id) < 10) {
                    return array('valid' => false, 'message' => __('Invalid Account ID format', 'ai-auto-tool'));
                }
                
                // API tokens are typically longer
                if (strlen($api_token) < 20) {
                    return array('valid' => false, 'message' => __('Invalid API Token format', 'ai-auto-tool'));
                }
                
                return array('valid' => true, 'message' => __('Valid format', 'ai-auto-tool'));
            }
        }
        
        // If no separator, it might be just an API token (backward compatibility)
        if (strlen($key) >= 20) {
            return array('valid' => true, 'message' => __('Valid format (API token only, account ID will need to be added separately)', 'ai-auto-tool'));
        }
        
        return array('valid' => false, 'message' => __('Invalid format. Expected: account_id|api_token', 'ai-auto-tool'));
    }
    
    /**
     * Validate Jina AI API Key format
     */
    public function validate_jina_key($key) {
        if (empty($key)) {
            return array('valid' => false, 'message' => __('API Key cannot be empty. Get a key from https://jina.ai/', 'ai-auto-tool'));
        }
        
        // Jina AI API keys typically start with "jina_" and have at least 30 characters
        if (preg_match('/^jina_[a-zA-Z0-9_\-]{30,}$/', $key)) {
            return array('valid' => true, 'message' => __('Valid format', 'ai-auto-tool'));
        }
        
        // Also accept keys that are at least 30 characters (for backward compatibility)
        if (strlen($key) >= 30) {
            return array('valid' => true, 'message' => __('Valid format', 'ai-auto-tool'));
        }
        
        return array('valid' => false, 'message' => __('Invalid Jina AI API Key format. Should start with "jina_" and have at least 30 characters, or be at least 30 characters long', 'ai-auto-tool'));
    }

    /**
     * Validate generic OpenAI-compatible API key format.
     */
    public function validate_openai_compatible_key($key) {
        if (empty($key)) {
            return array('valid' => false, 'message' => __('API Key cannot be empty', 'ai-auto-tool'));
        }

        if (strlen($key) < 3) {
            return array('valid' => false, 'message' => __('API Key is too short', 'ai-auto-tool'));
        }

        return array('valid' => true, 'message' => __('Valid format', 'ai-auto-tool'));
    }

    public function validate_openrouter_key($key) { return $this->validate_openai_compatible_key($key); }
    public function validate_groq_key($key) { return $this->validate_openai_compatible_key($key); }
    public function validate_deepseek_key($key) { return $this->validate_openai_compatible_key($key); }
    public function validate_mistral_key($key) { return $this->validate_openai_compatible_key($key); }
    public function validate_together_key($key) { return $this->validate_openai_compatible_key($key); }
    public function validate_fireworks_key($key) { return $this->validate_openai_compatible_key($key); }
    public function validate_perplexity_key($key) { return $this->validate_openai_compatible_key($key); }
    public function validate_xai_key($key) { return $this->validate_openai_compatible_key($key); }
    public function validate_ollama_key($key) { return $this->validate_openai_compatible_key($key); }
    public function validate_anthropic_key($key) { return $this->validate_openai_compatible_key($key); }
    public function validate_elevenlabs_key($key) { return $this->validate_openai_compatible_key($key); }

    public function validate_azure_openai_key($key) {
        if (empty($key)) {
            return array('valid' => false, 'message' => __('Credentials cannot be empty. Format: endpoint|deployment|api_key', 'ai-auto-tool'));
        }

        if (strpos($key, '|') === false) {
            return array('valid' => false, 'message' => __('Invalid format. Expected: endpoint|deployment|api_key', 'ai-auto-tool'));
        }

        $parts = array_map('trim', explode('|', $key, 3));
        if (count($parts) !== 3 || empty($parts[0]) || empty($parts[1]) || empty($parts[2])) {
            return array('valid' => false, 'message' => __('Invalid format. Expected: endpoint|deployment|api_key', 'ai-auto-tool'));
        }

        if (strpos($parts[0], 'https://') !== 0) {
            return array('valid' => false, 'message' => __('Azure endpoint should start with https://', 'ai-auto-tool'));
        }

        return array('valid' => true, 'message' => __('Valid format', 'ai-auto-tool'));
    }
    
    /**
     * Test OpenAI API connection
     */
    public function test_openai_connection($api_key) {
        $url = 'https://api.openai.com/v1/models';
        
        $response = wp_remote_get($url, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'application/json',
            ),
            'timeout' => 15,
        ));
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => __('Connection error: ', 'ai-auto-tool') . $response->get_error_message()
            );
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        
        if ($status_code === 200) {
            return array(
                'success' => true,
                'message' => __('OpenAI API Key is valid and working!', 'ai-auto-tool')
            );
        } else {
            $body = json_decode(wp_remote_retrieve_body($response), true);
            $error_message = isset($body['error']['message']) ? $body['error']['message'] : __('Invalid API Key', 'ai-auto-tool');
            
            return array(
                'success' => false,
                'message' => __('OpenAI API Error: ', 'ai-auto-tool') . $error_message
            );
        }
    }
    
    /**
     * Test Gemini API connection
     */
    public function test_gemini_connection($api_key) {
        $url = 'https://generativelanguage.googleapis.com/v1beta/models?key=' . $api_key;
        
        $response = wp_remote_get($url, array(
            'timeout' => 15,
        ));
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => __('Connection error: ', 'ai-auto-tool') . $response->get_error_message()
            );
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        
        if ($status_code === 200) {
            return array(
                'success' => true,
                'message' => __('Gemini API Key is valid and working!', 'ai-auto-tool')
            );
        } else {
            $body = json_decode(wp_remote_retrieve_body($response), true);
            $error_message = isset($body['error']['message']) ? $body['error']['message'] : __('Invalid API Key', 'ai-auto-tool');
            
            return array(
                'success' => false,
                'message' => __('Gemini API Error: ', 'ai-auto-tool') . $error_message
            );
        }
    }
    
    /**
     * Test Pollinations.ai API connection
     */
    public function test_pollinations_connection($api_key) {
        $url = 'https://enter.pollinations.ai/api/generate/text/models';
        
        $response = wp_remote_get($url, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'application/json',
            ),
            'timeout' => 15,
        ));
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => __('Connection error: ', 'ai-auto-tool') . $response->get_error_message()
            );
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        
        if ($status_code === 200) {
            $body = json_decode(wp_remote_retrieve_body($response), true);
            $model_count = is_array($body) ? count($body) : 0;
            return array(
                'success' => true,
                'message' => sprintf(__('Pollinations.ai API is working! Found %d available models.', 'ai-auto-tool'), $model_count)
            );
        } else {
            $body = json_decode(wp_remote_retrieve_body($response), true);
            $error_message = isset($body['error']['message']) ? $body['error']['message'] : __('Invalid API Key', 'ai-auto-tool');
            
            return array(
                'success' => false,
                'message' => __('Pollinations.ai API Error: ', 'ai-auto-tool') . $error_message
            );
        }
    }
    
    /**
     * Test LLM7 API connection
     * @deprecated Use test_pollinations_connection() instead. This method is kept for backward compatibility only.
     */
    public function test_llm7_connection($api_key) {
        return $this->test_pollinations_connection($api_key);
    }
    
    /**
     * Test Cloudflare API connection
     */
    public function test_cloudflare_connection($api_key) {
        // Parse credentials
        $account_id = '';
        $api_token = '';
        
        if (strpos($api_key, '|') !== false) {
            $parts = explode('|', $api_key, 2);
            if (count($parts) === 2) {
                $account_id = trim($parts[0]);
                $api_token = trim($parts[1]);
            }
        } else {
            // If no separator, treat as api_token only
            $api_token = $api_key;
        }
        
        if (empty($account_id) || empty($api_token)) {
            return array(
                'success' => false,
                'message' => __('Invalid credentials format. Expected: account_id|api_token', 'ai-auto-tool')
            );
        }
        
        $url = 'https://api.cloudflare.com/client/v4/accounts/' . $account_id . '/ai/v1/responses';
        
        $body = array(
            'model' => '@cf/openai/gpt-oss-120b',
            'input' => 'Hello, please respond with "OK" to confirm the connection.'
        );
        
        $response = wp_remote_post($url, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_token,
                'Content-Type' => 'application/json',
            ),
            'body' => json_encode($body),
            'timeout' => 15,
        ));
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => __('Connection error: ', 'ai-auto-tool') . $response->get_error_message()
            );
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        
        if ($status_code === 200) {
            return array(
                'success' => true,
                'message' => __('Cloudflare API is working!', 'ai-auto-tool')
            );
        } else {
            $body = json_decode(wp_remote_retrieve_body($response), true);
            $error_message = __('Invalid credentials', 'ai-auto-tool');
            
            if (isset($body['errors']) && is_array($body['errors']) && !empty($body['errors'])) {
                $error_message = $body['errors'][0]['message'];
            } elseif (isset($body['error']['message'])) {
                $error_message = $body['error']['message'];
            } elseif (isset($body['message'])) {
                $error_message = $body['message'];
            }
            
            return array(
                'success' => false,
                'message' => __('Cloudflare API Error: ', 'ai-auto-tool') . $error_message
            );
        }
    }
    
    /**
     * Test HuggingFace API connection
     */
    public function test_huggingface_connection($api_key) {
        $url = 'https://router.huggingface.co/v1/chat/completions';
        
        $body = array(
            'model' => 'google/gemma-2-2b-it:nebius',
            'messages' => array(
                array(
                    'role' => 'user',
                    'content' => 'Hello'
                )
            ),
            'stream' => false
        );
        
        $response = wp_remote_post($url, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'application/json',
            ),
            'body' => json_encode($body),
            'timeout' => 15,
        ));
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => __('Connection error: ', 'ai-auto-tool') . $response->get_error_message()
            );
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        
        if ($status_code === 200) {
            return array(
                'success' => true,
                'message' => __('HuggingFace API is working!', 'ai-auto-tool')
            );
        } else {
            $body = json_decode(wp_remote_retrieve_body($response), true);
            $error_message = isset($body['error']['message']) ? $body['error']['message'] : __('Invalid API Key', 'ai-auto-tool');
            
            return array(
                'success' => false,
                'message' => __('HuggingFace API Error: ', 'ai-auto-tool') . $error_message
            );
        }
    }
    
    /**
     * Test Jina AI API connection
     */
    public function test_jina_connection($api_key) {
        // Test with Jina AI Search API
        $url = 'https://s.jina.ai/?q=test';
        
        $response = wp_remote_get($url, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'X-Respond-With' => 'no-content',
                'Accept' => 'application/json',
            ),
            'timeout' => 15,
        ));
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => __('Connection error: ', 'ai-auto-tool') . $response->get_error_message()
            );
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        
        if ($status_code === 200) {
            $body = json_decode(wp_remote_retrieve_body($response), true);
            $result_count = 0;
            if (isset($body['results']) && is_array($body['results'])) {
                $result_count = count($body['results']);
            } elseif (isset($body['data']) && is_array($body['data'])) {
                $result_count = count($body['data']);
            }
            return array(
                'success' => true,
                'message' => sprintf(__('Jina AI API is working! Found %d search results.', 'ai-auto-tool'), $result_count)
            );
        } else {
            $body = json_decode(wp_remote_retrieve_body($response), true);
            $error_message = __('Invalid API Key', 'ai-auto-tool');
            
            if ($status_code === 401) {
                $error_message = __('Unauthorized. Please check your Jina AI API key.', 'ai-auto-tool');
            } elseif ($status_code === 429) {
                $error_message = __('Rate limit exceeded. Please try again later.', 'ai-auto-tool');
            } elseif (isset($body['error']['message'])) {
                $error_message = $body['error']['message'];
            } elseif (isset($body['message'])) {
                $error_message = $body['message'];
            }
            
            return array(
                'success' => false,
                'message' => __('Jina AI API Error: ', 'ai-auto-tool') . $error_message
            );
        }
    }

    /**
     * Test generic OpenAI-compatible provider connection.
     */
    private function test_openai_compatible_connection($provider, $api_key) {
        $configs = array(
            'openrouter' => array(
                'name' => 'OpenRouter',
                'url' => 'https://openrouter.ai/api/v1/chat/completions',
                'model' => 'openai/gpt-4o-mini',
                'headers' => array('HTTP-Referer' => 'https://aiautotool.com', 'X-Title' => 'AI Auto Tool'),
            ),
            '9router' => array(
                'name' => '9Router',
                'url' => 'https://api9.aiautotool.com/v1/chat/completions',
                'model' => 'vkct',
                'headers' => array(),
            ),
            'groq' => array(
                'name' => 'Groq',
                'url' => 'https://api.groq.com/openai/v1/chat/completions',
                'model' => 'llama-3.3-70b-versatile',
                'headers' => array(),
            ),
            'deepseek' => array(
                'name' => 'DeepSeek',
                'url' => 'https://api.deepseek.com/chat/completions',
                'model' => 'deepseek-v4-flash',
                'headers' => array(),
            ),
            'mistral' => array(
                'name' => 'Mistral AI',
                'url' => 'https://api.mistral.ai/v1/chat/completions',
                'model' => 'mistral-small-latest',
                'headers' => array(),
            ),
            'together' => array(
                'name' => 'Together AI',
                'url' => 'https://api.together.xyz/v1/chat/completions',
                'model' => 'meta-llama/Llama-3.3-70B-Instruct-Turbo',
                'headers' => array(),
            ),
            'fireworks' => array(
                'name' => 'Fireworks AI',
                'url' => 'https://api.fireworks.ai/inference/v1/chat/completions',
                'model' => 'accounts/fireworks/models/llama-v3p1-8b-instruct',
                'headers' => array(),
            ),
            'perplexity' => array(
                'name' => 'Perplexity',
                'url' => 'https://api.perplexity.ai/chat/completions',
                'model' => 'sonar',
                'headers' => array(),
            ),
            'xai' => array(
                'name' => 'xAI',
                'url' => 'https://api.x.ai/v1/chat/completions',
                'model' => 'grok-4',
                'headers' => array(),
            ),
            'ollama' => array(
                'name' => 'Ollama Local',
                'url' => 'http://localhost:11434/v1/chat/completions',
                'model' => 'llama3.1',
                'headers' => array(),
            ),
            'anthropic' => array(
                'name' => 'Anthropic',
                'url' => 'https://api.anthropic.com/v1/messages',
                'model' => 'claude-sonnet-4-5',
                'headers' => array('anthropic-version' => '2023-06-01'),
            ),
            'glm_coding' => array(
                'name' => 'GLM Coding',
                'url' => 'https://open.bigmodel.cn/api/paas/v4/chat/completions',
                'model' => 'glm-4.5',
                'headers' => array(),
            ),
            'glm_china' => array(
                'name' => 'GLM China',
                'url' => 'https://open.bigmodel.cn/api/paas/v4/chat/completions',
                'model' => 'glm-4.5-air',
                'headers' => array(),
            ),
            'kimi' => array(
                'name' => 'Kimi',
                'url' => 'https://api.moonshot.cn/v1/chat/completions',
                'model' => 'moonshot-v1-8k',
                'headers' => array(),
            ),
            'minimax_coding' => array(
                'name' => 'Minimax Coding',
                'url' => 'https://api.minimax.io/v1/chat/completions',
                'model' => 'MiniMax-M1',
                'headers' => array(),
            ),
            'minimax_china' => array(
                'name' => 'Minimax China',
                'url' => 'https://api.minimax.chat/v1/chat/completions',
                'model' => 'MiniMax-M1',
                'headers' => array(),
            ),
            'alibaba' => array(
                'name' => 'Alibaba',
                'url' => 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
                'model' => 'qwen-plus',
                'headers' => array(),
            ),
            'alibaba_intl' => array(
                'name' => 'Alibaba Intl',
                'url' => 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions',
                'model' => 'qwen-plus',
                'headers' => array(),
            ),
            'volcengine_ark' => array(
                'name' => 'Volcengine Ark',
                'url' => 'https://ark.cn-beijing.volces.com/api/v3/chat/completions',
                'model' => 'doubao-seed-1-6',
                'headers' => array(),
            ),
            'byteplus_modelark' => array(
                'name' => 'BytePlus ModelArk',
                'url' => 'https://ark.ap-southeast.bytepluses.com/api/v3/chat/completions',
                'model' => 'doubao-seed-1-6',
                'headers' => array(),
            ),
            'cerebras' => array(
                'name' => 'Cerebras',
                'url' => 'https://api.cerebras.ai/v1/chat/completions',
                'model' => 'llama-3.3-70b',
                'headers' => array(),
            ),
            'cohere' => array(
                'name' => 'Cohere',
                'url' => 'https://api.cohere.com/compatibility/v1/chat/completions',
                'model' => 'command-a-03-2025',
                'headers' => array(),
            ),
            'nebius' => array(
                'name' => 'Nebius AI',
                'url' => 'https://api.studio.nebius.com/v1/chat/completions',
                'model' => 'meta-llama/Meta-Llama-3.1-70B-Instruct',
                'headers' => array(),
            ),
            'siliconflow' => array(
                'name' => 'SiliconFlow',
                'url' => 'https://api.siliconflow.cn/v1/chat/completions',
                'model' => 'deepseek-ai/DeepSeek-V3',
                'headers' => array(),
            ),
            'hyperbolic' => array(
                'name' => 'Hyperbolic',
                'url' => 'https://api.hyperbolic.xyz/v1/chat/completions',
                'model' => 'meta-llama/Meta-Llama-3.1-70B-Instruct',
                'headers' => array(),
            ),
            'chutes' => array(
                'name' => 'Chutes AI',
                'url' => 'https://llm.chutes.ai/v1/chat/completions',
                'model' => 'deepseek-ai/DeepSeek-V3',
                'headers' => array(),
            ),
            'nvidia_nim' => array(
                'name' => 'NVIDIA NIM',
                'url' => 'https://integrate.api.nvidia.com/v1/chat/completions',
                'model' => 'meta/llama-3.1-70b-instruct',
                'headers' => array(),
            ),
        );

        if (!isset($configs[$provider])) {
            return array(
                'success' => false,
                'message' => __('Unknown provider', 'ai-auto-tool')
            );
        }

        $config = $configs[$provider];
        if ($provider === '9router' && is_string($api_key)) {
            if (preg_match('#^https?://#i', $api_key) && strpos($api_key, '|') === false) {
                $config['url'] = rtrim($api_key, '/') . '/chat/completions';
                $api_key = 'unused';
            } elseif (strpos($api_key, '|') !== false) {
                $parts = array_map('trim', explode('|', $api_key, 2));
                if (!empty($parts[0]) && preg_match('#^https?://#i', $parts[0])) {
                    $config['url'] = rtrim($parts[0], '/') . '/chat/completions';
                }
                $api_key = isset($parts[1]) ? $parts[1] : '';
            }
        }

        $headers = array_merge(
            array(
                'Content-Type' => 'application/json',
            ),
            $config['headers']
        );

        if ($provider === 'anthropic') {
            $headers['x-api-key'] = $api_key;
        } elseif ($provider === '9router') {
            if (!empty($api_key) && $api_key !== 'unused') {
                $headers['Authorization'] = 'Bearer ' . $api_key;
            }
        } elseif ($provider !== 'ollama' && $api_key !== 'unused') {
            $headers['Authorization'] = 'Bearer ' . $api_key;
        }

        if ($provider === 'anthropic') {
            $request_body = array(
                'model' => $config['model'],
                'messages' => array(
                    array(
                        'role' => 'user',
                        'content' => 'Reply with OK.'
                    )
                ),
                'temperature' => 0.2,
                'max_tokens' => 32,
            );
        } else {
            $request_body = array(
                'model' => $config['model'],
                'messages' => array(
                    array(
                        'role' => 'user',
                        'content' => 'Reply with OK.'
                    )
                ),
                'temperature' => 0.2,
                'max_tokens' => 32,
            );
        }

        $response = wp_remote_post($config['url'], array(
            'headers' => $headers,
            'body' => json_encode($request_body),
            'timeout' => 15,
        ));

        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => __('Connection error: ', 'ai-auto-tool') . $response->get_error_message()
            );
        }

        $status_code = wp_remote_retrieve_response_code($response);
        if ($status_code >= 200 && $status_code < 300) {
            return array(
                'success' => true,
                'message' => sprintf(__('%s API is working!', 'ai-auto-tool'), $config['name'])
            );
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $error_message = __('Invalid API Key or model', 'ai-auto-tool');
        if (isset($body['error']['message'])) {
            $error_message = $body['error']['message'];
        } elseif (isset($body['message'])) {
            $error_message = $body['message'];
        }

        return array(
            'success' => false,
            'message' => sprintf(__('%s API Error: ', 'ai-auto-tool'), $config['name']) . $error_message
        );
    }

    public function test_openrouter_connection($api_key) { return $this->test_openai_compatible_connection('openrouter', $api_key); }
    public function test_groq_connection($api_key) { return $this->test_openai_compatible_connection('groq', $api_key); }
    public function test_deepseek_connection($api_key) { return $this->test_openai_compatible_connection('deepseek', $api_key); }
    public function test_mistral_connection($api_key) { return $this->test_openai_compatible_connection('mistral', $api_key); }
    public function test_together_connection($api_key) { return $this->test_openai_compatible_connection('together', $api_key); }
    public function test_fireworks_connection($api_key) { return $this->test_openai_compatible_connection('fireworks', $api_key); }
    public function test_perplexity_connection($api_key) { return $this->test_openai_compatible_connection('perplexity', $api_key); }
    public function test_xai_connection($api_key) { return $this->test_openai_compatible_connection('xai', $api_key); }
    public function test_ollama_connection($api_key) { return $this->test_openai_compatible_connection('ollama', $api_key); }
    public function test_anthropic_connection($api_key) { return $this->test_openai_compatible_connection('anthropic', $api_key); }

    public function test_compatible_provider_connection($provider, $api_key) {
        return $this->test_openai_compatible_connection($provider, $api_key);
    }

    public function test_elevenlabs_connection($api_key) {
        $response = wp_remote_get('https://api.elevenlabs.io/v1/voices', array(
            'headers' => array(
                'xi-api-key' => $api_key,
            ),
            'timeout' => 15,
        ));

        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => __('Connection error: ', 'ai-auto-tool') . $response->get_error_message()
            );
        }

        $status_code = wp_remote_retrieve_response_code($response);
        if ($status_code >= 200 && $status_code < 300) {
            return array(
                'success' => true,
                'message' => __('ElevenLabs API is working!', 'ai-auto-tool')
            );
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $error_message = isset($body['detail']['message']) ? $body['detail']['message'] : __('Invalid API Key', 'ai-auto-tool');

        return array(
            'success' => false,
            'message' => __('ElevenLabs API Error: ', 'ai-auto-tool') . $error_message
        );
    }

    public function test_azure_openai_connection($api_key) {
        $validation = $this->validate_azure_openai_key($api_key);
        if (!$validation['valid']) {
            return array(
                'success' => false,
                'message' => $validation['message']
            );
        }

        $parts = array_map('trim', explode('|', $api_key, 3));
        $url = rtrim($parts[0], '/') . '/openai/deployments/' . rawurlencode($parts[1]) . '/chat/completions?api-version=2024-10-21';
        $response = wp_remote_post($url, array(
            'headers' => array(
                'api-key' => $parts[2],
                'Content-Type' => 'application/json',
            ),
            'body' => json_encode(array(
                'messages' => array(
                    array(
                        'role' => 'user',
                        'content' => 'Reply with OK.'
                    )
                ),
                'temperature' => 1.0,
                'max_tokens' => 32,
            )),
            'timeout' => 15,
        ));

        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => __('Connection error: ', 'ai-auto-tool') . $response->get_error_message()
            );
        }

        $status_code = wp_remote_retrieve_response_code($response);
        if ($status_code >= 200 && $status_code < 300) {
            return array(
                'success' => true,
                'message' => __('Azure OpenAI API is working!', 'ai-auto-tool')
            );
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $error_message = isset($body['error']['message']) ? $body['error']['message'] : __('Invalid Azure OpenAI credentials or deployment', 'ai-auto-tool');

        return array(
            'success' => false,
            'message' => __('Azure OpenAI API Error: ', 'ai-auto-tool') . $error_message
        );
    }
}

// Backward compatibility: Create alias for old API Manager methods
if (!class_exists('AIAutotool_API_Manager')) {
    class AIAutotool_API_Manager {
        public static function get_openai_key() {
            return AIAutotool_AI_Provider_API_Keys::get_openai_key();
        }
        
        public static function get_gemini_key() {
            return AIAutotool_AI_Provider_API_Keys::get_gemini_key();
        }
        
        public static function get_llm7_key() {
            return AIAutotool_AI_Provider_API_Keys::get_pollinations_key();
        }
        
        public static function get_pollinations_key() {
            return AIAutotool_AI_Provider_API_Keys::get_pollinations_key();
        }
        
        public static function get_huggingface_key() {
            return AIAutotool_AI_Provider_API_Keys::get_huggingface_key();
        }
        
        public static function get_cloudflare_key() {
            return AIAutotool_AI_Provider_API_Keys::get_cloudflare_key();
        }
        
        public static function get_jina_key() {
            return AIAutotool_AI_Provider_API_Keys::get_jina_key();
        }
    }
}
