<?php

namespace OfficeBrain\Bundle\ServiceGroupBundle\Manager\Extended;

use OfficeBrain\Bundle\ServiceGroupBundle\Manager\AbstractManager\ServiceRuleAbstract;
use OfficeBrain\Bundle\ServiceGroupBundle\Entity\ServiceRuleMaster;
use OfficeBrain\Bundle\ServiceGroupBundle\Entity\ServiceRuleMappingMaster;
use OfficeBrain\Bundle\ServiceGroupBundle\Entity\ServiceRuleMappingInnerConditions;
use OfficeBrain\Bundle\ServiceGroupBundle\Entity\ServiceRuleMappingColumnQty;
use OfficeBrain\Bundle\ServiceGroupBundle\Entity\ServiceRuleProductPrice;
use OfficeBrain\Bundle\ServiceGroupBundle\Entity\ServiceRuleChargeProductPrice;

/**
 * @author OfficeBrain 4589 <info@officebrain.com>
 *
 * Description : Service Group Extended Class
 */
class ServiceRuleMappingAdminExtended extends ServiceRuleAbstract
{
    public function __construct($entityManager, $request, $session, $serviceContainer, $translatorService, $countries, $languages, $coreManager, $productTagManager, $serviceGroupAPiClient, $twigExtension)
    {
        parent::__construct($entityManager, $request, $session, $serviceContainer, $countries, $languages, $coreManager, $productTagManager, $serviceGroupAPiClient, $translatorService, $twigExtension);


        $this->conditionAry = $this->getConditionArray();
        $this->conditionMutlipleValueAry = $this->getConditionMultipleValueList();
        $this->cultureList = $this->getCultureList();

        $this->actionTypes = $this->getActionTypes();
        $this->actionLimitPer = $this->getActionLimitPer();
        $this->actionRuleTypes = $this->getActionRuleTypes();
        $this->actionChargeTypes = $this->getActionChargeTypes();
        $this->actionAmountTypes = $this->getActionAmountTypes();
        $this->actionRuleStatus = $this->getRuleStatus();

        $this->translatorService = $translatorService;

        $this->recordsPerPage = $this->projectSetting['configuration_rule']['promo_discount']['option']['rule_mapping']['option']['record_per_page'];

        $this->serviceRuleMappingRulesRepository = $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleMappingRules')
                                                    ->setProjectSetting($this->projectSetting);

        $this->serviceRuleChargesEquationRepository = $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleChargesEquation');
                                                    //->setProjectSetting($this->projectSetting);
    }

    public function __destruct()
    {
        unset($this->conditionAry);
        unset($this->conditionMutlipleValueAry);
        unset($this->cultureList);
        unset($this->actionTypes);
        unset($this->actionLimitPer);
        unset($this->actionRuleTypes);
        unset($this->actionChargeTypes);
        unset($this->actionAmountTypes);
        unset($this->actionRuleStatus);
        unset($this->translatorService);
        unset($this->recordsPerPage);
        unset($this->serviceRuleMappingRulesRepository);
        unset($this->serviceRuleMappingMasterRepository);
    }


    /**
     * @author Employee Id: 4589
     * Description : List service rule mapping
     *
     * @param 1 : Null
     *
     * @return type : ServiceRuleMapping
     *
     * @throws Exception: Null
     */
    public function getRuleMappingList()
    {
        $countryId = $this->request->get('countryId', $this->countryId);
        $searchQuery = $this->request->get('search_query', null);
        $page = $this->request->get('page', 1);

        $ruleMappingList = $this->serviceRuleMappingMasterRepository->findByCountryId($this->ruleType, $page, $this->recordsPerPage, $countryId, $searchQuery);

        //$pagination = $this->paginatorService->paginate($ruleMappingList, $page, $this->recordsPerPage, array(), count($ruleMappingList));

        $data['pagination'] = $ruleMappingList;
        $data['records_per_page'] = $this->recordsPerPage;
        $data['page'] = $page;
        $data['search_query'] = $searchQuery;
        $data['country_id'] = $countryId;

        $data['amount_type_list'] = $this->getActionAmountTypes();
        $data['rule_type_list'] = $this->getActionRuleTypes();
        $data['charges_type_list'] = $this->getActionChargeTypes();

        return $data;
    }

    public function getAllApplyRuleMapping()
    {
        $page = $this->request->get('page', 1);
        return $this->serviceRuleMappingMasterRepository->findByCountryId($this->ruleType, $page, null, null, null, true);
    }

