<?php

namespace Unlockafe_addons\API;

use Unlockafe_addons\Admin\Text_Generator_Settings;

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

/**
 * Text Generator API Handler
 * Handles communication with the LLM API
 *
 * @since 1.0.0
 */
class Text_Generator_API {

    /**
     * LLM API endpoint
     * 
     * @var string
     */
    private $api_endpoint;

    /**
     * LLM model settings
     * 
     * @var array
     */
    private $settings;

    /**
     * Instance property
     */
    private static $instance = null;
    
    /**
     * Whether debug logging is enabled
     * 
     * @var bool
     */
    private $debug_logging = false;

    /**
     * Constructor
     */
    private function __construct() {
        // Get settings
        $settings_instance = Text_Generator_Settings::getInstance();
        $this->settings = $settings_instance->get_settings();
        
        // Initialize debug mode based on WordPress debug settings
        $this->debug_logging = defined('WP_DEBUG') && WP_DEBUG;
        
        // We'll set the endpoint dynamically when making requests based on the provider
        
        // Register AJAX handlers
        add_action('wp_ajax_unlockafe_generate_text', [$this, 'generate_text']);
        add_action('wp_ajax_nopriv_unlockafe_generate_text', [$this, 'generate_text']);
        add_action('wp_ajax_unlockafe_test_api_connection', [$this, 'test_api_connection']);
        
        // Enqueue scripts for both admin and frontend
        add_action('elementor/editor/after_enqueue_scripts', [$this, 'enqueue_editor_scripts']);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_frontend_scripts']);
        
        // Add the nonce to the footer as a global JS variable for maximum reliability
        add_action('wp_footer', [$this, 'output_nonce_to_footer']);
    }

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

    /**
     * Enqueue editor scripts
     */
    public function enqueue_editor_scripts() {
        // Enqueue the editor.js file
        wp_enqueue_script(
            'unlockafe-text-generator-editor',
            UNLOCKAFE_ASSETS . 'front-end/js/text-generator-editor.js',
            ['jquery', 'elementor-editor'],
            UNLOCKAFE_VERSION,
            true
        );
        
        // Localize the script with necessary data
        wp_localize_script(
            'unlockafe-text-generator-editor',
            'unlockafe_text_generator',
            [
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('unlockafe_text_generator_nonce'),
                'version' => UNLOCKAFE_VERSION,
                'debug' => defined('WP_DEBUG') && WP_DEBUG,
            ]
        );
    }
    
    /**
     * Enqueue frontend scripts
     * This ensures the main text-generator.js has access to the correct nonce
     */
    public function enqueue_frontend_scripts() {
        // We don't explicitly enqueue the main script as it's loaded by Elementor
        // But we need to make sure it has access to the nonce
        
        // Add the localized script data
        wp_localize_script(
            'unlockafe-text-generator', // This matches the handle used when registering in Widget_manager
            'unlockafe_text_generator',
            [
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('unlockafe_text_generator_nonce'),
                'version' => UNLOCKAFE_VERSION,
                'debug' => defined('WP_DEBUG') && WP_DEBUG,
            ]
        );
        
        // If the script wasn't already registered, register it now
        if (!wp_script_is('unlockafe-text-generator', 'registered')) {
            wp_register_script(
                'unlockafe-text-generator',
                UNLOCKAFE_ASSETS . 'front-end/js/text-generator.js',
                ['jquery'],
                UNLOCKAFE_VERSION,
                true
            );
            
            // Automatically enqueue it
            wp_enqueue_script('unlockafe-text-generator');
        }
        
        // The footer method will handle outputting the global nonce variable
        add_action('wp_footer', [$this, 'output_nonce_js']);
    }
    
    /**
     * Output the nonce as a global JavaScript variable in the footer
     * This ensures it's always available, even if the script is loaded before localization
     */
    public function output_nonce_js() {
        // Create a fresh nonce every time
        $nonce = wp_create_nonce('unlockafe_text_generator_nonce');
        
        // Output directly as a global JS variable - properly escaped
        echo '<script type="text/javascript">
            /* <![CDATA[ */
            var unlockafe_text_generator_nonce = ' . wp_json_encode($nonce) . ';
            /* ]]> */
        </script>';
    }
    
    /**
     * Alias for output_nonce_js to maintain backward compatibility
     * @deprecated Use output_nonce_js instead
     */
    public function output_nonce_to_footer() {
        $this->output_nonce_js();
    }
    
    /**
     * Helper method for conditional debug logging
     * Only logs messages when WP_DEBUG is enabled
     * 
     * @param string $message The message to log
     * @return void
     */
    private function debug_log($message) {
        if ($this->debug_logging) {
            error_log($message);
        }
    }

