<?php

declare(strict_types=1);

class CartController extends CartControllerCore
{
    /**
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     *
     * TODO : A supprimer
     */
    protected function processChangeProductInCart(): void
    {
        if (!$this->context->customer->isLogged()) {
            $this->errors[] = $this->trans(
                'Vous devez vous connecter pour ajouter un produit au panier',
                [],
                'Modules.Myvetshopclinique.Shop'
            );

            return;
        }

        $product = new Product(\intval(Tools::getValue('id_product')));

        $container = $this->getContainer();
        if (!$container || !$container->has(\Myvetshop\Module\Clinique\Cart\ProductAddToCartPreventer::class)) {
            $module = \Module::getInstanceByName('myvetshopclinique');
            $container = $module ? $module->getContainer() : null;
        }

        if ($container && $container->has(\Myvetshop\Module\Clinique\Cart\ProductAddToCartPreventer::class)) {
            $addToCartPreventer = $container->get(\Myvetshop\Module\Clinique\Cart\ProductAddToCartPreventer::class);
            \assert($addToCartPreventer instanceof \Myvetshop\Module\Clinique\Cart\ProductAddToCartPreventer);

            $idProductAttribute = \intval(Tools::getValue('id_product_attribute'));
            $quantity = \intval(Tools::getValue('qty'));
            $op = \strval(Tools::getValue('op', 'up'));

            if (
                $addToCartPreventer instanceof \Myvetshop\Module\Clinique\Cart\ProductAddToCartPreventer
                && $errorMessage = $addToCartPreventer->getErrorMessage(
                    $product,
                    $idProductAttribute,
                    $quantity,
                    $op,
                    $this->context->customer,
                    $this->context->cart
                )
            ) {
                $this->errors[] = $this->trans(
                    $errorMessage,
                    [],
                    'Modules.Myvetshopclinique.Shop'
                );
            }
        }

        if (!$product->id || !$product->active || !$product->checkAccess($this->context->cart->id_customer)) {
            $this->errors[] = $this->trans(
                'This product is no longer available.', [],
                'Shop.Notifications.Error'
            );

            return;
        }
        if (0 == count($this->errors)) {
            parent::processChangeProductInCart();
        }
    }

    public function initContent(): void
    {
        if ('show' === Tools::getValue('action')) {
            if (!$this->context->customer->isLogged()) {
                Tools::redirect('index.php');
            } elseif (true === $this->areProductsAvailable()) {
                Tools::redirect((new Link())->getPageLink('order'));
            }
        }

        parent::initContent();
    }
}
