<?php

use MintyPHP\Buffer;
use MintyPHP\Http\Request;
use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Module\Helpdesk\Service\DebitorDetailService;
use MintyPHP\Router;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

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

$request = requestInput();
$customerNo = trim((string) ($id ?? ''));

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

    return;
}

$detailService = app(DebitorDetailService::class);
$detail = $detailService->loadCustomer($customerNo);

$detailStatus = (string) ($detail['status'] ?? '');

if ($detailStatus === 'not_found') {
    Flash::error(t('Debtor not found'), 'helpdesk', 'debtor_not_found');
    Router::redirect('helpdesk');

    return;
}

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

    return;
}

$customer = $detail['customer'] ?? [];
$hasError = $detailStatus === 'error';
$errorMessage = $detail['error'] ?? '';

$customerName = (string) ($customer['Name'] ?? $customerNo);

$returnTarget = Request::safeReturnTarget((string) $request->query('return', ''));
if ($returnTarget !== '') {
    $backUrl = lurl($returnTarget);
} else {
    $searchQuery = trim((string) $request->query('search', ''));

    $backUrl = $searchQuery !== ''
        ? lurl('helpdesk') . '?search=' . rawurlencode($searchQuery)
        : lurl('helpdesk');
}

// --- Tickets filter context ---
$ticketsFilterSchema = require __DIR__ . '/debitor-tickets-filter-schema.php';
$ticketsFilterState = gridParseFilters($request->queryAll(), gridSchemaQuery($ticketsFilterSchema));
$ticketsToolbarOptionSets = [
    'category_items' => [],
];
$ticketsListFilterContext = gridBuildListFilterContext($ticketsFilterSchema, [
    'filter_state' => $ticketsFilterState,
    'search_keys' => ['search'],
    'toolbar_option_sets' => $ticketsToolbarOptionSets,
]);
$searchToolbarFilterSchema = $ticketsListFilterContext['searchToolbarFilterSchema'];
$drawerToolbarFilterSchema = $ticketsListFilterContext['drawerToolbarFilterSchema'];
$toolbarFilterState = $ticketsListFilterContext['toolbarFilterState'];
$toolbarOptionSets = $ticketsListFilterContext['toolbarOptionSets'];
$schemaByKey = $ticketsListFilterContext['schemaByKey'];
$clientFilterSchema = $ticketsListFilterContext['clientFilterSchema'];
$searchConfig = $ticketsListFilterContext['searchConfig'];
$filterChipMeta = [
    'search' => [
        'label' => t('Search'),
        'type' => 'text',
    ],
    'status' => [
        'label' => t('Status'),
        'type' => 'select',
        'default' => (string) (($schemaByKey['status']['default'] ?? '')),
        'options' => gridOptionMapFromAllowed((array) ($schemaByKey['status'] ?? [])),
    ],
    'category' => [
        'label' => t('Category'),
        'type' => 'select',
        'default' => (string) (($schemaByKey['category']['default'] ?? '')),
        'options' => gridOptionMapFromItems((array) ($toolbarOptionSets['category_items'] ?? [])),
    ],
];

// --- Contacts filter context ---
$contactsFilterSchema = require __DIR__ . '/debitor-contacts-filter-schema.php';
$contactsFilterState = gridParseFilters($request->queryAll(), gridSchemaQuery($contactsFilterSchema));
$contactsToolbarOptionSets = [
    'type_items' => [],
];
$contactsListFilterContext = gridBuildListFilterContext($contactsFilterSchema, [
    'filter_state' => $contactsFilterState,
    'search_keys' => ['search'],
    'toolbar_option_sets' => $contactsToolbarOptionSets,
]);
$contactsSearchToolbarFilterSchema = $contactsListFilterContext['searchToolbarFilterSchema'];
$contactsDrawerToolbarFilterSchema = $contactsListFilterContext['drawerToolbarFilterSchema'];
$contactsToolbarFilterState = $contactsListFilterContext['toolbarFilterState'];
$contactsToolbarOptionSets = $contactsListFilterContext['toolbarOptionSets'];
$contactsSchemaByKey = $contactsListFilterContext['schemaByKey'];
$contactsClientFilterSchema = $contactsListFilterContext['clientFilterSchema'];
$contactsSearchConfig = $contactsListFilterContext['searchConfig'];
$contactsFilterChipMeta = [
    'search' => [
        'label' => t('Search'),
        'type' => 'text',
    ],
    'type' => [
        'label' => t('Type'),
        'type' => 'select',
        'default' => (string) (($contactsSchemaByKey['type']['default'] ?? '')),
        'options' => gridOptionMapFromItems((array) ($contactsToolbarOptionSets['type_items'] ?? [])),
    ],
];

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