<?php
namespace OfficeBrain\Bundle\ProductBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Translation\Translator;
use OfficeBrain\Bundle\CoreBundle\CustomeHandler as FormErrorManager;
use OfficeBrain\Bundle\SearchBundle\Form\Type\ProductSearchType;
use OfficeBrain\Bundle\SearchBundle\Form\Data\ProductSearchData;

/*
 * This class for base functionality related to product admin. @author Office Brain - 4808 <support@officebrain.com>
 */

/**
 * @Route("/admin/{_locale}/product")
 */
class ProductConfigureController extends Controller
{
   /**
	 * @author Employee Id: 4808
	 * 
	 * Description : This function used for Set and intilize variables and request array
	 *
	 **/
    public function init(){
        $this->request = $this->getRequest();
        $this->entityManager = $this->getDoctrine()->getManager();
        $this->session = $this->request->getSession();
        $this->translator = $this->get('translator');
        $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->attributeApiManager = $this->get("officebrain_attribute_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->productDetailManager = $this->get('office_brain_product_detail_manager');
        $this->subShopThemeManager = $this->get('office_brain_subshop_theme_manager');
        $this->user = $this->projectUserSetting['user_data'];
        $this->projectSetting = $this->request->get('project_setting');
    	$this->countries = $this->container->getParameter('country');
    	$this->searchManager = $this->get('office_brain_search_manager');
        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');
        }
        $this->languageId = $this->searchManager->getLanguageId();
    }
    
    
    /**
     * @author Employee Id: 4532
     *
     * Description : This function used for update order.
     *
     * @Route("/update-product-order",
     * name="officebrain_bundle_product_update_product_order",
     * options={"expose"=true},
     * requirements={"records_per_page"="12|24|48|100|996", "page"="\d+"},
     * defaults={"records_per_page"=100,"page"=1})
     *
     */
    public function updateProductOrderAction(){
    	$this->init();
    	
    	$projectSetting = $this->request->get('project_setting');
    	$newOrder= $this->request->get('newOrder');
    	$oldOrder = $this->request->get('oldOrder');
    	$productId = $this->request->get('productId');
    	$totalProduct = $this->request->get('totalCount');
    	$page = $this->request->get('page');
    	$responce = array();
    	if($totalProduct < $newOrder){
    		$responce['type'] = 'Error';
    		$responce['msg'] = 'Enter Order in not more then total product count';
    		return $responce;
    	}
    	$result = $this->productApiManager->updateProductOrder($newOrder,$oldOrder,$productId);
    	//echo '<pre>'; print_r($result); die;
    	$env = $this->container->getParameter("kernel.environment");
    	$localization_to_update = $this->container->getParameter('localization_to_fetch');
    	foreach ($result as $rs){
    		$this->productApiManager->updateSolrData($rs['productId'],$localization_to_update,$projectSetting['project_id'],$env,$projectSetting['instance_id'],'update');
    	}
    	$responce['type'] = 'Success';
    	$responce['msg'] = 'Order update successfully';
    	
    	//return new JsonResponse($responce);
    	
    	return new JsonResponse(array('type' => 'success','msg'=> 'Order update successfully', 'page_url' => $this->generateUrl('officebrain_bundle_product_list_product_wo_culture', array('page' => $page))));
    }
    
    /**
     * @author 4532
     *
     * Desciption: import product ranking sheet
     *
     * @return JSON Response
     *
     * @Route("/rearrange-product-order",
     * 	name="officebrain_product_bundle_rearrange_product_order", options={"expose"=true}
     * )
     */
    
    public function rearrangeProductOrderAction()
    {
    	$this->init();
    	$ranking_sheet_path = $this->container->getParameter('ranking_sheet_path');
    	$ranking_sheet_path = $ranking_sheet_path.'/Rankings of Active Products_012918 new.csv';
    	
    	
//     	$file = fopen($ranking_sheet_path,"r");
//     	print_r(fgetcsv($file));
//     	fclose($file);
    	//echo '<pre>';
    	$file = fopen($ranking_sheet_path,"r");
    	$result = array();
    	while(! feof($file))
    	{	
    		$result[] = fgetcsv($file);
    	}
    	
    	fclose($file);
//     	echo '<pre>'; print_r($result);
//     	die;
    	
    	$i = 0;
    	foreach ($result as $res){
    		if($i != 0){
    		$criteria['sku'] = $res[0];
    	
	    	$productSearchData = new ProductSearchData($this->entityManager, $this->languageId);
	    	$productSearchForm = new ProductSearchType();
	    	
	    	$this->form = $this->createForm($productSearchForm, $productSearchData, array('csrf_protection' => false));
	    	$this->form->bind($criteria);
	    	$this->responseArray = $this->searchManager->searchResult($this->form->getData());
    	
	    	$finalResult = array();
	    	foreach ($this->responseArray['search_result_array']['data'] as $val){
	    		$finalResult['product_id'] = $val['product_id'];
	    		$finalResult['sku'] = $res[0];
	    		$finalResult['ranking'] = $res[1];
	    		$this->productApiManager->syncProductOrderGivenByClient($finalResult);
	    	}
	    	
    		}$i++;
    	}
    	echo 'done'; die;
    	//echo '<pre>'; print_r($finalResult); die;
    	
    	//$this->productApiManager->syncProductOrderGivenByClient($finalResult);
    	
    	
    	return new JsonResponse($logoeverything);
    }
    
    /**
     * @author Employee Id: 4532
     *
     * Description : This function used for generate order for product and solr sync..
     *
     * @Route("/product-order",
     * name="officebrain_bundle_product_product_order",
     * options={"expose"=true},
     * requirements={"records_per_page"="12|24|48|100|996", "page"="\d+"},
     * defaults={"records_per_page"=100,"page"=1})
     *
     */
    public function productOrderAction(){
    	$this->init();
    	$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', '');
    	$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 = $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;
    	}
    	
    	
    	
    	$cultureCategory =  $activeCulture . "_" . $country;
    	
    	// For Pagination
    	$page = $this->request->get('page', '1');
    	$records_per_page = $param['records_per_page'];
    	$records_per_page = '3000';
    	$recordsPerPage = $this->request->query->get('recordsPerPage',$records_per_page);
    	$start_index = (($page - 1) * $recordsPerPage - 1);
    	// End Pagination
    	
    	$projectId = $projectSetting['project_id'];
    	$productData = $this->productApiManager->listProduct($searchStatus,$searchParam, $searchQuery, $sortType, $sortBy,$activeCulture,$country,$supplier_id,$records_per_page,$page,$projectId,$brandIds,$catIds);
    	//echo '<pre>'; print_r($productData); die;
    	
    	$env = $this->container->getParameter("kernel.environment");
    	$localization_to_update = $this->container->getParameter('localization_to_fetch');
    	
