<?php

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

/**
 * Description of OrganizationFunctionRepository
 *
 */
class OrganizationFunctionRepository extends EntityRepository
{
    /**
     * @param Access $access
     * @return array
     */
    public function getArchivedOrganizationFunction($enDate, $organizationId)
    {
        $filter = $this->_em->getFilters()->enable('activity_year');
        $filter->setParameter('disabledFilter', 1);
        $qb = $this->createQueryBuilder('organization_function');

        $qb
            ->innerJoin('organization_function.access', 'access')
            ->innerJoin('access.organization', 'organization')
            ->andWhere('organization_function.endDate = :enDate')
            ->andWhere('organization.id = :id')
            ->setParameter('id', $organizationId)
            ->setParameter('enDate', $enDate)
        ;

        $filter->setParameter('disabledFilter', 0);
        return $qb->getQuery()->getResult();
    }

    public function getAllOrganizationFunctionByAccessAndDates(Access $access,$startDate,$endDate)
    {
        $filter = $this->_em->getFilters()->enable('activity_year');
        $filter->setParameter('disabledFilter', 1);
        $qb = $this->createQueryBuilder('organization_function');

        $qb
            ->innerJoin('organization_function.access', 'access')
            ->andWhere('access.id = :access')
            ->andWhere('(organization_function.startDate <= :startDate and (organization_function.endDate is null or organization_function.endDate > :startDate)) or (organization_function.startDate > :startDate and organization_function.startDate < :endDate)')
            ->setParameter('access', $access)
            ->setParameter('startDate', $startDate)
            ->setParameter('endDate', $endDate)
        ;

        $filter->setParameter('disabledFilter', 0);
        return $qb->getQuery()->getResult();
    }
}
