<?php
/**
 * Settings Manager Class
 * 
 * Handles plugin settings using WordPress Settings API
 * 
 * @package AIProductContentImageGenerator\Admin
 * @since 1.0.0
 */

namespace AIProductContentImageGenerator\Admin;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

class SettingsManager {
    
    /**
     * Settings group name
     */
    const SETTINGS_GROUP = 'apcig_settings';
    
    /**
     * Settings page slug
     */
    const SETTINGS_PAGE = 'apcig-settings';
    
    /**
     * Default settings
     */
    private $default_settings = [
        'openai_api_key' => '',
        'claude_api_key' => '',
        'gemini_api_key' => '',
        'openrouter_api_key' => '',
        'default_provider' => 'openai',
        'default_tone' => 'professional',
        'default_language' => 'en',
        'max_tokens' => 1000,
        'temperature' => 0.7,
        'enable_seo_optimization' => true,
        'enable_content_validation' => true,
        'enable_duplicate_detection' => true,
        'auto_apply_content' => false,
        'backup_original_content' => true,
        'data_retention_days' => 90
    ];
    
    /**
     * Initialize settings
     */
    public function init() {
        add_action('admin_init', [$this, 'register_settings']);
        add_action('apcig_settings_saved', [$this, 'handle_settings_saved']);
    }
    
    /**
     * Register settings using WordPress Settings API
     */
    public function register_settings() {
        foreach ($this->default_settings as $setting_name => $default_value) {
            register_setting(
                self::SETTINGS_GROUP,
                'apcig_' . $setting_name,
                [
                    'type' => $this->get_setting_type($setting_name),
                    'description' => $this->get_setting_description($setting_name),
                    'sanitize_callback' => [$this, 'sanitize_setting'],
                    'show_in_rest' => false,
                    'default' => $default_value
                ]
            );
        }
        
        add_settings_section(
            'apcig_ai_providers',
            __('AI Providers', 'contengen-ai-product-content-image-generator'),
            [$this, 'ai_providers_section_callback'],
            self::SETTINGS_PAGE
        );
        
        add_settings_section(
            'apcig_default_settings',
            __('Default Settings', 'contengen-ai-product-content-image-generator'),
            [$this, 'default_settings_section_callback'],
            self::SETTINGS_PAGE
        );
        
        add_settings_section(
            'apcig_generation_parameters',
            __('Generation Parameters', 'contengen-ai-product-content-image-generator'),
            [$this, 'generation_parameters_section_callback'],
            self::SETTINGS_PAGE
        );
        
        add_settings_section(
            'apcig_content_features',
            __('Content Features', 'contengen-ai-product-content-image-generator'),
            [$this, 'content_features_section_callback'],
            self::SETTINGS_PAGE
        );
        
        $this->add_settings_fields();
    }
    
    /**
     * Add settings fields
     */
    private function add_settings_fields() {
        $providers = ['openai', 'claude', 'gemini', 'openrouter'];
        foreach ($providers as $provider) {
            add_settings_field(
                'apcig_' . $provider . '_api_key',
                ucfirst($provider) . ' API Key',
                [$this, 'api_key_field_callback'],
                self::SETTINGS_PAGE,
                'apcig_ai_providers',
                ['provider' => $provider]
            );
        }
        
        add_settings_field(
            'apcig_default_provider',
            __('Default Provider', 'contengen-ai-product-content-image-generator'),
            [$this, 'select_field_callback'],
            self::SETTINGS_PAGE,
            'apcig_default_settings',
            [
                'setting' => 'default_provider',
                'options' => [
                    'openai' => 'OpenAI',
                    'claude' => 'Claude',
                    'gemini' => 'Gemini',
                    'openrouter' => 'OpenRouter'
                ]
            ]
        );
        
        add_settings_field(
            'apcig_default_tone',
            __('Default Tone', 'contengen-ai-product-content-image-generator'),
            [$this, 'select_field_callback'],
            self::SETTINGS_PAGE,
            'apcig_default_settings',
            [
                'setting' => 'default_tone',
                'options' => [
                    'professional' => __('Professional', 'contengen-ai-product-content-image-generator'),
                    'friendly' => __('Friendly', 'contengen-ai-product-content-image-generator'),
                    'casual' => __('Casual', 'contengen-ai-product-content-image-generator'),
                    'luxury' => __('Luxury', 'contengen-ai-product-content-image-generator'),
                    'technical' => __('Technical', 'contengen-ai-product-content-image-generator'),
                    'persuasive' => __('Persuasive', 'contengen-ai-product-content-image-generator')
                ]
            ]
        );
        
        add_settings_field(
            'apcig_max_tokens',
            __('Max Tokens', 'contengen-ai-product-content-image-generator'),
            [$this, 'range_field_callback'],
            self::SETTINGS_PAGE,
            'apcig_generation_parameters',
            [
                'setting' => 'max_tokens',
                'min' => 100,
                'max' => 2000,
                'step' => 50
            ]
        );
        
        add_settings_field(
            'apcig_temperature',
            __('Temperature', 'contengen-ai-product-content-image-generator'),
            [$this, 'range_field_callback'],
            self::SETTINGS_PAGE,
            'apcig_generation_parameters',
            [
                'setting' => 'temperature',
                'min' => 0.1,
                'max' => 1.0,
                'step' => 0.1
            ]
        );
        
        $features = [
            'enable_seo_optimization' => __('SEO Optimization', 'contengen-ai-product-content-image-generator'),
            'enable_content_validation' => __('Content Validation', 'contengen-ai-product-content-image-generator'),
            'enable_duplicate_detection' => __('Duplicate Detection', 'contengen-ai-product-content-image-generator'),
            'auto_apply_content' => __('Auto-Apply Content', 'contengen-ai-product-content-image-generator'),
            'backup_original_content' => __('Backup Original Content', 'contengen-ai-product-content-image-generator')
        ];
        
        foreach ($features as $feature => $label) {
            add_settings_field(
                'apcig_' . $feature,
                $label,
                [$this, 'checkbox_field_callback'],
                self::SETTINGS_PAGE,
                'apcig_content_features',
                ['setting' => $feature]
            );
        }
    }
    
