<?php

use MintyPHP\Http\Request;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Guard;

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

Guard::requireLogin();
$userAccountService = app(\MintyPHP\Service\User\UserAccountService::class);
$errorBag = formErrors();

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

if (!Session::checkCsrfToken()) {
    if (Request::wantsJson()) {
        http_response_code(400);
        Router::json(['ok' => false, 'error' => 'csrf']);
        return;
    }
    Router::redirect('admin');
    return;
}

$userId = (int) ($session['user']['id'] ?? 0);
if ($userId <= 0) {
    http_response_code(401);
    if (Request::wantsJson()) {
        Router::json(['ok' => false, 'error' => 'unauthorized']);
        return;
    }
    Router::redirect('login');
    return;
}

if (!allowUserTheme()) {
    http_response_code(403);
    if (Request::wantsJson()) {
        Router::json(['ok' => false, 'error' => 'theme_disabled']);
        return;
    }
    $errorBag->addGlobal(t('Theme change is disabled for this tenant'));
    flashFormErrors($errorBag, 'admin', 'theme_change');
    Router::redirect('admin');
    return;
}

$theme = strtolower(trim((string) (requestInput()->bodyAll()['theme'] ?? '')));
$themes = appThemes();
if ($theme === '' || !isset($themes[$theme])) {
    http_response_code(400);
    if (Request::wantsJson()) {
        Router::json(['ok' => false, 'error' => 'invalid_theme']);
        return;
    }
    Router::redirect('admin');
    return;
}

$updated = $userAccountService->setTheme($userId, $theme);
if (!$updated) {
    http_response_code(500);
    if (Request::wantsJson()) {
        Router::json(['ok' => false, 'error' => 'update_failed']);
        return;
    }
    Router::redirect('admin');
    return;
}

$userSession = $sessionStore->get('user', []);
if (is_array($userSession)) {
    $userSession['theme'] = $theme;
    $sessionStore->set('user', $userSession);
}

if (Request::wantsJson()) {
    Router::json(['ok' => true, 'theme' => $theme]);
    return;
}

Router::redirect('admin');
