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

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

class ApiManager{
	private $request;
	private $em;
	private $attributeApi;
	private $attributeMappingRepository;
	private $attributeValueMappingRepository;
	private $container;

	public function __construct(Request $request, $em, $attributeApi, $serviceContainer)
	{
		$this->request = $request;
		$this->em = $em;
		$this->attributeApi = $attributeApi;
		$this->attributeMappingRepository = $this->em->getRepository('OfficeBrainAttributeBundle:AttributeMapping');
		$this->attributeValueMappingRepository = $this->em->getRepository('OfficeBrainAttributeBundle:AttributeValueMapping');
		$this->attributeColorMasterColorMappingRepository = $this->em->getRepository('OfficeBrainAttributeBundle:AttributeColorMasterColorMapping');
		$this->container = $serviceContainer;
		$this->productApiManager = $this->container->get("office_brain_product_admin_manager");
		$this->masterColorSwatches = $this->container->getParameter("master_color_swatches");
		$this->attributeColorMasterColorMappingRepository = $this->container->get("doctrine")->getRepository('OfficeBrainAttributeBundle:AttributeColorMasterColorMapping');
		$this->projectSetting = $this->request->get('project_setting');
        $this->statsh_cache_wrapper = RedisCacheService::create();		
		$this->translator = $this->container->get('translator');
	}

	/**
	 * This Function is for Get Attribute List on Listing Page
	 * @author Employee Id : 4246
	 * @param unknown $culture
	 * @param unknown $masterIds
	 * @return NULL
	 */
	public function getList($culture,$masterIds = array(), $getAttributeValuesMaster = 0,$exclude_master_ids=array(),$searchQuery="",$sortBy="",$sortType="",$records_per_page="",$page="",$isFromAttributePage = 0,$attribute_value_limit = ''){
		$data = array();
		$countData = array();
		$culture = (array)$culture;
		$masterData = array();
		$masterData = $this->attributeMappingRepository->getAttributeMapping();

		$pms_id_and_local_id = array();
		if($masterData){
			$pms_id_and_local_id = @array_combine(array_column($masterData,'pms_id'),array_column($masterData,'local_id'));
		}
		$called_explicitly = false;

		if(!count($masterIds)){
			$masterIds = array_column($masterData,'pms_id');
		}else{
			$called_explicitly = true;
		}
		if($masterIds)
		{
			if(count($exclude_master_ids)){
				$masterIds = array_diff($masterIds,$exclude_master_ids);
			}
		    $params = array('cultures'=>json_encode($culture),'attribute_master_ids'=>json_encode($masterIds));
		    if($getAttributeValuesMaster == 1) {
		    	$finalMasterValuesIds = array();
		    	foreach((array)$masterIds as $attributeId){
		    		$masterValuesData = $this->attributeValueMappingRepository->getAttributeValueMapping($attributeId,null,0,$attribute_value_limit,$isFromAttributePage);

		    		//TODO : Need To Improve :  Is from Attribute Page
		    		if($isFromAttributePage == 1){
		    			$masterValuesIds = array_column($masterValuesData['data'],'pms_id');
		    			$finalMasterValuesIds[$attributeId] = $masterValuesIds;
		    			if($masterValuesData['count'] >= $attribute_value_limit){
		    				$countData[$attributeId] = 1;
		    			}else{
		    				$countData[$attributeId] = 0;
		    			}
		    		}else{
		    			//TODO : Need To Improve :  When Call From Other Page
		    			$masterValuesIds = array_column($masterValuesData,'pms_id');
		    			$finalMasterValuesIds[$attributeId] = $masterValuesIds;
		    		}
		    	}
		    	$params['attribute_values_master_ids'] = json_encode($finalMasterValuesIds);
		    }
			if($searchQuery){
				$params['search_query'] = $searchQuery;
			}
			if($sortBy){
				$params['sort_by'] = $sortBy;
			}
			if($sortType)
			{
				$params['sort_type'] = $sortType;
			}
			if($records_per_page != ""){
				$params['records_per_page'] = $records_per_page;
				$params['page'] = $page;
			}
			$params['is_from_attribute_page'] = $isFromAttributePage;
			$this->attributeApi->init('list_attributes');
			$this->attributeApi->setCallParameters($params);
			$this->attributeApi->doProcess();
			if ($this->attributeApi->isSuccess()) {
				$data = $this->attributeApi->getResultArray();
				if($called_explicitly){
					foreach($data as $culture=>$value){
						foreach($value as $index=>$attribute_data){
							$pms_id =$data[$culture][$index]['id'] ;
							$data[$culture][$index]['pms_id'] = $pms_id;
							$data[$culture][$index]['local_id'] = (isset($pms_id_and_local_id[$pms_id]))?$pms_id_and_local_id[$pms_id]:null;
						}
					}
				}
				$returnData = $data;
			}
			else $returnData = Null;
		}
		else $returnData = Null;

		if($isFromAttributePage == 1){
			return array($returnData,$countData);
		}else{
			return $returnData;
		}
	}
	
	
	
	
	