    /**
     * Get setting type
     */
    private function get_setting_type($setting_name) {
        $boolean_settings = [
            'enable_seo_optimization',
            'enable_content_validation', 
            'enable_duplicate_detection',
            'auto_apply_content',
            'backup_original_content'
        ];
        
        $integer_settings = [
            'max_tokens',
            'data_retention_days'
        ];
        
        $number_settings = [
            'temperature'
        ];
        
        if (in_array($setting_name, $boolean_settings)) {
            return 'boolean';
        } elseif (in_array($setting_name, $integer_settings)) {
            return 'integer';
        } elseif (in_array($setting_name, $number_settings)) {
            return 'number';
        }
        
        return 'string';
    }
    
    /**
     * Get setting description
     */
    private function get_setting_description($setting_name) {
        $descriptions = [
            'openai_api_key' => __('OpenAI API key for GPT models', 'contengen-ai-product-content-image-generator'),
            'claude_api_key' => __('Anthropic Claude API key', 'contengen-ai-product-content-image-generator'),
            'gemini_api_key' => __('Google Gemini API key', 'contengen-ai-product-content-image-generator'),
            'openrouter_api_key' => __('OpenRouter API key', 'contengen-ai-product-content-image-generator'),
            'default_provider' => __('Default AI provider for content generation', 'contengen-ai-product-content-image-generator'),
            'default_tone' => __('Default tone for generated content', 'contengen-ai-product-content-image-generator'),
            'default_language' => __('Default language for content generation', 'contengen-ai-product-content-image-generator'),
            'max_tokens' => __('Maximum tokens for AI generation', 'contengen-ai-product-content-image-generator'),
            'temperature' => __('Creativity level for AI generation', 'contengen-ai-product-content-image-generator'),
            'enable_seo_optimization' => __('Enable SEO optimization features', 'contengen-ai-product-content-image-generator'),
            'enable_content_validation' => __('Enable content validation', 'contengen-ai-product-content-image-generator'),
            'enable_duplicate_detection' => __('Enable duplicate content detection', 'contengen-ai-product-content-image-generator'),
            'auto_apply_content' => __('Automatically apply generated content', 'contengen-ai-product-content-image-generator'),
            'backup_original_content' => __('Backup original content before replacement', 'contengen-ai-product-content-image-generator'),
            'data_retention_days' => __('Number of days to retain generation data', 'contengen-ai-product-content-image-generator')
        ];
        
        return $descriptions[$setting_name] ?? '';
    }
    
    /**
     * Sanitize setting value
     * 
     * @param mixed $value The value to sanitize
     * @return mixed Sanitized value
     */
    public function sanitize_setting($value) {
        // Get the setting name from the current filter
        $current_filter = current_filter();
        $setting_name = str_replace(['sanitize_option_apcig_', 'sanitize_option_'], '', $current_filter);
        
        // Determine the appropriate sanitization based on setting type
        $type = $this->get_setting_type($setting_name);
        
        switch ($type) {
            case 'boolean':
                $value = (bool) $value;
                break;
            case 'integer':
                $value = absint($value);
                // Apply range validation for specific integer settings
                if ($setting_name === 'max_tokens') {
                    $value = max(100, min(4000, $value)); // Limit between 100 and 4000
                } elseif ($setting_name === 'data_retention_days') {
                    $value = max(1, min(365, $value)); // Limit between 1 and 365 days
                }
                break;
            case 'number':
                $value = floatval($value);
                // Apply range validation for temperature
                if ($setting_name === 'temperature') {
                    $value = max(0.0, min(1.0, $value)); // Clamp between 0.0 and 1.0
                }
                break;
            case 'string':
            default:
                // Check if it's an API key (sensitive data)
                if (strpos($setting_name, 'api_key') !== false) {
                    $value = sanitize_text_field($value);
                } else {
                    $value = sanitize_text_field($value);
                    
                    // Validate against allowed values for specific settings
                    $allowed_values = [
                        'default_provider' => ['openai', 'claude', 'gemini', 'openrouter'],
                        'default_tone' => ['professional', 'friendly', 'casual', 'luxury', 'technical', 'persuasive'],
                        'default_language' => ['en', 'es', 'fr', 'de', 'it', 'pt', 'nl', 'pl', 'ru', 'ja', 'zh', 'ko', 'ar']
                    ];
                    
                    if (isset($allowed_values[$setting_name])) {
                        if (!in_array($value, $allowed_values[$setting_name], true)) {
                            // Return default value if not in allowed list
                            $value = $this->default_settings[$setting_name] ?? '';
                        }
                    }
                }
                break;
        }
        
        // Apply additional filters for extensibility
        $value = apply_filters('apcig_sanitize_setting', $value, $setting_name);
        $value = apply_filters('apcig_sanitize_setting_' . $setting_name, $value);
        
        return $value;
    }
    
