<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Module\Helpdesk\Service\HelpdeskSettingsGateway;
use MintyPHP\Module\Helpdesk\Service\HelpdeskTenantSettingsGateway;
use MintyPHP\Module\Helpdesk\Repository\HelpdeskTokenRepository;
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

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

$request = requestInput();
$settingsGateway = app(HelpdeskSettingsGateway::class);
$tenantSettingsGateway = app(HelpdeskTenantSettingsGateway::class);
$tokenRepository = app(HelpdeskTokenRepository::class);

$sessionStore = app(SessionStoreInterface::class);
$session = $sessionStore->all();
$currentTenantId = (int) ($session['current_tenant']['id'] ?? 0);
$currentTenantName = trim((string) ($session['current_tenant']['description'] ?? ''));

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

    return;
}

if ($request->isMethod('POST')) {
    $post = $request->bodyAll();
    $target = trim((string) ($post['save_target'] ?? 'global'));

    if ($target === 'tenant' && $currentTenantId > 0) {
        // --- Tenant override save ---
        $overrideEnabled = isset($post['override_enabled']);

        $tenantData = [
            'override_enabled' => $overrideEnabled ? '1' : '0',
            'auth_mode' => trim((string) ($post['tenant_auth_mode'] ?? HelpdeskSettingsGateway::AUTH_MODE_BASIC)),
            'odata_base_url' => trim((string) ($post['tenant_odata_base_url'] ?? '')),
            'company_name' => trim((string) ($post['tenant_company_name'] ?? '')),
            'basic_user' => trim((string) ($post['tenant_basic_user'] ?? '')),
            'oauth_tenant_id' => trim((string) ($post['tenant_oauth_tenant_id'] ?? '')),
            'oauth_client_id' => trim((string) ($post['tenant_oauth_client_id'] ?? '')),
            'oauth_token_endpoint' => trim((string) ($post['tenant_oauth_token_endpoint'] ?? '')),
        ];

        $errorBag = formErrors();

        $tenantOdataUrl = $tenantData['odata_base_url'];
        if ($tenantOdataUrl !== '' && !preg_match('#^https://#i', $tenantOdataUrl)) {
            $errorBag->add('tenant_odata_base_url', t('OData Base URL must use HTTPS'));
        }

        $tenantTokenEndpoint = $tenantData['oauth_token_endpoint'];
        if ($tenantTokenEndpoint !== '' && !preg_match('#^https://#i', $tenantTokenEndpoint)) {
            $errorBag->add('tenant_oauth_token_endpoint', t('Token endpoint must use HTTPS'));
        }

        if (!$errorBag->hasAny()) {
            // Handle secrets — only update if new value provided
            $tenantBasicPassword = trim((string) ($post['tenant_basic_password'] ?? ''));
            if ($tenantBasicPassword !== '') {
                $tenantData['basic_password'] = $tenantBasicPassword;
            }

            $tenantOauthSecret = trim((string) ($post['tenant_oauth_client_secret'] ?? ''));
            if ($tenantOauthSecret !== '') {
                $tenantData['oauth_client_secret'] = $tenantOauthSecret;
            }

            try {
                $saved = $tenantSettingsGateway->save($currentTenantId, $tenantData);
            } catch (\Throwable) {
                $saved = false;
            }
            if ($saved) {
                $tokenRepository->deleteByTenantId($currentTenantId);
                Flash::success(t('Tenant settings saved'), 'helpdesk/settings', 'tenant_settings_saved');
            } else {
                Flash::error(t('Failed to save tenant settings'), 'helpdesk/settings', 'tenant_settings_error');
            }
        } else {
            flashFormErrors($errorBag, 'helpdesk/settings', 'tenant_settings_error');
        }

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

        return;
    }

    // --- Global save (existing flow) ---
    $post = $request->bodyAll();

    $authMode = trim((string) ($post['auth_mode'] ?? HelpdeskSettingsGateway::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'] ?? ''));
    $recommendationsMaxItems = (int) ($post['recommendations_max_items'] ?? 5);

    $errorBag = formErrors();

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

    if (!$errorBag->hasAny()) {
        $settingsGateway->setAuthMode($authMode);

        if ($odataBaseUrl !== '') {
            $settingsGateway->setODataBaseUrl($odataBaseUrl);
        }
        if ($companyName !== '') {
            $settingsGateway->setCompanyName($companyName);
        }

        $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);
        }
        if ($oauthTokenEndpoint !== '') {
            $settingsGateway->setOAuthTokenEndpoint($oauthTokenEndpoint);
        }

        $settingsGateway->setSystemRecommendationsConfig([
            'version' => 1,
            'max_items' => $recommendationsMaxItems,
            'rules' => [
                'escalation_overdue' => [
                    'enabled' => isset($post['recommendations_escalation_overdue_enabled']),
                    'priority' => 100,
                    'min_overdue_minutes' => (int) ($post['recommendations_escalation_overdue_min_overdue_minutes'] ?? 0),
                ],
                'high_risk_aging' => [
                    'enabled' => isset($post['recommendations_high_risk_aging_enabled']),
                    'priority' => 90,
                    'codes' => trim((string) ($post['recommendations_high_risk_aging_codes'] ?? 'MAX,HOCH')),
                    'min_age_hours' => (int) ($post['recommendations_high_risk_aging_min_age_hours'] ?? 8),
                ],
                'unassigned_open' => [
                    'enabled' => isset($post['recommendations_unassigned_open_enabled']),
                    'priority' => 80,
                    'min_age_hours' => (int) ($post['recommendations_unassigned_open_min_age_hours'] ?? 2),
                ],
                'stale_open' => [
                    'enabled' => isset($post['recommendations_stale_open_enabled']),
                    'priority' => 70,
                    'min_age_hours' => (int) ($post['recommendations_stale_open_min_age_hours'] ?? 48),
                ],
                'customer_backlog' => [
                    'enabled' => isset($post['recommendations_customer_backlog_enabled']),
                    'priority' => 60,
                    'min_open_tickets' => (int) ($post['recommendations_customer_backlog_min_open_tickets'] ?? 6),
                ],
            ],
        ]);

        $settingsGateway->setControllingRiskConfig([
            'version' => 1,
            'rules' => [
                'ticket_volume_increase' => [
                    'enabled' => isset($post['controlling_ticket_volume_increase_enabled']),
                    'threshold_percent' => (int) ($post['controlling_ticket_volume_increase_threshold'] ?? 30),
                ],
                'avg_resolution_high' => [
                    'enabled' => isset($post['controlling_avg_resolution_high_enabled']),
                    'threshold_hours' => (int) ($post['controlling_avg_resolution_high_threshold'] ?? 72),
                ],
                'open_aging' => [
                    'enabled' => isset($post['controlling_open_aging_enabled']),
                    'threshold_hours' => (int) ($post['controlling_open_aging_threshold'] ?? 168),
                ],
                'unassigned_ratio' => [
                    'enabled' => isset($post['controlling_unassigned_ratio_enabled']),
                    'threshold_percent' => (int) ($post['controlling_unassigned_ratio_threshold'] ?? 20),
                ],
            ],
        ]);

        $tokenRepository->deleteAll();

        $action = trim((string) ($post['action'] ?? 'save'));
        Flash::success(t('Settings saved'), 'helpdesk/settings', 'settings_saved');

        if ($action === 'save_close') {
            Router::redirect('helpdesk');

            return;
        }
    } else {
        flashFormErrors($errorBag, 'helpdesk/settings', 'settings_error');
    }

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

    return;
}