    /**
     * @author Employee Id: 4589
     * Description : List service rule mapping
     *
     * @param 1 : Null
     *
     * @return type : ServiceRuleMapping
     *
     * @throws Exception: Null
     */
    public function getRuleMappingForEdit()
    {
        $id = $this->request->get('id');

        if ($id && $id > 0) {
            $ruleMappingMaster = $this->getServiceRuleMappingById($id);
            $ruleMappingRules = $this->getMappingRulesByMappingMasterId($id);
        }

        $countryId = $ruleMappingMaster->getCountryId();

        $responseArray['options']['mode'] = 'edit';
        $responseArray['options']['culture'] = $this->getSelectedCultures();
        $responseArray['options']['rule_type'] = $this->actionRuleTypes;
        $responseArray['options']['amount_type'] = $this->actionAmountTypes;
        $responseArray['options']['rule_status'] = $this->actionRuleStatus;
        $responseArray['options']['charge_type'] = $this->actionChargeTypes;

        $ruleMappingRule = $ruleMappingMaster->getRuleMapMasterId()->first();
        $ruleMappingRuleArray = $this->getMappingRulesById($ruleMappingRule->getId());
        //echo "<pre>";print_r($ruleMappingRuleArray);die;
        $responseArray['mapping_rule_id'] = $ruleMappingMaster->getId();
        $responseArray['rule_master_id'] = $ruleMappingRule->getRuleMasterId();

        $responseArray['rule_condition'] = $ruleMappingRuleArray['ruleMapRulesId'];
        $responseArray['conditions'] = json_encode(array_values($this->getConditionArray($countryId)));
        $responseArray['service_rule_mapping_column_qty'] = $ruleMappingMaster->getServiceRuleMappingQtyId()->toArray();
        $serviceGroups = array();
        foreach ($ruleMappingMaster->getServiceRuleMappingGroupId()->toArray() as $serviceGroupMap) {
            foreach ($serviceGroupMap->getServiceGroupId()->getLanguageMapping() as $serviceGroupLanguage) {
                $serviceGroups[] = array('id' => $serviceGroupLanguage->getId(),'groupName' => $serviceGroupLanguage->getGroupName());
            }
        }
        $responseArray['service_rule_mapping_groups'] = $serviceGroups;
        $responseArray['rule_mapping_rules'] = (isset($ruleMappingRules) ? $ruleMappingRules : null);
        $responseArray['rule_mapping_master'] = $ruleMappingMaster;
        $responseArray['rule_mapping_rules'] = $ruleMappingRules;

        return $responseArray;
    }

    /**
     * @author Employee Id: 4589
     * Description : Set Rule Mapping
     *
     * @param 1 : Form
     * @param 2 : Culture Id
     *
     * @return type : Messages
     *
     * @throws Exception: Null
     */
    public function setRuleMapping($form)
    {
        $ruleErrors = null;

        $dataAry = $this->request->request->all();
        if (!isset($dataAry['mapping_rule_id']) || (int) $dataAry['mapping_rule_id'] <= 0 || $dataAry['mapping_rule_id']=='') {
            $ruleErrors = array('rules' => 'Please add at-least one Rule.');
        }

        if (isset($dataAry['has_rule_cond_error']) && $dataAry['has_rule_cond_error'] == 'true') {
            $ruleErrors['rules'] = $this->translatorService->trans('admin.service_group_management.rule_mapping.rule_condition_error');
        } elseif (!isset($dataAry['rule_condition']) || trim($dataAry['rule_condition']) == null) {
            $ruleErrors['rules'] = $this->translatorService->trans('admin.service_group_management.rule_mapping.rule_condition_blank_error');
        } elseif (isset($dataAry['rule_condition']) && isset($dataAry['rules'])) {
            $ruleConditionAry = null;
            $rule_condition = (isset($dataAry['rule_condition']) ? $dataAry['rule_condition'] : '');
            $rule_condition = explode('=', $rule_condition);
            $ruleConditionAry = array('condition' => $rule_condition[1],'rules' => $dataAry['rules']);
            if (is_array($ruleErrors)) {
                $ruleErrors = array_merge($ruleErrors, $this->validateRules($dataAry['rules'], 'mapping'));
            } else {
                $ruleErrors = $this->validateRules($dataAry['rules'], 'mapping');
            }
        }

        if ($form->isValid() && $ruleErrors === null) {
            $rulesIdAry = array($dataAry['mapping_rule_id']);

            $serviceRuleMappingMaster = $form->getData();
            $extraArray = array();
            $extraArray['rule_master_id'] = $dataAry['rule_master_id'];
            $extraArray['mapping_rule_id'] = $dataAry['mapping_rule_id'];
            $extraArray['serviceRuleMappingGroupId'] = $form->get('serviceRuleMappingGroupId')->getData();

            if ($serviceRuleMappingMaster->getIsColumnQty()) {
                $serviceRuleMappingMaster->setAmount(null);
            }
            $data['rule_condition'] = null;
            $rule_condition = (isset($dataAry['rule_condition']) ? $dataAry['rule_condition'] : '');
            if (isset($dataAry['rules'])) {
                $rule_condition = explode('=', $rule_condition);
                $data['rule_condition'] = array('condition' => $rule_condition[1],'rules' => $dataAry['rules']);
            }

            $ruleCondition = isset($data['rule_condition']) ? ($data['rule_condition']) : '';

            $serviceRuleMappingMasterObj = $this->serviceRuleMappingMasterRepository->addServiceRuleMappingMaster($serviceRuleMappingMaster, $extraArray, $this->ruleType);

            if ($serviceRuleMappingMasterObj == null) {
                return array('error_message' => $this->translatorService->trans('admin.service_group_management.rule_master.rule_master_blank'));
            } else {
                if ($rulesIdAry && is_array($rulesIdAry) && count($rulesIdAry) > 0) {
                    $this->serviceRuleMappingRulesRepository
                            ->editServiceRuleMappingRulesMasterId($rulesIdAry, $serviceRuleMappingMasterObj->getId());

                    $ruleMappingRule = $this->serviceRuleMappingRulesRepository->find($rulesIdAry[0]);
                    if ($ruleMappingRule) {
                        $this->removeExistingRuleMappingCondition($ruleMappingRule->getId());
                        $this->setRuleCondition($ruleMappingRule, $ruleCondition['rules'], $ruleCondition['condition']);
                    }
                }

                $serviceRuleMappingColumnQtyRepository = $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleMappingColumnQty')
                                                    ->setProjectSetting($this->projectSetting);

                if ($serviceRuleMappingMasterObj->getIsColumnQty()) {
                    foreach ($dataAry['column_wise_amount'] as $columnNo => $columnWiseAmount) {
                        if ($columnWiseAmount != '') {
                            if ($dataAry['column_wise_id'][$columnNo] && $dataAry['column_wise_id'][$columnNo] > 0) {
                                $serviceRuleMappingColumnQty = $serviceRuleMappingColumnQtyRepository->find($dataAry['column_wise_id'][$columnNo]);
                            } else {
                                $serviceRuleMappingColumnQty = new ServiceRuleMappingColumnQty();
                            }
                            $serviceRuleMappingColumnQty->setServiceRuleMappingId($serviceRuleMappingMasterObj);
                            $serviceRuleMappingColumnQty->setColumnNo($columnNo);
                            $serviceRuleMappingColumnQty->setColumnAmount($columnWiseAmount);
                            $serviceRuleMappingColumnQty->setColumnDiscountCode($dataAry['column_wise_amount_code'][$columnNo]);

                            $serviceRuleMappingColumnQtyRepository->addServiceRuleMappingColumnQty($serviceRuleMappingColumnQty);
                            unset($serviceRuleMappingColumnQty);
                        }
                    }
                } else {
                    $serviceRuleMappingColumnQtyRepository->removeColumnQty($serviceRuleMappingMasterObj);
                }

                return true;
            }
        } else {
            return $ruleErrors;
        }
    }


