<?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);

$tenantUuid = trim((string) ($id ?? ''));
$tenant = $tenantUuid !== '' ? directoryServicesFactory()->createTenantService()->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);
if (!directoryServicesFactory()->createDirectoryScopeGateway()->canAccess('tenants', $tenantId, $currentUserId)) {
    Router::redirect('error/forbidden');
    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::createForTenant($tenantId, $_POST, $currentUserId);
if (!($result['ok'] ?? false)) {
    $errors = $result['errors'] ?? [];
    $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);
