<?php

namespace App\Repository;

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

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

    public function deleteByPeriode($periode)
    {
        $qb = $this->createQueryBuilder('ct')
            ->delete();

        if (isset($periode['date_debut'])) {
            $qb->andWhere('ct.date_debut = :date_debut')->setParameter(':date_debut', $periode['date_debut']);
        }
        if (isset($periode['date_fin'])) {
            $qb->andWhere('ct.date_fin = :date_fin')->setParameter(':date_fin', $periode['date_fin']);
        }
        return $qb->getQuery()->getResult();
    }

    public function updateLastPeriode($periode) {
        return $this->createQueryBuilder('ct')
            ->update()
            ->set('ct.date_fin', 'null')
            ->andWhere('ct.date_fin = :date_debut')
            ->setParameter('date_debut', $periode['date_debut_1_day'])
            ->getQuery()
            ->getSingleScalarResult()
            ;
    }

    public function addDateFin($date_fin)
    {
        return $this->createQueryBuilder('ct')
            ->update()
            ->set('ct.date_fin', ':date_fin')
            ->setParameter('date_fin', $date_fin)
            ->where('ct.date_fin is null')
            ->getQuery()
            ->getSingleScalarResult()
            ;
    }

    public function majField($field, $old_value, $new_value)
    {
        return $this->createQueryBuilder('ct')
            ->update()
            ->set('ct.' . $field, ':new_value')
            ->setParameter('new_value', $new_value)
            ->where('ct.' . $field . ' = :old_value')
            ->setParameter('old_value', $old_value)
            ->getQuery()
            ->getSingleScalarResult();
    }

    public function getPrestationTarifsByType($id_type) {
        return $qb = $this->createQueryBuilder('ct')
                    ->innerJoin('ct.produit', 'p')
                    ->innerJoin('p.produit_type', 'pt')
                    ->andWhere('pt.id = :id_type')
                    ->setParameter('id_type', $id_type)
                    ->addOrderBy('ct.date_debut', 'DESC')
                    ->addOrderBy('p.designation', 'ASC')
                    ->getQuery()
                    ->getResult();
    }
}