// Load current global values for display
$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();
$recommendationsConfigEnvelope = $settingsGateway->getSystemRecommendationsConfigEnvelope();
$recommendationsConfig = is_array($recommendationsConfigEnvelope['config'] ?? null)
    ? $recommendationsConfigEnvelope['config']
    : [];
$recommendationsConfigSource = (string) ($recommendationsConfigEnvelope['source'] ?? 'default');

$controllingConfigEnvelope = $settingsGateway->getControllingRiskConfigEnvelope();
$controllingConfig = is_array($controllingConfigEnvelope['config'] ?? null)
    ? $controllingConfigEnvelope['config']
    : [];
$controllingConfigSource = (string) ($controllingConfigEnvelope['source'] ?? 'default');

// Load tenant override values
$tenantOverrideEnabled = false;
$tenantRow = null;
$tenantHasBasicPassword = false;
$tenantHasOAuthSecret = false;
if ($currentTenantId > 0) {
    $tenantOverrideEnabled = $tenantSettingsGateway->isOverrideEnabled($currentTenantId);
    $tenantRow = $tenantSettingsGateway->findByTenantId($currentTenantId);
    $tenantHasBasicPassword = $tenantSettingsGateway->getBasicPassword($currentTenantId) !== null;
    $tenantHasOAuthSecret = $tenantSettingsGateway->getOAuthClientSecret($currentTenantId) !== null;
}

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