	/**
	 * This Function is for Get Swatches color list on swatches Listing Page
	 * @author Employee Id : 4532
	 * @param unknown $culture
	 * @param unknown $masterIds
	 * @return NULL
	 */
	public function getSwatchesList($culture,$masterIds = array(), $getAttributeValuesMaster = 0,$exclude_master_ids=array(),$searchQuery="",$sortBy="",$sortType="",$records_per_page="",$page="",$isFromAttributePage = 0,$attribute_value_limit = ''){
		$data = array();
		$countData = array();
		$culture = (array)$culture;
		$masterData = array();
		$masterData = $this->attributeMappingRepository->getAttributeMapping();

		$pms_id_and_local_id = array();
		if($masterData){
			$pms_id_and_local_id = @array_combine(array_column($masterData,'pms_id'),array_column($masterData,'local_id'));
		}
		$params['page'] = 1;
		$startIndex=0;
		if($records_per_page != ""){
			$params['records_per_page'] = $records_per_page;
			$params['page'] = $page;
			$startIndex = ($params['page']-1)*$records_per_page;
		}
		//echo $startIndex; die;
		$called_explicitly = false;

		if(!count($masterIds)){
			$masterIds = array_column($masterData,'pms_id');
		}else{
			$called_explicitly = true;
		}
		$masterDatacount = array();
		if($masterIds)
		{
			if(count($exclude_master_ids)){
				$masterIds = array_diff($masterIds,$exclude_master_ids);
			}
		    
		    if($getAttributeValuesMaster == 1) {
		    	$finalMasterValuesIds = array();
		    	foreach((array)$masterIds as $attributeId){
		    		$masterValuesData = $this->attributeValueMappingRepository->getAttributeValueMapping($attributeId,null,$startIndex,$attribute_value_limit,$isFromAttributePage);
		    		$masterDatacount[$attributeId]= $masterValuesData['all_data'];
		    		//TODO : Need To Improve :  Is from Attribute Page
		    		if($isFromAttributePage == 1){
		    			$masterValuesIds = array_column($masterValuesData['data'],'pms_id');
		    			$finalMasterValuesIds[$attributeId] = $masterValuesIds;
		    			if($masterValuesData['count'] >= $attribute_value_limit){
		    				$countData[$attributeId] = 1;
		    			}else{
		    				$countData[$attributeId] = 0;
		    			}
		    		}else{
		    			//TODO : Need To Improve :  When Call From Other Page
		    			$masterValuesIds = array_column($masterValuesData,'pms_id');
		    			//$finalMasterValuesIds[$attributeId] = $masterValuesIds;
		    		}
		    	}
		    	//$params['attribute_values_master_ids'] = json_encode($finalMasterValuesIds);
		    }
		    $params = array('culture_code'=>implode(" ",$culture),'attribute_master_id'=>implode(" ",$masterIds));
		    $params['attribute_values_master_ids'] = json_encode($masterValuesIds);
			if($searchQuery){
				$params['search_query'] = $searchQuery;
			}
			if($sortBy){
				$params['sort_by'] = $sortBy;
			}
			if($sortType)
			{
				$params['sort_type'] = $sortType;
			}
			if($records_per_page != ""){
				$params['records_per_page'] = $records_per_page;
				$params['page'] = 1;
			}
			$params['is_from_attribute_page'] = $isFromAttributePage;
			//echo '<pre>'; print_r($params);  die;
			$this->attributeApi->init('attribute_values_for_list');
			$this->attributeApi->setCallParameters($params);
			$this->attributeApi->doProcess();
			if ($this->attributeApi->isSuccess()) {
				//$data = $this->attributeApi->getResultArray();
				$returnData['data'] = $this->attributeApi->getResultArray();
				$returnData['data_count'] = $masterDatacount;
				//$returnData = $data;
			}
			else $returnData = Null;
		}
		else $returnData = Null;

		if($isFromAttributePage == 1){
			return array($returnData,$countData);
		}else{
			return $returnData;
		}
	}
	
