<?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)
            ->addJavaScript('js/front/native-checkout.js');
    }

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

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

            return;
        }

        try {
            $this->saveDeliveryOption($cart, $event->getRequest());
        } catch (\Exception $e) {
            $this->addError($this->getTranslator()->trans('Could not update delivery option.', [], 'Modules.Glspoland.Checkout'));

            $event->setComplete(false);
        }
    }

    protected function addError(string $error): void
    {
        if (!isset($this->controller)) {
            return;
        }

        $this->controller->errors[] = $error;
    }
}
