<?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\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\MainBundle\Templating\TranslatableStringHelperInterface;
use Chill\PersonBundle\Entity\Household\HouseholdComposition;
use Chill\PersonBundle\Entity\Household\HouseholdCompositionType;
use Chill\PersonBundle\Entity\Household\HouseholdMember;
use Chill\PersonBundle\Export\Declarations;
use Chill\PersonBundle\Repository\Household\HouseholdCompositionTypeRepositoryInterface;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;

class ByHouseholdCompositionFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;

    public function __construct(private readonly HouseholdCompositionTypeRepositoryInterface $householdCompositionTypeRepository, private readonly RollingDateConverterInterface $rollingDateConverter, private readonly TranslatableStringHelperInterface $translatableStringHelper) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $p = 'person_by_household_compo_filter';

        $qb
            ->andWhere(
                $qb->expr()->exists(
                    'SELECT 1 FROM '.HouseholdMember::class." {$p}_hm  ".
                    'JOIN '.HouseholdComposition::class." {$p}_compo WITH {$p}_hm.household = {$p}_compo.household  ".
                    "WHERE {$p}_hm.person = person AND {$p}_hm.shareHousehold = 'TRUE' ".
                    "AND ({$p}_hm.startDate <= :{$p}_date AND ({$p}_hm.endDate IS NULL OR {$p}_hm.endDate > :{$p}_date)) ".
                    "AND ({$p}_compo.startDate <= :{$p}_date AND ({$p}_compo.endDate IS NULL OR {$p}_compo.endDate > :{$p}_date)) ".
                    "AND {$p}_compo.householdCompositionType IN (:{$p}_accepted)"
                )
            )
            ->setParameter("{$p}_accepted", $data['compositions'])
            ->setParameter("{$p}_date", $this->rollingDateConverter->convert($data['calc_date']), Types::DATE_IMMUTABLE);
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('compositions', EntityType::class, [
                'class' => HouseholdCompositionType::class,
                'choices' => $this->householdCompositionTypeRepository->findAllActive(),
                'choice_label' => fn (HouseholdCompositionType $compositionType) => $this->translatableStringHelper->localize($compositionType->getLabel()),
                'label' => 'export.filter.person.by_composition.Accepted compositions',
                'multiple' => true,
                'expanded' => true,
            ])
            ->add('calc_date', PickRollingDateType::class, [
                'label' => 'export.filter.person.by_composition.Date calc',
            ]);
    }

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

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

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

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

    public function describeAction($data, ExportGenerationContext $context): string|\Symfony\Contracts\Translation\TranslatableInterface|array
    {
        $compos = array_map(
            fn (HouseholdCompositionType $compositionType) => $this->translatableStringHelper->localize($compositionType->getLabel()),
            $data['compositions'] instanceof Collection ? $data['compositions']->toArray() : $data['compositions']
        );

        return ['export.filter.person.by_composition.Filtered by composition at %date%: only %compositions%', [
            '%compositions%' => implode(', ', $compos),
            '%date%' => $this->rollingDateConverter->convert($data['calc_date'])->format('d-m-Y'),
        ]];
    }

    public function getTitle(): string|\Symfony\Contracts\Translation\TranslatableInterface
    {
        return 'export.filter.person.by_composition.Filter by household composition';
    }
}
