<?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;

use InPost\International\Asset\Assets;
use InPost\International\Checkout\Event\StepCompleteValidationEvent;
use Symfony\Component\HttpFoundation\Request;

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

final class NativeCheckout extends AbstractCheckout
{
    public static function supports(\FrontControllerCore $controller, Request $request): bool
    {
        return $controller instanceof \OrderControllerCore || $request->attributes->get('_inpost_intl_checkout');
    }

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

    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;
        }

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

    public function renderView(Request $request, \Cart $cart, int $carrierId): string
    {
        // if the request is not a GET request, the user will be redirected so we can safely skip rendering carrier content
        if ('GET' !== $request->getMethod()) {
            return '';
        }

        return parent::renderView($request, $cart, $carrierId);
    }

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