    /**
     * @author Employee Id: 4589
     * Description : Set Rule Mapping
     *
     * @param 1 : Form
     * @param 2 : Culture Id
     *
     * @return type : Messages
     *
     * @throws Exception: Null
     */
    public function setChargesRuleMapping($form)
    {
        $ruleErrors = null;

        $dataAry = $this->request->request->all();

        if (!isset($dataAry['mapping_rule_id']) || (int) $dataAry['mapping_rule_id'] <= 0 || $dataAry['mapping_rule_id']=='') {
            $ruleErrors = array('rules' => 'Please add at-least one Rule.');
        }

        if (isset($dataAry['has_rule_cond_error']) && $dataAry['has_rule_cond_error'] == 'true') {
            $ruleErrors['rules'] = $this->translatorService->trans('admin.service_group_management.rule_mapping.rule_condition_error');
        } elseif (!isset($dataAry['rule_condition']) || trim($dataAry['rule_condition']) == null) {
            $ruleErrors['rules'] = $this->translatorService->trans('admin.service_group_management.rule_mapping.rule_condition_blank_error');
        } elseif (isset($dataAry['rule_condition']) && isset($dataAry['rules'])) {
            $ruleConditionAry = null;
            $rule_condition = (isset($dataAry['rule_condition']) ? $dataAry['rule_condition'] : '');
            $rule_condition = explode('=', $rule_condition);
            $ruleConditionAry = array('condition' => $rule_condition[1],'rules' => $dataAry['rules']);
            if (is_array($ruleErrors)) {
                $ruleErrors = array_merge($ruleErrors, $this->validateRules($dataAry['rules'], 'mapping'));
            } else {
                $ruleErrors = $this->validateRules($dataAry['rules'], 'mapping');
            }
        }


        if ($form->isValid() && $ruleErrors === null) {
            $rulesIdAry = array($dataAry['mapping_rule_id']);

            $serviceRuleMappingMaster = $form->getData();
            $extraArray = array();
            $extraArray['rule_master_id'] = $dataAry['rule_master_id'];
            $extraArray['mapping_rule_id'] = $dataAry['mapping_rule_id'];
            $extraArray['serviceRuleMappingGroupId'] = $form->get('serviceRuleMappingGroupId')->getData();
            $serviceRuleChargesEquationMaster = $serviceRuleMappingMaster->getServiceRuleChargesEquationId();

            foreach ($serviceRuleChargesEquationMaster as $index=>$serviceRuleChargesEquation) {
                $serviceRuleChargesEquation->setCreatedUid($this->userId);
                $serviceRuleChargesEquation->setUpdatedUid($this->userId);
                   // $serviceRuleChargesEquation->setServiceRuleMappingId($serviceRuleMappingId);

                    if ($serviceRuleChargesEquation->getId()) {
                        $this->serviceRuleChargesEquationRepository->removeServiceRuleChargesEquation($serviceRuleChargesEquation);
                    }
            }
            $data['rule_condition'] = null;
            $rule_condition = (isset($dataAry['rule_condition']) ? $dataAry['rule_condition'] : '');
            if (isset($dataAry['rules'])) {
                $rule_condition = explode('=', $rule_condition);
                $data['rule_condition'] = array('condition' => $rule_condition[1],'rules' => $dataAry['rules']);
            }

            $ruleCondition = isset($data['rule_condition']) ? ($data['rule_condition']) : '';

            $serviceRuleMappingMasterObj = $this->serviceRuleMappingMasterRepository->addServiceRuleMappingMaster($serviceRuleMappingMaster, $extraArray, $this->ruleType);
            if ($serviceRuleMappingMasterObj == null) {
                return array('error_message' => $this->translatorService->trans('admin.service_group_management.rule_master.rule_master_blank'));
            } else {
                if ($rulesIdAry && is_array($rulesIdAry) && count($rulesIdAry) > 0) {
                    $this->serviceRuleMappingRulesRepository
                        ->editServiceRuleMappingRulesMasterId($rulesIdAry, $serviceRuleMappingMasterObj->getId());

                    $ruleMappingRule = $this->serviceRuleMappingRulesRepository->find($rulesIdAry[0]);
                    if ($ruleMappingRule) {
                        $this->removeExistingRuleMappingCondition($ruleMappingRule->getId());
                        $this->setRuleCondition($ruleMappingRule, $ruleCondition['rules'], $ruleCondition['condition']);
                    }
                }

                $serviceRuleMappingColumnQtyRepository = $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleMappingColumnQty')
                    ->setProjectSetting($this->projectSetting);
                $i = 0;
                foreach ($serviceRuleChargesEquationMaster as $index=>$serviceRuleChargesEquation) {
                    if ($serviceRuleChargesEquation->getIsColumnQty()) {
                        $serviceRuleChargesEquation->setAmount(null);
                    }
                    $serviceRuleChargesEquationObj = $this->serviceRuleChargesEquationRepository->addServiceRuleChargesEquation($serviceRuleChargesEquation, $serviceRuleMappingMasterObj);

                    if ($serviceRuleChargesEquation->getIsColumnQty()) {
                        foreach ($dataAry['column_wise_amount'] as $columnNo => $columnWiseAmount) {
                            if ((int)$columnWiseAmount[$i] > 0) {
                                if ($dataAry['column_wise_id'][$columnNo][$i] && $dataAry['column_wise_id'][$columnNo][$i] > 0) {
                                    $serviceRuleMappingColumnQty = $serviceRuleMappingColumnQtyRepository->find($dataAry['column_wise_id'][$columnNo][$i]);
                                } else {
                                    $serviceRuleMappingColumnQty = new ServiceRuleMappingColumnQty();
                                }
                                $serviceRuleMappingColumnQty->setServiceRuleMappingId($serviceRuleMappingMasterObj);
                                $serviceRuleMappingColumnQty->setColumnNo($columnNo);
                                $serviceRuleMappingColumnQty->setColumnAmount($columnWiseAmount[$i]);
                                $serviceRuleMappingColumnQty->setColumnDiscountCode($dataAry['column_wise_amount_code'][$columnNo][$i]);

                                $serviceRuleMappingColumnQtyRepository->addServiceRuleMappingColumnQty($serviceRuleMappingColumnQty);
                                unset($serviceRuleMappingColumnQty);
                            }
                        }
                    } else {
                        $serviceRuleMappingColumnQtyRepository->removeColumnQty($serviceRuleMappingMasterObj);
                    }
                    $i++;
                }
                return true;
            }
        } else {
            return $ruleErrors;
        }
    }

