<?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 Neos\Flow\Utility\Now;
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)
 * @method Event|null findOneBy(array $criteria, array $orderBy = null)
 */
class EventRepository extends AbstractRepository
{
    use TranslatableRepository {
        createQueryBuilder as private createTranslatableQueryBuilder;
    }

    protected $alias = 'event';

    public function createQueryBuilder($alias, $indexBy = null, bool $withHidden = false): QueryBuilder
    {
        $query = $this->createTranslatableQueryBuilder($alias, $indexBy);

        if (!$withHidden) {
            $query->addFixedExpression(
                $query->expr()->eq(sprintf('%s.hidden', $alias), 'false')
            );
        }

        return $query;
    }

    /**
     * Specific method for fetching all data for a data source
     * (e.g. multi-select in a neos node type property) in the
     * most performant way.
     *
     * @param \DateTimeInterface|null $now
     * @return array
     */
    public function findAllForDataSource(\DateTimeInterface $now = null): array
    {
        $now = $now ?? new Now();
        $query = $this->createQueryBuilder('event');

        $query->select(
            [
                'event.title AS event_title',
                'event.Persistence_Object_Identifier AS event_identifier',
                'event.originalId AS event_originalId',
                'event.beginsAt AS event_start',
                'event.endsAt AS event_end',
            ]
        )->join('event.eventDates', 'eventDate');

        $query->andWhere(
            $query->expr()->orX(
                $query->expr()->gte('DATE(eventDate.beginsAt)', ':date'),
                $query->expr()->gte('DATE(eventDate.endsAt)', ':date')
            )
        );
        $query->setParameter('date', $now);
        $query->addOrderBy('eventDate.beginsAt', 'asc')->groupBy('event_identifier');

        $events = $query->getQuery()->getScalarResult();
        $data = [];
        foreach ($events as $event) {
            $dateFrom = new \DateTime($event['event_start']);
            $dateTo = new \DateTime($event['event_end']);
            $data[] = [
                'label' => $event['event_title'],
                'value' => $event['event_identifier'],
                'group' => $dateFrom->format('Y-m-d') .
                    ' - ' . $dateTo->format('Y-m-d'),
            ];
        }

        return $data;
    }

    /**
     * @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->andWhere('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->andWhere('DATE(eventDate.beginsAt) >= :date')
                ->setParameter('date', $fromDate->format('Y-m-d'));
        } elseif ($toDate !== null) {
            $query->andWhere('(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;
    }

    protected function queryBuilderForOriginalIdQuery(string $alias): QueryBuilder
    {
        return $this->createQueryBuilder($alias, null, true);
    }
}
