<?php

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

Guard::requireLogin();
$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->setActiveByUuid($uuid, false, $currentUserId);
if (!($result['ok'] ?? false)) {
    if (($result['error'] ?? '') === 'self_deactivate') {
        Flash::error('You cannot deactivate your own account', 'admin/users', 'user_self_deactivate');
        if (Request::wantsJson()) {
            http_response_code(400);
            Router::json(['error' => 'self_deactivate']);
            return;
        }
    } elseif (Request::wantsJson()) {
        http_response_code((int) ($result['status'] ?? 404));
        Router::json(['error' => 'not_found']);
        return;
    }
    Router::redirect('admin/users');
    return;
}

if (Request::wantsJson()) {
    http_response_code(204);
    return;
}

Router::redirect('admin/users');
