<?php

namespace AppBundle\Entity\Booking\Repository;

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

class AttendanceBookingRepository extends EntityRepository {

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

        $queryBuilder
            ->select('SUM(TIMESTAMPDIFF(MINUTE, o.datetimeStart, o.datetimeEnd)) AS time')
            ->leftJoin('o.access', 'access')
            ->andWhere('o.datetimeStart < :datetimeEnd')
            ->andWhere(
                $queryBuilder->expr()->orX(
                    $queryBuilder->expr()->gt('o.datetimeEnd', ':datetimeStart'),
                    $queryBuilder->expr()->isNull('o.datetimeEnd')
                ))
            ->andWhere('o.access = :access')
            ->andWhere('access.organization = :organization')
            ->setParameter('datetimeStart', $date_start)
            ->setParameter('datetimeEnd', $date_end)
            ->setParameter('access', $access)
            ->setParameter('organization', $access->getOrganization())
        ;

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