<?php 
namespace OfficeBrain\Bundle\ProductBundle\Manager\Service;
use Symfony\Component\HttpFoundation\Request;

/**
 * 
 * @author Employee Id: 4808
 * @Description: This is class Related For Brand 
 *
 */
class BrandApiManager
{
	private $cultureManager;
	private $request;
	private $brandApi;
	private $imageManager;

    /**
     * @author Employee Id:4808
     * 
     * @Description: This Function is Related For Intilizer Variable and Objects
     * 
     * @param Request $request
     * @param unknown $brandApi
     * @param unknown $imageManager
     * @param unknown $brandMappingEntity
     * @param unknown $brandMappingRepository
     */
	public function __construct(Request $request, $brandApi, $imageManager,$brandMappingEntity,$brandMappingRepository,$serviceContainer)
	{
		$this->request=$request;
		$this->brandApi=$brandApi;		
		$this->imageManager=$imageManager;
		$this->brandMappingEntity = $brandMappingEntity;
		$this->brandMappingRepository =$brandMappingRepository;

		$this->container = $serviceContainer;
		$this->productApiManager = $this->container->get("office_brain_product_admin_manager");
		$this->entityManager = $this->container->get('doctrine')->getEntityManager();
		
	}
	
    /**
     * @author Employee Id:4808
     * @description: This Function is Used For Brand Listing
     *  
     * @param unknown $cultures
     * @return unknown
     */
	public function getList($cultures,$masterIds = array(),$searchQuery="",$sortBy="",$sortType="",$records_per_page="",$page="",$isFromBrandPage = 0,$supplierId = 0)
	{
		$cultures = (array) $cultures;
		$data = array();
		$masterIds = (array)$masterIds;
		
		$mappingData = $this->getBrandMapping();		
		$pms_id_and_local_id = @array_combine(array_column($mappingData,'pms_id'),array_column($mappingData,'local_id'));
		$called_explicitly = false;
		$status = array_column($mappingData, 'status','pms_id');
		
		
	    if(!$masterIds)
		{	//Get PMS ID and Parent ID			
			$masterIds = array_column($mappingData, 'pms_id');
		}else{
			$called_explicitly = true;
		}
		
		$called_explicitly = true;
		if($masterIds) {	
			$params = array('cultures'=>json_encode($cultures),'master_id'=>json_encode($masterIds),'sort_by' => $sortBy, 'sort_type' => $sortType);
			if($searchQuery){
				$params['search_query'] = $searchQuery;
			}
			$params['records_per_page'] = $records_per_page;
			$params['page'] = $page;
			$params['is_from_brand_page'] = $isFromBrandPage;
			$params['supplier_id'] = $supplierId; // supplierId used for get supplierwise Brand. if project settings "supplierwise_brand":0 its retrive all brand data.
			$this->brandApi->init('list_brand');
			$this->brandApi->setCallParameters($params);
			$this->brandApi->doProcess();
			if ($this->brandApi->isSuccess()) {
				$data = $this->brandApi->getResultArray();
			}else{
				$data = NULL;
			}

			
			
			if($called_explicitly && $data){
				foreach($data as $culture=>$value){
					if($culture != 'count'){
						foreach($value as $index=>$brand_data){
							$pms_id =$data[$culture][$index]['pms_id'] ;
							$data[$culture][$index]['pms_id'] = $pms_id;
							$data[$culture][$index]['local_id'] = $pms_id_and_local_id[$pms_id];
							$data[$culture][$index]['status']=$status[$pms_id];
						}
					}
				}
				$returnData = $data;
			}else{
				$returnData = Null;
			}
		}else{
			$returnData = Null;
		}
		return $returnData;
		
	}
	
	public function getBrandMapping()
	{		
		return $this->brandMappingRepository->getBrandMapping();
	}
	
