<?php
/**
 * 2026 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2026 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */

declare(strict_types=1);

use Paysera\PrestashopPayments\Checker\ModuleStatusChecker;
use Paysera\PrestashopPayments\Controller\AbstractPayseraFrontController;
use Paysera\PrestashopPayments\Handler\PaymentInitiationHandler;
use Paysera\PrestashopPayments\Repository\OrderRepository;
use Paysera\PrestashopPayments\Service\CartRestorationService;
use Paysera\PrestashopPayments\Service\CheckoutErrorHandler;
use Paysera\PrestashopPayments\Service\CmsCookieFacade;
use Paysera\PrestashopPayments\Service\CmsToolsFacade;
use Paysera\PrestashopPayments\Service\OrderStatusManager;
use Paysera\PrestashopPayments\Service\PopupBridgeRenderer;

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

class PayserapaymentsPaymentModuleFrontController extends AbstractPayseraFrontController
{
    public function postProcess(): void
    {
        $this->logger()->debug('Payment process started', [
            'cart_id' => $this->context->cart ? $this->context->cart->id : null,
        ]);

        if (!$this->checkModuleStatus()) {
            return;
        }

        $cart = $this->context->cart;

        $this->processPaymentInitiation($cart);
    }

    private function checkModuleStatus(): bool
    {
        $statusChecker = $this->get(ModuleStatusChecker::class);

        if (!$statusChecker->isOperational($this->module)) {
            $this->redirectToCheckoutWithPopupSupport(
                $this->module->getTranslator()->trans('Payment method is currently unavailable. Please contact support.', [], 'Modules.Payserapayments.Global')
            );

            return false;
        }

        return true;
    }

    private function processPaymentInitiation(Cart $cart): void
    {
        $cmsToolsFacade = $this->get(CmsToolsFacade::class);
        $paymentMethod = $cmsToolsFacade->getValue('paysera_payment_method');
        $countryCode = $cmsToolsFacade->getValue('paysera_country_code');

        $paymentMethod = $paymentMethod !== null && $paymentMethod !== '' ? (string) $paymentMethod : null;
        $countryCode = $countryCode !== null && $countryCode !== '' ? (string) $countryCode : null;

        if ($paymentMethod === null) {
            $this->logger()->debug('Payment method not selected', [
                'cart_id' => $cart->id,
            ]);

            $this->redirectToCheckoutWithPopupSupport(
                $this->module->getTranslator()->trans(
                    'Please select a Paysera payment method to proceed.',
                    [],
                    'Modules.Payserapayments.Global'
                )
            );

            return;
        }

        $order = null;

        try {
            $orderId = $this->createOrder($cart);
            $orderRepository = $this->get(OrderRepository::class);
            $order = $orderRepository->findById($orderId);

            if ($order === null) {
                throw new Exception(sprintf('Order %d not found after creation', $orderId));
            }

            $paymentUrl = $this->initiatePayment($cart, $order, $paymentMethod, $countryCode);

            $cookie = $this->get(CmsCookieFacade::class);
            $cookie->set('paysera_pending_cart_id', $cart->id);
            $cookie->write();

            $this->logger()->debug('Redirecting to payment URL', [
                'cart_id' => $cart->id,
                'order_id' => $orderId,
            ]);

            $cmsToolsFacade->redirect($paymentUrl);
        } catch (Exception $exception) {
            $this->markOrderFailed($order);
            $this->get(CartRestorationService::class)->restoreCartForFailedPayment($this->context, $cart->id);
            $this->handlePaymentError($cart, $exception);
        }
    }

    private function markOrderFailed(?Order $order): void
    {
        if ($order === null) {
            return;
        }

        $this->get(OrderStatusManager::class)->setToFailed($order);
    }

    private function handlePaymentError(Cart $cart, Exception $exception): void
    {
        $this->logger()->error('Payment initiation failed', [
            'cart_id' => $cart->id,
            'exception' => $exception->getMessage(),
            'code' => $exception->getCode(),
        ]);

        $this->redirectToCheckoutWithPopupSupport(
            $this->module->getTranslator()->trans(
                'Payment could not be initiated. Please try again or contact support.',
                [],
                'Modules.Payserapayments.Global'
            )
        );
    }

    private function redirectToCheckoutWithPopupSupport(string $message): void
    {
        $errorHandler = new CheckoutErrorHandler($this->context->cookie);
        $errorHandler->setError($message);
        $this->context->cookie->write();

        $checkoutUrl = $this->context->link->getPageLink('order', true);

        $this->get(PopupBridgeRenderer::class)->redirect($checkoutUrl, $this->context->cookie);
    }

    private function createOrder(Cart $cart): int
    {
        $orderRepository = $this->get(OrderRepository::class);

        $orderId = $orderRepository->createFromCart($cart, $this->module);

        $this->logger()->debug('Order created successfully', [
            'cart_id' => $cart->id,
            'order_id' => $orderId,
        ]);

        return $orderId;
    }

    private function initiatePayment(Cart $cart, Order $order, ?string $paymentMethod, ?string $countryCode): string
    {
        $paymentHandler = $this->get(PaymentInitiationHandler::class);

        return $paymentHandler->initiatePayment($cart, $order, $paymentMethod, $countryCode);
    }
}
