<?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\PickRollingDateType;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodInfo;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * Filter accompanying course which have a row in AccompanyingPeriodInfo within the given
 * interval.
 */
final readonly class HavingAnAccompanyingPeriodInfoWithinDatesFilter implements FilterInterface
{
    public function __construct(
        private RollingDateConverterInterface $rollingDateConverter,
    ) {}

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('start_date', PickRollingDateType::class, [
                'label' => 'export.filter.course.having_info_within_interval.start_date',
            ])
            ->add('end_date', PickRollingDateType::class, [
                'label' => 'export.filter.course.having_info_within_interval.end_date',
            ]);
    }

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

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

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

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

    public function getTitle(): string
    {
        return 'export.filter.course.having_info_within_interval.title';
    }

    public function describeAction($data, ExportGenerationContext $context): array
    {
        return [
            'export.filter.course.having_info_within_interval.Only course with events between %startDate% and %endDate%',
            [
                '%startDate%' => $this->rollingDateConverter->convert($data['start_date'])->format('d-m-Y'),
                '%endDate%' => $this->rollingDateConverter->convert($data['end_date'])->format('d-m-Y'),
            ],
        ];
    }

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $ai = 'having_ai_within_interval_acc_info';
        $as = 'having_ai_within_interval_start_date';
        $ae = 'having_ai_within_interval_end_date';

        $qb
            ->andWhere(
                $qb->expr()->exists(
                    'SELECT 1 FROM '.AccompanyingPeriodInfo::class." {$ai} WHERE {$ai}.infoDate BETWEEN :{$as} AND :{$ae} AND IDENTITY({$ai}.accompanyingPeriod) = acp.id"
                )
            )
            ->setParameter($as, $this->rollingDateConverter->convert($data['start_date']), Types::DATETIME_IMMUTABLE)
            ->setParameter($ae, $this->rollingDateConverter->convert($data['end_date']), Types::DATETIME_IMMUTABLE);
    }

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