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

use Chill\CalendarBundle\Export\Declarations;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

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

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

    public function alterQuery(QueryBuilder $qb, $data): void
    {
        $clause = $qb->expr()->andX(
            $qb->expr()->gte('cal.startDate', ':dateFrom'),
            $qb->expr()->lte('cal.endDate', ':dateTo')
        );

        $qb->andWhere($clause);
        $qb->setParameter(
            'dateFrom',
            $this->rollingDateConverter->convert($data['date_from'])
        );
        // modify dateTo so that entire day is also taken into account up until the beginning of the next day.
        $qb->setParameter(
            'dateTo',
            $this->rollingDateConverter->convert($data['date_to'])->modify('+1 day')
        );
    }

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

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

    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'): array
    {
        return ['Filtered by calendars between %dateFrom% and %dateTo%', [
            '%dateFrom%' => $this->rollingDateConverter->convert($data['date_from'])->format('d-m-Y'),
            '%dateTo%' => $this->rollingDateConverter->convert($data['date_to'])->format('d-m-Y'),
        ]];
    }

    public function getTitle(): string
    {
        return 'Filter calendars between certain dates';
    }
}
