<?php
namespace OfficeBrain\Bundle\AttributeBundle\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 Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Translation\Translator;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
use OfficeBrain\Bundle\CoreBundle\Cache\RedisCacheService;

/**
 *
 * @Route("/admin/{_locale}/attribute")
 */
class AttributeAdminController extends Controller
{
	public function __construct()
	{
		$this->viewTwigData = null;
		$this->request = null;
		$this->formErrorManager = new FormErrorManager\JsonError ();
        $this->projectSetting = null;
        $this->queueApiManager = null;
        $this->default_languagge = '';
        $this->statsh_cache_wrapper = RedisCacheService::create();
        $this->masterColorSwatches = null;
	}
	
	public function __destruct()
	{
		unset($this->viewTwigData);
		unset($this->request);
		unset($this->formErrorManager);
        unset($this->projectSetting);
        unset ($this->queueApiManager);
        unset ($this->default_languagge);
        unset ($this->statsh_cache_wrapper);
        unset($this->masterColorSwatches);
	}
	
	public function init()
	{
		$this->masterColorSwatches = $this->container->getParameter("master_color_swatches");
		$this->attributeColorMasterColorMappingRepository = $this->container->get("doctrine")->getRepository('OfficeBrainAttributeBundle:AttributeColorMasterColorMapping');
		$this->request = $this->getRequest();		
		$this->translator = $this->get('translator');
        $this->projectSetting = $this->request->get('project_setting');
        if ($this->has('office_brain_queue_api_manager')) {
            $this->request->attributes->set('object', 'CultureAttribute');
            $this->queueApiManager = $this->get('office_brain_queue_api_manager');
        }
        $this->projectUserSetting = $this->request->get('project_user_setting');
        $this->user = $this->projectUserSetting['user_data'];
        $this->supplierId = $this->user->getObCustomerId();
        $this->supplierId = str_replace(array('OB','ob'), '', $this->supplierId);
        if(empty($this->supplierId)){
        	$this->supplierId = 0;
        }
        list($this->default_languagge) = explode("_",$this->container->getParameter('locale'));
	}
	
	
	/**
	 * @Route("/list/{language}/{page}",
	 * name="officebrain_bundle_attribute_list",
	 * requirements={"records_per_page"="12|24|48|96|996"},
	 * defaults={"records_per_page"=12,"page"=1,"language"=""})
	 * @Template("OfficeBrainAttributeBundle:Admin:list.html.twig")
	 */
	public function listAction()
	{
		$this->init();
		$data['pagination']=array();
		$param = $this->request->get('_route_params');
		
		$culture = ($param['language'])? $param['language'] : $this->default_languagge;
		
		$searchQuery = $this->request->get('search_query');
		$sortBy = $this->request->get('sort_by');
		$sortType = $this->request->get('sort_type');
		
		// 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
		
		// Set Attrbute Value Limit For Listing
		$attribute_value_limit  = 50;
		if(! isset($param['culture'])){
			$param['culture']='';
		}
		$cultures = $this->container->getParameter('language');
		$api_manager = $this->get('officebrain_attribute_api_manager');
		@list($attribute_data,$countArray)= $api_manager->getList($culture,array(),1,array(),$searchQuery,$sortBy,$sortType,$records_per_page,$page,1,$attribute_value_limit);
		if($attribute_data){
			$paginator  = $this->get('knp_paginator');
 			$attributePaginationData['data'] = $attribute_data[$culture];
			$attributePaginationData['count'] = $attribute_data['count'];
			$attributePaginationData['extra'] = 'extra';
			$data['pagination'] = $paginator->paginate($attributePaginationData, $page, $recordsPerPage);
		}
// 		$data['attribute_value_to_display'] = $attribute_value_limit;
		$data['view_more_display'] = $countArray;
		$data['search_query'] = $searchQuery;
		$data['sort_by'] = $sortBy;
		$data['sort_type'] = $sortType;
		$data['params_to_append'] = array_merge($this->request->get('_route_params'), $this->request->query->all());
		return array("activeCulture" => $culture,"attributeData" => $attribute_data[$culture],"data" => $data);
	}
	
