<?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\Factory\RequestFactory;
use Paysera\PrestashopPayments\Repository\OrderRepository;
use Paysera\PrestashopPayments\Repository\PayseraPaymentRepository;
use Paysera\PrestashopPayments\Service\CartRestorationService;
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 PayserapaymentsValidationModuleFrontController extends ModuleFrontController
{
    public function postProcess(): void
    {
        $logger = $this->get('paysera.logger');
        $link = $this->context->link;

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

        $this->logValidationHit($logger);

        $this->get(CartRestorationService::class)->restoreFromRequest($this->context);

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

        if (!$cart || !$cart->id || $cart->id_customer === 0) {
            $logger->warning('Payment validation failed: Invalid cart');
            $this->get(PopupBridgeRenderer::class)->redirect($link->getPageLink('order', true), $this->context->cookie);

            return;
        }

        $orderRepository = $this->get(OrderRepository::class);
        $order = $orderRepository->findByCartId($cart->id);

        if (!$order) {
            $logger->warning('Payment validation failed: No order found for cart', [
                'cart_id' => $cart->id,
            ]);
            $this->get(PopupBridgeRenderer::class)->redirect($link->getPageLink('order', true), $this->context->cookie);

            return;
        }

        $orderStatusManager = $this->get(OrderStatusManager::class);
        $orderStatusManager->setToAwaitingConfirmation($order);

        $this->redirectToConfirmation($order, $cart, $link);
    }

    private function logValidationHit(Psr\Log\LoggerInterface $logger): void
    {
        $request = $this->get(RequestFactory::class)->createFromGlobals();
        $cartId = (int) $this->get(CmsToolsFacade::class)->getValue('id_cart');

        $context = [
            'id_cart' => $cartId,
            'query_string' => $request->getUri()->getQuery(),
            'referer' => $request->getHeaderLine('Referer'),
        ];

        if ($cartId > 0) {
            $order = $this->get(OrderRepository::class)->findByCartId($cartId);

            if ($order !== null) {
                $context['id_order'] = (int) $order->id;
                $context['current_state'] = (int) $order->current_state;
                $context['reference'] = $order->reference;

                $paysera = $this->get(PayseraPaymentRepository::class)->findByOrderId((int) $order->id);
                if ($paysera !== null) {
                    $context['paysera_payment_id'] = $paysera->getPayseraPaymentId();
                    $context['paysera_order_id'] = $paysera->getPayseraOrderId();
                    $context['payment_method'] = $paysera->getPaymentMethod();
                }
            }
        }

        $logger->info('Paysera validation URL hit — customer returned from gateway (success path)', $context);
    }

    private function redirectToConfirmation(Order $order, Cart $cart, $link): void
    {

        $customer = new Customer($order->id_customer);
        $logger = $this->get('paysera.logger');

        $logger->debug('Payment validation successful, redirecting to confirmation', [
            'order_id' => $order->id,
            'cart_id' => $cart->id,
            'reference' => $order->reference,
        ]);

        $confirmationUrl = $link->getPageLink(
            'order-confirmation',
            true,
            null,
            [
                'id_cart' => $cart->id,
                'id_module' => $this->module->id,
                'id_order' => $order->id,
                'key' => $customer->secure_key,
            ]
        );

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