<?php

namespace Myvetshop\Module\Clinique\Prestashop\Hook\DisplayProductExtraContent;

use Myvetshop\Module\Clinique\Entity\ProductFood;
use Myvetshop\Module\Clinique\Repository\ProductFoodRepository;
use PrestaShop\PrestaShop\Adapter\LegacyContext;
use PrestaShop\PrestaShop\Core\Product\ProductExtraContent;

class ProductFoodListener implements DisplayProductExtraContentInterface
{
    private LegacyContext $legacyContext;

    private ProductFoodRepository $productFoodRepository;

    public function __construct(
        LegacyContext $legacyContext,
        ProductFoodRepository $productFoodRepository
    ) {
        $this->legacyContext = $legacyContext;
        $this->productFoodRepository = $productFoodRepository;
    }

    /**
     * @return ProductExtraContent[]
     */
    public function displayProductExtraContent(\Product $product): array
    {
        $context = $this->legacyContext->getContext();
        if (!$context) {
            return [];
        }

        /** @var ProductFood|null $productFood */
        $productFood = $this->productFoodRepository->findOneBy(['idProduct' => $product->id]);
        if ($productFood !== null) {
            $productFoodLang = $productFood->getProductFoodLang((int) $context->language->id);
        } else {
            $productFoodLang = null;
        }

        if ($productFoodLang) {
            $context->smarty->assign('productFood', $productFoodLang);

            return [
                (new ProductExtraContent())
                ->setTitle('Informations nutritionnelles')
                ->setContent(
                    $context->smarty->fetch('module:myvetshopclinique/views/templates/hook/productfood.tpl')
                ),
            ];
        }

        return [];
    }
}
