<?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\Twig\Components\Shop;

use CpCreation\VitiCore\Marketing\ProductReviewCardSummaryProvider;
use CpCreation\VitiCore\Marketing\ProductReviewCardSummary;
use CpCreation\VitiCore\Product\Model\Product;
use CpCreation\VitiCore\Product\Model\ProductCategory;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;
use Symfony\UX\TwigComponent\Attribute\PostMount;

#[AsTwigComponent('shop:ProductGrid', template: '@components/shop/ProductGrid.html.twig')]
final class ProductGrid
{
    /** @var array<string, ProductReviewCardSummary> */
    private array $reviewSummaries = [];

    private bool $reviewsEnabled = false;

    public function __construct(
        private readonly ProductReviewCardSummaryProvider $reviewSummaryProvider,
    ) {}

    /**
     * @var Product[]
     */
    public array $products = [];

    public ?ProductCategory $category = null;

    public bool $showLoginWhenEmpty = true;

    #[PostMount]
    public function loadReviewSummaries(): void
    {
        $reviewData = $this->reviewSummaryProvider->getForProducts($this->products);
        $this->reviewsEnabled = $reviewData->enabled;
        $this->reviewSummaries = $reviewData->summaries;
    }

    public function isReviewsEnabled(): bool
    {
        return $this->reviewsEnabled;
    }

    public function getReviewSummary(Product $product): ?ProductReviewCardSummary
    {
        return $this->reviewSummaries[$product->getId()->toString()] ?? null;
    }
}
