<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\UserAuthorizationPolicy;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$userAccountService = app(\MintyPHP\Service\User\UserAccountService::class);
$userAvatarService = app(\MintyPHP\Service\User\UserAvatarService::class);

if (!actionRequirePost('admin')) {
    return;
}

if (!actionRequireCsrf('admin', 'admin', 'user_avatar_upload')) {
    return;
}

$errorBag = formErrors();
$uuid = trim((string) ($id ?? ''));
if (!$userAvatarService->isValidUuid($uuid)) {
    $errorBag->addGlobal('User not found');
    flashFormErrors($errorBag, 'admin', 'user_avatar_upload');
    Router::redirect('admin');
    return;
}

$currentUserId = (int) ($session['user']['id'] ?? 0);
$user = $uuid !== '' ? $userAccountService->findByUuid($uuid) : null;
$userId = (int) ($user['id'] ?? 0);
$decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_AVATAR_UPLOAD, [
    'actor_user_id' => $currentUserId,
    'target_user_id' => $userId,
]);
if (!$decision->isAllowed()) {
    Router::redirect('error/forbidden');
    return;
}

$result = $userAvatarService->saveUpload($uuid, requestInput()->filesAll()['avatar'] ?? []);
if (!($result['ok'] ?? false)) {
    $error = $result['error'] ?? t('Upload failed');
    $errorBag->addGlobal((string) $error);
    flashFormErrors($errorBag, "admin/users/edit/{$uuid}", 'user_avatar_upload');
    Router::redirect("admin/users/edit/{$uuid}");
    return;
}

Flash::success('Avatar updated', "admin/users/edit/{$uuid}", 'avatar_updated');
Router::redirect("admin/users/edit/{$uuid}");
