<?php

namespace Actigraph\ActipageBaseBundle\Repository;

use Actigraph\ActipageBaseBundle\Entity\Formule;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @method Formule|null find($id, $lockMode = null, $lockVersion = null)
 * @method Formule|null findOneBy(array $criteria, array $orderBy = null)
 * @method Formule[]    findAll()
 * @method Formule[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class FormuleRepository extends EntityRepository
{
    public function add(Formule $entity, bool $flush = false): void
    {
        $this->getEntityManager()->persist($entity);

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

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

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

    /**
     * @return Formule[]|null
     */
    public function getFormules($name, $pref)
    {
        $qb = $this->createQueryBuilder('f')
            ->select('f, i, p')
            ->leftJoin('f.items', 'i')
            ->leftJoin('i.profile', 'p')
            ->andWhere('p.id = :name')
            ->setParameter('name', $name);
        if  ($pref == 'Régulier') {
            $qb->andWhere('i.isRegulier = TRUE');
        } elseif ($pref == 'Occasionnel') {
            $qb->andWhere('i.isOccasionnel = TRUE');
        }

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

    /**
     * @return Formule[]|null
     */
    public function getFormulesOccesionnel()
    {
        $qb = $this->createQueryBuilder('f')
            ->select('f, i');
        $qb = $qb->leftJoin('f.items', 'i')
            ->andWhere('i.isOccasionnel = TRUE');

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

    /**
     * @return Formule[]|null
     */
    public function getFormulesRegulier()
    {
        $qb = $this->createQueryBuilder('f')
            ->select('f, i');
        $qb = $qb->leftJoin('f.items', 'i')
            ->andWhere('i.isRegulier = TRUE');

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