    public function editRuleMapping($form)
    {
        $dataAry = $this->request->request->all();
        $ruleId = $this->request->get('id');
        $ruleErrors = null;
        if (isset($dataAry['has_rule_cond_error']) && $dataAry['has_rule_cond_error'] == 'true') {
            $ruleErrors['rule-condition'] = $this->translatorService->trans('admin.service_group_management.rule_mapping.rule_condition_error');
        } elseif (!isset($dataAry['rule_condition']) || trim($dataAry['rule_condition']) == null) {
            $ruleErrors['rule-condition'] = $this->translatorService->trans('admin.service_group_management.rule_mapping.rule_condition_blank_error');
        } elseif (isset($dataAry['rule_condition']) && isset($dataAry['rules'])) {
            $ruleConditionAry = null;
            $rule_condition = (isset($dataAry['rule_condition']) ? $dataAry['rule_condition'] : '');
            $rule_condition = explode('=', $rule_condition);
            $ruleConditionAry = array('condition' => $rule_condition[1],'rules' => $dataAry['rules']);
            if (is_array($ruleErrors)) {
                $ruleErrors = array_merge($ruleErrors, $this->validateRules($dataAry['rules'], 'mapping'));
            } else {
                $ruleErrors = $this->validateRules($dataAry['rules'], 'mapping');
            }
        }

        if ($ruleErrors === null) {
            $data['rule_condition'] = null;
            $rule_condition = (isset($dataAry['rule_condition']) ? $dataAry['rule_condition'] : '');
            if (isset($dataAry['rules'])) {
                $rule_condition = explode('=', $rule_condition);
                $data['rule_condition'] = array('condition' => $rule_condition[1],'rules' => $dataAry['rules']);
            }

            $ruleCondition = isset($data['rule_condition']) ? ($data['rule_condition']) : '';

            if ($ruleId && $ruleCondition != '' && count($ruleCondition) > 0) {
                $ruleMasterObj = $form->getData()->getRuleMapMasterId()->first();

                if ($ruleMasterObj == null) {
                    $this->returnData = array('error_message' => $this->translatorService->trans('admin.service_group_management.rule_mapping.no_rules_added'));
                    $this->returnStatusCode = 400;
                } else {
                    if ($ruleCondition != null) {
                        $this->removeExistingRuleMappingCondition($ruleId);
                        $this->setRuleCondition($ruleMasterObj, $ruleCondition['rules'], $ruleCondition['condition']);
                    }

                    //$this->getMappingRulesByRuleMasterId($ruleId);

                    return true;
                }
            } else {
                return  array('error_message' => $this->translatorService->trans('admin.service_group_management.rule_mapping.blank_id_data'));
            }
        }

        return $ruleErrors;
    }

    /**
     * @author Employee Id: 4589
     * Description : Copy Rule Mapping Master
     *
     * @param 1 : Service Group Id
     *
     * @return type : Boolean
     *
     * @throws Exception: Null
     */
    public function copyRuleMappingMaster()
    {
        $id = $this->request->get('service_group_id');
        if ($id) {
            $serviceRuleMappingMaster = $this->serviceRuleMappingMasterRepository->find($id);
            if ($serviceRuleMappingMaster) {
                $make_copy_country = $this->request->request->get('make_copy_country');
                $make_copy_status = $this->request->request->get('make_copy_status');

                foreach ($make_copy_country as $countryId => $value) {
                    if (isset($make_copy_status[$countryId])) {
                        $this->makeCopyRuleMappingMaster(clone $serviceRuleMappingMaster, $countryId, true);
                    } else {
                        $this->makeCopyRuleMappingMaster(clone $serviceRuleMappingMaster, $countryId, false);
                    }
                }

                // commit persist objects if any
                $this->serviceRuleMappingMasterRepository->commit();
            }

            return true;
        }

        return false;
    }

