<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Checkout\Module;

use Gls\GlsPoland\PrestaShop\Asset\DTO\Assets;
use Gls\GlsPoland\PrestaShop\Checkout\AbstractCheckout;
use Gls\GlsPoland\PrestaShop\Checkout\Event\CarrierProcessEvent;
use Gls\GlsPoland\PrestaShop\Checkout\ModuleCheckoutInterface;

final class ETSOnePageCheckout extends AbstractCheckout implements ModuleCheckoutInterface
{
    use ModuleControllerCheckerTrait;

    private const MODULE_NAME = 'ets_onepagecheckout';
    private const CREATE_ORDER_PARAM = 'submitCompleteMyOrder';

    public static function getModuleName(): string
    {
        return self::MODULE_NAME;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            CarrierProcessEvent::class => 'onCarrierProcess',
        ];
    }

    public function getAssets(\Cart $cart): Assets
    {
        return parent::getAssets($cart)
            ->addJavaScript('js/front/ets-one-page-checkout.js');
    }

    public function onCarrierProcess(CarrierProcessEvent $event): void
    {
        $request = $event->getRequest();

        if (!$request->request->has(self::CREATE_ORDER_PARAM)) {
            return;
        }

        $cart = $event->getCart();

        if (false === $deliveryOption = $cart->getDeliveryOption(null, true, false)) {
            $this->addError($this->getTranslator()->trans('The selected delivery option is not available.', [], 'Modules.Glspoland.Checkout'));

            return;
        }

        $request = clone $request;
        $request->request->set('delivery_option', $deliveryOption); // the module might have adjusted the original address IDs
        $params = $request->request->all();

        if (!$this->validateDeliveryOption($cart, $params)) {
            return;
        }

        $this->saveDeliveryOption($cart, $request);
    }

    private static function getCheckoutControllerNames(): array
    {
        return ['order'];
    }
}
