<?php

/*
 * This file is part of the VitiCore 2.
 *
 * (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\Utils;

use CpCreation\VitiCore\Product\Model\Product;
use CpCreation\VitiCore\Product\Model\ProductPrice;
use CpCreation\VitiCore\Product\Model\ProductVariant;
use CpCreation\VitiCore\Product\Repository\ProductRepository;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

class PriceGroupWithCookie
{
    public function __construct(
        private ProductRepository $productRepository,
        private RequestStack $requestStack,
    ) {
    }

    private function getSession(): ?SessionInterface
    {
        return $this->requestStack->getSession();
    }

    public function findAllPublish(): array
    {
        $priceGroupId = $this->getSession()->get('groupPrice', null);
        $products = $this->productRepository->findOnlyShop($priceGroupId);

        /** @var Product $product */
        foreach ($products as $product) {
            /** @var ProductVariant $variant */
            foreach ($product->getVariants() as $variant) {
                /** @var ProductPrice $price */
                foreach ($variant->getPrices() as $price) {
                    if ($price->getGroup()->getId()->toString() === $priceGroupId) {
                        $variant->setPrice($price->getPrice());
                        $variant->setPriceDiscount($price->getPriceDiscount());
                    }
                }
            }
        }

        return $products;
    }
}