    /**
     * @author Employee Id: 4589
     * Description : Make copy of Rule mapping master
     *
     * @param 1 : Service Rule Mapping Master
     * @param 2 : country Id
     * @param 3 : isActive
     *
     * @return type : NULL
     *
     * @throws Exception: Null
     */
    public function makeCopyRuleMappingMaster($serviceRuleMappingMaster, $countryId, $isActive)
    {
        $serviceRuleMappingMaster->setId(null);

        if ($countryId) {
            $serviceRuleMappingMaster->setIsActive($isActive);
            $serviceRuleMappingMaster->setCultureId($countryId);
            $serviceRuleMappingMaster->setGroupId(null);
            $serviceRuleMappingMaster->setServiceId(null);

            $this->serviceRuleMappingMasterRepository->copyRuleMappingMaster($serviceRuleMappingMaster);
        }
    }

    /**
     * @author Employee Id: 4589
     * Description : Update Rule Mapping
     *
     * @param 1 : form
     * @param 2 : Rule Mapping Id
     * @param 3 : culture
     *
     * @return type : boolean or error messages
     *
     * @throws Exception: Null
     */
    public function updateRuleMapping($form, $id, $culture)
    {
        $ruleMappingRepo = $this->serviceRuleMappingMasterRepository;
        $rulesError = null;

        $dataAry = $this->request->request->all();

        if (!isset($dataAry['mapping_rule_id']) || !is_array($dataAry['mapping_rule_id']) || count($dataAry['mapping_rule_id']) <= 0) {
            $rulesError = array('rules' => $this->translatorService->trans('admin.service_group_management.rule_mapping.rule_condition_blank_error'));
        }

        if ($form->isValid() && $rulesError === null) {
            $data = array();

            $cultureId = $form->get('cultureId')->getData();
            $groupId = $form->get('groupId')->getData();
            $serviceId = $form->get('serviceId')->getData();
            $status = $dataAry['service_group_data']['isActive'];
            $rulesIdAry = $dataAry['mapping_rule_id'];

            if ($id && $groupId && $serviceId) {
                $ruleMasterObj = $ruleMappingRepo->editServiceRuleMappingMaster($id, $groupId, $serviceId, $status);

                if ($ruleMasterObj == null) {
                    return array('error_message' => $this->translatorService->trans('admin.service_group_management.rule_master.rule_master_blank'));
                } else {
                    if ($rulesIdAry && is_array($rulesIdAry) && count($rulesIdAry) > 0) {
                        $this->serviceRuleMappingRulesRepository
                        ->editServiceRuleMappingRulesMasterId($rulesIdAry, $ruleMasterObj->getId());
                    }

                    return true;
                }
            } else {
                return array('error_message' => $this->translatorService->trans('admin.service_group_management.rule_mapping.blank_data'));
            }
        } else {
            return $rulesError;
        }
    }

    /**
     * @author Employee Id: 4589
     * Description : Set Rule Condition
     *
     * @param 1 : Master Id
     * @param 1 : Rule Array
     * @param 1 : Codition
     * @param 1 : Parent Id
     * @param 1 : Counter
     *
     * @return type : Null
     *
     * @throws Exception: Null
     */
    public function setRuleCondition($masterIdObj, $ruleArray, $condOp, $parentId = 0, &$counter = 0)
    {

        //*** Add into rule_main_condition
        $ruleMasterMainCondObj = $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleMappingMainConditions')
                                                ->addServiceRuleMappingMainCondition($masterIdObj, $parentId, $condOp);

        foreach ($ruleArray as $rule) {
            if (isset($rule['rules'])) {
                $this->setRuleCondition($masterIdObj, $rule['rules'], $rule['condition'], $ruleMasterMainCondObj->getId(), $counter);
            } else {
                ++$counter;

                    //*** Add into rule_inner_condition
                    $ruleMasterInnerCond = $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleMappingInnerConditions')
                                                            ->addServiceRuleMappingInnerCondition($ruleMasterMainCondObj, $rule['field'], $rule['operator'], $rule['value'], $counter);
            }
        }
    }


    /**
     * @author Employee Id: 4589
     * Description : Check Service rule Master exist
     *
     * @param 1 : Rule Master Id
     *
     * @return type : ServiceRuleMasterRule| NULL
     *
     * @throws Exception: Null
     */
    public function CheckRuleExists($id)
    {
        return $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceRuleMaster')->CheckRuleExists($id);
    }

    /**
     * @author Employee Id: 4589
     * Description : Add Service rule mapping rules
     *
     * @param 1 : Mapping Id
     * @param 1 : Rule Master Id
     * @param 1 : Start Date
     * @param 1 : End Date
     *
     * @return type : serviceRuleMapRules
     *
     * @throws Exception: Null
     */
    public function addServiceRuleMappingRules($ruleMappingId, $ruleMasterId)
    {
        $RuleMappRules = $this->serviceRuleMappingRulesRepository->addServiceRuleMappingRules($ruleMappingId, $ruleMasterId);

        $this->removeExistingRuleMappingCondition($RuleMappRules->getId());
        $this->addRuleConditionFromRuleMaster($ruleMasterId, $RuleMappRules);

        //return $this->getMappingRulesByRuleMasterId($RuleMappRules->getId());
        return $this->getMappingRulesById($RuleMappRules->getId());
    }

    /**
     * @author Employee Id: 4589
     * Description : Get Mapping Rules by Rule master Id
     *
     * @param 1 : Rule Master Id
     *
     * @return type : ServiceRuleMa
     *
     * @throws Exception: Null
     */
    public function getMappingRulesByRuleMasterId($id)
    {
        return $this->serviceRuleMappingRulesRepository->getMappingRulesByRuleMasterId($id);
    }

