<?php

namespace OfficeBrain\CustomBundle\ProductBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
// use OfficeBrain\CustomBundle\ProductBundle\Form\SkuMaskingType;
use OfficeBrain\Bundle\CoreBundle\CustomeHandler as FormErrorManager;
//use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use OfficeBrain\Bundle\SearchBundle\Form\Type\ProductSearchType;
use OfficeBrain\Bundle\SearchBundle\Form\Data\ProductSearchData;
/**
 * @author OfficeBrain 5497 <info@officebrain.com>
 *
 * Description : Sku Masking Admin controller class
 *
 * @Route("/admin/{_locale}/sku-masking")
 **/
class SkuMaskingController extends Controller
{
    private $request;

    private $session;

    private $translator;

    private $projectSetting;

    private $recordsPerPage;

    private $skuMasking;

    private $responseArray;
    
    private $productApiManager;
    
    private $projectUserSetting;
    
    public function __construct()
    {
    	$this->productApiManager = null;
    }

    public function __destruct()
    {
        unset($this->request);
        unset($this->session);
        unset($this->translator);
        unset($this->projectSetting);
        unset($this->skuMasking);
        unset($this->responseArray);
        unset($this->productApiManager);
    }

    public function initAction()
    {
		
        $this->request = $this->getRequest();
        $this->session = $this->request->getSession();
        $this->translator = $this->get('translator');
        $this->projectSetting = $this->request->get('project_setting');
        $this->skuMasking = $this->get('office_brain_sku_masking_manager');
        $this->productApiManager = $this->get("office_brain_product_admin_manager");
        $this->responseArray = array();
        
        $this->formErrorManager = new FormErrorManager\JsonError();
        $this->productApiManager = $this->get("office_brain_product_admin_manager");
        $this->brandApiManager = $this->get("office_brain_brand_api_manager");
        $this->categoryApiManager = $this->get("officebrain_category_api_manager");
        $this->userManager = $this->get("office_brain_user_manager");
        $this->projectUserSetting = $this->request->get('project_user_setting');
        $this->userId = $this->projectUserSetting['user_data']->getId();
        
        $this->user = $this->projectUserSetting['user_data'];
        if (!$this->getUser() && $this->request->isXmlHttpRequest()) {
        	// throw new AccessDeniedHttpException();
        }
        if ($this->has('office_brain_queue_api_manager')) {
        	$this->request->attributes->set('object', 'Product');
        	$this->queueApiManager = $this->get('office_brain_queue_api_manager');
        }
        /* Start Custom code to fetch all subshop instance */
        // $subshopObj = $this->skuMasking->findBySubshopByStatus($this->userId);
        $projectSetting = $this->request->get('project_setting');
        $this->instanceArray = array();
        // foreach($subshopObj as $key=>$val){
        	// array_push($this->instanceArray,$val->getParentId());
        // }
        array_push($this->instanceArray,$projectSetting['instance_id']);
        //$this->instanceArray = array(7,8);
        $this->searchManager = $this->get('office_brain_search_manager');
        $this->entityManager = $this->getDoctrine()->getManager();
        $this->productTagManager = $this->get('office_brain_product_tag_manager');
        $this->tagProductMappingRepository = $this->entityManager->getRepository('OfficeBrainProductTagBundle:PrivateTagProductMapping');
        $this->solrProductManager =$this->get('office_brain_solr_product_mapping_manager');
        /* Ends Custom code to fetch all subshop instance */
    }

