<?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\PersonBundle\Export\Declarations;
use Doctrine\ORM\Query\Expr\Andx;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

class EmergencyFilter implements FilterInterface
{
    private const CHOICES = [
        'is emergency' => 'true',
        'is not emergency' => 'false',
    ];

    private const DEFAULT_CHOICE = 'false';

    public function __construct(private readonly TranslatorInterface $translator) {}

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

    public function alterQuery(QueryBuilder $qb, $data): void
    {
        $where = $qb->getDQLPart('where');
        $clause = $qb->expr()->eq('acp.emergency', ':emergency');

        if ($where instanceof Andx) {
            $where->add($clause);
        } else {
            $where = $qb->expr()->andX($clause);
        }

        $qb->add('where', $where);
        $qb->setParameter('emergency', $data['accepted_emergency']);
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('accepted_emergency', ChoiceType::class, [
            'choices' => self::CHOICES,
            'multiple' => false,
            'expanded' => true,
            'empty_data' => self::DEFAULT_CHOICE,
        ]);
    }

    public function getFormDefaultData(): array
    {
        return ['accepted_emergency' => self::DEFAULT_CHOICE];
    }

    public function describeAction($data, $format = 'string'): array
    {
        return [
            'Filtered by emergency: only %emergency%', [
                '%emergency%' => $this->translator->trans(
                    $data['accepted_emergency'] ? 'is emergency' : 'is not emergency'
                ),
            ],
        ];
    }

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