<?php

namespace App\Controller;

use App\Controller\Helper\AjaxResponseBuilder;
use App\Form\NewsletterFormType;
use App\Tool\Utils;
use Pimcore\Controller\FrontendController;
use Pimcore\Model\Document;
use Pimcore\Model\Site;
use Pimcore\Controller\KernelControllerEventInterface;
use Pimcore\Bundle\ApplicationLoggerBundle\ApplicationLogger;
use Pimcore\Cache\RuntimeCache;
use Pimcore\Translation\Translator;
use Pimcore\Twig\Extension\Templating\HeadLink;
use Pimcore\Twig\Extension\Templating\HeadMeta;
use Pimcore\Twig\Extension\Templating\HeadScript;
use Pimcore\Twig\Extension\Templating\HeadTitle;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Twig\Environment;

class BaseController extends FrontendController implements KernelControllerEventInterface
{
	use Helper\ControllerTrait;

	/**
	 * @var FormInterface
	 */
	protected $newsletterForm;


	/**
	 * @param FilterControllerEvent $event
	 */
	public function __construct(
		Environment $twig,
		Translator $translator,
		AjaxResponseBuilder $ajaxResponseBuilder,
		HeadScript $headScript,
		HeadLink $headLink,
		HeadMeta $headMeta,
		HeadTitle $headTitle,
		ApplicationLogger $applicationLogger,
	) {
		$this->twig = $twig;
		$this->translator = $translator;

		//inject view helpers
		$this->headScript = $headScript;
		$this->headLink = $headLink;
		$this->headMeta = $headMeta;
		$this->headTitle = $headTitle;

		$this->ajaxResponseBuilder = $ajaxResponseBuilder;

		$this->applicationLogger = $applicationLogger;
	}

	 /**
     * @param ControllerEvent $event
     */
    public function onKernelControllerEvent(ControllerEvent $event): void
	{
		$this->twig->addGlobal('document', $this->document);

		//avoid cache misses in some cases
		\Pimcore\Cache::setForceImmediateWrite(true);

		//set request
		$this->request = $event->getRequest();

		//detect language
		$this->defaultLanguage = Utils::getDefaultLanguage();
		$this->language = substr($event->getRequest()->getLocale(), 0, 2);
		if (!$this->language) {
			$this->language = Utils::getDefaultLanguage();
		}
		$this->twig->addGlobal('language', $this->language);

		//detect current url
		$this->currentUrl = strtok($event->getRequest()->getRequestUri(), '?');
		$this->twig->addGlobal('currentUrl', $this->currentUrl);

		//generate unique cache keys for various cachable content chunks based on current URL
		$cacheKeySuffix = $this->language.'_'.$this->currentUrl;
		if (Site::isSiteRequest()) {
			$cacheKeySuffix = Site::getCurrentSite()->getId() . '_'.$cacheKeySuffix;
		}
		$this->cacheKeySuffix = Utils::toCacheKey($cacheKeySuffix);
		$this->twig->addGlobal('cacheKey', $this->cacheKeySuffix);
		$this->twig->addGlobal('breadcrumbsCacheKey', '_breadcrumbs_'.$this->cacheKeySuffix);
		$this->twig->addGlobal('metaCacheKey', '_meta_'.$this->cacheKeySuffix);
		$this->twig->addGlobal('languageSwitchCacheKey', '_language_switch_'.$this->cacheKeySuffix);
		$this->twig->addGlobal('mainNavCacheKey', '_main_nav_'.$this->cacheKeySuffix);

		//assign breadcrumbs extension to template variable by reference (for legacy reasons)
		$addToBreadcrumbs = new \stdClass();
		$addToBreadcrumbs->pages = &$this->addToBreadcrumbs;
		$this->twig->addGlobal('addToBreadcrumbs', $addToBreadcrumbs);

		//assign language switch extension to template variable by reference (for legacy reasons)
		$languageSwitch = new \stdClass();
		$languageSwitch->pages = &$this->languageSwitch;
		$this->twig->addGlobal('languageSwitch', $languageSwitch);

		// Other variables.
		$this->twig->addGlobal('isFrontendRequestByAdmin', \Pimcore\Tool::isFrontendRequestByAdmin());


		//global forms
		if ($this->document instanceof Document\Page) {
			$this->newsletterForm = $this->createForm(NewsletterFormType::class);
			$this->twig->addGlobal('newsletterForm', $this->newsletterForm->createView());
		}

		// Flash messages.
		if($this->request->hasSession() && $this->request->getSession()) {
			$session = $this->request->getSession();
			$sessionFlashMessages = $session instanceof Session ? $session->getFlashBag()->all() : [];
			$currentRequestFlashMessages = RuntimeCache::isRegistered('currentRequestFlashMessages') ? RuntimeCache::get('currentRequestFlashMessages') : [];
			$this->twig->addGlobal('flashMessages', array_merge($sessionFlashMessages, $currentRequestFlashMessages));
		}

		$rootDoc = Utils::getTranslatedDocumentByPath('/'.Utils::getDefaultLanguage(), $this->language)
				?: Utils::getTranslatedDocumentByPath('/', $this->language);
		$this->twig->addGlobal('rootDocument', $rootDoc);
	}
}
