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

require_once VMO_AI_BUILDER_DIR . 'includes/modules/core/class-vmo-service.php';

class VMO_OpenAI_Service extends VMO_Service {
    private $api_key;

    public function __construct() {
        parent::__construct('openai');
        // Only load API key in master mode
        if (!defined('VMO_CLIENT_MODE') || VMO_CLIENT_MODE !== true) {
            $this->api_key = get_option('vmo_openai_api_key');
        }
    }

    public function generate_text($prompt, $model = null) {
        if (!$this->is_available()) {
            return $this->get_fallback();
        }

        if ($model === null || $model === '' || strpos((string) $model, 'gpt-5.2') !== false || strpos((string) $model, 'gpt-4') !== false) {
            if (function_exists('vmo_get_optimal_model')) {
                $model = vmo_get_optimal_model('content_creation', ['prompt' => $prompt, 'skip_log' => true]);
            } else {
                $model = function_exists('vmo_get_model') ? vmo_get_model('mini') : (defined('VMO_OPENAI_MODEL') ? VMO_OPENAI_MODEL : 'gpt-5.5');
            }
        }
        
        // ✅ TOKEN DEDUCTION v8.1.0: Charge for text generation
        $user_id = get_current_user_id();
        if (function_exists('vmo_deduct_tokens')) {
            $token_cost = function_exists('vmo_get_token_cost') ? (int) vmo_get_token_cost('content') : 2500;
            if (!vmo_deduct_tokens($user_id, $token_cost, 'content', 'AI text generation')) {
                return "Insufficient tokens. Please top up your balance.";
            }
        }

        // Use centralized API request helper if available
        if (function_exists('vmo_openai_chat')) {
            $messages = [['role' => 'user', 'content' => $prompt]];
            $response = vmo_openai_chat($messages, $model, ['temperature' => 0.7]);
            
            if (is_wp_error($response)) {
                $this->record_failure($response->get_error_message());
                return $this->get_fallback();
            }
            
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);
            
            if (isset($data['error'])) {
                $this->record_failure($data['error']['message']);
                return $this->get_fallback();
            }
            
            $this->reset_circuit();
            return $data['choices'][0]['message']['content'] ?? '';
        }

        // Fallback: Direct API call (master mode only)
        if (empty($this->api_key)) {
            return "Error: AI API Key is missing.";
        }

        $args = [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->api_key,
                'Content-Type'  => 'application/json',
            ],
            'body' => json_encode([
                'model' => $model,
                'messages' => [['role' => 'user', 'content' => $prompt]],
                'temperature' => 0.7,
            ]),
            'timeout' => 60,
        ];

        $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);

        if (is_wp_error($response)) {
            $this->record_failure($response->get_error_message());
            return $this->get_fallback();
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (isset($data['error'])) {
            $this->record_failure($data['error']['message']);
            return $this->get_fallback();
        }

        $this->reset_circuit(); // Success!
        return $data['choices'][0]['message']['content'] ?? '';
    }

    public function generate_image($prompt, $size = '1024x1024') {
        if (!$this->is_available()) {
            return false;
        }
        
        // ✅ TOKEN DEDUCTION v8.1.0: Charge for image generation
        $user_id = get_current_user_id();
        if (function_exists('vmo_deduct_tokens')) {
            $token_cost = function_exists('vmo_get_token_cost') ? (int) vmo_get_token_cost('dalle_image') : 1080;
            if (!vmo_deduct_tokens($user_id, $token_cost, 'dalle_image', 'AI image generation')) {
                return false;
            }
        }

        // Use centralized API request helper if available
        if (function_exists('vmo_openai_image')) {
            $response = vmo_openai_image($prompt, $size);
            
            if (is_wp_error($response)) {
                $this->record_failure($response->get_error_message());
                return false;
            }
            
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);
            
            if (isset($data['error'])) {
                $this->record_failure($data['error']['message']);
                return false;
            }
            
            $this->reset_circuit();
            if (!empty($data['data'][0]['b64_json'])) {
                return 'data:image/png;base64,' . $data['data'][0]['b64_json'];
            }
            return $data['data'][0]['url'] ?? false;
        }

        // Fallback: Direct API call (master mode only)
        if (empty($this->api_key)) {
            return false;
        }

        $fallback_model = function_exists('vmo_get_model') ? vmo_get_model('image') : 'gpt-image-1';
        $fallback_body = [
            'model' => $fallback_model,
            'prompt' => $prompt,
            'n' => 1,
            'size' => $size,
        ];
        if (strpos((string) $fallback_model, 'gpt-image') !== false || strpos((string) $fallback_model, 'openai-image-generation') !== false) {
            $fallback_body['output_format'] = 'png';
        } else {
            $fallback_body['response_format'] = 'url';
        }

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

        $response = wp_remote_post('https://api.openai.com/v1/images/generations', $args);

        if (is_wp_error($response)) {
            $this->record_failure($response->get_error_message());
            return false;
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (isset($data['error'])) {
            $this->record_failure($data['error']['message']);
            return false;
        }

        $this->reset_circuit();
        if (!empty($data['data'][0]['b64_json'])) {
            return 'data:image/png;base64,' . $data['data'][0]['b64_json'];
        }
        return $data['data'][0]['url'] ?? false;
    }

    protected function get_fallback() {
        return "I am currently experiencing high traffic. As your VMO Business Consultant, I recommend we focus on your core business values while I reconnect to my knowledge base.";
    }
}
