<?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\SocialWorkFilters;

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
{
    private const PREFIX = 'acpw_filter_creator';

    public function addRole(): ?string
    {
        return null;
    }

    public function alterQuery(QueryBuilder $qb, $data): void
    {
        $p = self::PREFIX;

        $qb
            ->leftJoin('acpw.createdBy', "{$p}_creator")
            ->andWhere($qb->expr()->in("{$p}_creator", ":{$p}_creators"))
            ->setParameter("{$p}_creators", $data['creators']);
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('creators', PickUserDynamicType::class, [
                'multiple' => true,
                'label' => 'export.filter.work.by_creator.Creators',
            ]);
    }

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

    public function getFormDefaultData(): array
    {
        return [
            'creators' => [],
        ];
    }

    public function getTitle(): string
    {
        return 'export.filter.work.by_creator.title';
    }
}
