<?php

namespace Velis\Mvc\Controller\Listeners;

use Phalcon\Http\RequestInterface;
use Velis\App;
use Velis\Lang;
use Velis\Mvc\Controller\Exception\ForbiddenException;
use Velis\Mvc\Controller\Listeners\Concrete\AbstractListener;

class VerifyCsrfTokenListener extends AbstractListener
{
    private const CSRF_PROTECTED_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE'];

    /**
     * @throws ForbiddenException
     */
    public function handle(): void
    {
        /** @var RequestInterface $request */
        $request = $this->dispatcher->getDI()->get('request');

        if (in_array($request->getMethod(), self::CSRF_PROTECTED_METHODS)) {
            if ($request->getHeader('X-CSRF-TOKEN') != App::$session->csrfToken) {
                $message = Lang::get('GENERAL_ACCESS_DENIED');

                if ($_SERVER['ON_DEV']) {
                    $message .= ' - token mismatch';
                }

                throw new ForbiddenException($message);
            }
        }
    }
}
