<?php

namespace AppBundle\Entity\Booking\Repository;

use AppBundle\Entity\AccessAndFunction\Access;
use Doctrine\ORM\EntityRepository;

class CourseRepository extends EntityRepository {

    /**
     * @param  $date_start
     * @param  $date_end
     * @param Access $access
     */
    public function getCourses($date_start, $date_end, Access $access) {
        $queryBuilder = $this->createQueryBuilder('o');

        $queryBuilder
            ->andWhere(
                    $queryBuilder->expr()->between('o.datetimeStart', ':dateStart', ':dateEnd')
                )
            ->andWhere('o.organization = :organization')
            ->setParameter('dateStart', $date_start)
            ->setParameter('dateEnd', $date_end)
            ->setParameter('organization', $access->getOrganization())
        ;

        $query = $queryBuilder->getQuery();
        $results = $query->getResult();

        return $results;
    }

    /**
     * @param $organization
     * @param null $year
     * @param null $idsCourses
     * @return array
     */
    public function getCoursesToDuplicate($organization, $year = null, $idsCourses = null){
        $qb = $this->createQueryBuilder('courses');

        if($year){
            $qb
                ->andWhere($qb->expr()->eq('courses.startYear', ':year'))
                ->setParameter('year', $year);
        }else{
            $qb
                ->andWhere($qb->expr()->in('courses.id', ':ids'))
                ->setParameter('ids', $idsCourses);
        }

        $qb
            ->andWhere('courses.organization = :organization')
            ->andWhere('courses.isCanceled = :canceled')
            ->leftJoin('courses.timeline', 'timeline')
            ->leftJoin('timeline.eventRecur', 'booking_recurr')
            ->setParameter('organization', $organization)
            ->setParameter('canceled', false)
            ->having('COUNT(timeline.id) = 0')
            ->having('COUNT(booking_recurr.id) = 0')
            ->groupBy('courses.id')
        ;

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