    /**
     * @author Employee Id: 5497
     *
     * Description : This function used for List Product Information
     *
     * @Route("/list/{page}",
     * name="officebrain_custom_productbundle_sku_masking_admin_list_wo_culture",
     * options={"expose"=true},
     * requirements={"records_per_page"="12|24|48|100|996", "page"="\d+"},
     * defaults={"records_per_page"=100,"page"=1})
     *
     * @Route("/list/{country}/{language}/{page}",
     * name="officebrain_custom_productbundle_sku_masking_admin_list",
     * requirements={"records_per_page"="12|24|48|100|996","page"="\d+"},
     * defaults={"records_per_page"=20,"page"=1})
     * @Template("OfficeBrainCustomBundleProductBundle:SkuMasking:skuMaskingList.html.twig")
     */
    public function skuMaskingListAction()
    {
        $this->initAction();
        $projectSetting = $this->request->get('project_setting');
        list($defaultCulture,$defaultCountry) = explode("_",$this->request->get("_locale"));
		
		$param = $this->request->get('_route_params');
        $culture = $this->request->get('language',$defaultCulture);
        $country = $this->request->get('country',$defaultCountry);
        $activeCulture = $culture;
		$searchStatus = $this->request->query->get('search_status', '1');
		$searchQuery = $this->request->query->get('search_query', '');
		$sortBy = $this->request->query->get('sort', 'updatedAt');
		$sortType = $this->request->query->get('direction', 'desc');
		$searchParam = $this->request->query->get('search_param', '');
		$supplier_id = $this->request->query->get('supplier_id','');
		$brandIds = $this->request->query->get('brand_id','');
		$catIds = $this->request->query->get('cat_id','');
		
		//$instanceType = strtolower($this->container->getParameter('default_main_instance_type'));
		$instanceType = $projectSetting['instance_type'];
		
		if ($this->user->getUserType()=='admin' && $instanceType=='association'){
			$supplier_id = $this->request->query->get('supplier_id','');
		} else if($this->user->getUserType()=='supplier' || $this->user->getUserType()=='distributor' || 
				($this->user->getUserType() == 'admin' && $instanceType == 'distributor') || ($this->user->getUserType() == 'admin' && $instanceType == 'supplier')){
			$supplier_id = $this->user->getObCustomerId();
			$supplier_id = str_replace(array('OB','ob'), '', $supplier_id);
			
			if(empty($supplier_id)){
				$supplier_id = 0;
			}
		}else{
			$supplier_id = 0;
		}

        if ($this->user->getUserType()=='admin' && $instanceType=='distributor' && $projectSetting['instance_id'] == $this->container->getParameter('default_main_instance_id')) {
            $supplier_id = '';   
        }

        if ($this->user->getUserType()=='admin' && $this->request->query->get('supplier_id') != '') {
        	$supplier_id = $this->request->query->get('supplier_id','');
        }

        $cultureCategory =  $activeCulture . "_" . $country;
		
		// For Pagination
		$page = $this->request->get('page', '1');
		$records_per_page = $param['records_per_page'];
		$recordsPerPage = $this->request->query->get('recordsPerPage',$records_per_page);
		$start_index = (($page - 1) * $recordsPerPage - 1);
		// End Pagination
		
		$projectId = $projectSetting['project_id'];
		//search with new sku
		$searchParamOriginal = $searchParam;
		$searchQueryOriginal = $searchQuery;
		if($searchParam == 'new_sku_number'){
			$skuMasking = $this->skuMasking->getMaskingByNewSku($searchQuery);
			if (is_object($skuMasking)) {//record found
				$searchParam = 'sku_number';
				$searchQuery = $skuMasking->getSku();
				$productData = $this->productApiManager->listProduct($searchStatus,$searchParam, $searchQuery, $sortType, $sortBy,$activeCulture,$country,$supplier_id,$records_per_page,$page,$projectId,$brandIds,$catIds,true);
			}
			else{
				$productData = $this->productApiManager->listProduct($searchStatus,$searchParam, $searchQuery, $sortType, $sortBy,$activeCulture,$country,$supplier_id,$records_per_page,$page,$projectId,$brandIds,$catIds);
			}
		}
		else{
			$productData = $this->productApiManager->listProduct($searchStatus,$searchParam, $searchQuery, $sortType, $sortBy,$activeCulture,$country,$supplier_id,$records_per_page,$page,$projectId,$brandIds,$catIds);
		}
		//end search with new sku	
		$supplierData = $this->productApiManager->getSupplierNameList($projectId);
		

 		//$brandData = $this->brandApiManager->getList($culture);
		$brandData = array();

		//GET CATEGORY AND SUBCATEGORY
 		$categoryAndSubCategoryData = $this->categoryApiManager->getList(array($cultureCategory),array(),true);
		$this->catArrayNew = array();
 		if ($categoryAndSubCategoryData) {
 			foreach($categoryAndSubCategoryData[$cultureCategory] as $catKey=>$categoryAndSubCategory){
 			    $this->recursiveCategory($categoryAndSubCategory);
 			}
 			// Sort Category array using category name
 	        usort($this->catArrayNew, function ($a, $b) {
 	            return strcasecmp($a['cat_name'], $b['cat_name']);
 	        });
 		}
		 $data['category_SubCategory_data'] = $this->catArrayNew;
		 $paginator  = $this->get('knp_paginator');
		 $data['pagination'] = $paginator->paginate($productData, $page, $recordsPerPage);
		 $data['page']=$page;
		 $data['search_status']=$searchStatus;
		 $data['search_query']=$searchQueryOriginal;
		 $data['sort_by']=$sortBy;
		 $data['sort_type']=$sortType;
		 $data['search_param']=$searchParamOriginal;
		 $data['supplier_id']=$supplier_id;
		 $data['records_per_page'] = $recordsPerPage;
		$data['supplier_data'] = $supplierData;
		$data['brand_id']=$brandIds;
		$data['cat_id']=$catIds;
 		$data['brand_data']= isset($brandData[$culture]) ? $brandData[$culture] : array();
//		$data['brand_data']= array();
		$data['INSTANCE_TYPE'] = $instanceType;
		
		if(array_key_exists('status',$productData) && $productData['status'] == 'error' && is_array($productData))
		{
			$productSentData = array();
			$data['error_message'] = $productData['error_message'];
		}
		else
		{
			if($productData['data']){
				$data['total_product'] = $productData['count'];
				$data['image_url'] = (array_key_exists('image_url',$productData)?$productData['image_url']:'');
				$productSentData = $productData['data'];
			}else{
				$productSentData = array();
				$data['error_message'] = $this->get('translator')->trans("product.RECORD_NOT_FOUND");
			}
		}
		
		$data['params_to_append'] = array_merge($this->request->get('_route_params'), $this->request->query->all());
		
		$sku_masking_list = $this->skuMasking->getAllSkuList();
		
		$sku_arr = array();
		if( isset($sku_masking_list) && count($sku_masking_list) > 0 ){
			foreach($sku_masking_list as $sml){
				$sku_arr[$sml->getSku()."_".$sml->getSupplierId()]['id'] = $sml->getId();
				$sku_arr[$sml->getSku()."_".$sml->getSupplierId()]['supplier_id'] = $sml->getSupplierId();
				$sku_arr[$sml->getSku()."_".$sml->getSupplierId()]['masking_sku'] = $sml->getMaskingSku();
			}
		}
		
		return array('data'=>$data,'activeCountry' => $country, 'activeCulture'=>$activeCulture,'productData'=>$productSentData, 'sku_masking_list'=>$sku_arr);
	 }

