<?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\Cache\RedisCacheService;

/**
 * This class for base functionality related to Brand. @author Office Brain - 4808 <support@officebrain.com>
 *
 * @Route("/admin/{_locale}/brand")
 */
class BrandAdminController extends Controller
{
	/**
	 * @author Employee Id: 4808
	 *
	 * Description : This function used for Set and intilize variables and request array
	 *
	 **/
	public function __construct()
	{
		$this->viewTwigData = null;
		$this->entityManager = null;
		$this->session = null;
		$this->brandApiManager = null;
		$this->brandApiManager = null;
		$this->queueApiManager = null;
        $this->projectSetting = null;
        $this->default_language = null;
	}
   /**
	* @author Employee Id: 4808
	*
	* Description : This function used for Unset the objects and variables
	*
	**/
	public function __destruct()
	{
		unset($this->viewTwigData);
		unset($this->request);
		unset($this->entityManager);
		unset($this->session);
		unset($this->brandApiManager);
		unset($this->formErrorManager);
        unset ($this->queueApiManager);
        unset($this->projectSetting);
        unset($this->default_language);
	}
	/**
	 * @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->brandApiManager = $this->get('officebrain_brand_api_manager');
		$this->productApiManager = $this->get("office_brain_product_admin_manager");
		$this->projectSetting = $this->request->get('project_setting');
		if ($this->has('office_brain_queue_api_manager')) {
            $this->request->attributes->set('object', 'CultureBrand');
            $this->queueApiManager = $this->get('office_brain_queue_api_manager');
        }
        list($this->default_language) = explode("_",$this->container->getParameter('locale'));
        $this->statsh_cache_wrapper=RedisCacheService::create();
		$this->moduleCachePrefix = '__HomePageBrandList__';
		$this->moduleCachePrefixAll = '__AllBrandPageList__';
	}

	/**
	 * @author Employee Id:4808
	 *
	 * Description: This Function is Used For Display Listing of Brands
	 *
	 * @Route("/list/{language}/{page}",
	 * name="officebrain_bundle_brand_list_brand_wo_culture",
	 * requirements={"records_per_page"="12|24|48|96|996"},
	 * defaults={"records_per_page"=12,"page"=1,"language"=""})
	 * @Template("OfficeBrainProductBundle:BrandAdmin:list.html.twig")
	 */

	public function listBrandAction()
	{
		$this->init();
		$data['pagination']=array();
		$param = $this->request->get('_route_params');
		$culture = ($param['language'])? $param['language'] : $this->default_language;

		$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_by', 'name');
		$sortType = $this->request->query->get('sort_type', 'asc');
		$search_Culture=$this->request->query->get('sort_culture');
		$searchParam = $this->request->query->get('search_param', '');
		$supplierId = $this->request->query->get('supplier_id', '');

		// 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
		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 = array($culture);
		$brandApiManager= $this->get("officebrain_brand_api_manager");
		$brandData = $brandApiManager->getList($culture,array(),$searchQuery,$sortBy,$sortType,$records_per_page,$page,1,$supplierId);


		$returnBrandData = array();
		if($brandData){
			$returnBrandData = $brandData[$activeCulture];
			$paginator  = $this->get('knp_paginator');
			$brandPaginationData['data'] = $brandData[$activeCulture];
			$brandPaginationData['count'] = $brandData['count'];
			$brandPaginationData['extra'] = 'extra';
			$data['pagination'] = $paginator->paginate($brandPaginationData, $page, $recordsPerPage);
		}

		//get supplier
		$projectId = $this->projectSetting['project_id'];
		$supplierData = $this->productApiManager->getSupplierNameList($projectId);
		
		// here we have to check and then pass brand Data
		$data['activeTab']=$defultCultureId;
		$data['search_query']=$searchQuery;
		$data['search_status']=$searchStatus;
		$data['sort_by']=$sortBy;
		$data['sort_type']=$sortType;
		$data['search_param']=$searchParam;
		$data['culture_list']=$culture_response;
		$data['supplier_id']=$supplierId;
		$data['params_to_append'] = array_merge($this->request->get('_route_params'), $this->request->query->all());
		return array('data'=>$data,'activeCulture'=>$activeCulture,'brandData'=>$returnBrandData,'supplierData'=>$supplierData);		
	}
	/**
	 * @author Employee Id:4808
	 * Description: Brand List From Master
	 * @Route("/ajaxbrandlist/{brand_culture}",
	 * name="officebrain_bundle_ajax_brand_list",
	 * requirements={"records_per_page"="12|24|48|96|996"},
	 * defaults={"records_per_page"=12,"brand_culture"=""})
	 */
	public function ajaxBrandlistAction()
	{
		$this->init();
		$data['pagination']=array();
		$param = $this->request->get('_route_params');
		$culture = $this->request->get('brand_culture',$this->default_language);

		$brand_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', '');

		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;

			$brandApiManager= $this->get("officebrain_brand_api_manager");
			$brandList = $brandApiManager->getAutoselectList($searchStatus, $searchParam, $searchQuery, $sortType, $sortBy,$culture,$brand_text);
			$selBrandValue = array();
			foreach ($brandList as $selectedValue)
			{
				$selBrandValue[] = array("value"=>$selectedValue['name'],"label"=> $selectedValue['name']);
			}
			return new Response($_GET['callback'] . '('.json_encode($selBrandValue).')');
	}

