<?php

use MintyPHP\Buffer;
use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Module\Helpdesk\Service\BcODataGateway;
use MintyPHP\Router;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

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

$request = requestInput();
$ticketNo = trim((string) ($id ?? ''));
$fromCustomerNo = trim((string) $request->query('from', ''));

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

    return;
}

$gateway = app(BcODataGateway::class);

try {
    $ticket = $gateway->getTicket($ticketNo);
} catch (\Throwable) {
    $ticket = null;
    $connectionError = true;
}

$connectionError = $connectionError ?? false;

if ($ticket === null && !$connectionError) {
    Flash::error(t('Ticket not found'), 'helpdesk', 'ticket_not_found');
    Router::redirect('helpdesk');

    return;
}

$ticketCustomerNo = $fromCustomerNo;
$ticketDescription = (string) ($ticket['Description'] ?? $ticketNo);
$ticketCommunicationUrl = lurl('helpdesk/ticket-communication-data');

Buffer::set('title', $ticketDescription . ' — ' . t('Helpdesk'));
Buffer::set('style_groups', json_encode(['helpdesk']));
$breadcrumbs = [
    ['label' => t('Home'), 'path' => 'admin'],
    ['label' => t('Helpdesk'), 'path' => 'helpdesk'],
];
if ($ticketCustomerNo !== '') {
    $breadcrumbs[] = ['label' => (string) ($ticket['Company_Contact_Name'] ?? $ticketCustomerNo), 'path' => 'helpdesk/debitor/' . rawurlencode($ticketCustomerNo)];
}
$breadcrumbs[] = ['label' => t('Ticket') . ' ' . $ticketNo];
