<?php

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

/**
 * Handles communication with the OpenRouter API.
 *
 * @since      1.6.5
 */
class NewCodeByte_Chatbot_Api {

    /**
     * Generate a response from the AI model.
     *
     * @param string $user_message The user's message.
     * @param array  $conversation_history The history of the conversation.
     * @param string|null $user_name The user's name, if provided.
     * @return string The bot's response.
     * @since    1.6.5
     */
        public function generate_response($user_message, $conversation_history = [], $user_name = null) {
        $api_key = get_option('newcodebyte_chatbot_api_key', '');
        $model = get_option('newcodebyte_chatbot_model', 'google/gemma-3-27b-it:free');
        $responses_info = get_option('newcodebyte_chatbot_responses_info', '');
        $behavior_type = get_option('newcodebyte_chatbot_behavior_type', '');
        $server_url = 'https://openrouter.ai/api/v1/chat/completions';

        $system_prompt_content = sprintf(
            __("You are an assistant for the website %1\$s. Follow these rules:\n%2\$s\n\nUse the following information as a knowledge base:\n%3\$s", NCB_CHATBOT_TEXT_DOMAIN),
            get_bloginfo('name'),
            $behavior_type,
            $responses_info
        );

        if ($user_name) {
            $system_prompt_content .= "\n\nIMPORTANT: The user's name is '{$user_name}'. You MUST greet them by this name.";
        }

        $messages_for_api = [['role' => 'system', 'content' => $system_prompt_content]];
        
        // La cronologia che arriva dal JS è già l'array di messaggi completo.
        // Dobbiamo solo accodarlo.
        $messages_for_api = array_merge($messages_for_api, $conversation_history);

        $response = wp_remote_post($server_url, [
            'headers' => [
                'Authorization' => 'Bearer ' . $api_key,
                'HTTP-Referer' => home_url(),
                'X-Title' => get_bloginfo('name'),
                'Content-Type' => 'application/json'
            ],
            'body' => wp_json_encode(['model' => $model, 'messages' => $messages_for_api]),
            'timeout' => 30
        ]);

        if (is_wp_error($response)) {
            return __('Sorry, I was unable to get a response from the server.', NCB_CHATBOT_TEXT_DOMAIN);
        }

        $response_body = wp_remote_retrieve_body($response);
        $response_data = json_decode($response_body, true);

        if (isset($response_data['choices'][0]['message']['content'])) {
            return $response_data['choices'][0]['message']['content'];
        }
        if (isset($response_data['error']['message'])) {
            return sprintf(__('API Error: %s', NCB_CHATBOT_TEXT_DOMAIN), sanitize_text_field($response_data['error']['message']));
        }

        return __('Sorry, I was unable to get a response from the server.', NCB_CHATBOT_TEXT_DOMAIN);
    }
}