<?php

namespace Ig\IgReservations\Domain\Repository;

use TYPO3\CMS\Extbase\Persistence\Repository;
use TYPO3\CMS\Extbase\Persistence\QueryInterface;
use PDO;
use DateTime;
use Doctrine\DBAL\ParameterType;
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 Repository
{
    /**
     * @var array
     */
    protected $defaultOrderings = [
        'sorting' => QueryInterface::ORDER_ASCENDING,
    ];

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

    
    public function injectDataMapper(DataMapper $dataMapper): void
    {
        $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, ParameterType::INTEGER))
            );
        }

        $now = new DateTime();

        // Only get locations that have an active event bound to them
        $queryBuilder->andWhere(
            $queryBuilder->expr()->or($queryBuilder->expr()->and($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->executeQuery()
->fetchAllAssociative();
        $reservationTypes = [];
        if (!empty($res)) {
            $reservationTypes = $this->dataMapper->map(ReservationType::class, $res);
        }

        return $reservationTypes;
    }
}
