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

use Doctrine\ORM\QueryBuilder;
use Ferienpass\AdminBundle\Form\Filter\AbstractFilterType;
use Ferienpass\AdminBundle\Form\Filter\AsSubFilter;
use Ferienpass\CoreBundle\Entity\BookEntry;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\Translation\TranslatableInterface;

#[AsSubFilter(key: 'with_balance', section: 'toggles', views: ['admin_payments_debtors'])]
class WithBalanceFilter extends AbstractFilterType
{
    public function getParent(): string
    {
        return CheckboxType::class;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'label' => 'payments.filter.withBalance',
        ]);
    }

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

        $qb
            ->andWhere('(SELECT SUM(be.value) FROM '.BookEntry::class.' be WHERE be.debtor = i AND be.type = :be_type_manual) <> 0')
            ->setParameter('be_type_manual', 'manual')
        ;
    }

    protected function getHumanReadableValue(FormInterface $form): string|TranslatableInterface|null
    {
        return $form->getData() ? 'payments.filter.withBalance' : null;
    }
}
