<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;

/**
 * UploadsController — securely serves files from writable/uploads/.
 * Only accessible to authenticated admins.
 */
class UploadsController extends BaseController
{
    public function serve(string $path = '')
    {
        // Sanitise path — prevent directory traversal
        $path = ltrim(str_replace(['..', '\\'], '', $path), '/');

        if (empty($path)) {
            return $this->response->setStatusCode(404);
        }

        $fullPath = WRITEPATH . 'uploads/' . $path;

        if (! file_exists($fullPath) || ! is_file($fullPath)) {
            return $this->response->setStatusCode(404);
        }

        $mime = mime_content_type($fullPath) ?: 'application/octet-stream';

        return $this->response
                    ->setHeader('Content-Type', $mime)
                    ->setHeader('Cache-Control', 'private, max-age=3600')
                    ->setHeader('X-Content-Type-Options', 'nosniff')
                    ->setBody(file_get_contents($fullPath));
    }
}
