<?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);
$tenantAvatarService = (new TenantServicesFactory())->createTenantAvatarService();

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

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

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

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