<?php

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

$rawLocale = (string) ($_REQUEST['locale'] ?? ($_GET['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) {
    (new UserServicesFactory())->createUserAccountService()->setLocale($userId, $locale);
    $_SESSION['user']['locale'] = $locale;
  }
} else {
  setcookie('locale', $locale, time() + 31536000, '/', '', false, true);
}

$target = Request::safeReturnTarget($_GET['return'] ?? '');
$target = Request::stripLocale($target);
$target = Request::withLocale($target, $locale);
Router::redirect($target);
