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

namespace Paysera\PrestashopPayments\Service;

use Paysera\PrestashopPayments\Provider\SettingsProvider;
use Paysera\PrestashopPayments\Repository\OrderRepository;
use Psr\Log\LoggerInterface;

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

class CartRestorationService
{
    public function __construct(
        private LoggerInterface $logger,
        private SettingsProvider $settingsProvider,
        private CmsToolsFacade $cmsToolsFacade,
        private CmsCookieFacade $cookieFacade,
        private OrderRepository $orderRepository,
        private OrderStatusManager $orderStatusManager
    ) {
    }

    public function restoreFromRequest(\Context $context): void
    {
        $cartId = (int) $this->cmsToolsFacade->getValue('id_cart');

        if ($cartId <= 0) {
            return;
        }

        $cart = $this->loadAndValidateCart($cartId, $context);

        if ($cart === null) {
            return;
        }

        $this->assignCartToContext($context, $cart);
    }

    public function restoreCartForFailedPayment(\Context $context, int $cartId): bool
    {
        if ($cartId <= 0) {
            return false;
        }

        $cart = $this->loadAndValidateCart($cartId, $context);

        if ($cart === null) {
            return false;
        }

        $order = $this->orderRepository->findByCartId($cartId);

        if ($order === null) {
            $this->assignCartToContext($context, $cart);

            return true;
        }

        $duplication = $cart->duplicate();

        if (!isset($duplication['success']) || !$duplication['success'] || !isset($duplication['cart'])) {
            $this->logger->error('Cart duplication failed', [
                'cart_id' => $cartId,
            ]);

            return false;
        }

        $newCart = $duplication['cart'];
        $this->copyCheckoutState($cart, $newCart);
        $this->assignCartToContext($context, $newCart);
        $this->cookieFacade->write();

        $this->orderStatusManager->setToCancelled($order);

        $this->logger->debug('Cart restored for failed payment', [
            'original_cart_id' => $cartId,
            'new_cart_id' => $newCart->id,
        ]);

        return true;
    }

    public function consumePendingCartId(\Context $context): ?int
    {
        $cartId = (int) $this->cookieFacade->get('paysera_pending_cart_id', 0);

        if ($cartId <= 0) {
            return null;
        }

        $this->cookieFacade->set('paysera_pending_cart_id', 0);
        $this->cookieFacade->write();

        if (!$this->isAwaitingPaymentOrder($cartId)) {
            return null;
        }

        return $cartId;
    }

    public function restorePendingPaymentCart(\Context $context): ?\Order
    {
        $cartId = (int) $this->cookieFacade->get('paysera_pending_cart_id', 0);

        if ($cartId <= 0) {
            return null;
        }

        $this->cookieFacade->set('paysera_pending_cart_id', 0);
        $this->cookieFacade->write();

        $order = $this->orderRepository->findByCartId($cartId);

        if ($order === null) {
            return null;
        }

        $awaitingPaymentStatus = $this->settingsProvider->getStatusAwaitingPayment();

        if ($awaitingPaymentStatus === null || (int) $order->current_state !== $awaitingPaymentStatus) {
            return null;
        }

        $restored = $this->restoreCartForFailedPayment($context, $cartId);

        if (!$restored) {
            return null;
        }

        $this->logger->debug('Cart restored for pending payment', [
            'order_id' => $order->id,
            'cart_id' => $cartId,
        ]);

        return $order;
    }

    private function isAwaitingPaymentOrder(int $cartId): bool
    {
        $order = $this->orderRepository->findByCartId($cartId);

        if ($order === null) {
            return false;
        }

        $awaitingPaymentStatus = $this->settingsProvider->getStatusAwaitingPayment();

        return $awaitingPaymentStatus !== null && (int) $order->current_state === $awaitingPaymentStatus;
    }

    private function copyCheckoutState(\Cart $source, \Cart $target): void
    {
        $target->id_address_delivery = $source->id_address_delivery;
        $target->id_address_invoice = $source->id_address_invoice;
        $target->id_carrier = $source->id_carrier;
        $target->gift = $source->gift;
        $target->gift_message = $source->gift_message;
        $target->update();

        $this->restoreDeliveryOption($source, $target);
        $this->copyCheckoutSessionData($source, $target);

        $this->logger->debug('Checkout state copied', [
            'source_cart_id' => $source->id,
            'target_cart_id' => $target->id,
            'id_address_delivery' => $target->id_address_delivery,
            'id_address_invoice' => $target->id_address_invoice,
            'id_carrier' => $target->id_carrier,
            'delivery_option' => $target->delivery_option,
        ]);
    }

    private function copyCheckoutSessionData(\Cart $source, \Cart $target): void
    {
        try {
            $sessionData = \Db::getInstance()->getValue(
                'SELECT `checkout_session_data` FROM `' . _DB_PREFIX_ . 'cart`'
                . ' WHERE `id_cart` = ' . (int) $source->id
            );

            if ($sessionData === false || $sessionData === null || $sessionData === '') {
                return;
            }

            \Db::getInstance()->update(
                'cart',
                ['checkout_session_data' => pSQL($sessionData)],
                '`id_cart` = ' . (int) $target->id
            );
        } catch (\Throwable $exception) {
            $this->logger->debug('Could not copy checkout session data', [
                'source_cart_id' => $source->id,
                'target_cart_id' => $target->id,
                'error' => $exception->getMessage(),
            ]);
        }
    }

    private function restoreDeliveryOption(\Cart $source, \Cart $target): void
    {
        if ($source->delivery_option === null || $source->delivery_option === '') {
            return;
        }

        $deliveryOption = json_decode($source->delivery_option, true);

        if (!is_array($deliveryOption) || $deliveryOption === []) {
            return;
        }

        $target->setDeliveryOption($deliveryOption);
        $target->save();
    }

    private function assignCartToContext(\Context $context, \Cart $cart): void
    {
        $context->cart = $cart;
        $this->cookieFacade->set('id_cart', $cart->id);
    }

    private function loadAndValidateCart(int $cartId, \Context $context): ?\Cart
    {
        $cart = new \Cart($cartId);

        if (!\Validate::isLoadedObject($cart)) {
            $this->logger->warning('Cart restoration failed: cart not found', [
                'cart_id' => $cartId,
            ]);

            return null;
        }

        if (!$this->isCartOwnedByCurrentUser($cart, $context)) {
            $this->logger->warning('Cart ownership validation failed', [
                'cart_id' => $cartId,
                'cart_customer_id' => (int) $cart->id_customer,
                'context_customer_id' => (int) ($context->customer->id ?? 0),
            ]);

            return null;
        }

        return $cart;
    }

    private function isCartOwnedByCurrentUser(\Cart $cart, \Context $context): bool
    {
        $customerId = (int) ($context->customer->id ?? 0);
        $cartCustomerId = (int) $cart->id_customer;

        return $customerId > 0 && $cartCustomerId === $customerId;
    }
}
