<?php


if (!defined('ABSPATH')) {
    exit;
}

class AI_eShop_Chat_OpenAI_API {

    
    private static $instance = null;

    
    const OPENAI_API_URL = 'https://api.openai.com/v1/';

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

    
    private function __construct() {
        
    }

    
    private function get_api_key() {
        $api_key = get_option('aieo_chat_openai_api_key', '');
        return !empty($api_key) ? $api_key : false;
    }

    
    public function generate_embedding($text, $model = null) {
        $api_key = $this->get_api_key();
        if (!$api_key) {
            return new WP_Error('no_api_key', __('OpenAI API key not configured', 'ai-eshop-optimizer'));
        }

        
        if ($model === null) {
            $model = get_option('aieo_chat_openai_embedding_model', 'text-embedding-3-large');
        }

        
        $body = array(
            'input' => $text,
            'model' => $model
        );

        
        $response = wp_remote_post(self::OPENAI_API_URL . 'embeddings', array(
            'timeout' => 30,
            'headers' => array(
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . $api_key
            ),
            'body' => wp_json_encode($body)
        ));

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

        $status_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);
        $data = json_decode($response_body, true);

        if ($status_code !== 200) {
            $error_message = isset($data['error']['message']) ? $data['error']['message'] : __('Unknown API error', 'ai-eshop-optimizer');
            
            return new WP_Error('api_error', sprintf(__('OpenAI API error (%1$d): %2$s', 'ai-eshop-optimizer'), $status_code, $error_message));
        }

        if (!isset($data['data'][0]['embedding'])) {
            return new WP_Error('invalid_response', __('Invalid response from OpenAI API', 'ai-eshop-optimizer'));
        }

        return $data['data'][0]['embedding'];
    }

    
    public function generate_embeddings_batch($texts, $model = null) {
        $api_key = $this->get_api_key();
        if (!$api_key) {
            return new WP_Error('no_api_key', __('OpenAI API key not configured', 'ai-eshop-optimizer'));
        }

        
        if ($model === null) {
            $model = get_option('aieo_chat_openai_embedding_model', 'text-embedding-3-large');
        }

          
        
        $original_keys = array_keys($texts);
        $input_array = array_values($texts);

        $body = array(
            'input' => $input_array,
            'model' => $model
        );

        
        $response = wp_remote_post(self::OPENAI_API_URL . 'embeddings', array(
            'timeout' => 60,  
            'headers' => array(
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . $api_key
            ),
            'body' => wp_json_encode($body)
        ));

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

        $status_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);
        $data = json_decode($response_body, true);

        if ($status_code !== 200) {
            $error_message = isset($data['error']['message']) ? $data['error']['message'] : __('Unknown API error', 'ai-eshop-optimizer');
            
            return new WP_Error('api_error', sprintf(__('OpenAI API error (%1$d): %2$s', 'ai-eshop-optimizer'), $status_code, $error_message));
        }

        if (!isset($data['data']) || !is_array($data['data'])) {
            return new WP_Error('invalid_response', __('Invalid response from OpenAI API', 'ai-eshop-optimizer'));
        }

        
        $results = array();
        foreach ($data['data'] as $index => $item) {
            if (isset($original_keys[$index]) && isset($item['embedding'])) {
                $post_id = $original_keys[$index];
                $results[$post_id] = $item['embedding'];
            }
        }

        return $results;
    }

    
    public function chat_completion($messages, $options = array()) {
        $api_key = $this->get_api_key();
        if (!$api_key) {
            return new WP_Error('no_api_key', __('OpenAI API key not configured', 'ai-eshop-optimizer'));
        }

        
        $defaults = array(
            'model' => get_option('aieo_chat_openai_chat_model', 'gpt-4o'),
            'max_tokens' => (int) get_option('aieo_chat_max_tokens', 500),
            'temperature' => (float) get_option('aieo_chat_temperature', 0.5),
            'system' => '',
        );

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

        
        $openai_messages = array();

        
        if (!empty($options['system'])) {
            $openai_messages[] = array(
                'role' => 'system',
                'content' => $options['system']
            );
        }

        
        $openai_messages = array_merge($openai_messages, $messages);

        
        $body = array(
            'model' => $options['model'],
            'messages' => $openai_messages,
            'max_completion_tokens' => $options['max_tokens'], 
        );

        
        
        if ($options['temperature'] == 1) {
            $body['temperature'] = 1;
        }
        

        
        $response = wp_remote_post(self::OPENAI_API_URL . 'chat/completions', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'application/json',
            ),
            'body' => wp_json_encode($body),
            'timeout' => 60,
        ));

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

        $status_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);
        $data = json_decode($response_body, true);

        if ($status_code !== 200) {
            $error_message = isset($data['error']['message'])
                ? $data['error']['message']
                : __('OpenAI API request failed', 'ai-eshop-optimizer');

            return new WP_Error('api_error', $error_message, array('status' => $status_code));
        }

        
        if (isset($data['choices'][0]['message']['content'])) {
            return array(
                'content' => array(
                    array(
                        'text' => $data['choices'][0]['message']['content'],
                        'type' => 'text'
                    )
                ),
                'model' => $data['model'],
                'usage' => isset($data['usage']) ? $data['usage'] : array()
            );
        }

        return new WP_Error('invalid_response', __('Invalid response from OpenAI', 'ai-eshop-optimizer'));
    }

    
    public function process_chat($message, $system_prompt = '', $conversation_history = array(), $model = 'gpt-4o-mini') {
        $api_key = $this->get_api_key();
        if (!$api_key) {
            return new WP_Error('no_api_key', __('OpenAI API key not configured', 'ai-eshop-optimizer'));
        }

        
        $messages = array();

        
        if (!empty($system_prompt)) {
            $messages[] = array(
                'role' => 'system',
                'content' => $system_prompt
            );
        }

        
        foreach ($conversation_history as $msg) {
            $messages[] = array(
                'role' => $msg['role'],
                'content' => $msg['message']
            );
        }

        
        $messages[] = array(
            'role' => 'user',
            'content' => $message
        );

        
        $body = array(
            'model' => $model,
            'messages' => $messages,
            'max_completion_tokens' => 1000 
        );
        

        
        $response = wp_remote_post(self::OPENAI_API_URL . 'chat/completions', array(
            'timeout' => 60,
            'headers' => array(
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . $api_key
            ),
            'body' => wp_json_encode($body)
        ));

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

        $status_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);
        $data = json_decode($response_body, true);

        if ($status_code !== 200) {
            $error_message = isset($data['error']['message']) ? $data['error']['message'] : __('Unknown API error', 'ai-eshop-optimizer');
            
            return new WP_Error('api_error', sprintf(__('OpenAI API error (%1$d): %2$s', 'ai-eshop-optimizer'), $status_code, $error_message));
        }

        if (!isset($data['choices'][0]['message']['content'])) {
            return new WP_Error('invalid_response', __('Invalid response from OpenAI API', 'ai-eshop-optimizer'));
        }

        return array(
            'content' => $data['choices'][0]['message']['content'],
            'model' => $data['model'],
            'usage' => isset($data['usage']) ? $data['usage'] : array()
        );
    }
}
