<?php

use MintyPHP\Router;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\CustomField\TenantCustomFieldService;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requirePermissionOrForbidden(PermissionService::CUSTOM_FIELDS_MANAGE);

$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);
if (!directoryServicesFactory()->createDirectoryScopeGateway()->canAccess('tenants', $tenantId, $currentUserId)) {
    Router::redirect('error/forbidden');
    return;
}

$tenant = directoryServicesFactory()->createTenantService()->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 (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== '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::updateByUuid($fieldUuid, $_POST, $currentUserId);
if (!($result['ok'] ?? false)) {
    $errors = $result['errors'] ?? [];
    $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);
