<?php
// app/Controllers/MediaController.php

namespace App\Controllers;

use Core\Response;

class MediaController
{
    /**
     * Serve images securely from storage.
     *
     * Example URL: /media/vehicles/abc123.jpg
     */
    public function serve($path = '')
    {
        $path = trim($path, '/');

        if (!$path) {
            Response::abort(404);
        }

        $filePath = FS_STORAGE_PATH . DIRECTORY_SEPARATOR . $path;

        if (!file_exists($filePath) || !is_readable($filePath)) {
            Response::abort(404);
        }

        // Get mime type
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = $finfo ? finfo_file($finfo, $filePath) : 'application/octet-stream';
        finfo_close($finfo);

        // Serve file with headers
        header("Content-Type: {$mimeType}");
        header("Content-Length: " . filesize($filePath));

        readfile($filePath);
        exit;
    }
}
