<?php

use MintyPHP\Buffer;
use MintyPHP\Router;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Auth\AuthServicesFactory;
use MintyPHP\Service\CustomField\TenantCustomFieldService;
use MintyPHP\Service\User\UserServicesFactory;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;
Guard::requireLogin();
Guard::requirePermissionOrForbidden(PermissionService::TENANTS_VIEW);

$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
if ($currentUserId > 0) {
    permissionGateway()->getUserPermissions($currentUserId);
}
$userAccountService = (new UserServicesFactory())->createUserAccountService();

$uuid = trim((string) ($id ?? ''));
$tenant = $uuid !== '' ? directoryServicesFactory()->createTenantService()->findByUuid($uuid) : null;
if (!$tenant) {
    Flash::error('Tenant not found', 'admin/tenants', 'tenant_not_found');
    Router::redirect('admin/tenants');
}

$tenantId = (int) ($tenant['id'] ?? 0);
$authServicesFactory = new AuthServicesFactory();
$tenantSsoService = $authServicesFactory->createTenantSsoService();
$canManageCustomFields = permissionGateway()->userHas($currentUserId, PermissionService::CUSTOM_FIELDS_MANAGE);
$canManageSso = permissionGateway()->userHas($currentUserId, PermissionService::TENANTS_SSO_MANAGE);
$customFieldDefinitions = $canManageCustomFields
    ? TenantCustomFieldService::listForTenant($tenantId)
    : [];
$ssoConfig = $canManageSso ? $tenantSsoService->getTenantMicrosoftAuth($tenantId) : [];
$ssoUiState = $canManageSso ? $tenantSsoService->buildMicrosoftUiState($tenantId, $ssoConfig) : [];
$creatorId = (int) ($tenant['created_by'] ?? 0);
if ($creatorId > 0) {
    $creator = $userAccountService->findById($creatorId);
    if ($creator) {
        $creatorName = trim(($creator['first_name'] ?? '') . ' ' . ($creator['last_name'] ?? ''));
        $tenant['created_by_label'] = $creatorName !== '' ? $creatorName : ($creator['email'] ?? '');
        $tenant['created_by_uuid'] = $creator['uuid'] ?? null;
    }
}
$modifierId = (int) ($tenant['modified_by'] ?? 0);
if ($modifierId > 0) {
    $modifier = $userAccountService->findById($modifierId);
    if ($modifier) {
        $modifierName = trim(($modifier['first_name'] ?? '') . ' ' . ($modifier['last_name'] ?? ''));
        $tenant['modified_by_label'] = $modifierName !== '' ? $modifierName : ($modifier['email'] ?? '');
        $tenant['modified_by_uuid'] = $modifier['uuid'] ?? null;
    }
}
$statusChangedById = (int) ($tenant['status_changed_by'] ?? 0);
if ($statusChangedById > 0) {
    $statusChanger = $userAccountService->findById($statusChangedById);
    if ($statusChanger) {
        $statusChangerName = trim(($statusChanger['first_name'] ?? '') . ' ' . ($statusChanger['last_name'] ?? ''));
        $tenant['status_changed_by_label'] = $statusChangerName !== '' ? $statusChangerName : ($statusChanger['email'] ?? '');
        $tenant['status_changed_by_uuid'] = $statusChanger['uuid'] ?? null;
    }
}

$errors = [];
$form = array_merge($tenant, $ssoConfig);

if (isset($_POST['description'])) {
    if (!permissionGateway()->userHas($currentUserId, PermissionService::TENANTS_UPDATE)) {
        Router::redirect('error/forbidden');
        return;
    }
    $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()->updateFromAdmin($tenantId, $_POST, $currentUserId);
    $form = $result['form'] ?? $form;
    $errors = $result['errors'] ?? [];

    if ($result['ok'] ?? false) {
        if ($canManageSso) {
            $ssoSaveResult = $tenantSsoService->saveTenantMicrosoftAuth($tenantId, $_POST);
            if (!($ssoSaveResult['ok'] ?? false)) {
                $errors = array_merge($errors, $ssoSaveResult['errors'] ?? [t('Tenant SSO settings could not be saved')]);
            }
        }
    }

    if (($result['ok'] ?? false) && !$errors) {
        if ($currentUserId > 0) {
            $authServicesFactory->createAuthService()->loadTenantDataIntoSession($currentUserId);
        }
        $action = (string) ($_POST['action'] ?? 'save');
        if ($action === 'save_close') {
            Flash::success('Tenant updated', 'admin/tenants', 'tenant_updated');
            Router::redirect('admin/tenants');
        } else {
            Flash::success('Tenant updated', "admin/tenants/edit/{$uuid}", 'tenant_updated');
            Router::redirect("admin/tenants/edit/{$uuid}");
        }
    }

    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($tenantId, $_POST);
    }
}

if ($canManageSso && empty($ssoUiState)) {
    $ssoUiState = $tenantSsoService->buildMicrosoftUiState($tenantId, $form);
}

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