<?php

declare(strict_types=1);

namespace KupShop\ComponentsBundle\Twig\Components\EditableContent;

use KupShop\ComponentsBundle\Attributes\Blocek;
use KupShop\ComponentsBundle\Attributes\BlocekAttribute;
use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Twig\Components\Utils\EditableContent\BlocekDataResult;
use KupShop\ComponentsBundle\Twig\Components\Utils\EditableContent\BlocekDataTrait;
use KupShop\ContentBundle\Page\FragmentPage;
use KupShop\ContentBundle\Util\BlocekTypes;
use Query\Operator;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent(template: '@Components/components/EditableContent/ContentTemplate/ContentTemplate.1.html.twig')]
#[Component(1, [
    new Version(1, newJs: null, newCss: null),
])]
#[Blocek(title: 'Fragment')]
class Fragments extends ContentTemplate
{
    use BlocekDataTrait;

    #[BlocekAttribute(
        title: 'Fragment',
        type: BlocekTypes::AUTOCOMPLETE,
        autocompleteType: 'fragments',
        autocompletePreload: 'fragments'
    )]
    public ?array $fragmentConfig = null;

    protected function getTemplateData($data): false|array
    {
        if (empty($data['fragmentConfig'])) {
            return false;
        }

        $fragments = new BlocekDataResult($data['fragmentConfig']);

        return sqlQueryBuilder()->select('id, name, id_block')->from('pages')
            ->where(Operator::equals(['type' => FragmentPage::getType()]))
            ->andWhere(Operator::inStringArray($fragments->getValues(), 'code'))
            ->execute()->fetchAssociative();
    }
}
