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

final readonly class AdministrativeLocationFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;

    public function __construct(private TranslatableStringHelper $translatableStringHelper, private LocationTypeRepository $locationTypeRepository) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): 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 getNormalizationVersion(): int
    {
        return 1;
    }

    public function normalizeFormData(array $formData): array
    {
        return ['accepted_locations' => $this->normalizeDoctrineEntity($formData['accepted_locations'])];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return ['accepted_locations' => $this->denormalizeDoctrineEntity($formData['accepted_locations'], $this->locationTypeRepository)];
    }

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

    public function describeAction($data, ExportGenerationContext $context): 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';
    }
}
