<?php

namespace OfficeBrain\Bundle\ServiceGroupBundle\Entity;

use Doctrine\ORM\EntityRepository;

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

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

        return $this;
    }

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

    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: 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 getQueryBuilder()
    {
        return $this->getEntityManager()->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleMappingMaster')->createQueryBuilder('srmm');
    }

    public function findById($id, $isReward = false)
    {
        $queryBulder = $this->getQueryBuilder();
        $queryBulder->select(['srmm', 'srmr', 'srmmc', 'srmic'])
                ->leftJoin('srmm.ruleMapMasterId', 'srmr')
                ->leftJoin('srmr.ruleMapRulesId', 'srmmc')
                ->leftJoin('srmr.ruleMapMainCondId', 'srmic')
                ->where('srmm.id=:id')
                ->setParameter(':id', $id);
        if ($isReward) {
            $queryBulder->andWhere('srmm.isReward = true');
        }

        $result = $queryBulder->getQuery()->getOneOrNullResult();

        return $result;
    }

    public function findAll($isReward = false)
    {
        $queryBulder = $this->getQueryBuilder();
        $queryBulder->select(['srmm', 'srmr', 'srmmc', 'srmic'])
                ->leftJoin('srmm.ruleMapMasterId', 'srmr')
                ->leftJoin('srmr.ruleMapRulesId', 'srmmc')
                ->leftJoin('srmmc.ruleMapMainCondId', 'srmic');
        $queryBulder->where('srmm.isActive = 1')
                ->andWhere('srmm.deletedAt is NULL');
        $queryBulder->andWhere('srmm.isReward = :isReward')
                ->setParameter('isReward', $isReward);

        $result = $queryBulder->getQuery()->getResult();

        return $result;
    }

    /**
     * To list Rule Mapping Master.
     *
     * @return ServiceRuleMappingMasterObject|NULL
     */
    public function findByCountryId($ruleType, $page, $recordPerPage, $countryId=null, $searchKeywords = null, $exludeDeleted=null)
    {
        $serviceRuleMapping = $this->_em->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleMappingMaster')
                ->createQueryBuilder('rmm');
        $serviceRuleMapping->select('rmm');
        if (!$exludeDeleted) {
            $serviceRuleMapping
                ->where('rmm.deletedAt is NULL');
        }
        if ($countryId > 0) {
            $serviceRuleMapping
                ->andWhere('rmm.countryId = :countryId')
                ->setParameter('countryId', $countryId);
        }
        $serviceRuleMapping
            ->andWhere('rmm.masterRuleType = :ruleType')
            ->setParameter('ruleType', $ruleType)
        ->andWhere('rmm.instanceId = :instanceId')
                ->setParameter('instanceId', $this->instanceId)
        ->andWhere('rmm.instanceType = :instanceType')
                ->setParameter('instanceType', $this->instanceType);

        /*if ($searchKeywords && $searchKeywords != "") {
            $qb->andWhere('srm.ruleName like :searchKeywords');
            $qb->setParameter(':searchKeywords', "%".$searchKeywords."%");
        }*/

        $serviceRuleMapping->orderBy('rmm.id', 'DESC');

        if ($recordPerPage==null) {
            return $serviceRuleMapping->getQuery()->getResult();
        } else {
            return $this->paginatorService->paginate($serviceRuleMapping, $page, $recordPerPage);
        }
    }

    /*
     * =========================================
     */

    /**
     * To add rule mapping.
     *
     * @param object $serviceRuleMappingMasterObj
     *
     * @return \OfficeBrain\Bundle\ServiceGroupBundle\Entity\ServiceRuleMappingMaster
     */
    public function addServiceRuleMapping($countryId, $groupId, $serviceId, $isActive)
    {
        $serviceRuleMap = new ServiceRuleMappingMaster();
        $em = $this->getEntityManager();
        $serviceRuleMap->setCultureId($ruleName);
        $serviceRuleMap->setGroupId($ruleType);
        $serviceRuleMap->setServiceId($startDate);
        $serviceRuleMap->setIsActive($endDate);

        $em->persist($serviceRuleMap);
        $em->flush();

        return $serviceRuleMap;
    }

    /*
     * =========================================
     */

    /**
     * To add rule mapping.
     *
     * @param object $serviceRuleMappingMasterObj
     *
     * @return \OfficeBrain\Bundle\ServiceGroupBundle\Entity\ServiceRuleMappingMaster
     */
    public function addServiceRuleMappingMaster($serviceRuleMappingMaster, $dataArray, $ruleType)
    {
        $serviceRuleMappingMaster->setMasterRuleType($ruleType);

        $serviceRuleMappingMaster->setInstanceId($this->instanceId);
        $serviceRuleMappingMaster->setInstanceType($this->instanceType);
        $serviceRuleMappingMaster->setCreatedUid($this->userId);
        $serviceRuleMappingMaster->setUpdatedUid($this->userId);

        if ($serviceRuleMappingMaster->getId()) {
            $this->removeServiceRuleMappingGroup($serviceRuleMappingMaster);
        }

        foreach ($dataArray['serviceRuleMappingGroupId'] as $serviceGroup) {
            $serviceGroupMapping = new ServiceRuleMappingGroup();
            $serviceGroupMapping->setServiceRuleMappingId($serviceRuleMappingMaster);
            $serviceGroupMapping->setServiceGroupId($serviceGroup->getServiceGroup());

            $serviceGroupMapping->setInstanceId($this->instanceId);
            $serviceGroupMapping->setInstanceType($this->instanceType);
            $serviceGroupMapping->setCreatedUid($this->userId);
            $serviceGroupMapping->setUpdatedUid($this->userId);

            $this->_em->persist($serviceGroupMapping);
        }


        $this->_em->persist($serviceRuleMappingMaster);
        $this->_em->flush();

        return $serviceRuleMappingMaster;
    }


    /**
     * To remove ServiceRuleMappingGroup.
     *
     * @param object $serviceRuleMappingMasterObj
     *
     * @return
     */
      public function removeServiceRuleMappingGroup($serviceRuleMappingMasterObj)
      {
          $query = $this->createQueryBuilder('srmg')
                ->delete('OfficeBrainServiceGroupBundle:ServiceRuleMappingGroup', 'srmg')
                ->where('srmg.serviceRuleMappingId =:serviceRuleMappingId')
                ->setParameter('serviceRuleMappingId', $serviceRuleMappingMasterObj);
          $result = $query->getQuery()->execute();

          return $result;
      }


    /**
     * To edit rule mapping.
     *
     * @param object $serviceRuleMappingMasterObj
     *
     * @return \OfficeBrain\Bundle\ServiceGroupBundle\Entity\ServiceRuleMappingMaster
     */
    public function editServiceRuleMappingMaster($id, $groupId, $serviceId, $isActive)
    {
        $serviceRuleMap = $this->findOneById($id);
        $em = $this->getEntityManager();

        //$serviceRuleMap->setCultureId($countryId);
        $serviceRuleMap->setGroupId($groupId);
        $serviceRuleMap->setServiceId($serviceId);
        $serviceRuleMap->setIsActive($isActive);

        $serviceRuleMap->setUpdatedAt(new \DateTime());
        $serviceRuleMap->setUpdatedUid($this->userId);

        $em->persist($serviceRuleMap);
        $em->flush();

        return $serviceRuleMap;
    }

    /**
     * To get Rule Mapping Master By id.
     *
     * @param int id
     *
     * @return ServiceRuleMappingMasterObject|NULL
     */
    public function getServiceRuleMappingById($id, $exludeDeleted=null)
    {
        $serviceRuleMapping = $this->createQueryBuilder('rmm')
            ->select('rmm')
            ->where('rmm.id = :id')
            ->setParameter(':id', $id);

        if (!$exludeDeleted) {
            $serviceRuleMapping->andWhere('rmm.deletedAt is NULL');
        }

        return $serviceRuleMapping->getQuery()->getOneOrNullResult();
    }


    /**
     * To get Rule Mapping Master By priority.
     *
     * @param int id
     *
     * @return ServiceRuleMappingMasterObject|NULL
     */
    public function getServiceRuleMappingByPriority($priority, $exludeDeleted=null)
    {
        $serviceRuleMapping = $this->createQueryBuilder('rmm')
        ->select('rmm')
        ->where('rmm.priority = :priority')
        ->setParameter(':priority', $priority);

        if (!$exludeDeleted) {
            $serviceRuleMapping->andWhere('rmm.deletedAt is NULL');
        }

        return $serviceRuleMapping->getQuery()->getOneOrNullResult();
    }

    /**
     * To delete Rule Mapping Master.
     *
     * @param int $id
     *
     * @return bool
     */
    public function deleteRuleMappingMaster($id)
    {
        $serviceRuleMast = $this->findOneBy(array('id' => $id));

        if ($serviceRuleMast) {
            $em = $this->getEntityManager();
            $serviceRuleMast->setDeletedAt(new \DateTime());
            $serviceRuleMast->setDeletedUid($this->userId);

            $em->persist($serviceRuleMast);
            $em->flush();

            return $serviceRuleMast;
        }

        return false;
    }

    /**
     * To find exsisitng priority
     *
     * @param1 int $countryId
     *
     * @param2 int $prority
     *
     * @param3 string $masterRuleType
     *
     * @param4 int $id
     *
     * @return bool
     */
    public function findExistPriority($countryId, $prority, $masterRuleType, $id=null)
    {
        $queryBulder = $this->getQueryBuilder();
        $queryBulder->select('count(srmm.id)')
                ->where('srmm.countryId=:countryId')
                ->andWhere('srmm.deletedAt is NULL')
                ->setParameter(':countryId', $countryId)
                ->andWhere('srmm.masterRuleType=:masterRuleType')
                ->setParameter(':masterRuleType', $masterRuleType)
                ->andWhere('srmm.instanceId = :instanceId')
                ->setParameter('instanceId', $this->instanceId)
                ->andWhere('srmm.instanceType = :instanceType')
                ->setParameter('instanceType', $this->instanceType);
        if ($prority != '') {
            $queryBulder->andWhere('srmm.priority = :priority')
                         ->setParameter('priority', $prority);
        }
        if ($id != '') {
            $queryBulder->andWhere('srmm.id != :id')
                         ->setParameter('id', $id);
        }
        return $queryBulder->getQuery()->getSingleScalarResult();
    }
    public function copyRuleMappingMaster($ruleMappingMaster)
    {
        $em = $this->getEntityManager();
        $em->persist($ruleMappingMaster);
    }

    public function commit()
    {
        $em = $this->getEntityManager();
        $em->flush();
    }

    public function clear()
    {
        $em = $this->getEntityManager();
        $em->clear();
    }
}
