<?php

namespace OfficeBrain\CustomBundle\ServiceGroupBundle\Entity;

/**
 * RedeemCouponRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class RedeemCouponRepository extends \Doctrine\ORM\EntityRepository
{
	protected $projectSetting;
	protected $instanceId;
	protected $cultureId;
	protected $cultureCode;
	protected $userId;
	/**
	 * @author Employee Id: 5497
	 * Description : Set project settings
	 */
	public function setProjectSetting($projetSetting)
	{
		$this->projectSetting = $projetSetting;
		$this->prepareProjectSettingData();
		$this->currentDate = new \DateTime();
	}
	
	/**
	 * @author Employee Id: 5497
	 * Description : Get project settings
	 */
	public function getProjectSetting()
	{
		return $this->projetSetting;
	}
	
	/**
	 * @author Employee Id: 5497
	 * Description : Prepare data from project setting
	 */
	public function prepareProjectSettingData()
	{
		$this->instanceId = $this->projectSetting['instance_id'];
		$this->cultureId = $this->projectSetting['culture_id'];
		$this->cultureCode = $this->projectSetting['culture_code'];
		$this->userId = $this->projectSetting['user_id'];
	}

	public function findByPreAddToCartId($preCartId) {
		if ($userId ==0) {
			$userId = $this->userId;
		}
	
		return $this->createQueryBuilder('rc')
					->select('rc')
					->where('rc.preAddToCartId = :preCartId')
					->andWhere('rc.userId = :userId')
					->setParameter(':preCartId', $preCartId)
					->setParameter(':userId', $userId)
					->getQuery()
					->getOneOrNullResult();
	}
	
	public function findByCouponId($couponId) {
		if ($userId ==0) {
			$userId = $this->userId;
		}
	
		return $this->createQueryBuilder('rc')
		->select('rc')
		->where('rc.couponId = :couponId AND rc.orderId IS NULL')
		->andWhere('rc.userId = :userId')
		->setParameter(':couponId', $couponId)
		->setParameter(':userId', $userId)
		->getQuery()
		->getResult();
	}
	
	public function getCouponCodeByOrder($orderId){
		if ($userId ==0) {
			$userId = $this->userId;
		}
		
		return $this->createQueryBuilder('rc')
		->select('rc')
		->where('rc.orderId = :orderId')
		->andWhere('rc.userId = :userId')
		->setParameter(':orderId', $orderId)
		->setParameter(':userId', $userId)
		->getQuery()
		->getResult();
	}
	
	public function set($entity)
	{
		return $this->commit($entity);
	}
	
	private function commit($entity)
	{
		$this->_em->persist($entity);
		$this->_em->flush();
	
		return $entity;
	}
	
	public function remove($entity)
	{
		$this->_em->remove($entity);
		$this->_em->flush();
		return true;
	}
}
