<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\SettingsAuthorizationPolicy;
use MintyPHP\Service\Settings\AdminSettingsService;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
$request = requestInput();

$currentUserId = (int) ($session['user']['id'] ?? 0);
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$viewDecision = $authorizationService->authorize(SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_VIEW, [
    'actor_user_id' => $currentUserId,
]);
if (!$viewDecision->isAllowed()) {
    Guard::deny();
}
$viewCapabilities = $viewDecision->attribute('capabilities', []);
$canUpdateSettings = is_array($viewCapabilities) ? (bool) ($viewCapabilities['can_update_settings'] ?? false) : false;

$adminSettingsService = app(AdminSettingsService::class);
$pageData = $adminSettingsService->buildPageData();
$tenants = is_array($pageData['tenants'] ?? null) ? $pageData['tenants'] : [];
$roles = is_array($pageData['roles'] ?? null) ? $pageData['roles'] : [];
$departments = is_array($pageData['departments'] ?? null) ? $pageData['departments'] : [];
$values = is_array($pageData['values'] ?? null) ? $pageData['values'] : [];
$settings = is_array($pageData['settings'] ?? null) ? $pageData['settings'] : [];
$activeLoginTokens = (int) ($pageData['active_login_tokens'] ?? 0);
$activeApiTokens = (int) ($pageData['active_api_tokens'] ?? 0);

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

if ($request->isMethod('POST')) {
    $post = $request->bodyAll();
    if (!array_key_exists('settings_submit', $post)) {
        Router::redirect('admin/settings');
    }

    $updateDecision = $authorizationService->authorize(SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_UPDATE, [
        'actor_user_id' => $currentUserId,
    ]);
    if (!$updateDecision->isAllowed()) {
        Guard::deny();
    }

    $updateResult = $adminSettingsService->updateFromAdmin($post);
    $errorBag = formErrors();
    foreach ((array) ($updateResult['errors'] ?? []) as $error) {
        if (is_array($error)) {
            $message = trim((string) ($error['message'] ?? ''));
            $field = trim((string) ($error['field'] ?? 'input'));
            if ($message !== '') {
                $errorBag->add($field !== '' ? $field : 'input', $message);
            }
            continue;
        }

        $message = trim((string) $error);
        if ($message !== '') {
            $errorBag->addGlobal($message);
        }
    }

    if ($errorBag->hasAny()) {
        flashFormErrors($errorBag, 'admin/settings', 'settings_update_error');
        Router::redirect('admin/settings');
    }

    Flash::success('Settings updated', 'admin/settings', 'settings_updated');
    Router::redirect('admin/settings');
}

Buffer::set('title', t('Settings'));