	public function getAttributeSwatchesColor($attributeId,$start_index, $recordsPerPage,$culture,$searchBy, $searchQuery){
		$data = $this->attributeValueMappingRepository->getAttributeSwatchesColor($attributeId,$start_index, $recordsPerPage,$searchBy, $searchQuery);

		$returnData = Null;
		$param = array();
		if(count($data['all_data'])>0){
			$attribute_values = json_encode(array_column($data['data'],'pms_id'));
			$param["culture_code"] = $culture;
			$param["attribute_master_id"] = $attributeId;
			$param["attribute_values_master_ids"] = $attribute_values; 
			$param["records_per_page"] = $recordsPerPage;
			$param["page"] = 1;
			$param["is_from_attribute_page"] = 1;
			$this->attributeApi->init('attribute_values_for_list');
			$this->attributeApi->setCallParameters($param);
			$this->attributeApi->doProcess();
			if ($this->attributeApi->isSuccess()) {
				$returnData['api_data'] = $this->attributeApi->getResultArray();
				$returnData['all_data'] = $data['all_data'];
				//$returnData['data'] = $data['data'];
			}
		}
		
		return $returnData;
	}

	public function getAttributeSwatchesColorExport($attributeId){
		return $this->attributeValueMappingRepository->getAttributeSwatchesColorExport($attributeId);
	}

	public function moveswatchimage(){
		
	}
	
	public function getAttributeValueList($attributeId,$language,$recordsPerPage,$start_index){
		$masterValuesData = $this->attributeValueMappingRepository->getAttributeValueMapping($attributeId,null,$start_index,$recordsPerPage);
		$masterValuesIds = array_column($masterValuesData,'pms_id');
		$masterValuesIds = json_encode($masterValuesIds);
// 		attribute-values-for-list
		$params = array('culture_code'=>$language,'attribute_master_id'=>$attributeId,'attribute_values_master_ids' => $masterValuesIds);
		$this->attributeApi->init('attribute_values_for_list');
		$this->attributeApi->setCallParameters($params);
		$this->attributeApi->doProcess();
		if ($this->attributeApi->isSuccess()) {
			$data = $this->attributeApi->getResultArray();
			$returnData = $data;
		}
		else {
			$returnData = Null;
		}
		return $returnData;
	}

	/**
	 * This Function is for get Category Name For Autofill
	 * @author Employee Id : 4246
	 * @param unknown $culture
	 * @param unknown $attributeText
	 * @return NULL
	 */
	public function getAutofillList($culture,$attributeText){
		$data = array();
		if($culture)
		{
			$mappingData = $this->attributeMappingRepository->getAttributeMapping();
			$masterIds = array_column($mappingData, 'pms_id');
			$params = array('culture_code'=>$culture,'attribute_text'=>$attributeText,'exclude_pms_ids' => json_encode($masterIds));
			$this->attributeApi->init('list_autofill_attributes');
			$this->attributeApi->setCallParameters($params);
			$this->attributeApi->doProcess();
			if ($this->attributeApi->isSuccess()) {
				$data = $this->attributeApi->getResultArray();
				$returnData = $data;
			}
			else {
				$returnData = Null;
			}
		}
		else
		{
			$returnData = Null;
		}
		return $returnData;
	}
    /**
	 * Functio for Get Selected Attribute Information
	 * @author Employee Id : 4246
	 * @param unknown $culture
	 * @param unknown $cultures
	 * @param unknown $attributeText
	 * @return NULL
	 */
	function getSelectedAttribute($culture,$cultures,$attributeText)
	{
		$data = array();
		if($culture)
		{
			$params = array('active_culture'=>$culture,'culture_codes'=> $cultures,'attribute_name'=>$attributeText);
			$this->attributeApi->init('selected_attribute');
			$this->attributeApi->setCallParameters($params);
			$this->attributeApi->doProcess();
			if ($this->attributeApi->isSuccess()) {
				$data = $this->attributeApi->getResultArray();
				$returnData = $data;
			}
			else {
				$returnData = Null;
			}
		}
		else
		{
			$returnData = Null;
		}
		return $returnData;
	}

/** Functio for Add Selected Attribute
	 * @author Employee Id : 4246
	 * @param unknown $culture
	 * @param unknown $formData
	 * @param unknown $cultures
	 * @return unknown
	 */
	public function addSelectedAttribute($formData,$cultures)
	{
		$setPostData = array();
		$masterId = 0;
		$attributeTypeId = 0;
		$cultures = json_decode($cultures);
		foreach($cultures as $value)
		{
			foreach($formData as $pData)
			{
				if($pData['name'] == "newAttribute-".$value)
				{
					$setPostData[$value] = $pData['value'];
				}
				if($pData['name'] == "attribute_pms_id-".$value)
				{
					$masterId = $pData['value'];
				}
				if($pData['name'] == "attribute_type")
				{
					$attributeTypeId = $pData['value'];
				}
			}
		}
		//Remove Blank Array Element
		$setPostData =array_filter($setPostData);

		// For New Attribute
		if(count($setPostData) > 0)
		{
			$params = array('pms_id'=>$masterId,'culture_attr_name'=> json_encode($setPostData),'attribute_type_id'=>$attributeTypeId);
			$this->attributeApi->init('add_selected_attribute');
			$this->attributeApi->setCallParameters($params);
			$this->attributeApi->doProcess();
			if ($this->attributeApi->isSuccess()) {
				//call api for add data in master
				$data = $this->attributeApi->getResultArray();
				if($data)
				{
					// add data in Attribute mapping client entity
					$mappingData = $this->attributeMappingRepository->addAttributeMapping($data['id']);
					//$returnData = $mappingData;
				}
				//$returnData = $data;
				$returnData = array("status" => "success_message" , "message"=>"attribute.ATTRIBUTE_ADDED_SUCCESSFULLY","pms_id"=>$mappingData->getPmsId());
			}
			else {
				$returnData = Null;
			}
		}
		else
		{
			// Check Duplication in Mapping Entity
			$dupMappingData = $this->attributeMappingRepository->checkDuplicateAttribute($masterId);
			if($dupMappingData)
			{
				$returnData = array("status" => "error" , "message"=>"attribute.ATTRIBUTE_ALREADY_EXISTS");
			}
			else
			{
				// add data in mapping
				$mappingData = $this->attributeMappingRepository->addAttributeMapping($masterId);
				//$returnData = $mappingData;
				$returnData = array("status" => "success" , "message"=>"attribute.ATTRIBUTE_ADDED_SUCCESSFULLY","pms_id"=>$mappingData->getPmsId());
			}
		}
		return $returnData;
	}
	public function processAttributeData($pms_id, $cultures) {
	    $result = $this->getList($cultures, (array)$pms_id);
        $queueData = array();
		$queueData['pms_id'] = $pms_id;
        if($result){
        	unset($result['count']);
            foreach ($result as $key => $value) {
	    		foreach ($value as $k => $v) {
	    			$queueData['id'] = $value[$k]['local_id'];
                    $queueData['type'] = $value[$k]['attribute_type'];
                    $queueData['data'][] = array('culture' => $key, 'name' => $value[$k]['label']);
	    		}
	    	}
	    }
		return $queueData;
	}


