<?php

namespace OfficeBrain\Bundle\CompanyBundle\Entity;

use Doctrine\ORM\EntityRepository;
// use Symfony\Component\Validator\Constraints\Null;
use Symfony\Component\Form\FormError;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\MessageSelector;
use Symfony\Component\Translation\Loader\YamlFileLoader;

/**
 * CompanyRepository.
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class CompanyRepository extends EntityRepository
{
    protected $projectSetting;
    protected $projectUserSetting;
    protected $instanceId;
    protected $instanceType;
    protected $cultureId;
    protected $cultureCode;
    protected $userType;
    protected $parentId;
    protected $paginatorService;
    protected $projectSettingService;    
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - getPaginatorService
     * Function created to get Paginator Service
     */
    public function getPaginatorService()
    {
    	return $this->paginatorService;
    }
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - setPaginatorService
     * Function created to set Paginator Service
     */
    public function setPaginatorService($paginatorService)
    {
    	$this->paginatorService = $paginatorService;
    }
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - setProjectSetting
     * Function created to set Project Setting
     */
    public function setProjectSetting($projetSetting)
    {
        $this->projectSetting = $projetSetting;
        $this->prepareProjectSettingData();
    }
    
    /**
     * @author Employee Id: 4493
     * 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;
    }

    public function prepareProjectSettingData()
    {
    	$this->userId = $this->projectSetting['user_id'];
    	$this->createdUid = $this->upatedUid = $this->userId;
    	$this->instanceId = $this->projectSetting['instance_id'];
    	$this->instanceType = $this->projectSetting['instance_type'];
    	$this->cultureId = $this->projectSetting['culture_id'];
    	$this->cultureCode = $this->projectSetting['culture_code'];
    }
    
    public function prepareProjectUserSettingData()
    {
        $this->user = $this->projectUserSetting['user_data'];
    	$this->userType = $this->user->getUserType();
    	$this->parentId = null;
    	if(is_object($this->user->getParent())){
    		$this->parentId = $this->user->getParent()->getId();
    	}
    }
    
    public function getQueryBuilder()
    {
        return $this->getEntityManager()->getRepository("OfficeBrainCompanyBundle:Company")->createQueryBuilder('cmp');
    }
    
    public function getBranchQueryBuilder()
    {
        return $this->getEntityManager()->getRepository("OfficeBrainCompanyBundle:Company")->createQueryBuilder('b');
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - getCompanylist
     * Function created to get AllUsers
     */
    public function getCompanyList($userId,$companyCountFlag, $searchParameterArray, $page, $recordsPerPage, $status, $companyId)
    {
    	$userObj = $this->projectUserSetting['user_data'];
        $query=$this->createQueryBuilder('cmp');
        if($companyCountFlag == '1'){
        	$query->select('count(cmp.id)','cmp.status');
        } else {
        	$query->select('cmp');
        }	         
        if ($this->userType && $this->userType=='employee' || $this->userType=='branchEmployee') {
        	$userId = $this->parentId;
        }
        $query->where("cmp.userc =:userId")
              ->orWhere("cmp.createdUid =:userId")
              ->setParameter('userId', $userId);
        if (isset($searchParameterArray) and $searchParameterArray!='') {
        	foreach ($searchParameterArray as $key=>$val) {
                if ($key == 'countryId') {
                    $query->leftJoin('OfficeBrainCoreBundle:Country', 'c', 'WITH', 'cmp.countryId=c.id');
                    $query->andWhere('c.countryName LIKE :country')->setParameter('country', '%'. $val .'%');
                    continue;
                }elseif ($key == 'stateId') {
                    $query->leftJoin('OfficeBrainCoreBundle:State', 's', 'WITH', 'cmp.stateId=s.id');
                    $query->andWhere('s.stateName LIKE :state')->setParameter('state', '%'. $val .'%');
                    continue;
                }elseif ($key == 'cityId') {
                    $query->leftJoin('OfficeBrainCoreBundle:City', 'ct', 'WITH', 'cmp.cityId=ct.id');
                    $query->andWhere('ct.cityName LIKE :city')->setParameter('city', '%'. $val .'%');
                    continue;
                }elseif ($key != '') {
                    $param = 'company'.$key;
                    $query->andWhere('cmp.'.$key.' LIKE :'.$param)->setParameter($param, '%'. $val .'%');
                }
            }
        }
        if($status != '') {
        	$query->andWhere("cmp.status =:status")
            	  ->setParameter('status', $status);
        }
        if($companyId != '') {
            $query->andWhere("cmp.parent =:companyId")
                  ->setParameter('companyId', $companyId)
                  ->andWhere('cmp.parent is not NULL');
        } else {
            $query->andWhere('cmp.parent is NULL');
        }
        $query->andWhere("cmp.deletedAt is NULL");
        
        if($companyCountFlag == '1'){
        	$query->groupBy('cmp.status');
        	return $query->getQuery()->getArrayResult();
        }        
        return $this->paginatorService->paginate($query, $page, $recordsPerPage);
        
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - company
     * Function created for get usertype from id( employee or branchemployee )
     */
    public function isBranch($companyId)
    {
        $queryBuilder=$this->getBranchQueryBuilder('b');
        $queryBuilder->where('b.id =:companyId')
                    ->setParameter('companyId', $companyId)
                    ->andWhere('b.parent is not NULL');
        //echo $queryBuilder->getQuery()->getSql();
        $data=$queryBuilder->getQuery()->getResult();
        if ($data and $data !='') {
            return 'branchEmployee';
        } else {
            return 'employee';
        }
    }
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - company
     * Function created for add company
     */
    public function saveCompany($companyData,$logoUrl,$fromerp)
    {
    	if ($this->userType && $this->userType=='employee' || $this->userType=='branchEmployee') {
    		$parentObj = $this->getEntityManager()->getRepository('OfficeBrainUserBundle:User')->find($this->parentId);
    		$companyData->setUserc($parentObj);
    	} else {
    		$companyData->setUserc($this->user);
    	}
        if ($fromerp=="0") {
            if (is_object($companyData->getParent())) {
                $companyData->setStatus($this->projectSetting['configuration_rule']['user']['branch']['status']);
            }else{
                $companyData->setStatus($this->projectSetting['configuration_rule']['user']['company']['status']);
            }   
        }
    	$companyData->setCreatedUid($this->createdUid);
    	if (is_object($companyData->getCompanyLogo()) && $fromerp=="0") {
    		$companyLogo=$companyData->getCompanyLogo()->getClientOriginalName();
    		$companyData->setCompanyLogo($companyLogo);
    		$companyData->setCompanyLogoUrl($logoUrl.$companyLogo);    		
    	}
    	$this->_em->persist($companyData);
	    $this->_em->flush();
	    return $companyData;    	    
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - company
     * Function created for edit company
     */
    public function editCompany($companyData,$logoUrl,$fromerp)
    {	
    	$companyArray = $this->getSingleCompany($companyData->getId());
    	$companyLogo = $companyArray[0]['companyLogo'];     	
    	if (is_object($companyData->getCompanyLogo()) && $fromerp=="0" ) {
    		$companyLogo=$companyData->getCompanyLogo()->getClientOriginalName();  
            $companyData->setCompanyLogo($companyLogo);
            $companyData->setCompanyLogoUrl($logoUrl.$companyLogo);
       	}  else{
       		$companyData->setCompanyLogo($companyLogo);
       	}
       	
    	$companyData->setUpdatedUid($this->upatedUid);
    	$this->_em->persist($companyData);
        $this->_em->flush();
        return $companyData;
    }
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - getCompanylist
     * Function created to get single company
     */
    public function getSingleCompany($companyId)
    {	
    	$query=$this->createQueryBuilder('cmp')
    				->select('cmp')
    				->Where('cmp.id=:companyId')
    				->setParameter('companyId',$companyId);    	
    	return $query->getQuery()->getArrayResult();    	
    }
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - company
     * Function created for check record is deleted or not 
     */
    public function isDelete($companyId)
    {
        $query = $this->getQueryBuilder()->select('cmp')
                        ->leftJoin('cmp.userc', 'u')
                        ->where('cmp.parent=:parent')
                        ->setParameter('parent', $companyId)
                        ->orWhere('u.userCompany=:company')
                        ->setParameter('company', $companyId)
                        ->andWhere('cmp.deletedAt is NULL')
                        ->andWhere('u.deletedAt is NULL');
        return $query->getQuery()->getArrayResult();
    }
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - company
     * Function created for deletecompany
     */
    public function deleteCompany($companyId)
    {
        $queryBuilder = $this->createQueryBuilder('cmp')
                        ->delete()
                        ->where('cmp.id = :companyId')
                        ->setParameter('companyId', $companyId);
        return $queryBuilder->getQuery()->execute();
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - company
     * Function created for update status
     */
    public function updateStatus($companyObj)
    {
        if ($companyObj) {
            $this->_em->persist($companyObj);
            $this->_em->flush();
            return array('status'=>'SUCCESS','data'=>$companyObj);
        }
        return array('status'=>'FAIL');
    }

   
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - check company Exist
     * Function for check company Exist
     */
    public function checkCompanyExists($form)
    {
    	$result = array();
    	$translator = new Translator($this->projectSetting['locale_language'], new MessageSelector());
    	$translator->addLoader('yaml', new YamlFileLoader());
    	$translator->addResource('yaml', __DIR__.'/../Resources/translations/validators.'.$this->projectSetting['locale_language'].'.yml', $this->projectSetting['locale_language']);

    	if ($form->has('companyName')) {
    		$companyName = $form->getData()->getCompanyName();
    		    
    		$query=$this->createQueryBuilder('cmp');
    		$query->where("LOWER(cmp.companyName)=:companyName")->setParameter('companyName', strtolower($companyName));
    		if($form->getParent() && $form->getParent() != ''){
    			$query->andWhere("cmp.parent is NOT NULL");
    			$query->andWhere("cmp.parent =:parent")->setParameter('parent',$form->getParent()->getId());    			
    		}else{
    			$query->andWhere("cmp.parent is NULL");
    		}
    		$query->andWhere("cmp.deletedAt is NULL");
    		$query->setMaxResults("1");
    		$companyNameExist = $query->getQuery()->getOneorNullResult();    		
    		if ($companyNameExist && $companyNameExist->getId()!=$form->getData()->getId()) {
    			$form->get('companyName')->addError( new FormError($translator->trans('admin.company.companyname.exist')));
    			return false;
    		}
    	}
    	if ($form->has('companyAsiNumber')) {
    		$companyaAsiNumber = $form->getData()->getCompanyAsiNumber();
    		    
    		$query=$this->createQueryBuilder('cmp');
    		$query->where("cmp.companyAsiNumber=:companyAsiNumber")->setParameter('companyAsiNumber', $companyaAsiNumber);
    		if($form->getParent() && $form->getParent() != ''){
    			$query->andWhere("cmp.parent is NOT NULL");
    			$query->andWhere("cmp.parent =:parent")->setParameter('parent',$form->getParent()->getId());    			
    		}else{
    			$query->andWhere("cmp.parent is NULL");
    		}
    		$query->andWhere("cmp.deletedAt is NULL");
    		$query->setMaxResults("1");
    		$companyAsiNumberExist = $query->getQuery()->getOneOrNullResult();    		
    		if ($companyAsiNumberExist && $companyAsiNumberExist->getId()!=$form->getData()->getId()) {    	
    			$form->get('companyAsiNumber')->addError( new FormError($translator->trans('admin.company.companyasi.exist')));
    			return false;
    		}
    	}
    	return true;
    }
    
}
