<?php
namespace OfficeBrain\Bundle\CategoryBundle\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 OfficeBrain\Bundle\CategoryBundle\Entity as Entity;
use OfficeBrain\Bundle\CoreBundle\CustomeHandler as FormErrorManager;
use OfficeBrain\Bundle\CategoryBundle\Entity\CategoryMaster as CategoryMaster;
use OfficeBrain\Bundle\CategoryBundle\Entity\CultureCategory as CultureCategory;
use OfficeBrain\Bundle\CategoryBundle\Form\CategoryMasterType;
use OfficeBrain\Bundle\CategoryBundle\Form\CultureCategoryType;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Translation\Translator;
use OfficeBrain\Bundle\CoreBundle\Cache\RedisCacheService;

use OfficeBrain\Bundle\SolrBundle\Helper\ProductHelper;
use OfficeBrain\Bundle\SearchBundle\Form\Data\ProductSearchData;
use OfficeBrain\Bundle\SearchBundle\Form\Type\ProductSearchType;

/**
 *
 * @Route("/admin/{_locale}/category")
 */
class CategoryAdminController extends Controller
{
	public function __construct()
	{
		$this->viewTwigData = null;
		$this->request = null;
		$this->entityManager = null;
		//$this->session = null;
		$this->categoryApiManager = null;
		$this->formErrorManager = new FormErrorManager\JsonError ();
        $this->projectSetting = null;
        $this->queueApiManager = null;
	}
	public function __destruct()
	{
		unset($this->viewTwigData);
		unset($this->request);
		unset($this->entityManager);
		//unset($this->session);
		unset($this->categoryApiManager);
		unset($this->formErrorManager);
        unset($this->projectSetting);
        unset ($this->queueApiManager);
	}
	public function init()
	{
		$this->request = $this->getRequest();
		$this->entityManager = $this->getDoctrine()->getManager();
		
		$this->translator = $this->get('translator');
		$this->categoryApiManager = $this->get('officebrain_category_api_manager');

		if (
		    !$this->request->isXmlHttpRequest() &&
		    !$this->request->attributes->get('_stateless', false) &&
		    $this->has('office_brain_queue_api_manager')
		) {
		    $this->request->attributes->set('object', 'CultureCategory');
		    $this->queueApiManager = $this->get('office_brain_queue_api_manager');
		}

        $this->projectSetting = $this->request->get('project_setting');
        $this->productApiManager = $this->get("office_brain_product_admin_manager");
        if(isset($this->projectSetting['instance_theme_meta']['product_category']['custom_label'])){
        	$this->categoryCustomlabel = $this->projectSetting['instance_theme_meta']['product_category']['custom_label'];
        }
        $this->statsh_cache_wrapper=RedisCacheService::create();
		$this->moduleCachePrefix = '__HomePageCategoryList__';
		$this->recordsPerPage= 10 ;
    	$this->page=1;
	}
	
	
	/**
	 * @Route("/list/{language}",
	 * name="officebrain_bundle_category_list_category_wo_culture",
	 * defaults={"language"=""})	 
	 *
	 * description : for list category on listing page
	 * @Template("OfficeBrainCategoryBundle:Admin:list.html.twig")
	 */
	public function listAction()
	{
		$this->init();
		$data['pagination']=array();
		$param = $this->request->get('_route_params');		
		list($default_languagge) = explode("_",$this->container->getParameter('locale'));
		$culture = ($param['language'])? $param['language'] : $default_languagge;
		
		$searchQuery = $this->request->query->get('search_query', '');
		$searchStatus = $this->request->query->get('search_status', '');
		$sortBy = $this->request->query->get('sort', 'name');
		$sortType = $this->request->query->get('direction', 'asc');
		$search_Culture=$this->request->query->get('sort_culture');
		$searchParam = $this->request->query->get('search_param', '');
			
		$defultCultureId = $culture;
		$api_manager = $this->get('officebrain_category_culture_manager');
		$culture_response= $api_manager->getList(TRUE);
		$apiManager= $this->get("officebrain_category_api_manager");
		$categoryData = $apiManager->getList((array)$culture);
		$categoryList = array();
		$ignoreData = $apiManager->getIgnoreData();
		$categoryList['mappingData'] = $categoryData;
		$categoryList['ignoreData'] = $ignoreData;
		$data['activeTab']=$defultCultureId;
		$data['culture_list']=$culture_response;
		$syncCategory = $apiManager->getAllSynCategoryForChangeStatus('Progress');
		$blocked_id = 0;
		if($syncCategory!=NULL){
			$blocked_id = $syncCategory->getPmsId();
		}
		return array('data'=>$data,'blocked_id'=>$blocked_id,'activeCulture'=>$culture,'categoryData'=>$categoryList['mappingData'][$culture],'ignoreData'=>$categoryList['ignoreData']);
	}
	
