<?php

namespace AppBundle\Repository;

use Doctrine\ORM\Query;

/**
 * EstablishmentRepository
 *
 * @author Bastien Gatellier <contact@bgatellier.fr>
 */
abstract class EstablishmentRepository extends BaseRepository
{
    /**
     * List establishment that are for end-users only, ordered by name.
     * @param bool $authorizedOnly Indicates if only the establishment that have been marked as 'available for users' are retrieved
     * @param bool $returnQueryBuilder Indicates if the method should return the query builder or the list of results
     * @return array|\Doctrine\ORM\QueryBuilder
     */
    public function findForUsers(bool $authorizedOnly = true, bool $returnQueryBuilder = false)
    {
        $qb = $this->createQueryBuilder('e')
            ->orderBy('e.name', 'ASC');

        if ($authorizedOnly) {
            $qb
                ->where('e.availableForUsers = :e_available_for_users')
                ->setParameter('e_available_for_users', $authorizedOnly);

        }

        return $returnQueryBuilder ? $qb : $qb->getQuery()->getResult(Query::HYDRATE_ARRAY);
    }

    /**
     * Get List with only id and name by a set of criteria.
     *
     * Optionally sorting and limiting details can be passed. An implementation may throw
     * an UnexpectedValueException if certain values of the sorting or limiting details are
     * not supported.
     *
     * @param array      $criteria // Not used
     * @param array|null $orderBy
     * @param int|null   $limit
     * @param int|null   $offset
     *
     * @return array The objects.
     *
     * @throws \UnexpectedValueException
     */
    public function findSimpleListBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) 
    {
        $items_list = array();

        //$tmp = $this->findBy($criteria, $orderBy, $limit, $offset);
        //Custom request :

        $qb = $this->createQueryBuilder('e');

        $qb->where($qb->expr()->isNotNull('e.logoPath'))
        ->orderBy('e.name', 'ASC')
        ->setMaxResults($limit)
        ->setFirstResult($offset);

        foreach ($orderBy as $column => $dir) {
            $qb->addOrderBy($column, $dir);
        }

        $tmp = $qb->getQuery()->getResult(Query::HYDRATE_OBJECT);
        
        foreach($tmp as $item) {
            $items_list[$item->getId()] = $item->getName();
        }

        return $items_list;
    } 
}
