<?php 
namespace OfficeBrain\Bundle\CategoryBundle\Manager;

use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Symfony\Component\HttpFoundation\Request;
use OfficeBrain\Bundle\CoreBundle\Cache\RedisCacheService;

class ApiManager{
	private $cultureManager;
	private $request;
	private $categoryApi;
	private $imageManager;
	private $categoryMappingEntity;
	private $categoryMappingRepository;
	private $countryCategoryIgnoreEntity;
	private $countryCategoryIgnoreRepository;
	private $enbaled_localization;
	private $productCategoryMappingRepository;
	private $cultureCategoryMappingRepository;
	private $serviceContainer;
	private $subShopInquiryManager;
	
	public function __construct(Request $request, $categoryApi,$categoryMappingEntity,$categoryMappingRepository,$countryCategoryIgnoreEntity,$countryCategoryIgnoreRepository,$country,$productCategoryMappingRepository,$cultureCategoryMappingRepository,$serviceContainer,$subShopInquiryManager)
	{
		$this->container = $serviceContainer;
		$this->request = $request;		
		$this->categoryApi = $categoryApi;
		$this->categoryMappingEntity = $categoryMappingEntity;
		$this->categoryMappingRepository = $categoryMappingRepository;
		$this->countryCategoryIgnoreEntity = $countryCategoryIgnoreEntity;;
		$this->countryCategoryIgnoreRepository = $countryCategoryIgnoreRepository;
		$this->productCategoryMappingRepository = $productCategoryMappingRepository;
		$this->cultureCategoryMappingRepository = $cultureCategoryMappingRepository;
		$this->enbaled_localization = array();
		$this->country_and_countrycode = array();
		$this->serviceContainer = $serviceContainer;
		$this->projectSetting = $this->request->get('project_setting');
		$this->countryId = 233;
		$this->subShopInquiryManager = $subShopInquiryManager;
		$this->cultureCode = $this->projectSetting['culture_code'];
		$this->instanceId = $this->projectSetting['instance_id'];
		if(isset($this->projectSetting['instance_theme_meta']['product_category']['custom_label'])){
			$this->categoryCustomlabel = $this->projectSetting['instance_theme_meta']['product_category']['custom_label'];
		}
		
		$enbaled_culture = array();
		foreach($country as $data){
			$index = $data['id'];
			$this->country_and_countrycode[$data['id']] = $data['short_name'];
			$enbaled_culture[$index] =array();
			$enbaled_culture[$index]['locallization'] = array();
			foreach($data['language'] as $language=>$value){
				$enbaled_culture[$index]['locallization'][] = $language."_".$data['short_name'];
			}
		}
		$this->entityManager = $this->serviceContainer->get('doctrine')->getEntityManager();
		$this->CmsMenuItemRepository = $this->entityManager->getRepository('OfficeBrainCmsBundle:CmsMenuItem');
		$this->CmsMenuItemLanguageRepository = $this->entityManager->getRepository('OfficeBrainCmsBundle:CmsMenuItemLanguage');
		
		$this->categoryStatusSchedular = $this->entityManager->getRepository('OfficeBrainCategoryBundle:CategoryStatusSchedular');

		$this->paginatorManager = $this->serviceContainer->get('knp_paginator');
		$this->categoryStatusSchedular->setPaginatorService($this->paginatorManager);

		$this->statsh_cache_wrapper = RedisCacheService::create();
		$this->moduleCachePrefix = '__InstanceThemeMetaData__';
		
		//KEY: Country ID, VALUE: Enabled culture
		$this->enbaled_localization = $enbaled_culture;
		//print_r($this->country_and_countrycode);
		$this->statsh_cache_wrapper=RedisCacheService::create();
	}
	
