<?php

namespace App\Appointment\Repository;

use App\Appointment\Entity\Holiday;
use App\Doctor\Entity\Doctor;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

class HolidayRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Holiday::class);
    }

    public function findByUuid(string $uuid): ?Holiday
    {
        return $this->findOneBy(['uuid' => $uuid]);
    }

    /** @return Holiday[] */
    public function findAllByDoctor(Doctor $doctor): array
    {
        return $this->createQueryBuilder('h')
            ->where('h.doctor = :doctor')
            ->setParameter('doctor', $doctor)
            ->orderBy('h.startDate', 'DESC')
            ->getQuery()
            ->getResult();
    }

    /** @return Holiday[] */
    public function findActiveByDoctor(Doctor $doctor, int $from, int $to): array
    {
        return $this->createQueryBuilder('h')
            ->where('h.doctor = :doctor')
            ->andWhere('h.active = true')
            ->andWhere('h.startDate <= :to')
            ->andWhere('h.endDate >= :from')
            ->setParameter('doctor', $doctor)
            ->setParameter('from', $from)
            ->setParameter('to', $to)
            ->getQuery()
            ->getResult();
    }

    public function save(Holiday $entity, bool $flush = true): void
    {
        $this->getEntityManager()->persist($entity);
        if ($flush) $this->getEntityManager()->flush();
    }

    public function remove(Holiday $entity, bool $flush = true): void
    {
        $this->getEntityManager()->remove($entity);
        if ($flush) $this->getEntityManager()->flush();
    }
}