    /**
     * @author Employee Id: 4589
     * Description : Get Mapping Rules by Rule Id
     *
     * @param 1 : Rule Id
     *
     * @return type : ServiceRuleMappingRules
     *
     * @throws Exception: Null
     */
    public function getMappingRulesById($ruleId)
    {
        return $this->serviceRuleMappingRulesRepository->getMappingRulesById($ruleId);
    }

    /**
     * @author Employee Id: 4589
     * Description : Delete rule mapping rules
     *
     * @param 1 : Rule Mapping Rules Id
     *
     * @return type : boolean
     *
     * @throws Exception: Null
     */
    public function deleteRuleMappingRules($ruleMappingRulesId)
    {
        return $this->serviceRuleMappingRulesRepository->deleteRuleMappingRules($ruleMappingRulesId);
    }

    /**
     * @author Employee Id: 4589
     * Description : Get service group list by culture
     *
     * @param 1 : Culture Id
     *
     * @return type : Service group list
     *
     * @throws Exception: Null
     */
    public function getServiceGroupListByCulture($culture_id)
    {
        return $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:Service')->getServiceGroupListByCulture($culture_id);
    }

    /**
     * @author Employee Id: 4589
     * Description : Get Mapping Rules by Mapping master Id
     *
     * @param 1 : Mapping Master Id
     *
     * @return type : ServiceRuleMappingRulesObj|null
     *
     * @throws Exception: Null
     */
    public function getMappingRulesByMappingMasterId($mappingMasterId)
    {
        return $this->serviceRuleMappingRulesRepository->getMappingRulesByMappingMasterId($mappingMasterId);
    }

    /**
     * @author Employee Id: 4589
     * Description : Edit service rule mapping rules
     *
     * @param 1 : Rule Id
     * @param 2 : Start Date
     * @param 3 : End Date
     *
     * @return type : ServiceRuleMappingRules
     *
     * @throws Exception: Null
     */
    public function editServiceRuleMappingRules($id)
    {
        return $this->serviceRuleMappingRulesRepository->editServiceRuleMappingRules($id);
    }

