<?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\Event\ValidateStepCompleteEvent;
use Gls\GlsPoland\PrestaShop\Checkout\ModuleCheckoutInterface;
use Gls\GlsPoland\PrestaShop\ModuleRepository;
use Symfony\Component\HttpFoundation\Request;

final class WebkulOnePageCheckout extends AbstractCheckout implements ModuleCheckoutInterface
{
    use ModuleControllerCheckerTrait {
        ModuleControllerCheckerTrait::supports as private isModuleController;
    }

    private const MODULE_NAME = 'wkonepagecheckout';

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

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

    public static function supports(\FrontControllerCore $controller, ModuleRepository $moduleRepository, ?Request $request = null): bool
    {
        if (self::isModuleController($controller, null, $request)) {
            return true;
        }

        if (!$controller instanceof \OrderControllerCore) {
            return false;
        }

        return $moduleRepository->isEnabled(self::MODULE_NAME);
    }

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

    public function onValidateStepComplete(ValidateStepCompleteEvent $event): void
    {
        if (!$this->validateDeliveryOption($event->getCart(), $event->getRequestParameters())) {
            $event->setComplete(false);
        }
    }

    public function onCarrierProcess(CarrierProcessEvent $event): void
    {
        $request = $event->getRequest();
        if (!$request->request->has('delivery_option')) {
            return;
        }

        $cart = $event->getCart();
        $params = $request->request->all();
        if (!$this->validateDeliveryOption($cart, $params)) {
            return;
        }

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

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