	/**
	 * @author: Employee Id : 4808
	 * @description: This function used to get Brand List with pagination (Not used)
	 * @param string $searchParam
	 * @param string $searchQuery
	 * @param string $sortType
	 * @param string $sortBy
	 * @param string $cultureid
	 * @param string $culture
	 * @param string $show_name_in_other_culture
	 * @param string $records_per_page
	 * @param string $page
	 * 
	 * @return multitype:
	 */
	public function getBrandList($searchParam='', $searchQuery='', $sortType='ASC', $sortBy='name',$cultureid="",$culture="",$show_name_in_other_culture=false,$records_per_page=12,$page=1)
	{
	    $data = array();
	    $params = array('searchParam'=>$searchParam ,'searchQuery'=>$searchQuery, 'sortType'=>$sortType, 'sortBy'=>$sortBy,
	        'culture_id'=>$cultureid,'show_name_in_other_culture'=>$show_name_in_other_culture,
	        'records_per_page'=>$records_per_page,'page'=>$page);
	
	    $this->brandApi->init('list_complete_brand');
	    $this->brandApi->setCulture($culture);
	    $this->brandApi->setCallParameters($params);
	    $this->brandApi->doProcess();
	
	    if ($this->brandApi->isSuccess()) {
	        $data = $this->brandApi->getResultArray();
	    }
	    return $data;
	}
	
	
	public function getListById($brandId,$cultureId)
	{
		$data=array();
		$params = array('cultureId'=>$cultureId,'brandId'=>$brandId);
		
		$this->brandApi->init("list_brand_by_id");
		$this->brandApi->setCallParameters($params);
		$this->brandApi->doProcess();
		
		if($this->brandApi->isSuccess())
		{
			$data=$this->brandApi->getResultArray();
		}
		return $data;
	}
	/**
	 * @author: Employee Id : 4808
	 * @description: This function used to display the Brand add
	 * @param unknown $culture
	 * @param unknown $brandName
	 * @param unknown $description
	 * @param number $mappingCultureId
	 * @param number $mappingbrandId
	 * @param string $image
	 * @param string $copyImageId
	 * @return multitype:string |multitype:string NULL
	 */
	public function add($culture, $brandName,$description,$mappingCultureId = 0,$mappingbrandId=0,$image="",$copyImageId="")
	{
		if($image)
		{
			$response = $this->imageManager->addImage($image,"brand");
			if($response['status']=="success")
			{
				$imgId = $response['data']['id'];
			}
		}else if($copyImageId){
			$imgId = $copyImageId;
		}
		
		$params=array('cultureId'=>$culture,'brandName'=>$brandName,'description'=>$description,'mapping_culture_id'=>$mappingCultureId,
				'mapping_brand_id'=>$mappingbrandId,'image_id'=>$imgId);

		$this->brandApi->init('add_brand');
		$this->brandApi->setCallParameters($params);
		$this->brandApi->setPostMethodTrue();
		$this->brandApi->doProcess();
	
		if ($this->brandApi->isSuccess()) {
			return array('status'=>'success','message'=>'Brand added successfully');
		}
	
		return array('status'=>'error', 'message'=>$this->brandApi->getErorDescription());
	}
	public function update($Culture,$Name,$Description,$MappingCultureId,$MappingCultureBrandId,$brandid,$image="",$isRemoveRequest=0)
	{
		
		$imgId = "";
		if($image)
		{
			$response = $this->imageManager->addImage($image,"brand");
			if($response['status']=="success")
			{
				$imgId = $response['data']['id'];
			}
		}
		
		$params=array('brandId'=>$brandid,'cultureId'=>$Culture,'brandName'=>$Name,'description'=>$Description,'mappingCultureId'=>$MappingCultureId,'mappingBrandId'=>$MappingCultureBrandId,'image_id'=>$imgId,'remove_request'=>$isRemoveRequest);

		$this->brandApi->init('update_brand');
		$this->brandApi->setCallParameters($params);
		$this->brandApi->setPostMethodTrue();
		$this->brandApi->doProcess();
		if ($this->brandApi->isSuccess()) 
		{
			return array('status'=>'success','message'=>'Brand update successfully');
		}
		return array('status'=>'error', 'message'=>$this->brandApi->getErorDescription());

	}
	public function getListCopyCultureById($id)
	{
		
		$data=array();
		$params = array('brandId'=>$id);
		
		$this->brandApi->init("list_makecopy_brand_by_id");
		$this->brandApi->setCallParameters($params);
		$this->brandApi->doProcess();
		
		if($this->brandApi->isSuccess())
		{
			$data=$this->brandApi->getResultArray();
		}
		return $data;
		
	}
	public function addKeyword($param)
	{
		$data=array();
		$this->brandApi->init("add_keyword");
		$this->brandApi->setCAllParameters($param);
		$this->brandApi->doProcess();
		if($this->brandApi->isSuccess())
		{
			$data = $this->brandApi->getResultArray();
		}
		return $data;
	}