    /**
     * @author Employee Id: 4589
     * Description : Save price in client db
     *
     * @param 1 : products
     *
     * @return type : true or false
     *
     * @throws Exception: Null
     */
    public function setServiceRuleProductPrice($products)
    {
        if ($products && isset($this->ruleMappingMaster)) {
            $serviceGroupArray = $this->ruleMappingMaster->getServiceRuleMappingGroupId();
            $isDefaultGroup = false;

            //check is supplier or association
            $isDiscountCodeApply = ($this->configurationRule['option']['apply_code_on_product_detail']['status']==1) ? true : false;
            
            $discountCodes = array();//EMP4464: Added this line because of variable not found error.

            if ($isDiscountCodeApply) {
                //get discount code list from API
                $discountCodes = $this->getDiscountCodeArray();
                $isMaxDiscountCodeApply = !$this->ruleMappingMaster->getIsDiscountOnCode();
            }

            $userData = $this->request->get('project_user_setting');

            //get products
            $returnOwnerProductArray = array();
            foreach ($products as $product_index=>$product) {
                $product_id = $product['product_id'];
                $skipGroupArray = array();

                if ($serviceGroupArray->count() > 0) {
                    //get service group for checking priority
                    foreach ($serviceGroupArray as $index=>$serviceGroup) {
                        if ($this->serviceRuleProductPriceRepository->countByProductIdAndGroupLowPriority($product_id, $serviceGroup->getServiceGroupId()->getId(), $this->ruleMappingMaster->getPriority()) > 0) {
                            //remove entry if exists
                            $this->serviceRuleProductPriceRepository->removeByProductId($product_id, $serviceGroup->getServiceGroupId()->getId());
                        }
                        //remove entry if exists with same priority for another groups
                        $this->serviceRuleProductPriceRepository->removeProductByPriority($this->ruleMappingMaster->getPriority(), $product_id);

                        if ($this->serviceRuleProductPriceRepository->countByProductIdAndGroupHeighPriority($product_id, $serviceGroup->getServiceGroupId()->getId(), $this->ruleMappingMaster->getPriority()) > 0) {
                            $skipGroupArray[] = $serviceGroup->getServiceGroupId()->getId();
                        }
                        if ($serviceGroup->getServiceGroupId()->getIsDefault()) {
                            $isDefaultGroup = true;
                        }
                    }
                }

                $newColumnQtyArray = array();

                if ($this->ruleMappingMaster->getServiceRuleMappingQtyId() && $this->ruleMappingMaster->getServiceRuleMappingQtyId()->count() > 0) {
                    $columnQtyArray = $this->ruleMappingMaster->getServiceRuleMappingQtyId();

                    if ($columnQtyArray && is_object($columnQtyArray)) {
                        foreach ($columnQtyArray as $columnQty) {
                            $newColumnQtyArray[$columnQty->getColumnNo()] = $columnQty;
                        }
                    }
                }

                $returnProductArray[$product_index]['product_id'] = $product_id;
                //for infinite loop for any number of qty
                if (isset($product['rule_eqp']) && $product['rule_eqp']) {
                    for ($i = 1;; $i ++) { //start infinite loop
                        if (isset($product ['min_qty_' . $i])) {
                            $eqpPrice = $product ['price_' . $i]; //get last column price
                        } else {
                            break;
                        }
                    }
                }
                //check is price matrix apply
                $isPriceMatrixApply = (isset($product['matrix_details']) && isset($product['matrix_details']['price']) && count($product['matrix_details']['price']['values']) > 0 && $this->configurationRule['option']['apply_matrix']['status']==1) ? true : false;

                for ($i = 1;; $i ++) { //start infinite loop
                    if (isset($product ['min_qty_' . $i])) {
                        //replace all column price with last column price if EQP true
                        if (isset($product['rule_eqp']) && isset($eqpPrice)) {
                            $product ['price_' . $i] = $eqpPrice;
                        }

                        $oldPrice = $newRate = $product ['price_' . $i]; // $product ['min_qty_' . $i];
                        $priceData = $this->calculateProductRulePrice($product, $i, $this->ruleMappingMaster, $discountCodes, $newColumnQtyArray, $product['price_' . $i], $product['code_' . $i], $product['min_qty_' . $i]);
                        $product ['price_' . $i] = $priceData['productPrice'];
                        $product ['code_' . $i] = $priceData['productCode'];



                        if ($oldPrice != $product ['price_' . $i]) {
                            if ($serviceGroupArray->count() > 0) {
                                // Apply price matrix if any
                                /*if(isset($priceMatrixRate) && $priceMatrixRate > 0){
                                $productPrice = $productPrice * $priceMatrixRate;
                                }*/

                                //get service group
                                foreach ($serviceGroupArray as $index=>$serviceGroup) {
                                    if (in_array($serviceGroup->getServiceGroupId()->getId(), $skipGroupArray)) {
                                        continue;
                                    }

                                    $serviceRuleProductPrice = new ServiceRuleProductPrice();
                                    $serviceRuleProductPrice->setProductId($product_id);
                                    $serviceRuleProductPrice->setFromQty($product ['min_qty_' . $i]);
                                    $serviceRuleProductPrice->setToQty($product ['max_qty_' . $i]);
                                    $serviceRuleProductPrice->setCode($product ['code_' . $i]);
                                    $serviceRuleProductPrice->setPrice($product ['price_' . $i]);
                                    $serviceRuleProductPrice->setPriority($this->ruleMappingMaster->getPriority());
                                    $serviceRuleProductPrice->setExpiredAt($this->ruleMappingMaster->getEndDate());

                                    $serviceRuleProductPrice->setServiceGroupId($serviceGroup->getServiceGroupId()->getId());

                                    $this->serviceRuleProductPriceRepository->set($serviceRuleProductPrice);

                                    if ($isDefaultGroup && //$this->instanceType == "supplier" &&
                                                $userData && isset($userData['user_data']) && is_object($userData['user_data']) && isset($product['supplier_id']) &&
                                                $userData['user_data']->getObCustomerId() == $product['supplier_id']) {
                                        $returnOwnerProductArray[$product_index]['user_group_pricing'][$serviceGroup->getServiceGroupId()->getId()][$i] =  array(
                                                        'from' => $product ['min_qty_' . $i],
                                                        'to' => $product ['max_qty_' . $i],
                                                        'code' => $product ['code_' . $i],
                                                        'rate' => $product ['price_' . $i],
                                                        'priority' => $this->ruleMappingMaster->getPriority(),
                                                        'expired_at' => $this->ruleMappingMaster->getEndDate()
                                                );
                                    }
                                }
                            }
                        }
                    } else {
                        //if nomore qty than break infinite loop
                                                        break;
                    }
                } //end infinite loop

                $this->serviceRuleProductPriceRepository->commit();
                $this->serviceRuleProductPriceRepository->clear();

                // update product in all solr core defined in localization_to_fetch config
                $localizationArray = $this->getLocalization();
                if ($localizationArray && !empty($localizationArray)) {
                    foreach ($localizationArray as $localization) {
                        exec("php ../app/console office_brain:solr:sync:product --culture=".$localization." --productId=".$product_id."  --projectId=".$this->projectSetting['project_id']." --instanceId=".$this->instanceId." &");
                    }
                }
            }
            return $returnOwnerProductArray;
        }
        return false;
    }

    
    /**
     * @author Employee Id: 4589
     * Description : create chunk of all products array
     *
     * @param 1 : products
     *
     * @return type : true or false
     *
     * @throws Exception: Null
     */
    public function setServiceRuleProductPriceMain($mappingType, $outputArray){
    
    	$productUpdateArrayAll = $productUpdateArray = array();
    	
    	foreach ($outputArray as $out){
    		if($mappingType=='charges')
    			$productUpdateArray = $this->setServiceRuleChargeProductPrice($out);
    		
    		elseif($mappingType=='catalogue'){    			
    			$productUpdateArray = $this->setServiceRuleProductPrice($out);
    			$productUpdateArrayAll = array_merge($productUpdateArrayAll, $productUpdateArray);
    		}
    	}
    	$this->serviceRuleChargeProductPriceRepository->commit();
    	$this->serviceRuleChargeProductPriceRepository->clear();
    	    	
    	//TODO: Check is product owner and default group assign, Currently all product update in API
	    if ($mappingType=='catalogue' && $productUpdateArrayAll && !empty($productUpdateArrayAll)) {
	    	$response = $this->serviceContainer->get('office_brain_product_admin_manager')->editProductGroupPrice(array("products"=>$productUpdateArray));
	    }
	    return $productUpdateArray;
    		/*for($i=0;;$i++){
    		
    			$this->request->query->set('per_page', 50);
    			$this->request->query->set('page', $i+1);
    		
    			$productArray = $ruleMappingArray = array();
    			$searchProducts = $this->serviceContainer->get('office_brain_search_manager')->searchResult($form->getData(), true);
    		
    			$tmpProductArray = array();
    			foreach ($searchProducts['search_result_array']['data'] as $searchProduct) {
    				//$searchProduct['rule_eqp'] = (isset($searchQuery['search']['is_eqp']) && $searchQuery['search']['is_eqp']) ? true : false ;
    				$tmpProductArray[$searchProduct['product_id']] = $searchProduct;
    			}
    			//$ruleMappingArray = array_merge($productArray,$searchProducts['search_result_array']['data']);
    		
    			$ruleMappingArray[$searchQuery['search']['rule_mapping_id']] = array(
    					"main_condition"=>$searchQuery['search']['main_search_type'],
    					"products"=>$tmpProductArray
    			);
    			$productArray[$searchQuery['search']['rule_mapping_id']] = $searchQuery['search']['rule_mapping_parent_id'];
    		
    			// 		    		echo "<pre>",print_r(array_keys($products['search_result_array']));
    			// 		    		echo "<br />",$products['search_result_array']['totalCount'];
    			// 		    		echo "<br />",count($products['search_result_array']['data']);
    			// 		    		exit;
    		
    			krsort($productArray, SORT_NUMERIC);
    			$newProductArray = array();
    		
    			foreach ($productArray as $ruleMappingId=>$ruleMappingParentId) {
    				$main_condition = ($ruleMappingParentId > 0) ? $ruleMappingArray[$ruleMappingParentId]['main_condition'] : $ruleMappingArray[$ruleMappingId]['main_condition'];
    				if ($ruleMappingParentId > 0) {
    					if (empty($newProductArray)) {
    						$newProductArray = $ruleMappingArray[$ruleMappingId]['products'];
    					} elseif ($main_condition == "AND") {
    						$newProductArray = array_merge($newProductArray, array_intersect_key($ruleMappingArray[$ruleMappingParentId]['products'], $ruleMappingArray[$ruleMappingId]['products']));
    					} else {
    						$newProductArray = array_merge($newProductArray, $ruleMappingArray[$ruleMappingId]['products']);
    					}
    				} else {
    					$newProductArray = array_merge($newProductArray, $ruleMappingArray[$ruleMappingId]['products']);
    				}
    			}
    		
    			$newProductArray = array_map("unserialize", array_unique(array_map("serialize", $newProductArray)));
    		
    			$productUpdateArray = $this->setServiceRuleChargeProductPrice($newProductArray);
    		
    			if(($i+1) == $searchProducts['search_result_array']['data']['last']){
    				echo ($i+1) ,'==', $searchProduct['last'];
    				break;
    			}
    		
    		}*/
    	
    }

