<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\Form\Filter\Payment;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Ferienpass\AdminBundle\Form\Filter\AbstractFilterType;
use Ferienpass\AdminBundle\Form\Filter\AsSubFilter;
use Ferienpass\CoreBundle\Entity\User;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\Translation\TranslatableInterface;

#[AsSubFilter(key: 'user', section: 'base', views: ['admin_payments_receipts'])]
class UserFilter extends AbstractFilterType
{
    public function getParent(): string
    {
        return EntityType::class;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'class' => User::class,
            'query_builder' => static fn (EntityRepository $er): QueryBuilder => $er->createQueryBuilder('u')
                ->where("JSON_SEARCH(u.roles, 'one', :role) IS NOT NULL")
                ->setParameter('role', 'ROLE_ADMIN')
                ->innerJoin('u.payments', 'p')
                ->orderBy('u.firstname'),
            'choice_label' => 'name',
            'placeholder' => '-',
        ]);
    }

    public function apply(QueryBuilder $qb, FormInterface $form): void
    {
        if ($form->isEmpty()) {
            return;
        }

        $k = $form->getName();
        $v = $form->getData();

        $qb
            ->andWhere('i.user = :q_'.$k)
            ->setParameter('q_'.$k, $v)
        ;
    }

    protected function getHumanReadableValue(FormInterface $form): string|TranslatableInterface|null
    {
        return $form->getData()?->getName();
    }
}