	/**
	 * @Route("/ajaxcategorylist/{cat_culture}",
	 * name="officebrain_bundle_ajax_category_list",
	 * requirements={"records_per_page"="12|24|48|96|996", "culture"="\w+"},
	 * defaults={"records_per_page"=12,"cat_culture"="en"})
	 * description : for list category for autofill
	 */
	public function ajaxCategorylistAction()
	{	
		$this->init();
		$data['pagination']=array();
		$param = $this->request->get('_route_params');
		
		$param = $this->request->get('_route_params');
		list($default_languagge) = explode("_",$this->container->getParameter('locale'));
		$culture = ($param['cat_culture'])? $param['cat_culture'] : $default_languagge;
		
		//$culture = $this->request->get('cat_culture','en');
		
		$category_text = $this->request->get('q');
// 		$page = 1;
// 		$records_per_page = $param['records_per_page'];
	
		$searchQuery = $this->request->query->get('search_query', '');
		$searchStatus = $this->request->query->get('search_status', '');
		$sortBy = $this->request->query->get('sort', 'name');
		$sortType = $this->request->query->get('direction', 'asc');
		$search_Culture=$this->request->query->get('sort_culture');
		$searchParam = $this->request->query->get('search_param', '');
		
		$isFromProduct = $this->request->query->get('from_product_add', false);
	
		if(! isset($param['culture'])){
			$param['culture']='';
		}
		$defultCultureId = $param['culture'];
// 		$recordsPerPage = $this->request->query->get('recordsPerPage',$records_per_page);
// 		$start_index = (($page - 1) * $recordsPerPage - 1);
	
		$api_manager = $this->get('officebrain_category_culture_manager');
		$culture_response= $api_manager->getList(TRUE);
		
		if($culture){
			$activeCulture = $culture;
			$apiManager= $this->get("officebrain_category_api_manager");
			$categorylist = $apiManager->getAutoselectList($culture,$category_text, $isFromProduct);
			$selCat = [];
			foreach ($categorylist as $selectedCategory)
			{
				$selCat[] = array("value"=>$selectedCategory['name'],"label"=> $selectedCategory['name'], "value_id"=>$selectedCategory['category_master_id']);
			}
			return new Response($_GET['callback'] . '('.json_encode($selCat).')');
		}
		else
		{
			$this->get('session')->getFlashBag()->add('culture-list-warning', 'Please add atleast one active culture');
			//$this->session->set('culture-list-warning', 'Please add atleast one active culture');
			return $this->redirect($this->generateUrl("officebrain_culture_bundle_list"));
			// redirect to add culture
		}
	}
	
