<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\TenantAuthorizationPolicy;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
$request = requestInput();
$returnTarget = requestResolveReturnTarget();
$closeTarget = requestResolveReturnTarget('admin/tenants');
$createTarget = requestPathWithReturnTarget('admin/tenants/create', $returnTarget);

$currentUserId = (int) ($session['user']['id'] ?? 0);
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$decision = $authorizationService->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_CREATE, [
    'actor_user_id' => $currentUserId,
]);
if (!$decision->isAllowed()) {
    Guard::deny();
}
$capabilities = $decision->attribute('capabilities', []);
$canManageSso = is_array($capabilities) ? (bool) ($capabilities['can_manage_sso'] ?? false) : false;
$canManageCustomFields = is_array($capabilities) ? (bool) ($capabilities['can_manage_custom_fields'] ?? false) : false;
$tenantSsoService = app(\MintyPHP\Service\Auth\TenantSsoService::class);

$errorBag = formErrors();
$errors = [];
$form = [
    'description' => '',
    'address' => '',
    'postal_code' => '',
    'city' => '',
    'country' => '',
    'region' => '',
    'vat_id' => '',
    'tax_number' => '',
    'phone' => '',
    'fax' => '',
    'email' => '',
    'support_email' => '',
    'support_phone' => '',
    'billing_email' => '',
    'website' => '',
    'privacy_url' => '',
    'imprint_url' => '',
    'primary_color' => '',
    'primary_color_use_default' => 0,
    'default_theme' => '',
    'allow_user_theme_mode' => '',
    'status' => 'active',
];
$ssoUiState = $canManageSso ? $tenantSsoService->buildMicrosoftUiState(0, $form) : [];

if ($request->isMethod('POST') && !Session::checkCsrfToken()) {
    Flash::error(t('Form expired, please try again'), $createTarget, 'csrf_expired');
    Router::redirect($createTarget);
    return;
}

if ($request->hasBody('description')) {
    $post = $request->bodyAll();
    $ssoFields = [
        'microsoft_enabled',
        'enforce_microsoft_login',
        'sync_profile_on_login',
        'sync_profile_fields',
        'entra_tenant_id',
        'allowed_domains',
        'use_shared_app',
        'client_id_override',
        'client_secret_override',
        'clear_client_secret_override',
    ];
    foreach ($ssoFields as $ssoField) {
        if (array_key_exists($ssoField, $post) && !$canManageSso) {
            Router::redirect('error/forbidden');
            return;
        }
    }
    $result = app(\MintyPHP\Service\Tenant\TenantService::class)->createFromAdmin($post, $currentUserId);
    $form = $result['form'] ?? $form;
    $errorBag->merge($result['errors'] ?? []);
    if ($canManageSso) {
        $form = array_merge($form, [
            'microsoft_enabled' => !empty($post['microsoft_enabled']) ? '1' : '0',
            'enforce_microsoft_login' => !empty($post['enforce_microsoft_login']) ? '1' : '0',
            'sync_profile_on_login' => !empty($post['sync_profile_on_login']) ? '1' : '0',
            'sync_profile_fields_list' => $tenantSsoService->normalizeProfileSyncFields($post['sync_profile_fields'] ?? []),
            'entra_tenant_id' => trim((string) ($post['entra_tenant_id'] ?? '')),
            'allowed_domains' => trim((string) ($post['allowed_domains'] ?? '')),
            'use_shared_app' => !empty($post['use_shared_app']) ? '1' : '0',
            'client_id_override' => trim((string) ($post['client_id_override'] ?? '')),
            'auto_remember_mode' => $post['microsoft_auto_remember_mode'] ?? null,
        ]);
        $ssoUiState = $tenantSsoService->buildMicrosoftUiState(0, $post);
    }

    if (($result['ok'] ?? false) && !$errorBag->hasAny()) {
        if ($canManageSso) {
            $createdTenantId = (int) ($result['id'] ?? 0);
            if ($createdTenantId > 0) {
                $ssoSaveResult = $tenantSsoService->saveTenantMicrosoftAuth($createdTenantId, $post);
                if (!($ssoSaveResult['ok'] ?? false)) {
                    Flash::error(
                        (string) (($ssoSaveResult['errors'][0] ?? t('Tenant SSO settings could not be saved'))),
                        $closeTarget,
                        'tenant_sso_create_failed'
                    );
                }
            }
        }
        $action = (string) ($post['action'] ?? 'create');
        if ($action === 'create_close') {
            Flash::success('Tenant created', $closeTarget, 'tenant_created');
            Router::redirect($closeTarget);
        } else {
            $uuid = (string) ($result['uuid'] ?? '');
            if ($uuid !== '') {
                $target = requestPathWithReturnTarget("admin/tenants/edit/{$uuid}", $returnTarget);
                Flash::success('Tenant created', $target, 'tenant_created');
                Router::redirect($target);
            } else {
                Flash::success('Tenant created', $closeTarget, 'tenant_created');
                Router::redirect($closeTarget);
            }
        }
    }
}

$validationSummaryErrors = $errorBag->toArray();
$errors = $errorBag->toFlatList();
Buffer::set('title', t('Create tenant'));
