<?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();
$request = requestInput();
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$tenantCustomFieldService = app(TenantCustomFieldService::class);

$fieldUuid = trim((string) ($id ?? ''));
$tenantId = $tenantCustomFieldService->definitionTenantIdByUuid($fieldUuid);
if ($tenantId <= 0) {
    Flash::error(t('Custom field not found'), 'admin/tenants', 'tenant_custom_field_not_found');
    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 === '') {
    Flash::error(t('Tenant not found'), 'admin/tenants', 'tenant_not_found');
    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_csrf')) {
    return;
}

$result = $tenantCustomFieldService->updateByUuid($fieldUuid, $request->bodyAll(), $currentUserId);
if (!($result['ok'] ?? false)) {
    $errors = formErrorsFrom($result['errors'] ?? [])->toFlatList();
    $message = $errors ? implode(' | ', $errors) : t('Custom field can not be updated');
    Flash::error($message, $flashScope, 'tenant_custom_field_update_failed');
    Router::redirect($redirect);
    return;
}

Flash::success(t('Custom field saved'), $flashScope, 'tenant_custom_field_saved');
Router::redirect($redirect);