	/**
     * Employee Id : 5083
     * Description: This Function used to delete Brand
     *
     */
    public function delete($brand_id,$supplier_id){

    	$params = array('brand_id'=>$brand_id ,'supplier_id'=>$supplier_id);

	    $this->brandApi->init('check_brand_mapping_with_product');
	    $this->brandApi->setCallParameters($params);
	    $this->brandApi->doProcess();

	    if ($this->brandApi->isSuccess()) {
	        $data = $this->brandApi->getResultArray();
	    }
	   if($data[0]['brandcount']==0){
        $brandObj = $this->brandMappingRepository->deleteBrand($brand_id);
	      if(is_object($brandObj)){
	        $data = array('status'=>'success_message','message'=>'Brand delete successfully');
	      }else{
	      	$data = array('status'=>'error','message'=>'Brand delete issue');
	      }
	   }else{
        $data = array('status'=>'error','message'=>'Brand mapped with product');
	   }
       return $data;
    }


    public function getUpdateInfoById($brandId,$cultureId){

    	$params = array('cultureId'=>$cultureId,'brandId'=>$brandId);
		$brandMapByPmsId = $this->brandMappingRepository->findOneBy(array("pmsId"=>$brandId));
		//var_dump($brandMapByPmsId->getImage());exit;
		$this->brandApi->init("get_selected_brand");
		$this->brandApi->setCallParameters($params);
		$this->brandApi->doProcess();

		if($this->brandApi->isSuccess())
		{
			$data=$this->brandApi->getResultArray();
		}
		/*if($brandMapByPmsId->getImage()!=''){
		$webImagePath=$this->container->getParameter('brand_upload_base_url');
		$data['imageurl']= $webImagePath;
		$data[0]['orgName']= $brandMapByPmsId->getImage();
	    }*/
		//echo '<pre/>';print_r($data);exit;
		return $data;

	}

