<?php

declare(strict_types=1);

class ProductController extends ProductControllerCore
{
    /**
     * @param array<mixed> $product_for_template
     */
    protected function assignAttributesGroups($product_for_template = null): void
    {
        parent::assignAttributesGroups();

        $combinations = $this->context->smarty->getTemplateVars('combinations');

        if (!\is_array($combinations) || 0 === \count($combinations)) {
            return;
        }

        $id_combinations = \array_keys($combinations);

        // On ajoute : le poids net et le tarif fardelage
        $tarifs_specifiques = \Db::getInstance()->executeS(
            'SELECT pa.`id_product_attribute` as `id_product_attribute`,
            mts.`tarif_fardelage` AS `tarif_fardelage`, pa.`net_weight` AS `net_weight`
          FROM `ps_product_attribute` pa
          LEFT JOIN `ps_myvetshop_tarif_specifique` mts  ON mts.`id_product_attribute` = pa.`id_product_attribute`
          WHERE pa.`id_product_attribute` IN (' . \implode(',', $id_combinations) . ')'
        );
        if (!\is_array($tarifs_specifiques)) {
            $tarifs_specifiques = [];
        }
        foreach ($tarifs_specifiques as $tarif_specifique) {
            $combinations[$tarif_specifique['id_product_attribute']]['net_weight'] = $tarif_specifique['net_weight'];
        }

        // Mise à jour de la liste des variations
        $this->context->smarty->assign(['combinations' => $combinations]);
    }

    protected function assignPriceAndTax(): void
    {
        \assert(\method_exists($this->product, 'getReductionPrivilege'));
        $this->context->smarty->assign('reduction_privilege', $this->product->getReductionPrivilege());

        parent::assignPriceAndTax();
    }

    public function process(): void
    {
        $combinations = $this->context->smarty->getTemplateVars('combinations');

        if (!\is_array($combinations)) {
            return;
        }

        \Myvetshop\Module\Clinique\Domain\ProductAttribute\ProductAttributeSorter::sort($combinations);

        $this->context->smarty->assign(['combinations' => $combinations]);
    }
}