	public function processAttributeValueData($pms_id,$attribute_pms_id, $cultures) {
		$attributeData = $this->getList($cultures,$attribute_pms_id);
		$mappingValueData = $this->attributeValueMappingRepository->getAttributeValueMapping($attribute_pms_id, $pms_id);
        $attrivuteValuData = $this->getAttributeValueInformation($pms_id,$attribute_pms_id,$cultures,$attributeData);
        $sentData = array();
        if($mappingValueData){
            $sentData['pms_id'] = $mappingValueData[0]['pms_id'];
            $sentData['id'] = $mappingValueData[0]['local_id'];
            $sentData['type'] = $attrivuteValuData['en'][0]['attribute_type'];
        }
        foreach($attrivuteValuData as $key=>$data) {
		    $sentData['data'][] = array('culture' => $key, 'pms_attribute_id' => $data[0]['pms_id'], 'attribute_id' => $data[0]['local_id'], 'type' => $data[0]['attribute_type'], 'name' => $data[1]['attribute_value']);
		}
		return $sentData;
	}

	public function getAttributeValueInformation($pms_id,$attribute_pms_id,$cultures,$attributeData){
		$data = array();
		foreach ($cultures as $key=>$culture){
			$params = array('culture_code'=>$culture,'attribute_id'=>json_encode(array($pms_id)),'attribute_master_id'=>$attribute_pms_id);
			$this->attributeApi->init('get_attribute_value_information');
			$this->attributeApi->setCallParameters($params);
			$this->attributeApi->doProcess();
			if ($this->attributeApi->isSuccess()) {
				$data[$culture] = $this->attributeApi->getResultArray();
			}
			array_push($attributeData[$culture],$data[$culture][0]);
		}
		return $attributeData;
	}
	/**
	 * @author: Employee Id: 4808
	 * @Description: This Function is Used to related to AutoSelect AttributeValues Based on attributeId
	 *
	 * @param string $searchStatus
	 * @param string $searchParam
	 * @param string $searchQuery
	 * @param string $sortType
	 * @param string $sortBy
	 * @param string $culture
	 * @param string $brandText
	 * @return multitype:
	 */