    	$this->productApiManager->syncProductOrder($productData,$localization_to_update,$projectSetting['project_id'],$env,$projectSetting['instance_id']);
    	
    	
    	//$env = $this->container->getParameter("kernel.environment");
    	//$localization_to_update = $this->container->getParameter('localization_to_fetch');
    	//$this->productApiManager->updateSolrData($apiResponse['master_product_id'],$localization_to_update,$projectSetting['project_id'],$env,$projectSetting['instance_id'],'update');
    	
    }
    
    /**
     * @author Employee Id: 4532
     *
     * Description : This function used for generate order for product and solr sync..
     *
     * @Route("/product-order-client",
     * name="officebrain_bundle_product_product_order_client",
     * options={"expose"=true},
     * requirements={"records_per_page"="12|24|48|100|996", "page"="\d+"},
     * defaults={"records_per_page"=100,"page"=1})
     *
     */
    public function productOrderClientAction(){
    	$this->init();
    	$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', '');
    	$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 = $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;
    	}
    	
    	
    	
    	$cultureCategory =  $activeCulture . "_" . $country;
    	
    	// For Pagination
    	$page = $this->request->get('page', '1');
    	$records_per_page = $param['records_per_page'];
    	$records_per_page = '3000';
    	$recordsPerPage = $this->request->query->get('recordsPerPage',$records_per_page);
    	$start_index = (($page - 1) * $recordsPerPage - 1);
    	// End Pagination
    	
    	$projectId = $projectSetting['project_id'];
    	$productData = $this->productApiManager->listProduct($searchStatus,$searchParam, $searchQuery, $sortType, $sortBy,$activeCulture,$country,$supplier_id,$records_per_page,$page,$projectId,$brandIds,$catIds);
    	//echo '<pre>'; print_r($productData); die;
    	
    	$env = $this->container->getParameter("kernel.environment");
    	$localization_to_update = $this->container->getParameter('localization_to_fetch');
    	
    	$this->productApiManager->syncProductOrder($productData,$localization_to_update,$projectSetting['project_id'],$env,$projectSetting['instance_id']);
    	
    	
    	//$env = $this->container->getParameter("kernel.environment");
    	//$localization_to_update = $this->container->getParameter('localization_to_fetch');
    	//$this->productApiManager->updateSolrData($apiResponse['master_product_id'],$localization_to_update,$projectSetting['project_id'],$env,$projectSetting['instance_id'],'update');
    	
    }
    
	/**
	 * @author Employee Id: 4808
	 * 
	 * Description : This function used for List Product Information 
	 * 
	 * @Route("/list/{page}",
	 * name="officebrain_bundle_product_list_product_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_bundle_product_list_product",
	 * requirements={"records_per_page"="12|24|48|100|996","page"="\d+"},
	 * defaults={"records_per_page"=20,"page"=1})
	 * @Template("OfficeBrainProductBundle:ProductAdmin:list.html.twig")
	 */
	public function listProductAction(){
        $this->init();
        $this->complianceManager = $this->get('office_brain_supplier_compliance_manager');
        $complianceProductMapping = array();
        $complianceList = array();
        $complianceData = $this->complianceManager->getAllComplianceList();
        if(count($complianceData)>0){
           foreach($complianceData as $cpm){
            $complianceList[$cpm['id']] = $cpm['name'];
            if($cpm['productId']!=NULL){
               $complianceProductMapping[$cpm['productId']] = $cpm['id'];
            }
           }
        }
        $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', '');
		$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);
		    $supplier_id = $this->request->query->get('supplier_id','');
			
			if(empty($supplier_id)){
				$supplier_id = 0;
			}
		}else{
			$supplier_id = 0;
		}

		

        $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'];
		$productData = $this->productApiManager->listProduct($searchStatus,$searchParam, $searchQuery, $sortType, $sortBy,$activeCulture,$country,$supplier_id,$records_per_page,$page,$projectId,$brandIds,$catIds);
		
		$supplierData = $this->productApiManager->getSupplierNameList($projectId);
 		$brandData = $this->brandApiManager->getList($culture);
 		$productOrderData = $this->productApiManager->getProductOrderData();
		//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;
		$data['total_count'] = $productData['count'];
		$paginator  = $this->get('knp_paginator');
		$data['pagination'] = $paginator->paginate($productData, $page, $recordsPerPage);
		$data['page']=$page;
		$data['search_status']=$searchStatus;
		$data['search_query']=$searchQuery;
		$data['sort_by']=$sortBy;
		$data['sort_type']=$sortType;
		$data['search_param']=$searchParam;
		$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']= $brandData[$culture];
		$data['INSTANCE_TYPE'] = $instanceType;
		$data['product_order'] = $productOrderData;
		//echo '<pre>'; print_r($data['supplier_data']);  die; 
		
		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());
		
		return array('data'=>$data,'activeCountry' => $country, 'activeCulture'=>$activeCulture,'productData'=>$productSentData,'complianceList'=>$complianceList,'complianceProductMapping'=>$complianceProductMapping);
	}
	
	/**
     * 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: 4808
     * 
     * Description : This function used for Add Product Information 
     * @return array 
     * @Route("/add", name="officebrain_product_add"),
     * @Template("OfficeBrainProductBundle:ProductAdmin:add.html.twig")
     */
    public function addAction(){
        $this->init();
        $projectSetting = $this->request->get('project_setting');
        //$instanceType = strtolower($this->container->getParameter('default_main_instance_type'));
        $instanceType = $projectSetting['instance_type'];
        
        $cultureName = $this->request->get('culture_name');
        $master_product_id = $this->request->get('master_product_id', '');
        $param = $this->request->get('_route_params');
        $route = $this->request->get('_route');
        $quoteId = $this->request->get('quote_id',0);
        $locale_language = $param['_locale'];
        $productAddSettings = $projectSetting['configuration_rule']['product']['add_update'];
        $supplier_id = 0;
        // set global_pricing_keys which are active
        $globalPricingKeys = '';        
        if(array_key_exists('global_pricing', $productAddSettings))
        {
        	foreach ($productAddSettings['global_pricing'] as $key => $val) 
        	{
        		if ($val['status'] == 1) 
        		{
        			$globalPricingKeys .= ($val['pricing_box_id'].':'.$val['pricing_box_name']).',';
        		}
        	}
        }
        
        //$supplierData = $this->productApiManager->getSupplierNameList($projectSetting['project_id']);        
        if($this->userId>0 && $quoteId>0){
            if($this->user->getObCustomerId()==NULL || $this->user->getObCustomerId()==''){
              $this->userManager->createNewObCustomerIdFromApi($this->userId);
            }
        }
        if($productAddSettings['brand']['supplierwise_brand']){
        	$supplier_id = $this->user->getObCustomerId();
        	$supplier_id = str_replace(array('OB','ob'), '', $supplier_id);
        	if(empty($supplier_id)){
        		$supplier_id = 0;
        	}
        }
        if ($this->request->isXmlHttpRequest() && $this->request->getMethod()=='POST') {
        	
        	$data = $this->request->request->all();
            $data['master_product_id'] = $master_product_id;
            $data['project_id'] = $projectSetting['project_id'];
            $data['locale_language'] = $locale_language;
            $data['instance_type'] = $projectSetting['instance_type'];
            $data['instance_id'] = $projectSetting['instance_id'];
            $data['thumb_width'] =  $this->container->getParameter('thumb_width'); 
            $data['medium_thumb_width'] = $this->container->getParameter('medium_thumb_width');
            if(isset($data['imprint_information']['charges']) && !empty($data['imprint_information']['charges'])) {
	            foreach ($data['imprint_information']['charges'] as $i=>$ic) {
	            	if(trim($ic['production_days']) == '') {
	            		$data['imprint_information']['charges'][$i]['production_days'] = 0;
	            	}
	            }
            }
            
            $apiResponse =  $this->productApiManager->add($cultureName, $data);
            if ($apiResponse['status']=='success') {
            	$response = array('product_id'=>$apiResponse['master_product_id'],'quote_id'=>$quoteId,'form_status' => $apiResponse['status'],'success_message'=>$this->get('translator')->trans($apiResponse['success_message']));
            	$this->session->set('product-list-success', $this->get('translator')->trans($apiResponse['success_message']));
            	
            	$actionPerformed = 'create';
            	if ($master_product_id) { $actionPerformed = 'update';}
            	
            	//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($apiResponse['master_product_id'],$localization_to_update,$projectSetting['project_id'],$env,$projectSetting['instance_id'],'update');
            	}
            	//SOLR SYNC CODE END
            	
                // To Integrate With ERP
                $erpIntegration = $projectSetting['configuration_rule']['erp_integration'];
                if($erpIntegration && $erpIntegration['productManagement'] == 1 && !empty($this->queueApiManager)) {
                    $this->productApiManager->integrateWithErp($this->queueApiManager, $actionPerformed, $apiResponse['master_product_id']);
				}
				
				//configure ASI URL Call
				if($productAddSettings['asi_call']['status']){
					foreach ($apiResponse['product_slugs'] as $culture => $slug){
						$asiurl = $productAddSettings['asi_call']['url'] . "?product_slug=".$slug;
						exec("wget '$asiurl' &", $output);
					}
				}
            } else {
                $response = array('form_status' => $apiResponse['status'],'error_message'=>$this->get('translator')->trans($apiResponse['message']));
            }
            return new JsonResponse($response);
        }
        
    	$data_to_set =  $this->productApiManager->preSetDataForPlugin($projectSetting['configuration_rule']['product'],$projectSetting['project_id'],array(),$supplier_id);
    	    	    	
    	$this->viewTwigData['plugin_data'] = $data_to_set['plugin_data'];
        $this->viewTwigData['ATTR_TYPE_IDS'] = $this->container->getParameter('attributes_types');
        $this->viewTwigData['ATTR_IMPRINT_POSITION'] = $this->container->getParameter('imprint_position_master_id');
        $this->viewTwigData['ATTR_IMPRINT_COLOR'] = $this->container->getParameter('imprint_color_master_id');
        $this->viewTwigData['API_VERSION'] = $this->container->getParameter('api.available_call_to_override');
        $this->viewTwigData['ATTR_COLOR_ID'] = $this->container->getParameter('color_attribute_id');        
        $this->viewTwigData['params_to_append'] = array_merge($this->request->get('_route_params'), $this->request->query->all());
        $this->viewTwigData['form_method'] = 'add';
        $this->viewTwigData['quote_id'] = $quoteId;
        $this->viewTwigData['global_pricing_keys'] = trim($globalPricingKeys, ',');
        $this->viewTwigData['INSTANCE_TYPE'] = strtolower($instanceType);        
        
        return $this->viewTwigData;
    }
    
    /**
     * @author Employee Id: 4045
     *
     * Description : This function used to Edit Product Information
     * @return array
     * @Route("/edit/{master_product_id}", name="officebrain_product_edit"),
     * @Template("OfficeBrainProductBundle:ProductAdmin:add.html.twig")
     */
    public function editNewAction(){
    	$this->init();
    	$projectSetting = $this->request->get('project_setting');
    	//$instanceType = strtolower($this->container->getParameter('default_main_instance_type'));
    	$instanceType = $projectSetting['instance_type'];
    	
        $countryArray = $this->container->getParameter('country');
        $languageArray = $this->container->getParameter('language');
        $country_to_pass = array_column($countryArray,'short_name');
        $language_to_pass = array_keys($languageArray);
        $locale = $this->request->get('_locale',$this->container->getParameter('locale'));
        @list($default_language,$default_country) = explode("_",$locale);
    	$cultureName = $this->request->get('culture_name');
    	$masterProductId = $this->request->get('master_product_id', '');
    	$param = $this->request->get('_route_params');
    	$route = $this->request->get('_route');
    	$quoteId = $this->request->get('quote_id',0);
    	
    	// set global_pricing_keys which are active
    	$globalPricingKeys = '';
    	$productAddSettings = $projectSetting['configuration_rule']['product']['add_update'];
    	if(array_key_exists('global_pricing', $productAddSettings))
    	{
    		foreach ($productAddSettings['global_pricing'] as $key => $val)
    		{
    			if ($val['status'] == 1)
    			{
    				$globalPricingKeys .= ($val['pricing_box_id'].':'.$val['pricing_box_name']).',';
    			}
    		}
    	}

    	$productInfo = $this->productApiManager->editView($masterProductId,$language_to_pass,$country_to_pass,$default_language);
    	//$supplierData = $this->productApiManager->getSupplierNameList($projectSetting['project_id']);
    	
    	if(!count($productInfo)){
    		throw $this->createNotFoundException('The product does not exist');
    	}
    	
    	$data_to_set =  $this->productApiManager->preSetDataForPlugin($projectSetting['configuration_rule']['product'], $projectSetting['project_id'],$productInfo);
    	$this->viewTwigData['plugin_data'] = $data_to_set['plugin_data'];
    	$this->viewTwigData['ATTR_TYPE_IDS'] = $this->container->getParameter('attributes_types');
    	$this->viewTwigData['ATTR_IMPRINT_POSITION'] = $this->container->getParameter('imprint_position_master_id');
    	$this->viewTwigData['ATTR_IMPRINT_COLOR'] = $this->container->getParameter('imprint_color_master_id');
    	$this->viewTwigData['API_VERSION'] = $this->container->getParameter('api.available_call_to_override');
    	$this->viewTwigData['ATTR_COLOR_ID'] = $this->container->getParameter('color_attribute_id');
    	$this->viewTwigData['params_to_append'] = array_merge($this->request->get('_route_params'), $this->request->query->all());
    	$this->viewTwigData['master_product_id'] = $masterProductId;
    	$this->viewTwigData['form_method'] = 'edit';
    	$this->viewTwigData['quote_id'] = $quoteId;
    	$this->viewTwigData['global_pricing_keys'] = trim($globalPricingKeys, ',');
    	$this->viewTwigData['INSTANCE_TYPE'] = strtolower($instanceType);
    	if(isset($this->viewTwigData['plugin_data']['valid_up_to'][1]['value'])
    			&& $this->viewTwigData['plugin_data']['valid_up_to'][1]['value'] != ''
    			&& $this->viewTwigData['plugin_data']['valid_up_to'][1]['value'] == '11-30-1999')
    	{
    		$this->viewTwigData['plugin_data']['valid_up_to'][1]['value'] = '';
    	}
    	if(isset($this->viewTwigData['plugin_data']['special_price_valid_up_to'][1]['value'])
    			&& $this->viewTwigData['plugin_data']['special_price_valid_up_to'][1]['value'] != ''
    			&& $this->viewTwigData['plugin_data']['special_price_valid_up_to'][1]['value'] == '11-30-1999')
    	{
    		$this->viewTwigData['plugin_data']['special_price_valid_up_to'][1]['value'] = '';
    	}
    	return $this->viewTwigData;
    }

    /**
     * @author: Employee Id : 4808
     * Description: This Function is Related For Image Library
     *
     * @Route("/image-library",name="officebrain_product_image_library"),
     * @Template("OfficeBrainProductBundle:ProductAdmin:imageLibrary.html.twig")
     */
    public function imageLibraryAction(){
    	//TODO: need to get dynamic product once listing get done
       $this->init();
       $this->viewTwigData['data']=array('productId'=>1);
        $mainErrorMessage='';
        $isImageUploaded = false;
        if ($this->request->getMethod() == "POST" ) {
            $request = $this->getRequest();
            $fileData = $request->files->get("FileUpload");
            $zipData = $request->files->get("zipUpload");

            $fileUploadType = $request->get('FileUpload_type');
            //TODO: need to get dynamic product once listing get done
            $productId = 1;
            $index = 0;
            $imageArray = array();
            foreach($fileData as $image){
                foreach($image as $v){
                    if(!empty($v)){
                        $isImageUploaded = true;
                        break;
                    }
                }
                if($isImageUploaded) break;
            }
            if(!$isImageUploaded){
                foreach($zipData as $image){
                    foreach($image as $v){
                        if(!empty($v)){
                            $isImageUploaded = true;
                            break;
                        }
                    }
                    if($isImageUploaded) break;
                }
            }
            $mainErrorMessage='';
            if(!$isImageUploaded){
                $mainErrorMessage =  $this->get('translator')->trans('admin.image_template_library.select_files_error_msg');
            }
            $res =  $this->productApiManager->uploadfiles($productId, $fileData,'image',$fileUploadType);
            $error_file_upload = $res['error_file_upload'];
            $res = $this->productApiManager->uploadfiles($productId, $zipData,'zip');
            $error_file_upload_zip = $res['error_file_upload'];
        }
        $errMsg = '';
        $successMsg = '';
        if (!empty($error_file_upload) || !empty($error_file_upload_zip)) {
            $errMsg = '<ul>';
            $arrImgType = array('web' => 'Web', 'template' => 'Template', 'high_res' => 'High Res');
            foreach ($arrImgType as $type => $files) {
                if (isset($error_file_upload[$type]) || isset($error_file_upload_zip[$type])) {
                    $errMsg.="<li>" . $files . "<ul>\n";
                    if (isset($error_file_upload[$type])) {
                        foreach ($error_file_upload[$type] as $fileName => $error) {
                            $errMsg.="<li>" . $fileName . ":<i><b>" . $error . "</b></i></li>";
                        }
                    }
                    if (isset($error_file_upload_zip[$type])) {
                        foreach ($error_file_upload_zip[$type] as $fileName => $error) {
                            $errMsg.="<li>" . $fileName . ":<i><b>" . $error . "</b></i></li>";
                        }
                    }
                    $errMsg.="</ul></li>";
                }
            }
            $errMsg.='</ul>';
        }elseif($mainErrorMessage != '' ){
            $errMsg = '<ul><li>'.$mainErrorMessage.'</li></ul>';
        }elseif($isImageUploaded){
            $successMsg = $this->get('translator')->trans('admin.image_template_library.upload_succ');
        }
       return $this->viewTwigData;
    }

    /**
     * @Route("/browse-product-image", name="OfficeBrainImageLibraryAdmin_browse_product_image")
     * @Method({"POST"})
     * @Template("OfficeBrainProductBundle:ProductAdmin:browseProductImage.html.twig")
     */
    public function browseProductImageAction() {
    	$this->init();
    	$this->request = $this->getRequest();
    	$productId = intval($this->request->get('id'));
    	$imageType = $this->request->get('type');
    	$data = $this->productApiManager->productImages($productId,$imageType);
    	$imageArray = array();
    	if($data){
    		if($imageType =='high_res'){
    			foreach($data as $image){
    				
    				if(trim($image['fileType'])!='imprinted')
    					$imageArray['blank'][]=$image;
    				else
    					$imageArray['imprinted'][]=$image;
    			}
    		} else {
    			$imageArray = $data;
    		}
    	}
    	return array('imageArray' => $imageArray, 'imageType' => $imageType);
    }
    /**
     * @Route("/remove-product-image",
     * name="officebrain_image_library_admin_bundle_remove_product_image"),
     *	 @Method({"GET|POST"})
     * @Template()
     */
    public function removeProductImageAction() {
    	$this->init();
    	$productId = $this->request->get('productId');
    	$imageType = $this->request->get('imageType');
    	$imageId = $this->request->get('imageId');
    	
    	$result = $this->productApiManager->removeProductImage($productId,$imageId);
    	if ($result)
    		echo $this->get('translator')->trans('admin.image_template_library.image_removed_succ');
    	else
    		echo $this->get('translator')->trans('admin.image_template_library.image_removed_fail');
    }
    /**
     * @author Employee Id: 4246
     * Description : This function used for View Product Information
     * @Route("/view",
     * name="officebrain_product_view")
     * @Template("OfficeBrainProductBundle:ProductAdmin:view.html.twig")
     */
    public function viewAction(){
    	$this->init();
    	$productIsDeleted =false;
    	$product_culture = $this->request->get('product_culture');
    	$product_ids = $this->request->get('product_ids');
    	//$productAdminManager = $this->get('office_brain_product_admin_manager');
    	$productData = $this->productApiManager->view($product_ids,$product_culture,true);
    	
    	$projectSetting = $this->request->get('project_setting');
    	$productAddSettings = $projectSetting['configuration_rule']['product']['add_update'];
    	if(array_key_exists('global_pricing', $productAddSettings))
    	{
    		foreach ($productAddSettings['global_pricing'] as $key => $val)
    		{
    			if ($val['status'] == 1)
    			{
    				$global_pricing_arr[$key] = 1;
    			}
    		}
    	}
    	
    	$culture_id = $this->request->get('culture_id');
    	if(!count($productData)){
    		throw $this->createNotFoundException('The product does not exist');
    	}
    	if($productData['status'] == "success"){
    		$productInfo = $productData['data'];
    		$productIsDeleted = $productInfo[$product_ids]['is_deleted'];
    		if($productIsDeleted){
    			return $this->redirect($this->generateUrl('officebrain_bundle_product_list_product_wo_culture'));
    		}
    		if(array_key_exists('price_unit',$productInfo[$product_ids])){
    			$priceUnit = $this->container->getParameter('price_unit');
    			$productInfo[$product_ids]['price_unit'] = array_key_exists(trim($productInfo[$product_ids]['price_unit']),$priceUnit)?$priceUnit[$productInfo[$product_ids]['price_unit']]:$productInfo[$product_ids]['price_unit'];
    		}
    		$this->viewTwigData['data'] = $productInfo[$product_ids];
    	}else{
    		$this->viewTwigData['error_message'] = $this->get('translator')->trans('product.'.$productData['message']);
    	}
    	$this->viewTwigData['API_VERSION'] = $this->container->getParameter('api.available_call_to_override');
    	$this->viewTwigData['params_to_append'] = array_merge($this->request->get('_route_params'), $this->request->query->all());
    	/* if exist ob customer id create  flyer*/
    	$this->viewTwigData['ob_customer_id']=$this->userManager->getObCustomerId($this->viewTwigData['data']['supplier']['supplier_id']);
    	
    	$this->viewTwigData['global_pricing_arr'] = $global_pricing_arr;
    	
    	return $this->viewTwigData;
    }
    
    
    /**
     * @author Employee Id: 4246
     * Description : This function used for map Product size extra charge
     * @Route("/size-extra-chare-post",
     * name="officebrain_product_sizeExtraChargepost")
     * @Template("OfficeBrainProductBundle:ProductAdmin:sizeExtraCharge.html.twig")
     */
    public function sizeExtraChargePostAction(){
		$this->init();
    	$product_size = $this->request->get('extraCharge');
    	$product_id = $this->request->get('product_id');
    	$data ['charges'] = json_encode($product_size);
    	$data ['product_id'] = $product_id;
    	$object = $this->productDetailManager->getExtraChargeByProductId($product_id);
    	$this->productDetailManager->setProductExtraCharge($object, $data);
		echo 'SUCCESS';
    	die;
	}
    
    /**
     * @author Employee Id: 4246
     * Description : This function used for map Product size extra charge
     * @Route("/size-extra-chare",
     * name="officebrain_product_sizeExtraCharge")
     * @Template("OfficeBrainProductBundle:ProductAdmin:sizeExtraCharge.html.twig")
     */
    public function sizeExtraChargeAction(){
    	$this->init();
    	$productIsDeleted =false;
    	$product_culture = $this->request->get('product_culture');
    	$product_ids = $this->request->get('product_ids');
    	//$productAdminManager = $this->get('office_brain_product_admin_manager');
    	$productData = $this->productApiManager->view($product_ids,$product_culture,true);
    	$extraCharge = $this->productDetailManager->getExtraChargeByProductId($product_ids);
    	$exchargeData = array();
    	if($extraCharge!=null){
			$exchargeData = json_decode($extraCharge->getExtraCharge(),true);
		}
    	$projectSetting = $this->request->get('project_setting');
    	$productAddSettings = $projectSetting['configuration_rule']['product']['add_update'];
    	if(array_key_exists('global_pricing', $productAddSettings))
    	{
    		foreach ($productAddSettings['global_pricing'] as $key => $val)
    		{
    			if ($val['status'] == 1)
    			{
    				$global_pricing_arr[$key] = 1;
    			}
    		}
    	}
    	
    	$culture_id = $this->request->get('culture_id');
    	if(!count($productData)){
    		throw $this->createNotFoundException('The product does not exist');
    	}
    	if($productData['status'] == "success"){
    		$productInfo = $productData['data'];
    		$productIsDeleted = $productInfo[$product_ids]['is_deleted'];
    		if($productIsDeleted){
    			return $this->redirect($this->generateUrl('officebrain_bundle_product_list_product_wo_culture'));
    		}
    		if(array_key_exists('price_unit',$productInfo[$product_ids])){
    			$priceUnit = $this->container->getParameter('price_unit');
    			$productInfo[$product_ids]['price_unit'] = array_key_exists(trim($productInfo[$product_ids]['price_unit']),$priceUnit)?$priceUnit[$productInfo[$product_ids]['price_unit']]:$productInfo[$product_ids]['price_unit'];
    		}
    		$this->viewTwigData['data'] = $productInfo[$product_ids];
    	}else{
    		$this->viewTwigData['error_message'] = $this->get('translator')->trans('product.'.$productData['message']);
    	}
    	$this->viewTwigData['API_VERSION'] = $this->container->getParameter('api.available_call_to_override');
    	$this->viewTwigData['params_to_append'] = array_merge($this->request->get('_route_params'), $this->request->query->all());
    	/* if exist ob customer id create  flyer*/
    	$this->viewTwigData['ob_customer_id']=$this->userManager->getObCustomerId($this->viewTwigData['data']['supplier']['supplier_id']);
    	
    	$this->viewTwigData['global_pricing_arr'] = $global_pricing_arr;
    	$this->viewTwigData['exchargeData'] =$exchargeData;
    	return $this->viewTwigData;
    }
    
    /**
     * @author Employee Id: 4246
     * Description : This function used for Delete Product
     * @Route("/delete",
     * name="officebrain_product_delete")
     */
    public function deleteAction(){
        $this->init();
        $product_master_id = $this->request->get('product_master_id');
        $product_country = $this->request->get('product_country');
        $projectSetting = $this->request->get('project_setting');
        $project_id = $projectSetting['project_id'];
        $locale_language = $projectSetting['locale_language'];
        $supplier_id = $projectSetting['user_id'];
        $instance_type = $projectSetting['instance_type'];
        $instance_id = $projectSetting['instance_id'];
        $productData = $this->productApiManager->delete($product_master_id, $project_id, $supplier_id, $locale_language, $instance_type, $instance_id, $product_country);
        // Data Array Convert Object To Array
        $productData['data'] = (array)$productData['data'];
        
        //TO NOTICE: $productData['data']['id']  REPLACE WITH  $product_master_id
        
        if($productData['status'] == 'success'){
        	$data['status'] = 'success_message';
        	//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($product_master_id,$localization_to_update,$projectSetting['project_id'],$env,$projectSetting['instance_id'],'delete');
         	}
        	//SOLR SYNC CODE END
        		
            // To Integrate with ERP
            $erpIntegration = $projectSetting['configuration_rule']['erp_integration'];
            if($erpIntegration && $erpIntegration['productManagement'] == 1 && !empty($this->queueApiManager)) {
                $dt = new \DateTime($productData['data']['deleted_at']);
                $params = array('product_id' => $product_master_id, 'country_id' => $productData['data']['country_id'], 'deleted_at'=> $dt->format('Y-m-d H:i:s'));
                $this->productApiManager->integrateWithErp($this->queueApiManager, 'remove', $product_master_id, $params);
            }
        }else{
        	$data['status'] = 'error_message';
        }
        $data['message'] = $this->translator->trans($productData['message']);
        return new JsonResponse($data);
    }
    
    /**
     * EMp Id : 4246
     * Description : This Function is Used For Update Product Status According To Parameter
     * 
     * @Route("/changestatus/{country}/{set_status}",
     * requirements = {"set_status"="1|0"},
     * name="officebrain_product_changestatus")
     */
    public function changeProductStatusAction(){
    	$this->init();
    	$param=$this->request->get('_route_params');
    	
    	$ids_to_pass = array();
    	$ids = $this->request->get('ids','');
    	$ids_to_pass = explode("::",$ids);
    	$productId = json_encode($ids_to_pass);
    	
        $projectSetting = $this->request->get('project_setting');
    	$country = $this->request->get('country');
    	$setStatus = $this->request->get('set_status');
    	
        $project_id = $projectSetting['project_id'];
        $locale_language = $projectSetting['locale_language'];
        $supplier_id = $projectSetting['user_id'];
        $instance_type = $projectSetting['instance_type'];
        $instance_id = $projectSetting['instance_id'];
        
    	//$productAdminManager = $this->get('office_brain_product_admin_manager');
    	$productData = $this->productApiManager->changeProductStatus($productId,$country,$setStatus, $project_id, $supplier_id, $locale_language, $instance_type, $instance_id);
        $data = array();
    	if($productData['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');
    			foreach($ids_to_pass as $product_id_to_process){
	    			if(!$setStatus){
	    				$this->productApiManager->updateSolrData($product_id_to_process,$localization_to_update,$projectSetting['project_id'],$env,$projectSetting['instance_id'],'delete');
	    			}else{
	    				$this->productApiManager->updateSolrData($product_id_to_process,$localization_to_update,$projectSetting['project_id'],$env,$projectSetting['instance_id'],'update');
	    			}
    			}
    		}
    		//SOLR SYNC CODE END
    		
    	    // To Integrate with ERP
    	    $productIds = json_decode($productId);
            $erpIntegration = $projectSetting['configuration_rule']['erp_integration'];
            if($erpIntegration && $erpIntegration['productManagement'] == 1 && !empty($this->queueApiManager)) {
                foreach ($productData['data'] as $key => $value) {
                    $params = array('product_id' => $productIds[$key], 'country_id' => $value['countryId'],'status'=> $setStatus);
                    $this->productApiManager->integrateWithErp($this->queueApiManager, 'updateStatus', $productIds[$key], $params);
                }
            }
    		$data['status'] = 'success';
    	}else{
    		$data['status'] = 'error';
    	}
    	$data['message'] = $this->translator->trans('product.'.$productData['message']);
    	return new JsonResponse($data);
    }
    
    /**
     * EMp Id : 4246
     * Description : This Function is Used For Update Product Status According To Parameter
     *
     * @Route("/check-duplicate-sku",
     * name="officebrain_product_check_duplicate_sku", options={"expose"=true})
     */
    public function checkDuplicateSKU(){
    	$this->init();
    	$sku = $this->request->get('sku');
    	$supplierId = $this->request->get('supplier_id');
    	$productId = $this->request->get('product_id','');
    	$data = $this->productApiManager->checkDuplicateSKU($sku,$supplierId,$productId);
    	$data['message'] = $this->translator->trans('product.'.$data['message']);
    	return new JsonResponse($data);
    }
    
    /**
     * @author Employee Id: 5190
     * Description : This function used for List Matrix Information
     * @Route("/matrix/list",
     * name="officebrain_product_matrix_list")
     * @Template("OfficeBrainProductBundle:ProductAdmin:listMatrix.html.twig")
     */
    public function listMatrixAction(){
		$this->init();
		$projectSetting = $this->request->get('project_setting');
		$projectId = $projectSetting['project_id'];
		$data['matrix_data'] = $this->productApiManager->getMatrixList($projectId);
		return array('data'=>$data);
    }
    
    /**
     * @author Employee Id: 5190
     *
     * Description : This function used for Export Product data culture and country wise
     * @return array
     * @Route("/export", name="officebrain_product_export"),
     * @Template("OfficeBrainProductBundle:ProductAdmin:export.html.twig")
     */
    public function exportAction(){
    	$this->init();
    	$projectSetting = $this->request->get('project_setting');
    	$projectId = $projectSetting['project_id'];
    	list($defaultCulture,$defaultCountry) = explode("_",$this->request->get("_locale"));
    	$culture = $this->request->get('language',$defaultCulture);
    	$country = $this->request->get('country',$defaultCountry);
    	$supplier_id = $this->request->query->get('supplier_id','');
    	
    	$countryArray = $this->container->getParameter('country');
    	$languageArray = $this->container->getParameter('language');
    	 
    	$supplierData = $this->productApiManager->getSupplierNameList($projectId);
    	$instanceType = $projectSetting['instance_type'];
    	//$country_to_pass = array_column($countryArray,'short_name');
    	//$language_to_pass = array_keys($languageArray);
    	$brandData = $this->brandApiManager->getList($culture);
    	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;
    	}
    	
    	foreach($countryArray as $countryKey => $country){
    		$data['country_data'][] = array('id'=>$country['id'],'code'=>$country['short_name'],'title'=>$country['name'],'language'=>$country['language']);
    	}
    	
    	if ($this->request->isXmlHttpRequest() && $this->request->getMethod()=='POST') {
    		$data = $this->request->request->all();
    		$apiResponse =  $this->productApiManager->getExportProduct($data);
    		
    		return new JsonResponse($apiResponse);
    	}
    	
    	$data['project_id'] = $projectId;
    	$data['country_array'] = $countryArray;
    	$data['language_data'] = $languageArray;
    	$data['supplier_data'] = $supplierData;
    	$data['INSTANCE_TYPE'] = $instanceType;
    	$data['supplier_id']=$supplier_id;
    	$data['brand_data']= $brandData[$culture];
    	 
    	return array('data'=>$data);
    	 
    }
    
    /**
     * @author Employee Id: 5540
     *
     * Description : This function used to Edit Product Information
     * @return array
     * @Route("/copy/{master_product_id}/{supplier_id}", name="officebrain_product_copy"),
     * @Template("OfficeBrainProductBundle:ProductAdmin:add.html.twig")
     */
    public function copyProductAction()
    {
    	//$this->init();
    	$supplierId = $this->getRequest()->get('supplier_id');
    	$productId = $this->getRequest()->get('master_product_id','');

    	$projectSetting = $this->getRequest()->get('project_setting');
    	 
    	$returnData = $this->get("office_brain_product_admin_manager")->copy($supplierId, $productId);
    	$returnData = array('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->get("office_brain_product_admin_manager")->updateSolrData($newProductId,$localization_to_update,$projectSetting['project_id'],$env,$projectSetting['instance_id'],'update');
    	}
    	//SOLR SYNC CODE END 
    	 */
    	
    	if($returnData['status'] == 'success')
    	{
    		$data['status'] = 'success_message';
    		$data['message'] = $this->get('translator')->trans('product_add_edit.product_copied_successfully');
    		//$this->getRequest()->getSession()->set('product-list-success', $this->get('translator')->trans('product_add_edit.product_copied_successfully'));
    	}
    	else
    	{
    		$data['status'] = 'error_message';
    		$data['message'] = $this->get('translator')->trans('product_add_edit.product_not_copied');
    	}
    	
    	return new JsonResponse($data);
    	//return $this->redirect($this->generateUrl("officebrain_bundle_product_list_product_wo_culture"));
    }
    
    /**
     * @author Employee Id: 5190
     *
     * Description : This function used for Import Product data supplier, culture and country wise
     * @return array
     * @Route("/import", name="officebrain_product_import"),
     * @Template("OfficeBrainProductBundle:ProductAdmin:import.html.twig")
     */
    
    public function importAction(){
    	$this->init();
    	$instanceId = $this->projectSetting['instance_id'];
    	
    	$projectSetting = $this->request->get('project_setting');
    	$projectId = $projectSetting['project_id'];
    	list($defaultCulture,$defaultCountry) = explode("_",$this->request->get("_locale"));
    	$culture = $this->request->get('language',$defaultCulture);
    	$country = $this->request->get('country',$defaultCountry);
    	$supplier_id = $this->request->query->get('supplier_id','');
    	$solrKeyCulture = $this->request->get("_locale");
    	 
    	$countryArray = $this->container->getParameter('country');
    	$languageArray = $this->container->getParameter('language');
    
    	$supplierData = $this->productApiManager->getSupplierNameList($projectId);
    	$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;
    	}
    	 
    	foreach($countryArray as $countryKey => $country){
    		$data['country_data'][] = array('id'=>$country['id'],'code'=>$country['short_name'],'title'=>$country['name'],'language'=>$country['language']);
    	}
    	 
    	if ($this->request->isXmlHttpRequest() && $this->request->getMethod()=='POST') {
    		$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 = '';
    		$extension = '';
    		$error = false;
    		$supplierId = $this->request->get('supplier_id','');
    		$countryId = $this->request->get('country_id','');
    		$cultureId = $this->request->get('culture_id','');
    		$userId = $this->userId;
    		
    		if(!empty($_FILES) && $countryId >0 && $cultureId >0 && $supplierId>0){
	    		foreach($_FILES as $file)
	    		{
	    			$filename = $file['name'];
    				$extension = pathinfo($filename, PATHINFO_EXTENSION);
	    			if($extension != 'xls'){
    					$error = true;
    					$error_message = $translator->trans('product_import_export.allowed_import_file_type');
    				}
    				
    				if(!$error){
	    				$ext = $extension;
	    				$importFileName = "import_supplierid_".$supplierId."_countryid_".$countryId."_cultureid_".$cultureId."_".time().".".$ext;
	    				$uploadImportFile = $uploadImportFilePath.$importFileName;
	    				$file_moved = @move_uploaded_file($file['tmp_name'], $uploadImportFile);
	    				if($file_moved){
	    					$response = $this->productApiManager->uploadImportFile($supplierId,$countryId,$cultureId,$projectId,$uploadImportFile,$uploadImportFilePath, $userId);
	    															
	    					if($response['status'] == 'success'){
	    						if(file_exists($uploadImportFile)){
	    							@unlink($uploadImportFile);
	    						}
	    						$error = false;
	    						$success_message = $translator->trans('product_import_export.import_process_start');
	    					}
	    					else{
	    						$error = true;
	    						$error_message = $translator->trans('product_import_export.file_upload_error_message');
	    					}
	    				}
		    			else {
		    				$error = true;
		    				$error_message = $translator->trans('File not moved to target'); 
		    			}
    				}
	    		}
    		}
    		else{
    			$error = true;
    			$error_message = $translator->trans('product.file_not_found');   //"Please select file" ;
    		}
    		
    		if(!$error){
    			$return = array (
    					'status' => 'success',
    					'success_message'=> $success_message,
    					'supplierId' => $supplier_id,
    					'solrKeyCulture' => $solrKeyCulture
    			);
    		} else {
    			$return = array (
    					'status' => 'error',
    					'error_message' => $error_message,
    					'supplierId' => $supplier_id,
    					'solrKeyCulture' => $solrKeyCulture
    			);
    		}
    		
    		return new JsonResponse($return);
    	}
    	$data['country_array'] = $countryArray;
    	$data['language_data'] = $languageArray;
    	$data['supplier_data'] = $supplierData;
    	$data['INSTANCE_TYPE'] = $instanceType;
    	$data['supplier_id']=$supplier_id;
    	$data['supplierId']=$supplier_id;
    	$data['solrKeyCulture']=$solrKeyCulture;
    	return array('data'=>$data);
    
    }
    
    /**
     * @author Employee Id: 5190
     *
     * Description : This function used for Import Product data supplier, culture and country wise
     * @return array
     * @Route("/check_import_status", name="officebrain_product_check_import_status",options={"expose"=true}),
     * @Template("OfficeBrainProductBundle:ProductAdmin:checkImportStatus.html.twig")
     */
    
    public function checkImportStatusAction(){
    	$this->init();
    	$supplierId = $this->getRequest()->get('supplier_id');
    	
    	$projectSetting = $this->request->get('project_setting');
    	$projectId = $projectSetting['project_id'];
    	$returnData = $this->productApiManager->checkImportStatus($supplierId,$projectId);
    	return array('data'=>$returnData);
    }
    


    /**
     * @author Employee Id: 5190
     *
     * Description : This function used for Import Product data supplier, culture and country wise
     * @return array
     * @Route("/solr-sync-status-of-supplier-culture", name="officebrain_product_solr_sync_status_of_supplier_culture"),
     *
     */
    
    public function solrSyncStatusOfSuppilerCultureAction(){
    
    	/* pppc code started */
    	$this->init();
    
    	$supplierId = $this->getRequest()->get('supplier_id');
    	$solrKeyCountryId = $this->getRequest()->get('solr_key_country_id');
    	$solrKeyLanguageId = $this->getRequest()->get('solr_key_culture_id');
    	
    	$solrKeyCulture = $this->searchManager->getCultureCode($solrKeyCountryId,$solrKeyLanguageId,$this->countries);
    	if($solrKeyCulture == 'en_ca')
    	{
    		$solrKeyCulture = 'en_us';
    	}
    	$instanceId =1;
    	$solrSyncStatusOfSupplierCulture = $this->searchManager->getSolrSyncStatusSupplierCulture($this->subShopThemeManager,$supplierId,$solrKeyCulture,$instanceId);
    	$this->responseArray['solr_sync_status_of_supplier_culture'] = $solrSyncStatusOfSupplierCulture;
    	$this->responseArray['supplier_id'] = $supplierId;
    	$this->responseArray['solr_key_culture'] = $solrKeyCulture;
    	 
    	return new JsonResponse($this->responseArray);
    	/* pppc code ended */
    }
    
    /**
     * @author Employee Id: 5190
     *
     * Description : This function used for Import Product data supplier, culture and country wise
     * @return array
     * @Route("/sync-supplier-product", name="officebrain_product_sync_sypplier_product"),
     * 
     */
    
    public function syncSupplierProductAction(){   	

    	/* pppc code started */
    	$this->init();
    	$supplierId = $this->getRequest()->get('supplier_id');
    	$solrKeyCountryId = $this->getRequest()->get('country_id');
    	$solrKeyLanguageId = $this->getRequest()->get('culture_id');
    	$solrKeyCulture = $this->searchManager->getCultureCode($solrKeyCountryId,$solrKeyLanguageId,$this->countries);
    	if($solrKeyCulture == 'en_ca')
    	{
    		$solrKeyCulture = 'en_us';
    	}
    	$projectSetting = $this->request->get('project_setting');
    	$projectId = $projectSetting['project_id'];
    	
//     	$imprintMethodMasterId = $this->getParameter('imprint_method_master_id');
//     	$imprintPositionMasterId = $this->getParameter('imprint_position_master_id');
//     	$packagingTypeMasterId = $this->getParameter('packaging_type_master_id');
    	
    	/* Data Mapping */
//     	$brandData = $this->brandApiManager->doBrandMappingFromProjectId($projectId);
//     	$attributeData = $this->attributeApiManager->doAttributeMappingFromProjectId($projectId);
//     	$imprintMethodAttributeData = $this->attributeApiManager->doAttributeMappingFromProjectId($projectId,'imprint_method',$imprintMethodMasterId);
//     	$imprintLocationAttributeData = $this->attributeApiManager->doAttributeMappingFromProjectId($projectId,'imprint_location',$imprintPositionMasterId);
//     	$imprintLocationAttributeData = $this->attributeApiManager->doAttributeMappingFromProjectId($projectId,'packaging',$imprintPositionMasterId);
//     	$attributeMappingData = $this->attributeApiManager->doAttributeMapping();
//     	$categoryMapping = $this->categoryApiManager->doCategoryMapping($projectId);
    	$productCategoryMapping = $this->productApiManager->doProductCategoryMapping($projectId);
    	/* End Data Mapping */
    	
    	$this->responseArray = $this->searchManager->solrSync($solrSyncStatusOfSupplier,$supplierId,$solrKeyCulture);
    	
    	return new JsonResponse($this->responseArray);
    	/* pppc code ended */  
    }
    
    /**
     * @author Employee Id: 5190
     *
     * Description : This function used for get importErrorLog using importId.
     * @return array
     * @Route("/import_error_log/{import_id}", name="officebrain_product_import_error_log"),
     * @Template("")
     */
    
    public function importErrorLogAction(){
    	$this->init();
    	$importId = $this->getRequest()->get('import_id');
    	$returnData = $this->productApiManager->importErrorLog($importId);
    	$filename = "import_error_log_" . $importId.".csv";
    	$response = $this->render('OfficeBrainProductBundle:ProductAdmin:importErrorLog.csv.twig',array('data' => $returnData));
    	//$response->setStatusCode(200);
    	$response->headers->set('Content-Type', 'text/csv');
    	$response->headers->set('Content-Disposition', 'attachment; filename="'.$filename.'"');
    	$response->headers->set('Pragma', 'no-cache');
    	$response->headers->set('Expires', '0');
    	//$response->sendHeaders();
    	//$response->sendContent();
    	return $response;
    	
    	//return array('data'=>$returnData);
    }
    
    /**
     * @author Employee Id: 5069
     *
     * Description : This function used for List Product Information
     *
     * @Route("/list-product-filtered-by-category/{productId}/{page}",
     * name="officebrain_bundle_product_list_product_filtered_by_category_wo_culture",
     * requirements={"records_per_page"="12|24|48|100|996", "page"="\d+"},
     * defaults={"records_per_page"=20,"page"=1})
     *
     * @Route("/list-product-filtered-by-category/{productId}/{country}/{language}/{page}",
     * name="officebrain_bundle_product_list_product_filtered_by_category",
     * requirements={"records_per_page"="12|24|48|100|996","page"="\d+"},
     * defaults={"records_per_page"=20,"page"=1})
     * @Template("OfficeBrainProductBundle:ProductAdmin:listProductFilteredByCategory.html.twig")
     */
    public function listProductFilteredByCategoryAction($productId){
    	 
    	$this->init();
    
    	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);
    	$countryId = $this->container->getParameter('country')[$country]['id'];
    	//echo $countryId= $this->country_;exit;
    	$activeCulture = $culture;
    	$searchStatus = $this->request->query->get('search_status', '');
    	$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','');
    
    	$cultureCategory =  $activeCulture . "_" . $country;
    	//      select all of the category ids from categorymapping entity, where product id of entity matches the product id passed in request, and country id of entity matches the country id passed in request
    	//		then using those category ids we will filter out the products and then we will show only the products coming in these specific categories
    	$productCategoryIds = $this->productApiManager->getCategoryIds($productId,$countryId);
    	$catIds = implode(",",$productCategoryIds);
    	//print_r($productCategoryIds);exit;
    	$comproductreletedid =   $this->productApiManager->productreletedid($productId);
    	$productdetails = $this->productDetailManager->getProductDetailById($productId,$cultureCategory);
    	
    	$product_title = $productdetails[$productId]['basic_information']['title'];
    	// 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
    	$projectSetting = $this->request->get('project_setting');
    
    	$projectId = $projectSetting['project_id'];
    
    	$productData = $this->productApiManager->listProduct($searchStatus,$searchParam, $searchQuery, $sortType, $sortBy,$activeCulture,$country,$supplier_id,$records_per_page,$page,$projectId,$brandIds,$catIds);
    
    	/* code for not showing the parent product in related products started */
    	if(isset($productData['data']))
    	{
    		$productIndex = 0;
    		foreach($productData['data'] as $singleProductDetail)
    		{
    			if(isset($singleProductDetail['product_master_id']))
    			{
    				if($singleProductDetail['product_master_id'] == $productId)
    				{
    					unset($productData['data'][$productIndex]);
    				}
    			}
    			$productIndex++;
    		}
    	}
    	$productData['count'] = $productData['count'] - 1;
    	/* code for not showing the parent product in related products ended */
    
    	$supplierData = $this->productApiManager->getSupplierNameList($projectId);
    	$brandData = $this->brandApiManager->getList($culture);
    	//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']=$searchQuery;
    	$data['sort_by']=$sortBy;
    	$data['sort_type']=$sortType;
    	$data['search_param']=$searchParam;
    	$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']= $brandData[$culture];
    	 
    	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());
    	return array('data'=>$data,'activeCountry' => $country, 'activeCulture'=>$activeCulture,'productData'=>$productSentData,'productId' => $productId,'comproductreletedid'=> $comproductreletedid,'product_title'=>$product_title);
    }
    
    /**
     * EMp Id : 5069
     * Description : This Function is Used For Update Product Status According To Parameter
     *
     * @Route("/change-relation-status/{country}/{set_status}",
     * requirements = {"set_status"="1|0"},
     * name="officebrain_product_change_relation_status")
     */
    public function changeProductRelationStatusAction(){
    	$this->init();
    	$param=$this->request->get('_route_params');
    	$productId=$this->request->get('productId');
    	$setStatus=$this->request->get('set_status');
    
    	$relatedProductIds = array();
    	$relatedProductIds = $this->request->get('ids','');
    	$relatedProductIds = explode("::",$relatedProductIds);
    
    	$projectSetting = $this->request->get('project_setting');
    	$locale_language = $projectSetting['locale_language'];
    
    	//$productAdminManager = $this->get('office_brain_product_admin_manager');
    
    	if($setStatus == 1)
    	{
    		$productData = $this->productApiManager->insertRelatedProducts($productId,$relatedProductIds,$locale_language);
    	}
    	else if($setStatus == 0)
    	{
    		$productData = $this->productApiManager->deleteRelatedProducts($productId,$relatedProductIds,$locale_language);
    	}
    
    	$data = array();
    	$data['status'] = 'success';
    	$data['message'] = $this->translator->trans('product.PRODUCT_RELATION_UPDATED');
    	return new JsonResponse($data);
    }
    
    
}