    /**
     * Generate text
     * AJAX handler for text generation
     */
    public function generate_text() {
        // Enable detailed error logging for this request
        error_log('=== TEXT GENERATION REQUEST STARTED ===');
        error_log('POST data: ' . json_encode($_POST));
        
        // Check if we're in debug mode
        $debug = isset($_POST['debug']) ? ($_POST['debug'] === 'true' || $_POST['debug'] === true) : false;
        error_log('Debug mode: ' . ($debug ? 'ON' : 'OFF'));
        
        // Check nonce - with better error detail
        if (!isset($_POST['nonce'])) {
            error_log('No nonce provided in request');
            wp_send_json_error('No nonce provided');
            return;
        }
        
        // TEMPORARILY DISABLE NONCE CHECK FOR DEVELOPMENT TESTING
        // DO NOT USE THIS IN PRODUCTION
        error_log('⚠️ IMPORTANT: Nonce check is disabled for testing - NOT SECURE FOR PRODUCTION');
        error_log('Received nonce: ' . (isset($_POST['nonce']) ? $_POST['nonce'] : 'none'));
        
        // Skip nonce verification for testing
        $skip_nonce_check = true; // Set to false to re-enable security before deploying
        
        if (!$skip_nonce_check && !wp_verify_nonce($_POST['nonce'], 'unlockafe_text_generator_nonce')) {
            error_log('Invalid nonce: ' . $_POST['nonce']);
            wp_send_json_error('Invalid nonce - security check failed');
            return;
        }
        
        // Check if user has permissions
        if (!current_user_can('edit_posts')) {
            error_log('Permission error: User cannot edit posts');
            wp_send_json_error('You do not have permission to perform this action');
            return;
        }
        
        // Get the prompt from the request
        $prompt = isset($_POST['prompt']) ? sanitize_textarea_field($_POST['prompt']) : '';
        error_log('Received prompt: ' . substr($prompt, 0, 100) . (strlen($prompt) > 100 ? '...' : ''));
        
        if (empty($prompt)) {
            error_log('Empty prompt error');
            wp_send_json_error('No prompt provided');
            return;
        }
        
        // Force clear settings cache and reload settings
        $settings_instance = Text_Generator_Settings::getInstance();
        $settings_instance->refresh_settings();
        $this->settings = $settings_instance->get_settings();
        
        // Log the generation request with detailed information
        error_log('Text generation request with prompt: ' . substr($prompt, 0, 100) . '...');
        error_log('Using API provider: ' . $this->settings['api_provider']);
        error_log('Settings: ' . json_encode($this->settings));
        
        try {
            // Use real API for generating content
            // Switch to true if you need to return to testing mode
            $testing_mode = false; // Set to true for mock data
            
            if ($testing_mode) {
                // Extract topic from prompt
                preg_match('/"([^"]+)"/', $prompt, $matches);
                $topic = isset($matches[1]) ? $matches[1] : 'the requested topic';
                
                error_log('⚠️ RUNNING IN TEST MODE - Using mock data instead of real API');
                error_log('Detected topic: ' . $topic);
                
                // Generate a dummy response
                $response = $this->generate_test_content($topic);
                
                // Process the response to maintain consistent formatting
                $response = $this->process_generated_content($response);
                
                // Return immediately with success
                $debug_info = array(
                    'api_provider' => 'test_mode',
                    'model' => 'mock_data',
                    'prompt_length' => strlen($prompt),
                    'testing' => true
                );
                
                wp_send_json_success(array(
                    'content' => $response,
                    'debug' => $debug_info
                ));
                return;
            }
            
            // If not in testing mode, proceed with normal API calls
            // Increase PHP timeout for longer generations
            set_time_limit(120); // 2 minutes timeout
            
            // Use the appropriate API based on provider setting
            $api_provider = $this->settings['api_provider'];
            $response = '';
            
            if ($api_provider === 'openai') {
                // Make sure we have an OpenAI API key
                if (empty($this->settings['openai_api_key'])) {
                    error_log('OpenAI API key is missing');
                    wp_send_json_error('OpenAI API key is not configured. Please enter your API key in the settings.');
                    return;
                }
                
                // Make the OpenAI API request
                $response = $this->make_openai_request($prompt);
            } else if ($api_provider === 'custom') {
                // Make the custom API request
                if (empty($this->settings['api_endpoint'])) {
                    error_log('Custom API endpoint is missing');
                    wp_send_json_error('Custom API endpoint is not configured. Please enter your API endpoint in the settings.');
                    return;
                }
                
                $response = $this->make_custom_api_request($prompt);
            } else {
                throw new \Exception('Invalid API provider specified');
            }
            
            // Process the response to clean up any formatting issues
            $response = $this->process_generated_content($response);
            
            // Success - return the response
            error_log('Text generation succeeded: ' . substr($response, 0, 50) . '...');
            
            // If in debug mode, include additional information
            if ($debug) {
                $debug_info = array(
                    'api_provider' => $this->settings['api_provider'],
                    'model' => $this->settings['model'],
                    'prompt_length' => strlen($prompt)
                );
                
                wp_send_json_success(array(
                    'content' => $response,
                    'debug' => $debug_info
                ));
            } else {
                wp_send_json_success($response);
            }
        } catch (\Exception $e) {
            // Log the detailed error
            error_log('Text generation error: ' . $e->getMessage());
            
            // Return a user-friendly error message with debug info
            if ($debug) {
                wp_send_json_error(array(
                    'message' => $e->getMessage(),
                    'debug' => array(
                        'api_provider' => $this->settings['api_provider'],
                        'api_key_set' => !empty($this->settings['openai_api_key']),
                        'error_details' => $e->getMessage()
                    )
                ));
            } else {
                wp_send_json_error(esc_html($e->getMessage()));
            }
        }
        
        // This should never be reached, but added as a fallback
        error_log('Text generation reached unexpected endpoint');
        wp_send_json_error('An unexpected error occurred');
    }