	/**
	 * @Route("/attribute-value-list/{language}",
	 * name="officebrain_bundle_attribute_value_for_list",
	 * requirements={"records_per_page"="12|24|48|96|996"},
	 * defaults={})
	 * @Template("OfficeBrainAttributeBundle:Admin:list.html.twig")
	 */
	public function attributeValueListAction()
	{
		$this->init();
		$language = $this->request->get('language');
		$attributeId = $this->request->get('attribute-id');
		// For Pagination
		$page = $this->request->get('page', 1);
		$recordsPerPage = $this->request->get('recordsPerPage',20);
		$start_index = (($page - 1) * $recordsPerPage - 1);
		// End Pagination
		$api_manager = $this->get('officebrain_attribute_api_manager');
		$attribute_value_data= $api_manager->getAttributeValueList($attributeId,$language,$recordsPerPage,$start_index);
		return new JsonResponse($attribute_value_data);
	}
	/**
	 * @Route("/autofilllist/{language}",
	 * name="officebrain_bundle_attribute_autofill_list",
     * options={"expose"=true},
	 * requirements={"records_per_page"="12|24|48|96|996"},
	 * defaults={"records_per_page"=12,"language"=""})
	 */
    public function autofillListAction()
	{
		$this->init();
		$data['pagination']=array();
		$language = $this->request->get('language',$this->default_languagge);
		$attributeText = $this->request->get('attrText');

		$activeCulture = $language;
		$api_manager = $this->get('officebrain_attribute_api_manager');
		$attribute_data= $api_manager->getAutofillList($language,$attributeText);

		$selAttribute = array();
		foreach ($attribute_data as $selectedValue)
		{
			$selAttribute[] = array("label"=> $selectedValue['label'],"value"=>$selectedValue['label']);
		}
		return new Response($_GET['callback'] . '('.json_encode($selAttribute).')');
	}
	/**
	 * @Route("/selectedattribute/{language}",
	 * name="officebrain_bundle_attribute_selected_attribute",
	 * options={"expose"=true},
	 * requirements={"records_per_page"="12|24|48|96|996"},
	 * defaults={"records_per_page"=12,"language"=""})
	 */
	public function selectedAttributeAction()
	{
		$this->init();
		$data['pagination']=array();
		$language = $this->request->get('language',$this->default_languagge);
		$attributeText = $this->request->get('attrName');
		$cultures = $this->request->get('cultures');
		
		$activeCulture = $language;
		$api_manager = $this->get('officebrain_attribute_api_manager');
		$attribute_data= $api_manager->getSelectedAttribute($language,$cultures,$attributeText);
		return new JsonResponse($attribute_data);			
	}
	
/**
	 * @Route("/addselectedattribute/{language}",
	 * name="officebrain_bundle_attribute_add_selected_attribute",
	 * options={"expose"=true},
	 * requirements={"records_per_page"="12|24|48|96|996"},
	 * defaults={"records_per_page"=12,"language"=""})
	 */
	public function addSelectedAttributeAction()
	{
	    $this->init();
		$formData = $this->request->get('data');
		$culture_ids = $this->container->getParameter('language');
		$cultures = $this->request->get('cultures');
		$api_manager = $this->get('officebrain_attribute_api_manager');
		$response= $api_manager->addSelectedAttribute($formData,$cultures);
		
		if($response['status'] == 'success_message'){
			$pms_id	= $response['pms_id'];
            
			try{
				//ERP SYNC
				$erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
                if($erpIntegration && $erpIntegration['productManagement'] == 1 && !empty($this->queueApiManager)) {
                    $cultureNames = array_keys($culture_ids);
                    $queueData = $api_manager->processAttributeData($pms_id, $cultureNames);
                    $this->queueApiManager->mapQueue('create', $queueData);
                }
				//ERP SYNC END
			}catch(Exception $e){
				
			}
		}else{
			//PROCESS ERROR
		}
		$response['message'] = $this->translator->trans($response['message']);
		return new JsonResponse($response);		
	}
	
