<?php

function getMimeType($file) {
    $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));

    switch ($extension) {
        case 'wav':
            return 'audio/wav';
        default:
            return 'application/octet-stream';
    }
}

if (isset($_GET['path'])) {
    $filePath = $_GET['path'];

    $allowedDir = "../../../data/audio_messages/";
    $realPath = realpath($allowedDir . $filePath);

    if (strpos($realPath, realpath($allowedDir)) !== 0 || !file_exists($realPath)) {
        header('HTTP/1.1 404 Not Found');
        echo 'File not found.';
        exit();
    }

    $mimeType = getMimeType($realPath);
    header('Content-Type: ' . $mimeType);
    header('Content-Length: ' . filesize($realPath));

    readfile($realPath);
    exit();
} else {
    header('HTTP/1.1 400 Bad Request');
    echo 'No file path specified.';
    exit();
}
