<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\TenantAuthorizationPolicy;
use MintyPHP\Service\Tenant\TenantLogoService;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$tenantLogoService = app(TenantLogoService::class);

if (!actionRequirePost('admin/tenants')) {
    return;
}

if (!actionRequireCsrf('admin/tenants', 'admin/tenants', 'tenant_logo_delete')) {
    return;
}

$errorBag = formErrors();
$uuid = trim((string) ($id ?? ''));
if (!$tenantLogoService->isValidUuid($uuid)) {
    $errorBag->addGlobal('Tenant not found');
    flashFormErrors($errorBag, 'admin/tenants', 'tenant_logo_delete');
    Router::redirect('admin/tenants');
    return;
}

$body = requestInput()->bodyAll();
$theme = strtolower(trim((string) ($body['theme'] ?? '')));
if (!$tenantLogoService->isValidTheme($theme)) {
    $errorBag->addGlobal(t('Invalid theme'));
    flashFormErrors($errorBag, "admin/tenants/edit/{$uuid}", 'tenant_logo_delete');
    Router::redirect("admin/tenants/edit/{$uuid}");
    return;
}

$tenant = app(\MintyPHP\Service\Tenant\TenantService::class)->findByUuid($uuid);
$tenantId = (int) ($tenant['id'] ?? 0);
$currentUserId = (int) ($session['user']['id'] ?? 0);
$decision = $authorizationService->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_MEDIA_UPDATE, [
    'actor_user_id' => $currentUserId,
    'target_tenant_id' => $tenantId,
]);
if (!$decision->isAllowed()) {
    Router::redirect('error/forbidden');
    return;
}

$tenantLogoService->delete($uuid, $theme);
Flash::success('Logo removed', "admin/tenants/edit/{$uuid}", 'tenant_logo_removed');
Router::redirect("admin/tenants/edit/{$uuid}");
