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

use Doctrine\ORM\QueryBuilder;
use Ferienpass\AdminBundle\Form\Filter\AbstractFilterType;
use Ferienpass\AdminBundle\Form\Filter\AsSubFilter;
use Ferienpass\AdminBundle\Form\Filter\Ttl;
use Ferienpass\CoreBundle\Entity\OfferDate;
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: 'hidePast', section: 'toggles', priority: 84, views: ['admin_offers_index'], ttl: Ttl::EndOfDay)]
class HidePastFilter extends AbstractFilterType
{
    public function getParent(): string
    {
        return CheckboxType::class;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'label' => 'Vergangene ausblenden',
        ]);
    }

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

        if (!$form->getData()) {
            return;
        }

        $offerAlias = $qb->getRootAliases()[0] ?? 'o';

        $qb->andWhere(
            $qb->expr()->orX(
                \sprintf('%s.dates IS EMPTY', $offerAlias),
                $qb->expr()->exists(
                    \sprintf(
                        'SELECT 1 FROM %s d_hp WHERE d_hp.offer = %s AND d_hp.end >= CURRENT_TIMESTAMP()',
                        OfferDate::class,
                        $offerAlias,
                    ),
                ),
            ),
        );
    }

    protected function getHumanReadableValue(FormInterface $form): string|TranslatableInterface|null
    {
        return $form->getData() ? 'Zukünftige' : 'vergangene anzeigen';
    }
}
