<?php

declare(strict_types=1);

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

use Gls\GlsPoland\AdePlus\ParcelShop\ParcelShop;
use Gls\GlsPoland\DataProvider\ParcelShopDataProvider;
use Gls\GlsPoland\Entity\ShopDeliveryCarrier;
use Gls\GlsPoland\PrestaShop\Checkout\Presenter\ParcelShopAddressPresenter;
use Gls\GlsPoland\PrestaShop\Helper\CarrierFinder;
use Gls\GlsPoland\PrestaShop\Hook\HookInterface;
use Gls\GlsPoland\PrestaShop\Templating\RendererInterface;
use Gls\GlsPoland\Repository\CheckoutSessionRepository;

final class DisplayOrderConfirmation implements HookInterface
{
    public const HOOK_NAME = 'displayOrderConfirmation';

    private $carrierFinder;
    private $sessionRepository;
    private $dataProvider;
    private $presenter;
    private $renderer;

    public function __construct(CarrierFinder $carrierFinder, CheckoutSessionRepository $sessionRepository, ParcelShopDataProvider $dataProvider, ParcelShopAddressPresenter $presenter, RendererInterface $renderer)
    {
        $this->carrierFinder = $carrierFinder;
        $this->sessionRepository = $sessionRepository;
        $this->dataProvider = $dataProvider;
        $this->presenter = $presenter;
        $this->renderer = $renderer;
    }

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

        if (!$order instanceof \Order) {
            return '';
        }

        $carrier = $this->carrierFinder->findOneByCarrierId((int) $order->id_carrier);

        if (!$carrier instanceof ShopDeliveryCarrier) {
            return '';
        }

        if (null === $parcelShop = $this->getParcelShop($order, $carrier->getId()->getValue())) {
            return '';
        }

        return $this->renderer->render('module:glspoland/views/templates/hook/order_confirmation.tpl', [
            'parcel_shop_address' => $this->presenter->present($parcelShop),
        ]);
    }

    private function getParcelShop(\Order $order, int $carrierId): ?ParcelShop
    {
        $checkoutSession = $this->sessionRepository->find((int) $order->id_cart);

        if (null === $checkoutSession || null === $parcelShopId = $checkoutSession->getParcelShopId($carrierId)) {
            return null;
        }

        return $this->dataProvider->getParcelShop($parcelShopId);
    }
}
