<?php

namespace AutoAdmin\Bundle\Admin\Controller\Admin;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Routing\RouterInterface;

class LocaleSwitcherController extends AbstractAdminController
{
    #[Route('/switch-locale/{newLocale}', name: 'aa_admin_locale_switcher_switch')]
    public function changeLocale(string $newLocale, Request $request, RouterInterface $router): RedirectResponse
    {
        $params = $this->getRefererParams($request, $router);
        $params = array_merge_recursive($params, $request->query->all());

        $route = $params['_route'];
        $params['_admin_locale'] = $newLocale;

        unset($params['_route']);

        return $this->redirect($this->generateUrl($route, $params));
    }

    public function getRefererParams(Request $request, RouterInterface $router): array
    {
        $referer = $request->headers->get('referer');
        $lastPath = substr($referer, strlen($request->getSchemeAndHttpHost()));

        return $router->getMatcher()->match(strtok($lastPath, '?'));
    }
}
