<?php

namespace OfficeBrain\CustomBundle\UserBundle\Entity;

use Doctrine\ORM\EntityRepository;
use OfficeBrain\Bundle\UserBundle\Service\CustomPasswordEncoder;
use Symfony\Component\Form\FormError;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\MessageSelector;
use Symfony\Component\Translation\Loader\YamlFileLoader;

/**
 * UserRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class UserRepository extends EntityRepository
{

    protected $projectSetting;
    protected $instanceId;
    protected $instanceType;
    protected $cultureId;
    protected $cultureCode;
    protected $userType;
    protected $paginatorService;
    protected $projectSettingService;
    protected $projectUserSetting;
    protected $userApi;
    protected $serviceGroupService;
    protected $jmsSerializer;
    protected $projectId;
    protected $coreManager;

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - setCoreManager
     * Function created to set core manager
     */
    public function setCoreManager($coreManager)
    {
    	$this->coreManager = $coreManager;
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - getCoreManager
     * Function created to get core manager
     */
    public function getCoreManager()
    {
    	return $this->coreManager;
    }

  

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - setServiceGroup Service
     * Function created to setServiceGroup  Service
     */
    public function setServiceGroupService($serviceGroupService)
    {
    	$this->serviceGroupService = $serviceGroupService;
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - getServiceGroup Service
     * Function created to get setServiceGroup Service
     */
    public function getServiceGroupService()
    {
    	return $this->serviceGroupService;
    }



    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - setProjectSetting
     * Function created to set Project Setting
     */
    public function setProjectSetting($projetSetting)
    {
        $this->projectSetting = $projetSetting;
        $this->prepareProjectSettingData();
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - getProjectSetting
     * Function created to get Project Setting
     */
    public function getProjectSetting()
    {
        return $this->projetSetting;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - setProjectUserSetting
     * Function created to set Project User Setting
     */
    public function setProjectUserSetting($projectUserSetting)
    {
        $this->projectUserSetting = $projectUserSetting;
        $this->prepareProjectUserSettingData();
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - getProjectUserSetting
     * Function created to get Project User Setting
     */
    public function getProjectUserSetting()
    {
        return $this->projectUserSetting;
    }

    /**
     * @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;
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - prepareProjectSettingData
     * Function created to prepare Project Setting Data
     */
    public function prepareProjectSettingData()
    {
    	$this->userId = $this->projectSetting['user_id'];
    	$this->createdUid = $this->upatedUid = $this->userId;
    	$this->projectId = $this->projectSetting['project_id'];
    	$this->instanceId = $this->projectSetting['instance_id'];
    	$this->instanceType = $this->projectSetting['instance_type'];
    	$this->cultureId = $this->projectSetting['culture_id'];
    	$this->cultureCode = $this->projectSetting['culture_code'];
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - prepareProjectUserSettingData
     * Function created to prepare Project User Setting Data
     */
    public function prepareProjectUserSettingData()
    {
    	$this->user = $this->projectUserSetting['user_data'];
      $this->userType = null;
      if(!empty($this->user) && method_exists($this->user, 'getUserType')) {
    	   $this->userType = $this->user->getUserType();
      }
    }
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - getDistributorsStateDetail
     * Function created to  getDistributorsStateDetail
     */
    public function getDistributorsStateDetail($stateOrCountryCode,$callType)
    {
    	if ($stateOrCountryCode!='') {
    		$query=$this->createQueryBuilder('u');
    		if($callType && $callType=='country_code' ){
    			$query->select('s.id', 's.stateCode', 's.stateName', 's.countryCode');
    		}else if($callType && $callType=='state_code' ){
    			$query->select('s.id', 's.stateCode', 's.stateName', 's.countryCode','ct.id', 'ct.cityName');
    		}
    		$query->leftJoin('OfficeBrainCoreBundle:State', 's', 'WITH', 'u.stateId=s.id');
    		$query->leftJoin("OfficeBrainCoreBundle:Country", "con", "WITH", "s.countryCode=con.countryCode");
    		$query->where("u.userType='distributor'");
    		if($callType && $callType=='country_code' ){
    			$query->andWhere($query->expr()->in('con.id', array($stateOrCountryCode)));
    			$query->andWhere('u.stateId IS NOT NULL');
    			$query->orderBy('s.stateName',' ASC')->groupBy('u.stateId');
    		}else if($callType && $callType=='state_code' ){
    			$query->leftJoin('OfficeBrainCoreBundle:City', 'ct', 'WITH', 'u.cityId=ct.id');
    			$query->andWhere($query->expr()->in('s.id', array($stateOrCountryCode)));
    			$query->andWhere('u.cityId IS NOT NULL');
    			$query->orderBy('ct.cityName',' ASC')->groupBy('ct.cityName');
    		}
    		$query->andWhere("u.status='active'");
    		$query->andWhere("u.locked is NULL");
    		$query->andWhere("u.expired is NULL");
    		$query->andWhere("u.deletedAt is NULL");
    		if (isset($this->projectSetting['instance_id'])) {
    			$query->andWhere("u.instanceId=:instanceId")->setParameter('instanceId', $this->projectSetting['instance_id']);
    		}    	
    		return $query->getQuery()->getArrayResult();
    	}else{
    		return array();
    	}
    }
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - findDistributorForSubShop
     * Function created to findDistributorForSubShop
     */
    public function findDistributorForSubShop($page,$recordPerPage,$search_query)
    {
    	$query=$this->createQueryBuilder('u')->select('u');
    	$query->where("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");    	
    	if (isset($this->projectSetting['instance_id'])) {
    		$query->andWhere("u.instanceId=:instanceId")->setParameter('instanceId', $this->projectSetting['instance_id']);
    	}
    
    	if (isset($search_query) and $search_query!='') {
    		foreach ($search_query as $key=>$val) {
    			if ($key == 'countryId') {
    				$query->leftJoin('OfficeBrainCoreBundle:Country', 'c', 'WITH', 'u.countryId=c.id');
    				$query->andWhere('c.id = :country')->setParameter('country', $val);
    				continue;
    			} elseif ($key == 'stateId') {
    				$query->leftJoin('OfficeBrainCoreBundle:State', 'st', 'WITH', 'u.stateId=st.id');
    				$query->andWhere('st.id = :state')->setParameter('state', $val);
    				continue;
    			} elseif ($key == 'cityId') {
    				$query->leftJoin('OfficeBrainCoreBundle:City', 'ct', 'WITH', 'u.cityId=ct.id');
    				$query->andWhere('ct.id = :city')->setParameter('city', $val);
    				continue;
    			}  elseif ($key == 'zipcode') {
    				$param = 'user'.$key;
    				$queryZipciode=$this->getEntityManager()->getRepository("OfficeBrainUserBundle:User")->findOneBy(array('zipcode'=>$val));
    				if(is_object($queryZipciode))
    				{
    					$query->andWhere('u.'.$key.' LIKE :'.$param)->setParameter($param, '%'. $val .'%');
    				}
    				else {
    					$query->andWhere('REGEXP(u.zipcode, :regexp) = true')
    				->setParameter('regexp', '^'.substr($val, 0,2)); // insert your own regex here
    					
    				}
//     				$query->andWhere($query->expr()->like('u.'.$key, ':'.$param);
//     				$query->andWhere('u.'.$key.' LIKE :'.$param .' or '.'u.'.$key.' LIKE :'.'user'.$key)->setParameter($param, '%'. $val .'%')->setParameter('user'.$key, '%'. substr($val, 0,2) .'%');    				
    				
//     				$query->andWhere('u.'.$key.' LIKE :'.$param)->setParameter($param, '%'. $val .'%');
//     				$query->andWhere('u.'.$key.' LIKE :'.$param)->setParameter($param, '%'. $val .'%');
//     				$query->orWhere($query->expr()->like('u.'.$key, ':'.$param))->setParameter('user'.$key, '^'. substr($val, 0,2));
//     				$query->andWhere($query->expr()->like('u.'.$key, ':'.$param))->setParameter('user'.$key, '^'. substr($val, 0,2));
//     				$query->andWhere('u.'.$key.' REGEXP :'.$param)->setParameter($param, '^'. substr($val, 0,2));
//     				$query->andWhere('u.'.$key.' REGEXP :'.$param)->setParameter($param, '^'. substr($val, 0,2));
//     				$query->andWhere("REGEXP('u.zipcode', :userzipcode)=true")->setParameter('userzipcode', '^'. substr($val, 0,2));
    				/* $qb = $this->createQueryBuilder('x');*/
//     				$query->andWhere('u.'.$key.' LIKE :'.$param .' or '.'u.'.$key.' LIKE :'.'user'.$key)->setParameter($param, '%'. $val .'%')->setParameter('user'.$key, '%'. substr($val, 0,2) .'%');
    				
    				
    				
    			}
    		}
    	}
    	$query->orderBy("u.id","ASC");
//     	echo $query->getQuery()->getSQL();

    	
//     	return $query->getQuery()->getArrayResult();
    	return $this->paginatorService->paginate($query, $page, $recordPerPage);
    }
    
    public function getAllUserObject()
    {
    	$objUsers = $this->createQueryBuilder("U")
    	->select("U")
    	->andWhere("U.status='active'")
    	->addOrderBy("U.loginUsername", "ASC")
    	->andWhere("U.deletedAt is NULL")
    	->getQuery()// -> getSQL();
    	->getResult();
    	return $objUsers;
    }
}
