<?php

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

Guard::requireLogin();
$userServicesFactory = new UserServicesFactory();
$userAccountService = $userServicesFactory->createUserAccountService();
$userAvatarService = $userServicesFactory->createUserAvatarService();

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

$uuid = trim((string) ($id ?? ''));
if (!$userAvatarService->isValidUuid($uuid)) {
    Flash::error('User not found', 'admin', 'user_not_found');
    Router::redirect('admin');
    return;
}

$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)) {
    Router::redirect('error/forbidden');
    return;
}

$result = $userAvatarService->saveUpload($uuid, $_FILES['avatar'] ?? []);
if (!($result['ok'] ?? false)) {
    $error = $result['error'] ?? t('Upload failed');
    Flash::error($error, "admin/users/edit/{$uuid}", 'avatar_upload_failed');
    Router::redirect("admin/users/edit/{$uuid}");
    return;
}

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