<?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\Export\Declarations;
use Doctrine\ORM\Query\Expr\Andx;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

class ActiveOnDateFilter implements FilterInterface
{
    public function __construct(private readonly RollingDateConverterInterface $rollingDateConverter) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $where = $qb->getDQLPart('where');

        $clause = $qb->expr()->andX(
            $qb->expr()->lte('acp.openingDate', ':ondate'),
            $qb->expr()->orX(
                $qb->expr()->gt('acp.closingDate', ':ondate'),
                $qb->expr()->isNull('acp.closingDate')
            )
        );

        if ($where instanceof Andx) {
            $where->add($clause);
        } else {
            $where = $qb->expr()->andX($clause);
        }

        $qb->add('where', $where);
        $qb->setParameter(
            'ondate',
            $this->rollingDateConverter->convert($data['on_date'])
        );
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('on_date', PickRollingDateType::class, []);
    }

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

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

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

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

    public function describeAction($data, ExportGenerationContext $context): array
    {
        return ['Filtered by actives courses: active on %ondate%', [
            '%ondate%' => $this->rollingDateConverter->convert($data['on_date'])->format('d-m-Y'),
        ]];
    }

    public function getTitle(): string
    {
        return 'Filter by active on date';
    }
}
