<?php

use MintyPHP\Service\Access\TenantAuthorizationPolicy;
use MintyPHP\Support\Guard;

Guard::requireLogin();

header('Content-Type: application/json; charset=utf-8');

if (!actionRequirePost(
    'admin/tenants',
    jsonAware: true,
    jsonError: 'Method not allowed',
    jsonPayload: ['ok' => false, 'error' => 'Method not allowed'],
    forceJson: true
)) {
    return;
}

if (!actionRequireCsrf(
    'admin/tenants',
    jsonAware: true,
    jsonError: 'CSRF token invalid',
    jsonStatusCode: 403,
    jsonPayload: ['ok' => false, 'error' => 'CSRF token invalid'],
    flashOnFailure: false,
    redirectOnFailure: false,
    forceJson: true
)) {
    return;
}

$session = app(\MintyPHP\Http\SessionStoreInterface::class)->all();
$currentUserId = (int) ($session['user']['id'] ?? 0);
$decision = app(\MintyPHP\Service\Access\AuthorizationService::class)->authorize(
    TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_EDIT_CONTEXT,
    [
        'actor_user_id' => $currentUserId,
        'target_tenant_id' => (int) (requestInput()->bodyAll()['tenant_id'] ?? 0),
    ]
);
if (!$decision->isAllowed()) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'Forbidden']);
    return;
}

$capabilities = $decision->attribute('capabilities', []);
if (!is_array($capabilities) || empty($capabilities['can_manage_sso'])) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'Forbidden']);
    return;
}

$post = requestInput()->bodyAll();
$host = trim((string) ($post['ldap_host'] ?? ''));
$port = (int) ($post['ldap_port'] ?? 389);
$encryptionMode = (string) ($post['ldap_encryption_mode'] ?? 'starttls');
$verifyTls = !empty($post['ldap_verify_tls_certificate']);
$baseDn = trim((string) ($post['ldap_base_dn'] ?? ''));
$bindDn = trim((string) ($post['ldap_bind_dn'] ?? ''));
$bindPassword = trim((string) ($post['ldap_bind_password'] ?? ''));
$networkTimeout = max(1, min(10, (int) ($post['ldap_network_timeout'] ?? 5)));

if ($host === '') {
    echo json_encode(['ok' => false, 'error' => t('LDAP host is required')]);
    return;
}

$ldapAuthService = app(\MintyPHP\Service\Auth\LdapAuthService::class);

$config = [
    'host' => $host,
    'port' => $port,
    'encryption_mode' => $encryptionMode,
    'verify_tls_certificate' => $verifyTls,
    'base_dn' => $baseDn,
    'bind_dn' => $bindDn,
    'bind_password' => $bindPassword,
    'network_timeout' => $networkTimeout,
];

$result = $ldapAuthService->testConnection($config);

echo json_encode($result);
