<?php

namespace App\Repository;

use App\Entity\AgentGps;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\ORMException;
use Doctrine\Persistence\ManagerRegistry;

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

    /**
     * @throws ORMException
     * @throws OptimisticLockException
     */
    public function add(AgentGps $entity, bool $flush = true): void
    {
        $this->_em->persist($entity);
        if ($flush) {
            $this->_em->flush();
        }
    }

    /**
     * @throws ORMException
     * @throws OptimisticLockException
     */
    public function remove(AgentGps $entity, bool $flush = true): void
    {
        $this->_em->remove($entity);
        if ($flush) {
            $this->_em->flush();
        }
    }

    public function getCoordsGps($agent, $date)
    {
        $queryBuilder = $this->createQueryBuilder('a');

        $dateDebut = new \DateTime($date); // '2025-02-25 00:00:00'
        $dateFin = (clone $dateDebut)->modify('+1 day'); // '2025-02-26 00:00:00'

        $request = $queryBuilder
            ->where('a.utilisateur_agent = :agent')
            ->andWhere('a.date_heure >= :date_debut')
            ->andWhere('a.date_heure < :date_fin')
            ->setParameter('agent', $agent)
            ->setParameter('date_debut', $dateDebut)
            ->setParameter('date_fin', $dateFin)
            ->orderBy('a.date_heure', 'ASC')
            ->getQuery();

        return $request->getResult() ;
    }

}
