<?php
/* POST /api/voice.php?order_id=<id>
 *   multipart: file=<audio-blob> — speichert Audio-Notiz zum Auftrag
 *
 * Audio wird als Anhang im Auftrags-Verzeichnis abgelegt.
 * Dateiname: voice_<timestamp>.webm (oder .mp3/.ogg je nach mime)
 */
require_once __DIR__.'/_inc.php';

api_authenticate();
global $db, $user, $conf;

if (!$user->hasRight('bericht', 'write')) api_fail('Permission denied', 403);

$order_id = (int) ($_GET['order_id'] ?? 0);
if (!$order_id) api_fail('order_id fehlt');

if (empty($_FILES['file']['tmp_name'])) api_fail('file fehlt');

require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';

$cmd = new Commande($db);
if ($cmd->fetch($order_id) <= 0) api_fail('Auftrag nicht gefunden', 404);

$upload_dir = $conf->commande->multidir_output[$cmd->entity].'/'.dol_sanitizeFileName($cmd->ref);
if (!is_dir($upload_dir)) dol_mkdir($upload_dir);

$mime = $_FILES['file']['type'] ?? 'audio/webm';
$ext = 'webm';
if (strpos($mime, 'mp4') !== false) $ext = 'mp4';
elseif (strpos($mime, 'mp3') !== false || strpos($mime, 'mpeg') !== false) $ext = 'mp3';
elseif (strpos($mime, 'ogg') !== false) $ext = 'ogg';

$filename = 'voice_'.dol_print_date(dol_now(), '%Y%m%d_%H%M%S').'.'.$ext;
$target = $upload_dir.'/'.$filename;
if (!move_uploaded_file($_FILES['file']['tmp_name'], $target)) api_fail('Upload fehlgeschlagen', 500);

api_ok(array('filename' => $filename, 'path' => 'commande/'.dol_sanitizeFileName($cmd->ref).'/'.$filename));
