<?php

namespace OfficeBrain\Bundle\ServiceGroupBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use OfficeBrain\Bundle\CoreBundle\CustomeHandler as FormErrorManager;
use Symfony\Component\HttpFoundation\JsonResponse;
use OfficeBrain\Bundle\ServiceGroupBundle\Form\ServiceChargesRuleMappingType;
use OfficeBrain\Bundle\ServiceGroupBundle\Entity\ServiceRuleMappingMaster;
use OfficeBrain\Bundle\SearchBundle\Form\Data\ProductSearchData;
use OfficeBrain\Bundle\SearchBundle\Form\Type\ProductSearchType;

/**
 * This class for base functionality related to charges rule mapping with Group.
 *
 * @author Office Brain - 4072
 * @Route("/admin/{_locale}/charges/rule-mapping",
 * defaults={"rule_service"="rule_mapping"})
 */
class ChargesRuleMappingAdminController extends Controller
{
    protected $request;
    protected $session;
    protected $formErrorManager;
    protected $conditionAry;
    protected $cultureList;
    protected $ruleKeyNameAry;
    protected $actionTypes;
    protected $actionLimitPer;
    protected $actionRuleTypes;
    protected $actionChargeTypes;
    protected $actionAmountTypes;
    protected $ruleMasterManager;
    protected $projectSetting;
    protected $responseArray;
    protected $translator;
    protected $serviceGroupServiceManager;
    protected $ruleType;
    protected $OBCommon;

    /**
     * @author Employee Id: 4589
     * Description : set value as null.
     *
     * @param 1 : No parameter
     *
     * @return type : No return type.
     *
     * @throws Exception: No exception
     * */
    public function __construct()
    {
        $this->request = null;
        $this->entityManager = null;
        $this->session = null;
        $this->apiClient = null;
        $this->formErrorManager = new FormErrorManager\JsonError();
        $this->conditionAry = null;
        $this->cultureList = null;
        $this->isRuleMapping = false;
        $this->ruleKeyNameAry = null;
        $this->actionTypes = null;
        $this->actionLimitPer = null;
        $this->actionRuleTypes = null;
        $this->actionChargeTypes = null;
        $this->actionAmountTypes = null;
        $this->actionRuleStatus = null;
        $this->serviceGroupRuleManager = null;
        $this->projectSetting = null;
        $this->responseArray = array();
        $this->translator = null;
        $this->ruleType = null;
        $this->OBCommon = null;
    }

    /**
     * @author Employee Id: 4589
     * Description : unset value.
     *
     * @param 1 : No parameter
     *
     * @return type : No return type.
     *
     * @throws Exception: No exception
     * */
    public function __destruct()
    {
        unset($this->request);
        unset($this->entityManager);
        unset($this->session);
        unset($this->apiClient);
        unset($this->formErrorManager);
        unset($this->conditionAry);
        unset($this->cultureList);
        unset($this->isRuleMapping);
        unset($this->ruleKeyNameAry);
        unset($this->actionTypes);
        unset($this->actionLimitPer);
        unset($this->actionRuleTypes);
        unset($this->actionChargeTypes);
        unset($this->actionAmountTypes);
        unset($this->actionRuleStatus);
        unset($this->serviceGroupRuleManager);
        unset($this->projectSetting);
        unset($this->responseArray);
        unset($this->translator);
        unset($this->serviceGroupServiceManager);
        unset($this->ruleType);
        unset($this->OBCommon);
    }

