<?php

use MintyPHP\Http\Request;
use MintyPHP\Router;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\User\UserServicesFactory;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

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

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
    Router::redirect('admin/users');
    return;
}

$uuid = trim((string) ($id ?? ''));
$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
$user = $uuid !== '' ? $userAccountService->findByUuid($uuid) : null;
$userId = (int) ($user['id'] ?? 0);
if ($userId > 0 && $currentUserId !== $userId && !directoryServicesFactory()->createDirectoryScopeGateway()->canAccess('users', $userId, $currentUserId)) {
    if (Request::wantsJson()) {
        http_response_code(403);
        Router::json(['error' => 'permission_denied']);
        return;
    }
    Router::redirect('error/forbidden');
    return;
}
$result = $userAccountService->deleteByUuid($uuid, $currentUserId);

if (!($result['ok'] ?? false)) {
    if (($result['error'] ?? '') === 'self_delete') {
        Flash::error('You cannot delete your own account', 'admin/users', 'user_self_delete');
        if (Request::wantsJson()) {
            http_response_code(400);
            Router::json(['error' => 'self_delete']);
            return;
        }
    } else {
        Flash::error('User not found', 'admin/users', 'user_not_found');
        if (Request::wantsJson()) {
            http_response_code(404);
            Router::json(['error' => 'not_found']);
            return;
        }
    }
    Router::redirect('admin/users');
    return;
}

if (Request::wantsJson()) {
    http_response_code(204);
    Router::json([]);
    return;
}

Flash::success('User deleted', 'admin/users', 'user_deleted');
Router::redirect('admin/users');
