<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Site;

use CpCreation\VitiCore\Product\Model\Product;
use CpCreation\VitiCore\Product\Repository\ProductRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\ValueResolver;

final class CuveeController extends AbstractController
{
    public function __construct(
        private readonly ProductRepository $productRepository,
    ) {
    }

    public function index(Request $request): Response
    {
        $cuvees = $this->productRepository->findOnlyCuvee();

        $names = [];
        $refCuvees = [];

        /** @var Product $cuvee */
        foreach ($cuvees as $key => $cuvee) {
            $name = $cuvee->getName();

            if (\in_array($name, $names, true)) {
                $prevCuvee = $refCuvees[$name];

                $cuvee->translate($request->getLocale())
                    ->setQuality($prevCuvee['quality'].' & '.$cuvee->getQuality());

                unset($cuvees[$prevCuvee['key']]);
                continue;
            }

            $names[] = $name;
            $refCuvees[$name] = [
                'key' => $key,
                'quality' => $cuvee->getQuality(),
            ];
        }

        return $this->render('cuvees.html.twig', [
            'classMenu' => 'black',
            'subMenu' => true,
            'cuvees' => $cuvees,
        ]);
    }

    public function item(
        #[ValueResolver('translation_resolver')]
        Product $product,
    ): Response {
        $cuvees = $this->productRepository->findOnlyCuvee();
        $prevProduct = $this->productRepository->findPreviousCuvee($product->getPosition());
        $nextProduct = $this->productRepository->findNextCuvee($product->getPosition());

        return $this->render('cuveeItem.html.twig', [
            'cuvees' => $cuvees,
            'item' => $product,
            'prevItem' => $prevProduct,
            'nextItem' => $nextProduct,
        ]);
    }
}
