<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\UserAuthorizationPolicy;
use MintyPHP\Service\User\UserAccessTemplateService;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$userAccountService = app(\MintyPHP\Service\User\UserAccountService::class);
$mailService = app(\MintyPHP\Service\Mail\MailService::class);
$userAccessTemplateService = app(UserAccessTemplateService::class);

$uuid = trim((string) ($id ?? ''));
$user = $uuid !== '' ? $userAccountService->findByUuid($uuid) : null;
if (!$user) {
    Flash::error(t('User not found'), 'admin/users', 'user_not_found');
    Router::redirect('admin/users');
}

$userId = (int) ($user['id'] ?? 0);
$currentUserId = (int) ($session['user']['id'] ?? 0);
$decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_SEND_ACCESS, [
    'actor_user_id' => $currentUserId,
    'target_user_id' => $userId,
]);
if (!$decision->isAllowed()) {
    Router::redirect('error/forbidden');
    return;
}

$context = $userAccessTemplateService->buildContext($user);
$locale = (string) ($context['locale'] ?? '');
$subject = (string) ($context['subject'] ?? t('Your access details'));
$vars = is_array($context['vars'] ?? null) ? $context['vars'] : [];

$result = $mailService->sendTemplate('access_info', $vars, (string) $user['email'], $subject, $locale);
if (!($result['ok'] ?? false)) {
    Flash::error(t('Access email failed'), "admin/users/edit/{$uuid}", 'access_email_failed');
    Router::redirect("admin/users/edit/{$uuid}");
}

Flash::success(t('Access email sent'), "admin/users/edit/{$uuid}", 'access_email_sent');
Router::redirect("admin/users/edit/{$uuid}");