	public function updateBrandCategory($postData,$culture,$supplierId)
    {
		$setPostData = array();
		$setPostData[$culture] = $postData['newBrand-'.$culture];
		$brandId = $postData['brandid'];
		//$tempPath = $this->container->getParameter('tmp_image_upload_path');
		//$uploadBrandPath = $this->container->getParameter('brand_upload_base_path');

		$imageName = $postData['image_category'];
		if (strpos($imageName, 'brand') !== false) {
			$imageData=explode('/',$imageName);
			if(!file_exists($uploadBrandPath.$imageName)){
			copy($postData['api_image'], $tempPath.$imageData[1]);
		    }
			$imageName =$imageData[1];
         }else{
         	$imageName = $imageName;
         }
        //echo $imageName; die;
		$activeCultureId =$postData['activeculture_id'];
		if(count($setPostData) > 0)
		{
			//For Image Add
			$imageId = "";
			if($imageName){
				// For image Add in Api
				$imageData = $this->imageManager->addImage('brand/'.$imageName);
				if($imageData){
					if($imageData['status'] == "success"){
						$imageId = $imageData['data']['id'];
					}
				}
			}

			$brandNames = json_encode($setPostData);
			$data = array();
			$params = array('brand_id'=>$brandId,'brand_names'=>$brandNames,'supplier_id'=>$supplierId,'culture_id'=>$activeCultureId,'culture_name'=>$culture,'brand_image_id'=>$imageId);
			$this->brandApi->init('update_selected_brand');
			$this->brandApi->setCallParameters($params);
			$this->brandApi->doProcess();

			if ($this->brandApi->isSuccess()) {
				$data = $this->brandApi->getResultArray();
				$master_id = $data['data'];
				$brandMapByPmsId = $this->brandMappingRepository->findOneBy(array("pmsId"=>$master_id));
				if(is_object($brandMapByPmsId))
				{
					$brandMappingObj = $this->brandMappingRepository->updateBrand($brandMapByPmsId,$master_id,$imageName);
					// Move Uploaded Image
					/*$tempPath = $this->container->getParameter('tmp_image_upload_path');
		            $uploadBrandPath = $this->container->getParameter('brand_upload_base_path');
					if($imageName != null && $imageName != ""){
						if(!IS_DIR($uploadBrandPath)){
							mkdir($uploadBrandPath,0777,true);
						}
						if(file_exists($tempPath.$imageName)){
							$status = rename($tempPath.$imageName, $uploadBrandPath.$imageName);
						}
					}*/

					// Move Upload Image
						$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'];
						$brandProductIds = (!empty($data['product_ids']))?$data['product_ids']:'';

						if(is_array($brandProductIds)){
							foreach($brandProductIds as $key=>$value){
								$this->productApiManager->updateSolrData($value['id'],$localization_to_update,$projectSetting['project_id'],$env,$instanceId,'update');
							}
						}
					$array_to_return = array('status'=>'success_message','message'=>'Brand update successfully','pms_id'=>$brandMappingObj->getPmsId());
				}
				else
				{
					$brandMapByPmsId = $this->brandMappingRepository->findOneBy(array("pmsId"=>$brandId));
					$brandMappingObj = $this->brandMappingRepository->updateBrand($brandMapByPmsId,$master_id,$imageName);
					if(count($brandMappingObj) > 0){
						// Move Uploaded Image
						/*$tempPath = $this->container->getParameter('tmp_image_upload_path');
		                $uploadBrandPath = $this->container->getParameter('brand_upload_base_path');
						if($imageName != null && $imageName != ""){
							if(!IS_DIR($uploadBrandPath)){
								mkdir($uploadBrandPath,0777,true);
							}
							if(file_exists($tempPath.$imageName)){
								$status = rename($tempPath.$imageName, $uploadBrandPath.$imageName);
							}
						}*/ 
						// End Move Uploaded Image

						$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'];
						$brandProductIds = (!empty($data['product_ids']))?$data['product_ids']:'';

						if(is_array($brandProductIds)){
							foreach($brandProductIds as $key=>$value){
								$this->productApiManager->updateSolrData($value['id'],$localization_to_update,$projectSetting['project_id'],$env,$instanceId,'update');
							}
						}
						$array_to_return = array('status'=>'success_message','message'=>'Brand update successfully','pms_id'=>$brandMappingObj->getPmsId());
					}

				}

			}
		}
         return $array_to_return;

    }


