<?php

namespace OfficeBrain\Bundle\FlyerBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Validator\Constraints\DateTime;

/**
 * FlyerRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class FlyerRepository extends EntityRepository
{
	
	protected $projectSetting;
	protected $instanceId;
	protected $instanceType;
	protected $cultureId;
	protected $cultureCode;
	protected $paginatorService;
	
	/**
	 * @author Employee Id: 4488
	 * OB eCommerce Product - getPaginatorService
	 * Function created to get Paginator Service
	 */
	public function getPaginatorService()
	{
		return $this->paginatorService;
	}
	
	/**
	 * @author Employee Id: 4488
	 * OB eCommerce Product - setPaginatorService
	 * Function created to set Paginator Service
	 */
	public function setPaginatorService($paginatorService)
	{
		$this->paginatorService = $paginatorService;
	}
	
	
	/**
	 * @author Employee Id: 4571
	 *
	 * Description : Set project setting
	 *
	 * @param : null
	 *
	 * @return null
	 *
	 * @throws : null
	 *
	 **/
	public function setProjectSetting($projetSetting)
	{
		$this->projectSetting = $projetSetting;
		$this->prepareProjectSettingData();
	}
	
	/**
	 * @author Employee Id: 4571
	 *
	 * Description : get proj setting
	 *
	 * @param : null
	 *
	 * @return project setting array
	 *
	 * @throws : null
	 *
	 **/
	public function getProjectSetting()
	{
		return $this->projetSetting;
	}
	
	/**
	 * @author Employee Id: 4571
	 *
	 * Description : Prepare Project Setting
	 *
	 * @param : null
	 *
	 * @return null
	 *
	 * @throws : null
	 *
	 **/
	public function prepareProjectSettingData()
	{
		$this->instanceId = $this->projectSetting['instance_id'];
		$this->instanceType = $this->projectSetting['instance_type'];
		$this->userId = $this->projectSetting['user_id'];
		$this->cultureId = $this->projectSetting['culture_id'];
		$this->cultureCode = $this->projectSetting['culture_code'];
	}
	
	/**
	 * @author Employee Id: 4571
	 *
	 * Description : Commit entity
	 *
	 * @param : null
	 *
	 * @return last inserted id
	 *
	 * @throws : null
	 *
	 **/
	private function findCommitIt($entity)
	{		 
		$this->_em->persist($entity);
		$this->_em->flush();
		
		return $entity->getId();
	}
	
	/**
	 * @author Employee Id: 4571
	 *
	 * Description : Find user
	 *
	 * @param 1 : int $id
	 *
	 * @return record set
	 *
	 * @throws : null
	 *
	 **/
	public function findAdminUser()
	{  		
		$query=$this->getEntityManager()->getRepository("OfficeBrainUserBundle:User")->createQueryBuilder('u'); // required .. do not remove
		$query->select('u');		
		$query->where("u.status='active'");
		
		if (isset($this->instanceId)) {
			$query->andWhere("u.instanceId=:instanceId")->setParameter('instanceId', $this->instanceId);
		}
		
		$query->andWhere("u.locked is NULL");
		$query->andWhere("u.expired is NULL");
		$query->andWhere("u.deletedAt is NULL");
		$query->andWhere('u.parent is NULL');		
		$query->andWhere("u.id=:id")->setParameter('id', $this->userId);

		return $query->getQuery()->getScalarResult();
	}
	

	
	
	/**
	 * @author Employee Id: 4571
	 *
	 * Description : Find user
	 *
	 * @param 1 : int $id
	 *
	 * @return record set
	 *
	 * @throws : null
	 *
	 **/
	
	public function getFlyerBySlug($slug,$page,$recordsPerPage,$keywords,$countryId)
	{
       	$query=$this->getEntityManager()->getRepository("OfficeBrainCustomBundleFlyerBundle:FlyerCategory")->createQueryBuilder('f'); // required .. do not remove
		$query->select('f.id');
		$query->where("f.parentId IS NOT NULL AND f.parentId !=0 AND f.slug = :slug")->setParameter('slug', $slug);
		$result = $query->getQuery()->getResult();
		
		if(empty($result[0]['id'])==false){ $flyerscategoryId=$result[0]['id']; }else{ $flyerscategoryId=0; }	

		$query=$this->getEntityManager()->getRepository("OfficeBrainFlyerBundle:Flyer")->createQueryBuilder('p'); // required .. do not remove
		$query->select('p');
		$query->addSelect('CASE WHEN p.sortPosition is Null THEN 1 ELSE 0 END AS HIDDEN sortCondition');//query for null value is displayed last
		$query->where('p.deletedAt IS NULL AND p.countryId = :countryId AND p.instanceId = :instanceId')
		->setParameter('countryId', $countryId)
		->setParameter('instanceId', $this->instanceId);
		$query->andWhere('p.flyerscategoryId = :flyerscategoryId')->setParameter('flyerscategoryId', $flyerscategoryId);
		$query->andWhere('p.publishedFlag = 1');
		$query->orderBy('p.sortPosition', 'ASC');//query for null value is displayed last
		//$query->addorderBy('p.sortPosition', 'ASC');
		if ($keywords != '')
		{
			$query->andWhere('p.title LIKE :title')->setParameter('title', '%'.$keywords.'%');
		}
		//$query->getQuery()->getSQL();die;
		return $this->paginatorService->paginate($query, $page, $recordsPerPage);
	}
	
	public function getFlyertitleBySlug($slug,$countryId)
	{
		$query=$this->getEntityManager()->getRepository("OfficeBrainCustomBundleFlyerBundle:FlyerCategory")->createQueryBuilder('f'); // required .. do not remove
		$query->select('f.title');
		$query->where("f.parentId IS NOT NULL AND f.parentId !=0 AND f.slug = :slug")->setParameter('slug', $slug);
		$result = $query->getQuery()->getResult();
		return $result[0]['title'];
	}
	
	/**
	 * @author Employee Id: 4571
	 *
	 * Description : Find Flyer by id
	 *
	 * @param 1 : int $id
	 *  
	 * @return record set
	 *
	 * @throws : null
	 *
	 **/
	public function find($id, $lockMode = NULL, $lockVersion = NULL)
	{
		$sql =  $this->createQueryBuilder('cm')
		->select('cm')
		->where('cm.id =:id AND cm.instanceId = :instanceId AND cm.instanceType = :instanceType ')
		->setParameter('instanceId', $this->instanceId)
		->setParameter('instanceType', $this->instanceType)
		->setParameter('id', $id)
		->getQuery()
		->getResult();//getOneOrNullResult();
		return $sql[0];
	}
	
	
	/**
	 * @author Employee Id: 4571
	 *
	 * Description : find Flyer by Unique Id
	 *
	 * @param 1 : int $customUniqueId
	 *  
	 * @return record set
	 *
	 * @throws : null
	 *
	 **/
	public function findByUniqueID($customUniqueId)
	{
		return $this->createQueryBuilder('fl')
		->select('fl')
		->where('fl.uniqueId =:uniqueId AND fl.instanceId = :instanceId AND fl.instanceType = :instanceType')
		->setParameter('uniqueId', $customUniqueId)		
		->setParameter('instanceId', $this->instanceId)
		->setParameter('instanceType', $this->instanceType)
		->getQuery()
		->getResult(); // OneOrNull
	}
	 
	
	/**
	 * @author Employee Id: 4571
	 *
	 * Description : Get active Flyer list
	 *
	 * @param 1 : int country id
	 * @param 2 : int languageid
	 * @param 3: string search
	 * @param 4: int adminUser
	 * 
	 * @return record set
	 *
	 * @throws : null
	 *
	 **/
	public function findActiveFlyerList($countryId, $languageId, $search=null, $adminUser,$page='',$recordPerPage='',$subid)
	{		
		$adminUser=1;
		$extrawhere="";
		if ($search) {
			$extrawhere = "AND fl.title LIKE '%$search%'";
		}
		if(!$adminUser){
			$extrawhere.=" AND fl.createdUid = $this->userId";
			 
		}
		$em = $this->getEntityManager();
// 		$count = $em
// 		->createQuery("SELECT COUNT(fl) FROM OfficeBrainFlyerBundle:Flyer AS fl WHERE fl.deletedAt IS NULL AND fl.instanceId = $this->instanceId AND fl.instanceType = '$this->instanceType' AND fl.countryId = $countryId AND fl.culture = $languageId AND fl.flyerscategoryId IN ($subids) $extrawhere")
// 		->getSingleScalarResult();
		
		$query = $em
		->createQuery("SELECT fl,CASE WHEN fl.sortPosition is Null THEN 1 ELSE 0 END AS HIDDEN sortCondition FROM OfficeBrainFlyerBundle:Flyer AS fl WHERE fl.deletedAt IS NULL AND fl.instanceId = $this->instanceId AND fl.instanceType = '$this->instanceType' AND fl.countryId = $countryId AND fl.culture = $languageId AND fl.flyerscategoryId=$subid $extrawhere ORDER By fl.sortPosition");// 		->setHint('knp_paginator.count', $count);
		return $query->getResult();
// // 		return $this->paginatorService->paginate($query, $page, $recordPerPage);

	}
	
	
	/**
	 * @author Employee Id: 4571
	 *
	 * Description : Get active Flyer list
	 *
	 * @param 1 : int country id
	 * @param 2 : int languageid
	 * @param 3: $supplier
	 *
	 * @return record set
	 *
	 * @throws : null
	 *
	 **/
	public function findFrontFlyerList($countryId, $languageId, $supplier)
	{ 
		$query = $this->createQueryBuilder('fl');
		$query->select('fl')->addSelect('CASE WHEN fl.sortPosition is Null THEN 1 ELSE 0 END AS HIDDEN sortCondition');
		$query->where('fl.instanceId = :instanceId')
		->andWhere('fl.instanceType = :instanceType')
		->andWhere('fl.countryId = :countryId')
		->andWhere('fl.culture = :culture')
		->andWhere('fl.publishedFlag = :flag')
		->andWhere('fl.validUntilDate >= :now')
		->orderBy('sortCondition', 'ASC')
		->addorderBy('fl.sortPosition', 'ASC')
		->setParameter('countryId', $countryId)
		->setParameter('culture', $languageId)
		->setParameter('instanceId', $this->instanceId)
		->setParameter('instanceType', $this->instanceType)
		->setParameter('flag', '1')				
		->setParameter('now', new \DateTime(date('Y-m-d 00:00:00')));
		
		if ($supplier > 0) {  
			$query->andWhere('fl.supplierId = :supplierId');
			$query->setParameter('supplierId', $supplier);
		}
		
		$result = $query->getQuery()->getArrayResult();
		 	
		return $result;
	}
	
	/**
	 * @author Employee Id: 4571
	 *
	 * Description : Get Flyer Html
	 *
	 * @param 1 : int country id
	 * @param 2 : int languageid
	 * @return record set
	 *
	 * @throws : null
	 *
	 **/	
    function fetchFlyerHTML($flyerUniqueId) 
    {
    	$flyerHTML = $this->findOneBy(array('uniqueId' => $flyerUniqueId));
        return $flyerHTML;
    }

    /**
     * @author Employee Id: 4571
     *
     * Description : Reset Flyer Html
     *
     * @param 1 : $request
     * 
     * @return record set
     *
     * @throws : null
     *
     **/
    function resetFlyerHTML($request) 
    {    	 
        $em = $this->getEntityManager();
        $session = $request->getSession();
        $customUniqueId = $session->get('flyerUniqueId');
          
        if( ! $customUniqueId ) {
            return true;
        } 
        
        $flyerExists = $this->findOneBy(array('uniqueId' => $customUniqueId));
        $em->remove($flyerExists);
        $em->flush();

        return true;
    }
    
    /**
     * @author Employee Id: 5430
     *
     * Description : Find user
     *
     * @param 1 : int $id
     *
     * @return record set
     *
     * @throws : null
     *
     **/
    public function getFlyerSubCategories($parentcategoryid)
    {
    	$query=$this->getEntityManager()->getRepository("OfficeBrainCustomBundleFlyerBundle:FlyerCategory")->createQueryBuilder('f'); // required .. do not remove
    	$query->select('f.id,f.title');
    	$query->where("f.parentId IS NOT NULL AND f.parentId !=0 and f.deletedAt IS NULL AND f.parentId=$parentcategoryid");
    
    	$result = $query->getQuery()->getArrayResult();
		 	
		return $result;
    }
    
    /**
     * @author Employee Id: 5430
     *
     * Description : Find user
     *
     * @param 1 : int $id
     *
     * @return record set
     *
     * @throws : null
     *
     **/
    public function getParentCategories()
    {
    	$em = $this->getEntityManager();
		$this->dbConnection = $em->getConnection();
	 	$query="SELECT t1.id,t1.title,(SELECT GROUP_CONCAT(DISTINCT t2.id) FROM tbl_flyers_category AS t2 WHERE t2.parent_id = t1.id and t2.deleted_at IS NULL) AS subids FROM tbl_flyers_category AS t1 WHERE (parent_id IS NULL OR parent_id=0) AND t1.deleted_at IS NULL";
		$statement = $this->dbConnection->prepare($query);
		$statement->execute();
		$result = $statement->fetchAll();
		//echo"<pre>";print_r($result);die();
		//$result = $query->getQuery()->getResult();
		return $result;
    }
    public function deleterecord($id)
    {
    	$entity = $this->createQueryBuilder('f')
			    		->select('f')
			    		->where('f.id = :id')
			    		->setParameter(':id', $id)
			    		->getQuery()
			    		->getOneOrNullResult();
    	
		if ($entity) {
			$entity->setDeletedAt(new \DateTime());
			$entity->setDeletedUid($this->userId);
			$this->_em->persist($entity);
			$this->_em->flush();
			
			return 1;
		} else {
			return 0;
		}	    		
    	/*$em = $this->getEntityManager();
    	$this->dbConnection = $em->getConnection();
    	$query="update tbl_flyers SET deleted_at=now(),deleted_uid=".$this->userId." WHERE id =".$id." ";
    	$statement = $this->dbConnection->prepare($query);
    	$statement->execute();
    	$result = $statement->rowCount();
    	return count($return);*/
    
    }
    public function updateFlyerPosition($query)
    {
    	$em = $this->getEntityManager();
    	$this->dbConnection = $em->getConnection();
    	$statement = $this->dbConnection->prepare($query);
    	$statement->execute();
    	$result = $statement->rowCount();
    	
    	return $result;
    
    }
    public function getFlyerPositionUpdateQuery($id,$pos_val)
    {
    	$query="update tbl_flyers SET sort_position=$pos_val WHERE id ='$id';";
    	return $query;
    
    }
    
    public function findsubCategories($subids)
    {
    	$em = $this->getEntityManager();
    	$this->dbConnection = $em->getConnection();
    	$query="SELECT t1.id,t1.title,(SELECT GROUP_CONCAT(DISTINCT t2.id) FROM tbl_flyers AS t2 WHERE t1.id = t2.flyers_category_id) AS flyerid FROM tbl_flyers_category AS t1 WHERE t1.id IN ($subids) AND t1.deleted_at IS NULL";
    	$statement = $this->dbConnection->prepare($query);
    	$statement->execute();
    	$result = $statement->fetchAll();
    	//echo"<pre>";print_r($result);die();
    	//$result = $query->getQuery()->getResult();
    	return $result;
    } 
    

    public function updateFlyerPositionById($id, $position) {
    	$entity = $this->createQueryBuilder('f')
    	->select('f')
    	->where('f.id = :id')
    	->setParameter(':id', $id)
    	->getQuery()
    	->getOneOrNullResult();

    	if ($entity) {
    		$entity->setSortPosition($position);
    		$entity->setDeletedUid($this->userId);
    		$this->_em->persist($entity);
    		$this->_em->flush();
    	}
    }
}
