<?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\FilterInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Form\Type\PickUserDynamicType;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

class ReferrerFilter implements FilterInterface
{
    private const A = 'acp_referrer_filter_uhistory';

    private const P = 'acp_referrer_filter_date';

    private const PU = 'acp_referrer_filter_users';

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

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

    public function alterQuery(QueryBuilder $qb, $data): 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, $data['accepted_referrers'])
            ->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', PickUserDynamicType::class, [
                'multiple' => true,
            ])
            ->add('date_calc', PickRollingDateType::class, [
                'label' => 'export.filter.course.by_referrer.Computation date for referrer',
                'required' => true,
            ]);
    }

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

    public function describeAction($data, $format = 'string'): array
    {
        $users = [];

        foreach ($data['accepted_referrers'] as $r) {
            $users[] = $r;
        }

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

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