    /**
     * @author Employee Id: 4589
     * Description : initialize value.
     *
     * @param 1 : No parameter
     *
     * @return type : No return type.
     *
     * @throws Exception: No exception
     * */
    public function initAction()
    {
        $this->request = $this->getRequest();
        $this->ruleType = 'charges';

        $this->entityManager = $this->getDoctrine()->getManager();
        $this->projectSetting = $this->request->get('project_setting');
        $this->OBCommon = $this->get('office_brain_core_manager');
        $this->session = $this->request->getSession();
        $this->formErrorManager = new FormErrorManager\JsonError();
        $this->serviceGroupRuleManager = $this->get('office_brain_service_group_rule_manager');
        $this->serviceGroupRuleManager->setRuleType($this->ruleType);

        $this->conditionAry = $this->serviceGroupRuleManager->getConditionArray($this->ruleType);
        $this->cultureList = $this->serviceGroupRuleManager->getCultureList();
        $this->ruleKeyNameAry = $this->serviceGroupRuleManager->setRuleKeyNameArray(true);
        $this->actionTypes = $this->serviceGroupRuleManager->getActionTypes();
        $this->actionLimitPer = $this->serviceGroupRuleManager->getActionLimitPer();
        $this->actionRuleTypes = $this->serviceGroupRuleManager->getActionRuleTypes();
        $this->actionChargeTypes = $this->serviceGroupRuleManager->getActionChargeTypes();
        $this->actionAmountTypes = $this->serviceGroupRuleManager->getActionAmountTypes();
        $this->actionRuleStatus = $this->serviceGroupRuleManager->getRuleStatus();
        $this->translator = $this->get('translator');
    }

