<?php

namespace Unlockafe_addons\Admin;

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

/**
 * Text Generator Settings
 * 
 * Handles the settings page for the Text Generator
 * 
 * @since 1.0.0
 */
class Text_Generator_Settings {

    /**
     * Settings instance
     * 
     * @var null|Text_Generator_Settings
     */
    private static $instance = null;
    
    /**
     * Whether debug logging is enabled
     * 
     * @var bool
     */
    private $debug_logging = false;

    /**
     * Settings option name
     * 
     * @var string
     */
    private $option_name = 'unlockafe_text_generator_settings';

    /**
     * Settings defaults
     * 
     * @var array
     */
    private $defaults = [
        'api_endpoint' => '',
        'model' => 'gpt-3.5-turbo',
        'max_tokens' => 2000,
        'temperature' => 0.7,
        'api_provider' => 'openai', // Default to OpenAI for better user experience
        'openai_api_key' => '',
        'top_p' => 1
    ];

    /**
     * Constructor
     */
    private function __construct() {
        // Initialize debug mode based on WordPress debug settings
        $this->debug_logging = defined('WP_DEBUG') && WP_DEBUG;
        
        // Register the settings page - DISABLED to remove menu item
        // add_action('admin_menu', [$this, 'add_settings_page']);
        
        // Register settings
        add_action('admin_init', [$this, 'register_settings']);
        
        // Register REST API endpoint for React admin
        add_action('rest_api_init', [$this, 'register_rest_routes']);
        
        // Add AJAX action for API testing in admin
        add_action('wp_ajax_unlockafe_test_api_connection', [$this, 'test_api_connection_ajax']);
        
        // Add script to handle smooth navigation between PHP and React pages
        add_action('admin_footer', function() {
            // Only add on our plugin's admin pages
            $screen = get_current_screen();
            if (strpos($screen->id, 'unlock-addons') !== false || strpos($screen->id, 'unlockafe') !== false) {
                ?>
                <script>
                document.addEventListener('DOMContentLoaded', function() {
                    // Improve navigation between PHP and React pages
                    const pluginLinks = document.querySelectorAll('#adminmenu a[href*="unlock-addons"], #adminmenu a[href*="unlockafe"]');
                    pluginLinks.forEach(link => {
                        // Ensure the React container is properly reinitialized when navigating
                        link.addEventListener('click', function() {
                            // If we have the unlockAddonsData object, update it to reflect the current page
                            if (typeof window.unlockAddonsData !== 'undefined') {
                                const url = new URL(this.href);
                                window.unlockAddonsData.currentPage = url.searchParams.get('page');
                            }
                        });
                    });
                });
                </script>
                <?php
            }
        });
    }

    /**
     * Get instance
     * 
     * @return Text_Generator_Settings
     */
    public static function getInstance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Add settings page
     */
    public function add_settings_page() {
        add_submenu_page(
            'unlock-addons', // Changed from 'elementor' to your plugin's menu
            __('Text Generator Settings', 'unlock-addons-for-elementor'),
            __('Text Generator', 'unlock-addons-for-elementor'),
            'manage_options',
            'unlockafe-text-generator',
            [$this, 'render_settings_page']
        );
    }

