<?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\QueryBuilder;
use Ferienpass\AdminBundle\Form\Filter\AbstractFilterType;
use Ferienpass\AdminBundle\Form\Filter\AsSubFilter;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\Translation\TranslatableInterface;

/**
 * Lower bound (inclusive) on a payment's creation date. Combined with
 * {@see DateUntilFilter} to scope the receipts list to a date range — e.g.
 * both set to today for a daily cash report.
 */
#[AsSubFilter(key: 'from', section: 'date', priority: 70, views: ['admin_payments_receipts'])]
class DateFromFilter extends AbstractFilterType
{
    public function getParent(): string
    {
        return DateType::class;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'widget' => 'single_text',
            'input' => 'datetime_immutable',
            'required' => false,
        ]);
    }

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

        $value = $form->getData();
        if (!$value instanceof \DateTimeInterface) {
            return;
        }

        $qb
            ->andWhere('i.createdAt >= :q_from')
            ->setParameter('q_from', \DateTimeImmutable::createFromInterface($value)->setTime(0, 0, 0))
        ;
    }

    protected function getHumanReadableValue(FormInterface $form): string|TranslatableInterface|null
    {
        $value = $form->getData();

        return $value instanceof \DateTimeInterface ? $value->format('d.m.Y') : null;
    }
}
