<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\TenantAuthorizationPolicy;
use MintyPHP\Service\CustomField\TenantCustomFieldService;
use MintyPHP\Session;
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);

$tenantUuid = trim((string) ($id ?? ''));
$tenant = $tenantUuid !== '' ? app(\MintyPHP\Service\Tenant\TenantService::class)->findByUuid($tenantUuid) : null;
if (!$tenant) {
    Flash::error(t('Tenant not found'), 'admin/tenants', 'tenant_not_found');
    Router::redirect('admin/tenants');
    return;
}

$tenantId = (int) ($tenant['id'] ?? 0);
$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;
}

$flashScope = 'admin/tenants/edit/' . $tenantUuid;
$redirect = $flashScope . '?tab=custom_fields';
if (!$request->isMethod('POST')) {
    Router::redirect($redirect);
    return;
}
if (!Session::checkCsrfToken()) {
    Flash::error(t('Form expired, please try again'), $flashScope, 'tenant_custom_fields_csrf');
    Router::redirect($redirect);
    return;
}

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

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