<?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\SocialWorkFilters;

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;

final readonly class ReferrerFilter implements FilterInterface
{
    private const PREFIX = 'acpw_referrer_filter';

    public function __construct(private RollingDateConverterInterface $rollingDateConverter) {}

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

    public function alterQuery(QueryBuilder $qb, $data): void
    {
        $p = self::PREFIX;

        $qb
            ->leftJoin('acpw.referrersHistory', $p.'_acpwusers_history')
            ->andWhere("{$p}_acpwusers_history.startDate <= :{$p}_calc_date AND ({$p}_acpwusers_history.endDate IS NULL or {$p}_acpwusers_history.endDate > :{$p}_calc_date)")
            ->andWhere("{$p}_acpwusers_history.user IN (:{$p}_agents)");

        $qb
            ->setParameter("{$p}_agents", $data['accepted_agents'])
            ->setParameter("{$p}_calc_date", $this->rollingDateConverter->convert(
                $data['agent_at'] ?? new RollingDate(RollingDate::T_TODAY)
            ))
        ;
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('accepted_agents', PickUserDynamicType::class, [
                'multiple' => true,
                'label' => 'export.filter.work.by_treating_agent.Accepted agents',
            ])
            ->add('agent_at', PickRollingDateType::class, [
                'label' => 'export.filter.work.by_treating_agent.Calc date',
                'help' => 'export.filter.work.by_treating_agent.calc_date_help',
            ])
        ;
    }

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

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

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

        return [
            'exports.filter.work.by_treating_agent.Filtered by treating agent at date', [
                'agents' => implode(', ', $users),
                'agent_at' => $this->rollingDateConverter->convert($data['agent_at'] ?? new RollingDate(RollingDate::T_TODAY)),
            ], ];
    }

    public function getTitle(): string
    {
        return 'export.filter.work.by_treating_agent.Filter by treating agent';
    }
}
