<?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\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 ConfidentialFilter implements FilterInterface
{
    private const CHOICES = [
        'is not confidential' => 'false',
        'is confidential' => 'true',
    ];

    private const DEFAULT_CHOICE = 'false';

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

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

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

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

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

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

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

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

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

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return ['accepted_confidentials' => $formData['accepted_confidentials']];
    }

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

    public function describeAction($data, ExportGenerationContext $context): array
    {
        return [
            'Filtered by confidential: only %confidential%', [
                '%confidential%' => $this->translator->trans(
                    $data['accepted_confidentials'] ? 'is confidential' : 'is not confidential'
                ),
            ],
        ];
    }

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