<?php

use MintyPHP\Router;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Auth\AuthServicesFactory;
use MintyPHP\Service\User\UserServicesFactory;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

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

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

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

$rememberMeService->forgetAllForUser($userId);
Flash::success(t('Login tokens cleared'), "admin/users/edit/{$uuid}", 'tokens_cleared');
Router::redirect("admin/users/edit/{$uuid}");
