<?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\Repository\UserRepositoryInterface;
use Chill\MainBundle\Form\Type\PickUserOrMeDynamicType;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\MainBundle\Templating\Entity\UserRender;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class ReferrerFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;

    private const A = 'acp_referrer_filter_uhistory_x';

    private const P = 'acp_referrer_filter_date';

    private const PU = 'acp_referrer_filter_users';

    public function __construct(private RollingDateConverterInterface $rollingDateConverter, private UserRepositoryInterface $userRepository, private UserRender $userRender) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $qb
            ->join('acp.userHistories', self::A)
            ->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.'.user', ':'.self::PU)
            )
            ->setParameter(self::PU, $this->userOrMe($data['accepted_referrers'], $exportGenerationContext))
            ->setParameter(
                self::P,
                $this->rollingDateConverter->convert($data['date_calc'])
            );
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('accepted_referrers', PickUserOrMeDynamicType::class, [
                'multiple' => true,
            ])
            ->add('date_calc', PickRollingDateType::class, [
                'label' => 'export.filter.course.by_referrer.Computation date for referrer',
                'required' => true,
            ]);
    }

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

    public function normalizeFormData(array $formData): array
    {
        return ['accepted_referrers' => $this->normalizeUserOrMe($formData['accepted_referrers']), 'date_calc' => $formData['date_calc']->normalize()];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return ['accepted_referrers' => $this->denormalizeUserOrMe($formData['accepted_referrers'], $this->userRepository), 'date_calc' => RollingDate::fromNormalized($formData['date_calc'])];
    }

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

    public function describeAction($data, ExportGenerationContext $context): array
    {
        $users = [];

        foreach ($this->userOrMe($data['accepted_referrers'], $context) as $r) {
            $users[] = $this->userRender->renderString($r, []);
        }

        return [
            'Filtered by referrer: only %referrers%', [
                '%referrers%' => implode(', ', $users),
            ], ];
    }

    public function getTitle(): string
    {
        return 'Filter by referrers';
    }
}
