<?php

namespace App\Appointment\Repository;

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

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

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

    /**
     * استثناهای یک context. برخلاف تعطیلی، هیچ اجتماعی در کار نیست: استثنای کلینیک
     * فقط در همان کلینیک دیده می‌شود و استثنای شخصی فقط در مطب شخصی.
     *
     * @return DateOverride[]
     */
    public function findByDoctorAndClinic(Doctor $doctor, ?Clinic $clinic): array
    {
        $qb = $this->createQueryBuilder('o')
            ->where('o.doctor = :doctor')
            ->setParameter('doctor', $doctor)
            ->orderBy('o.date', 'ASC');

        if ($clinic === null) {
            $qb->andWhere('o.clinic IS NULL');
        } else {
            $qb->andWhere('o.clinic = :clinic')->setParameter('clinic', $clinic);
        }

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

    /** @return DateOverride[] */
    public function findByDoctor(Doctor $doctor): array
    {
        return $this->findByDoctorAndClinic($doctor, null);
    }

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

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