<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/config.php';
require_once __DIR__ . '/../src/logger.php';
require_once __DIR__ . '/../src/settings.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, max-age=0');
header('X-Content-Type-Options: nosniff');

try {
    $headers = function_exists('getallheaders') ? getallheaders() : [];
    $authorization = (string) ($headers['Authorization'] ?? $headers['authorization'] ?? '');
    $accessToken = preg_match('/^Bearer\s+(.+)$/i', $authorization, $matches)
        ? trim((string) $matches[1])
        : '';
    $domain = (string) ($headers['X-Bitrix-Domain'] ?? $headers['x-bitrix-domain'] ?? '');
    $user = authorizeAppSettingsRequest($domain, $accessToken);

    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        echo json_encode([
            'ok' => true,
            'groups' => appSettingsGroups(),
            'values' => currentAppSettingsForUi(),
            'user' => [
                'id' => (string) ($user['ID'] ?? ''),
                'name' => trim((string) (($user['NAME'] ?? '') . ' ' . ($user['LAST_NAME'] ?? ''))),
            ],
        ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        throw new RuntimeException('Метод не поддерживается.');
    }

    $payload = json_decode((string) file_get_contents('php://input'), true);
    if (!is_array($payload) || !is_array($payload['values'] ?? null)) {
        throw new InvalidArgumentException('Некорректный формат настроек.');
    }

    $requestedPortalHost = strtolower((string) parse_url(
        (string) ($payload['values']['BITRIX_PORTAL_URL'] ?? ''),
        PHP_URL_HOST
    ));
    if ($requestedPortalHost !== strtolower(trim($domain))) {
        throw new InvalidArgumentException('Портал Bitrix24 должен совпадать с текущим порталом.');
    }
    $requestedUsers = normalizeAppSettingValue(
        $payload['values']['SETTINGS_ALLOWED_USER_IDS'] ?? [],
        ['type' => 'csv', 'item_type' => 'integer']
    );
    $adminAccessAllowed = (bool) config('SETTINGS_ALLOW_PORTAL_ADMINS', true)
        && isBitrixPortalAdministrator($user);
    if (!$adminAccessAllowed && !in_array((int) ($user['ID'] ?? 0), $requestedUsers, true)) {
        throw new InvalidArgumentException('Нельзя удалить текущего пользователя из списка доступа.');
    }

    $saved = saveAppSettings($payload['values'], $user);
    global $config;
    $config = array_replace($config, $saved['values']);

    logMessage('info', 'Application settings updated', [
        'user_id' => (string) ($user['ID'] ?? ''),
        'keys' => array_keys($saved['values']),
    ]);

    echo json_encode([
        'ok' => true,
        'saved_at' => $saved['updated_at'],
        'values' => currentAppSettingsForUi(),
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (InvalidArgumentException $exception) {
    http_response_code(422);
    echo json_encode(['ok' => false, 'error' => $exception->getMessage()], JSON_UNESCAPED_UNICODE);
} catch (Throwable $exception) {
    if (http_response_code() < 400) {
        http_response_code(403);
    }
    echo json_encode(['ok' => false, 'error' => $exception->getMessage()], JSON_UNESCAPED_UNICODE);
}