	/**
	 * @Route("/ajax-brand-select/{brand_culture}",
	 * name="officebrain_bundle_ajax_brand_select",
	 * requirements={"records_per_page"="12|24|48|96|996"},
	 * defaults={"records_per_page"=12,"brand_culture"=""})
	 */
	public function ajaxBrandSelectAction()
	{
		$this->init();
		$data['pagination']=array();
		$param = $this->request->get('_route_params');
		$culture = $this->request->get('brand_culture',$this->default_language);
		$brand_name = $this->request->get('brandValue');
		$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['brand_culture'])){
			$param['brand_culture']='';
		}

		$defultCultureId = $param['brand_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);

			$brandManager= $this->get("officebrain_brand_api_manager");

			$selectedBrandList = $brandManager->getSelectBrand($searchStatus, $searchParam, $searchQuery, $sortType, $sortBy,$culture,$send_culture_ids,$brand_name);
			$selBrand = array();

			foreach($culture_response as $key=>$value){
				if(isset($selectedBrandList[$key]) && count($selectedBrandList[$key]) >1)
				{
					//$selBrand[$key] = array("image"=>$selectedBrandList[$key]['image'],"culture_name" => $selectedBrandList[$key]['culture_description'],"name" => $selectedBrandList[$key]['name'],"id" => $selectedBrandList[$key]['culture_brand_id'],"brand_id" => $selectedBrandList[$key]['brand_id']);
					$selBrand[$key] = array("culture_name" => $selectedBrandList[$key]['culture_description'],"name" => $selectedBrandList[$key]['name'],"id" => $selectedBrandList[$key]['culture_brand_id'],"brand_id" => $selectedBrandList[$key]['brand_id'],"image"=>$selectedBrandList[$key]['image']);
				}
				else {
					$selBrand[$key]="";
				}
			}
			$selData['selectedData'] = $selBrand;
			return new JsonResponse($selData);
	}

	/**
	 * @Route("/addculturebrand/{brand_culture}",
	 * name="officebrain_bundle_add_culture_brand",
	 * requirements={"records_per_page"="12|24|48|96|996"})
	 * defaults={"records_per_page"=12,"band_culture"=""})
	 * Description : Function for Add New Brand
	 */
	public function addCultureBrandAction()
	{
		$this->init();
		$culture = $this->request->get('brand_culture',$this->default_language);
		$post_data = $this->request->get('data');
		$culture_ids = $this->container->getParameter('language');
		$apiManager = $this->get("officebrain_brand_api_manager");
		$response = $apiManager->setBrandData($culture,$_POST['data'],$culture_ids);
		if($response['status']=='success'){
			$pms_id = $response['pms_id'];
			RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);

			RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefixAll);

			
			//ERP SYNC
			try{
				$erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
                if($erpIntegration && $erpIntegration['productManagement'] == 1 && !empty($this->queueApiManager)) {
					$cultureNames = array_keys($culture_ids);
					$queueData = $apiManager->processBrandData($pms_id, $cultureNames);
					$this->queueApiManager->mapQueue('create', $queueData);
				}
			}catch(Exception $e){

			}
			//ERP SYNC END
		}else{
			//PROCESS ERROR
		}

		$response['message'] = $this->translator->trans($response['message']);

		return new JsonResponse($response);
	}
	/**
	 * @Route("/addimage",
	 * name="officebrain_bundle_ajax_brand_image_add")
	 * Description : Function for Add New Brand
	 */
	function addBrandImageAction()
	{
		// Now called API for brand Image
		$apiManager = $this->get("officebrain_brand_api_manager");
		$apiManager->addBrandImage($_FILES);
		RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);

		RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefixAll);
	}

	/**
     * @author Employee Id:5190
     * Description: Supplierwise Brand List From Master
     * @Route("/ajaxsupplierwisebrandlist",options={"expose"=true},
     * name="officebrain_bundle_ajax_supplierwise_brand_list",options={"expose"=true})
     */
	public function ajaxSupplierwiseBrandlistAction()
	{
		$this->init();
		$param = $this->request->get('_route_params');
		$culture = $this->request->get('culture');
		$supplierId = $this->request->get('supplier_id');
		$brandData = $this->brandApiManager->getList($culture,array(),"","","","","",0,$supplierId);

		if(!empty($brandData)){
			$array_to_return = array('status'=>'success','brand_data'=>$brandData);
		}
		else{
			$array_to_return = array('status'=>'error','brand_data'=>$brandData);
		}
		return new JsonResponse($array_to_return);
	}

	/**
	 * @Route("/delete",
	 * name="officebrain_brand_bundle_delete_brand",
	 * options={"expose"=true},)
	 * @Template("OfficeBrainBrandBundle:Admin:list.html.twig")
	 */
	public function deleteAction(){
		$this->init();
		$projectId = $this->projectSetting['project_id'];
		$supplierData = $this->productApiManager->getSupplierNameList($projectId);
		$pmsId = $this->request->get('pms_id');
		$api_manager = $this->get('officebrain_brand_api_manager');
		$data = $api_manager->delete($pmsId,$supplierData[0]['supplier_id']);
		//$api_manager->deleteShowhideBrand($pmsId);
		$data['message'] = $this->translator->trans($data['message']);
		RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
		RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefixAll);

		return new JsonResponse($data);
	}

	/**
	 * @Route("/update",
	 * name="officebrain_brand_bundle_update_brand",
	 * options={"expose"=true},)
	 * @Template("OfficeBrainBrandBundle:Admin:list.html.twig")
	 */
	public function updateAction(){
		$this->init();
		$projectId = $this->projectSetting['project_id'];
		$supplierData = $this->productApiManager->getSupplierNameList($projectId);
		$pmsId = $this->request->get('pms_id');
		$activeCultureId = $this->request->get('culture_id');
		$api_manager = $this->get('officebrain_brand_api_manager');
		$data = $api_manager->getUpdateInfoById($pmsId,$activeCultureId);
		return new JsonResponse($data);
	}

	/**
	 * @Route("/updateculturebrand",
	 * name="officebrain_brand_bundle_updateculturebrand_brand",
	 * options={"expose"=true},)
	 * @Template("OfficeBrainBrandBundle:Admin:list.html.twig")
	 */

	 public function updateCultureBrandAction(){
	 	$this->init();
	 	if ($this->request->isXmlHttpRequest() && $this->request->getMethod()=='POST') {
			$postData = $this->request->request->all();
		}
		$projectId = $this->projectSetting['project_id'];
		$supplierData = $this->productApiManager->getSupplierNameList($projectId);
		$culture_ids = $this->container->getParameter('language');
		$activeCulture = $this->request->get('brand_culture');
		$apiManager = $this->get('officebrain_brand_api_manager');
		//print_r($postData); die;
		$response = $apiManager->updateBrandCategory($postData,$activeCulture,$supplierData[0]['supplier_id']);
		if($response['status']=='success'){
			$pms_id = $response['pms_id'];
			RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
			RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefixAll);
			//ERP SYNC
			try{
				$erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
                if($erpIntegration && $erpIntegration['productManagement'] == 1 && !empty($this->queueApiManager)) {
					$cultureNames = array_keys($culture_ids);
					$queueData = $apiManager->processBrandData($pms_id, $cultureNames);
					$this->queueApiManager->mapQueue('create', $queueData);
				}
			}catch(Exception $e){

			}
			//ERP SYNC END
		}else{
			//PROCESS ERROR
		}

		$response['message'] = $this->translator->trans($response['message']);

		return new JsonResponse($response);

	 }

	 /**
 	 * @Route("/updatebrand-status/{{ pmdid}}/{{brand-status}}",
 	 * name="officebrain_brand_bundle_updatebrand_status",
 	 * options={"expose"=true},)
 	 */

	 public function updateBrandStatusAction()
	 {
		 	$this->init();
		 $pms_id = $this->request->get('pms_id');
		 $brand_status =$this->request->get('brand_status');
		 $status=$this->brandApiManager->updataBrandStatus($pms_id,$brand_status);
		 if(is_object($status)){
			 $response['status'] ='success_message';
			 $response['message'] ='Brand status updated sucessfully';
		 }else{
       $response['status']='failed';
			 $response['message'] ='Please try later';
		 }

		return new JsonResponse($response);
	 }



	  /**
     *
     * @author Employee Id: 4273
     *
     * Description : Change Status brand.
     *
     * @param 1 : brand Master Id
     *
     * @return type : JsonResponse object
     *
     * @throws Exception: No exception
     *
     * @Route("/brand/change-status/{brand_id}", name="officebrain_brand_bundle__change_status",
     * requirements={"instance_id"="\d+"},
     * defaults={"brand_id"="0"},
     * options={"expose"=true}
     * )
     *
     * @Method({"POST"})
     *
     * @Template()
     *
     */
    public function changeStatusAction()
    {
    	$this->init();
    
    	$id = $this->request->get('id');


    
    	if ($id) {
    		$status = $this->brandApiManager->changeBrandStatus($id);
    		RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
    		RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefixAll);
    		if ($status) {
    			return new JsonResponse(array('status' => 'success', 'status_message' =>'Status changed sucessfully'));
    		}
    	}
    
    	return new JsonResponse(array('status' => 'fail', 'status_message' => 'Please try later'));
    }
}
