<?php

namespace App\Repository;

use App\Entity\UserTrip;
use App\Entity\Trip;
use App\Entity\User;
use DateTimeImmutable;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    public function save(UserTrip $userTrip, bool $flush = false): void
    {
        $this->getEntityManager()->persist($userTrip);

        if ($flush) {
            $this->getEntityManager()->flush();
        }
    }

    public function remove(UserTrip $userTrip, bool $flush = false): void
    {
        $this->getEntityManager()->remove($userTrip);

        if ($flush) {
            $this->getEntityManager()->flush();
        }
    }

    /**
     * @return UserTrip[]
     */
    public function findByTrip(Trip $trip): array
    {
        return $this->createQueryBuilder('ut')
            ->andWhere('ut.trip = :trip')
            ->setParameter('trip', $trip)
            ->orderBy('ut.startDate', 'ASC')
            ->getQuery()
            ->getResult();
    }

    /**
     * @return UserTrip[]
     */
    public function findByUser(User $user): array
    {
        return $this->createQueryBuilder('ut')
            ->andWhere('ut.user = :user')
            ->setParameter('user', $user)
            ->orderBy('ut.startDate', 'DESC')
            ->getQuery()
            ->getResult();
    }

    /**
     * @return UserTrip[]
     */
    public function findByDateRange(DateTimeImmutable $start, DateTimeImmutable $end): array
    {
        return $this->createQueryBuilder('ut')
            ->andWhere('ut.startDate >= :start')
            ->andWhere('ut.endDate <= :end')
            ->setParameter('start', $start)
            ->setParameter('end', $end)
            ->orderBy('ut.startDate', 'ASC')
            ->getQuery()
            ->getResult();
    }
}