	public function getAutoselectAttributeValueList($searchStatus='', $searchParam='', $searchQuery='', $sortType='ASC', $sortBy='ID',$culture="",$attribute_value_text = "",$attribute_id="",$isFromProductPage =false){
		$data = array();
		$valueMappingData = array();
		$params = array('status'=>$searchStatus, 'searchParam'=>$searchParam ,'searchQuery'=>$searchQuery, 'sortType'=>$sortType,
				'sortBy'=>$sortBy,'culture_code'=>$culture,'attribute_value_text'=>$attribute_value_text,'attribute_id'=>$attribute_id);
		/* For Ignore Attribute Values */

		$masterValuesData = $this->attributeValueMappingRepository->getAttributeValueMapping(null);
		$masterValuesIds = array_column($masterValuesData,'pms_id');
		if($isFromProductPage){
			$params['added_pms_ids'] = json_encode($masterValuesIds);
		}elseif($masterValuesIds){
				$params['exclude_pms_ids'] = json_encode($masterValuesIds);
		}
		$this->attributeApi->init('auto_list_attribute_value_list');
		$this->attributeApi->setCallParameters($params);
		$this->attributeApi->doProcess();

		if ($this->attributeApi->isSuccess()) {
			$data = $this->attributeApi->getResultArray();
		}
		return $data;
	}
	/**
	 * @author : Employee Id : 4808
	 * @description This Function is Related to get attribute valkues of LKist
	 * @param unknown $culture
	 * @param unknown $attributeId
	 */
	public function getAttributeValues($cultures,$attribute_id = array()) {
		$cultures = (array) $cultures;
		$data = array();
		$masterIds = (array)$attribute_id;
		//$masterIds = array();
		if(!$masterIds)
		{	//Get PMS ID
		  $mappingData = $this->getAttributeValueMapping();
		  $masterIds = array_column($mappingData, 'pms_id');
		}

		if($masterIds) {
			$params = array('cultures'=>json_encode($cultures),'master_id'=>json_encode($masterIds));
			$this->attributeApi->init('list_brand');
			$this->attributeApi->setCallParameters($params);
			$this->attributeApi->doProcess();
			if ($this->attributeApi->isSuccess()) {
				$data = $this->attributeApi->getResultArray();
			}
		}
		return $data;
	}
	public function getAttributeValueMapping()
	{
		return $this->attributeValueMappingRepository->getAttributeValueMapping();
	}
	/**
	 * @author: Employee Id : 4808
	 * @description : This Function used for get values of attribute values from master
	 */
	public function getSelectAttributeValue($culture,$culture_ids,$attribute_id,$attribute_value_name){
		$data =   array();
		$params = array('culture_code'=>$culture,'culture_ids' => $culture_ids,'attribute_name'=>$attribute_value_name,'attribute_id'=>$attribute_id);

		$this->attributeApi->init('selected_attribute_value');
		$this->attributeApi->setCallParameters($params);
		$this->attributeApi->doProcess();

		if ($this->attributeApi->isSuccess()) {
			$data = $this->attributeApi->getResultArray();
			
			// override api response with our custom response only if we have any response about the master color
			if((isset($data['master_color']) && is_array($data['master_color']) && (!(empty($data['master_color'])))) || $attribute_id == 10)
			{
				$data = $this->getSelectAttributeValueClient($data,$culture,$culture_ids,$attribute_id,$attribute_value_name);
			}
		}
		return $data;
	}

