<?php

use MintyPHP\Buffer;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\AddressBook\AddressBookServicesFactory;
use MintyPHP\Session;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requirePermissionOrForbidden(PermissionService::ADDRESS_BOOK_VIEW);

$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
$addressBookService = (new AddressBookServicesFactory())->createAddressBookService();
$context = $addressBookService->buildIndexContext($currentUserId, $_GET);
$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'] ?? [];

$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)
);
