<?php

namespace Lc\SovBundle\Field\Filter;


use EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto;
use Lc\SovBundle\Repository\RepositoryQueryInterface;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * @author La clic ! <contact@laclic.fr>
 */
class DateFilter
{
    use FilterTrait;

    public function buildProperty(FormBuilderInterface $builder, FieldDto $fieldDto, $options = array())
    {
        $builder->add(
            $builder->create(
                str_replace('.', '_', $fieldDto->getProperty()),
                FormType::class,
                array('inherit_data' => true)
            )
                ->add(
                    'dateStart',
                    DateType::class,
                    array(
                        'widget' => 'single_text',
                        'required' => false,
                    )
                )
                ->add(
                    'dateEnd',
                    DateType::class,
                    array(
                        'widget' => 'single_text',
                        'required' => false,

                    )
                )
        );
    }

    public function applyFilter(RepositoryQueryInterface $repositoryQuery, FieldDto $fieldDto, \DateTime $dateStart = null, \DateTime $dateEnd = null)
    {
        $fieldProperty = $this->getFieldProperty($fieldDto);
        if ($dateStart) {
            $repositoryQuery->andWhere(
                '.' . $fieldProperty . ' >= :dateStart'
            )->setParameter('dateStart', $dateStart);
        }
        if ($dateEnd) {
            $dateEnd->setTime(23, 59, 59);
            $repositoryQuery->andWhere(
                '.' . $fieldProperty . ' <= :dateEnd'
            )->setParameter('dateEnd', $dateEnd);
        }
    }
}
