<?php

use MintyPHP\Buffer;
use MintyPHP\Module\Security\Repository\SecurityTokenRepository;
use MintyPHP\Module\Security\SecurityAuthorizationPolicy;
use MintyPHP\Module\Security\Service\SecurityBcSettingsGateway;
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requireAbilityOrForbidden(SecurityAuthorizationPolicy::ABILITY_SETTINGS_MANAGE);

$request = requestInput();
$settingsGateway = app(SecurityBcSettingsGateway::class);
$tokenRepository = app(SecurityTokenRepository::class);

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

    return;
}

if ($request->isMethod('POST')) {
    $post = $request->bodyAll();
    $authMode = trim((string) ($post['auth_mode'] ?? SecurityBcSettingsGateway::AUTH_MODE_BASIC));
    $odataBaseUrl = trim((string) ($post['odata_base_url'] ?? ''));
    $companyName = trim((string) ($post['company_name'] ?? ''));
    $basicUser = trim((string) ($post['basic_user'] ?? ''));
    $basicPassword = trim((string) ($post['basic_password'] ?? ''));
    $oauthTenantId = trim((string) ($post['oauth_tenant_id'] ?? ''));
    $oauthClientId = trim((string) ($post['oauth_client_id'] ?? ''));
    $oauthClientSecret = trim((string) ($post['oauth_client_secret'] ?? ''));
    $oauthTokenEndpoint = trim((string) ($post['oauth_token_endpoint'] ?? ''));

    $errorBag = formErrors();
    if ($odataBaseUrl !== '' && !preg_match('#^https://#i', $odataBaseUrl)) {
        $errorBag->add('odata_base_url', t('OData Base URL must use HTTPS'));
    }
    if ($oauthTokenEndpoint !== '' && !preg_match('#^https://#i', $oauthTokenEndpoint)) {
        $errorBag->add('oauth_token_endpoint', t('Token endpoint must use HTTPS'));
    }

    if (!$errorBag->hasAny()) {
        $settingsGateway->setAuthMode($authMode);
        $settingsGateway->setODataBaseUrl($odataBaseUrl !== '' ? $odataBaseUrl : null);
        $settingsGateway->setCompanyName($companyName !== '' ? $companyName : null);
        $settingsGateway->setBasicUser($basicUser !== '' ? $basicUser : null);
        if ($basicPassword !== '') {
            $settingsGateway->setBasicPassword($basicPassword);
        }
        $settingsGateway->setOAuthTenantId($oauthTenantId !== '' ? $oauthTenantId : null);
        $settingsGateway->setOAuthClientId($oauthClientId !== '' ? $oauthClientId : null);
        if ($oauthClientSecret !== '') {
            $settingsGateway->setOAuthClientSecret($oauthClientSecret);
        }
        $settingsGateway->setOAuthTokenEndpoint($oauthTokenEndpoint !== '' ? $oauthTokenEndpoint : null);

        $tokenRepository->deleteAll();
        Flash::success(t('Settings saved'), 'security/settings', 'settings_saved');
    } else {
        flashFormErrors($errorBag, 'security/settings', 'settings_error');
    }

    Router::redirect('security/settings');

    return;
}

$authMode = $settingsGateway->getAuthMode();
$odataBaseUrl = $settingsGateway->getODataBaseUrl();
$companyName = $settingsGateway->getCompanyName();
$basicUser = $settingsGateway->getBasicUser() ?? '';
$hasBasicPassword = $settingsGateway->getBasicPassword() !== null;
$oauthTenantId = $settingsGateway->getOAuthTenantId() ?? '';
$oauthClientId = $settingsGateway->getOAuthClientId() ?? '';
$hasOAuthClientSecret = $settingsGateway->getOAuthClientSecret() !== null;
$oauthTokenEndpoint = $settingsGateway->getOAuthTokenEndpoint() ?? '';
$configErrors = $settingsGateway->validateConfiguration();

Buffer::set('title', t('Security settings'));
Buffer::set('style_groups', json_encode(['security']));
$breadcrumbs = [
    ['label' => t('Home'), 'path' => 'admin'],
    ['label' => t('Security'), 'path' => 'security/checks'],
    ['label' => t('Settings')],
];
