<?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\Export\FilterInterface;
use Chill\MainBundle\Form\Type\PickUserLocationType;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

class AdministrativeLocationFilter implements FilterInterface
{
    public function __construct(private readonly TranslatableStringHelper $translatableStringHelper) {}

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

    public function alterQuery(QueryBuilder $qb, $data): void
    {
        $clause = $qb->expr()->in('acp.administrativeLocation', ':locations');
        $qb
            ->andWhere($clause)
            ->setParameter('locations', $data['accepted_locations']);
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('accepted_locations', PickUserLocationType::class, [
            'label' => 'Accepted locations',
            'multiple' => true,
        ]);
    }

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

    public function describeAction($data, $format = 'string'): array
    {
        $locations = [];

        foreach ($data['accepted_locations'] as $l) {
            $locations[] = $l->getName();
        }

        return ['Filtered by administratives locations: only %locations%', [
            '%locations%' => implode(', ', $locations),
        ]];
    }

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