<?php
// public_html/v.centrx.eu/api/stt.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');

// Проверяем файл
if (!isset($_FILES['file']) || !is_uploaded_file($_FILES['file']['tmp_name'])) {
    http_response_code(400);
    echo json_encode(['error' => 'No audio file uploaded']);
    exit;
}

$audioPath = $_FILES['file']['tmp_name'];
$lang      = $_POST['lang'] ?? 'en';

// Готовим поля для multipart
$postFields = [
    'model'    => 'whisper-1',
    'language' => $lang,
    'file'     => new CURLFile($audioPath, mime_content_type($audioPath), 'audio.webm'),
];

// Инициализируем cURL
$ch = curl_init('https://api.openai.com/v1/audio/transcriptions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . OPENAI_API_KEY,
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_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 ($httpCode !== 200) {
    http_response_code($httpCode);
    $msg = $data['error']['message'] ?? $response;
    echo json_encode(['error' => $msg]);
    exit;
}

// Всё OK
echo json_encode(['text' => $data['text'] ?? '']);
