<?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\ActivityBundle\Export\Filter\ACPFilters;

use Chill\ActivityBundle\Entity\Activity;
use Chill\ActivityBundle\Entity\ActivityType;
use Chill\ActivityBundle\Repository\ActivityTypeRepositoryInterface;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class ActivityTypeFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;
    private const BASE_EXISTS = 'SELECT 1 FROM '.Activity::class.' act_type_filter_activity WHERE act_type_filter_activity.accompanyingPeriod = acp';

    public function __construct(
        private ActivityTypeRepositoryInterface $activityTypeRepository,
        private TranslatableStringHelperInterface $translatableStringHelper,
        private RollingDateConverterInterface $rollingDateConverter,
    ) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $exists = self::BASE_EXISTS;

        if (count($data['accepted_activitytypes']) > 0) {
            $exists .= ' AND act_type_filter_activity.activityType IN (:act_type_filter_activity_types)';
            $qb->setParameter('act_type_filter_activity_types', $data['accepted_activitytypes']);
        }

        if (null !== $data['date_after']) {
            $exists .= ' AND act_type_filter_activity.date >= :act_type_filter_activity_date_after';
            $qb->setParameter('act_type_filter_activity_date_after', $this->rollingDateConverter->convert($data['date_after']));
        }

        if (null !== $data['date_before']) {
            $exists .= ' AND act_type_filter_activity.date >= :act_type_filter_activity_date_before';
            $qb->setParameter('act_type_filter_activity_date_before', $this->rollingDateConverter->convert($data['date_before']));
        }

        if (self::BASE_EXISTS !== $exists) {
            $qb->andWhere($qb->expr()->exists($exists));
        }
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('accepted_activitytypes', EntityType::class, [
            'class' => ActivityType::class,
            'choices' => $this->activityTypeRepository->findAllActive(),
            'choice_label' => fn (ActivityType $aty) => ($aty->hasCategory() ? $this->translatableStringHelper->localize($aty->getCategory()->getName()).' > ' : '')
            .
            $this->translatableStringHelper->localize($aty->getName()),
            'multiple' => true,
            'expanded' => true,
        ]);

        $builder->add('date_after', PickRollingDateType::class, [
            'label' => 'export.filter.activity.acp_by_activity_type.activity after',
            'help' => 'export.filter.activity.acp_by_activity_type.activity after help',
            'required' => false,
        ]);

        $builder->add('date_before', PickRollingDateType::class, [
            'label' => 'export.filter.activity.acp_by_activity_type.activity before',
            'help' => 'export.filter.activity.acp_by_activity_type.activity before help',
            'required' => false,
        ]);
    }

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

    public function normalizeFormData(array $formData): array
    {
        return ['accepted_activitytypes' => $this->normalizeDoctrineEntity($formData['accepted_activitytypes']), 'date_after' => $formData['date_after']?->normalize(), 'date_before' => $formData['date_before']?->normalize()];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return ['accepted_activitytypes' => $this->denormalizeDoctrineEntity($formData['accepted_activitytypes'], $this->activityTypeRepository), 'date_after' => \Chill\MainBundle\Service\RollingDate\RollingDate::fromNormalized($formData['date_after']), 'date_before' => \Chill\MainBundle\Service\RollingDate\RollingDate::fromNormalized($formData['date_before'])];
    }

    public function getFormDefaultData(): array
    {
        return [
            'accepted_activitytypes' => [],
            'date_after' => null,
            'date_before' => null,
        ];
    }

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

        foreach ($data['accepted_activitytypes'] as $aty) {
            $types[] = $this->translatableStringHelper->localize($aty->getName());
        }

        return ['export.filter.activity.acp_by_activity_type.acp_containing_at_least_one_activitytypes', [
            'activitytypes' => implode(', ', $types),
            'has_date_after' => null !== $data['date_after'] ? 1 : 0,
            'date_after' => $this->rollingDateConverter->convert($data['date_after']),
            'has_date_before' => null !== $data['date_before'] ? 1 : 0,
            'date_before' => $this->rollingDateConverter->convert($data['date_before']),
        ]];
    }

    public function getTitle(): string
    {
        return 'Filter accompanying course by activity type';
    }
}
