<?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\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod\UserHistory;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

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

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $qb
            ->andWhere('
                NOT EXISTS (
                    SELECT 1 FROM '.UserHistory::class.' uh
                    WHERE uh.startDate <= :has_no_referrer_filter_date
                    AND (
                        uh.endDate IS NULL
                        or uh.endDate > :has_no_referrer_filter_date
                    )
                    AND uh.accompanyingPeriod = acp
                )
            ')
            ->setParameter(
                'has_no_referrer_filter_date',
                $this->rollingDateConverter->convert($data['calc_date'])
            );
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('calc_date', PickRollingDateType::class, [
                'label' => 'Has no referrer on this date',
            ]);
    }

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

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

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return ['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): array
    {
        return ['Filtered acp which has no referrer on date: %date%', [
            '%date%' => $this->rollingDateConverter->convert($data['calc_date'])->format('d-m-Y'),
        ]];
    }

    public function getTitle(): string
    {
        return 'Filter by which has no referrer';
    }
}
