<?php

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

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

$request = requestInput();
if ($request->isMethod('POST') && !Session::checkCsrfToken()) {
    Flash::error(t('Form expired, please try again'), '', 'csrf_expired');
    Router::redirect('');
    return;
}

$rawLocale = (string) $request->body(
    'locale',
    $request->query('locale', $request->query('lang', ''))
);
$locale = strtolower(trim($rawLocale));
if ($locale !== '' && strpos($locale, '-') !== false) {
    $locale = explode('-', $locale, 2)[0];
}
$locales = defined('APP_LOCALES') ? APP_LOCALES : [I18n::$defaultLocale];

if ($locale === '' || !in_array($locale, $locales, true)) {
    Flash::error('Language not supported', null, 'lang_not_supported');
    Router::redirect('');
}

I18n::$locale = $locale;
if (isset($session['user']['id'])) {
    $userId = (int) ($session['user']['id'] ?? 0);
    if ($userId) {
        (app(UserServicesFactory::class))->createUserAccountService()->setLocale($userId, $locale);
        $userSession = $sessionStore->get('user', []);
        if (is_array($userSession)) {
            $userSession['locale'] = $locale;
            $sessionStore->set('user', $userSession);
        }
    }
} else {
    setcookie('locale', $locale, time() + 31536000, '/', '', false, true);
}

$target = Request::safeReturnTarget($request->query('return', ''));
$target = Request::stripLocale($target);
$target = Request::withLocale($target, $locale);
Router::redirect($target);
