<?php

namespace App\Controllers;

/**
 * Serves files written by handle_image_upload() (see app/Helpers/
 * upload_helper.php) back out over HTTP. writable/uploads/ is
 * deliberately outside public/ (CodeIgniter's convention — nothing in
 * writable/ is served directly by the webserver), so anything that
 * needs to appear in an <img> tag on a normal page (tenant logo, menu
 * item photos) has to be streamed through a small controller like this
 * one instead. PDF rendering (invoices, reports) doesn't need this route
 * at all — dompdf reads the file straight off disk and embeds it as a
 * base64 data URI, no HTTP round-trip.
 *
 * Public (no login filter) — these are decorative branding/menu images,
 * not sensitive data, and the login page may want the tenant's logo
 * before a session exists.
 */
class UploadController extends BaseController
{
    public function serve(string $subdir, string $filename)
    {
        // Reject anything that isn't a plain filename component — no
        // traversal via ../, no absolute paths.
        if (str_contains($subdir, '..') || str_contains($filename, '..') || str_contains($filename, '/')) {
            return $this->response->setStatusCode(404);
        }

        $path = WRITEPATH . 'uploads/' . $subdir . '/' . $filename;

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

        $mime = guess_mime_type($path);

        return $this->response
            ->setHeader('Content-Type', $mime)
            ->setHeader('Cache-Control', 'public, max-age=86400')
            ->setBody(file_get_contents($path));
    }
}
