<?php

namespace App\Repository;

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

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

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

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

    public function getPlanificationByAgent(Utilisateur $utilisateur, $tablette = false)
    {
        $queryBuilder = $this->createQueryBuilder('p');
        $expr = $queryBuilder->expr();
        $dateJour = new \DateTime();
        $dateJour = $dateJour->format('d/m/Y');

        $dateFin = '31/12/2025';

        if ($tablette) {
            // Pour les tablettes : J et prochain jour avec des données
            // D'abord, récupérer le prochain jour avec des données
            $subQuery = $this->createQueryBuilder('p2')
                ->select('MIN(p2.date)')
                ->where('p2.utilisateur_agent = :ids')
                ->andWhere('p2.date > :dateJour')
                ->andWhere('p2.statut IS NOT NULL')
                ->setParameter('ids', $utilisateur->getId())
                ->setParameter('dateJour', $dateJour)
                ->getQuery()
                ->getSingleScalarResult();

            
            if ($subQuery) {
                $prochainJourAvecDonnees = new \DateTime($subQuery);
                $dateFin = $prochainJourAvecDonnees->format('d/m/Y');
            } else {
                // Si pas de prochain jour avec données, on prend juste aujourd'hui
                $dateFin = $dateJour;
            }

        }

        $request = $queryBuilder
            ->where($expr->in('p.utilisateur_agent', ':ids'))
            ->andWhere('p.date >= :dateJour')
            ->andWhere('p.date <= :dateFin')
            ->orderBy('p.date', 'ASC')
            ->setParameter('ids', $utilisateur->getId())
            ->setParameter('dateJour', $dateJour)
            ->setParameter('dateFin', $dateFin)
            ->getQuery();
        
        return $request->getResult();
    }


}