	/**
	 * @author: Employee Id : 4808
	 * @description : This Function used for get values of attribute values from master
	 */
	public function getSelectAttributeValueClient($data,$culture,$culture_ids,$attribute_id,$attribute_value_name){
		// Here we are overriding the master colors of api with the custom master colors from project settings yml file 
		$data['master_color'] = $this->container->getParameter('master_color_swatches');
		
		// Now retrive the $attribute_value_id from api data
		$attribute_value_id = 0;
		if(isset($data[$culture]['attribute_value_id']))
		{
			$attribute_value_id = $data[$culture]['attribute_value_id'];
		}

		// Here we are fetching the custom selected master colors from an entity instead of api
		$data['selected_master_colors'] = array();
		$selectedMasterColorObjArray = $this->attributeColorMasterColorMappingRepository->findByAttributeColorId($attribute_value_id);
		if(isset($selectedMasterColorObjArray) && is_array($selectedMasterColorObjArray) && (!(empty($selectedMasterColorObjArray))))
		{
			foreach($selectedMasterColorObjArray as $selectedMasterColorObjArrayIndex => $selectedMasterColorObj)
			{
				$data['selected_master_colors'][$selectedMasterColorObjArrayIndex]['productColor'] = $selectedMasterColorObj->getAttributeColorId();
				$data['selected_master_colors'][$selectedMasterColorObjArrayIndex]['htmlColor'] = $selectedMasterColorObj->getMasterColorId();
			}
		}
		
		return $data;
	}
	/**
	 * @author : Employee Id : 4808
	 * @description: This function related to add Attribute Value and Mapping of Attribute Value to Local
	 */
	public function setAttributeValueData($culture,$formData,$culture_ids,$attribute_id)
	{
		$setPostData = array();
		$masterId = 0;
		$attributeTypeId = 0;
	    foreach($culture_ids as $key => $value)
		{
			if(array_key_exists('newAttributeValue-'.$key,$formData)){
				$setPostData[$key] = $formData['newAttributeValue-'.$key];
			}
			// For New Value
			if(array_key_exists('attribute_value_id-'.$key,$formData)){
				$masterId = $formData['attribute_value_id-'.$key];
			}
		}
		$master_color = array();
		if(array_key_exists('master_color',$formData)){
			$master_color = $formData['master_color'];
		}
		$setPostData =array_filter($setPostData);
		if(count($setPostData) > 0)
		{

			// If new Entry then First Insert in Master
			$params = array('pms_id'=>$masterId,'culture_attr_value_name'=> json_encode($setPostData),'attribute_id'=>$attribute_id,'master_color' => json_encode($master_color));
			$this->attributeApi->init('add_selected_attribute_value');
			$this->attributeApi->setCallParameters($params);
			$this->attributeApi->doProcess();
			if ($this->attributeApi->isSuccess()) {
				$data = $this->attributeApi->getResultArray();
				if($data)
				{
					// Insert in Mapping Table
					$mappingData = $this->attributeValueMappingRepository->addAttributeValueMapping($data['id'],$data['attribute_master']['id']);
					$returnData = array('status'=>'success_message','message'=>'attribute.ATTRIBUTE_VALUE_ADDED_SUCCESSFULLY','pms_id'=>$mappingData->getPmsId());
				}
			}
			// if its not return Data
			else {
				$returnData = array('status'=>'error_message','message'=>'attribute.ATTRIBUTE_VALUE_NOT_ADDED_SUCCESSFULLY','pms_id'=>"");
			}
		}
		// If Value already exist on master we have to save it on local
		else
		{
			// For Duplicate Data
			$dupMappingData = $this->attributeMappingRepository->checkDuplicateAttributeValue($masterId,$attribute_id);

			if($dupMappingData)
			{
				$returnData = array('status'=>'error_message','message'=>'attribute.ATTRIBUTE_VALUE_ALREADY_EXISTS');
			}
			else
			{
				// Insert New Value in Web Client
				$mappingData = $this->attributeMappingRepository->addAttributeValueMapping($masterId,$attribute_id);
				$returnData = array('status'=>'success_message','message'=>'attribute.ATTRIBUTE_VALUE_ADDED_SUCCESSFULLY','pms_id'=>$mappingData->getPmsId());
			}
		}
		return $returnData;
	}
	
