<?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\Templating\TranslatableStringHelper;
use Chill\PersonBundle\Entity\SocialWork\Evaluation;
use Chill\PersonBundle\Export\Declarations;
use Chill\PersonBundle\Repository\SocialWork\EvaluationRepositoryInterface;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;

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

    public function __construct(private EvaluationRepositoryInterface $evaluationRepository, private TranslatableStringHelper $translatableStringHelper) {}

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

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

        if (!\in_array('workeval', $qb->getAllAliases(), true)) {
            $qb->join('acpw.accompanyingPeriodWorkEvaluations', 'workeval');
        }

        if (!\in_array('eval', $qb->getAllAliases(), true)) {
            $qb->join('workeval.evaluation', 'eval');
        }

        $clause = $qb->expr()->in('eval.id', ':evaluations');
        $qb->andWhere($clause);
        $qb->setParameter('evaluations', $data['accepted_evaluations']);
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('accepted_evaluations', EntityType::class, [
            'class' => Evaluation::class,
            'choices' => $this->evaluationRepository->findAllActive(),
            'choice_label' => fn (Evaluation $ev) => $this->translatableStringHelper->localize($ev->getTitle()),
            'multiple' => true,
            'expanded' => false,
            'attr' => ['class' => 'select2'],
        ]);
    }

    public function getNormalizationVersion(): int
    {
        return 1;
    }

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

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

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

    public function describeAction($data, ExportGenerationContext $context): array
    {
        $evaluations = [];

        foreach ($data['accepted_evaluations'] as $ev) {
            $evaluations[] = $this->translatableStringHelper->localize($ev->getTitle());
        }

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

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