<?php

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

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();

$currentUserId = (int) ($session['user']['id'] ?? 0);
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$decision = $authorizationService->authorize(SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_BRANDING_UPDATE, [
    'actor_user_id' => $currentUserId,
]);
if (!$decision->isAllowed()) {
    Guard::deny();
}

if ((requestInput()->method()) !== 'POST') {
    Router::redirect('admin/settings');
    return;
}

$errorBag = formErrors();
$faviconService = app(\MintyPHP\Service\Branding\BrandingFaviconService::class);
$result = $faviconService->saveUpload(requestInput()->filesAll()['favicon'] ?? []);
if (!($result['ok'] ?? false)) {
    $error = $result['error'] ?? t('Upload failed');
    $errorBag->addGlobal((string) $error);
    flashFormErrors($errorBag, 'admin/settings', 'favicon_upload');
    Router::redirect('admin/settings');
    return;
}

Flash::success('Favicon updated', 'admin/settings', 'favicon_updated');
Router::redirect('admin/settings');
