<?php
// lib/OpenAIClient.php - Responses API via cURL (PHP 7.4)
class OpenAIClient {
    private $apiKey;
    private $baseUrl;
    private $model;
    private $useChat;

    public function __construct() {
        $this->apiKey  = getenv('OPENAI_API_KEY') ?: '';
        $this->baseUrl = rtrim(getenv('OPENAI_BASE_URL') ?: 'https://api.openai.com/v1', '/');
        $this->model   = getenv('OPENAI_MODEL') ?: 'gpt-4o-mini';
        $this->useChat = getenv('USE_CHAT_COMPLETIONS') ? true : false;
        if (!$this->apiKey) {
            throw new Exception('Missing OPENAI_API_KEY in .env');
        }
    }

    public function createResponse(array $messages) {
        if ($this->useChat) {
            // Fallback to Chat Completions if desired
            $endpoint = $this->baseUrl . '/chat/completions';
            $payload = [
                'model' => $this->model,
                'messages' => $messages,
            ];
        } else {
            $endpoint = $this->baseUrl . '/responses';
            // Responses API accepts "input" (string or role-based array). We'll send role-based.
            $payload = [
                'model' => $this->model,
                'input' => $messages
            ];
        }

        $ch = curl_init($endpoint);
        $headers = [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->apiKey,
        ];
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_TIMEOUT => 60,
        ]);

        $res = curl_exec($ch);
        if ($res === false) {
            $err = curl_error($ch);
            curl_close($ch);
            throw new Exception('cURL error: ' . $err);
        }
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $json = json_decode($res, true);
        if ($status >= 400) {
            $message = isset($json['error']['message']) ? $json['error']['message'] : ('HTTP ' . $status);
            throw new Exception('OpenAI API error: ' . $message);
        }

        // Try extracting text robustly across Responses or Chat Completions
        $text = '';

        // Responses API aggregate
        if (isset($json['output_text'])) {
            $text = $json['output_text'];
        }
        // Responses API granular content
        if (!$text && isset($json['output']) && is_array($json['output'])) {
            foreach ($json['output'] as $item) {
                if (isset($item['content']) && is_array($item['content'])) {
                    foreach ($item['content'] as $c) {
                        if (isset($c['text'])) {
                            if (is_string($c['text'])) {
                                $text .= $c['text'];
                            } elseif (isset($c['text']['value'])) {
                                $text .= $c['text']['value'];
                            }
                        }
                    }
                }
            }
        }
        // Chat Completions
        if (!$text && isset($json['choices'][0]['message']['content'])) {
            $text = $json['choices'][0]['message']['content'];
        }

        if (!$text) {
            $text = '[No text output received]';
        }
        return $text;
    }
}