    /**
     * @author Employee Id: 5497
     * Description : Get the list sku.
     *
     * @Route("/list-ajax/{page}", name="officebrain_custom_productbundle_sku_masking_admin_listajax",
     * options={"expose"=true},
     * requirements={ "page"="\d+"},
     * defaults={ "page"=1})
     *
     * @Method("POST")
     * @Template("OfficeBrainCustomBundleProductBundle:SkuMasking:skuMaskingListAjax.html.twig")
     *
     * @return array
     */
    public function skuMaskingListAjaxAction()
    {
        $this->initAction();
        $this->responseArray = $this->skuMasking->getSkuMaskingList();

        return $this->responseArray;
    }
    
    
    
    
    /**
     * @author Employee Id: 5497
     * Description : Get the list sku.
     *
     * @Route("/save-sku", name="officebrain_custom_productbundle_sku_masking_save",
     * options={"expose"=true},
     * requirements={ "page"="\d+"},
     * defaults={ "page"=1})
     *
     * @Method("POST")
     *
     * @return array
     */
    public function saveSkuMaskingAction()
    {
    	$this->initAction();
    	// $subshopObj = $this->skuMasking->findBySubshopByStatus($this->userId);
    	$sku = $this->request->get('sku');
    	$maskingSku = $this->request->get('masking_sku');
    	$productId = $this->request->get('product_id');
    	$supplierId = $this->request->get('supplier_id');
    	$projectId = $this->projectSetting['project_id'];
    	$instanceId = $this->projectSetting['instance_id'];
    	
    	$product = $this->container->get("office_brain_product_detail_manager")->getProductDetailsBySku($maskingSku);
    	//$maskCount = $this->getDoctrine()->getRepository('OfficeBrainCustomBundleProductBundle:SkuMasking')->findOneBy(array('maskingSku' => $maskingSku,'supplierId' => $supplierId));
    	$maskCount = $this->getDoctrine()->getRepository('OfficeBrainCustomBundleProductBundle:SkuMasking')->findOneBy(array('maskingSku' => $maskingSku));
    	
    	$this->request->query->set('sku',$sku);
    	
    	//if($product && $product['product_id'] != $productId && $product['supplier_id'] == $supplierId){
    	  if(count($maskCount)>0){  
    		//error
    		$data['status'] = 'error';
    		$data['msg'] = 'PLEASE_INSERT_UNIQUE_NEW_SKU';
    		$data['id'] = $this->request->get('id');
    	}else{
    		$data = $this->skuMasking->setSkuMasking();
    	}
    	
    	if($data['status'] == 'success'){
    		// Custom code to sync sku masking for each subshop
    		
	    	//SOLR SYNC CODE START
	    	$is_solr_syn_enabled = $this->container->getParameter('solr_sync');
	    	if($is_solr_syn_enabled){
	    		$env = $this->container->getParameter("kernel.environment");
	    		$localization_to_update = $this->container->getParameter('localization_to_fetch');
	    		foreach ($this->instanceArray as $instanceKey => $instance){
	    			$result = $this->checkProductAvailableinSolr($instance, $productId);
	    			if($result){
	    				// //remove product from tbl_private_tag_product_mapping - PPM - 7716
	    				
	    				// $madeToOrderId =  $this->productTagManager->getStatusOfTag($instance,"featured-product");
	    				// if(isset($madeToOrderId) && $madeToOrderId['id']>0)
	    				// {
	    				// 	$this->tagProductMappingRepository->removeProductByTagAndProduct($madeToOrderId['id'],$productId);
	    				// }
	    				
	    				//END - remove product from tbl_private_tag_product_mapping
	    				
	    				$this->productApiManager->updateSolrData($productId,$localization_to_update,$projectId,$env,$instance,'update');
	    			}
	    		}
	    	}
	    	//SOLR SYNC CODE END

	    	// Custom code to sync sku masking for each subshop END
    	}
    	
    	return new JsonResponse($data);
    }
    