	/**
	 * @author : Employee Id : 4808
	 * @description: This function related to add Attribute Value and Mapping of Attribute Value to Local
	 */
	public function setEditAttributeValueData($culture,$formData,$culture_ids,$attribute_id,$supplierId)
	{
		$setPostData = array();
		$pmsId = 0;
		$attributeTypeId = 0;
		foreach($culture_ids as $key => $value){
			if(array_key_exists('newAttributeValue-'.$key,$formData)){
				$setPostData[$key] = $formData['newAttributeValue-'.$key];
			}
			// For New Value
			if(array_key_exists('attribute_value_id-'.$key,$formData)){
				$pmsId = $formData['attribute_value_id-'.$key];
			}
		}
		$master_color = array();
		if(array_key_exists('master_color',$formData)){
			$master_color = $formData['master_color'];
		}
		
		$colorCode = "";
		if(array_key_exists('color_code',$formData) && $formData['color_code'] != ""){
			$colorCode = $formData['color_code'];
		}
	
		$setPostData =array_filter($setPostData);
		$this->attributeApi->init('edit_selected_attribute_value');
		
		$this->attributeApi->setCallParameters(array('pms_id'=>$pmsId,'culture_attr_value_name' => $setPostData,'attribute_id'=>$attribute_id,'master_color'=>$master_color,'supplier_id'=>$supplierId));
		$this->attributeApi->doProcess();
		if ($this->attributeApi->isSuccess()) {
			$attributeData = $this->attributeApi->getResultArray();
			
			if(!empty($attributeData)){
				$attributeValueId = isset($attributeData['attribute_data']['id'])?$attributeData['attribute_data']['id']:'';
				// For Duplicate Data
				$dupMappingData = $this->attributeMappingRepository->checkDuplicateAttributeValue($attributeValueId,$attribute_id);
				if(!$dupMappingData){
					// Insert New Value in Web Client
					$mappingData = $this->attributeMappingRepository->addAttributeValueMapping($attributeValueId,$attribute_id);
					$this->attributeValueMappingRepository->removeAttributeValueMapping($pmsId,$attribute_id);
					$old_name = $this->container->getParameter('swatches_image.file_path').'/'.$pmsId.'.jpg';
					if (file_exists($old_name)) {
						$new_name = $this->container->getParameter('swatches_image.file_path').'/'.$attributeValueId.'.jpg';
						rename($old_name, $new_name);
					}
				}else{
					//$this->attributeValueMappingRepository->updateAttributeValueMapping($attributeValueId,$attribute_id,$colorCode);
				}
				
				//SOLR SYNC CODE START
				$env = $this->container->getParameter("kernel.environment");
				$localization_to_update = array($this->request->get('_locale'));
				$projectSetting = $this->request->get('project_setting');
				$instanceId = $this->request->get('project_setting')['instance_id'];
				$attributeValueProductIds = (!empty($attributeData['product_data']))?$attributeData['product_data']:'';
				if(is_array($attributeValueProductIds)){
					foreach($attributeValueProductIds as $key=>$value){
						$this->productApiManager->updateSolrData($value,$localization_to_update,$projectSetting['project_id'],$env,$instanceId,'update');
					}
				}
				$returnData = array('status'=>'success_message','message'=>'attribute.ATTRIBUTE_VALUE_UPDATED_SUCCESSFULLY','pms_id'=>$attributeValueId);
				//SOLR SYNC CODE END
			}
		}else{
			$returnData = array('status'=>'error_message','message'=>'attribute.ATTRIBUTE_VALUE_NOT_UPDATED_SUCCESSFULLY','pms_id'=>"");
		}
		return $returnData;
	}
	/**
	 * @author : Employee Id : 4808
	 * @description: This function related to add Attribute Value and Mapping of Attribute Value to Local
	 */
	public function addCultureAttributeValue($culture,$attribute_id,$post_data,$culture_ids,$apiManager,$supplierId)
	{
		if(isset($post_data['attribute_value_id-'.$culture]) && $post_data['attribute_value_id-'.$culture] > 0)
		{
			$attribute_value_id = $post_data['attribute_value_id-'.$culture];
		}
		if(isset($post_data['custom_attribute_name-'.$culture]) && $post_data['custom_attribute_name-'.$culture] != '')
		{
			$custom_attribute_name = $post_data['custom_attribute_name-'.$culture];
		}
		
		
		// call api only for add mode
		if($attribute_value_id > 0)
		{
			// Before editing the color master data in custom table, remove the old custom master data
			$this->attributeColorMasterColorMappingRepository->removeAttributeColorMasterColorMappingByAttributeColorId($attribute_value_id);
				
			// Edit the color master data in custom table
			$post_data['client_master_id'] = $post_data['master_color'];
			foreach($post_data['client_master_id'] as $index => $clientMasterId)
			{
				$mappingData = $this->attributeColorMasterColorMappingRepository->addAttributeColorMasterColorMapping($attribute_value_id,$clientMasterId);
			}
			$response = array();
			$response['status'] = 'success_message';
			$response['message'] = $this->translator->trans('attribute.ATTRIBUTE_VALUE_UPDATED_SUCCESSFULLY');
			
			/* Solr Sync Coding Started */
			$setPostData = array();
			$pmsId = 0;
			$attributeTypeId = 0;
			$formData = $post_data;
			foreach($culture_ids as $key => $value){
				if(array_key_exists('newAttributeValue-'.$key,$formData)){
					$setPostData[$key] = $formData['newAttributeValue-'.$key];
				}
				// For New Value
				if(array_key_exists('attribute_value_id-'.$key,$formData)){
					$pmsId = $formData['attribute_value_id-'.$key];
				}
			}
			$master_color = array();
			if(array_key_exists('master_color',$formData)){
				$master_color = $formData['master_color'];
			}
			
			$colorCode = "";
			if(array_key_exists('color_code',$formData) && $formData['color_code'] != ""){
				$colorCode = $formData['color_code'];
			}
		
			$setPostData =array_filter($setPostData);
			$pmsId = $attribute_value_id;
			$this->attributeApi->init('edit_selected_attribute_value');
			
			$this->attributeApi->setCallParameters(array('pms_id'=>$pmsId,'culture_attr_value_name' => json_encode(array($culture=>$custom_attribute_name)),'attribute_id'=>$attribute_id,'master_color'=>array(),'supplier_id'=>$supplierId));
			$this->attributeApi->doProcess();
			if ($this->attributeApi->isSuccess()) {
				$attributeData = $this->attributeApi->getResultArray();
					
				if(!empty($attributeData)){
					$attributeValueId = isset($attributeData['attribute_data']['id'])?$attributeData['attribute_data']['id']:'';			
					//SOLR SYNC CODE START
					$env = $this->container->getParameter("kernel.environment");
					$localization_to_update = array($this->request->get('_locale'));
					$projectSetting = $this->request->get('project_setting');
					$instanceId = $this->request->get('project_setting')['instance_id'];
					$attributeValueProductIds = (!empty($attributeData['product_data']))?$attributeData['product_data']:'';
					if(is_array($attributeValueProductIds)){
						foreach($attributeValueProductIds as $key=>$value){
							$this->productApiManager->updateSolrData($value,$localization_to_update,$projectSetting['project_id'],$env,$instanceId,'update');
						}
					}
					
					/* Update Local Mapping */
					if($attributeValueId != '')
					{
						$dupMappingData = $this->attributeMappingRepository->checkDuplicateAttributeValue($attributeValueId,$attribute_id);
						if(!$dupMappingData){
							// Insert New Value in Web Client
							$mappingData = $this->attributeMappingRepository->addAttributeValueMapping($attributeValueId,$attribute_id);
						}
					}
					
					/* clear the redis */
					$this->moduleCachePrefix='__swatchManagement__';
					$cacheKey=RedisCacheService::generateKey($this->statsh_cache_wrapper,array('Swatchesvalue', $culture),$this->moduleCachePrefix);
					RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$cacheKey);
					
					$returnData = array('status'=>'success_message','message'=>'attribute.ATTRIBUTE_VALUE_UPDATED_SUCCESSFULLY','pms_id'=>$attributeValueId);
					//SOLR SYNC CODE END
				}
			}else{
				$returnData = array('status'=>'error_message','message'=>'attribute.ATTRIBUTE_VALUE_NOT_UPDATED_SUCCESSFULLY','pms_id'=>"");
			}
			/* Solr Sync Coding Ended */
		}
		else
		{
			// Before submitting this data to api, update the master_color
			if(isset($post_data['master_color']))
			{
				// and before updating the master_color take the backup of master color
				$post_data['client_master_id'] = $post_data['master_color'];
				foreach($post_data['master_color'] as $index => $clientMasterId)
				{
					foreach($this->masterColorSwatches as $masterColorSwatchesIndex => $masterColorSwatchesData)
					{
						if(isset($masterColorSwatchesData['client_master_id']) && $masterColorSwatchesData['client_master_id'] == $clientMasterId)
						{
							$post_data['master_color'][$index] = $masterColorSwatchesData['api_master_id'];
						}
					}
				}
			}
				
			// Insert this color in trim color as well
			$trim_attribute_id = 210;
			$apiManager->setAttributeValueData($culture,$post_data,$culture_ids,$trim_attribute_id);
			// Insert this color in barrel color as well
			$barrel_attribute_id = 209;
			$apiManager->setAttributeValueData($culture,$post_data,$culture_ids,$barrel_attribute_id);
				
			$response = $apiManager->setAttributeValueData($culture,$post_data,$culture_ids,$attribute_id);
			$cultureNames = array_keys($culture_ids);
				
			if($response['status']=='success_message'){
				$pms_id = $response['pms_id'];
				try{
					foreach($post_data['client_master_id'] as $index => $clientMasterId)
					{
						$mappingData = $this->attributeColorMasterColorMappingRepository->addAttributeColorMasterColorMapping($pms_id,$clientMasterId);
					}
		
					//ERP SYNC
					$erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
					if($erpIntegration && $erpIntegration['productManagement'] == 1 && !empty($this->queueApiManager)) {
						$this->request->attributes->set('object', 'CultureAttributeValue');
						$queueData = $apiManager->processAttributeValueData($pms_id,$attribute_id,$cultureNames);
						$this->queueApiManager->mapQueue('create', $queueData);
					}
					//ERP SYNC END
					// start remove swatch color cache code
					$swatchesColorId = $this->container->getParameter('swatches_color_id');
					if(in_array($attribute_id,$swatchesColorId)){
						$this->moduleCachePrefix='__swatchManagement__';
						$cacheKey=RedisCacheService::generateKey($this->statsh_cache_wrapper,array('Swatchesvalue', $culture),$this->moduleCachePrefix);
						RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$cacheKey);
					}
					// end remove swatch color cache code
				}catch(Exception $e){
					 
				}
				//ERP SYNC END
			}else{
				//PROCESS ERROR
			}
		
			$response['message'] = $this->translator->trans($response['message']);
		}
		return $response;
	}
}
