<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../lib/Env.php';
require_once __DIR__ . '/../../lib/Database.php';
require_once __DIR__ . '/../../lib/OpenAIClient.php';

load_env(__DIR__ . '/../../.env');

function json_fail($msg, $code=400) {
    http_response_code(200);
    echo json_encode(['ok'=>false, 'error'=>$msg], JSON_UNESCAPED_UNICODE);
    exit;
}
$body = json_decode(file_get_contents('php://input'), true);
$message = isset($body['message']) ? trim($body['message']) : '';
$conversationId = isset($body['conversation_id']) ? intval($body['conversation_id']) : null;

if ($message === '') json_fail('Empty message');

try {
    $db = new Database();
    $pdo = $db->pdo();

    // Ensure conversation
    if (!$conversationId) {
        $pdo->prepare("INSERT INTO conversations(title) VALUES(NULL)")->execute();
        $conversationId = (int)$pdo->lastInsertId();
    }

    // Insert user message
    $stmt = $pdo->prepare("INSERT INTO messages (conversation_id, role, content) VALUES (?, 'user', ?)");
    $stmt->execute([$conversationId, $message]);

    // Build message history (last 15 messages)
    $hist = $pdo->prepare("SELECT role, content FROM messages WHERE conversation_id=? ORDER BY id ASC LIMIT 30");
    $hist->execute([$conversationId]);
    $rows = $hist->fetchAll();

    // Prepend a lightweight system prompt
    array_unshift($rows, ['role' => 'system', 'content' => 'You are a helpful assistant. Reply in the same language as the user if possible.']);

    // Call OpenAI
    $client = new OpenAIClient();
    $reply = $client->createResponse($rows);

    // Save assistant reply
    $stmt2 = $pdo->prepare("INSERT INTO messages (conversation_id, role, content) VALUES (?, 'assistant', ?)");
    $stmt2->execute([$conversationId, $reply]);

    echo json_encode(['ok'=>true, 'conversation_id'=>$conversationId, 'reply'=>$reply], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    json_fail($e->getMessage());
}