    /**
     * @author Employee Id: 5497
     * Description : Get the list sku.
     *
     * @Route("/save-supplier-sku", name="officebrain_custom_productbundle_supplier_sku_masking_save",
     * options={"expose"=true},
     * requirements={ "page"="\d+"},
     * defaults={"records_per_page"=100,"page"=1})
     *
     * @Method("POST")
     *
     * @return array
     */
    public function saveSupplierSkuMaskingAction()
    {
    	$this->initAction();
    	$projectSetting = $this->request->get('project_setting');
    	list($defaultCulture,$defaultCountry) = explode("_",$this->request->get("_locale"));
    	
    	$culture = $this->request->get('language',$defaultCulture);
    	$country = $this->request->get('country',$defaultCountry);
    	$activeCulture = $culture; 
    	$searchStatus = $this->request->query->get('search_status', '1');
    	$searchQuery = $this->request->query->get('search_query', '');
    	$sortBy = $this->request->query->get('sort', 'updatedAt');
    	$sortType = $this->request->query->get('direction', 'desc');
    	$searchParam = $this->request->query->get('search_param', '');
    	$brandIds = $this->request->query->get('brand_id','');
    	$catIds = $this->request->query->get('cat_id','');
    	
    	$supplier_id = $this->request->get('supplier_id','');
    	//$supplierMaskSku = $this->request->get('supplier_mask_sku','');
    	$projectId = $this->projectSetting['project_id'];
    	//echo $supplier_id."===".$supplierMaskSku."---";
    	$instanceType = $projectSetting['instance_type'];
    	
    	if ($supplier_id){
    	}else{
    		$supplier_id = 0;
    	}
        
    	$records_per_page=7000;
    	$cultureCategory =  $activeCulture . "_" . $country;
		    	    	
    	$projectId = $projectSetting['project_id'];
    	$productData = $this->productApiManager->listProduct($searchStatus,$searchParam, $searchQuery, $sortType, $sortBy,$activeCulture,$country,$supplier_id,$records_per_page,$page,$projectId,$brandIds,$catIds);
    	$productChunkData=array_chunk($productData['data'],1000,true);
	    	$skuId = $this->skuMasking->setSupplierSkuMasking($productChunkData);
	    	if($skuId > 0){
	    		$data['status'] = 'success';
	    		$data['msg'] = 'MASK_INPROGRESS';
	    	}
	    	else{
	    		$data['status'] = 'error';
	    		$data['msg'] = 'Error';
	    	}
    	
    	//SOLR SYNC CODE START
    		if($data['status'] == 'success')
    		{
    			// do one entry here as 0 Or update it
    			
    			$connection = $this->entityManager->getConnection();
    			
    			$connection->insert('tbl_masking_supplier_status', array('supplier_id' => $supplier_id,'flag'=>0,'status'=>'In Process'));
    			
		    	$env = $this->container->getParameter("kernel.environment");
		    	$localization_to_update = $this->locale;
		    	$kernelRootDir = 'php '.$this->container->getParameter('subshop_media_upload_location')['kernel_root_dir'];
		    	foreach ($this->instanceArray as $instanceKey => $instance){
					$cmd = 'nohup '.$kernelRootDir.DIRECTORY_SEPARATOR.'console office_brain:solr:sync:skumaskingproduct --supplierId='.$supplier_id.' --instanceId='.$instance.' --projectId='.$this->projectSetting['project_id'] .' --culture='.$cultureCategory.' --env="'.$env.'" > /dev/null 2>&1 &';
					
					shell_exec($cmd);
					unset($cmd);
		    	}
		    	unset($kernelRootDir);
    		}
    	return new JsonResponse($data);
    }
    
    
    /* Start Custom code to update product for all instance */
    public function checkProductAvailableinSolr($instanceId, $productId){
    	$projectId = $projectSetting['project_id'];
    	//$opration='update';
    	$searchQuery = $this->searchManager->getSearchArray();
    	$searchQuery['product_search']['instanceId']= $instanceId;
    	$searchQuery['product_search']['productId']= array($productId);
    	$searchQuery['product_search']['sku']= '';
    	$productSearchData = new ProductSearchData($this->entityManager,1);
    	$productSearchForm = new ProductSearchType();
    	$this->form = $this->createForm($productSearchForm, $productSearchData, array('csrf_protection' => false));
    	$this->form->bind($searchQuery['product_search']);
    	$responseArray = $this->searchManager->searchResult($this->form->getData(),true);
    	if($responseArray['search_result_array']['totalCount']==1){
    		return TRUE;
    	}
    	else{
    		return FALSE;
    	}
    }
    /* Ends Custom code to update product for all instance */
    