    /**
     * Register settings
     */
    public function register_settings() {
        register_setting(
            'unlockafe_text_generator',
            $this->option_name,
            [
                'sanitize_callback' => [$this, 'sanitize_settings'],
                'default' => $this->defaults
            ]
        );
        
        add_settings_section(
            'unlockafe_text_generator_section',
            __('API Settings', 'unlock-addons-for-elementor'),
            [$this, 'render_section_description'],
            'unlockafe_text_generator'
        );
        
        add_settings_field(
            'api_provider',
            __('API Provider', 'unlock-addons-for-elementor'),
            [$this, 'render_api_provider_field'],
            'unlockafe_text_generator',
            'unlockafe_text_generator_section'
        );
        
        add_settings_field(
            'api_endpoint',
            __('API Endpoint', 'unlock-addons-for-elementor'),
            [$this, 'render_api_endpoint_field'],
            'unlockafe_text_generator',
            'unlockafe_text_generator_section'
        );
        
        add_settings_field(
            'openai_api_key',
            __('OpenAI API Key', 'unlock-addons-for-elementor'),
            [$this, 'render_openai_api_key_field'],
            'unlockafe_text_generator',
            'unlockafe_text_generator_section'
        );
        
        add_settings_field(
            'model',
            __('Model', 'unlock-addons-for-elementor'),
            [$this, 'render_model_field'],
            'unlockafe_text_generator',
            'unlockafe_text_generator_section'
        );
        
        add_settings_field(
            'max_tokens',
            __('Max Tokens', 'unlock-addons-for-elementor'),
            [$this, 'render_max_tokens_field'],
            'unlockafe_text_generator',
            'unlockafe_text_generator_section'
        );
        
        add_settings_field(
            'temperature',
            __('Temperature', 'unlock-addons-for-elementor'),
            [$this, 'render_temperature_field'],
            'unlockafe_text_generator',
            'unlockafe_text_generator_section'
        );
    }

    /**
     * Sanitize settings
     * 
     * @param array $input Settings input
     * @return array Sanitized settings
     */
    public function sanitize_settings($input) {
        $sanitized = [];
        
        if (isset($input['api_endpoint'])) {
            $sanitized['api_endpoint'] = esc_url_raw($input['api_endpoint']);
        }
        
        if (isset($input['model'])) {
            $sanitized['model'] = sanitize_text_field($input['model']);
        }
        
        if (isset($input['max_tokens'])) {
            $sanitized['max_tokens'] = intval($input['max_tokens']);
        }
        
        if (isset($input['temperature'])) {
            $sanitized['temperature'] = floatval($input['temperature']);
            if ($sanitized['temperature'] < 0) {
                $sanitized['temperature'] = 0;
            } elseif ($sanitized['temperature'] > 1) {
                $sanitized['temperature'] = 1;
            }
        }
        
        if (isset($input['api_provider'])) {
            $sanitized['api_provider'] = sanitize_text_field($input['api_provider']);
        }
        
        if (isset($input['openai_api_key'])) {
            $sanitized['openai_api_key'] = sanitize_text_field($input['openai_api_key']);
        }
        
        return $sanitized;
    }

    /**
     * Render section description
     */
    public function render_section_description() {
        echo '<p>' . esc_html__('Configure the settings for the Text Generator API connection.', 'unlock-addons-for-elementor') . '</p>';
    }

    /**
     * Render API provider field
     */
    public function render_api_provider_field() {
        $options = get_option($this->option_name, $this->defaults);
        $value = isset($options['api_provider']) ? $options['api_provider'] : $this->defaults['api_provider'];
        ?>
        <select name="<?php echo esc_attr($this->option_name); ?>[api_provider]" class="regular-text">
            <option value="custom" <?php selected($value, 'custom'); ?>><?php esc_html_e('Custom API', 'unlock-addons-for-elementor'); ?></option>
            <option value="openai" <?php selected($value, 'openai'); ?>><?php esc_html_e('OpenAI', 'unlock-addons-for-elementor'); ?></option>
        </select>
        <p class="description"><?php esc_html_e('Select the API provider for the Text Generator.', 'unlock-addons-for-elementor'); ?></p>
        <?php
    }

    /**
     * Render API endpoint field
     */
    public function render_api_endpoint_field() {
        $options = get_option($this->option_name, $this->defaults);
        $value = isset($options['api_endpoint']) ? $options['api_endpoint'] : $this->defaults['api_endpoint'];
        ?>
        <input type="url" name="<?php echo esc_attr($this->option_name); ?>[api_endpoint]" value="<?php echo esc_attr($value); ?>" class="regular-text">
        <p class="description"><?php esc_html_e('Enter the URL of your LLM API endpoint.', 'unlock-addons-for-elementor'); ?></p>
        <?php
    }

