<?php

namespace Club\BookingBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * IntervalRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class IntervalRepository extends EntityRepository
{
  public function findValidByField(\Club\BookingBundle\Entity\Field $field, $day=null)
  {
    $qb = $this->_em->createQueryBuilder()
      ->select('i')
      ->from('ClubBookingBundle:Interval', 'i')
      ->where('i.field = :field_id')
      ->andWhere('i.valid_from < :date')
      ->andWhere('(i.valid_to >= :date OR i.valid_to IS NULL)')
      ->setParameter('field_id', $field->getId())
      ->setParameter('date', new \DateTime());

    if ($day != null)
      $qb
        ->andWhere('i.day = :day')
        ->setParameter('day', $day);

    return $qb
      ->getQuery()
      ->getResult();
  }

  public function getAll(\DateTime $start, \DateTime $end, \Club\BookingBundle\Entity\Field $field)
  {
    return $this->_em->createQueryBuilder()
      ->select('i')
      ->from('ClubBookingBundle:Interval', 'i')
      ->where('((i.start_time <= :start and i.stop_time > :start) or (i.start_time >= :start and i.start_time < :stop))')
      ->andWhere('i.field = :field')
      ->andWhere('i.day = :day')
      ->setParameter('start', $start->format('H:i:s'))
      ->setParameter('stop', $end->format('H:i:s'))
      ->setParameter('field', $field->getId())
      ->setParameter('day', $start->format('N'))
      ->getQuery()
      ->getResult();
  }
}