	/**
	 * @Route("/ajax-category-select/{cat_culture}",
	 * name="officebrain_bundle_ajax_category_select",
	 * options={"expose"=true},
	 * requirements={"records_per_page"="12|24|48|96|996", "culture"="\w+"},
	 * defaults={"records_per_page"=12,"cat_culture"="en"})
	 * Description : For get Selected Attribute Information and Parent Information
	 */
	public function ajaxCategorySelectAction()
	{
		$this->init();
		$data['pagination']=array();
		$param = $this->request->get('_route_params');
		$culture = $this->request->get('cat_culture','en');
		$category_name = $this->request->get('catValue');
		$page = 1;
		$records_per_page = $param['records_per_page'];
		$searchQuery = $this->request->query->get('search_query', '');
		$searchStatus = $this->request->query->get('search_status', '');
		$sortBy = $this->request->query->get('sort', 'name');
		$sortType = $this->request->query->get('direction', 'asc');
		$search_Culture=$this->request->query->get('sort_culture');
		$searchParam = $this->request->query->get('search_param', '');
		if(! isset($param['culture'])){
			$param['culture']='';
		}
		$defultCultureId = $param['culture'];
		$recordsPerPage = $this->request->query->get('recordsPerPage',$records_per_page);
		$start_index = (($page - 1) * $recordsPerPage - 1);
		
		$api_manager = $this->get('officebrain_category_culture_manager');
		$culture_response= $api_manager->getList(TRUE);

			$activeCulture = $culture;
			$culture_ids = $this->container->getParameter('language');
			$send_culture_ids = array();
			foreach($culture_ids as $key => $value)
			{
				$send_culture_ids[$key]=$value['id'];
			}
			$send_culture_ids = json_encode($send_culture_ids);
			
			$apiManager= $this->get("officebrain_category_api_manager");
			$selectedCategoryList = $apiManager->getSelectCategory($searchStatus, $searchParam, $searchQuery, $sortType, $sortBy,$culture,$send_culture_ids,$category_name);
// 			echo "<pre>";print_R($selectedCategoryList);die;
			foreach ($selectedCategoryList as $key => $value)
			{
				if($value != "")
				{
					if($key != "image"){
						/* if(isset($this->categoryCustomlabel)){
							$this->categoryCustomlabel[$value['category_master_id']][]
						} */
						$selCat[$key] = array("culture_name" => $value['culture_description'],"name" => $value['name'],"custom_label" => $value['custom_label'],"keywords"=>isset($value['keywords'])?$value['keywords']:'', "description"=>isset($value['description'])?$value['description']:'',"id" => $value['culture_category_id'],"cat_master_id" => $value['category_master_id']);
					}
					$selCat["image"] = $value;
				}
				else {
					$selCat[$key]="";
				}	
			}
			/* for Set Parent Dropdown */
			
			$categorylist = $apiManager->getList(array($culture));
			$selData = array();
			$selData['selectedData'] = $selCat;
			// Format parent data array so that it can't get sorted from js
			$selData['parentData'] = array();
			
			$selData['parentData'] = $this->resetArrayCatKeysForParent($categorylist[$activeCulture]);
			//$selData['parentData'] = $categorylist[$activeCulture];
			return new JsonResponse($selData);
	}
	
	public function resetArrayCatKeysForParent($arr = array(),$ignoreId = 0){
	    $arr = (array) $arr;
		$parentData=array();
		foreach($arr as $key=>$value){
			if($value['local_id'] == $ignoreId){continue;}
			if(isset($value['child'])){
				$value['child'] = $this->resetArrayCatKeysForParent($value['child'],$ignoreId);
			}
			$parentData['_'.$key]=$value;
		}
		return $parentData;
	}
	
	/**
	 * @Route("/addculturecategory/{cat_culture}",
	 * name="officebrain_bundle_add_culture_category",
	 * options={"expose"=true},
	 * requirements={"records_per_page"="12|24|48|96|996", "culture"="\w+"},
	 * defaults={"records_per_page"=12,"cat_culture"="en"})
	 * Description : Function for Add New Category
	 */
	public function addCultureCategoryAction()
	{	
		$this->init();
		
		// Remove Category CUnique Key
		$this->statsh_cache_wrapper->removeCacheByPrefix('cunique');
		
		$culture = $this->request->get('cat_culture');
		$postData = array();
		if ($this->request->isXmlHttpRequest() && $this->request->getMethod()=='POST') {
			$postData = $this->request->request->all();			
		}
		$culture_ids = $this->container->getParameter('language');
		$apiManager = $this->get("officebrain_category_api_manager");
		$country_ids = $this->container->getParameter('country');
		$response = $apiManager->setCategoryData($culture,$postData,$culture_ids,$country_ids,true);
		if($response['status']=='success_message'){			
	       		try{
		        	$erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
			        if($erpIntegration && $erpIntegration['productManagement'] == 1 && !empty($this->queueApiManager)) {
			            $cultureNames = array_keys($culture_ids);
			            $queueData = $apiManager->processCategoryData($response['category_object'], $cultureNames);
			            $this->queueApiManager->mapQueue('create', $queueData);
			        }
			        unset($response['category_object']);
	       		}catch(Exception $e){
			        	 
				}  
		}else{
	        //PROCESS ERROR	
	    }
        $response['message'] = $this->translator->trans($response['message']);
        return new JsonResponse($response);
	}
	
