<?php
// public_html/v.centrx.eu/api/translate.php

require __DIR__ . '/config.php';

// Включаем ошибки для отладки (потом можно убрать)
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

// Отдаём JSON
header('Content-Type: application/json; charset=utf-8');

// Читаем вход
$payload = json_decode(file_get_contents('php://input'), true);
$text    = trim($payload['text']   ?? '');
$source  = $payload['source']      ?? 'auto';
$target  = $payload['target']      ?? 'auto';

if ($text === '') {
    http_response_code(400);
    echo json_encode(['error' => 'Empty text']);
    exit;
}

// Формируем сообщения
$messages = [
    ['role' => 'system', 'content' => "You are a translator from $source to $target."],
    ['role' => 'user',   'content' => $text],
];

// Тело запроса
$postData = json_encode([
    'model'    => 'gpt-3.5-turbo',
    'messages' => $messages,
]);

// Инициализируем cURL
$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . OPENAI_API_KEY,
    'Content-Type: application/json',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

$response = curl_exec($ch);
$code     = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$error    = curl_error($ch);
curl_close($ch);

if ($error) {
    http_response_code(500);
    echo json_encode(['error' => 'cURL error: ' . $error]);
    exit;
}

$data = json_decode($response, true);
if ($code !== 200) {
    http_response_code($code);
    $msg = $data['error']['message'] ?? $response;
    echo json_encode(['error' => $msg]);
    exit;
}

// Отдаём перевод
$translation = $data['choices'][0]['message']['content'] ?? '';
echo json_encode(['translation' => trim($translation)]);
