<?php

use MintyPHP\Router;
use MintyPHP\Service\Tenant\TenantServicesFactory;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;
use MintyPHP\Service\Access\PermissionService;

Guard::requireLogin();
Guard::requirePermissionOrForbidden(PermissionService::TENANTS_UPDATE);
$tenantFaviconService = (new TenantServicesFactory())->createTenantFaviconService();

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
    Router::redirect('admin/tenants');
    return;
}

$uuid = trim((string) ($id ?? ''));
if (!$tenantFaviconService->isValidUuid($uuid)) {
    Flash::error('Tenant not found', 'admin/tenants', 'tenant_not_found');
    Router::redirect('admin/tenants');
    return;
}

$result = $tenantFaviconService->saveUpload($uuid, $_FILES['favicon'] ?? []);
if (!($result['ok'] ?? false)) {
    $error = $result['error'] ?? t('Upload failed');
    Flash::error($error, "admin/tenants/edit/{$uuid}", 'tenant_favicon_upload_failed');
    Router::redirect("admin/tenants/edit/{$uuid}");
    return;
}

Flash::success('Favicon updated', "admin/tenants/edit/{$uuid}", 'tenant_favicon_updated');
Router::redirect("admin/tenants/edit/{$uuid}");