    /**
     * Render OpenAI API key field
     */
    public function render_openai_api_key_field() {
        $options = get_option($this->option_name, $this->defaults);
        $value = isset($options['openai_api_key']) ? $options['openai_api_key'] : $this->defaults['openai_api_key'];
        ?>
        <input type="text" name="<?php echo esc_attr($this->option_name); ?>[openai_api_key]" value="<?php echo esc_attr($value); ?>" class="regular-text">
        <p class="description"><?php esc_html_e('Enter your OpenAI API key.', 'unlock-addons-for-elementor'); ?></p>
        <?php
    }

    /**
     * Render model field
     */
    public function render_model_field() {
        $options = get_option($this->option_name, $this->defaults);
        $value = isset($options['model']) ? $options['model'] : $this->defaults['model'];
        $api_provider = isset($options['api_provider']) ? $options['api_provider'] : $this->defaults['api_provider'];
        ?>
        <div class="custom-api-models" style="<?php echo $api_provider === 'custom' ? 'display:block;' : 'display:none;'; ?>">
            <select name="<?php echo esc_attr($this->option_name); ?>[model]" class="regular-text custom-model-select">
                <option value="llama3" <?php selected($value, 'llama3'); ?>><?php esc_html_e('Llama 3', 'unlock-addons-for-elementor'); ?></option>
                <option value="mistral" <?php selected($value, 'mistral'); ?>><?php esc_html_e('Mistral', 'unlock-addons-for-elementor'); ?></option>
                <option value="gemma" <?php selected($value, 'gemma'); ?>><?php esc_html_e('Gemma', 'unlock-addons-for-elementor'); ?></option>
            </select>
        </div>
        <div class="openai-models" style="<?php echo $api_provider === 'openai' ? 'display:block;' : 'display:none;'; ?>">
            <select name="<?php echo esc_attr($this->option_name); ?>[model]" class="regular-text openai-model-select">
                <option value="gpt-3.5-turbo" <?php selected($value, 'gpt-3.5-turbo'); ?>><?php esc_html_e('GPT-3.5 Turbo', 'unlock-addons-for-elementor'); ?></option>
                <option value="gpt-4o" <?php selected($value, 'gpt-4o'); ?>><?php esc_html_e('GPT-4o', 'unlock-addons-for-elementor'); ?></option>
                <option value="gpt-4-turbo" <?php selected($value, 'gpt-4-turbo'); ?>><?php esc_html_e('GPT-4 Turbo', 'unlock-addons-for-elementor'); ?></option>
            </select>
        </div>
        <p class="description"><?php esc_html_e('Select the model to use for text generation.', 'unlock-addons-for-elementor'); ?></p>
        <?php
    }

    /**
     * Render max tokens field
     */
    public function render_max_tokens_field() {
        $options = get_option($this->option_name, $this->defaults);
        $value = isset($options['max_tokens']) ? $options['max_tokens'] : $this->defaults['max_tokens'];
        ?>
        <input type="number" name="<?php echo esc_attr($this->option_name); ?>[max_tokens]" value="<?php echo esc_attr($value); ?>" class="small-text" min="1" step="1">
        <p class="description"><?php esc_html_e('Maximum number of tokens to generate.', 'unlock-addons-for-elementor'); ?></p>
        <?php
    }

    /**
     * Render temperature field
     */
    public function render_temperature_field() {
        $options = get_option($this->option_name, $this->defaults);
        $value = isset($options['temperature']) ? $options['temperature'] : $this->defaults['temperature'];
        ?>
        <input type="number" name="<?php echo esc_attr($this->option_name); ?>[temperature]" value="<?php echo esc_attr($value); ?>" class="small-text" min="0" max="1" step="0.1">
        <p class="description"><?php esc_html_e('Controls randomness. Lower values are more focused and deterministic (0-1).', 'unlock-addons-for-elementor'); ?></p>
        <?php
    }