	public function deleteKeyword($param)
	{
		$this->brandApi->init("delete_keyword");
		$this->brandApi->setCAllParameters($param);
		$this->brandApi->doProcess();
		if($this->brandApi->isSuccess())
		{
			return array('status'=>'success','message'=>'Deleted successfully');
		}
		return array('status'=>'error', 'message'=>$this->brandApi->getErorDescription());
	}
	public function isexistKeyword($param)
	{
		$data=array();
		$this->brandApi->init("is_exist_keyword");
		$this->brandApi->setCAllParameters($param);
		$this->brandApi->doProcess();
		if($this->brandApi->isSuccess())
		{
			$data = $this->brandApi->getResultArray();
		}
		return $data;
	}
	public function listKeyword($param)
	{
		$data=array();
		$this->brandApi->init("list_keyword");
		$this->brandApi->setCAllParameters($param);
		$this->brandApi->doProcess();
		if($this->brandApi->isSuccess())
		{
			$data = $this->brandApi->getResultArray();
		}
		return $data;
	}
	public function listProduct($searchStatus,$searchParam='', $searchQuery='', $sortType='ASC', $sortBy='name',$cultureid="",$supplier_id="",$records_per_page=12,$page=1)
	{	
		$data = array();
		$params = array('status'=>$searchStatus,'searchParam'=>$searchParam ,'searchQuery'=>$searchQuery, 'sortType'=>$sortType, 'sortBy'=>$sortBy,
					'culture_id'=>$cultureid,'supplier_id'=>$supplier_id,'records_per_page'=>$records_per_page,'page'=>$page);
	

		$this->brandApi->init('list_product');
		$this->brandApi->setCallParameters($params);
		$this->brandApi->doProcess();
		
		if ($this->brandApi->isSuccess()) {
			
			$data = $this->brandApi->getResultArray();
			
		}
		return $data;
		
	}
	public function changeStatus($ids,$status,$cultureId){
		
		$params = array('product_id'=>json_encode($ids), 'status'=>$status,'culture_id'=>$cultureId);
				
		$this->brandApi->init('change_status_product');
		$this->brandApi->setCallParameters($params);
		$this->brandApi->doProcess();
		
		if ($this->brandApi->isSuccess()) {
			if($status){
				return array('status'=>'success','message'=>'Product is activated successfully');
			}else {
				return array('status'=>'success','message'=>'Product is de-activated successfully');
			}
		}
		
		return array('status'=>'error', 'message'=>$this->brandApi->getErorDescription());
	}
	/**
	 * @author: Employee Id: 4808
	 * @Description: This Function is Used to related to AutoSelect Brand
	 * 
	 * @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 getAutoselectList($searchStatus='', $searchParam='', $searchQuery='', $sortType='ASC', $sortBy='ID',$culture="",$brandText = ""){
		$data = array();
		
		$params = array('status'=>$searchStatus, 'searchParam'=>$searchParam ,'searchQuery'=>$searchQuery, 'sortType'=>$sortType,
				'sortBy'=>$sortBy,'culture_code'=>$culture,'brand_text'=>$brandText);
		
		$mappingData = $this->getBrandMapping();
		if($mappingData){
			$mappingValuesIds = array_column($mappingData,'pms_id');
			$params['exclude_brand_ids'] = json_encode($mappingValuesIds);
		}
		$this->brandApi->init('auto_list_brand');
		$this->brandApi->setCallParameters($params);
		$this->brandApi->doProcess();
		
		if ($this->brandApi->isSuccess()) {
			$data = $this->brandApi->getResultArray();
		}
		return $data;
	}
	/**
	 * @author: Employee Id :4808
	 * @description: This function used to get Selected Brand
	 * 
	 * @param string $searchStatus
	 * @param string $searchParam
	 * @param string $searchQuery
	 * @param string $sortType
	 * @param string $sortBy
	 * @param string $culture
	 * @param string $cultureIds
	 * @param string $categoryName
	 * @return multitype:
	 */
	public function getSelectBrand($searchStatus='', $searchParam='', $searchQuery='', $sortType='ASC', $sortBy='ID',$culture="",$cultureIds = "",$brandName = ""){
		
		$data =   array();
		$params = array('status'=>$searchStatus, 'searchParam'=>$searchParam ,'searchQuery'=>$searchQuery, 'sortType'=>$sortType,
				  'sortBy'=>$sortBy,'culture_code'=>$culture,'culture_ids' => $cultureIds,'brand_name'=>$brandName);

		$this->brandApi->init('selected_brand');
		$this->brandApi->setCallParameters($params);
		$this->brandApi->doProcess();
	
		if ($this->brandApi->isSuccess()) {
			$data = $this->brandApi->getResultArray();
		}
		return $data;
	}
	/**
	 * @author: Employee Id: 4808
	 * @description: This function is Related to insert data in Brand
	 * 
	 * @param unknown  $culture
	 * @param unknown  $postData
	 * @param unknown  $culture_ids
	 * @param unknown  $fileData
	 */
	public function setBrandData($culture,$postData,$culture_ids)
	{
		$cat_master_id = "";
		$setPostData = array();
		$masterId = 0;
		$textCounter = 0;
		$brandImageName="";
		$supplierId = 0;
		foreach($culture_ids as $key => $value)
		{
			foreach($postData as $pkey=>$pData)
			{
				// For new Value
				if($pData['name']=='newBrand-'.$key){
					$setPostData[$key] = $pData['value'];
				}
				if($pData['name'] == 'brand_id-'.$key){
					$masterId = $pData['value'];
				}
				if($pData['name'] == 'image_brand'){
					$brandImageName = $pData['value'];
				}
				if($pData['name'] == 'supplier_id'){
					$supplierId = $pData['value'];
				}
			}
		}
		//For Image Add
		$imageId = "";
		if($brandImageName){
			// For image Add in Api
			$imageData = $this->imageManager->addImage('brand/'.$brandImageName);
			if($imageData){
				if($imageData['status'] == "success"){
					$imageId = $imageData['data']['id'];
				}
			}
		}
		// check here that if brand is already exist then return
		if($masterId != 0){
		  $brandMapByPmsId = $this->brandMappingRepository->findOneBy(array("pmsId"=>$masterId));
		  if (count($brandMapByPmsId) > 0) {
		  	$array_to_return = array('status'=>'error','message'=>'product.BRAND_ALREADY_EXISTS');
		  	return $array_to_return;		  	
		  }
		}

		$brandMappingObj = array();
		
		if(count($setPostData) > 0)
		{	
			$brandNames = json_encode($setPostData);
			$data = array();
			$params = array('brand_id'=>$masterId,'brand_names'=>$brandNames,'supplier_id'=>$supplierId);
			if($imageId){
				$params['brand_image_id'] = $imageId;
			}
			$this->brandApi->init('add_new_brand');
			// $this->brandApi->setTraceMethodTrue();
			$this->brandApi->setCallParameters($params);
			$this->brandApi->doProcess();
			if ($this->brandApi->isSuccess()) {
				$data = $this->brandApi->getResultArray();
				$master_id = $data['data'];
				$brandMapByPmsId = $this->brandMappingRepository->findOneBy(array("pmsId"=>$masterId));
				if(is_object($brandMapByPmsId))
				{
					$brandMappingObj = $this->brandMappingRepository->updateBrand($brandMapByPmsId);
					$array_to_return = array('status'=>'success','message'=>'product.BRAND_ADDED_SUCCESSFULLY','pms_id'=>$brandMappingObj->getPmsId());
				}
				else
				{
					$brandMappingObj = $this->brandMappingRepository->addBrandMapping($master_id);
					if(count($brandMappingObj) > 0){
						$array_to_return = array('status'=>'success','message'=>'product.BRAND_ADDED_SUCCESSFULLY','pms_id'=>$brandMappingObj->getPmsId());
					}
				}
			}
		} else {	
			if($masterId != 0)
			{	
				$brandMappingObj = $this->brandMappingRepository->addBrandMapping($masterId);
				$array_to_return = array('status'=>'success','message'=>'product.BRAND_ADDED_SUCCESSFULLY','pms_id'=>$brandMappingObj->getPmsId());
			}
		}

		return $array_to_return;
	}

    public function processBrandData($pms_id, $cultures) {
        $result = $this->getList($cultures, (array)$pms_id);
        $queueData = array();        
        $queueData['pms_id'] = $pms_id;
        foreach ($result as $key => $value) {
            $queueData['id'] = $value[$pms_id]['local_id'];
            $queueData['data'][] = array('culture' => $key, 'name' => $value[$pms_id]['name'], 'image' => $value[$pms_id]['image']);
        }
        return $queueData;
    }
    /**
     * Employee Id : 4808
     * Description: This Function used to add Brand Image
     * 
     */
    public function addBrandImage($files)
    {
    	return $this->imageManager->addImage($image,$uploadPath, $placeInuploadDir = true);
    }

    public function changeBrandStatus($id)
    {
    	return $this->brandMappingRepository->changeBrandStatus($id);
    }
}
?>
