<?php

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

Guard::requireLogin();
Guard::requirePermission(PermissionService::USERS_LIFECYCLE_RESTORE);

$auditId = (int) ($id ?? 0);

if (strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'POST') {
    Router::redirect('admin/user-lifecycle-audit');
}
if (!Session::checkCsrfToken()) {
    Flash::error(t('Form expired, please try again'), 'admin/user-lifecycle-audit', 'user_lifecycle_restore_csrf');
    Router::redirect('admin/user-lifecycle-audit');
}

$result = (new UserServicesFactory())->createUserLifecycleRestoreService()->restoreFromLifecycleAudit(
    $auditId,
    (int) ($_SESSION['user']['id'] ?? 0)
);

if (!($result['ok'] ?? false)) {
    $error = (string) ($result['error'] ?? 'restore_unexpected_error');
    if ($error === 'restore_email_exists') {
        Flash::error(t('Restore not possible: email already exists'), "admin/user-lifecycle-audit/view/$auditId", 'restore_email_exists');
    } elseif ($error === 'restore_uuid_exists') {
        Flash::error(t('Restore not possible: uuid already exists'), "admin/user-lifecycle-audit/view/$auditId", 'restore_uuid_exists');
    } elseif ($error === 'snapshot_unavailable') {
        Flash::error(t('Lifecycle snapshot unavailable'), "admin/user-lifecycle-audit/view/$auditId", 'lifecycle_snapshot_unavailable');
    } elseif ($error === 'audit_event_already_restored') {
        Flash::error(t('Lifecycle event was already restored'), "admin/user-lifecycle-audit/view/$auditId", 'lifecycle_already_restored');
    } else {
        Flash::error(t('User restore failed'), "admin/user-lifecycle-audit/view/$auditId", 'user_restore_failed');
    }
    Router::redirect("admin/user-lifecycle-audit/view/$auditId");
}

Flash::success(t('User restored'), "admin/user-lifecycle-audit/view/$auditId", 'user_restored');
Router::redirect("admin/user-lifecycle-audit/view/$auditId");
