<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Checkout\Module;

use InPost\International\Asset\Assets;
use InPost\International\Checkout\AbstractCheckout;
use InPost\International\Checkout\Event\CarrierProcessEvent;
use InPost\International\Checkout\ModuleCheckoutInterface;
use InPost\International\Delivery\Util\CarrierFinder;
use InPost\International\PrestaShop\Module\Util\ControllerChecker;
use Symfony\Component\HttpFoundation\Request;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class ETSOnePageCheckout extends AbstractCheckout implements ModuleCheckoutInterface
{
    private const MODULE_NAME = 'ets_onepagecheckout';
    private const CREATE_ORDER_PARAM = 'submitCompleteMyOrder';

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

    public static function supports(\FrontControllerCore $controller, Request $request): bool
    {
        return ControllerChecker::isModuleController($controller, self::MODULE_NAME, [
            'order',
        ]);
    }

    public static function getSubscribedServices(): array
    {
        return parent::getSubscribedServices() + [
            CarrierFinder::class,
        ];
    }

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

    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->context->controller->errors[] = $this->context->getTranslator()->trans('The selected delivery option is not available.', [], 'Modules.Inpostinternational.Checkout');

            return;
        }

        if ([] === $this->get(CarrierFinder::class)->findByDeliveryOption($deliveryOption)) {
            return;
        }

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

        $this->processDeliveryForm($cart, $request);

        $address = $this->getDeliveryAddress($cart);
        $this->validatePhoneNumber($address);
    }

    protected function addCheckoutAssets(Assets $assets): void
    {
        $assets->addJavaScript('js/front/ets-one-page-checkout.js');
    }
}
