<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\PersonBundle\Export\Filter\AccompanyingCourseFilters;

use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Form\Type\PickUserDynamicType;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

class CreatorFilter implements FilterInterface
{
    public function addRole(): ?string
    {
        return null;
    }

    public function alterQuery(QueryBuilder $qb, $data): void
    {
        if (!\in_array('acp_creator', $qb->getAllAliases(), true)) {
            $qb->join('acp.createdBy', 'acp_creator');
        }

        $qb
            ->andWhere($qb->expr()->in('acp_creator', ':creators'))
            ->setParameter('creators', $data['accepted_creators']);
    }

    public function applyOn(): string
    {
        return Declarations::ACP_TYPE;
    }

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('accepted_creators', PickUserDynamicType::class, [
                'multiple' => true,
                'label' => false,
            ]);
    }

    public function getFormDefaultData(): array
    {
        return [];
    }

    public function describeAction($data, $format = 'string'): array
    {
        return [
            'Filtered by creator: only %creators%', [
                '%creators%' => implode(
                    ', ',
                    array_map(
                        static fn (User $u) => $u->getLabel(),
                        $data['accepted_creators'] instanceof Collection ? $data['accepted_creators']->toArray() : $data['accepted_creators']
                    )
                ),
            ], ];
    }

    public function getTitle(): string
    {
        return 'Filter by creator';
    }
}
