<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Checkout;

use Gls\GlsPoland\PrestaShop\Asset\DTO\Assets;
use Gls\GlsPoland\PrestaShop\Checkout\Event\ValidateStepCompleteEvent;

class NativeCheckout extends AbstractCheckout
{
    public static function getSubscribedEvents(): array
    {
        return [
            ValidateStepCompleteEvent::class => 'onValidateStepComplete',
        ];
    }

    public function getAssets(\Cart $cart): Assets
    {
        return parent::getAssets($cart);
    }

    public function onValidateStepComplete(ValidateStepCompleteEvent $event): void
    {
        $cart = $event->getCart();
        $requestParameters = $event->getRequestParameters();

        if (!$this->validateDeliveryOption($cart, $requestParameters)) {
            $event->setComplete(false);

            return;
        }

        try {
            $request = clone $event->getRequest();
            $request->request->replace($requestParameters);

            $this->saveDeliveryOption($cart, $request);
        } catch (\Exception $e) {
            $this->logCheckoutError('GLS native checkout failed while saving delivery option.', [
                'cartId' => (int) $cart->id,
                'addressId' => (int) $cart->id_address_delivery,
                'requestUri' => $event->getRequest()->getRequestUri(),
                'requestParameters' => $requestParameters,
                'exception' => $e,
            ]);
            $this->addError($this->getTranslator()->trans('Could not update delivery option.', [], 'Modules.Glspoland.Checkout'));

            $event->setComplete(false);
        }
    }
}
