<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbilityOrForbidden(\MintyPHP\Module\AddressBook\AddressBookAuthorizationPolicy::ABILITY_VIEW);

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

$addressBookService = app(\MintyPHP\Module\AddressBook\Service\AddressBookService::class);
$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);
$breadcrumbs = [
    ['label' => t('Home'), 'path' => 'admin'],
    ['label' => t('Address book'), 'path' => 'address-book'],
    ['label' => $title],
];
