<?php

namespace Myvetshop\Module\Clinique\Prestashop\Hook;

use Myvetshop\Module\Clinique\Adapter\ConfigurationAdapter;
use Myvetshop\Module\Clinique\Adapter\Hook\DisplayOrderConfirmation1ListenerInterface;
use Myvetshop\Module\Clinique\Adapter\Repository\CartRepository;
use Myvetshop\Module\Clinique\Adapter\Repository\OrderRepository;
use PrestaShop\PrestaShop\Adapter\LegacyContext;

class OrderStatusDisplayOrderConfirmation1Listener implements DisplayOrderConfirmation1ListenerInterface
{
    private CartRepository $cartRepository;

    private ConfigurationAdapter $configurationAdapter;

    private LegacyContext $legacyContext;

    private OrderRepository $orderRepository;

    public function __construct(
        CartRepository $cartRepository,
        ConfigurationAdapter $configurationAdapter,
        LegacyContext $legacyContext,
        OrderRepository $orderRepository
    ) {
        $this->cartRepository = $cartRepository;
        $this->configurationAdapter = $configurationAdapter;
        $this->legacyContext = $legacyContext;
        $this->orderRepository = $orderRepository;
    }

    public function displayOrderConfirmation1(): string
    {
        /** @var string|int|null $idCart */
        $idCart = \Tools::getValue('id_cart');

        $cart = $this->cartRepository->findById((int) $idCart);

        if (!$cart || $cart->secure_key !== \Tools::getValue('key')) {
            return '';
        }
        $order = $this->orderRepository->findByCartId((int) $cart->id);

        $currentStateOrder = $order ? $order->getCurrentOrderState() : null;

        if (
            $currentStateOrder
            && !in_array(
                (int) $currentStateOrder->id,
                [
                    (int) $this->configurationAdapter->get('PS_OS_ERROR'),
                    (int) $this->configurationAdapter->get('PS_OS_OUTOFSTOCK_UNPAID'),
                ]
            )
        ) {
            // Succès
            $orderStatus = 'success';
        } else {
            // Echec
            $orderStatus = 'error';
        }

        $context = $this->legacyContext->getContext();

        $context->smarty->assign([
            'orderStatus' => $orderStatus,
        ]);

        return $context
            ->smarty
            ->fetch('module:myvetshopclinique/views/templates/hook/display_order_confirmation1.tpl');
    }
}
