<?php

namespace App\Repository;

use App\Entity\RdvTempo;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @extends ServiceEntityRepository<RdvTempo>
 *
 * @method RdvTempo|null find($id, $lockMode = null, $lockVersion = null)
 * @method RdvTempo|null findOneBy(array $criteria, array $orderBy = null)
 * @method RdvTempo[]    findAll()
 * @method RdvTempo[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class RdvTempoRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, RdvTempo::class);
    }


    public function RdvEncoursAdd($user, $serviceRdvReservation)
    {
        $this->RdvEncoursPasser();

        $rdvTempo = new RdvTempo();
        $rdvTempo->setClient($user);
        $rdvTempo->setDateAdd(new \DateTime());
        $rdvTempo->setServiceRdvReservation($serviceRdvReservation);

        $this->_em->persist($rdvTempo);
        $this->_em->flush();

        return $rdvTempo;
    }

    public function RdvEncoursListId()
    {
        $this->RdvEncoursPasser();

        $ListId = [];
        foreach($this->findAll() as $value){
            $ListId[] = $value->getServiceRdvReservation()->getId();
        }
        return $ListId;
    }


    public function RdvEncoursPasser()
    {
        $now = new \DateTime();
        
        foreach($this->findAll() as $RdvEncour){
            $dateAdd = clone $RdvEncour->getDateAdd();
            $dateAdd->modify("+15 minutes");
            if($now > $dateAdd){
                $this->_em->remove($RdvEncour);
            }
        }

        $this->_em->flush();
    }


    public function RdvEncoursDelete($serviceRdvReservation)
    {
        $rdvTempo = $this->findOneByBy(['serviceRdvReservation'=>$serviceRdvReservation]);
        
        if($rdvTempo){
            $this->_em->remove($rdvTempo);
            $this->_em->flush();
            return true;
        }
        
        return false;
        
    }

}