<?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\Event\StepCompleteValidationEvent;
use InPost\International\Checkout\ModuleCheckoutInterface;
use InPost\International\PrestaShop\Module\Util\ControllerChecker;
use Symfony\Component\HttpFoundation\Request;

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

final class STEasyCheckout extends AbstractCheckout implements ModuleCheckoutInterface
{
    private const MODULE_NAME = 'steasycheckout';

    /**
     * @var bool
     */
    private $formProcessed = false;

    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, [
            'default',
        ]);
    }

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

    /**
     * In the version of the module we had access to, the "actionValidateStepComplete" hook call was commented out.
     * We have not found another way to prevent orders if the required data has not been provided.
     */
    public function onValidateStepComplete(StepCompleteValidationEvent $event): void
    {
        $request = clone $event->getRequest();
        $request->request->replace($event->getRequestParameters());

        $cart = $event->getCart();

        try {
            $completed = $this->processDeliveryForm($cart, $request);

            $address = $this->getDeliveryAddress($cart);
            $completed = $completed && $this->validatePhoneNumber($address);
        } catch (\Exception $e) {
            $event->setUncompleted();
            $this->context->controller->errors[] = $this->context->getTranslator()->trans('An error occurred while processing your request.', [], 'Modules.Inpostinternational.Checkout');

            throw $e;
        } finally {
            $this->formProcessed = true;
        }

        if (!$completed) {
            $event->setUncompleted();
        }
    }

    public function onCarrierProcess(CarrierProcessEvent $event): void
    {
        if ($this->formProcessed) {
            return;
        }

        $request = $event->getRequest();

        if (!$request->request->has('delivery_option')) {
            return;
        }

        $this->processDeliveryForm($event->getCart(), $request);
    }

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