<?php
header('Content-Type: application/json; charset=utf-8');
session_start();
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$user_message = isset($input['message']) ? trim($input['message']) : '';
if ($user_message === '') {
    http_response_code(400);
    echo json_encode(['error' => 'Pesan kosong.']);
    exit;
}
if (OPENAI_API_KEY === '') {
    http_response_code(500);
    echo json_encode(['error' => 'OPENAI_API_KEY belum diset. Harap isi di file .env']);
    exit;
}

$session_id = session_id();
$conversation_id = create_conversation_if_needed($session_id);
add_message($conversation_id, 'user', $user_message);

// Build Responses API input
$history = get_recent_messages($conversation_id, 12);
$input_items = [];
//$input_items[] = ['role' => 'system', 'content' => [['type' => 'input_text', 'text' => SYSTEM_PROMPT]]];
foreach ($history as $m) {
    $content = mb_substr($m['content'], 0, 4000);
    $input_items[] = ['role' => $m['role'], 'content' => [['type' => 'input_text', 'text' => $content]]];
}

$payload = [
    'model' => OPENAI_MODEL,
    'input' => $content,
    //'temperature' => 0.7
];

$ch = curl_init('https://api.openai.com/v1/responses');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . OPENAI_API_KEY,
        'Content-Type: application/json'
    ],
    CURLOPT_POSTFIELDS => json_encode($payload)
]);
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_err = curl_error($ch);
curl_close($ch);

if ($response === false) {
    http_response_code(500);
    echo json_encode(['error' => 'Request gagal', 'detail' => $curl_err]);
    exit;
}

$data = json_decode($response, true);
if ($httpcode >= 400) {
    http_response_code($httpcode);
    echo json_encode(['error' => 'OpenAI API error', 'detail' => $data]);
    exit;
}

// Extract text
$assistant_text = '';
if (isset($data['output']) && is_array($data['output'])) {
    foreach ($data['output'] as $item) {
        if (isset($item['content']) && is_array($item['content'])) {
            foreach ($item['content'] as $c) {
                if (isset($c['text'])) { $assistant_text .= $c['text']; }
            }
        }
    }
}
if ($assistant_text === '' && isset($data['output_text'])) {
    $assistant_text = $data['output_text'];
}
if ($assistant_text === '') {
    $assistant_text = 'Maaf, tidak ada keluaran teks dari model.';
}

$openai_resp_id = isset($data['id']) ? $data['id'] : null;
add_message($conversation_id, 'assistant', $assistant_text, $openai_resp_id);

echo json_encode(['ok' => true, 'conversation_id' => $conversation_id, 'message' => $assistant_text]);
