<?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\ExportElementValidatedInterface;
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;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

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

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

    public function alterQuery(QueryBuilder $qb, $data): void
    {
        $where = $qb->getDQLPart('where');
        $clause = $qb->expr()->between(
            'person.birthdate',
            ':date_from',
            ':date_to'
        );

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

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

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('date_from', PickRollingDateType::class, [
            'label' => 'Born after this date',
        ]);

        $builder->add('date_to', PickRollingDateType::class, [
            'label' => 'Born before this date',
        ]);
    }

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

    public function describeAction($data, $format = 'string')
    {
        return ['Filtered by person\'s birthdate: '
            .'between %date_from% and %date_to%', [
                '%date_from%' => $this->rollingDateConverter->convert($data['date_from'])->format('d-m-Y'),
                '%date_to%' => $this->rollingDateConverter->convert($data['date_to'])->format('d-m-Y'),
            ], ];
    }

    public function getTitle()
    {
        return 'Filter by person\'s birthdate';
    }

    public function validateForm($data, ExecutionContextInterface $context): void
    {
        $date_from = $data['date_from'];
        $date_to = $data['date_to'];

        if (null === $date_from) {
            $context->buildViolation('The "date from" should not be empty')
                // ->atPath('date_from')
                ->addViolation();
        }

        if (null === $date_to) {
            $context->buildViolation('The "date to" should not be empty')
                // ->atPath('date_to')
                ->addViolation();
        }

        if (
            (null !== $date_from && null !== $date_to)
            && $date_from >= $date_to
        ) {
            $context->buildViolation('The date "date to" should be after the '
                .'date given in "date from" field')
                ->addViolation();
        }
    }
}
