<?php

namespace OfficeBrain\Bundle\SubShopBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * SubShopRepository.
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class SubShopRepository extends EntityRepository
{
    protected $projectSetting;
    protected $instanceId;
    protected $instanceType;
    protected $cultureId;
    protected $cultureCode;
    protected $userId;
    protected $paginatorService;

    public function setProjectSetting($projetSetting)
    {
        $this->projectSetting = $projetSetting;
        $this->prepareProjectSettingData();
    }

    public function getProjectSetting()
    {
        return $this->projetSetting;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - getPaginatorService
     * Function created to get Project pagination service
     */
    public function getPaginatorService()
    {
    	return $this->paginatorService;
    }
    
    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - getProjectUserSetting
     * Function created to get Project pagination service
     */
    public function setPaginatorService($paginatorService)
    {
    	$this->paginatorService = $paginatorService;
    }
    
    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'];
        $user = $this->_em->getRepository('OfficeBrainUserBundle:User')->getUserById($this->userId);
	}

    public function set($sub_shop_inquiry)
    {
        return $this->commit($sub_shop_inquiry);
    }

    public function findAll()
    {
        return $this->createQueryBuilder('s')
            ->select('s')
            ->orderBy('s.id', 'DESC')
            ->getQuery()
            ->getResult();
    }

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

    public function findByToken($token)
    {
        return $this->createQueryBuilder('s')
                    ->select('s')
                    ->where('s.token = :token')
                    ->setParameter(':token', $token)
                    ->getQuery()
                    ->getSingleResult();
    }

    public function findByStatus($status_id)
    {
    	return $this->createQueryBuilder('s')
            ->select('s')
            ->where('s.status = :status_id AND s.deletedAt IS NULL AND s.createdUid = :userId')
            ->orWhere('s.status = :status_id AND s.deletedAt IS NULL AND s.siteOwner = :userId')
            ->setParameter(':status_id', $status_id)
            ->setParameter(':userId', $this->userId)
            ->orderBy('s.id', 'DESC')
            ->getQuery()
            ->getResult();
    }

    public function findByParentId($id = 0)
    {
	if($id == 0)
	{
	  $id = $this->instanceId;
	}

        return $this->createQueryBuilder('s')
                    ->select('s')
                    ->where('s.parentId = :parentId and s.deletedAt IS NULL')
                    ->setParameter(':parentId', $id)
                    ->orderBy('s.id', 'DESC')
                    ->getQuery()
                    ->getSingleResult();
    }

    public function findByDelete()
    {
        return $this->createQueryBuilder('s')
                    ->select('s')
                    ->where('s.deletedAt IS NOT NULL AND s.createdUid = :userId')
                    ->orWhere('s.deletedAt IS NOT NULL AND s.siteOwner = :userId')
                    ->setParameter(':userId', $this->userId)
                    ->orderBy('s.id', 'DESC')
                    ->getQuery()
                    ->getResult();
    }

    public function findByOption($option, $keyword, $status_id)
    {
    	$keyword = trim($keyword);
        $return = $this->createQueryBuilder('s')
                       ->select('s')
                       ->where('s.status= :status_id AND s.deletedAt IS NULL AND s.createdUid = :userId')
                       ->orWhere('s.status= :status_id AND s.deletedAt IS NULL AND s.siteOwner = :userId')
                       ->andWhere('s.instanceId  = :instanceId');

        if ($option == 'id') {
            $return->andWhere('s.'.$option.' = :keyword')
                   ->setParameter(':keyword', $keyword);
        } elseif ($option == 'shopName') {
            $return->andWhere('s.shopName like :keyword')
                   ->setParameter(':keyword', '%'.$keyword.'%');
        } elseif ($option == 'createdAt') {
            $keyword = str_replace('/', '-', $keyword);
            $return->andWhere('s.'.$option.' BETWEEN :startedDatetime AND :endedDatetime')
                   ->setParameter(':startedDatetime', date('Y-m-d H:i:s', strtotime($keyword.' 00:00:00')))
                   ->setParameter(':endedDatetime', date('Y-m-d H:i:s', strtotime($keyword.' 23:59:59')));
        } else {
            $return->andWhere('s.'.$option.' like :keyword')
                   ->setParameter(':keyword', '%'.$keyword.'%');
        }

        $return->setParameter(':status_id', $status_id)
               ->setParameter(':instanceId', $this->instanceId)
               ->setParameter(':userId', $this->userId)
               ->orderBy('s.id', 'DESC')
               ->getQuery()
               ->getResult();

        return $return;
    }

    public function findByInstanceWithImage()
    {
        return $this->createQueryBuilder('s')
                    ->select('s AS subshop , st.themeImageName')
                    ->innerJoin('OfficeBrainSubShopBundle:SubShopTheme', 'st', 'WITH', 'st.id = s.shopThemeId')
                    ->where('s.instanceId = :instanceId AND s.status= 1 AND s.deletedAt IS NULL')
                    ->setParameter(':instanceId', $this->instanceId)
                    ->orderBy('s.id', 'DESC')
                    ->getQuery()
                    ->getResult();
    }

    public function findByInstanceDesign($mode)
    {
        return $this->createQueryBuilder('s')
                    ->select('std.customDesign')
                    ->innerJoin('OfficeBrainSubShopBundle:SubShopThemeDesign', 'std', 'WITH', 'std.subshopId = s.id AND std.mode = :mode AND s.parentId = :parentId AND s.status= 1 AND s.deletedAt IS NULL')
                    ->setParameter(':parentId', $this->instanceId)
                    ->setParameter(':mode', $mode)
                    ->orderBy('s.id', 'DESC')
                    ->getQuery()
                    ->getResult();
    }

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

        return $entity;
    }
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - getStateWiseDistributorsSiteDetail
     * Function created to  get State Wise Distributors Site List(sub shop) 
     */
    public function getStateWiseDistributorsSiteDetail($stateId,$page,$recordPerPage,$zipcode)
    {
    	$query=$this->createQueryBuilder('s');
    	$query->select('s.shopDomain','s.externalShopDomain','u.firstName','u.lastName','u.stateId','si.metaValue','u');
    	$query->leftJoin('OfficeBrainSubShopBundle:SubshopInstanceMeta', 'si', 'WITH', 'si.instanceId = s.parentId');
    	$query->leftJoin('OfficeBrainUserBundle:User', 'u', 'WITH', 'u.id = s.siteOwner OR u.id = s.createdUid');    	
    	$query->andWhere("u.stateId =:state")->setParameter("state",$stateId);
    	$query->andWhere("u.userType='distributor'");
    	$query->andWhere("u.status='active'");
    	$query->andWhere("u.locked is NULL");
    	$query->andWhere("u.expired is NULL");
    	$query->andWhere("u.deletedAt is NULL");    	
    	$query->andWhere("s.parentId is NOT NULL ");
    	$query->andWhere("s.status = 1");
    	$query->andWhere("si.metaKey =:metakey")->setParameter('metakey','theme_data');
    	if(isset($zipcode) && $zipcode != ''){
    		$query->andWhere("u.zipcode LIKE :zipcode")->setParameter("zipcode",'%'. $zipcode .'%');    		
    	}    	
    	if (isset($this->instanceId)) {
    		$query->andWhere("u.instanceId=:instanceId")->setParameter('instanceId', $this->instanceId);
    	}
    	//echo $query->getQuery()->getSql(); die;
    	//return $query->getQuery()->getArrayResult();
    	return $this->paginatorService->paginate($query, $page, $recordPerPage);
    }
}
