<?php
require_once __DIR__ . '/../includes/bootstrap.php';
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'message' => 'Method not allowed']);
    exit;
}
if (empty($_FILES['audio']) || !is_uploaded_file($_FILES['audio']['tmp_name'])) {
    echo json_encode(['ok' => false, 'message' => 'No audio uploaded.']);
    exit;
}
$file = $_FILES['audio'];
if (($file['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
    echo json_encode(['ok' => false, 'message' => 'Upload failed.']);
    exit;
}
if (($file['size'] ?? 0) > 10 * 1024 * 1024) {
    echo json_encode(['ok' => false, 'message' => 'Voice clip too large.']);
    exit;
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']) ?: 'application/octet-stream';
finfo_close($finfo);
$allowed = [
    'audio/webm' => 'webm',
    'audio/ogg' => 'ogg',
    'audio/mpeg' => 'mp3',
    'audio/mp4' => 'm4a',
    'audio/x-m4a' => 'm4a',
    'video/webm' => 'webm',
];
if (!isset($allowed[$mime])) {
    echo json_encode(['ok' => false, 'message' => 'Unsupported audio format.']);
    exit;
}
$dir = $ugfx['storage']['chat_uploads'] ?? (__DIR__ . '/../storage/chat');
ugfx_protect_storage_dir($dir);
$name = 'voice_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $allowed[$mime];
$target = rtrim($dir, '/\\') . DIRECTORY_SEPARATOR . $name;
if (!move_uploaded_file($file['tmp_name'], $target)) {
    echo json_encode(['ok' => false, 'message' => 'Could not save audio.']);
    exit;
}
$url = 'storage/chat/' . $name;
echo json_encode(['ok' => true, 'url' => $url, 'mime' => $mime], JSON_UNESCAPED_SLASHES);
