<?php
/**
 * Settings management class
 */
class Nietos_AI_Settings {

    /**
     * Option name
     */
    const OPTION_NAME = 'nietos_ai_settings';

    /**
     * Security instance
     */
    private $security;

    /**
     * Constructor
     */
    public function __construct() {
        $this->security = new Nietos_AI_Security();
    }

    /**
     * Register settings
     */
    public function register_settings() {
        register_setting('nietos_ai_settings', self::OPTION_NAME, array(
            'sanitize_callback' => array($this, 'sanitize_settings')
        ));
    }

    /**
     * Get all settings
     */
    public function get_settings() {
        $settings = get_option(self::OPTION_NAME, array());

        $defaults = array(
            'api_key' => '',
            'model' => 'gpt-4o',
            'max_tokens' => 4096,
            'temperature' => 0.7
        );

        $settings = wp_parse_args($settings, $defaults);

        return $settings;
    }

    /**
     * Get specific setting
     */
    public function get_setting($key, $default = null) {
        $settings = $this->get_settings();
        return isset($settings[$key]) ? $settings[$key] : $default;
    }

    /**
     * Update settings
     */
    public function update_settings($new_settings) {
        $current_settings = $this->get_settings();
        $updated_settings = wp_parse_args($new_settings, $current_settings);

        // Encrypt API key if provided and clear validation status
        if (!empty($updated_settings['api_key'])) {
            $updated_settings['api_key'] = $this->security->encrypt_api_key($updated_settings['api_key']);
            // Clear validation when API key changes
            $this->clear_api_key_validation();
        }

        return update_option(self::OPTION_NAME, $updated_settings);
    }

    /**
     * Get decrypted API key
     */
    public function get_api_key() {
        $settings = $this->get_settings();
        if (empty($settings['api_key'])) {
            return '';
        }

        return $this->security->decrypt_api_key($settings['api_key']);
    }

    /**
     * Check if plugin is configured with API key
     */
    public function is_configured() {
        $api_key = $this->get_api_key();
        return !empty($api_key);
    }

    /**
     * Check if API key has been validated successfully
     */
    public function is_api_key_valid() {
        if (!$this->is_configured()) {
            return false;
        }

        // Check if we have a recent successful validation (within 24 hours)
        $last_validation = get_option('nietos_ai_api_validated', 0);
        $validation_age = time() - $last_validation;

        // Valid if validated within last 24 hours
        return $validation_age < DAY_IN_SECONDS;
    }

    /**
     * Mark API key as validated
     */
    public function mark_api_key_validated() {
        update_option('nietos_ai_api_validated', time());
    }

    /**
     * Clear API key validation status
     */
    public function clear_api_key_validation() {
        delete_option('nietos_ai_api_validated');
    }

    /**
     * Sanitize settings before saving
     */
    public function sanitize_settings($settings) {
        if (!is_array($settings)) {
            return array();
        }

        $sanitized = array();

        // API key (don't sanitize, will be encrypted)
        if (isset($settings['api_key'])) {
            $sanitized['api_key'] = $settings['api_key'];
        }

        // Model
        if (isset($settings['model'])) {
            $sanitized['model'] = sanitize_text_field($settings['model']);
        }

        // Max tokens - validate range (100 to 128000)
        if (isset($settings['max_tokens'])) {
            $max_tokens = absint($settings['max_tokens']);
            $sanitized['max_tokens'] = max(100, min(128000, $max_tokens));
        }

        // Temperature - validate range (0.0 to 2.0)
        if (isset($settings['temperature'])) {
            $temperature = floatval($settings['temperature']);
            $sanitized['temperature'] = max(0.0, min(2.0, $temperature));
        }

        return $sanitized;
    }

    /**
     * Get available models
     */
    public function get_available_models() {
        // Try to get cached models first
        $cache_key = 'nietos_ai_models_openai';
        $cached_models = get_transient($cache_key);

        if ($cached_models !== false) {
            return $cached_models;
        }

        // Fetch models from API
        $models = $this->fetch_openai_models();

        // Cache for 24 hours
        if (!empty($models)) {
            set_transient($cache_key, $models, DAY_IN_SECONDS);
        }

        return $models;
    }

    /**
     * Fetch OpenAI models from API
     */
    private function fetch_openai_models() {
        $api_key = $this->get_api_key();

        if (empty($api_key)) {
            return $this->get_fallback_models();
        }

        $response = wp_remote_get('https://api.openai.com/v1/models', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
            ),
            'timeout' => 10
        ));

        if (is_wp_error($response)) {
            return $this->get_fallback_models();
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);

        if (empty($body['data'])) {
            return $this->get_fallback_models();
        }

        // Only include these specific models (most useful ones)
        $allowed_models = array(
            'gpt-4o',
            'gpt-4o-mini',
            'gpt-4-turbo',
            'gpt-4',
            'gpt-3.5-turbo'
        );

        $models = array();

        foreach ($body['data'] as $model) {
            $model_id = $model['id'];

            // Only include allowed models
            if (in_array($model_id, $allowed_models)) {
                $models[$model_id] = $this->format_model_name($model_id);
            }
        }

        // Sort models in preferred order
        $ordered_models = array();
        foreach ($allowed_models as $model_id) {
            if (isset($models[$model_id])) {
                $ordered_models[$model_id] = $models[$model_id];
            }
        }

        return !empty($ordered_models) ? $ordered_models : $this->get_fallback_models();
    }

    /**
     * Get fallback models if API fetch fails
     */
    private function get_fallback_models() {
        return array(
            'gpt-4o' => 'GPT-4o (Newest)',
            'gpt-4o-mini' => 'GPT-4o Mini (Fast)',
            'gpt-4-turbo' => 'GPT-4 Turbo',
            'gpt-4' => 'GPT-4',
            'gpt-3.5-turbo' => 'GPT-3.5 Turbo'
        );
    }

    /**
     * Format model name for display
     */
    private function format_model_name($model_id) {
        // Convert model ID to readable name
        $name = str_replace('-', ' ', $model_id);
        $name = ucwords($name);

        // Special formatting
        $name = str_replace('Gpt', 'GPT', $name);
        $name = str_replace('4o', '4o', $name);

        return $name;
    }

    /**
     * Clear models cache
     */
    public function clear_models_cache() {
        delete_transient('nietos_ai_models_openai');
    }
}