	public function mypc($object)
	{
		$dev = $this->request->get('dev');
		if($dev == 'yes')
		{
			print_r($object);exit;
		}
	}
	/* Get List of Selected Culture Category */
	public function getList($cultures,$masterIds = array(),$isFromProductPage = false){
		$cultures = (array)$cultures;
		$cultures_to_pass = array();
		$country_requested = array();
		
		//Displaying listing as per language
		//enable support for localization('en_us' etc...) as well as language('en' etc..)
		foreach($cultures as $culture){
			@list($cultures_to_pass[],$country_requested[]) = explode("_",$culture);
		}
		$data = array();
		$mappingData = array();
		if(!$masterIds)
		{	//Get PMS ID and Parent ID
			$mappingData = $this->getCategoryMapping();
			$masterIds = array_column($mappingData, 'pms_id');
		}
		if($masterIds)
			{
			$params = array('cultures'=>json_encode($cultures_to_pass),'master_id'=>json_encode($masterIds));
			
			$rCultures = implode($cultures_to_pass);
			$rmasterIds= implode($masterIds);
			
			/* Redis cache processing started */
			$locale=$this->request->getLocale();
			$smallString = md5($rCultures.$rmasterIds);
			$cacheSiteKey = array('cunique'.$smallString,$locale,$this->projectSetting['instance_id'],$this->container->getParameter('kernel.environment'));
			//categorylistunique11052018023597f2d8d003460418a2ca7e6e34a9b17f
			//print_r($cacheSiteKey);exit;
			
			$this->moduleCachePrefix='__SiteModuleHomePage__:';
			$this->statsh_cache_wrapper=RedisCacheService::create();//print_r($cacheSiteKey);exit;
			//dump($this->statsh_cache_wrapper);exit;
			$cacheKey = $this->moduleCachePrefix.RedisCacheService::generateKey($this->statsh_cache_wrapper,$cacheSiteKey);
			
			//echo $cacheKey;exit;
			$cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
			if($cacheData){
				$data = $cacheData;
			}
			else
			{
				//$this->mypc($params);
				$this->categoryApi->init('list_category');
				$this->categoryApi->setCallParameters($params);
				$this->categoryApi->doProcess();
				if ($this->categoryApi->isSuccess()) {
					$data = $this->categoryApi->getResultArray();/* API processing ended */
					//$this->mypc($data);
					if(!empty($cacheKey))
					{
						RedisCacheService::saveCacheData($this->statsh_cache_wrapper,$cacheKey,$data);
					}
				}
			}
			/* Redis cache processing ended */
		
			if (!(empty($data))) {
				$data_to_rearrange = array();
				if(count($country_requested)){
					foreach($cultures_to_pass as $index=>$passed_culture){
						if(array_key_exists($passed_culture,$data))
						{
							if($country_requested[$index]!=""){
								$data_to_rearrange[$passed_culture."_".$country_requested[$index]] = $data[$passed_culture];
							}else{
								$data_to_rearrange[$passed_culture] = $data[$passed_culture];
							}
						}
					}
				}else{
					$data_to_rearrange = $data;
				}
				if($mappingData){
					$data_to_rearrange = $this->categoryHierarchy($data_to_rearrange,$mappingData,$isFromProductPage);
				}else{
					/* $ignore_data = $this->getIgnoreData();
					$mappingData = $this->getCategoryMapping();
					
					$ignore_category_country_wise = array();
					
					foreach($ignore_data as $ignore_category){
						$country_id =$this->country_and_countrycode[$ignore_category['country_id']];
						if(array_key_exists($country_id, $ignore_category_country_wise)){
							$ignore_category_country_wise[$country_id] = array();
						}
						$ignore_category_country_wise[$country_id][] = $ignore_category['cat_map_id'];
					}
					
					print_r($data_to_rearrange);
					print_r($ignore_category_country_wise); */
					
				}
				$returnData = $data_to_rearrange;
			}
			else {
				$returnData = Null;
			}
		}else {
			$returnData = Null;
		}
		//echo "dfdfdf";
		//echo "<pre>";print_R($returnData);die;
		return $returnData;
	}
	/* Function for get Category from Country Ignore */
	public function getIgnoreData()
	{
		$ignoreData = $this->countryCategoryIgnoreRepository->getIgnoreData();
		return $ignoreData;
	}
	/* Generate Hierarchy of Category */
	public function categoryHierarchy($data,$mappingData,$isFromProductPage)
	{
		$cultureDetails = $this->serviceContainer->getParameter('language');
		$ignore_data = $this->getIgnoreData();
		$ignore_category_country_wise = array();
		
		foreach($ignore_data as $ignore_category){
			if(!isset($this->country_and_countrycode[$ignore_category['country_id']]))
				continue;
			$country_id =$this->country_and_countrycode[$ignore_category['country_id']];
			if(!array_key_exists($country_id, $ignore_category_country_wise)){
				$ignore_category_country_wise[$country_id] = array();
			}
			$ignore_category_country_wise[$country_id][] = $ignore_category['cat_map_id'];
		}
		
		$arrangeDataByPmsId = array();
		foreach ($mappingData as $mappeddata){ 
			$arrangeDataByPmsId[$mappeddata['pms_id']] = $mappeddata;
		}
		foreach($data as $key=>$value){
		    @list($language,$country) = explode('_',$key);
		    foreach($arrangeDataByPmsId as $pms_id=>$mappeddataValue){
		    	if(array_key_exists($country,$ignore_category_country_wise) && in_array($mappeddataValue['local_id'],$ignore_category_country_wise[$country])>=-1){
		    		if(!$isFromProductPage){
    		        	unset($data[$key][$pms_id]);
    		        }
    		    }
		    }
		}
		
		foreach($data as $key=>$value){
			@list($language,$country) = explode('_',$key);
			$pmsIdForLocalId = array();
			foreach($arrangeDataByPmsId as $pms_id=>$mappeddataValue){
				if(isset($value[$pms_id]['pms_id'])){
					
					if(array_key_exists($country,$ignore_category_country_wise) && in_array($mappeddataValue['local_id'],$ignore_category_country_wise[$country])>=-1){
						if(!$isFromProductPage){
							unset($data[$key][$pms_id]);
						}
					}
					
					$cultureId = $cultureDetails[$language]['id'];
					$localCultureCategoryMapping = $this->getCultureCategoryMapping($pms_id,$cultureId);
					//$data[$key][$pms_id]['custom_label'] = $this->subShopInquiryManager->getCustomLabel("product_category",$pms_id,$cultureId);
					
					if(isset($this->categoryCustomlabel) && isset($this->categoryCustomlabel[$pms_id])){
						//$data[$key][$pms_id]['custom_label'] = $this->categoryCustomlabel[$pms_id][$cultureId];
						$data[$key][$pms_id]['cat_name'] = $this->categoryCustomlabel[$pms_id][$cultureId];
					}
					$data[$key][$pms_id]['parent_id'] = $mappeddataValue['parent_id'];
					$data[$key][$pms_id]['sort_position'] = $mappeddataValue['sortPosition'] ? $mappeddataValue['sortPosition'] : 9999;
					$data[$key][$pms_id]['local_id'] = $mappeddataValue['local_id'];
					$data[$key][$pms_id]['image'] = $mappeddataValue['image'];
					$data[$key][$pms_id]['categoryLink'] = $mappeddataValue['categoryLink'];
					$data[$key][$pms_id]['status'] = $mappeddataValue['status'];
					$data[$key][$pms_id]['categoryFlag'] = $mappeddataValue['categoryFlag'];
					$data[$key][$pms_id]['keywords'] = isset($localCultureCategoryMapping['keywords'])?$localCultureCategoryMapping['keywords']:'';
					$data[$key][$pms_id]['description'] = isset($localCultureCategoryMapping['description'])?$localCultureCategoryMapping['description']:'';
				
					$pmsIdForLocalId[$mappeddataValue['local_id']] = $pms_id;
					$parentAndChild[$mappeddataValue['local_id']] = $mappeddataValue['parent_id'];
					
				}
			}
		}
		
		//Level 1 and 2
		foreach($data as $key=>$value){
			foreach($arrangeDataByPmsId as $pms_id=>$mappeddataValue){
				if(isset($value[$pms_id]['pms_id'])){
					if(!$data[$key][$pms_id]['parent_id']){
						continue;
					}
					$to_process_pms_id = 0;
					$parent_id = $data[$key][$pms_id]['parent_id'];
					if (array_key_exists($parent_id, $pmsIdForLocalId)) {
						$to_process_pms_id = $pmsIdForLocalId[$parent_id];
					}
					if(array_key_exists($parent_id, $parentAndChild)) {
						if($parentAndChild[$parent_id]){
							continue;
						}
					}
						
					if($to_process_pms_id)
					{
						if(!array_key_exists('child',$data[$key][$to_process_pms_id])){
							$data[$key][$to_process_pms_id]['child'] = array();
						}
						$data[$key][$to_process_pms_id]['child'][$pms_id] = $data[$key][$pms_id];
					}
					unset($data[$key][$pms_id]);
				}
			}
		}
		//Level 3
		foreach($data as $key=>$value){
			foreach($arrangeDataByPmsId as $pms_id=>$mappeddataValue){
				if(isset($value[$pms_id]['pms_id'])){
					if(!array_key_exists($pms_id,$data[$key]) || !$data[$key][$pms_id]['parent_id']){
						continue;
					}
					$parent_id = $data[$key][$pms_id]['parent_id'];
					$to_process_pms_id = $pmsIdForLocalId[$parent_id];
						
					if($parentAndChild[$parent_id]){
						$parent_id = $parentAndChild[$parent_id];
						if(array_key_exists($parent_id,$pmsIdForLocalId)){
							$to_process_pms_id_l2 = $pmsIdForLocalId[$parent_id];
							if(!array_key_exists('child',$data[$key][$to_process_pms_id_l2]['child'][$to_process_pms_id])){
								$data[$key][$to_process_pms_id_l2]['child'][$to_process_pms_id]['child'] = array();
							}
							$data[$key][$to_process_pms_id_l2]['child'][$to_process_pms_id]['child'][$pms_id] = $data[$key][$pms_id];
						}
						
						unset($data[$key][$pms_id]);
					}
				}
			}
		}
 		//echo "<pre>";print_R($data);die;
		return $data;
	}
	/* Get Category From Mapping Web-client */
	public function getCategoryMapping()
	{
		return $this->categoryMappingRepository->getCategoryMapping();
	}
	public function getCultureCategoryMapping($categoryPmsId,$cultureId){
		$data = $this->cultureCategoryMappingRepository->getCultureCategoryMapping($categoryPmsId,$cultureId);
		return isset($data[0])?$data[0]:array();
	}
	
