<?php
require_once __DIR__ . '/../../config/webrtc_config.php';
webrtc_require_login();

if (!webrtc_is_csr()) {
    webrtc_json(['ok' => false, 'error' => 'CSR access only'], 403);
}

$db = webrtc_db();
ensureAddressAndCallQueueTables($db);
ensureWebRtcCallWorkflow($db);

$csrId = (int)($_SESSION['csr_id'] ?? 0);
$room = trim((string)($_POST['room_token'] ?? ''));
$callId = (int)($_POST['call_id'] ?? 0);

if ($room === '' && $callId <= 0) {
    webrtc_json(['ok' => false, 'error' => 'Missing room token or call id'], 400);
}

if ($callId > 0) {
    $stmt = $db->prepare('SELECT * FROM call_requests WHERE id = :id LIMIT 1');
    $stmt->execute([':id' => $callId]);
} else {
    $stmt = $db->prepare('SELECT * FROM call_requests WHERE room_token = :room LIMIT 1');
    $stmt->execute([':room' => $room]);
}

$call = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$call) {
    webrtc_json(['ok' => false, 'error' => 'Call not found'], 404);
}

if ($csrId > 0 && function_exists('canCsrAccessCallRequest') && !canCsrAccessCallRequest($db, $csrId, (int)$call['id'])) {
    webrtc_json(['ok' => false, 'error' => 'Access denied'], 403);
}

if (empty($_FILES['recording']) || !isset($_FILES['recording']['tmp_name'])) {
    webrtc_json(['ok' => false, 'error' => 'No recording uploaded.'], 400);
}

if ($_FILES['recording']['error'] !== UPLOAD_ERR_OK) {
    webrtc_json(['ok' => false, 'error' => 'Recording upload failed.'], 400);
}

$size = (int)($_FILES['recording']['size'] ?? 0);
if ($size <= 0 || $size > 75 * 1024 * 1024) {
    webrtc_json(['ok' => false, 'error' => 'Recording must be 75MB or smaller.'], 400);
}

$mime = mime_content_type($_FILES['recording']['tmp_name']) ?: ($_FILES['recording']['type'] ?? 'audio/webm');
$allowed = ['audio/webm', 'video/webm', 'audio/ogg', 'audio/mpeg', 'audio/mp4', 'audio/wav', 'application/octet-stream'];
if (!in_array($mime, $allowed, true)) {
    if (stripos($mime, 'audio/') !== 0 && stripos($mime, 'video/webm') !== 0) {
        webrtc_json(['ok' => false, 'error' => 'Invalid recording file type: ' . $mime], 400);
    }
}

$dir = __DIR__ . '/../../uploads/call_recordings';
safeUploadDirectory($dir);

$ext = 'webm';
if (stripos($mime, 'ogg') !== false) {
    $ext = 'ogg';
} elseif (stripos($mime, 'wav') !== false) {
    $ext = 'wav';
} elseif (stripos($mime, 'mpeg') !== false || stripos($mime, 'mp3') !== false) {
    $ext = 'mp3';
} elseif (stripos($mime, 'mp4') !== false) {
    $ext = 'm4a';
}

$filename = 'call_' . (int)$call['id'] . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
$target = $dir . '/' . $filename;

if (!move_uploaded_file($_FILES['recording']['tmp_name'], $target)) {
    webrtc_json(['ok' => false, 'error' => 'Unable to save recording.'], 500);
}

$relativePath = 'uploads/call_recordings/' . $filename;

$durationSeconds = max(0, (int)($_POST['recording_duration_seconds'] ?? 0));

$update = $db->prepare("UPDATE call_requests
    SET recording_path = :path,
        recording_mime = :mime,
        recording_uploaded_at = NOW(),
        call_duration_seconds = CASE
            WHEN COALESCE(call_duration_seconds, 0) > 0 THEN call_duration_seconds
            WHEN :duration_seconds > 0 THEN :duration_seconds
            ELSE call_duration_seconds
        END
    WHERE id = :id");
$update->execute([
    ':path' => $relativePath,
    ':mime' => $mime,
    ':duration_seconds' => $durationSeconds,
    ':id' => (int)$call['id'],
]);

webrtc_json([
    'ok' => true,
    'recording_path' => $relativePath,
]);
