<?php

namespace OfficeBrain\Bundle\CouponBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * @author OfficeBrain 4835 <info@officebrain.com>
 * CouponProductMappingRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class CouponProductMappingRepository extends EntityRepository
{
    public function setData($coupon)
    {
        return $this->commit($coupon);
    }

    public function find($id, $lockMode = NULL, $lockVersion = NULL)
    {
        return $this->createQueryBuilder('s')
                        ->select('s')
                        ->where('s.id = :id')
                        ->setParameter(':id', $id)
                        ->getQuery()
                        ->getSingleResult();
    }

    public function getproductFromCoupon($id, $isAllowed = null)
    {
        $query = $this->createQueryBuilder('c')->select('c')
                ->where('c.couponId =:couponId')
                ->setParameter('couponId', $id);
        if ($isAllowed != null) {
            $query->andWhere('c.isAllowed =:isAllowed')
                    ->setParameter('isAllowed', $isAllowed);
        }
        $result = $query->getQuery()->getResult();

        return $result;
    }

    public function removeData($productidArray)
    {
        $qb = $this->_em->createQueryBuilder();
        $queryBuilder = $qb
                ->delete('OfficeBrainCouponBundle:CouponProductMapping', 'a')
                ->add('where', $qb->expr()->in('a.id', '?1'))
                ->setParameter(1, $productidArray);

        return $deletedCount = $queryBuilder->getQuery()->execute();
    }

    /**
     * Commit entity.
     */
    private function commit($entity)
    {
        $this->_em->persist($entity);
        $this->_em->flush();

        return $entity->getId();
    }
}
