<?php

namespace KupShop\ComponentsBundle\Twig\Components\Header;

use Doctrine\DBAL\Driver\Exception;
use KupShop\CatalogBundle\Entity\Section;
use KupShop\CatalogBundle\Repository\SectionsRepository;
use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Util\Contexts;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent(template: '@Components/components/Header/Sections/Sections.1.html.twig')]
#[Component(1, [
    new Version(1),
])]
class Sections extends BaseComponent
{
    public bool $home_link = false;
    public ?string $home_icon = null;
    public bool $remove_container = false;

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

    /**
     * @throws Exception
     * @throws \Doctrine\DBAL\Exception
     * @throws ExceptionInterface
     */
    public function getSections(): array
    {
        $menuSectionsQuery = sqlQueryBuilder()
            ->select('sr.id_section')
            ->from('sections_relation', 'sr')
            ->leftJoin('sr', 'sections', 's', 'sr.id_section = s.id')
            ->andWhere('sr.id_topsection IS NULL')
            ->andWhere('sr.id_section > 0')
            ->andWhere("s.figure = 'Y'")
            ->addOrderBy('sr.position');

        return $this->sectionsRepository->findManyById($menuSectionsQuery->execute()->fetchFirstColumn());
    }

    public function hasUserGroup($idGroup): bool
    {
        if ($user = Contexts::get(UserContext::class)->getActive()) {
            return $user->hasGroupId($idGroup);
        }

        return false;
    }

    public function getName(Section $section): string
    {
        return $section->getNameShort() ?: $section->getName();
    }

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