<?php

namespace KupShop\ComponentsBundle\Twig\Components\Section;

use KupShop\CatalogBundle\Entity\Section;
use KupShop\CatalogBundle\Repository\SectionsRepository;
use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Entity\Thumbnail;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use KupShop\ComponentsBundle\Twig\DataProvider\SectionDataTrait;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent(template: '@Components/components/Section/SubCategories/SubCategories.1.html.twig')]
#[Component(2, [
    new Version(1, newJs: null),
    new Version(2, newTemplate: true, newJs: null, newCss: true),
])]
class SubCategories extends BaseComponent
{
    use SectionDataTrait;

    private const MAX_SUBCATEGORIES = 12;

    /** @var array Section[] */
    protected array $sections;

    public function __construct(
        private readonly SectionsRepository $sectionsRepository,
    ) {
    }

    /**
     * @return Section[]
     */
    public function getSections(): array
    {
        if (isset($this->sections)) {
            return $this->sections;
        }

        $this->sections = [];
        if (!empty($this->id_producer)) {
            $sections = $this->sectionsRepository->findManyByProducerId($this->id_producer, $this->id_section, limit: self::MAX_SUBCATEGORIES);

            foreach ($sections as $section) {
                if ($section->getId() === $this->id_section) {
                    continue;
                }

                $this->sections[] = $section;
            }
        } else {
            foreach ($this->section->getChildren() as $category) {
                // Skip subcategory if not visible
                if ($category && !$category->isVisible()) {
                    continue;
                }

                $this->sections[] = $category;
            }
        }

        return $this->sections;
    }

    public function getThumbnail(Section $section): ?Thumbnail
    {
        if ($section->getPhotoFilename()) {
            return new Thumbnail((string) $section->getId(), $section->getName(), $section->getDateUpdated()->format('Y-m-d H:i:s'));
        }

        return null;
    }

    public function getUrl(Section $section): string
    {
        // (LegacyUrlGenerator) automaticky přidá locale prefix
        return path('page', ['path' => $this->id_producer ? $section->getAutogeneratedUrl() : $section->getUrl()]);
    }
}
