<?php

use MintyPHP\Service\Tenant\TenantServicesFactory;

define('MINTY_ALLOW_OUTPUT', true);

$query = requestInput()->queryAll();
$uuid = trim((string) ($query['uuid'] ?? ''));
$theme = strtolower(trim((string) ($query['theme'] ?? '')));
$size = isset($query['size']) ? (int) $query['size'] : null;
$tenantLogoService = (app(TenantServicesFactory::class))->createTenantLogoService();
if (!$tenantLogoService->isValidUuid($uuid) || !$tenantLogoService->isValidTheme($theme)) {
    http_response_code(404);
    return;
}

$tenant = app(\MintyPHP\Service\Directory\DirectoryServicesFactory::class)->createTenantService()->findByUuid($uuid);
if (!$tenant || (string) ($tenant['status'] ?? 'active') !== 'active') {
    http_response_code(404);
    return;
}

$path = $tenantLogoService->findLogoPath($uuid, $theme, $size);
if (!$path || !is_file($path)) {
    http_response_code(404);
    return;
}

$mime = $tenantLogoService->detectMime($path);
header('Content-Type: ' . $mime);
header('X-Content-Type-Options: nosniff');
header('Content-Security-Policy: sandbox');
header('Cache-Control: public, max-age=300');
header('Content-Length: ' . filesize($path));
readfile($path);
