<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\TenantAuthorizationPolicy;
use MintyPHP\Service\CustomField\TenantCustomFieldService;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$tenantCustomFieldService = app(TenantCustomFieldService::class);
$errorBag = formErrors();

$fieldUuid = trim((string) ($id ?? ''));
$tenantId = $tenantCustomFieldService->definitionTenantIdByUuid($fieldUuid);
if ($tenantId <= 0) {
    $errorBag->addGlobal(t('Custom field not found'));
    flashFormErrors($errorBag, 'admin/tenants', 'tenant_custom_field_delete');
    Router::redirect('admin/tenants');
    return;
}

$currentUserId = (int) ($session['user']['id'] ?? 0);
$decision = $authorizationService->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_CUSTOM_FIELDS_MANAGE, [
    'actor_user_id' => $currentUserId,
    'target_tenant_id' => $tenantId,
]);
if (!$decision->isAllowed()) {
    Router::redirect('error/forbidden');
    return;
}

$tenant = app(\MintyPHP\Service\Tenant\TenantService::class)->findById($tenantId);
$tenantUuid = trim((string) ($tenant['uuid'] ?? ''));
if ($tenantUuid === '') {
    $errorBag->addGlobal(t('Tenant not found'));
    flashFormErrors($errorBag, 'admin/tenants', 'tenant_custom_field_delete');
    Router::redirect('admin/tenants');
    return;
}

$flashScope = 'admin/tenants/edit/' . $tenantUuid;
$redirect = $flashScope . '?tab=custom_fields';
if (!actionRequirePost($redirect)) {
    return;
}

if (!actionRequireCsrf($redirect, $flashScope, 'tenant_custom_fields')) {
    return;
}

$result = $tenantCustomFieldService->deleteByUuid($fieldUuid);
if (!($result['ok'] ?? false)) {
    $errorBag->addGlobal(t('Custom field can not be deleted'));
    flashFormErrors($errorBag, $flashScope, 'tenant_custom_field_delete');
    Router::redirect($redirect);
    return;
}

Flash::success(t('Custom field deleted'), $flashScope, 'tenant_custom_field_deleted');
Router::redirect($redirect);
