<?php

namespace Ig\IgReservations\Domain\Repository;

use Ig\IgReservations\Domain\Model\ReservationType;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper;

/**
 * The repository for BookingType
 */
class ReservationTypeRepository extends \TYPO3\CMS\Extbase\Persistence\Repository
{
    /**
     * @var array
     */
    protected $defaultOrderings = [
        'sorting' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING,
    ];

    /**
     * DataMapper
     *
     * @var DataMapper
     */
    protected $dataMapper = null;

    
    public function injectDataMapper(DataMapper $dataMapper)
    {
        $this->dataMapper = $dataMapper;
    }

    /**
     * Find locations based on booking type and return only locations with events
     * @param  integer $bookingTypeUid
     * @return array
     */
    public function findByBookingType($bookingTypeUid = 0)
    {
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable(
            'tx_igreservations_domain_model_reservationtype'
        );
        $queryBuilder
            ->select('t.*')
            ->from('tx_igreservations_domain_model_reservationtype', 't')
            ->leftJoin('t', 'tx_igreservations_event_reservationtype_mm', 'mm', 'mm.uid_foreign = t.uid')
            ->leftJoin('mm', 'tx_igreservations_domain_model_event', 'e', 'mm.uid_local = e.uid');

        if ($bookingTypeUid) {
            $queryBuilder->andWhere(
                $queryBuilder->expr()
->eq('e.booking_type', $queryBuilder->createNamedParameter($bookingTypeUid, \PDO::PARAM_INT))
            );
        }

        $now = new \DateTime();

        // Only get locations that have an active event bound to them
        $queryBuilder->andWhere(
            $queryBuilder->expr()
->orX(
    $queryBuilder->expr()
->andX(
    $queryBuilder->expr()
->eq('e.start_date', $queryBuilder->createNamedParameter($now->format('Y-m-d'))),
    $queryBuilder->expr()
->gte('e.start_time', $queryBuilder->createNamedParameter($now->format('H:i:s'))),
),
    $queryBuilder->expr()
->gt('e.start_date', $queryBuilder->createNamedParameter($now->format('Y-m-d'))),
)
        );

        //$queryBuilder->andWhere('e.uid NOT IN (SELECT event FROM tx_igreservations_domain_model_reservation AS r WHERE hidden = 0)');

        $queryBuilder->orderBy('t.name');
        $queryBuilder->groupBy('t.uid');
        //echo $queryBuilder->getSQL();die();

        $res = $queryBuilder->execute()
->fetchAll();
        $reservationTypes = [];
        if (!empty($res)) {
            $reservationTypes = $this->dataMapper->map(ReservationType::class, $res);
        }

        return $reservationTypes;
    }
}