    /**
     * @author Employee Id: 4589
     * Description : Display charges rule mapping list.
     *
     * @param 1 : Page number
     *
     * @return type : Data.
     *
     * @throws Exception: Null
     *
     * @Route("/list/{page}",
     * name="office_brain_servicegroupbundle_chargesrulemappingadmin_list",
     * requirements={"page"="\d+"},
     * defaults={"page"=1})
     * )
     *
     * @Method({"GET"})
     * @Template()
     */
    public function listAction()
    {
        $this->initAction();

        $this->responseArray = $this->serviceGroupRuleManager->getRuleMappingList();

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4589
     * Description : Display charges rule mapping list using ajax.
     *
     * @param 1 : Record per page
     * @param 2 : Page number
     *
     * @return type : Data.
     *
     * @throws Exception: Null
     *
     *
     * @Route("/list/{page}",
     * name="office_brain_servicegroupbundle_chargesrulemappingadmin_listajax",
     * requirements={"page"="\d+"},
     * defaults={"page"=1})
     * )
     *
     * @Method({"POST"})
     * @Template()
     */
    public function listAjaxAction()
    {
        $this->initAction();

        $this->responseArray = $this->serviceGroupRuleManager->getRuleMappingList();

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4589
     * Description : Add rule mapping form.
     *
     * @param 1 : No parameter
     *
     * @return type : Rule Mapping form
     *
     * @throws Exception: No exception
     *
     * @Route("/add",
     * name="office_brain_servicegroupbundle_chargesrulemappingadmin_add")
     *
     * @Method({"GET"})
     * @Template()
     */
    public function addAction()
    {
        $this->initAction();

        $ruleMappSetDataAry['culture'] = $this->serviceGroupRuleManager->getSelectedCultures();
        $ruleMappSetDataAry['charge_type'] = $this->actionChargeTypes;
        $ruleMappSetDataAry['amount_type'] = $this->actionAmountTypes;
        $ruleMappSetDataAry['rule_status'] = $this->actionRuleStatus;

        $this->form = $this->createForm(new ServiceChargesRuleMappingType($this->container, $ruleMappSetDataAry), new ServiceRuleMappingMaster());
        $this->responseArray['form'] = $this->form->createView();
        $this->responseArray['conditions'] = json_encode(array_values($this->conditionAry));

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4589
     * Description : Submit add rule mapping form.
     *
     * @param 1 : No parameter
     *
     * @return type : Rule Mapping form and data
     *
     * @throws Exception: No exception
     *
     * @Route("/add",
     * name="office_brain_servicegroupbundle_chargesrulemappingadmin_processadd")
     *
     * @Method({"POST"})
     * @Template()
     */
    public function processAddAction()
    {
        $this->initAction();

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

        $countryId = (isset($dataAry['service_group_data']['countryId']) ? $dataAry['service_group_data']['countryId'] : 0);
        $group_id = (isset($dataAry['service_group_data']['serviceRuleMappingGroupId']) ? $dataAry['service_group_data']['serviceRuleMappingGroupId'] : 0);

        $ruleMappSetDataAry['culture'] = $this->serviceGroupRuleManager->getSelectedCultures();
        $ruleMappSetDataAry['charge_type'] = $this->actionChargeTypes;
        $ruleMappSetDataAry['amount_type'] = $this->actionAmountTypes;
        $ruleMappSetDataAry['rule_status'] = $this->actionRuleStatus;
        /*if ($culture_id > 0) {
            $ruleMappSetDataAry['group'] = $this->serviceGroupRuleManager->getServiceGroupListByCulture($countryId);
        }*/

        $this->form = $this->createForm(new ServiceChargesRuleMappingType($this->container, $ruleMappSetDataAry), new ServiceRuleMappingMaster());

        $this->form->handleRequest($this->request);

        if (!is_array($rulesError = $this->serviceGroupRuleManager->setChargesRuleMapping($this->form)) && $rulesError) {
            $this->session->getFlashBag()->add('success_message', $this->translator->trans('admin.service_group_management.rule_mapping.add_message_success'));

            return new JsonResponse(array(
                    'form_name' => $this->form->getName(),
                    'form_status' => 'success',
                    'page_url' => $this->generateUrl('office_brain_servicegroupbundle_chargesrulemappingadmin_list'),
            ));
        } else {
            return new JsonResponse($this->prepareFormJsonError($rulesError));
        }
    }

    /**
     * @author Employee Id: 4589
     * Description : Add rule mapping form.
     *
     * @param 1 : No parameter
     *
     * @return type : Rule Mapping form
     *
     * @throws Exception: No exception
     *
     * @Route("/edit/{id}",
     * name="office_brain_servicegroupbundle_chargesrulemappingadmin_edit")
     *
     * @Method({"GET"})
     * @Template()
     */
    public function editAction()
    {
        $this->initAction();

        $this->responseArray = array_merge($this->responseArray, $this->serviceGroupRuleManager->getRuleMappingForEdit());
        $this->responseArray['rule_condition'] = $this->getRuleConditionArray($this->responseArray['rule_condition']);
        $this->responseArray['service_rule_mapping_column_qty'] = $this->get('serializer')->serialize($this->responseArray['service_rule_mapping_column_qty'], 'json');
        $this->responseArray['service_rule_mapping_groups'] = $this->get('serializer')->serialize($this->responseArray['service_rule_mapping_groups'], 'json');

        $this->form = $this->createForm(new ServiceChargesRuleMappingType($this->container, $this->responseArray['options']), $this->responseArray['rule_mapping_master']);
        $this->responseArray['form'] = $this->form->createView();

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4589
     * Description : Submit add rule mapping form.
     *
     * @param 1 : No parameter
     *
     * @return type : Rule Mapping form and data
     *
     * @throws Exception: No exception
     *
     * @Route("/edit/{id}",
     * name="office_brain_servicegroupbundle_chargesrulemappingadmin_processedit")
     *
     * @Method({"POST"})
     * @Template()
     */
    public function processEditAction()
    {
        $this->initAction();

        $dataAry = $this->request->request->all();
        $ruleId = $this->request->get('id');
        $ruleErrors = null;

        $this->responseArray = array_merge($this->responseArray, $this->serviceGroupRuleManager->getRuleMappingForEdit());
        $this->responseArray['rule_condition'] = $this->getRuleConditionArray($this->responseArray['rule_condition']);
        $this->responseArray['service_rule_mapping_column_qty'] = $this->get('serializer')->serialize($this->responseArray['service_rule_mapping_column_qty'], 'json');
        $this->responseArray['service_rule_mapping_groups'] = $this->get('serializer')->serialize($this->responseArray['service_rule_mapping_groups'], 'json');

        $this->form = $this->createForm(new ServiceChargesRuleMappingType($this->container, $this->responseArray['options']), $this->responseArray['rule_mapping_master']);

        $this->form->handleRequest($this->request);

        if (!is_array($rulesError = $this->serviceGroupRuleManager->setChargesRuleMapping($this->form)) && $rulesError) {
            //if (!is_array($rulesError = $this->serviceGroupRuleManager->editRuleMapping($this->form)) && $rulesError) {
                $this->session->getFlashBag()->add('success_message', $this->translator->trans('admin.service_group_management.rule_mapping.add_message_success'));

            return new JsonResponse(array(
                        'form_name' => $this->form->getName(),
                        'form_status' => 'success',
                        'page_url' => $this->generateUrl('office_brain_servicegroupbundle_chargesrulemappingadmin_list'),
                ));
            //}
        }

        return new JsonResponse($this->prepareFormJsonError($rulesError));
    }

    /**
     * @author Employee Id: 4589
     * Description : Adding rule to mapping.
     *
     * @param 1 : Rule Id
     *
     * @return type : Rule Master Rule
     *
     * @throws Exception: No exception
     *
     * @Route("/add-rule-to-rule-mapping/{rule_id}",
     * name="office_brain_servicegroupbundle_chargesrulemappingadmin_addruletomapping",options={"expose"=true})
     *
     * @Method({"GET"})
     */
    public function addRuleToMappingAction($rule_id)
    {
        $this->initAction();

        if ($rule_id) {
            $rules = $this->serviceGroupRuleManager->CheckRuleExists($rule_id);

            if ($rules) {
                $rules = $this->serviceGroupRuleManager->addServiceRuleMappingRules(null, $rule_id);

                if ($rules) {
                    $countryId = $rules['countryId'];
                    $this->responseArray['mapping_rule_id'] = $rules['id'];
                    $this->responseArray['rule_master_id'] = $rule_id;
                    $this->responseArray['rule_condition'] = $this->getRuleConditionArray($rules['ruleMapRulesId']);
                    $this->responseArray['conditions'] = json_encode(array_values($this->serviceGroupRuleManager->getConditionArray($countryId)));
                    //$this->responseArray['data'] = $rules;
                }
            } else {
                $this->responseArray = array('error_message' => $this->translator->trans('admin.service_group_management.rule_master.not_found'));
            }
        } else {
            $this->responseArray = array('error_message' => $this->translator->trans('admin.service_group_management.rule_master.rule_id_blank'));
        }

        return new JsonResponse($this->responseArray);
    }

    /**
     * @author Employee Id: 4589
     * Description : View rule mapping.
     *
     * @param 1 : Rule mapping Id
     *
     * @return type : Rule Mapping Array
     *
     * @throws Exception: No exception
     *
     * @Route("/view", name="office_brain_servicegroupbundle_chargesrulemappingadmin_view")
     *
     * @Template()
     */
    public function viewAction()
    {
        $this->initAction();
        $id = $this->request->get('id', false);

        if ($id && $id > 0) {
            $ruleMappingMaster = $this->serviceGroupRuleManager->getServiceRuleMappingById($id);

            $ruleMappingRules = $this->serviceGroupRuleManager->getMappingRulesByMappingMasterId($id);
        }

        $this->responseArray['data'] = array($ruleMappingMaster,$ruleMappingRules);
        $this->responseArray['rule_mapping_rules'] = (isset($ruleMappingRules) ? $ruleMappingRules : null);
        $this->responseArray['read_only_rules'] = true;
        $this->responseArray['admin_culture_options'] = $this->cultureList;

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4589
     * Description : Delete Rule mapping master.
     *
     * @param 1 : Rule Mapping Id
     *
     * @return type : JsonResponse
     *
     * @throws Exception: No exception
     *
     * @Route("/delete", name="office_brain_servicegroupbundle_chargesrulemappingadmin_delete")
     *
     * @Method({"GET"})
     * @Template()
     */
    public function deleteAction()
    {
        $this->initAction();
        $id = $this->request->get('id');

        if ($id) {
            $this->serviceGroupRuleManager->deleteRuleMapping($id);
            $this->session->getFlashBag()->add('success_message', $this->translator->trans('admin.service_group_management.rule_mapping.delete_message_success'));
        } else {
            $this->session->getFlashBag()->add('success_message', $this->translator->trans('admin.service_group_management.rule_mapping.delete_message_error'));
        }

        return new JsonResponse(array('success' => 'success', 'page_url' => $this->generateUrl('office_brain_servicegroupbundle_chargesrulemappingadmin_list')));
    }

    /**
     * @author Employee Id: 4589
     * Description : Get Rule condition Array
     *
     * @param 1 : array $condOrderAry
     * @param 2 : bool  $readOnly
     *
     * @return array
     * */
    public function getRuleConditionArray($conditionAry, $readOnly = false)
    {
        if (!$conditionAry || $conditionAry == null) {
            return;
        }

        // ************** Get All the condition in single array ************** //
        //$parentRelAry = array_column($conditionAry, $this->ruleKeyNameAry['parent_id'], 'key');
        $parentRelAry = $this->OBCommon->get_array_column($conditionAry, $this->ruleKeyNameAry['parent_id'], 'key');
        $allCondition = $this->serviceGroupRuleManager->getAllCondition($conditionAry, $parentRelAry);

        // ******************** Set Array in sorting of 'order' ****************** //
        //$condOrderAry = array_column($allCondition, $this->ruleKeyNameAry['display_order']);
        $condOrderAry = $this->OBCommon->get_array_column($allCondition, $this->ruleKeyNameAry['display_order']);
        array_multisort($condOrderAry, SORT_ASC, $allCondition);

        // ********* Set array in Json Format(jquery Plugin format) to show it on Edit/View ****** //
        $jsonAry = $this->serviceGroupRuleManager->setArrayWithJsonFormat($allCondition, $readOnly);

        if ($jsonAry && count($jsonAry) > 0) {
            return json_encode($jsonAry);
        } else {
            return;
        }
    }

    /**
     * @author Employee Id: 4589
     * Description : Prepare form error
     *
     * @param 1 : array $extraFormErrors
     *
     * @return array
     * */
    public function prepareFormJsonError($extraFormErrors = null)
    {
        $formErrors = $this->formErrorManager->prepareErrorArray($this->get('validator')->validate($this->form));
        if ($extraFormErrors != null) {
            $formErrors = array_merge($formErrors, $extraFormErrors);
        }

        return array(
                'form_name' => $this->form->getName(),
                'form_status' => 'error',
                'form_errors' => $formErrors,
        );
    }

    /**
     * @author Employee Id: 4273
     * Description : Apply rule.
     *
     * @param 1 : Rule Mapping Id
     *
     * @return type : JsonResponse
     *
     * @throws Exception: No exception
     *
     * @Route("/apply-rule/{id}", name="office_brain_servicegroupbundle_chargesrulemappingadmin_applyrule")
     *
     * @Method({"GET"})
     * @Template()
     */
    public function applyRuleAction()
    {
    	
        $this->initAction();
         
        $id = $this->request->get('id');

        $this->applyRuleCommonLogic($id);

        return $this->redirect(
                $this->generateUrl('office_brain_servicegroupbundle_chargesrulemappingadmin_list')
        );
    }

    /**
     * @author Employee Id: 4273
     * Description : Apply rule.
     *
     * @param 1 : Rule Mapping Id
     *
     * @return type : JsonResponse
     *
     * @throws Exception: No exception
     *
     * @Route("/apply-rule-cron", name="office_brain_servicegroupbundle_chargesrulemappingadmin_applyrulecron")
     *
     * @Method({"GET"})
     * @Template()
     */
    public function applyRuleCronAction()
    {
        $this->initAction();

        $allRuleMappingArray = $this->serviceGroupRuleManager->getAllApplyRuleMapping();

        foreach ($allRuleMappingArray as $allRuleMapping) {
            $this->applyRuleCommonLogic($allRuleMapping->getId());
        }

        return new JsonResponse(array('status' => 'success'));
    }

    /**
     * @author Employee Id: 4273
     * Description : Apply rule.
     *
     * @param 1 : Rule Mapping Id
     *
     * @return type : JsonResponse
     *
     * @throws Exception: No exception
     *
     */
    public function applyRuleCommonLogicNew($id=null)
    {
    	if (!empty($id) && $id > 0) {
    		$searchQueryArray = $this->serviceGroupRuleManager->applyChargesRuleMapping($id);
    
    		//echo "<pre>",print_r($searchQueryArray);exit;
    
    		if ($searchQueryArray and !empty($searchQueryArray)) {
    			$productSearchData = new ProductSearchData($this->entityManager, $this->serviceGroupRuleManager->getLanguageId());
    
    			
    			foreach ($searchQueryArray as $searchQuery) {
    				$form = $this->createForm(new ProductSearchType(), $productSearchData, array('csrf_protection' => false));
    				//continue;
    				$form->bind($searchQuery['product_search']);
    
    				if ($form->isValid()) {
    					
    					$productUpdateArray = $this->serviceGroupRuleManager->setServiceRuleChargeProductPriceMain($form);
    					
    				} else {
    					//echo "<br />ERROR: ",(string) $form->getErrors(true, false);
    				}
    			}die;
    			$this->session->getFlashBag()->add('success_message', $this->translator->trans('admin.catalog_rule_mapping.success_apply_rule_message'));
    		} else {
    			$this->session->getFlashBag()->add('error_message', $this->translator->trans('admin.charges_rule_mapping.error_apply_rule_message'));
    		}
    	} else {
    		$this->session->getFlashBag()->add('error_message', $this->translator->trans('admin.charges_rule_mapping.error_apply_rule_message'));
    	}
    }

    /**
     * @author Employee Id: 4273
     * Description : Apply rule.
     *
     * @param 1 : Rule Mapping Id
     *
     * @return type : JsonResponse
     *
     * @throws Exception: No exception
     *
     */
    public function applyRuleCommonLogic($id=null)
    {
        if (!empty($id) && $id > 0) {
            $searchQueryArray = $this->serviceGroupRuleManager->applyChargesRuleMapping($id);
            
            //$this->request->attributes->add(array('per_page' => 10));
            
            //echo "<pre>",print_r($searchQueryArray);exit;

            if ($searchQueryArray and !empty($searchQueryArray)) {
                $productSearchData = new ProductSearchData($this->entityManager, $this->serviceGroupRuleManager->getLanguageId());

                $productArray = $ruleMappingArray = array();
                foreach ($searchQueryArray as $searchQuery) {
                    $form = $this->createForm(new ProductSearchType(), $productSearchData, array('csrf_protection' => false));
                    //continue;
                    $form->bind($searchQuery['product_search']);

                    if ($form->isValid()) {
                        $searchProducts = $this->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;
                    } else {
                        //echo "<br />ERROR: ",(string) $form->getErrors(true, false);
                    }
                }

                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)));

				$dataCount = count($newProductArray);
				if ($dataCount == 0) return false;
				$segmentLimit = ceil($dataCount / 1000); 
				$outputArray = array_chunk($newProductArray, $segmentLimit, true);
                  
                    //save product and price in db
				$productUpdateArray = $this->serviceGroupRuleManager->setServiceRuleProductPriceMain($this->ruleType, $outputArray);
				
                    
                //$productUpdateArray = $this->serviceGroupRuleManager->setServiceRuleChargeProductPrice($newProductArray);
                $this->session->getFlashBag()->add('success_message', $this->translator->trans('admin.catalog_rule_mapping.success_apply_rule_message'));
            } else {
                $this->session->getFlashBag()->add('error_message', $this->translator->trans('admin.charges_rule_mapping.error_apply_rule_message'));
            }
        } else {
            $this->session->getFlashBag()->add('error_message', $this->translator->trans('admin.charges_rule_mapping.error_apply_rule_message'));
        }
    }
}