	/**
	 * @author Employee Id:4808
	 * Description: Ajax Autofill Attribute Values List From Master
	 * @Route("/ajaxattributevaluelist/{attribute_culture}",
	 * name="officebrain_bundle_ajax_attribute_value_list",
	 * options={"expose"=true},
	 * requirements={"records_per_page"="12|24|48|96|996"},
	 * defaults={"records_per_page"=12,"attribute_culture"=""})
	 */
	public function ajaxAttributeValuelistAction()
	{
		$this->init();
		$data['pagination']=array();
		$param = $this->request->get('_route_params');
		$culture = $this->request->get('attribute_culture',$this->default_languagge);
		$attribute_id = $this->request->get('attribute_id');
		$attribute_value_text = $this->request->get('q');
		$isFromProductPage = $this->request->get('from_product_add',false);
		$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;
		$attributeApiManager= $this->get("officebrain_attribute_api_manager");
		$attributeValueList = $attributeApiManager->getAutoselectAttributeValueList($searchStatus, $searchParam, $searchQuery, $sortType, $sortBy,$culture,$attribute_value_text,$attribute_id,$isFromProductPage);
		$selAttributeValue = array();
		foreach ($attributeValueList as $key=>$selectedValue)
		{
			$selAttributeValue[] = array("label"=> $selectedValue['attribute_value'], "value"=>$selectedValue['attribute_value_id']);
		}
		return new Response($_GET['callback'] . '('.json_encode($selAttributeValue).')');		
	}
	
