<?php
namespace Newland\Toubiz\Sync\Neos\Domain\Repository;

/*
 * This file is part of the "toubiz-sync-neos" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Doctrine\ORM\QueryBuilder;
use Neos\Flow\Annotations as Flow;
use Newland\Toubiz\Sync\Neos\Domain\Filter\EventFilter;
use Newland\Toubiz\Sync\Neos\Domain\Filter\FilterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\Event;
use Newland\Toubiz\Sync\Neos\Translation\TranslatableRepository;

/**
 * Event repository.
 *
 * @Flow\Scope("singleton")
 *
 * @method Event|null findOneByOriginalId(string $originalId)
 * @method Event|null findByIdentifier(string $identifier)
 */
class EventRepository extends AbstractRepository
{
    use TranslatableRepository;

    protected $alias = 'event';

    /**
     * @param EventFilter $filter
     * @param QueryBuilder $query
     * @return QueryBuilder
     */
    protected function applyFilter(FilterInterface $filter, QueryBuilder $query): QueryBuilder
    {
        $this->applyBasicFilter($filter, $query);
        $query->innerJoin('event.eventDates', 'eventDate');
        $fromDate = $filter->getFromDate();
        $toDate = $filter->getToDate();

        if ($fromDate !== null && $toDate !== null) {
            $query->where('DATE(eventDate.beginsAt) <= :fromDate AND (eventDate.endsAt) >= :toDate')
                ->setParameter('fromDate', $fromDate->format('Y-m-d'))
                ->setParameter('toDate', $toDate->format('Y-m-d'));
        } elseif ($fromDate !== null) {
            $query->where('DATE(eventDate.beginsAt) >= :date')
                ->setParameter('date', $fromDate->format('Y-m-d'));
        } elseif ($toDate !== null) {
            $query->where('(eventDate.endsAt) >= :date')
                ->setParameter('date', $toDate->format('Y-m-d'));
        }

        $category = $filter->getCategory();
        if ($category !== null) {
            $query->innerJoin('event.categories', 'category')
                ->andWhere('category = :category')
                ->setParameter('category', $category);
        }

        $highlight = $filter->getHighlight();
        if ($highlight !== null) {
            $query->andWhere('event.isHighlight = :highlight')
                ->setParameter('highlight', $highlight);
        }

        return $query;
    }
}