    /**
     * @author Employee Id: 5633
     *
     * Description : This function used for Import Excel file for SKU masking
     *
     * @Route("/import/{country}/{language}/{page}",
     * name="officebrain_custom_productbundle_sku_masking_admin_import",
     * requirements={"records_per_page"="12|24|48|100|996","page"="\d+"},
     * defaults={"records_per_page"=20,"page"=1})
     * @Template("OfficeBrainCustomBundleProductBundle:SkuMasking:skuMaskingImport.html.twig")
     */
    public function skuMaskingImportAction()
    {
    	$this->initAction();
    	$projectSetting = $this->request->get('project_setting');
    	list($defaultCulture,$defaultCountry) = explode("_",$this->request->get("_locale"));
    
    	$param = $this->request->get('_route_params');
    	$culture = $this->request->get('language',$defaultCulture);
    	$country = $this->request->get('country',$defaultCountry);
    	$activeCulture = $culture;
    	$supplier_id = $this->request->query->get('supplier_id','');
    
    	//$instanceType = strtolower($this->container->getParameter('default_main_instance_type'));
    	$instanceType = $projectSetting['instance_type'];
    
    	if ($this->user->getUserType()=='admin' && $instanceType=='association'){
    		$supplier_id = $this->request->query->get('supplier_id','');
    	} else if($this->user->getUserType()=='supplier' || $this->user->getUserType()=='distributor' ||
    			($this->user->getUserType() == 'admin' && $instanceType == 'distributor') || ($this->user->getUserType() == 'admin' && $instanceType == 'supplier')){
    				$supplier_id = $this->user->getObCustomerId();
    				$supplier_id = str_replace(array('OB','ob'), '', $supplier_id);
    					
    				if(empty($supplier_id)){
    					$supplier_id = 0;
    				}
    	}else{
    		$supplier_id = 0;
    	}
    
    	if ($this->user->getUserType()=='admin' && $instanceType=='distributor' && $projectSetting['instance_id'] == $this->container->getParameter('default_main_instance_id')) {
    		$supplier_id = '';
    	}
    
    	if ($this->user->getUserType()=='admin' && $this->request->query->get('supplier_id') != '') {
    		$supplier_id = $this->request->query->get('supplier_id','');
    	}
    
    	$projectId = $projectSetting['project_id'];
    	$supplierData = $this->productApiManager->getSupplierNameList($projectId);
    
    	$data['supplier_id']=$supplier_id;
    	$data['supplier_data'] = $supplierData;
    	$data['INSTANCE_TYPE'] = $instanceType;
    	$data['params_to_append'] = array_merge($this->request->get('_route_params'), $this->request->query->all());
    
    	if ($this->request->isXmlHttpRequest() && $this->request->getMethod()=='POST') {
    		//return $this->skuMasking->setSkuFileUpload();
    		$uploadImportFilePath = $this->container->getParameter('tmp_image_upload_path');;
    		$allwedImportFileMimeType = $this->container->getParameter('allowed_import_file_mime_type');
    		$translator = $this->get('translator');
    		 
    		/*if(!IS_DIR($uploadImportFilePath)){
    		 mkdir($uploadImportFilePath,0777,true);
    		 }*/
    		 
    		$importFileName = '';
    		$error = false;
    		$supplierId = $this->request->get('supplier_id','');
    		$skuArray = array();
    		$skuErrorArray = array();
    		$projectId = $this->projectSetting['project_id'];
    		$instanceId = $this->projectSetting['instance_id'];
    		$instanceType = $this->projectSetting['instance_type'];
    		 
    		if(!empty($_FILES) && $supplierId>0 && $projectId>0){
    			foreach($_FILES as $file)
    			{
    				$extensionArr = explode('.', $file['name']);
    				$extension = $extensionArr[count($extensionArr)-1];
    				//if(!in_array($file['type'],$allwedImportFileMimeType)){
    				if($extension != 'xls'){
    					$error = true;
    					$error_message = $translator->trans('product_import_export.allowed_import_file_type');
    				}
    				 
    				if(!$error){
    					$ext = end((explode(".", basename($file['name']))));
    					$importFileName = "import_supplierid_".$supplierId."_countryid_".$country."_cultureid_".$activeCulture."_".time().".".$ext;
    					$uploadImportFile = $uploadImportFilePath.$importFileName;
    					$file_moved = @move_uploaded_file($file['tmp_name'], $uploadImportFile);
    		
    					if($file_moved){
    						$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($uploadImportFile);
    						foreach ($phpExcelObject->getWorksheetIterator() as $worksheet){
    							$highestRow         = $worksheet->getHighestRow(); // e.g. 10
    							$highestColumn      = $worksheet->getHighestColumn(); // e.g 'F'
    							$highestColumnIndex = ord($highestColumn) - 64;
    							for ($row = 2; $row <= $highestRow; ++ $row) {
    								for ($col = 0; $col < $highestColumnIndex; ++ $col) {
    									$cell = $worksheet->getCellByColumnAndRow($col, $row);
    									$val = $cell->getValue();
    									$skuArray[$row-2][$col] = $val;
    								}
    							}
    						}
    							
    						if(count($skuArray) > 0){
    							foreach($skuArray as $sa){
    								$id = '';
    								$productId = 0;
    								$sku = $sa[0];
    								$maskingSku = $sa[1];
    									
    								$skuMasking = $this->skuMasking->getMaskingBySkuAndSupplier($sku, $supplierId);
    								if(is_array($skuMasking) && isset($skuMasking['error'])){ //record not found
    									$mode = 'add';
    									
    									$product = $this->container->get("office_brain_product_detail_manager")->getProductDetailsBySku($maskingSku);
    									if($product && $product['supplier_id'] == $supplierId){
    										//error	
    										$skuErrorArray[] = $sa;
    									}else{
    										$product = $this->container->get("office_brain_product_detail_manager")->getProductDetailsBySku($sku);
    										if($product){
    											$productId = $product['product_id'];
    											$product_supplier_id = $product['supplier_id'];
    										}
    										$skuMasking = new SkuMasking();
    										$skuMasking->setProductId($productId);
    										$skuMasking->setSupplierId($supplierId);
    										$skuMasking->setSku($sku);
    										$skuMasking->setInstanceId($instanceId);
    										$skuMasking->setInstanceType($instanceType);
    										$skuMasking->setMaskingSku($maskingSku);
    									}
	    									
    								}else{
    									$mode = 'edit';
    									$productId = $skuMasking->getProductId();
    									
    									$product = $this->container->get("office_brain_product_detail_manager")->getProductDetailsBySku($maskingSku);
    									if($product && $product['product_id'] != $productId && $product['supplier_id'] == $supplierId){
    										//error
    										$skuErrorArray[] = $sa;
    									}else{
    										$skuMasking->setMaskingSku($maskingSku);
    									}
    								}
    									
    								
    								$data = $this->skuMasking->setSkuMaskingImport($skuMasking, $mode);
    								if($data['status'] == 'success'){
    									//SOLR SYNC CODE START
    									$is_solr_syn_enabled = $this->container->getParameter('solr_sync');
    									if($is_solr_syn_enabled){
    										$env = $this->container->getParameter("kernel.environment");
    										$localization_to_update = $this->container->getParameter('localization_to_fetch');
    										$this->productApiManager->updateSolrData($productId,$localization_to_update,$projectId,$env,$instanceId,'update');
    									}
    									//SOLR SYNC CODE END
    								}
    								if($data['status'] == 'error'){
    									$skuErrorArray[] = $sa;
    								}
	    								
    							}
    						}
    							
    						if(file_exists($uploadImportFile)){
    							@unlink($uploadImportFile);
    						}
    							
    						$error = false;
    						$success_message = $translator->trans('product_import_export.import_process_done');
    					}else{
    						$error = true;
    						$error_message = $translator->trans('product_import_export.file_upload_error_message');
    					}
    				}
    			}
    		}else{
    			$error = true;
    			$error_message = $translator->trans('product.file_not_found');   //"Please select file" ;
    		}
    		 
    		if(!$error){
    			$return = array (
    					'status' => 'success',
    					'success_message'=> $success_message,
    			);
    		} else {
    			$return = array (
    					'status' => 'error',
    					'error_message' => $error_message);
    		}
    		 
    		return new JsonResponse($return);
    	}
    
    	return array('data'=>$data,'activeCountry' => $country, 'activeCulture'=>$activeCulture);
    }
    
    
    
    
    
    
    
    
    /**
     * Recursive function for category list
     *
     * @param array $catArray
     */
    public function recursiveCategory($catArray){
    	if (array_key_exists("child",$catArray)) {
    		foreach($catArray['child'] as $subCatArray){
    			if (array_key_exists("child",$subCatArray)) {
    				foreach ($subCatArray['child'] as $leafCat) {
    					$this->recursiveCategory($leafCat);
    				}
    			}
    			else{
    				$this->catArrayNew[] = $subCatArray;
    			}
    		}
    	}
    	else {
    		$this->catArrayNew[] = $catArray;
    	}
    }
    /**
     * @author Employee Id: 5412
     * Description : Get the sku mapped sku 
     *
     * @Route("/mapped-sku/{product_id}/{sku}", name="officebrain_custom_productbundle_sku_mapped_sku",
     * options={"expose"=true},
     * requirements={ "product_id"="\d+"})
     *
     * @Method("GET")
     * 
     * @return array
     */
    public function getMappedSkuAction($product_id,$sku)
    {
    	$this->initAction();
   
    	$this->skuMappingManagaer->getMappedSku($product_id,$sku);
 		die;
    }
    
    
    /**
     * @author Employee Id: 4571
     * Description : check process continue in background through DB .. 
     *
     * @Route("/check-background-process", name="officebrain_custom_productbundle_check_background_process",
     * options={"expose"=true})
     * 
     *
     * @Method("POST")
     *
     * @return array
     */
    public function checkBackgroundProcessAction()
    {
    	$this->initAction();
    	
    	$supplierId = $this->request->get('supplier_id','0');
    	 
    	$connection = $this->entityManager->getConnection();
    	$flag = '';
    	$flag_in_process = '';
    	
    	$statement = $connection->prepare(
    			'SELECT flag FROM `tbl_masking_supplier_status` WHERE supplier_id = :supid'
    	);
    	$statement->bindValue('supid', $supplierId);
    	$statement->execute();
    	
       	$affected_rows = $statement->rowCount();
    	
    	if($affected_rows>0){
    		$result = $statement->fetchAll();
    		$flag = $result[0]['flag'];
    		if($flag==0){
    			
    			$data['status'] = 'in_progress';
    			$data['flag_in_process'] = 0; // backg process exe in progress..
    			$data['msg'] = 'Please wait Solr is running in the background..';
    		}
    	}else{
    		$data['status'] = 'success';
    		$data['flag_in_process'] = 1; // backg process exe done.. 
    		$data['msg'] = "Done";
    	}   	 
    	
    	return new JsonResponse($data);
    	
    }
    
    
}
