<?php

use MintyPHP\Router;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Mail\MailServicesFactory;
use MintyPHP\Service\User\UserAccessTemplateService;
use MintyPHP\Service\User\UserServicesFactory;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

Guard::requireLogin();
$userAccountService = (new UserServicesFactory())->createUserAccountService();

$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
$canUpdateUser = permissionGateway()->userHas($currentUserId, PermissionService::USERS_UPDATE);
$canUpdateSelf = permissionGateway()->userHas($currentUserId, PermissionService::USERS_SELF_UPDATE);
$mailService = (new MailServicesFactory())->createMailService();

$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);
$isOwnAccount = $currentUserId > 0 && $currentUserId === $userId;
$canEditUser = $isOwnAccount ? ($canUpdateUser || $canUpdateSelf) : $canUpdateUser;

if (!$canEditUser) {
    Router::redirect('error/forbidden');
    return;
}
if (!$isOwnAccount && !directoryServicesFactory()->createDirectoryScopeGateway()->canAccess('users', $userId, $currentUserId)) {
    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}");
