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

use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriodParticipation;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class WithParticipationBetweenDatesFilter implements FilterInterface
{
    public function __construct(
        private RollingDateConverterInterface $rollingDateConverter,
    ) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $p = 'with_participation_between_dates_filter';

        $qb
            ->andWhere(
                $qb->expr()->exists(
                    'SELECT 1 FROM '.AccompanyingPeriodParticipation::class." {$p}_acp JOIN {$p}_acp.accompanyingPeriod {$p}_acpp ".
                    "WHERE {$p}_acp.person = person ".
                    "AND OVERLAPSI({$p}_acp.startDate, {$p}_acp.endDate), (:{$p}_date_after, :{$p}_date_before) = TRUE ".
                    "AND OVERLAPSI({$p}_acpp.openingDate, {$p}_acpp.closingDate), (:{$p}_date_after, :{$p}_date_before) = TRUE"
                )
            )
            ->setParameter("{$p}_date_after", $this->rollingDateConverter->convert($data['date_after']), Types::DATE_IMMUTABLE)
            ->setParameter("{$p}_date_before", $this->rollingDateConverter->convert($data['date_before']), Types::DATE_IMMUTABLE);
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('date_after', PickRollingDateType::class, [
            'label' => 'export.filter.person.with_participation_between_dates.date_after',
        ]);

        $builder->add('date_before', PickRollingDateType::class, [
            'label' => 'export.filter.person.with_participation_between_dates.date_before',
        ]);
    }

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

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

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return ['date_after' => RollingDate::fromNormalized($formData['date_after']), 'date_before' => RollingDate::fromNormalized($formData['date_before'])];
    }

    public function getFormDefaultData(): array
    {
        return [
            'date_after' => new RollingDate(RollingDate::T_YEAR_CURRENT_START),
            'date_before' => new RollingDate(RollingDate::T_TODAY),
        ];
    }

    public function describeAction($data, ExportGenerationContext $context): string|\Symfony\Contracts\Translation\TranslatableInterface|array
    {
        return ['export.filter.person.with_participation_between_dates.Filtered by participations during period: between %dateafter% and %datebefore%', [
            '%dateafter%' => $this->rollingDateConverter->convert($data['date_after'])->format('d-m-Y'),
            '%datebefore%' => $this->rollingDateConverter->convert($data['date_before'])->format('d-m-Y'),
        ]];
    }

    public function getTitle(): string|\Symfony\Contracts\Translation\TranslatableInterface
    {
        return 'export.filter.person.with_participation_between_dates.title';
    }
}
