<?php

declare(strict_types=1);

namespace External\PompoBundle\View;

use KupShop\KupShopBundle\Exception\RedirectException;
use Symfony\Component\HttpFoundation\RequestStack;

class PageView extends \KupShop\ContentBundle\View\PageView
{
    /** @required */
    public RequestStack $requestStack;

    public function getBodyVariables()
    {
        $vars = parent::getBodyVariables();

        $passwordRequired = false;
        if (!empty($this->getPage()->getData()['password'])) {
            if ($request = $this->requestStack->getCurrentRequest()) {
                if ($request->isMethod('POST')) {
                    $this->authenticatePage(
                        $request->get('password')
                    );
                }

                if (!($hash = $request->get('hash'))) {
                    $hash = $request->getSession()->get(
                        $this->getPageHashSessionKey()
                    );
                }

                if (!$hash || (md5($this->getPage()->getData()['password']) !== $hash)) {
                    $passwordRequired = true;
                }
            }
        }

        $vars['passwordRequired'] = $passwordRequired;

        return $vars;
    }

    private function authenticatePage(?string $password): void
    {
        if (mb_strtolower($this->getPage()->getData()['password']) === mb_strtolower($password)) {
            $this->requestStack->getSession()->set(
                $this->getPageHashSessionKey(),
                md5($this->getPage()->getData()['password'])
            );

            throw new RedirectException('/'.$this->getPage()->getUrl());
        }
    }

    private function getPageHashSessionKey(): string
    {
        return 'pageHash_'.$this->getPage()->getId();
    }
}
