<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Module\Helpdesk\Service\DomainDetailService;
use MintyPHP\Module\Helpdesk\Service\DomainSecurityLevelService;
use MintyPHP\Router;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

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

$domainNo = trim((string) ($id ?? ''));

if ($domainNo === '') {
    Router::redirect('helpdesk/domains');

    return;
}

$domainDetailService = app(DomainDetailService::class);
$result = $domainDetailService->loadDomain($domainNo);

$resultStatus = (string) ($result['status'] ?? '');

if ($resultStatus === 'not_found') {
    Flash::error(t('Domain not found'), 'helpdesk-domains', 'domain_not_found');
    Router::redirect('helpdesk/domains');

    return;
}

if ($resultStatus === 'not_configured') {
    Flash::error(t('BC connection is not configured'), 'helpdesk-domains', 'not_configured');
    Router::redirect('helpdesk/domains');

    return;
}

$domain = $result['domain'] ?? [];
$hasError = $resultStatus === 'error';
$errorMessage = $result['error'] ?? '';

$domainUrl = (string) ($domain['URL'] ?? '');
$customerNo = (string) ($domain['Customer_No'] ?? '');
$customerName = (string) ($domain['Customer_Name'] ?? '');
$domainState = (string) ($domain['State'] ?? '');
$domainAdministration = (string) ($domain['Administration'] ?? '');

$session = app(SessionStoreInterface::class)->all();
$tenantId = (int) ($session['current_tenant']['id'] ?? 0);
$securityLevelService = app(DomainSecurityLevelService::class);
$securityDetails = $tenantId > 0 ? $securityLevelService->getDetails($tenantId, $domainNo) : ['level' => 'normal', 'note' => ''];
$securityLevel = $securityDetails['level'];
$securityLevelNote = $securityDetails['note'];
$securityLevelVariant = DomainSecurityLevelService::getBadgeVariant($securityLevel);

$pageTitle = $domainUrl !== '' ? $domainUrl : $domainNo;

Buffer::set('title', $pageTitle . ' — ' . t('Helpdesk'));
Buffer::set('style_groups', json_encode(['helpdesk']));
$breadcrumbs = [
    ['label' => t('Home'), 'path' => 'admin'],
    ['label' => t('Helpdesk'), 'path' => 'helpdesk'],
    ['label' => t('Domains'), 'path' => 'helpdesk/domains'],
    ['label' => $pageTitle],
];
