<?php

namespace Unlockafe_addons\API;

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

class AI_Chatbot_API
{
    private static $instance = null;

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

    private function __construct()
    {
        add_action('wp_ajax_unlockafe_ai_chatbot', [$this, 'handle_chatbot_request']);
        add_action('wp_ajax_nopriv_unlockafe_ai_chatbot', [$this, 'handle_chatbot_request']);
    }

    /**
     * Handle chatbot AJAX request
     */
    public function handle_chatbot_request()
    {
        // Verify nonce
        check_ajax_referer('unlockafe_ai_chatbot_nonce', 'nonce', false);

        $message = isset($_POST['message']) ? sanitize_text_field($_POST['message']) : '';
        $conversation_history = isset($_POST['conversation_history']) ? $_POST['conversation_history'] : [];
        $ai_model = isset($_POST['ai_model']) ? sanitize_text_field($_POST['ai_model']) : 'gpt-3.5-turbo';
        $max_tokens = isset($_POST['max_tokens']) ? intval($_POST['max_tokens']) : 500;
        $temperature = isset($_POST['temperature']) ? floatval($_POST['temperature']) : 0.7;
        $system_prompt = isset($_POST['system_prompt']) ? sanitize_textarea_field($_POST['system_prompt']) : 'You are a helpful AI assistant. Provide clear and concise answers.';

        if (empty($message)) {
            wp_send_json_error(['message' => 'Message is required']);
            return;
        }

        // Get OpenAI API key from settings
        $settings = get_option('unlockafe_ai_text_generator_settings', []);
        $api_key = isset($settings['openai_api_key']) ? $settings['openai_api_key'] : '';
        
        // Fallback: try alternative key name
        if (empty($api_key) && isset($settings['api_key'])) {
            $api_key = $settings['api_key'];
        }

        if (empty($api_key)) {
            wp_send_json_error(['message' => 'OpenAI API key is not configured. Please configure it in plugin settings.']);
            return;
        }

        // Prepare messages for API
        $messages = [
            [
                'role' => 'system',
                'content' => $system_prompt
            ]
        ];

        // Add conversation history
        if (!empty($conversation_history) && is_array($conversation_history)) {
            foreach ($conversation_history as $history_item) {
                if (isset($history_item['role']) && isset($history_item['content'])) {
                    $messages[] = [
                        'role' => sanitize_text_field($history_item['role']),
                        'content' => sanitize_text_field($history_item['content'])
                    ];
                }
            }
        }

        // Add current user message
        $messages[] = [
            'role' => 'user',
            'content' => $message
        ];

        // Call OpenAI API
        $response = $this->call_openai_api($api_key, $ai_model, $messages, $max_tokens, $temperature);

        if (is_wp_error($response)) {
            wp_send_json_error(['message' => $response->get_error_message()]);
            return;
        }

        if (isset($response['choices'][0]['message']['content'])) {
            $ai_message = $response['choices'][0]['message']['content'];
            wp_send_json_success(['message' => $ai_message]);
        } else {
            wp_send_json_error(['message' => 'Invalid response from AI']);
        }
    }

    /**
     * Call OpenAI API
     */
    private function call_openai_api($api_key, $model, $messages, $max_tokens, $temperature)
    {
        $url = 'https://api.openai.com/v1/chat/completions';

        $body = [
            'model' => $model,
            'messages' => $messages,
            'max_tokens' => $max_tokens,
            'temperature' => $temperature,
        ];

        $args = [
            'method' => 'POST',
            'headers' => [
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . $api_key,
            ],
            'body' => json_encode($body),
            'timeout' => 30,
        ];

        $response = wp_remote_post($url, $args);

        if (is_wp_error($response)) {
            return $response;
        }

        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);

        if ($response_code !== 200) {
            $error_data = json_decode($response_body, true);
            $error_message = isset($error_data['error']['message']) ? $error_data['error']['message'] : 'Unknown error';
            return new \WP_Error('openai_error', $error_message);
        }

        $data = json_decode($response_body, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            return new \WP_Error('json_error', 'Failed to parse API response');
        }

        return $data;
    }
}

// Initialize the API
AI_Chatbot_API::getInstance();

