<?php

use MintyPHP\Buffer;
use MintyPHP\Router;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Auth\AuthServicesFactory;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

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

$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
$canManageSso = permissionGateway()->userHas($currentUserId, PermissionService::TENANTS_SSO_MANAGE);
$tenantSsoService = (new AuthServicesFactory())->createTenantSsoService();

$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 (isset($_POST['description'])) {
    $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 = directoryServicesFactory()->createTenantService()->createFromAdmin($_POST, $currentUserId);
    $form = $result['form'] ?? $form;
    $errors = $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'] ?? '')),
        ]);
        $ssoUiState = $tenantSsoService->buildMicrosoftUiState(0, $_POST);
    }

    if ($result['ok'] ?? false) {
        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'))),
                        'admin/tenants',
                        'tenant_sso_create_failed'
                    );
                }
            }
        }
        $action = (string) ($_POST['action'] ?? 'create');
        if ($action === 'create_close') {
            Flash::success('Tenant created', 'admin/tenants', 'tenant_created');
            Router::redirect('admin/tenants');
        } else {
            $uuid = (string) ($result['uuid'] ?? '');
            if ($uuid !== '') {
                $target = "admin/tenants/edit/{$uuid}";
                Flash::success('Tenant created', $target, 'tenant_created');
                Router::redirect($target);
            } else {
                Flash::success('Tenant created', 'admin/tenants', 'tenant_created');
                Router::redirect('admin/tenants');
            }
        }
    }
}

Buffer::set('title', t('Create tenant'));