	/* For Auto Fill Textbox Get Categories , Call on Change of Category Textbox */
	public function getAutoselectList($culture="",$categoryText = "", $isFromProduct = false){
		$data = array();
		
		$mappingData = $this->getCategoryMapping();
		
		$params = array('status'=>true,'culture_code'=>$culture,'category_text'=>$categoryText, 'from_product_add' => $isFromProduct);
		$masterIds = array_column($mappingData, 'pms_id');
		if($masterIds){
			$params['exclude_pms_ids'] = json_encode($masterIds);
		}
		$this->categoryApi->init('auto_list_category');
		$this->categoryApi->setCallParameters($params);
		$this->categoryApi->doProcess();
	
		if ($this->categoryApi->isSuccess()) {
			$data = $this->categoryApi->getResultArray();
		}
		
		return $data;
	}
	
	/* For get Data of Selected Category from auto select Textbox */
	public function getSelectCategory($searchStatus='', $searchParam='', $searchQuery='', $sortType='ASC', $sortBy='ID',$culture="",$cultureIds = "",$categoryName = ""){
		$data = array();
		$params = array('status'=>$searchStatus, 'searchParam'=>$searchParam ,'searchQuery'=>$searchQuery, 'sortType'=>$sortType,
				'sortBy'=>$sortBy,'culture_code'=>$culture,'culture_ids' => $cultureIds,'category_name'=>$categoryName);
		$this->categoryApi->init('selected_category');
		$this->categoryApi->setCallParameters($params);
		$this->categoryApi->doProcess();
		
		if ($this->categoryApi->isSuccess()) {
			$data = $this->categoryApi->getResultArray();
			$data["image"] = "";
			$categoryPmsId = 0;
			$cultureIds = (array)json_decode($cultureIds);
			if($data){
				foreach($data as $key=>$value){
					if(isset($value['category_master_id']) && $value['category_master_id'] != ""){
						$categoryPmsId = $value['category_master_id'];
					}
					if($key !== "image" && isset($cultureIds[$key]) && $data[$key] !== ""){
						$cultureCategoryMappingData = $this->cultureCategoryMappingRepository->getCultureCategoryMapping($categoryPmsId,$cultureIds[$key]);
						$data[$key]['keywords'] = isset($cultureCategoryMappingData[0]['keywords'])?$cultureCategoryMappingData[0]['keywords']:'';
						$data[$key]['description'] = isset($cultureCategoryMappingData[0]['description'])?$cultureCategoryMappingData[0]['description']:'';
					}
// 					$data[$key]['custom_label'] = $this->subShopInquiryManager->getCustomLabel("product_category",$categoryPmsId,$cultureIds[$key]);
					if(isset($this->categoryCustomlabel) && isset($this->categoryCustomlabel[$categoryPmsId])){
						$data[$key]['custom_label'] = $this->categoryCustomlabel[$categoryPmsId][$cultureIds[$key]];
					}
				}
			}
			if($categoryPmsId != 0){
				$catMapByPmsId = $this->categoryMappingRepository->findOneBy(array("pmsId"=>$categoryPmsId,"deletedAt" => null));
				if(is_object($catMapByPmsId)){
					$data["image"] = $catMapByPmsId->getImage();
				}
				$cultureCategoryMappingObj = $this->cultureCategoryMappingRepository->findBy(array('pmsId' => $categoryPmsId)); 
			}
		}
		
		return $data;
	}
	