	/**
	 * @Route("/updateculturecategory/{cat_culture}",
	 * name="officebrain_bundle_update_culture_category",
	 * options={"expose"=true},
	 * requirements={"records_per_page"="12|24|48|96|996", "culture"="\w+"},
	 * defaults={"records_per_page"=12,"cat_culture"="en"})
	 * Description : Function for Add New Category
	 */
	public function updateCultureCategoryAction()
	{
		$this->init();
		
		// Remove Category CUnique Key
		$this->statsh_cache_wrapper->removeCacheByPrefix('cunique');
		
		$supplier = $this->getParameter('supplier');
		$culture = $this->request->get('cat_culture');
		$postData = "";
		if ($this->request->isXmlHttpRequest() && $this->request->getMethod()=='POST') {
			$postData = $this->request->request->all();
		}
		$culture_ids = $this->container->getParameter('language');
		$apiManager = $this->get("officebrain_category_api_manager");

		$data = $apiManager->setCategoryData($culture,$postData,$culture_ids,'',$supplier[1]['id']);

		if($data['status']=='success_message'){
			/* Solr sync when update category mappimg start - 5083 */
			if(array_key_exists("product_ids",$data)){
				foreach ($data['product_ids'] as $value){
					$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($value['id'],$localization_to_update,$this->projectSetting['project_id'],$env,$this->projectSetting['instance_id'],'update');
					}
				}
			}
			/* Solr sync when update category mapping end - 5083 */
    		try{
                $erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
                if($erpIntegration && $erpIntegration['productManagement'] == 1 && !empty($this->queueApiManager)) {
                    $cultureNames = array_keys($culture_ids);
                    $queueData = $apiManager->processCategoryData($data['category_object'], $cultureNames);
                    $this->queueApiManager->mapQueue('update', $queueData);
                }
                unset($data['category_object']);
            }catch(Exception $e){
                     
            }
		}else{
	        //PROCESS ERROR	
	    }
		RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
		$data['message'] = $this->translator->trans($data['message']);
		return new JsonResponse($data);
	}
	
	/**
	 * @Route("/addincategoryignore",
	 * name="officebrain_bundle_add_in_category_ignore")
	 * Description : Function for add Category in Country Ignore
	 */
	public function addInCategoryIgnoreAction()
	{
		$this->init();
		
		// Remove Category CUnique Key
		$this->statsh_cache_wrapper->removeCacheByPrefix('cunique');
		
		$countryId = $this->request->get('country_id');
		$catMapId = $this->request->get('cat_map_id');
		$pmsId = $this->request->get('pms_id');
		$api_manager = $this->get('officebrain_category_api_manager');
		$selData = $api_manager->addInCategoryIgnore($countryId,$catMapId,$pmsId);
		$selData['message'] = $this->translator->trans($selData['message']);
        if ($selData['status'] == 'success_message') {
            try {
                $erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
                if($erpIntegration && $erpIntegration['productManagement'] == 1 && !empty($this->queueApiManager)) {
                    $this->queueApiManager->mapQueue('removeFromCountry', array('id' => $catMapId, 'country_id' => $countryId));
                }
            } catch(Exception $e) {
                 
            }
        }
		return new JsonResponse($selData);
	}
	
	/**
	 * @Route("/removefromcategoryignore",
	 * name="officebrain_bundle_remove_from_category_ignore")
	 * description : This function for remove category from Country Ignore for access in country
	 */
	public function removeFromCategoryIgnoreAction()
	{
		$this->init();
		
		// Remove Category CUnique Key
		$this->statsh_cache_wrapper->removeCacheByPrefix('cunique');
		
		$countryId = $this->request->get('country_id');
		$catMapId = $this->request->get('cat_map_id');
		$api_manager = $this->get('officebrain_category_api_manager');
		$selData = $api_manager->removeFromCategoryIgnore($countryId,$catMapId);
		
        $selData['message'] = $this->translator->trans($selData['message']);
        if ($selData['status'] == 'success_message') {
            try {
                $erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
                if($erpIntegration && $erpIntegration['productManagement'] == 1 && !empty($this->queueApiManager)) {
                    $this->queueApiManager->mapQueue('addInCountry', array('id' => $catMapId, 'country_id' => $countryId));
                }
            } catch(Exception $e) {
                 
            }
        }
		return new JsonResponse($selData);
	}

	/**
	 * @Route("/edit",
	 * name="officebrain_category_bundle_edit_category",
	 * options={"expose"=true},)
	 * @Template("OfficeBrainCategoryBundle:Admin:list.html.twig")
	 */
	public function editAction(){
		$this->init();		
		
		// Remove Category CUnique Key
		$this->statsh_cache_wrapper->removeCacheByPrefix('cunique');
		
		$pmsId = $this->request->get('pms_id');
		$cultures = $this->container->getParameter('language');
		$activeCulture = $this->request->get('active_culture');
		$api_manager = $this->get('officebrain_category_api_manager');
		$data = $api_manager->getCategoryInfoByCategoryId($cultures,$pmsId);
		$parentData = $api_manager->getList($activeCulture);
		$selData = array();
		$selData['selectedData'] = $data;
		$ignoreId = $data[$activeCulture]['local_id'];
		$selData['parentData'] = $this->resetArrayCatKeysForParent($parentData[$activeCulture],$ignoreId);
		return new JsonResponse($selData);
	}
	/**
	 * @Route("/delete",
	 * name="officebrain_category_bundle_delete_category",
	 * options={"expose"=true},)
	 * @Template("OfficeBrainCategoryBundle:Admin:list.html.twig")
	 */
	public function deleteAction(){
		$this->init();
		// Remove Category CUnique Key
		$this->statsh_cache_wrapper->removeCacheByPrefix('cunique');
		
		$pmsId = $this->request->get('pms_id');
		$api_manager = $this->get('officebrain_category_api_manager');
		$country_ids = $this->container->getParameter('country');
		$data = $api_manager->delete($pmsId,$country_ids);
        if(array_key_exists('data',$data) && $data['data'])
        {
            try{
                $erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
                if($erpIntegration && $erpIntegration['productManagement'] == 1 && !empty($this->queueApiManager)) {
                    $this->queueApiManager->mapQueue('remove', array('id' => $data['data']->getId(),'pms_id' => $data['data']->getPmsId(), 'deleted_at' => $data['data']->getDeletedAt()->format('Y-m-d H:i:s')));
                }
            unset($data['data']);
            }catch(Exception $e){
                     
            }  
        }
		//$this->get('session')->getFlashBag()->add($data['status'], $this->translator->trans($data['message']));
		//return $this->redirectToRoute('officebrain_bundle_category_list_category_wo_culture');
		$data['message'] = $this->translator->trans($data['message']);
		return new JsonResponse($data);
	}

	/**
	 * @Route("/update-status",
	 * name="officebrain_category_bundle_update_status_category",
	 * options={"expose"=true},)
	 * @Template("OfficeBrainCategoryBundle:Admin:list.html.twig")
	 */
	public function updateStatusAction(){
		$this->init();
		$entityManager = $this->get('doctrine.orm.entity_manager');
		$searchManager = $this->get('office_brain_search_manager');
    	$formFactory = $this->get('form.factory');
		$pmsId = $this->request->get('pms_id');
		$status = $this->request->get('status');
		$name = $this->request->get('cname');
		$api_manager = $this->get('officebrain_category_api_manager');
		$instanceId=1;
		$languageId =1;
		$searchQuery = $searchManager->getSearchArray();
		$searchQuery['product_search']['instanceId']= $instanceId;
		if($pmsId!=0 || $pmsId !='' ){
			if ($status == 'Active') {
				$searchQuery['product_search']['inactiveCategoryId']= json_encode(array($pmsId.'|*'));
			}else{
				$searchQuery['product_search']['categoryId']= json_encode(array($pmsId));
			}
		}    		    			
		$productSearchData = new ProductSearchData($entityManager, $languageId);
		$productSearchForm = new ProductSearchType();
		$form = $formFactory->create($productSearchForm, $productSearchData, array('csrf_protection' => false));
		$form->bind($searchQuery['product_search']);
		$responseArray = $searchManager->searchResult($form->getData(),true);
		$productcount = count($responseArray['search_result_array']['data']);

		$data = $api_manager->updateStatus($pmsId,$status);
        $schdularObj = $api_manager->addCategoryStatusSchedular($pmsId,$status,$name,'Pending',NULL);
        $api_manager->setProductCount($schdularObj,$productcount);


        // Remove Category CUnique Key
		$this->statsh_cache_wrapper->removeCacheByPrefix('cunique');
		RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
		

		$data['message'] = $this->translator->trans($data['message']);
		return new JsonResponse($data);
	}

	/**
	 * @Route("/category-sync-list",
	 * name="officebrain_category_bundle_update_synclistcategory",
	 * options={"expose"=true},)
	 * @Template("OfficeBrainCategoryBundle:Admin:synclistcategory.html.twig")
	 */
	public function synclistcategoryAction()
    {
    	$this->init();
    	$this->responseArray['records_per_page'] = $this->recordsPerPage;
    	$this->responseArray['page'] = $this->page;
    	$this->prepareSearchParameterArray();
    	$api_manager = $this->get('officebrain_category_api_manager');
        $this->responseArray['data'] = $api_manager->getCategoryStatusSchedular($this->page,$this->recordsPerPage,$this->searchParameterArray,$this->searchKeyWordsArray);
    	return $this->responseArray;
    }

    private function prepareSearchParameterArray()
	{
        
		$this->option = $this->request->get('option', null);
		$this->keywords = $this->request->get('keyword', null);
		$this->searchParameterArray = array();
		$this->searchKeyWordsArray[$this->option]=trim($this->keywords);
		 
	}



	/**
	 * @Route("/set-category-flag",
	 * 	name="office_brain_custombundle_category_set_flag",options={"expose"=true}
	 * )
	 * @Template("")
	 */
	public function setCategoryFlagAction()
	{
		$this->init();
		$countryId = $this->request->get('country_id');
		$catMapId = $this->request->get('cat_map_id');
		$pmsId = $this->request->get('pms_id');
		$catFlag = $this->request->get('cat_flag');
		$apiManager= $this->get("officebrain_category_api_manager");

		RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
		$categoryData = $apiManager->setCategoryFlag($catMapId,$pmsId,$catFlag);
		$categoryData['message'] = $this->translator->trans($categoryData['message']);
		
		return new JsonResponse($categoryData);
	}

	/**
     * @author("Krunal")
     * @Route("/table-list/{language}",name="officebrain_bundle_category_tablelist_category_wo_culture")
     * defaults={"language"=""}
     * @Template("OfficeBrainCategoryBundle:Admin:tableListCategory.html.twig")
     **/
    public function tableListCateogorAction()
    {
        $this->init();
		$data['pagination']=array();
		$param = $this->request->get('_route_params');		
		list($default_languagge) = explode("_",$this->container->getParameter('locale'));
		$culture = ($param['language'])? $param['language'] : $default_languagge;
		
		$searchQuery = $this->request->query->get('search_query', '');
		$searchStatus = $this->request->query->get('search_status', '');
		$sortBy = $this->request->query->get('sort', 'name');
		$sortType = $this->request->query->get('direction', 'asc');
		$search_Culture=$this->request->query->get('sort_culture');
		$searchParam = $this->request->query->get('search_param', '');
			
		$defultCultureId = $culture;
		$api_manager = $this->get('officebrain_category_culture_manager');
		$culture_response= $api_manager->getList(TRUE);
		$apiManager= $this->get("officebrain_category_api_manager");
		$categoryData = $apiManager->getList((array)$culture);
		$categoryDataResult = $apiManager->fetchAllCategories($categoryData);
		$categoryList = $apiManager->buildCategoryListView($categoryDataResult["product_categories"]);
		$sort_position = array_column($categoryList, 'sort_position');
		array_multisort($sort_position, SORT_ASC, $categoryList);
		//echo "<pre>";print_r($categoryList);exit;


		return array('categoryList'=>$categoryList,'activeCulture'=>$culture);
    }

	 /**
     *
     * @author (Krunal Jethi)
     *
     * @param  : null
     *
     * @return Response
     *
     * @throws null
     *
     * @Route("/sort-position",
     * name="officebrain_bundle_category_updatePosition",
     * options={"expose"=true}
     * )
     * @Template()
     *
     **/
    public function categoryPositionUpdateAction()
    {
        $this->init();
		
        $param=$this->request->request->all();
        if (count($param)) {
            foreach ($param['prod_list'] as $key=>$pmsId) {
                $key=$key+1;
                $categoryApiManager = $this->categoryApiManager->setCateogryPosition($pmsId, $key);
            }
        }
		RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
        if ($this->request->isXmlHttpRequest()) {
            $response = new Response();
            $output = array('success' => 'success');
            $response->headers->set('Content-Type', 'application/json');
            $response->setContent(json_encode($output));
            return $response;
        }
    }

    /**
     *
     * @return Response
     *
     * @throws null
     *
     * @Route("/category-link/{pms_id}",
     * name="officebrain_bundle_category_updatelink",
     * options={"expose"=true}
     * )
     * @Template("OfficeBrainCategoryBundle:Admin:categoryUpdateLink.html.twig")
     *
     **/
    public function categoryUpdateLinkAction()
    {
        $this->init();
		$pmsId = $this->request->get('pms_id');
		$categoryPmsDetail = $this->categoryApiManager->getCategoryByPmsId($pmsId);
		return array('category'=>$categoryPmsDetail);
        /*$param=$this->request->request->all();
        if (count($param)) {
            foreach ($param['prod_list'] as $key=>$pmsId) {
                $key=$key+1;
                $categoryApiManager = $this->categoryApiManager->setCateogryPosition($pmsId, $key);
            }
        }
		RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
        if ($this->request->isXmlHttpRequest()) {
            $response = new Response();
            $output = array('success' => 'success');
            $response->headers->set('Content-Type', 'application/json');
            $response->setContent(json_encode($output));
            return $response;
        }*/
    }

    
    /**
     *
     * @return Response
     *
     * @throws null
     *
     * @Route("/category-link-update",
     * name="officebrain_bundle_category_savecategorylink",
     * options={"expose"=true}
     * )
     * 
     *
     **/
    public function saveCategoryLinkAction()
    {
        $this->init();
		$pmsId = $this->request->get('pms_id');
		$url = trim($this->request->get('url'));
		if($url!=""){
			$saveUrl = $this->categoryApiManager->setCateogryLink($pmsId, $url);
			RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
			return new JsonResponse([
			    'url' => trim($url),
			    'status' => 1
			]);
			//echo json_encode(array('url'=>trim($url),'status'=>1));
		}else{
			return new JsonResponse([
			    'message' => "Url is required",
			    'status' => 0
			]);
			//echo  json_encode(array('message'=>"Url is required",'status'=>0));
		}
    }
}
