<?php

namespace KupShop\ArticlesBundle\Twig\Components\Articles;

use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use KupShop\I18nBundle\Translations\ArticlesSectionsTranslation;
use KupShop\KupShopBundle\Util\StringUtil;
use Query\Operator;
use Query\Translation;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;
use Symfony\UX\TwigComponent\Attribute\PostMount;

#[AsTwigComponent(template: '@Articles/components/Articles/ArticleFlag/ArticleFlag.1.html.twig')]
#[Component(1, [
    new Version(1, newJs: null),
])]
class ArticleFlag extends BaseComponent
{
    public int $id_article;
    private ?array $articleFlags = null;

    #[PostMount]
    public function loadArticleFlags(): void
    {
        if (empty($this->articleFlags)) {
            $this->articleFlags = sqlQueryBuilder()
                ->select('ab.id, ab.name, ab.name as flag_name')
                ->from('articles_relation', 'ar')
                ->leftJoin('ar', 'articles_branches', 'ab', 'ar.id_branch = ab.id')
                ->andWhere(Operator::equals(['ar.id_art' => $this->id_article]))
                ->andWhere(Translation::coalesceTranslatedFields(ArticlesSectionsTranslation::class))
                ->execute()
                ->fetchAllAssociative();
        }
    }

    public function getArticleFlags(): array
    {
        return $this->articleFlags ?? [];
    }

    public function getSectionUrl(int $id): string
    {
        return path('kupshop_content_articles_articles_1', ['IDb' => $id]);
    }

    public function getFlagClass(string $sectionName): string
    {
        return StringUtil::slugify($sectionName);
    }
}
