<?php

namespace Myvetshop\Module\Clinique\Prestashop\Hook;

use Myvetshop\Module\Clinique\Adapter\Hook\ActionCartUpdateQuantityBeforeInterface;
use Myvetshop\Module\Clinique\Cart\Preventer\CentravetPreventer;
use Myvetshop\Module\Clinique\Cart\ProductAddToCartPreventer;
use Myvetshop\Module\Clinique\Repository\MyvetshopCliniqueRepository;
use PrestaShop\PrestaShop\Adapter\LegacyContext;

class AddToCartPreventerListener implements ActionCartUpdateQuantityBeforeInterface
{
    private \Db $db;

    private LegacyContext $legacyContext;

    private MyvetshopCliniqueRepository $cliniqueRepository;

    private ProductAddToCartPreventer $preventer;

    public function __construct(
        \Db $db,
        LegacyContext $legacyContext,
        MyvetshopCliniqueRepository $cliniqueRepository,
        ProductAddToCartPreventer $preventer
    ) {
        $this->db = $db;
        $this->legacyContext = $legacyContext;
        $this->cliniqueRepository = $cliniqueRepository;
        $this->preventer = $preventer;
    }

    public function actionCartUpdateQuantityBefore(
        \Cart $cart,
        \Product $product,
        int $idProductAttribute,
        int $quantity,
        string $operator,
        \Shop $shop
    ): void {
        /** @var \myvetshopclinique $module */
        $module = \Module::getInstanceByName('myvetshopclinique');
        $context = $this->legacyContext->getContext();

        $errorMessage = $this->preventer->getErrorMessage(
            $product,
            $idProductAttribute,
            $quantity,
            $operator,
            $context->customer,
            $cart
        );

        if (!$errorMessage) {
            return;
        }

        if ($context->controller instanceof \CartController) {
            // Add error to display for the customer
            $context->controller->errors[] = $module->getTranslator()->trans(
                $errorMessage,
                [],
                'Modules.Myvetshopclinique.Shop'
            );
        }

        // Prevent add to cart
        $product->available_for_order = false;

        if (
            $errorMessage === CentravetPreventer::ERROR_MESSAGE
            && $quantity <= 2
        ) {
            $clinique = $this->cliniqueRepository->findByGroupId((int) $context->customer->id_default_group);

            if ($clinique) {
                $this->db->execute(
                    'UPDATE `' . _DB_PREFIX_ . 'stock`'
                    . ' SET `physical_quantity` = 0, `usable_quantity` = 0'
                    . ' WHERE `id_warehouse` = ' . (int) $clinique->idWarehouse
                    . ' AND `id_product` = ' . (int) $product->id
                    . ' AND `id_product_attribute` = ' . $idProductAttribute
                );

                if (\StockAvailable::dependsOnStock((int) $product->id)) {
                    // synchronizes
                    \StockAvailable::synchronize((int) $product->id);
                }
            }
        }
    }
}
