<?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\MainBundle\Templating\Entity\UserRender;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use src\Bundle\ChillPersonBundle\Tests\Export\Filter\AccompanyingCourseFilters\ReferrerFilterBetweenDatesTest;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * Class ReferrerFilterBetweenDates.
 *
 * This class implements the FilterInterface and provides functionality to filter query results
 * based on a range of dates and accepted referrers.
 *
 * @see ReferrerFilterBetweenDatesTest for tests
 */
final readonly class ReferrerFilterBetweenDates implements FilterInterface
{
    private const A = 'acp_referrer_filter_uhistory';

    private const P = 'acp_referrer_filter_date_start';
    private const Q = 'acp_referrer_filter_date_end';

    private const PU = 'acp_referrer_filter_users';

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

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

    public function alterQuery(QueryBuilder $qb, $data): void
    {
        $history = self::A;
        $start = self::P;
        $end = self::Q;
        $users = self::PU;

        $qb
            ->join('acp.userHistories', self::A)
            ->andWhere(
                "OVERLAPSI({$history}.startDate, {$history}.endDate),(:{$start}, :{$end}) = TRUE"
            )
            ->andWhere(
                "{$history}.user IN (:{$users})",
            )
            ->setParameter($users, $data['accepted_referrers'])
            ->setParameter($start, $this->rollingDateConverter->convert($data['start_date']))
            ->setParameter($end, $this->rollingDateConverter->convert($data['end_date']));
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('accepted_referrers', PickUserDynamicType::class, [
                'multiple' => true,
            ])
            ->add('start_date', PickRollingDateType::class, [
                'label' => 'export.filter.course.by_referrer_between_dates.start date',
                'required' => true,
            ])
            ->add('end_date', PickRollingDateType::class, [
                'label' => 'export.filter.course.by_referrer_between_dates.end date',
                'required' => true,
            ]);
    }

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

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

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

        return [
            'exports.filter.course.by_referrer_between_dates.description', [
                'agents' => implode(', ', $users),
                'start_date' => $this->rollingDateConverter->convert($data['start_date']),
                'end_date' => $this->rollingDateConverter->convert($data['end_date']),
            ], ];
    }

    public function getTitle(): string
    {
        return 'export.filter.course.by_referrer_between_dates.title';
    }
}
