<?php

namespace KupShop\I18nBundle\Controller;

use KupShop\I18nBundle\Util\Locale\LanguageAwareUrlGenerator;
use KupShop\KupShopBundle\Context\ContextManager;
use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Exception\RedirectException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;

class ChangeLanguageController extends AbstractController
{
    /**
     * @Route("/change-language/{lang}/")
     * @Route("/change-language/{lang}/{url}")
     */
    public function changeAction(LanguageAwareUrlGenerator $urlGenerator, LanguageContext $languageContext, ContextManager $contextManager, Request $request, $lang, $url = null)
    {
        if ($url) {
            $referer = $url;
        } else {
            $referer = $request->headers->get('referer', '/');
        }

        $referer = str_replace($request->getSchemeAndHttpHost(), '', $referer);
        // check if language is valid
        if (!isset($languageContext->getSupported()[$lang])) {
            throw new RedirectException($referer);
        }
        $languageContext->remember($lang);

        try {
            $url = $urlGenerator->generateInLanguage($lang, $referer);
        } catch (\Exception $e) {
            throw new NotFoundHttpException('Failure when generating URL', previous: $e);
        }

        if ($domain = $contextManager->getDomainFromLanguage($lang)) {
            $url = 'https://'.$domain.'/'.ltrim($url, '/');
        }

        $request->getSession()->set('changeLanguage', true);

        throw new RedirectException($url);
    }
}