    /**
     * @author Employee Id: 4589
     * Description : Save charge price in client db
     *
     * @param 1 : products
     *
     * @return type : true or false
     *
     * @throws Exception: Null
     */
    public function setServiceRuleChargeProductPrice($products)
    {
        if ($products && isset($this->ruleMappingMaster)) {
            $serviceGroupArray = $this->ruleMappingMaster->getServiceRuleMappingGroupId();

            //get products
            $returnProductArray = array();
            foreach ($products as $product_index=>$product) {
                $product_id = $product['product_id'];
                $skipGroupArray = array();

                if ($serviceGroupArray->count() > 0) {
                    //get service group for checking priority
                    foreach ($serviceGroupArray as $index=>$serviceGroup) {
                        if ($this->serviceRuleChargeProductPriceRepository->countByProductIdAndGroupLowPriority($product_id, $serviceGroup->getServiceGroupId()->getId(), $this->ruleMappingMaster->getPriority(), $this->ruleMappingMaster->getChargesType()) > 0) {
                            //remove entry if exists
                            $this->serviceRuleChargeProductPriceRepository->removeByProductId($product_id, $serviceGroup->getServiceGroupId()->getId(), $this->ruleMappingMaster->getChargesType());
                        }
                        //remove entry if exists with same priority for another groups
                        $this->serviceRuleChargeProductPriceRepository->removeProductByPriority($this->ruleMappingMaster->getPriority(), $this->ruleMappingMaster->getChargesType(), $product_id);

                        if ($this->serviceRuleChargeProductPriceRepository->countByProductIdAndGroupHeighPriority($product_id, $serviceGroup->getServiceGroupId()->getId(), $this->ruleMappingMaster->getPriority(), $this->ruleMappingMaster->getChargesType()) > 0) {
                            $skipGroupArray[] = $serviceGroup->getServiceGroupId()->getId();
                        }
                    }
                }


                if ($serviceGroupArray->count() > 0) {

                    //get service group
                    foreach ($serviceGroupArray as $index=>$serviceGroup) {
                        if (in_array($serviceGroup->getServiceGroupId()->getId(), $skipGroupArray)) {
                            continue;
                        }

                        $serviceRuleChargeProductPrice = new ServiceRuleChargeProductPrice();
                        $serviceRuleChargeProductPrice->setProductId($product_id);
                        $serviceRuleChargeProductPrice->setRuleMappingId($this->ruleMappingMaster);
                        $serviceRuleChargeProductPrice->setChargeType($this->ruleMappingMaster->getChargesType());
                        $serviceRuleChargeProductPrice->setPriority($this->ruleMappingMaster->getPriority());

                        $serviceRuleChargeProductPrice->setServiceGroupId($serviceGroup->getServiceGroupId()->getId());

                        $this->serviceRuleChargeProductPriceRepository->set($serviceRuleChargeProductPrice);
                    }
                }
            }
            
            return true;
        }
        return false;
    }


    /**
     * @author Employee Id: 4835
     * Description : check valid or not which you entered priority.
     *
     * @param 1 : $countryId country id
     *
     * @param 2 : $priority  priority number
     *
     * @param 3: $id rule mapping id
     *
     * @return type : count of exsisting priority
     *
     * @throws Exception: Null
     */

    public function checkvalidPriority($countryId, $priority, $id)
    {
        return $this->serviceRuleMappingMasterRepository->findExistPriority($countryId, $priority, $this->getRuleType(), $id);
    }
}
