<?php

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

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

$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
$uuid = trim((string) ($id ?? ''));
if ($uuid === '') {
    Router::redirect('address-book');
}

$addressBookService = (new AddressBookServicesFactory())->createAddressBookService();
$viewContext = $addressBookService->buildViewContext($currentUserId, $uuid);
$status = (string) ($viewContext['status'] ?? '');
if ($status === 'not_found') {
    Flash::error('User not found', 'address-book', 'user_not_found');
    Router::redirect('address-book');
}
if ($status === 'forbidden') {
    Router::redirect('error/forbidden');
}
$user = $viewContext['user'] ?? null;
if (!is_array($user)) {
    Router::redirect('address-book');
}

Buffer::set('style_groups', json_encode(['address-book']));

$name = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
$title = $name !== '' ? $name : ($user['email'] ?? t('Address book'));
Buffer::set('title', $title);