	public function getProductMappingDataFromApi($pmsId,$offset,$limit){
		$params = array('pms_id'=>$pmsId,'country_id'=>233,'offset'=>$offset,'limit'=>$limit);
		$this->categoryApi->init('get_product_cat_mapping_list');
		$this->categoryApi->setCallParameters($params);
		$this->categoryApi->doProcess();

		if ($this->categoryApi->isSuccess()) {
			$data = $this->categoryApi->getResultArray();
			return $data;
		}
		return array();
	}

	/* For Add Data in Category Mapping Table and Category Master Table When Category is New */
	public function setCategoryData($culture,$postData,$culture_ids,$country_ids = array(),$supplier_id,$isAddData = false)
	{
		$cat_master_id = "";
		$categoryMappingObj = array();
		$setPostData = array();
		$masterId = 0;
		$textCounter = 0;
		$categoryImage = "";
		$parentId = 0;
 		//echo "<pre>";print_R($postData);die;
		/* For Set Data */
		foreach($culture_ids as $key => $value)
		{
			if(array_key_exists("newCategory",$postData) && array_key_exists($key,$postData['newCategory'])){
				$setPostData[$key]['title'] = isset($postData['newCategory'][$key]['title'])?$postData['newCategory'][$key]['title']:'';
				$setPostData[$key]['keywords'] = isset($postData['newCategory'][$key]['keywords'])?$postData['newCategory'][$key]['keywords']:'';
				$setPostData[$key]['description'] = isset($postData['newCategory'][$key]['description'])?$postData['newCategory'][$key]['description']:'';
			}
			if(array_key_exists("cat_master_id-".$key,$postData)){
				$masterId = $postData["cat_master_id-".$key];
			}
		}
		
		
		if(array_key_exists("selectedParent",$postData)){
			$parentId = $postData["selectedParent"];
		}
		if(array_key_exists("image_category",$postData)){
			$categoryImage = $postData["image_category"];
		}
		$mapping_product_count = 0;
		if($parentId != 0)
		{
			/* For Check Category Have Mapped Products or Not */
			$mappingData = $this->categoryMappingRepository->findOneBy(array('id' => $parentId));
			if(is_object($mappingData)){
				$pmsId = $mappingData->getPmsId();
				//$mapping_product_count = $this->getProductCatMapping($pmsId,6);
				$mapping_product_count = $mapping_product_count[0]['map_count'];
			}
		}
		
		if($mapping_product_count == 0){
			$setPostData =array_filter($setPostData);
			
			if( isset($postData['original_name']) && trim($postData['newCategory'][$key]['title']) !=trim($postData['original_name'])){ 
				if(count($setPostData) > 0){
			
					$categoryData = json_encode($setPostData);
			
					$params = array('category_Master_id'=>$masterId,'category_data'=>$categoryData,'supplier_id'=>$supplier_id,'culture_id'=>$culture_ids[$key]['id'],'active_culture'=>$postData['active_culture']);
					$this->categoryApi->init('update_new_category');
					$this->categoryApi->setCallParameters($params);
					$this->categoryApi->doProcess();
			
					if ($this->categoryApi->isSuccess()) {
						$data = $this->categoryApi->getResultArray();
						$master_id = $data['data'];
						$catMapByPmsId = $this->categoryMappingRepository->findOneBy(array("pmsId"=>$master_id,"deletedAt" => NULL));
						$catMapByPmsobj = $this->categoryMappingRepository->findOneBy(array("pmsId"=>$masterId,"deletedAt" => NULL));
						$productMappedObj =  $this->productCategoryMappingRepository->findOneBy(array("categoryId"=>$masterId));
						$CmsMenuItemObj=$this->CmsMenuItemRepository->findOneBy(array("referenceId"=>$masterId,"itemType"=>'browse-category-search',"deletedAt" => NULL));
						$CmsMenuItemProductCatListObj=$this->CmsMenuItemRepository->findOneBy(array("referenceId"=>$masterId,"itemType"=>'category-product-list',"deletedAt" => NULL));
						$CmsMenuItemProductCatObj=$this->CmsMenuItemRepository->findOneBy(array("referenceId"=>$masterId,"itemType"=>'product-category',"deletedAt" => NULL));
						if(is_object($CmsMenuItemObj)){
							$jsonArray['menu_item_type'] ='browse-category-search';
							$jsonArray['reference_id'] =$master_id;
							$jsonArray['title'] =array($data['category_data'][0]['name']);
							$jsonArray['slug']=array($data['category_data'][0]['slug']);
							$jsonData  =json_encode($jsonArray);
							$this->CmsMenuItemRepository->UpdateCmsMenu($CmsMenuItemObj,$master_id,$jsonData);
			
							$CmsMenuItemLanguage = $this->CmsMenuItemLanguageRepository->findOneBy(array("itemId"=>$CmsMenuItemObj->getId()));
			
							if(is_object($CmsMenuItemLanguage)){
								$urlArray=explode('/',$CmsMenuItemLanguage->getUrl());
								$urlArray[count($urlArray)-1]=$data['category_data'][0]['slug'];
								$updateUrl=implode('/',$urlArray);
								$title = $data['category_data'][0]['name'];
								$this->CmsMenuItemLanguageRepository->UpdateCmsLanguageMenu($CmsMenuItemLanguage,$updateUrl,$title);
								RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,"__MenuManagement__");
							}
						}
						if(is_object($CmsMenuItemProductCatListObj)){
							$jsonArray['menu_item_type'] ='category-product-list';
							$jsonArray['reference_id'] =$master_id;
							$jsonArray['title'] =array($data['category_data'][0]['name']);
							$jsonArray['slug']=array($data['category_data'][0]['slug']);
							$jsonData  =json_encode($jsonArray);
							$this->CmsMenuItemRepository->UpdateCmsMenu($CmsMenuItemProductCatListObj,$master_id,$jsonData);
			
							$CmsMenuItemLanguage = $this->CmsMenuItemLanguageRepository->findOneBy(array("itemId"=>$CmsMenuItemProductCatListObj->getId()));
			
							if(is_object($CmsMenuItemLanguage)){
								$urlArray=explode('/',$CmsMenuItemLanguage->getUrl());
								$urlArray[count($urlArray)-1]=$data['category_data'][0]['slug'];
								$updateUrl=implode('/',$urlArray);
								$title = $data['category_data'][0]['name'];
								$this->CmsMenuItemLanguageRepository->UpdateCmsLanguageMenu($CmsMenuItemLanguage,$updateUrl,$title);
								RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,"__MenuManagement__");
							}
						}
						if(is_object($CmsMenuItemProductCatObj)){
							$jsonArray['menu_item_type'] ='product-category';
							$jsonArray['reference_id'] =$master_id;
							$jsonArray['title'] =array($data['category_data'][0]['name']);
							$jsonArray['slug']=array($data['category_data'][0]['slug']);
							$jsonData  =json_encode($jsonArray);
							$this->CmsMenuItemRepository->UpdateCmsMenu($CmsMenuItemProductCatObj,$master_id,$jsonData);
			
							$CmsMenuItemLanguage = $this->CmsMenuItemLanguageRepository->findOneBy(array("itemId"=>$CmsMenuItemProductCatObj->getId()));
			
							if(is_object($CmsMenuItemLanguage)){
								$urlArray=explode('/',$CmsMenuItemLanguage->getUrl());
								$urlArray[count($urlArray)-1]=$data['category_data'][0]['slug'];
								$updateUrl=implode('/',$urlArray);
								$title = $data['category_data'][0]['name'];
								$this->CmsMenuItemLanguageRepository->UpdateCmsLanguageMenu($CmsMenuItemLanguage,$updateUrl,$title);
								RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,"__MenuManagement__");
							}
						}
						
						if(is_object($catMapByPmsId))
						{
							$categoryObj = $this->categoryMappingRepository->updateCategoryParent($catMapByPmsId,$parentId,$categoryImage);
							if(is_object($productMappedObj)){
								$this->categoryMappingRepository->updateProductCategoryMapping($productMappedObj,$master_id);
							}
							$this->categoryMappingRepository->updateCategoryMapping($catMapByPmsobj,$master_id,$parentId,$categoryImage);
							if(isset($postData['localCategory'])){
								$this->setCultureCategoryMapping($postData['localCategory'],$catMapByPmsId->getPmsId(),$culture_ids);
							}
							
							if(isset($postData['labelCategory'])){
								$this->subShopInquiryManager->setSubShopInstanceMetaKey("product_category",$postData['labelCategory'],$catMapByPmsId->getPmsId(),$culture_ids);
								RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
							}
							
							return array("status" => "success_message" , "message"=>"PRODUCT.CATEGORY_UPDATED_SUCCESSFULLY",'category_object'=>$categoryObj,'product_ids'=>$data['product_ids']);
						}
						else
						{   if($data['product_ids']!=''){
							//$categoryObj = $this->categoryMappingRepository->addCategoryMapping($master_id,$parentId,$categoryImage);
							$categoryObj = $this->categoryMappingRepository->updateCategoryMapping($catMapByPmsobj,$master_id,$parentId,$categoryImage);
							if(is_object($productMappedObj)){
								$this->categoryMappingRepository->updateProductCategoryMapping($productMappedObj,$master_id);
							}
							if(isset($postData['localCategory'])){
								$this->setCultureCategoryMapping($postData['localCategory'],$master_id,$culture_ids);
							}
							/* Add Data In Category Ignore Table */
							if($country_ids){
								foreach($country_ids as $country_id){
									$ignoreData = $this->addInCategoryIgnore($country_id['id'],$categoryObj->getId(),$master_id);
								}
							}
							
							if(isset($postData['labelCategory'])){
								$this->subShopInquiryManager->setSubShopInstanceMetaKey("product_category",$postData['labelCategory'],$master_id,$culture_ids);
								RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
							}
							
							return array("status" => "success_message" , "message"=>"PRODUCT.CATEGORY_UPDATED_SUCCESSFULLY",'category_object'=>$categoryObj,'product_ids'=>$data['product_ids']);
						}
						}
					}
					else{
						return array("status" => "error_message" , "message"=>"PRODUCT.CULTURE_DOES_NOT_EXIST");
					}
				}
			}else{
			if(count($setPostData) > 0)
			{
				$categoryData = json_encode($setPostData);
				$data = array();
				$params = array('category_Master_id'=>$masterId,'category_data'=>$categoryData);
				$this->categoryApi->init('add_new_category');
				$this->categoryApi->setCallParameters($params);
				$this->categoryApi->doProcess();
				
				if ($this->categoryApi->isSuccess()) {
					$data = $this->categoryApi->getResultArray();
					$master_id = $data['data'];
					$catMapByPmsId = $this->categoryMappingRepository->findOneBy(array("pmsId"=>$masterId,"deletedAt" => NULL));
					if(is_object($catMapByPmsId))
					{
						$categoryObj = $this->categoryMappingRepository->updateCategoryParent($catMapByPmsId,$parentId,$categoryImage);
						
						if(isset($postData['localCategory'])){
							$this->setCultureCategoryMapping($postData['localCategory'],$catMapByPmsId->getPmsId(),$culture_ids);
						}
						
						// Add Custom Category label in Subshop Instance Meta table 
						if(isset($postData['labelCategory'])){
							$this->subShopInquiryManager->setSubShopInstanceMetaKey("product_category",$postData['labelCategory'],$catMapByPmsId->getPmsId(),$culture_ids);
							exec("php ../app/console office_brain:solr:sync:product-category --culture=".$this->cultureCode." --categoryId=".$catMapByPmsId->getPmsId()." --instanceId=".$this->instanceId." &");
						}
						RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);						
						return array("status" => "success_message" , "message"=>"PRODUCT.CATEGORY_ADDED_SUCCESSFULLY",'category_object'=>$categoryObj);
					}
					else
					{
						$categoryObj = $this->categoryMappingRepository->addCategoryMapping($master_id,$parentId,$categoryImage);
						if(isset($postData['localCategory'])){
							$this->setCultureCategoryMapping($postData['localCategory'],$master_id,$culture_ids);
						}
						
						// Add Custom Category label in Subshop Instance Meta table
						if(isset($postData['labelCategory'])){
							$this->subShopInquiryManager->setSubShopInstanceMetaKey("product_category",$postData['labelCategory'],$master_id,$culture_ids);
							exec("php ../app/console office_brain:solr:sync:product-category --culture=".$this->cultureCode." --categoryId=".$master_id." --instanceId=".$this->instanceId." &");
						}
												
						/* Add Data In Category Ignore Table */
						if($country_ids){
							foreach($country_ids as $country_id){
							    $ignoreData = $this->addInCategoryIgnore($country_id['id'],$categoryObj->getId(),$master_id);
							}
						}
						RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
						return array("status" => "success_message" , "message"=>"PRODUCT.CATEGORY_ADDED_SUCCESSFULLY",'category_object'=>$categoryObj);
					}
				}
				else{
					return array("status" => "error_message" , "message"=>"PRODUCT.CULTURE_DOES_NOT_EXIST");
				}
				
			}
			else
			{
				if($masterId != 0)
				{
					$catMapByPmsId = $this->categoryMappingRepository->findOneBy(array("pmsId"=>$masterId,"deletedAt" => NULL));
					if(is_object($catMapByPmsId))
					{
						if($isAddData){
							return array("status" => "error_message" , "message"=>"PRODUCT.CATEGORY_ALREADY_EXIST");
						}else{
							$categoryObj = $this->categoryMappingRepository->updateCategoryParent($catMapByPmsId,$parentId,$categoryImage);
							if(isset($postData['localCategory'])){
								$this->setCultureCategoryMapping($postData['localCategory'],$catMapByPmsId->getPmsId(),$culture_ids);
							}
							// Add Custom Category label in Subshop Instance Meta table
							if(isset($postData['labelCategory'])){
								$this->subShopInquiryManager->setSubShopInstanceMetaKey("product_category",$postData['labelCategory'],$catMapByPmsId->getPmsId(),$culture_ids);
								exec("php ../app/console office_brain:solr:sync:product-category --instanceId=".$this->instanceId." --culture='".$this->cultureCode."' --categoryId=".$catMapByPmsId->getPmsId()." &");								
							}
							RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
							return array("status" => "success_message" , "message"=>"PRODUCT.CATEGORY_UPDATED_SUCCESSFULLY",'category_object'=>$categoryObj);
						}
					}
					else
					{
						$categoryObj = $this->categoryMappingRepository->addCategoryMapping($masterId,$parentId,$categoryImage);
						if(isset($postData['localCategory'])){
							$this->setCultureCategoryMapping($postData['localCategory'],$masterId,$culture_ids);
						}
						
						// Add Custom Category label in Subshop Instance Meta table
						if(isset($postData['labelCategory'])){
							$this->subShopInquiryManager->setSubShopInstanceMetaKey("product_category",$postData['labelCategory'],$masterId,$culture_ids);
							exec("php ../app/console office_brain:solr:sync:product-category --culture=".$this->cultureCode." --categoryId=".$masterId." --instanceId=".$this->instanceId." &");
						}
												
						/* Add Data In Category Ignore Table */
						if($country_ids){
							foreach($country_ids as $country_id){
								$ignoreData = $this->addInCategoryIgnore($country_id['id'],$categoryObj->getId(),$masterId);
							}
						}
						
						RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
						
						return array("status" => "success_message" , "message"=>"PRODUCT.CATEGORY_ADDED_SUCCESSFULLY",'category_object'=>$categoryObj);
					}
				}
				else{
					return array("status" => "error_message" , "message"=>"PRODUCT.PLEASE_ADD_CATEGORY_NAME");
				}
			}
		}
	} //
		else {
			return array("status" => "error_message" , "message"=>"PRODUCT.PRODUCT_ARE_MAPPED");
		}
		
	}
	
	private function setCultureCategoryMapping($categoryData,$pmsId,$cultures){
		$cultureCatMappingObj = array();
		foreach($cultures as $key=>$culture){
			if(isset($categoryData[$key])){
				$mappingObj = $this->cultureCategoryMappingRepository->findOneBy(array('pmsId' => $pmsId,'cultureId' => $culture['id']));
				if(is_object($mappingObj)){
					if(trim($categoryData[$key]['keywords']) !== "" || trim($categoryData[$key]['description']) !== "" && isset($categoryData[$key])){
						$cultureCatMappingObj = $this->cultureCategoryMappingRepository->updateCultureCategoryMapping($categoryData[$key],$mappingObj);
					}else{
						$cultureCatMappingObj = $this->cultureCategoryMappingRepository->removeCultureCategoryMapping($mappingObj);
					}
					
				}else{
					if(trim($categoryData[$key]['keywords']) !== "" || trim($categoryData[$key]['description']) !== "" && isset($categoryData[$key])){
						$cultureCatMappingObj = $this->cultureCategoryMappingRepository->setCultureCategoryMapping($categoryData[$key],$pmsId,$culture['id']);
					}
				}
			}
		}
		return $cultureCatMappingObj;
	}
	/**
	 * Function For Add Category in Country Ignore 
	 * @param unknown $countryId
	 * @param unknown $catMapId
	 * @param unknown $pmsId
	 */
	public function addInCategoryIgnore($countryId,$catMapId,$pmsId)
	{
		$mappingData = $this->productCategoryMappingRepository->getProductCategoryMapping($pmsId,$countryId);
		$mapping_product_count = count($mappingData);
		$returnData = array();
		if($mapping_product_count <= 0){
			$this->countryCategoryIgnoreRepository->addInCategoryIgnore($countryId,$catMapId,$pmsId);
			$returnData = array("status" => "success_message" , "message"=>"PRODUCT.CATEGORY_REMOVED_FROM_COUNTRY");
		}else{
			$returnData = array("status" => "error_message" , "message"=>"PRODUCT.PRODUCT_ARE_MAPPED");
		}
		return $returnData;
	}
	
	/**
	 * Function For Remove Category in Country Ignore 
	 * @param unknown $countryId
	 * @param unknown $catMapId
	 */
	public function removeFromCategoryIgnore($countryId,$catMapId)
	{
		$this->countryCategoryIgnoreRepository->removeFromCategoryIgnore($countryId,$catMapId);
		//For Remove Product Mapping From Api Side
		return array("status" => "success_message" , "message"=>"PRODUCT.CATEGORY_ADDED_TO_COUNTRY");
	}
	
    public function processCategoryData($categoryObj, $cultures) {
        $id = $categoryObj->getId();
        $parentId = $categoryObj->getParentId();
        $pmsId = $categoryObj->getPmsId();
        $result = $this->getList($cultures, (array)$pmsId);
        $queueData = array();
        $queueData['id'] = $id;
        $queueData['parent_id'] = $parentId;
        $queueData['pms_id'] = $pmsId;
        foreach ($result as $key => $value) {
            $queueData['data'][] = array('culture' => $key, 'name' => $value[$pmsId]['cat_name']);
        }
        return $queueData;
    }
    
    /**
     * This function is for edit category Pass Master Id and Get Data
     * @param unknown $categoryId
     * @return multitype:
     */
    public function getCategoryInfoByCategoryId($cultures,$categoryId){
    	$pass_cultures = array_keys($cultures);
    	$params = array('cultures' => json_encode($pass_cultures), 'category_id'=>$categoryId);
    	$this->categoryApi->init('category_by_id');
    	$this->categoryApi->setCallParameters($params);
    	$this->categoryApi->doProcess();
    
    	$data = array();
    	if ($this->categoryApi->isSuccess()) {
    		$data = $this->categoryApi->getResultArray();
    	}
    	$catMapByPmsId = $this->categoryMappingRepository->findOneBy(array("pmsId"=>$categoryId,"deletedAt" => null));
		foreach($cultures as $key => $culture){
			if(!array_key_exists($key,$data)){			
				$data[$key] = "";
			}else{
				if(is_object($catMapByPmsId)){
					$data[$key]['parent_id'] = $catMapByPmsId->getParentId();
					$data[$key]['local_id'] = $catMapByPmsId->getId();
				}
			}
			
			$cultureCategoryMappingData = $this->cultureCategoryMappingRepository->getCultureCategoryMapping($categoryId,$culture['id']);
			
			$data[$key]['keywords'] = isset($cultureCategoryMappingData[0]['keywords'])?$cultureCategoryMappingData[0]['keywords']:'';
			$data[$key]['description'] = isset($cultureCategoryMappingData[0]['description'])?$cultureCategoryMappingData[0]['description']:'';
			
// 			$data[$key]['custom_label'] = $this->subShopInquiryManager->getCustomLabel("product_category",$categoryId,$culture['id']);
			if(isset($this->categoryCustomlabel) && isset($this->categoryCustomlabel[$categoryId])){
				$data[$key]['custom_label'] = $this->categoryCustomlabel[$categoryId][$culture['id']];
			}
		}
		$data['image'] = $catMapByPmsId->getImage();
    	return $data;
    }


    public function updateStatus($pmsId,$status){
    	$this->categoryMappingRepository->updateStatus($pmsId,$status);
    	return array("status" => "success_message" , "message"=>"Category updated successfully."); 
    }

    public function addCategoryStatusSchedular($pmsId,$status,$cname,$cstatus,$id){
    	return $this->categoryStatusSchedular->addCategoryStatusSchedular($pmsId,$status,$cname,$cstatus,$id);
    }

    public function setProductCount($schdularObj,$productcount){
    	$this->categoryStatusSchedular->setProductCount($schdularObj,$productcount);
    }

    public function setEstimateTime($obj,$estimateTime){
    	$this->categoryStatusSchedular->setEstimateTime($obj,$estimateTime);
    }

    public function getAllSynCategoryForChangeStatus($status){
		return $this->categoryStatusSchedular->getAllSynCategoryForChangeStatus($status);
	}

	public function getSchedularCategoryById($id){
		return $this->categoryStatusSchedular->getSchedularCategoryById($id);
	}

    public function getCategoryStatusSchedular($page,$recordsPerPage,$searchParametersArray,$searchKeyWordsArray)
	{
		return $this->categoryStatusSchedular->getCategoryStatusSchedular($page,$recordsPerPage,$searchParametersArray,$searchKeyWordsArray);
	}

    /**
     * This Function is For Delete Category from category mapping by pmsId
     * @param unknown $pmsId
     */
    public function delete($pmsId,$country_ids){
        $mappingData = $this->productCategoryMappingRepository->getProductCategoryMapping($pmsId);
        $mapping_product_count = count($mappingData);
        if($mapping_product_count <= 0){
            $returnData = $this->categoryMappingRepository->delete($pmsId);
            $data = $returnData->getId();
            if($country_ids){
            	foreach($country_ids as $country_id){
            		$ignoreData = $this->removeFromCategoryIgnore($country_id['id'],$data);
            	}
            }
            return array("status" => "success_message" , "message"=>"PRODUCT.CATEGORY_DELETED_SUCCESSFULLY","data" => $returnData);
        }
        else{
        	return array("status" => "error_message" , "message"=>"PRODUCT.PRODUCT_ARE_MAPPED");
        }
    }
    
   public function getParentChildCategoryList($caregoryList,$availableCategory,$culture){
		$this->catArrayNew = array();
   		
    	if (count($caregoryList) > 0) {
    		if(is_array($availableCategory) && count($availableCategory)){
    			
    			foreach ($availableCategory as $key => $value){
    				foreach($caregoryList[$culture] as $catKey=>$categoryAndSubCategory){
    					
    					if($catKey == $key)
    					{
    						$this->catArrayNew['parent_id'][$catKey] =[$catKey] ;
    					}
    					else{
    						if(count($caregoryList[$culture][$catKey]['child']) > 0) { 
    							if(array_key_exists($key, $caregoryList[$culture][$catKey]['child'])){
    								$this->catArrayNew['parent_id'][$catKey];
		    						foreach($caregoryList[$culture][$catKey]['child'] as $subCat=>$subCategory){
		    							$this->catArrayNew['parent_id'][$catKey]['child'] = $subCat;
		    						}
    							}
    						}
    					}
    					

    				}
    			}
    		}
    	}
    	return $this->catArrayNew ;
    	
    
    	
    }

	  /**
     * Function For Add Category flag
     * @param unknown $countryId
     * @param unknown $catMapId
     * @param unknown $pmsId
     * @param unknown $catFlag
     */
    public function setCategoryFlag($catMapId,$pmsId,$catFlag)
    {
    	// $mappingData = $this->productCategoryMappingRepository->getProductCategoryMapping($pmsId,$countryId);
    	// $mapping_product_count = count($mappingData);
    	$returnData = array();
    	$categoryData = $this->categoryMappingRepository->setCategoryMappingById($catMapId,$pmsId,$catFlag);
    	if($categoryData){
    		$returnData = array("status" => "success_message" , "message"=>"category_admin.category_success");
    	}else{
    		$returnData = array("status" => "error_message" , "message"=>"category_admin.error_category");
    	}
    	return $returnData;
    }

	public function fetchAllCategories($productCategories)
    {
    	$data = array();
    	if (!empty($productCategories)) {
    		$languageProductCategories = $productCategories;
    		unset($languageProductCategories[key($languageProductCategories)]);
    		$data['countryId'] = $this->countryId ; 
    		$data['product_categories'] = $this->buildCategoryTree(current($productCategories), key($productCategories));
    	}
    	return $data;
    }

	
    
    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to set category tree view
     *
     * @param 1: $categories
     *
     * @return: Multilevel tree structure of categories
     *
     * @throws Exception: Null
     */
    public function buildCategoryTree($categories, $locate,$parentCategoryName=""){
    	$branch = array();
    	$locateExplode = explode('_', $locate);
    	foreach ($categories as $index => $category) {
    		if($category['categoryFlag'] == 1){
	    		$branch[$index]['cat_master_id'] = $category['cat_master_id'];
	    		//if (isset($this->languages[$locateExplode[0]]['id']) && $this->languageId == $this->languages[$locateExplode[0]]['id']) {
	    			$displayCategoryName = $category['cat_name'];
	    		//}
	    		$categoryName = $category['cat_name'];
	    		$categorySlug = $category['slug'];
	    		$branch[$index]['cat_name'] = $categoryName;
	    		$branch[$index]['slug'] = $categorySlug;
	    		$branch[$index]['display_cat_name'] = $displayCategoryName;
	    		$branch[$index]['status'] = $category['status'];
	    		$branch[$index]['categoryLink'] = $category['categoryLink'];
	    		$branch[$index]['image'] = $category['image'];
				$branch[$index]['description'] = $category['description'];
				$branch[$index]['sort_position'] = $category['sort_position'];
				$branch[$index]['parent_category_name'] = $parentCategoryName;
	    		if(!empty($category['child'])){
					$newParentCat = $parentCategoryName ? $parentCategoryName. " > ".$categoryName : $categoryName; 
	    			$children = $this->buildCategoryTree($category['child'], $locate,$newParentCat);
	    			if ($children) {
	    				$branch[$index]['child'] = $children;
	    			}
	    		}
    		}
    	}
//     	echo "<pre>";print_R($branch);die;
    	return $branch;
    }

	/**
     * @author ("Krunal Jethi")
     *
     * Description : This function is used to build list view from tree view
     *
     * @param 1: $categories
     *
     * @return: Multilevel tree structure of categories to single level 
     *
     * @throws Exception: Null
     */
	public function buildCategoryListView($categories){
    	$listArr = array();
    	foreach ($categories as $index => $category) {
			$child = null;
			if(isset($category['child'])){
				$child = $category['child'];
				unset($category['child']);
				$category["has_child"] = true;
			}
			array_push($listArr,$category);
			if($child!=NULL){
				if(isset($child) && !empty($child)){
					$arr = $this->buildCategoryListView($child);
					$listArr = array_merge($listArr,$arr);
				}
			}
    	}
    	return $listArr;
    }
    
	 /**
     * @author Krunal Jehti
     * Description : For Category update position on home
     *
     * @param2: int $positon
     * @param3: int $PmsId
     *
     * @return object
     *
     * @throws null
     *
     **/
    public function setCateogryPosition($pmsId, $pos)
    {
        $categoryMapObj= $this->categoryMappingRepository->getCategoryByPmsId($pmsId);
        $categoryMapObj->setSortPosition($pos);
        $this->categoryMappingRepository->set($categoryMapObj);
        $this->entityManager->flush();
    }

    /**
     * @author Krunal Jehti
     * Description : For Category update position on home
     *
     * @param2: int $positon
     * @param3: int $PmsId
     *
     * @return object
     *
     * @throws null
     *
     **/
    public function getCategoryByPmsId($pmsId)
    {
        $categoryMapObj= $this->categoryMappingRepository->getCategoryByPmsId($pmsId);
        return $categoryMapObj;
    }

    public function setCateogryLink($pmsId, $url)
    {
    	
        $categoryMapObj= $this->categoryMappingRepository->getCategoryByPmsId($pmsId);
        $categoryMapObj->setCategoryLink($url);
        $this->categoryMappingRepository->set($categoryMapObj);
        $this->entityManager->flush();
        return $url;
    }
}