    /**
     * Render settings page
     */
    public function render_settings_page() {
        if (!current_user_can('manage_options')) {
            return;
        }
        
        // Render the settings form
        ?>
        <div class="wrap">
            <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
            <form action="options.php" method="post">
                <?php
                settings_fields('unlockafe_text_generator');
                do_settings_sections('unlockafe_text_generator');
                submit_button(__('Save Settings', 'unlock-addons-for-elementor'));
                ?>
            </form>
            
            <div class="card" style="max-width: 600px; margin-top: 20px;">
                <h2><?php esc_html_e('Testing the API Connection', 'unlock-addons-for-elementor'); ?></h2>
                <p><?php esc_html_e('You can test your API connection by clicking the button below.', 'unlock-addons-for-elementor'); ?></p>
                <button id="unlockafe-test-api" class="button button-secondary">
                    <?php esc_html_e('Test API Connection', 'unlock-addons-for-elementor'); ?>
                </button>
                <div id="unlockafe-test-result" style="margin-top: 10px; padding: 10px; border-radius: 4px; display: none;"></div>
            </div>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            // Toggle fields based on API provider selection
            function toggleApiFields() {
                var provider = $('select[name="<?php echo esc_attr($this->option_name); ?>[api_provider]"]').val();
                
                if (provider === 'custom') {
                    $('.custom-api-models').show();
                    $('.openai-models').hide();
                    $('input[name="<?php echo esc_attr($this->option_name); ?>[api_endpoint]"]').closest('tr').show();
                    $('input[name="<?php echo esc_attr($this->option_name); ?>[openai_api_key]"]').closest('tr').hide();
                } else if (provider === 'openai') {
                    $('.custom-api-models').hide();
                    $('.openai-models').show();
                    $('input[name="<?php echo esc_attr($this->option_name); ?>[api_endpoint]"]').closest('tr').hide();
                    $('input[name="<?php echo esc_attr($this->option_name); ?>[openai_api_key]"]').closest('tr').show();
                }
            }
            
            // Initial toggle
            toggleApiFields();
            
            // Listen for changes
            $('select[name="<?php echo esc_attr($this->option_name); ?>[api_provider]"]').on('change', function() {
                toggleApiFields();
            });
            
            $('#unlockafe-test-api').on('click', function(e) {
                e.preventDefault();
                
                // Show loading state
                var $button = $(this);
                var originalText = $button.text();
                $button.text('Testing...');
                $button.prop('disabled', true);
                
                var $result = $('#unlockafe-test-result');
                $result.hide();
                
                // Make an AJAX call to test the API
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'unlockafe_test_api_connection',
                        nonce: '<?php echo esc_js(wp_create_nonce('unlockafe_test_api_connection')); ?>'
                    },
                    success: function(response) {
                        $button.text(originalText);
                        $button.prop('disabled', false);
                        
                        if (response.success) {
                            $result.html('<p style="color: green;">' + response.data + '</p>');
                            $result.css('background-color', '#f0fff0');
                            $result.css('border', '1px solid #c3e6cb');
                        } else {
                            $result.html('<p style="color: red;">' + response.data + '</p>');
                            $result.css('background-color', '#fff0f0');
                            $result.css('border', '1px solid #e6c3c3');
                        }
                        
                        $result.show();
                    },
                    error: function() {
                        $button.text(originalText);
                        $button.prop('disabled', false);
                        
                        $result.html('<p style="color: red;">An error occurred while testing the API connection.</p>');
                        $result.css('background-color', '#fff0f0');
                        $result.css('border', '1px solid #e6c3c3');
                        $result.show();
                    }
                });
            });
        });
        </script>
        <?php
    }

    /**
     * Test API connection via AJAX
     */
    public function test_api_connection_ajax() {
        // Verify nonce
        $nonce = isset($_POST['nonce']) ? wp_unslash(sanitize_key($_POST['nonce'])) : '';
        if (empty($nonce) || !wp_verify_nonce($nonce, 'unlockafe_test_api_connection')) {
            wp_send_json_error('Security check failed');
            return;
        }
        
        // Get settings
        $settings = $this->get_settings();
        
        // Check for required settings
        if (empty($settings['api_endpoint']) && $settings['api_provider'] === 'custom') {
            wp_send_json_error('API endpoint is not set');
            return;
        }
        
        if (empty($settings['openai_api_key']) && $settings['api_provider'] === 'openai') {
            wp_send_json_error('OpenAI API key is not set');
            return;
        }
        
        // Test the API connection
        if ($settings['api_provider'] === 'custom') {
            try {
                $response = wp_remote_post($settings['api_endpoint'], [
                    'headers' => [
                        'Content-Type' => 'application/json',
                    ],
                    'body' => json_encode([
                        'model' => $settings['model'],
                        'prompt' => 'Hello world!',
                        'max_tokens' => 5,
                    ]),
                    'timeout' => 15,
                ]);
                
                if (is_wp_error($response)) {
                    wp_send_json_error('Error connecting to API: ' . $response->get_error_message());
                    return;
                }
                
                $status = wp_remote_retrieve_response_code($response);
                if ($status !== 200) {
                    wp_send_json_error('API returned error status: ' . $status);
                    return;
                }
                
                wp_send_json_success('API connection successful!');
            } catch (\Exception $e) {
                wp_send_json_error('Error: ' . $e->getMessage());
            }
        } else { // OpenAI
            try {
                $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
                    'headers' => [
                        'Authorization' => 'Bearer ' . $settings['openai_api_key'],
                        'Content-Type' => 'application/json',
                    ],
                    'body' => json_encode([
                        'model' => $settings['model'],
                        'messages' => [['role' => 'user', 'content' => 'Hello world!']],
                        'max_tokens' => 5,
                    ]),
                    'timeout' => 15,
                ]);
                
                if (is_wp_error($response)) {
                    wp_send_json_error('Error connecting to OpenAI: ' . $response->get_error_message());
                    return;
                }
                
                $status = wp_remote_retrieve_response_code($response);
                if ($status !== 200) {
                    wp_send_json_error('OpenAI API returned error status: ' . $status);
                    return;
                }
                
                wp_send_json_success('OpenAI API connection successful!');
            } catch (\Exception $e) {
                wp_send_json_error('Error: ' . $e->getMessage());
            }
        }
    }

    /**
     * Register REST API routes for React admin
     */
    public function register_rest_routes() {
        // Debug: Log when this method is called
        error_log('Registering REST routes for Text Generator Settings');
        
        register_rest_route('unlockafe/v1', '/text-generator-settings', [
            [
                'methods' => 'GET',
                'callback' => [$this, 'get_settings_api'],
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                }
            ],
            [
                'methods' => 'POST',
                'callback' => [$this, 'update_settings_api'],
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                }
            ],
        ]);
        
        register_rest_route('unlockafe/v1', '/test-api-connection', [
            [
                'methods' => 'POST',
                'callback' => [$this, 'test_api_connection_api'],
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                }
            ],
        ]);
    }
    
    /**
     * Get settings via API
     * 
     * @return WP_REST_Response
     */
    public function get_settings_api() {
        $settings = $this->get_settings();
        
        // Don't expose sensitive info like API keys in response
        if (isset($settings['openai_api_key']) && !empty($settings['openai_api_key'])) {
            $settings['openai_api_key'] = '••••••••••••••••';
            $settings['has_openai_key'] = true;
        } else {
            $settings['has_openai_key'] = false;
        }
        
        return rest_ensure_response($settings);
    }
    
    /**
     * Update settings via API
     * 
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function update_settings_api($request) {
        // Check permissions
        if (!current_user_can('manage_options')) {
            return rest_ensure_response([
                'success' => false,
                'message' => 'You do not have permission to update settings'
            ]);
        }
        
        // Get the request body
        $body = $request->get_json_params();
        
        // Get existing settings
        $existing = $this->get_settings();
        
        // Updated settings
        $updated = [];
        
        // Handle API provider (must be either 'openai' or 'custom')
        if (isset($body['api_provider'])) {
            $api_provider = sanitize_text_field($body['api_provider']);
            if ($api_provider === 'openai' || $api_provider === 'custom') {
                $updated['api_provider'] = $api_provider;
            } else {
                $updated['api_provider'] = 'custom'; // Default to custom if invalid
            }
        } else {
            $updated['api_provider'] = $existing['api_provider'];
        }
        
        // API endpoint (required for custom provider)
        if (isset($body['api_endpoint'])) {
            $updated['api_endpoint'] = esc_url_raw($body['api_endpoint']);
        } else {
            $updated['api_endpoint'] = $existing['api_endpoint'];
        }
        
        // OpenAI API key (don't overwrite if not provided)
        if (isset($body['openai_api_key']) && !empty($body['openai_api_key'])) {
            // Only update if not the masked value
            if (!preg_match('/^[•]+$/', $body['openai_api_key'])) {
                $updated['openai_api_key'] = sanitize_text_field($body['openai_api_key']);
            } else {
                $updated['openai_api_key'] = $existing['openai_api_key'];
            }
        } else {
            $updated['openai_api_key'] = $existing['openai_api_key'];
        }
        
        // Model
        if (isset($body['model'])) {
            $updated['model'] = sanitize_text_field($body['model']);
        } else {
            $updated['model'] = $existing['model'];
        }
        
        // Max tokens
        if (isset($body['max_tokens'])) {
            $updated['max_tokens'] = intval($body['max_tokens']);
        } else {
            $updated['max_tokens'] = $existing['max_tokens'];
        }
        
        // Temperature
        if (isset($body['temperature'])) {
            $temp = floatval($body['temperature']);
            $updated['temperature'] = min(max($temp, 0), 1); // Ensure between 0 and 1
        } else {
            $updated['temperature'] = $existing['temperature'];
        }
        
        // Save the updated settings
        update_option($this->option_name, $updated);
        
        // Get the updated settings to return
        $settings = $this->get_settings();
        
        // Include safe version for frontend
        $safe_settings = $settings;
        if (!empty($safe_settings['openai_api_key'])) {
            $safe_settings['has_openai_key'] = true;
            $safe_settings['openai_api_key'] = '••••••••••••••••';
        } else {
            $safe_settings['has_openai_key'] = false;
        }
        
        error_log('Settings updated. API provider: ' . $settings['api_provider']);
        
        return rest_ensure_response([
            'success' => true,
            'message' => 'Settings updated successfully',
            'settings' => $safe_settings
        ]);
    }

    /**
     * Test API connection via API
     * 
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function test_api_connection_api($request) {
        // Get parameters from the request
        $params = $request->get_params();
        
        // Get existing settings
        $current_settings = $this->get_settings();
        
        // Merge with provided params - this ensures we use the settings from the React form
        if (!empty($params)) {
            $merged_settings = array_merge($current_settings, $params);
            
            // If API key contains placeholder bullets, use the saved one
            if (isset($merged_settings['openai_api_key']) && strpos($merged_settings['openai_api_key'], '•') !== false) {
                $merged_settings['openai_api_key'] = $current_settings['openai_api_key'];
            }
        } else {
            $merged_settings = $current_settings;
        }
        
        // Log the test connection request
        error_log('Testing API connection with provider: ' . ($merged_settings['api_provider'] ?? 'not set'));
        
        // Determine which API to test based on the provider
        $api_provider = isset($merged_settings['api_provider']) ? $merged_settings['api_provider'] : 'custom';
        
        if ($api_provider === 'openai') {
            // Check if OpenAI API key is set
            if (empty($merged_settings['openai_api_key'])) {
                return rest_ensure_response([
                    'success' => false,
                    'message' => 'OpenAI API key is not set. Please enter your API key and save settings.'
                ]);
            }
            
            // Test OpenAI connection
            $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Bearer ' . $merged_settings['openai_api_key'],
                ],
                'body' => wp_json_encode([
                    'model' => $merged_settings['model'],
                    'messages' => [
                        [
                            'role' => 'user',
                            'content' => 'Hello, this is a test message to verify API connectivity.'
                        ]
                    ],
                    'max_tokens' => 10,
                ]),
                'timeout' => 15,
            ]);
            
            if (is_wp_error($response)) {
                return rest_ensure_response([
                    'success' => false,
                    'message' => 'OpenAI connection failed: ' . $response->get_error_message()
                ]);
            }
            
            $response_code = wp_remote_retrieve_response_code($response);
            $response_body = wp_remote_retrieve_body($response);
            $response_data = json_decode($response_body, true);
            
            if ($response_code !== 200) {
                $error_message = isset($response_data['error']['message']) ? $response_data['error']['message'] : 'API returned an error (' . $response_code . ')';
                return rest_ensure_response([
                    'success' => false,
                    'message' => 'OpenAI API error: ' . $error_message
                ]);
            }
            
            return rest_ensure_response([
                'success' => true,
                'message' => 'OpenAI API connection successful! Your API key is working properly.'
            ]);
        } else {
            // Custom API
            if (empty($merged_settings['api_endpoint'])) {
                return rest_ensure_response([
                    'success' => false,
                    'message' => 'API endpoint is not set. Please enter your API endpoint and save settings.'
                ]);
            }
            
            // Ensure the endpoint has the right format
            $api_endpoint = $merged_settings['api_endpoint'];
            if (substr($api_endpoint, -1) !== '/') {
                $api_endpoint .= '/';
            }
            $api_endpoint .= 'api/generate';
            
            // Test the custom API
            $response = wp_remote_post($api_endpoint, [
                'headers' => [
                    'Content-Type' => 'application/json',
                ],
                'body' => wp_json_encode([
                    'model' => $merged_settings['model'], 
                    'prompt' => 'Hello, this is a test message to verify API connectivity.',
                    'stream' => false,
                    'max_tokens' => 10,
                    'temperature' => $merged_settings['temperature'],
                ]),
                'timeout' => 15,
            ]);
            
            if (is_wp_error($response)) {
                return rest_ensure_response([
                    'success' => false,
                    'message' => 'API connection failed: ' . $response->get_error_message()
                ]);
            }
            
            $response_code = wp_remote_retrieve_response_code($response);
            
            if ($response_code !== 200) {
                return rest_ensure_response([
                    'success' => false,
                    'message' => 'API returned an error (' . $response_code . ')'
                ]);
            }
            
            return rest_ensure_response([
                'success' => true,
                'message' => 'API connection successful!'
            ]);
        }
    }

    /**
     * Get settings
     * 
     * @return array Settings
     */
    public function get_settings() {
        $settings = get_option($this->option_name, $this->defaults);
        
        // Ensure api_provider is valid (either 'openai' or 'custom')
        if (!isset($settings['api_provider']) || ($settings['api_provider'] !== 'openai' && $settings['api_provider'] !== 'custom')) {
            $settings['api_provider'] = 'custom'; // Default to custom if invalid
        }
        
        // Log to help with debugging
        error_log('Current Text Generator API provider setting: ' . $settings['api_provider']);
        error_log('OpenAI API Key set: ' . (!empty($settings['openai_api_key']) ? 'Yes' : 'No'));
        
        return $settings;
    }
    
    /**
     * Refresh settings from database
     * This ensures we're not using cached values
     */
    public function refresh_settings() {
        // Clear WordPress option cache for this option
        wp_cache_delete($this->option_name, 'options');
        
        // Log the settings being refreshed
        $settings = get_option($this->option_name, $this->defaults);
        error_log('Refreshed settings: ' . json_encode($settings));
    }
}

// Initialize the settings
Text_Generator_Settings::getInstance();
