<?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\ExportDataNormalizerTrait;
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;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

class StepFilterOnDate implements FilterInterface
{
    use ExportDataNormalizerTrait;

    private const A = 'acp_filter_bystep_stephistories';

    private const DEFAULT_CHOICE = [
        AccompanyingPeriod::STEP_CONFIRMED,
        AccompanyingPeriod::STEP_CONFIRMED_INACTIVE_SHORT,
        AccompanyingPeriod::STEP_CONFIRMED_INACTIVE_LONG,
    ];

    private const P = 'acp_step_filter_date';

    private const STEPS = [
        'course.draft' => AccompanyingPeriod::STEP_DRAFT,
        'course.confirmed' => AccompanyingPeriod::STEP_CONFIRMED,
        'course.closed' => AccompanyingPeriod::STEP_CLOSED,
        'course.inactive_short' => AccompanyingPeriod::STEP_CONFIRMED_INACTIVE_SHORT,
        'course.inactive_long' => AccompanyingPeriod::STEP_CONFIRMED_INACTIVE_LONG,
    ];

    public function __construct(private readonly RollingDateConverterInterface $rollingDateConverter, private readonly TranslatorInterface $translator) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        if (!\in_array(self::A, $qb->getAllAliases(), true)) {
            $qb->leftJoin('acp.stepHistories', self::A);
        }

        $qb
            ->andWhere(
                $qb->expr()->andX(
                    $qb->expr()->lte(self::A.'.startDate', ':'.self::P),
                    $qb->expr()->orX(
                        $qb->expr()->isNull(self::A.'.endDate'),
                        $qb->expr()->gt(self::A.'.endDate', ':'.self::P)
                    )
                )
            )
            ->andWhere(
                $qb->expr()->in(self::A.'.step', ':acp_filter_by_step_steps')
            )
            ->setParameter(self::P, $this->rollingDateConverter->convert($data['calc_date']))
            ->setParameter('acp_filter_by_step_steps', $data['accepted_steps_multi']);
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('accepted_steps_multi', ChoiceType::class, [
                'label' => 'export.filter.course.by_step.steps',
                'choices' => self::STEPS,
                'multiple' => true,
                'expanded' => true,
            ])
            ->add('calc_date', PickRollingDateType::class, [
                'label' => 'export.filter.course.by_step.date_calc',
            ]);
    }

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

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

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

    public function getFormDefaultData(): array
    {
        return [
            'accepted_steps_multi' => self::DEFAULT_CHOICE,
            'calc_date' => new RollingDate(RollingDate::T_TODAY),
        ];
    }

    public function describeAction($data, ExportGenerationContext $context): array
    {
        $steps = array_map(
            fn (string $step) => $this->translator->trans(array_flip(self::STEPS)[$step]),
            $data['accepted_steps_multi'] instanceof Collection ? $data['accepted_steps_multi']->toArray() : $data['accepted_steps_multi']
        );

        return ['Filtered by steps: only %step%', [
            '%step%' => implode(', ', $steps),
        ]];
    }

    public function getTitle(): string
    {
        return 'export.filter.course.by_step.Filter by step';
    }
}
