<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Service\AddressBook\AddressBookServicesFactory;
use MintyPHP\Session;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbilityOrForbidden(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADDRESS_BOOK_VIEW);

$filterSchema = require __DIR__ . '/filter-schema.php';
$query = requestInput()->queryAll();
$currentUserId = (int) ($session['user']['id'] ?? 0);
$addressBookService = (app(AddressBookServicesFactory::class))->createAddressBookService();
$context = $addressBookService->buildIndexContext($currentUserId, $query);
$activeTenants = $context['activeTenants'] ?? [];
$activeRoles = $context['activeRoles'] ?? [];
$activeDepartments = $context['activeDepartments'] ?? [];
$tenantItems = $context['tenantItems'] ?? [];
$departments = $context['departments'] ?? [];
$roles = $context['roles'] ?? [];
$customFieldFilterDefinitions = $context['customFieldFilterDefinitions'] ?? [];
$customFieldFilterQuery = $context['customFieldFilterQuery'] ?? [];
$tenantDepartmentMap = $context['tenantDepartmentMap'] ?? [];
$toolbarOptionSets = [
    'tenant_items' => (array) $tenantItems,
    'department_items' => (array) $departments,
    'role_items' => (array) $roles,
];
$toolbarFilterStateOverrides = [
    'search' => (string) gridQueryString($query, 'search', ''),
    'tenants' => array_map('strval', (array) $activeTenants),
    'departments' => array_map('strval', (array) $activeDepartments),
    'roles' => array_map('strval', (array) $activeRoles),
];
$listFilterContext = gridBuildListFilterContext($filterSchema, [
    'query' => $query,
    'search_keys' => ['search'],
    'toolbar_state_overrides' => $toolbarFilterStateOverrides,
    'toolbar_option_sets' => $toolbarOptionSets,
]);
$toolbarFilterSchema = $listFilterContext['toolbarFilterSchema'];
$toolbarFilterState = $listFilterContext['toolbarFilterState'];
$searchToolbarFilterSchema = $listFilterContext['searchToolbarFilterSchema'];
$drawerToolbarFilterSchema = $listFilterContext['drawerToolbarFilterSchema'];
$toolbarOptionSets = $listFilterContext['toolbarOptionSets'];
$clientFilterSchema = $listFilterContext['clientFilterSchema'];
$searchConfig = $listFilterContext['searchConfig'];
$customFieldChipMeta = [];
foreach ($customFieldFilterDefinitions as $definition) {
    $definitionUuid = strtolower(trim((string) ($definition['uuid'] ?? '')));
    $definitionType = strtolower(trim((string) ($definition['type'] ?? '')));
    $definitionLabel = trim((string) ($definition['label'] ?? ''));
    $definitionOptions = is_array($definition['options'] ?? null) ? $definition['options'] : [];
    if ($definitionUuid === '' || $definitionType === '' || $definitionLabel === '') {
        continue;
    }

    if (in_array($definitionType, ['select', 'boolean'], true)) {
        $options = gridOptionMapFromItems($definitionOptions);
        if ($definitionType === 'boolean') {
            $options = ['1' => t('Yes'), '0' => t('No')];
        }
        $customFieldChipMeta[] = [
            'type' => 'scalar',
            'param' => 'cf_' . $definitionUuid,
            'label' => $definitionLabel,
            'options' => $options,
        ];
        continue;
    }

    if ($definitionType === 'multiselect') {
        $customFieldChipMeta[] = [
            'type' => 'multi_csv',
            'param' => 'cfm_' . $definitionUuid,
            'label' => $definitionLabel,
            'options' => gridOptionMapFromItems($definitionOptions),
        ];
        continue;
    }

    if ($definitionType === 'date') {
        $customFieldChipMeta[] = [
            'type' => 'date_range',
            'label' => $definitionLabel,
            'from_param' => 'cfd_' . $definitionUuid . '_from',
            'to_param' => 'cfd_' . $definitionUuid . '_to',
        ];
    }
}
$filterChipMeta = [
    'search' => [
        'label' => t('Search'),
        'type' => 'text',
    ],
    'tenants' => [
        'label' => t('Tenants'),
        'type' => 'multi_csv',
        'options' => gridOptionMapFromItems((array) $tenantItems),
    ],
    'departments' => [
        'label' => t('Departments'),
        'type' => 'multi_csv',
        'options' => gridOptionMapFromItems((array) $departments),
    ],
    'roles' => [
        'label' => t('Roles'),
        'type' => 'multi_csv',
        'options' => gridOptionMapFromItems((array) $roles),
    ],
    'custom_fields' => $customFieldChipMeta,
];

$csrfKey = Session::$csrfSessionKey;
$csrfToken = $session[$csrfKey] ?? '';

Buffer::set('title', t('Address book'));
Buffer::set('grid_lang', json_encode(gridLang(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
Buffer::set(
    'grid_csrf',
    json_encode(['key' => $csrfKey, 'token' => $csrfToken], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
);
