<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Hook\Front\Checkout;

use Gls\GlsPoland\PrestaShop\Checkout\CheckoutResolverInterface;
use Gls\GlsPoland\PrestaShop\Hook\HookInterface;
use Symfony\Component\HttpFoundation\Request;

final class DisplayBeforeBodyClosingTag implements HookInterface
{
    public const HOOK_NAME = 'displayBeforeBodyClosingTag';

    private $checkoutResolver;

    public function __construct(CheckoutResolverInterface $checkoutResolver)
    {
        $this->checkoutResolver = $checkoutResolver;
    }

    /**
     * @param array{request: Request} $parameters
     */
    public function execute(array $parameters): string
    {
        $request = $parameters['request'] ?? null;

        if ($request instanceof Request && $request->attributes->getBoolean('gls_poland_map_modal_rendered')) {
            return '';
        }

        if (null === $checkout = $this->checkoutResolver->resolve($request instanceof Request ? $request : null)) {
            return '';
        }

        if ($request instanceof Request) {
            $request->attributes->set('gls_poland_map_modal_rendered', true);
        }

        return $checkout->renderMapModal();
    }
}