	/**
	 * @Route("/ajax-attribute-value-select/{attribute_culture}/{attribute_id}",
	 * name="officebrain_bundle_ajax_attribute_value_select",
	 * requirements={"records_per_page"="12|24|48|96|996", "culture"="\w+"},
	 * defaults={"records_per_page"=12,"attribute_culture"="en"})
	 */
	public function ajaxAttributeValueSelectAction()
	{
		$this->init();
		
		$data['pagination']=array();
		$param = $this->request->get('_route_params');
		$culture = $this->request->get('attribute_culture',$this->default_languagge);
		$attribute_value_name = $this->request->get('attributeValue');
		$attribute_id = $this->request->get('attribute_id');
		$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['attribute_culture'])){
			$param['attribute_culture']='';
		}
	
		$defultCultureId = $param['attribute_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;
				
			$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);
			
			$attributeValueManager= $this->get("officebrain_attribute_api_manager");
			
			$selectedAttributeValueList = $attributeValueManager->getSelectAttributeValue($culture,$send_culture_ids,$attribute_id,$attribute_value_name);
			$selAttributeValue = array();
				
			foreach($culture_response as $key=>$value){

				if(isset($selectedAttributeValueList[$key]) && count($selectedAttributeValueList[$key]) >1)
				{
					$selAttributeValue[$key] = array("culture_name" => $selectedAttributeValueList[$key]['culture_name'],"name" => $selectedAttributeValueList[$key]['attribute_value'],"id" => $selectedAttributeValueList[$key]['id'],"attribute_value_id" => $selectedAttributeValueList[$key]['attribute_value_id']);
				}
				else {
					$selAttributeValue[$key]="";
				}
			}
			$selData['selectedData'] = $selAttributeValue;
			$selData['master_color'] = $selectedAttributeValueList['master_color'];
			$selData['selected_master_colors'] = $selectedAttributeValueList['selected_master_colors'];
			return new JsonResponse($selData);

		}
		else
		{
			$this->session->set('culture-list-warning',  $this->translator->trans('attribute.ADD_ATLEAST_ONE_CULTURE'));
			return $this->redirect($this->generateUrl("officebrain_culture_bundle_list"));
			// redirect to add culture
		}
	}
	/**
	 * @Route("/addcultureattributevalue/{attribute_culture}/{attribute_id}",
	 * name="officebrain_bundle_add_culture_attribute_value",
	 * requirements={"records_per_page"="12|24|48|96|996"})
	 * defaults={"records_per_page"=12,"attribute_culture"=""})
	 * Description : Function for Add New Culture Attribute Value
	 */
	public function addCultureAttributeValueAction()
	{
		$this->init();
		$culture = $this->request->get('attribute_culture',$this->default_languagge);
		$attribute_id = $this->request->get('attribute_id');
		$post_data = $this->request->request->all();
		$culture_ids = $this->container->getParameter('language');
		$apiManager = $this->get("officebrain_attribute_api_manager");
		
		$response = $apiManager->addCultureAttributeValue($culture,$attribute_id,$post_data,$culture_ids,$apiManager,$this->supplierId);
		
		return new JsonResponse($response);
	}

	/**
	 * @Route("/attributevalue/add",
	 * name="officebrain_bundle_attribute_value_add")
	 * @Template("OfficeBrainAttributeBundle:Admin:attributeValueForm.html.twig")
	 */
	
	public function addAction(){
		
		self::init();
		
		$route=$this->request->get('_route');
		$param = $this->request->get('_route_params');
		$attribute_master_id = $this->request->get('attribute_id');
		$attribute_name = $this->request->get('attribute_name');
		$active_culture = $this->request->get('active_culture');
		$dataAppendId = $this->request->get('data_append');
		$isEdit = false;
		
		$action=$this->generateUrl($route);
		
		$this->viewTwigData['form_action']= $action;
		$this->viewTwigData['attribute_id']= $attribute_master_id;
		$this->viewTwigData['attribute_name']= $attribute_name;
		$this->viewTwigData['activeCulture']= $active_culture;
		$this->viewTwigData['data_append_id']= $dataAppendId;
		
		
		return $this->viewTwigData;
	}
	
	/**
	 * Description: For Edit Attribute Value
	 * @Route("/editcultureattributevalue/{attribute_culture}/{attribute_id}",
	 * name="officebrain_bundle_edit_culture_attribute_value",
	 * requirements={"records_per_page"="12|24|48|96|996"})
	 * defaults={"records_per_page"=12,"attribute_culture"=""})
	 * Description : Function for Edit Existing Culture Attribute Value
	 */
	public function editCultureAttributeValueAction()
	{
		$this->init();
		$culture = $this->request->get('attribute_culture',$this->default_languagge);
		$attribute_id = $this->request->get('attribute_id');
		$post_data = $this->request->request->all();
		$culture_ids = $this->container->getParameter('language');
		$apiManager = $this->get("officebrain_attribute_api_manager");
		$supplierId = $this->supplierId;
		$supplierId = implode(",",$supplier_array);//$this->supplierId;
		
		$inkAttrColorId = $this->container->getParameter('ink_attr_color_id');
		$barrelAttrColorId = $this->container->getParameter('barrel_attr_color_id');
		$trimAttrColorId = $this->container->getParameter('trim_attr_color_id');
		$all_attribute_ids = array($inkAttrColorId, $barrelAttrColorId, $trimAttrColorId);
		$selected_attributes[$attribute_id] = $post_data;
		
		foreach($all_attribute_ids as $attribute_id){
			$this->request->attributes->set('attribute_id', $attribute_id);
			$res = $this->ajaxAttributeValueSelectAction();
			$res_content = json_decode($res->getContent());
			$attribute_value_id = $res_content->selectedData->en->attribute_value_id;
			if($attribute_value_id != ''){
				$post_data['attribute_value_id-'.$culture] = $attribute_value_id;
				$selected_attributes[$attribute_id] = $post_data;
			}
		}
		
		
		foreach($selected_attributes as $attribute_id=>$post_data){
		
			$response = $apiManager->setEditAttributeValueData($culture,$post_data,$culture_ids,$attribute_id,$supplierId);
			$cultureNames = array_keys($culture_ids);
			if($response['status']=='success_message'){
				$pms_id = $response['pms_id'];
				try{
					//ERP SYNC
					$erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
					if($erpIntegration && $erpIntegration['productManagement'] == 1 && !empty($this->queueApiManager)) {
						$this->request->attributes->set('object', 'CultureAttributeValue');
						$queueData = $apiManager->processAttributeValueData($pms_id,$attribute_id,$cultureNames);
						$this->queueApiManager->mapQueue('create', $queueData);
					}
					//ERP SYNC END
				}catch(Exception $e){
		
				}
				//ERP SYNC END
				$this->moduleCachePrefix='__swatchManagement__';
				$cacheKey=RedisCacheService::generateKey($this->statsh_cache_wrapper,array('Swatchesvalue', $culture),$this->moduleCachePrefix);
				//$cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
				RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$cacheKey);
			}else{
				//PROCESS ERROR
			}
		}
		
	
		//$response['message'] = $this->translator->trans($response['message']);
		$this->get('session')->getFlashBag()->set($response['status'], $this->translator->trans($response['message']));
		
		//return new JsonResponse($response);		
		return $this->redirect($this->generateUrl("officebrain_bundle_swatches_list",array('language' => $culture)));
	}
}
