<?php
session_start();
require_once '../../config/database.php';
require_once '../../includes/app_helpers.php';
header('Content-Type: application/json');

if (!isset($_SESSION['csr_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

try {
    $db = (new Database())->getConnection();
    ensureAddressAndCallQueueTables($db);

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

    if ($callId <= 0 || !canCsrAccessCallRequest($db, $csrId, $callId)) {
        echo json_encode(['success' => false, 'message' => 'Access denied.']);
        exit;
    }

    if (empty($_FILES['recording']) || !isset($_FILES['recording']['tmp_name'])) {
        echo json_encode(['success' => false, 'message' => 'No recording uploaded.']);
        exit;
    }

    if ($_FILES['recording']['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['success' => false, 'message' => 'Recording upload failed.']);
        exit;
    }

    $size = (int)($_FILES['recording']['size'] ?? 0);
    if ($size <= 0 || $size > 50 * 1024 * 1024) {
        echo json_encode(['success' => false, 'message' => 'Recording must be 50MB or smaller.']);
        exit;
    }

    $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)) {
        // Some browsers label MediaRecorder audio differently. Keep this permissive but not PHP-executable.
        if (stripos($mime, 'audio/') !== 0 && stripos($mime, 'video/webm') !== 0) {
            echo json_encode(['success' => false, 'message' => 'Invalid recording file type: ' . $mime]);
            exit;
        }
    }

    $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_' . $callId . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
    $target = $dir . '/' . $filename;

    if (!move_uploaded_file($_FILES['recording']['tmp_name'], $target)) {
        echo json_encode(['success' => false, 'message' => 'Unable to save recording.']);
        exit;
    }

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

    $stmt = $db->prepare("UPDATE call_requests
                          SET recording_path = :path,
                              recording_mime = :mime,
                              recording_uploaded_at = NOW()
                          WHERE id = :id");
    $stmt->execute([
        ':path' => $relativePath,
        ':mime' => $mime,
        ':id' => $callId
    ]);

    echo json_encode([
        'success' => true,
        'message' => 'Recording saved.',
        'recording_path' => '../' . $relativePath
    ]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