    /**
     * Handle settings saved action
     */
    public function handle_settings_saved($saved_settings) {
        wp_cache_flush();
        
        $this->update_provider_status_cache($saved_settings);
        
        do_action('apcig_after_settings_saved', $saved_settings);
    }
    
    /**
     * Update provider status cache
     */
    private function update_provider_status_cache($settings) {
        $providers = ['openai', 'claude', 'gemini', 'openrouter'];
        $status_cache = [];
        
        foreach ($providers as $provider) {
            $api_key = $settings[$provider . '_api_key'] ?? get_option('apcig_' . $provider . '_api_key', '');
            $status_cache[$provider] = !empty($api_key);
        }
        
        wp_cache_set('apcig_provider_status', $status_cache, 'apcig', HOUR_IN_SECONDS);
    }
    
    /**
     * Get setting value with default
     */
    public function get_setting($setting_name, $default = null) {
        if ($default === null) {
            $default = $this->default_settings[$setting_name] ?? '';
        }
        
        $value = get_option('apcig_' . $setting_name, $default);
        
        $value = apply_filters('apcig_get_setting_' . $setting_name, $value);
        $value = apply_filters('apcig_get_setting', $value, $setting_name);
        
        return $value;
    }
    
    /**
     * Get all settings
     */
    public function get_all_settings() {
        $settings = [];
        
        foreach ($this->default_settings as $setting_name => $default_value) {
            $settings[$setting_name] = $this->get_setting($setting_name, $default_value);
        }
        
        return apply_filters('apcig_get_all_settings', $settings);
    }
    
    /**
     * Section callbacks
     */
    public function ai_providers_section_callback() {
        echo '<p>' . esc_html__('Configure your AI provider API keys to start generating content.', 'contengen-ai-product-content-image-generator') . '</p>';
    }
    
    public function default_settings_section_callback() {
        echo '<p>' . esc_html__('Configure default options for content generation.', 'contengen-ai-product-content-image-generator') . '</p>';
    }
    
    public function generation_parameters_section_callback() {
        echo '<p>' . esc_html__('Fine-tune AI generation parameters for optimal results.', 'contengen-ai-product-content-image-generator') . '</p>';
    }
    
    public function content_features_section_callback() {
        echo '<p>' . esc_html__('Enable advanced content processing features.', 'contengen-ai-product-content-image-generator') . '</p>';
    }
    
    /**
     * Field callbacks
     */
    public function api_key_field_callback($args) {
        $provider = $args['provider'];
        $value = $this->get_setting($provider . '_api_key');
        
        printf(
            '<input type="password" name="apcig_%s_api_key" value="%s" class="regular-text" />',
            esc_attr($provider),
            esc_attr($value)
        );
    }
    
    public function select_field_callback($args) {
        $setting = $args['setting'];
        $options = $args['options'];
        $value = $this->get_setting($setting);
        
        printf('<select name="apcig_%s">', esc_attr($setting));
        
        foreach ($options as $option_value => $option_label) {
            printf(
                '<option value="%s" %s>%s</option>',
                esc_attr($option_value),
                selected($value, $option_value, false),
                esc_html($option_label)
            );
        }
        
        echo '</select>';
    }
    
    public function range_field_callback($args) {
        $setting = $args['setting'];
        $min = $args['min'];
        $max = $args['max'];
        $step = $args['step'];
        $value = $this->get_setting($setting);
        
        printf(
            '<input type="range" name="apcig_%s" min="%s" max="%s" step="%s" value="%s" />',
            esc_attr($setting),
            esc_attr($min),
            esc_attr($max),
            esc_attr($step),
            esc_attr($value)
        );
        
        printf('<span class="range-value">%s</span>', esc_html($value));
    }
    
    public function checkbox_field_callback($args) {
        $setting = $args['setting'];
        $value = $this->get_setting($setting);
        
        printf(
            '<input type="checkbox" name="apcig_%s" value="1" %s />',
            esc_attr($setting),
            checked($value, true, false)
        );
    }
}