<?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 === '' || $model === 'gpt-5.2-2025-12-11') {
            if (function_exists('vmo_get_optimal_model')) {
                $model = vmo_get_optimal_model('content_creation', ['prompt' => $prompt, 'skip_log' => true]);
            } else {
                $model = defined('VMO_OPENAI_MODEL') ? VMO_OPENAI_MODEL : 'gpt-5.4';
            }
        }
        
        // ✅ TOKEN DEDUCTION v8.1.0: Charge for text generation
        $user_id = get_current_user_id();
        if (function_exists('vmo_deduct_tokens')) {
            if (!vmo_deduct_tokens($user_id, 300, '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: OpenAI 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')) {
            if (!vmo_deduct_tokens($user_id, 960, 'dalle_image', 'GPT Image 1 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();
            return $data['data'][0]['url'] ?? false;
        }

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

        $args = [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->api_key,
                'Content-Type'  => 'application/json',
            ],
            'body' => json_encode([
                'model' => 'gpt-image-1',
                'prompt' => $prompt,
                'n' => 1,
                'size' => $size,
                'response_format' => 'url',
            ]),
            '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();
        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.";
    }
}
