<?php

use MintyPHP\Http\Request;
use MintyPHP\Router;
use MintyPHP\Service\User\UserServicesFactory;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

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

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== '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;
    }
    Flash::error(t('Theme change is disabled for this tenant'), 'admin', 'theme_disabled');
    Router::redirect('admin');
    return;
}

$theme = strtolower(trim((string) ($_POST['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;
}

$_SESSION['user']['theme'] = $theme;

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

Router::redirect('admin');
