<?php

namespace Club\ShopBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * OrderRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class OrderRepository extends EntityRepository
{
  public function getCount($filter = array())
  {
    $qb = $this->getQueryBuilder($filter);

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

  public function getWithPagination($filter = array(), $order_by = array(), $offset = 0, $limit = 0)
  {
    $qb = $this->getQueryBuilder($filter);

    $qb->leftJoin('o.order_status','os')
      ->add('orderBy', 'os.priority, o.id DESC');

    if ((isset($offset)) && (isset($limit))) {
      if ($limit > 0) {
        $qb->setFirstResult($offset);
        $qb->setMaxResults($limit);
      }
    }

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

  private function getQueryBuilder($filter = array())
  {
    $qb = $this->createQueryBuilder('o')
      ->select('o, u, p')
      ->join('o.user', 'u')
      ->join('u.profile', 'p');

    if (isset($filter['order_number'])) {
      $qb = $this->filterOrderNumber($qb,$filter['order_number']);
    }

    return $qb;
  }

  private function filterOrderNumber($qb, $value)
  {
    $qb->andWhere('o.id = :order_number');
    $qb->setParameter('order_number',$value);

    return $qb;
  }

  public function getOpenOrders($limit=10, \Club\UserBundle\Entity\User $user=null)
  {
    $qb = $this->getQueryBuilder()
      ->where('o.paid = false OR o.delivered = false')
      ->andWhere('o.cancelled = false')
      ->setMaxResults($limit)
      ->orderBy('o.updated_at', 'DESC');

    if (isset($user)) {
      $qb
        ->andWhere('o.user = :user')
        ->setParameter('user', $user->getId());
    }

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