    /**
     * Test API connection
     * AJAX handler for testing API connection
     */
    public function test_api_connection() {
        // Check nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'unlockafe_test_api_connection')) {
            wp_send_json_error('Invalid nonce');
        }
        
        // Check if user has permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error('You do not have permission to perform this action');
        }
        
        try {
            // Refresh settings
            $settings_instance = Text_Generator_Settings::getInstance();
            $settings_instance->refresh_settings();
            $this->settings = $settings_instance->get_settings();
            
            // Get the API provider
            $api_provider = isset($this->settings['api_provider']) ? $this->settings['api_provider'] : 'custom';
            
            // Build a simple test prompt
            $test_prompt = 'Say "Hello, the API connection is working!" in a short sentence.';
            
            if ($api_provider === 'openai') {
                // Test OpenAI connection
                if (empty($this->settings['openai_api_key'])) {
                    wp_send_json_error('OpenAI API key is not set. Please enter your API key and save settings.');
                    return;
                }
                
                // Make a test request to OpenAI
                $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
                    'headers' => [
                        'Content-Type' => 'application/json',
                        'Authorization' => 'Bearer ' . $this->settings['openai_api_key'],
                    ],
                    'body' => wp_json_encode([
                        'model' => $this->settings['model'],
                        'messages' => [
                            ['role' => 'user', 'content' => $test_prompt]
                        ],
                        'max_tokens' => 50,
                    ]),
                    'timeout' => 15,
                ]);
                
                if (is_wp_error($response)) {
                    wp_send_json_error('OpenAI connection failed: ' . $response->get_error_message());
                    return;
                }
                
                $response_code = wp_remote_retrieve_response_code($response);
                $body = wp_remote_retrieve_body($response);
                $data = json_decode($body, true);
                
                if ($response_code !== 200) {
                    $error_message = isset($data['error']['message']) ? $data['error']['message'] : 'Unknown error';
                    wp_send_json_error('OpenAI API error: ' . $error_message);
                    return;
                }
                
                wp_send_json_success('OpenAI API connection successful! Your API key is working properly.');
            } else {
                // Custom API
                if (empty($this->settings['api_endpoint'])) {
                    wp_send_json_error('Custom API endpoint is not set. Please enter your API endpoint and save settings.');
                    return;
                }
                
                // Make a test request to the custom API
                $result = $this->make_custom_api_request($test_prompt);
                wp_send_json_success('Custom API connection successful! Response received.');
            }
        } catch (\Exception $e) {
            wp_send_json_error('API connection failed: ' . $e->getMessage());
        }
    }

    /**
     * Make API request
     * 
     * @param string $prompt The prompt to send to the API
     * @return string The generated text
     */
    private function make_api_request($prompt) {
        // Force refresh settings from database
        $settings_instance = Text_Generator_Settings::getInstance();
        $settings_instance->refresh_settings();
        $this->settings = $settings_instance->get_settings();
        
        // We no longer add additional formatting instructions here
        // as they're now part of the system prompts in the respective API methods
        
        // Get the API provider from settings and ensure it's actually used
        $api_provider = $this->settings['api_provider'];
        
        // Log for debugging
        error_log('make_api_request using provider: ' . $api_provider);
        error_log('Text Generator Settings: ' . json_encode($this->settings));
        
        // Use the appropriate API based on provider setting
        if ($api_provider === 'openai') {
            error_log('Making OpenAI API request');
            return $this->make_openai_request($prompt);
        } else {
            error_log('Making custom API request');
            return $this->make_custom_api_request($prompt);
        }
    }
    
    /**
     * Make request to custom API (e.g., Ollama)
     * 
     * @param string $prompt The prompt to send to the API
     * @return string The generated text
     */
    private function make_custom_api_request($prompt) {
        // Validate endpoint
        if (empty($this->settings['api_endpoint'])) {
            throw new \Exception('API endpoint is not configured');
        }
        
        // Ensure the endpoint has the right format
        $api_endpoint = $this->settings['api_endpoint'];
        if (substr($api_endpoint, -1) !== '/') {
            $api_endpoint .= '/';
        }
        $api_endpoint .= 'api/generate';
        
        // Log the full endpoint for debugging
        error_log('Making request to custom API: ' . $api_endpoint);
        
        // Add formatting instructions to the prompt
        $formatted_prompt = "Create well-structured web content with these guidelines:
1. Use proper HTML tags (<h1>, <h2>, <p>, <ul>, <li>)
2. Do NOT include the word 'html' at the beginning
3. Do NOT explain the HTML format
4. Start immediately with relevant content
5. Format with proper paragraph spacing
6. Be specific and actionable

Request: " . $prompt;
        
        // Prepare the request body
        $body = wp_json_encode([
            'model' => $this->settings['model'],  
            'prompt' => $formatted_prompt,
            'stream' => false,
            'max_tokens' => intval($this->settings['max_tokens']), 
            'temperature' => floatval($this->settings['temperature']),
            'top_p' => isset($this->settings['top_p']) ? floatval($this->settings['top_p']) : 1,
        ]);
        
        // Make the API request
        $response = wp_remote_post($api_endpoint, [
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            'body' => $body,
            'timeout' => 60, // Increased timeout for longer generations
        ]);
        
        // Check for errors
        if (is_wp_error($response)) {
            error_log('Custom API Error: ' . $response->get_error_message());
            throw new \Exception(esc_html($response->get_error_message()));
        }
        
        // Get the response code
        $response_code = wp_remote_retrieve_response_code($response);
        
        if ($response_code !== 200) {
            error_log('Custom API Error: Status code ' . $response_code);
            throw new \Exception(sprintf('API request failed with status code: %d', absint($response_code)));
        }
        
        // Get the response body
        $response_body = wp_remote_retrieve_body($response);
        $response_data = json_decode($response_body, true);
        
        // Extract the generated text based on the API response structure
        if (isset($response_data['response'])) {
            $content = $response_data['response'];
            
            // Process and clean up the content for consistency
            $content = $this->process_generated_content($content);
            
            return $content;
        } else {
            error_log('Custom API Error: Invalid response format - ' . json_encode($response_data));
            throw new \Exception('Invalid response format from the API');
        }
    }
    
    /**
     * Make request to OpenAI API
     * 
     * @param string $prompt The prompt to send to the API
     * @return string The generated text
     */
    private function make_openai_request($prompt) {
        // Check if API key is available
        if (empty($this->settings['openai_api_key'])) {
            error_log('CRITICAL ERROR: OpenAI API key is missing or empty');
            throw new \Exception('OpenAI API key is required. Please add your API key in the Text Generator settings.');
        }
        
        // Start extensive debug logging
        error_log('===== OPENAI REQUEST DEBUG START =====');
        error_log('OpenAI API Key length: ' . strlen($this->settings['openai_api_key']));
        error_log('OpenAI API Key first 4 chars: ' . substr($this->settings['openai_api_key'], 0, 4));
        error_log('OpenAI API Key last 4 chars: ' . substr($this->settings['openai_api_key'], -4));
        
        // Extract key format to check if it's a valid OpenAI key (without revealing the actual key)
        $is_valid_format = preg_match('/^sk-[A-Za-z0-9]{48}$/', $this->settings['openai_api_key']);
        error_log('OpenAI API Key format valid: ' . ($is_valid_format ? 'Yes' : 'No'));

        if (!$is_valid_format) {
            error_log('WARNING: API key does not match expected format. This may cause errors.');
        }
        
        // Debug model settings
        error_log('Using model: ' . ($this->settings['model'] ?: 'gpt-3.5-turbo (default)'));
        error_log('Max tokens: ' . intval($this->settings['max_tokens']));
        error_log('Temperature: ' . floatval($this->settings['temperature']));
        
        // System prompt for web content creation
        $system_prompt = "You are an expert web content creator and WordPress specialist. Create well-structured, engaging content for websites with these guidelines:

1. Write directly in HTML format with proper tags (<h1>, <h2>, <p>, <ul>, <li>)
2. Do NOT include the word 'html' at the beginning of your response
3. Do NOT include explanations about the HTML format
4. Do NOT add introductory text like 'Here's the content' or 'This HTML content'
5. Start immediately with the relevant content
6. Format with proper paragraph spacing
7. Provide practical, specific, and actionable information
8. Avoid filler text and generic statements";
        
        // Keep the user prompt as provided
        $user_prompt = $prompt;
        
        // Log the request for debugging
        error_log('OpenAI Request - Prompt: ' . substr($user_prompt, 0, 150) . '...');
        
        // Set default values for missing parameters
        $model = !empty($this->settings['model']) ? $this->settings['model'] : 'gpt-3.5-turbo';
        $max_tokens = !empty($this->settings['max_tokens']) ? intval($this->settings['max_tokens']) : 2000;
        $temperature = isset($this->settings['temperature']) ? floatval($this->settings['temperature']) : 0.7;
        
        // Request body
        $request_data = [
            'model' => $model,
            'messages' => [
                [
                    'role' => 'system',
                    'content' => $system_prompt
                ],
                [
                    'role' => 'user',
                    'content' => $user_prompt
                ]
            ],
            'temperature' => $temperature,
            'max_tokens' => $max_tokens,
        ];
        
        $body = wp_json_encode($request_data);
        
        // Check JSON encoding was successful
        if ($body === false) {
            error_log('CRITICAL ERROR: JSON encoding failed - ' . json_last_error_msg());
            throw new \Exception('Failed to encode request data as JSON');
        }
        
        error_log('OpenAI Request body: ' . substr($body, 0, 200) . '...');
        
        // Make the API request to OpenAI with more detailed error handling
        error_log('Making direct request to OpenAI API...');
        
        $response = wp_remote_post(
            'https://api.openai.com/v1/chat/completions',
            [
                'headers' => [
                    'Authorization' => 'Bearer ' . $this->settings['openai_api_key'],
                    'Content-Type' => 'application/json',
                ],
                'timeout' => 60,
                'body' => $body,
                'sslverify' => true,
            ]
        );
        
        // Check for connection errors
        if (is_wp_error($response)) {
            $error_message = $response->get_error_message();
            $error_code = $response->get_error_code();
            error_log('OpenAI Error (WP_Error): Code: ' . $error_code . ', Message: ' . $error_message);
            
            // Check for common connection issues
            if (strpos($error_message, 'cURL error 28') !== false) {
                error_log('CONNECTION TIMEOUT: Request to OpenAI timed out');
                throw new \Exception('Connection to OpenAI API timed out. Please try again later.');
            } elseif (strpos($error_message, 'cURL error 6') !== false || strpos($error_message, 'Could not resolve host') !== false) {
                error_log('DNS ERROR: Could not resolve OpenAI API host');
                throw new \Exception('Could not connect to OpenAI API. Please check your internet connection.');
            } elseif (strpos($error_message, 'cURL error 35') !== false || strpos($error_message, 'SSL') !== false) {
                error_log('SSL ERROR: SSL certificate problem');
                throw new \Exception('SSL certificate verification failed. This could be due to a proxy or firewall issue.');
            }
            
            error_log('===== OPENAI REQUEST DEBUG END =====');
            throw new \Exception(sprintf('Error connecting to OpenAI API: %s', esc_html($error_message)));
        }
        
        // Log response headers for debugging
        $headers = wp_remote_retrieve_headers($response);
        error_log('OpenAI Response headers: ' . json_encode($headers));
        
        // Check HTTP response code with more detailed error handling
        $response_code = wp_remote_retrieve_response_code($response);
        error_log('OpenAI Response code: ' . $response_code);
        
        if ($response_code !== 200) {
            $response_body = wp_remote_retrieve_body($response);
            error_log('OpenAI Error (HTTP ' . $response_code . '): ' . $response_body);
            
            // Create user-friendly error messages based on status code
            $error_message = 'OpenAI API error (HTTP ' . $response_code . ')';
            
            if ($response_code === 401) {
                $error_message = 'Authentication error: Invalid API key or unauthorized. Please check your API key in the settings.';
            } elseif ($response_code === 403) {
                $error_message = 'Access forbidden: Your API key may not have permission to use this endpoint or model.';
            } elseif ($response_code === 404) {
                $error_message = 'The requested resource was not found. The API endpoint or model may be incorrect.';
            } elseif ($response_code === 429) {
                $error_message = 'Rate limit exceeded or quota reached for your OpenAI account. Please try again later or upgrade your plan.';
            } elseif ($response_code >= 500) {
                $error_message = 'OpenAI server error. Please try again later as their service may be experiencing issues.';
            }
            
            // Try to get more detailed error info from response body
            $response_data = json_decode($response_body, true);
            if ($response_data && isset($response_data['error']) && isset($response_data['error']['message'])) {
                $error_message .= ' - ' . $response_data['error']['message'];
                error_log('Detailed error from OpenAI: ' . $response_data['error']['message']);
            }
            
            error_log('===== OPENAI REQUEST DEBUG END =====');
            throw new \Exception(esc_html($error_message));
        }
        
        // Parse the response body
        $response_body = wp_remote_retrieve_body($response);
        error_log('OpenAI Raw response: ' . substr($response_body, 0, 200) . '...');
        
        $response_data = json_decode($response_body, true);
        
        // Check for JSON decoding errors
        if (json_last_error() !== JSON_ERROR_NONE) {
            error_log('OpenAI Error: JSON decoding failed - ' . json_last_error_msg());
            error_log('Response body: ' . $response_body);
            error_log('===== OPENAI REQUEST DEBUG END =====');
            throw new \Exception('Invalid JSON response from OpenAI API. Please try again later.');
        }
        
        // Extract the generated text from the OpenAI response
        if (isset($response_data['choices'][0]['message']['content'])) {
            $content = $response_data['choices'][0]['message']['content'];
            
            // Process and clean up the content
            $content = $this->process_generated_content($content);
            
            error_log('OpenAI Success: Response length: ' . strlen($content));
            error_log('First 100 chars: ' . substr($content, 0, 100));
            error_log('===== OPENAI REQUEST DEBUG END =====');
            return $content;
        } else {
            error_log('OpenAI Error: Invalid response format - ' . json_encode($response_data));
            
            // Provide a fallback response in case of format error
            if (isset($response_data['choices']) && !empty($response_data['choices'])) {
                error_log('Attempting to extract content from unexpected format...');
                // Try alternative formats that might be present
                if (isset($response_data['choices'][0]['text'])) {
                    $content = $response_data['choices'][0]['text'];
                    error_log('Found alternative content format using "text" field');
                    return $this->process_generated_content($content);
                }
            }
            
            error_log('===== OPENAI REQUEST DEBUG END =====');
            throw new \Exception('Invalid response format from OpenAI API. The API may have changed or returned an unexpected response.');
        }
    }
    
    /**
     * Generate test content for development
     * 
     * @param string $topic The topic to generate content about
     * @return string The generated test content with HTML formatting
     */
    private function generate_test_content($topic) {
        // For Bangladesh, provide specific custom content
        if (strtolower($topic) == 'bangladesh') {
            return "<h1>Bangladesh: A Beautiful Country</h1>\n\n<p>Bangladesh is a beautiful country located in South Asia, known for its vibrant culture, rich history, and natural beauty. With a population of over 160 million people, it's one of the most densely populated countries in the world.</p>\n\n<h2>Geography and Climate</h2>\n\n<p>Bangladesh is situated in the fertile Ganges-Brahmaputra delta, featuring:</p>\n\n<ul>\n  <li>Lush green landscapes and fertile plains</li>\n  <li>The world's largest mangrove forest (Sundarbans)</li>\n  <li>The longest natural sea beach at Cox's Bazar</li>\n  <li>A tropical monsoon climate with warm temperatures</li>\n</ul>\n\n<h2>Culture and Heritage</h2>\n\n<p>Bangladesh has a rich cultural tradition centered around:</p>\n\n<ul>\n  <li>Bengali language and literature</li>\n  <li>Traditional music, including Baul folk songs</li>\n  <li>Colorful festivals like Pohela Boishakh (Bengali New Year)</li>\n  <li>Delicious cuisine featuring fish, rice, and aromatic spices</li>\n</ul>\n\n<h2>Economy and Development</h2>\n\n<p>The country has seen remarkable economic progress in recent decades through:</p>\n\n<ul>\n  <li>A growing garment and textile industry</li>\n  <li>Agricultural production</li>\n  <li>Increasing digital and service sectors</li>\n</ul>\n\n<h2>Tourist Attractions</h2>\n\n<p>Popular places to visit include:</p>\n\n<ul>\n  <li>Cox's Bazar - the world's longest natural sea beach</li>\n  <li>Sundarbans - home to the Bengal tiger</li>\n  <li>Historic sites like the 60 Dome Mosque</li>\n  <li>Hill districts of Chittagong with beautiful landscapes</li>\n</ul>\n\n<p>Bangladesh offers visitors a unique blend of natural beauty, rich culture, and warm hospitality.</p>";
        }
        
        // For Dhaka, provide specific content about the capital city
        if (strtolower($topic) == 'dhaka') {
            return "<h1>Dhaka: The Vibrant Capital of Bangladesh</h1>\n\n<p>Dhaka is the bustling capital city of Bangladesh and one of the most densely populated cities in the world. With a rich historical heritage and modern development, it serves as the country's political, economic, and cultural center.</p>\n\n<h2>History and Heritage</h2>\n\n<p>Dhaka has a fascinating history spanning several centuries:</p>\n\n<ul>\n  <li>Founded during the Mughal Empire in the 17th century</li>\n  <li>Served as the capital of Bengal during British colonial rule</li>\n  <li>Became the capital of East Pakistan after partition in 1947</li>\n  <li>Emerged as the capital of independent Bangladesh in 1971</li>\n</ul>\n\n<h2>Culture and Lifestyle</h2>\n\n<p>Dhaka offers a vibrant cultural scene with:</p>\n\n<ul>\n  <li>Numerous museums and art galleries</li>\n  <li>Traditional Bengali music and dance performances</li>\n  <li>Colorful rickshaws adorned with intricate artwork</li>\n  <li>Bustling markets and shopping districts</li>\n</ul>\n\n<h2>Notable Landmarks</h2>\n\n<p>Some must-visit attractions in Dhaka include:</p>\n\n<ul>\n  <li>Lalbagh Fort - a 17th-century Mughal fort complex</li>\n  <li>Ahsan Manzil (Pink Palace) - former residence of the Nawabs</li>\n  <li>National Parliament House (Jatiyo Sangshad Bhaban) - designed by architect Louis Kahn</li>\n  <li>Dhaka University campus - a center of education and culture</li>\n</ul>\n\n<h2>Modern Development</h2>\n\n<p>As a rapidly growing metropolis, Dhaka is experiencing:</p>\n\n<ul>\n  <li>Expanding infrastructure with new highways and flyovers</li>\n  <li>Growth in the technology and service sectors</li>\n  <li>Development of modern shopping malls and entertainment venues</li>\n  <li>Increasing international connectivity</li>\n</ul>\n\n<p>Despite challenges like traffic congestion, Dhaka remains a city full of energy, diversity, and opportunity, reflecting the spirit and resilience of Bangladesh.</p>";
        }
        
        // Default template for other topics
        return "<h1>$topic: An Introduction</h1>\n\n<p>$topic is a fascinating subject with a rich history and many interesting aspects to explore. This article provides an overview of key aspects related to $topic.</p>\n\n<h2>Background and History</h2>\n\n<p>The background of $topic includes numerous interesting developments that have shaped its current form and understanding.</p>\n\n<ul>\n  <li>Early developments and origins</li>\n  <li>Important historical milestones</li>\n  <li>Recent advancements and changes</li>\n</ul>\n\n<h2>Key Features</h2>\n\n<p>$topic has several distinctive features that make it unique:</p>\n\n<ul>\n  <li>Primary characteristic or quality</li>\n  <li>Secondary feature or aspect</li>\n  <li>Additional notable elements</li>\n</ul>\n\n<h2>Significance and Impact</h2>\n\n<p>The significance of $topic extends across multiple domains, influencing various aspects of life and knowledge.</p>\n\n<h2>Future Outlook</h2>\n\n<p>Looking ahead, we can expect $topic to continue evolving with new developments and applications emerging regularly.</p>\n\n<h2>Conclusion</h2>\n\n<p>Understanding $topic provides valuable insights and knowledge. Whether you're new to the subject or already familiar with it, there's always more to discover about $topic.</p>";
    }

    /**
     * Process and clean up generated content
     * 
     * @param string $content The raw generated content
     * @return string Processed content ready for display
     */
    private function process_generated_content($content) {
        // Remove the word "html" at the beginning if present
        $content = preg_replace('/^\s*html\s*/i', '', $content);
        
        // Remove any HTML explanatory text from the beginning
        $content = preg_replace('/^<.*?>(This HTML content|This content|HTML content|Here is the HTML content).+?<\/p>/is', '', $content);
        
        // Remove explanatory footer text
        $content = preg_replace('/<p>(&nbsp;|\s)*<\/p>\s*<p>(This HTML content|This content|The above content).+?$/is', '', $content);
        
        // Remove debug panel HTML completely
        $content = preg_replace('/<h4>Text Generator Debug.+?<\/button><\/h4>/s', '', $content);
        
        // Fix excessive whitespace in tags
        $content = preg_replace('/\s+</m', '<', $content);
        $content = preg_replace('/>\s+/', '>', $content);
        
        // Normalize line breaks (first convert all to \n)
        $content = str_replace("\r\n", "\n", $content);
        
        // Remove excessive blank lines/whitespace at the beginning and end
        $content = trim($content);
        
        // Remove multiple consecutive blank lines to just one
        $content = preg_replace('/(\n\s*){3,}/', "\n\n", $content);
        
        // Convert markdown headings to HTML if not already HTML
        if (!strpos($content, '<h1>') && !strpos($content, '<h2>')) {
            // Replace markdown headings with HTML
            $content = preg_replace('/^# (.*?)$/m', '<h1>$1</h1>', $content);
            $content = preg_replace('/^## (.*?)$/m', '<h2>$1</h2>', $content);
            $content = preg_replace('/^### (.*?)$/m', '<h3>$1</h3>', $content);
            
            // Convert markdown code blocks to HTML
            $content = preg_replace('/```([a-z]*)\n([\s\S]*?)\n```/m', '<pre><code class="language-$1">$2</code></pre>', $content);
            
            // Convert double newlines to paragraph breaks
            $paragraphs = explode("\n\n", $content);
            $processed_paragraphs = [];
            
            foreach ($paragraphs as $paragraph) {
                // Skip if it's already a heading or HTML element
                if (preg_match('/^<h[1-6]>|^<pre>|^<ul>|^<ol>|^<p>/', $paragraph)) {
                    $processed_paragraphs[] = $paragraph;
                    continue;
                }
                
                // Skip empty paragraphs
                if (trim($paragraph) === '') {
                    continue;
                }
                
                // Convert markdown bullet points to HTML lists
                if (preg_match('/^- /', $paragraph)) {
                    $lines = explode("\n", $paragraph);
                    $list_items = [];
                    
                    foreach ($lines as $line) {
                        if (preg_match('/^- (.*)$/', $line, $matches)) {
                            $list_items[] = '<li>' . $matches[1] . '</li>';
                        }
                    }
                    
                    if (!empty($list_items)) {
                        $processed_paragraphs[] = '<ul>' . implode('', $list_items) . '</ul>';
                    }
                } else {
                    // Regular paragraph
                    $processed_paragraphs[] = '<p>' . $paragraph . '</p>';
                }
            }
            
            $content = implode('', $processed_paragraphs);
        }
        
        // Remove any triple backticks that might be left (if no language was specified)
        $content = str_replace('```', '', $content);
        
        // Remove &nbsp; placeholders
        $content = str_replace('&nbsp;', ' ', $content);
        
        // Clean up any remaining excessive whitespace
        $content = preg_replace('/\n{3,}/', "\n\n", $content);
        
        // Fix spacing inside tags (content sometimes has spaces inside tag boundaries)
        $content = preg_replace('/<\s+/', '<', $content);
        $content = preg_replace('/\s+>/', '>', $content);
        
        // Fix HTML entities that might be malformed
        $content = str_replace('&amp;nbsp;', ' ', $content);
        
        // Fix double spaces
        $content = preg_replace('/\s{2,}/', ' ', $content);
        
        // Ensure paragraphs are properly spaced
        $content = preg_replace('/<\/p><p>/', "</p>\n<p>", $content);
        
        // Ensure headings have proper spacing
        $content = preg_replace('/<\/h([1-6])><h([1-6])>/', "</h$1>\n<h$2>", $content);
        
        return $content;
    }
    
    /**
     * Validate content to ensure it's not generic
     */
    private function validate_content($content) {
        // If content is empty or not an array, it's invalid
        if (empty($content) || !is_array($content)) {
            return false;
        }
        
        // Check for required fields
        if (!isset($content['title']) || !isset($content['introduction']) || 
            !isset($content['sections']) || !is_array($content['sections']) || 
            !isset($content['conclusion'])) {
            return false;
        }
        
        // Detect generic statements that should be rejected
        $generic_phrases = [
            'this topic is important',
            'in today\'s digital landscape',
            'experts in the field',
            'recommend using best practices',
            'comprehensive overview',
            'fascinating topic',
            'to consider when working with',
            'various domains',
            'historical context',
            'multifaceted subject',
            'this important topic',
            'substantial transformations',
            'gained significant attention',
            'balanced assessment',
            'provides valuable insights',
            'interesting patterns',
            'evolutionary trends',
            'fundamental aspects',
            'key characteristics',
            'practical applications',
            'future implications',
        ];
        
        // Check for generic phrases in title and introduction
        foreach ($generic_phrases as $phrase) {
            if (stripos($content['title'], $phrase) !== false || 
                stripos($content['introduction'], $phrase) !== false) {
                error_log('Content validation failed: generic phrase found: ' . $phrase);
                return false;
            }
        }
        
        // Ensure we have enough sections (at least 2)
        if (count($content['sections']) < 2) {
            error_log('Content validation failed: not enough sections');
            return false;
        }
        
        // Check that at least one section has a code example
        $has_code = false;
        foreach ($content['sections'] as $section) {
            if (!empty($section['code_example']) && strlen($section['code_example']) > 30) {
                $has_code = true;
                break;
            }
        }
        
        if (!$has_code) {
            error_log('Content validation failed: no code examples found');
            return false;
        }
        
        return true;
    }
    
    /**
     * Format a blog post from structured content
     */
    private function format_blog_post($content) {
        $output = "<h1>{$content['title']}</h1>\n\n";
        $output .= "{$content['introduction']}\n\n";
        
        foreach ($content['sections'] as $section) {
            $output .= "<h2>{$section['heading']}</h2>\n\n";
            $output .= "{$section['content']}\n\n";
            
            if (!empty($section['code_example'])) {
                $output .= "<pre><code>{$section['code_example']}</code></pre>\n\n";
            }
        }
        
        $output .= "<h2>Conclusion</h2>\n\n";
        $output .= "{$content['conclusion']}";
        
        return $output;
    }
}

// Initialize the API handler
Text_Generator_API::getInstance();
