<?php

namespace KupShop\RewriteBundle\EventListener;

use KupShop\KupShopBundle\Event\NotFoundEvent;
use KupShop\KupShopBundle\Util\StringUtil;
use KupShop\RewriteBundle\Util\Rewrite;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;

class NotFoundListener implements EventSubscriberInterface
{
    protected $rewrite;

    public function __construct(Rewrite $rewrite)
    {
        $this->rewrite = $rewrite;
    }

    public static function getSubscribedEvents()
    {
        return [
            NotFoundEvent::class => ['rewrite', 200],
        ];
    }

    public function rewrite(NotFoundEvent $event)
    {
        // Try redirecting with query
        $resolvedUrl = $this->rewrite->resolve($event->getRequest()->getRequestUri(), $type);

        // Try redirecting without query
        if (!$resolvedUrl) {
            $resolvedUrl = $this->rewrite->resolve($event->getRequest()->getPathInfo(), $type);

            if ($resolvedUrl) {
                // Add query params - UTM etc
                $query = parse_url($event->getRequest()->getRequestUri(), PHP_URL_QUERY);
                if ($query) {
                    $resolvedUrl .= '?'.$query;
                }
            }
        }

        if ($resolvedUrl) {
            // RAW type returns "url" as content - usable for various site-validation files
            if ($type == Rewrite::TYPE_RAW) {
                $event->setResponse(new Response($resolvedUrl, 200));

                return;
            }

            if (!StringUtil::isAbsoluteUrl($resolvedUrl)) {
                $resolvedUrl = '/'.ltrim($resolvedUrl, '/');
            }
            $event->setResponse(new RedirectResponse($resolvedUrl, 301));
        }
    }
}
