<?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\Bridge\Symfony\Bundle\Context\ShopCountryContext;
use CpCreation\VitiCore\Product\Model\Product;
use CpCreation\VitiCore\Product\Model\ProductCategory;
use CpCreation\VitiCore\Shop\ShopCatalogResolver;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent('shop:CatalogMobileBar', template: '@components/shop/CatalogMobileBar.html.twig')]
final class CatalogMobileBar
{
    public string $source = ShopCatalogResolver::SOURCE_SHOP;
    public ?string $categorySlug = null;
    public ?string $collection = null;

    private ?array $catalog = null;

    public function __construct(
        private readonly ShopCatalogResolver $catalogResolver,
        private readonly RequestStack $requestStack,
        private readonly ShopCountryContext $shopCountryContext,
    ) {}

    public function isShopBlocked(): bool
    {
        return ShopCatalogResolver::SOURCE_SHOP === $this->source && $this->shopCountryContext->isBlocked();
    }

    /**
     * @return ProductCategory[]
     */
    public function getCategories(): array
    {
        return $this->getCatalog()['categories'];
    }

    /**
     * @return Product[]
     */
    public function getProducts(): array
    {
        return $this->getCatalog()['mobileBarProducts'];
    }

    public function getCategory(): ?ProductCategory
    {
        return $this->getCatalog()['category'];
    }

    public function isShowCategoryMenu(): bool
    {
        return $this->getCatalog()['showCategoryMenu'];
    }

    private function getCatalog(): array
    {
        if (null !== $this->catalog) {
            return $this->catalog;
        }

        return $this->catalog = $this->catalogResolver->resolveCatalog(
            $this->source,
            $this->resolveCategorySlug(),
            $this->collection,
        );
    }

    private function resolveCategorySlug(): ?string
    {
        if (null !== $this->categorySlug && '' !== mb_trim($this->categorySlug)) {
            return $this->categorySlug;
        }

        $slug = $this->requestStack->getCurrentRequest()?->attributes->get('slug');

        return \is_string($slug) && '' !== $slug ? $slug : null;
    }
}
