<?php

namespace App\Repository;

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

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

    // /**
    //  * @return ProduitStockSite[] Returns an array of ProduitStockSite objects
    //  */
    /*
    public function findByExampleField($value)
    {
        return $this->createQueryBuilder('p')
            ->andWhere('p.exampleField = :val')
            ->setParameter('val', $value)
            ->orderBy('p.id', 'ASC')
            ->setMaxResults(10)
            ->getQuery()
            ->getResult()
        ;
    }
    */

    /*
    public function findOneBySomeField($value): ?ProduitStockSite
    {
        return $this->createQueryBuilder('p')
            ->andWhere('p.exampleField = :val')
            ->setParameter('val', $value)
            ->getQuery()
            ->getOneOrNullResult()
        ;
    }
    */
    public function getEquipementMeaux($skip = null, $take = null, $filters = null, $sort = null) {
        $qb = $this->createQueryBuilder('pt')
            ->select('s.id,s.nom as s_nom,p.code as p_code, p.designation as p_designation, p.gtin as p_gtin, fa.libelle as fa_libelle,p.gu_etendue as p_gu_etendue,p.prix_ht as p_prix_ht,  CASE WHEN pt.visible_tablette =true then \'oui\' else \'non\' END as pt_visible_tablette')
            ->innerJoin('pt.site', 's')
            ->innerJoin('pt.produit', 'p')
            ->innerJoin('p.famille_agi', 'fa')->andWhere("fa.libelle <> 'T35'")
        ;

        if ($skip !== null && $take !== null) $qb->setFirstResult( $skip )->setMaxResults( $take );
        if ($filters['AND']) {
            foreach ($filters['AND'] as $filter) {
                $qb->andWhere($filter['filtersVariables']);
                foreach ($filter['parameters'] as $parameter) {
                    $qb->setParameter(':' . $parameter['key'],$parameter['value']);
                }
            }
        }
        if ($sort) {
            $pos = stripos($sort[0]['selector'], '_');
            $sortBy = substr_replace($sort[0]['selector'],'.',$pos,1);
            $order = ($sort[0]['desc']) ? " DESC" : " ASC";
            $qb->orderBy($sortBy, $order);
        } else $qb->orderBy('p.designation');

        $query = $qb->getQuery();
        return $query->getArrayResult();
    }

    public function countEquipementsMeaux($filters = null) {
        $qb = $this->createQueryBuilder('pt')
            ->select('count(pt.site)')
            ->innerJoin('pt.site', 's')
            ->innerJoin('pt.produit', 'p')
            ->innerJoin('p.famille_agi', 'fa')->andWhere("fa.libelle <> 'T35'");

        if ($filters['AND']) {
            foreach ($filters['AND'] as $filter) {
                $qb->andWhere($filter['filtersVariables']);
                foreach ($filter['parameters'] as $parameter) {
                    $qb->setParameter(':' . $parameter['key'],$parameter['value']);
                }
            }
        }
        return $qb->getQuery()
            ->getSingleScalarResult();
        ;
    }

    public function getConsommablesMeaux($skip = null, $take = null, $filters = null,  $sort = null) {
        $qb = $this->createQueryBuilder('pt')
            ->select("CONCAT(p.id,'-', s.id) as id, s.nom as s_nom,p.code as p_code, p.designation as p_designation, p.gtin as p_gtin, fa.libelle as fa_libelle,p.prix_ht as p_prix_ht,  CASE WHEN pt.gere_en_stock =true then 'oui' else 'non' END as pt_gere_en_stock, string_agg(cast(pp.nom as varchar), ',') as pp_photo")
            ->innerJoin('pt.site', 's')
            ->innerJoin('pt.produit', 'p')
            ->leftJoin('p.produitPhotos', 'pp')
            ->innerJoin('p.famille_agi', 'fa')->andWhere("fa.libelle = 'T35'")
            ->groupBy('id, s_nom,p_code, p_designation, p_gtin,fa_libelle, p_prix_ht,  pt_gere_en_stock', 'pt.gere_en_stock', 'pp.photo')
        ;

        if ($skip !== null && $take !== null) $qb->setFirstResult( $skip )->setMaxResults( $take );
        if ($filters['AND']) {
            foreach ($filters['AND'] as $filter) {
                $qb->andWhere($filter['filtersVariables']);
                foreach ($filter['parameters'] as $parameter) {
                    $qb->setParameter(':' . $parameter['key'],$parameter['value']);
                }
            }
        }

        if ($sort) {
            $pos = stripos($sort[0]['selector'], '_');
            $sortBy = substr_replace($sort[0]['selector'],'.',$pos,1);
            $order = ($sort[0]['desc']) ? " DESC" : " ASC";
            $qb->orderBy($sortBy, $order);
        } else $qb->orderBy('p.designation');

        $query = $qb->getQuery();
        return $query->getArrayResult();
    }

    public function countConsommablesMeaux($filters = null) {
        $qb = $this->createQueryBuilder('pt')
            ->select('count(pt.site)')
            ->innerJoin('pt.site', 's')
            ->innerJoin('pt.produit', 'p')
            ->innerJoin('p.famille_agi', 'fa')->andWhere("fa.libelle = 'T35'");

        if ($filters['AND']) {
            foreach ($filters['AND'] as $filter) {
                $qb->andWhere($filter['filtersVariables']);
                foreach ($filter['parameters'] as $parameter) {
                    $qb->setParameter(':' . $parameter['key'],$parameter['value']);
                }
            }
        }
        return $qb->getQuery()
            ->getSingleScalarResult();
        ;
    }
}
