<?php
if (!defined('ABSPATH')) {
    exit;
}

class foxblock_api_helper
{
    private static $instance = null;
    private $grok_model;
    private $grok_api_key;
    private $grok_enpoint;

    private function __construct()
    {
        $this->grok_api_key = get_option('foxblock_ai_apikey', '');
        $this->grok_model = get_option('foxblock_ai_model', '');
        $this->grok_enpoint = get_option('foxblock_ai_endpoint', '');
    }

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

    // Get Grok Model
    public function foxblock_get_grok_model()
    {
        return $this->grok_model;
    }

    public function foxblock_call_api($prompt, $temperature = 0.7)
    {
        if (empty($this->grok_api_key) || empty($this->grok_model) || empty($this->grok_enpoint)) {
            return new WP_Error('api_config_error', __('Khóa hoặc mô hình API chưa được cấu hình', 'foxblock'));
        }

        $api_url = $this->grok_enpoint; // Endpoint custom
        $response = wp_remote_post($api_url, array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->grok_api_key,
                'Content-Type' => 'application/json',
            ),
            'body' => json_encode(array(
                'model' => $this->grok_model,
                'messages' => array(
                        array('role' => 'system', 'content' => 'Bạn là một chuyên gia bảo mật website, chuyên phân tích mã độc PHP/JS.'),
                        array('role' => 'user', 'content' => $prompt),
                ),
                'temperature' => $temperature,
            )),
            'timeout' => 350,
        ));

        if (is_wp_error($response)) {
            return new WP_Error('grok_error', __('Unable to connect to AI API: ', 'foxblock') . $response->get_error_message());
        }

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

        if ($status_code !== 200) {
            $error_message = isset($body['error']['message']) ? $body['error']['message'] : __('Unknown API error', 'foxblock');
            return new WP_Error('api_error', sprintf(__('API error (Status %d): %s', 'foxblock'), $status_code, $error_message));
        }

        if (!isset($body['choices'][0]['message']['content'])) {
            return new WP_Error('invalid_response', __('Invalid response from AI API', 'foxblock'));
        }

        return trim($body['choices'][0]['message']['content']);
    }
}