<?php

namespace OfficeBrain\Bundle\ProductTagBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Translation\Translator;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use OfficeBrain\Bundle\ProductTagBundle\Entity\PrivateTagProductMapping;
use OfficeBrain\Bundle\ProductTagBundle\Form\PrivateTagMasterType;
use OfficeBrain\Bundle\SearchBundle\Form\Type\ProductSearchType;
use OfficeBrain\Bundle\SearchBundle\Form\Data\ProductSearchData;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
use OfficeBrain\Bundle\CoreBundle\Cache\RedisCacheService;

/**
 * @author OfficeBrain 4505 <info@officebrain.com>
 * Description : Private Tag Controller
 *
 * @Route("/admin/{_locale}/private-tag")
 */
class ProductTagAdminController extends Controller
{
    public function __construct()
    {
        $this->productTagManager = null;
        $this->countryMaster = null;
        $this->translator = null;
        $this->validationParams = null;
        $this->webImagesUrl = null;
        $this->featuredIconUrl = null;
        $this->featuredIconPath = null;
        $this->searchHelper = null;
        $this->searchManager = null;
        $this->paginationManager = null;
        $this->arrayToPaginationManager = null;
        $this->statsh_cache_wrapper = RedisCacheService::create();
        $this->moduleCachePrefix='__ProductTagManagement__';
    }

    public function __destruct()
    {
        unset($this->productTagManager);
        unset($this->countryMaster);
        unset($this->translator);
        unset($this->validationParams);
        unset($this->webImagesUrl);
        unset($this->featuredIconUrl);
        unset($this->featuredIconPath);
        unset($this->searchHelper);
        unset($this->searchManager);
        unset($this->paginationManager);
        unset($this->arrayToPaginationManager);
        unset($this->statsh_cache_wrapper);
    }

    public function initAction()
    {
        $this->request = $this->getRequest();

        $this->productTagManager = $this->get('office_brain_product_tag_manager');
        $this->translator = $this->get('translator');
        $this->countryMaster = $this->productTagManager->showCountryLanguage($this->container->getParameter('country'), $this->container->getParameter('language'));
        $this->validationParams = array('allowValidation' => true, 'fieldAllowed' => true, 'mode' => 'add', 'countryMaster' => $this->countryMaster);
        $this->webImagesUrl = $this->getParameter('web_image.base_url');
        $this->featuredIconUrl = $this->getParameter('private_tag.icon_url').'featured-icon/';
        $this->featuredIconPath = $this->getParameter('private_tag.icon_path').'featured-icon/';
        $this->projectSetting = $this->request->get('project_setting');
        $this->productApiManager = $this->get("office_brain_product_admin_manager");
        //$this->solrObj = $this->get('solarium.client.product_en'); //EMP4464: Original Line
        
        //EMP4464: Changed above line with below code: Start
        $culture = explode('_', $this->projectSetting['locale_language']);
        //$solrCore = 'solarium.client.product_'.$culture[0];
        $solrCore = 'solarium.client.product_'.$this->projectSetting['locale_language'];
        $this->solrObj = $this->container->get($solrCore);
        //EMP4464: Changed above line with below code: End
        
        $this->searchHelper = $this->get('office_brain_search_helper');
        $this->searchManager = $this->get('office_brain_search_manager');
        $this->paginationManager = $this->get('knp_paginator');
        $this->arrayToPaginationManager = $this->get('office_brain_array_to_pagination_manager');
    }

    /**
     * @author Employee Id: 4505
     * Description : Add Product Tag
     *
     * @param 1 : null
     *
     * @return type Array
     *
     * @throws Exception: Null
     *
     * @Route("/add", name="office_brain_producttagbundle_privatetagadmin_add",
     * defaults={"tag_type"="private"})
     *
     * @Template("OfficeBrainProductTagBundle:Admin:/PrivateTag/addPrivateTag.html.twig")
     *
     * @Method({"GET"})
     */
    public function addAction()
    {
        $this->initAction();

        $addForm = $this->addFormBind();

        return $addForm['form_data_response'];
    }

    /**
     * @author Employee Id: 4505
     * Description : Process Add Product Tag
     *
     * @param 1 : null
     *
     * @return Array
     *
     * @throws Exception: Null
     *
     * @Route("/add", name="office_brain_producttagbundle_privatetagadmin_processadd",
     * defaults={"tag_type"="private"})
     *
     * @Template("OfficeBrainProductTagBundle:Admin:/PrivateTag/addPrivateTag.html.twig")
     *
     * @Method({"POST"})
     */
    public function processAddAction()
    {
        $this->initAction();

        $addForm = $this->addFormBind();
        $form = $this->productTagManager->filterFormData($addForm['form_object'], $this->countryMaster);

        $errors = $this->productTagManager->getErrorMessages($form);
       // print_r($errors);
        //echo $form->getErrorsAsString();exit;
        if ($form->isValid()) {
            $add = $this->productTagManager->add($form, $this->countryMaster, $this->featuredIconPath);
            $countryShort = $this->productTagManager->getCountryName($this->countryMaster, $add->getCountryId());
            $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('tag.action.tag_add_success'));

            return $this->redirect($this->generateUrl('office_brain_producttagbundle_privatetagadmin_list', array('country' => $countryShort)));
        }
        $addForm['form_data_response']['form'] = $form->createView(); 

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

        return $addForm['form_data_response'];
    }

    /**
     * @author Employee Id: 4505
     * Description : Edit Product Tag
     *
     * @param 1 : $id
     *
     * @return Array
     *
     * @throws Exception: Null
     *
     * @Route("/edit/{id}", name="office_brain_producttagbundle_privatetagadmin_edit",
     * defaults={"tag_type"="private"}))
     *
     * @Template("OfficeBrainProductTagBundle:Admin:/PrivateTag/editPrivateTag.html.twig")
     */
    public function editAction($id)
    {
        $this->initAction();

        $editForm = $this->editFormBind();
        $form = $editForm['form_object'];
        
        if ($form->isValid()) {
            $formData = $form->getData();
            $edit = $this->productTagManager->edit($formData, $this->container, $this->featuredIconPath,$editForm['form_data_response']['iconArray']);
            $countryShort = $this->productTagManager->getCountryName($this->countryMaster, $edit->getCountryId());
            /* Solr sync when update private tag start - 5836 */
            $listMappedProducts = $this->generatePrivateMappedArray($id,'');
            foreach ($listMappedProducts['data'] 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['product_id'],$localization_to_update,$this->projectSetting['project_id'],$env,$this->projectSetting['instance_id'],'update');
            	}
            }
            
            RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
            
            /* Solr sync when update private tag end - 5836 */
            $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('tag.action.tag_edit_success'));

            return $this->redirect($this->generateUrl('office_brain_producttagbundle_privatetagadmin_list', array('country' => $countryShort)));
        }

        return $editForm['form_data_response'];
    }

    /**
     * @author Employee Id: 4505
     * Description : Listing of Product Tag.
     *
     * @param 1 : null
     *
     * @return Array
     *
     * @throws Exception: Null
     *
     * @Route("/list/{page}", name="office_brain_producttagbundle_privatetagadmin_list",
     * requirements={"records_per_page"="2|4|8|16|996","page"="\d+"},
     * defaults={"tag_type"="private","page"=1})
     *
     * @Method("GET")
     *
     * @Template("OfficeBrainProductTagBundle:Admin:/PrivateTag/listPrivateTag.html.twig")
     */
    public function listAction()
    {        
        $this->initAction();

        $data = $this->productTagManager->setPaggingParameters($this->countryMaster);
        $productTagMasterList = $this->productTagManager->getList($data['page_paramater']);

        if (count($productTagMasterList)) {
            $paginator = $this->get('knp_paginator');
            $data ['pagination'] = $paginator->paginate($productTagMasterList, $data['page_paramater']['page'], $data['page_paramater']['records_per_page'], array(), count($productTagMasterList));
            unset($productTagMasterList);
        }

        return $data;
    }

    /**
     * @author Employee Id: 4505
     * Description : Ajax Listing of Product Tag.
     *
     * @param : null
     *
     * @return type : Array / Json
     *
     * @throws Exception: Null
     *
     * @Route("/list-ajax/{page}", name="office_brain_producttagbundle_privatetagadmin_listajax",
     * requirements={"records_per_page"="2|4|8|16|996","page"="\d+"},
     * defaults={"tag_type"="private","records_per_page"=8,"page"=1,"language"="en"})
     *
     * @Template("OfficeBrainProductTagBundle:Admin:/PrivateTag/listPrivateTagAjax.html.twig")
     */
    public function listAjaxAction()
    {
        $this->initAction();

        $data = $this->productTagManager->setPaggingParameters($this->countryMaster);
        $productTagMasterList = $this->productTagManager->getList($data['page_paramater']);

        if (count($productTagMasterList)) {
            $paginator = $this->get('knp_paginator');
            $data['pagination'] = $paginator->paginate($productTagMasterList, $data['page_paramater']['page'], $data['page_paramater']['records_per_page'], array(), count($productTagMasterList));
            unset($productTagMasterList);
        }

        if ($this->request->isXmlHttpRequest()) {
            $varJason = $this->get('twig')->render('OfficeBrainProductTagBundle:Admin:/PrivateTag/listPrivateTagAjax.html.twig', $data);

            return new JsonResponse($varJason);
        } else {
            return $this->render('OfficeBrainProductTagBundle:Admin:/PrivateTag/listPrivateTagAjax.html.twig', $data);
        }
    }

    /**
     * @author Employee Id: 4505
     * Description : To delete Created Tag.
     *
     * @param : $id
     *
     * @return type : Array
     *
     * @throws Exception: Null
     *
     * @Route("/delete", name="office_brain_producttagbundle_privatetagadmin_delete",
     * defaults={"tag_type"="private"})
     */
    public function deleteAction()
    {
        $this->initAction();

        $id = $this->request->get('id');
        $response = $this->productTagManager->setDelete($id);
        
        if ($response > 0) {
            $this->responseArray['status'] = 'success';
            $this->responseArray['success_message'] = $this->translator->trans('tag.action.tag_delete_success');

            RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
            
        } else {
            $this->responseArray['status'] = 'error';
            $this->responseArray['error_message'] = $this->translator->trans('tag.action.tag_delete_error');
        }
        
        return new JsonResponse($this->responseArray);

        /* if ($response->getId() > 0) {
            $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('tag.action.tag_delete_success'));
        } else {
            $this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('tag.action.tag_delete_error'));
        }

        if ($this->request->isXmlHttpRequest()) {
            return new JsonResponse(array('success' => 'success', 'page_url' => $this->generateUrl('office_brain_producttagbundle_privatetagadmin_list', array())));
        } else {
            return $this->redirect($this->generateUrl('office_brain_producttagbundle_privatetagadmin_list'));
        } */
    }

    /**
     * @author Employee Id: 4505
     * Description : Show Make Copy for Event Category.
     *
     * @param : $country_id
     *
     * @return type : Array
     *
     * @throws Exception: Null
     *
     * @Route("/showmakecopy/{country_id}", name="office_brain_producttagbundle_privatetagadmin_showmakecopy")
     *
     * @Template("OfficeBrainProductTagBundle:Admin:makecopy.html.twig")
     */
    public function showMakeCopyAction($country_id)
    {
        $this->initAction();

        $finalCountryList = $this->productTagManager->getCountriesForCopy($country_id, $this->countryMaster);

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

        return $this->render('OfficeBrainProductTagBundle:Admin:makecopy.html.twig', array(
                  'countryMaster' => $finalCountryList, ));
    }

    /**
     * @author Employee Id: 4505
     * Description : Make Copy for Product Tag.
     *
     * @param : null
     *
     * @return type : Array
     *
     * @throws Exception: Null
     *
     * @Route("/makecopy", name="office_brain_producttagbundle_privatetagadmin_makecopy")
     *
     * @Template()
     */
    public function makeCopyAction()
    {
        $this->initAction();

        $country = $this->request->get('country');
        $productTagId = $this->request->get('submit_id');
        $countryList = $this->request->get('country_list');
        $countryListAction = $this->request->get('country_list_action');
        $productTagMaster = $this->productTagManager->makeCopy($this->countryMaster, $productTagId, $countryList, $countryListAction);

        if (is_object($productTagMaster)) {
            $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('tag.action.copy_success'));
            RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
        } else {
            $this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('tag.action.copy_success'));
        }

        return $this->redirect($this->generateUrl('office_brain_producttagbundle_privatetagadmin_list', array('country' => $country)));
    }

    /*
     * @author Employee Id: 4505
     * Description : Render form data
     *
     * @param : $productTagMaster
     *
     * @return type : Array
     *
     * @throws Exception: Null
     */

    public function renderDataInForm($productTagMaster)
    {
        $formData = array();
        $formData['featuredIconName'] = '';
        $formData['tagIconName'] = '';
        $formData['country_short'] = key($this->countryMaster);

        if ($productTagMaster->getFeaturedIcon()) {
            $formData['featuredIconName'] = $productTagMaster->getFeaturedIcon();
        }
        if ($productTagMaster->getTagIcon()) {
            $formData['tagIconName'] = $productTagMaster->getTagIcon();
        }

        if ($productTagMaster->getCountryId()) {
            $formData['country_short'] = $this->productTagManager->getCountryName($this->countryMaster, $productTagMaster->getCountryId());
        } elseif ($this->request->get('country')) {
            $formData['country_short'] = $this->request->get('country');
        }

        $formData['country_name'] = $this->countryMaster[$formData['country_short']]['name'];
        $formData['countryMaster'] = $this->countryMaster;
        $formData['countryList'] = $this->productTagManager->getCountries($this->countryMaster);
        $formData['featuredIconUrl'] = $this->featuredIconUrl;
        $formData['tagIconUrl'] = $this->featuredIconUrl;
        $formData['tmpImgIcon'] = $this->webImagesUrl.'no-image-available.png';
        $formData['tmpTagImgIcon'] = $this->webImagesUrl.'no-image-available.png';

        return $formData;
    }

    /**
     * @author Employee Id: 4505
     * Description : Bind form data add.
     *
     * @param : null
     *
     * @return Array
     *
     * @throws Exception: Null
     */
    public function addFormBind()
    {
        $this->validationParams['mode'] = 'add';
        $productTagMaster = $this->productTagManager->bindAddFormData($this->countryMaster);
        $form = $this->createForm(new PrivateTagMasterType($this->container, $this->validationParams, $productTagMaster), $productTagMaster);
        $form->handleRequest($this->request);
        $formDataResponse = $this->renderDataInForm($productTagMaster);
        $formDataResponse['_locale'] = $this->request->get('_locale');
        $formDataResponse['form'] = $form->createView();
        $formDataResponse['country_id'] = key($this->countryMaster);

        if ($form->getData()->getCountryId() > 0) {
            $formDataResponse['country_id'] = $form->getData()->getCountryId();
        }

        return array('form_object' => $form, 'form_data_response' => $formDataResponse);
    }

    /**
     * @author Employee Id: 4505
     * Description : Bind form data Edit.
     *
     * @param : null
     *
     * @return Array
     *
     * @throws Exception: Null
     */
    public function editFormBind()
    {
        $this->validationParams['mode'] = 'edit';
        $tagId = $this->request->get('id');
        $productTagMaster = $this->productTagManager->getDetail($tagId);
        $productTagMaster = $this->productTagManager->bindEditFormData($productTagMaster);
        
        $featuredIcon = $productTagMaster->getFeaturedIcon();
        $tagIcon = $productTagMaster->getTagIcon();
        $form = $this->createForm(new PrivateTagMasterType($this->container, $this->validationParams, $productTagMaster), $productTagMaster);
        $form->handleRequest($this->request);
        
        $formDataResponse = $this->renderDataInForm($productTagMaster);
        $formDataResponse['product_tag_id'] = $productTagMaster->getId();
        $formDataResponse['form'] = $form->createView();
        $formDataResponse['iconArray']['featuredIconName'] = $featuredIcon;
        $formDataResponse['iconArray']['tagIconName'] = $tagIcon;

        return array('form_object' => $form, 'form_data_response' => $formDataResponse);
    }

    /**
     * @author Employee Id: 4505
     * Description : Private tag product mapping action
     *
     * @param 1 : $id
     *
     * @return type Array
     *
     * @throws Exception: Null
     *
     * @Route("/product-mapping/{id}", name="office_brain_producttagbundle_privatetagadmin_productmapping",
     * defaults={"tag_type"="private"})
     *
     * @Template("OfficeBrainProductTagBundle:Admin:/PrivateTag/privateTagProductMapping.html.twig")
     */
    public function privateProductMappingAction($id)
    {
        $this->initAction();
        
        $searchParameters = $this->productTagManager->pageParameters($this->countryMaster);
        $searchParameters['tag_id'] = $id;
        $searchParameters['tag_name'] =  $this->productTagManager->getDetail($id)->getTags()->first()->getTagName();
        $searchParameters['advance_search_form_fields'] = $this->searchManager->advanceSearchService();
        
        if(!empty($_REQUEST['advance_search_product_mapping'])){
            $searchParameters['search_result_array'] = $this->searchManager->searchService();
            
            if(!empty($searchParameters['search_result_array'])){
                $searchParameters['search_result_array'] = $this->productTagManager->isAlreadyInTag($searchParameters['search_result_array']['search_result_array'], $searchParameters);
                
                $this->arrayToPaginationManager->setPaginationArray($searchParameters['search_result_array']);
                $this->arrayToPaginationManager->doConvert();
                $searchParameters['pagination'] = $this->arrayToPaginationManager->getPagination();
            }
        }

        return $searchParameters;
    }

    /**
     * @author Employee Id: 4505
     * Description : Private tag product mapping action
     *
     * @param 1 : null
     *
     * @return type Array
     *
     * @throws Exception: Null
     *
     * @Route("/map-product-in-tag/{tag_id}/{product_id}", name="office_brain_producttagbundle_privatetagadmin_mappproductintag",
     * defaults={"tag_type"="private"})
     *
     * @Template()
     */
    public function mapPrivateProductInTagAction()
    {
        $this->initAction();

        $data = $this->productTagManager->addToTag($this->solrObj);

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

        return $this->redirect($this->generateUrl('office_brain_producttagbundle_privatetagadmin_productmapping', array('id' => $data['tag_id'], 'response_data' => $data)));
    }

    /**
     * @author Employee Id: 4505
     * Description : Delete private product action
     *
     * @param 1 : $id
     *
     * @return type Array
     *
     * @throws Exception: Null
     *
     * @Route("/delete-product", name="office_brain_producttagbundle_privatetagadmin_deleteprivateproduct",
     * defaults={"tag_type"="private"})
     */
    public function deletePrivateProductAction()
    {
        $this->initAction();
        
        $id = $this->request->get('id');
        $response = $this->productTagManager->setDeleteProduct($id);
        
        if ($response > 0) {
            $this->responseArray['status'] = 'success';
            $this->responseArray['success_message'] = $this->translator->trans('tag.action.tag_delete_success');
            
            RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);

        } else {
            $this->responseArray['status'] = 'error';
            $this->responseArray['error_message'] = $this->translator->trans('tag.action.tag_delete_error');
        }
        
        return new JsonResponse($this->responseArray);

        /* if ($response > 0) {
            $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('tag.action.tag_delete_success'));
        } else {
            $this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('tag.action.tag_delete_error'));
        }

        if ($this->request->isXmlHttpRequest()) {
            return new JsonResponse(array('success' => 'success', 'page_url' => $this->generateUrl('office_brain_producttagbundle_privatetagadmin_list', array())));
        } else {
            return $this->redirect($this->generateUrl('office_brain_producttagbundle_privatetagadmin_list'));
        } */
    }

    /**
     * @author Employee Id: 4505
     * Description : List of mapped products
     *
     * @param 1 : $id
     *
     * @return type Array
     *
     * @throws Exception: Null
     *
     * @Route("/mapped-product-list/{id}/{page}", name="office_brain_producttagbundle_privatetagadmin_mappedproductlist",
     * requirements={"records_per_page"="2|4|8|16|996","page"="\d+"},
     * defaults={"tag_type"="private","records_per_page"=8,"page"=1,"type"="sku"})
     *
     * @Template("OfficeBrainProductTagBundle:Admin:/PrivateTag/privateTagMappedList.html.twig")
     */
    public function privateMappedProductListAction($id)
    {
        $this->initAction();
        
		$filterParameters = array();
        $filterQuerySkuOrKeyword = $this->request->query->get('filter_query_sku_or_keyword','');
        if($filterQuerySkuOrKeyword != "")
        {
        	$filterParameters["productSkuOrKeyword"] = $filterQuerySkuOrKeyword;
        }
        
        $data = $this->generatePrivateMappedArray($id,$filterParameters);
       // print_r($data);exit;
//         if (count($data['data'])) {
            $paginator = $this->get('knp_paginator');
            $data['pagination'] = $paginator->paginate($data['data'], $this->request->get('page'), $data['page_paramater']['records_per_page'], array(), $data['count']);
            $data['tag_id'] = $id;
            $data['filter_query_sku_or_keyword'] = $filterQuerySkuOrKeyword;
            //unset($data['data']);
//         }

        if ($this->request->isXmlHttpRequest()) {
            $varJason = $this->get('twig')->render('OfficeBrainProductTagBundle:Admin:/PrivateTag/privateTagMappedList.html.twig', $data);

            return new JsonResponse($varJason);
        } else {
            return $this->render('OfficeBrainProductTagBundle:Admin:/PrivateTag/privateTagMappedList.html.twig', $data);
        }
    }

    /**
     * @author Employee Id: 4505
     * Description : Generate Private Mapped Array
     *
     * @param 1 : $id
     *
     * @return type Array
     *
     * @throws Exception: Null
     */
    public function generatePrivateMappedArray($id,$filterParameters = "")
    {
		
    	$productList = $tagMappedList = array();
         
        $data = $this->productTagManager->setPaggingParameters($this->countryMaster);
        
        list($dataList, $tagName) = $this->productTagManager->getMappedList($id);
        
// 		foreach ($dataList as $values) {
//             $searchParameters = $data['page_paramater'];
//             if (trim($values->getProductSku()) != '') {
//                 $searchParameters['sku'] = $values->getProductSku();
//                 $result = $this->searchSkuAndName($searchParameters,$filterParameters);
                
//                 if(isset($result) && (!(empty($result))) && $result != '')
//                 {
// 	                $result[0]['mapped_id'] = $values->getId();
// 	                $productList[] = $result[0];
//                 }
//             }
//             unset($searchParameters);
//         }
//echo "<pre>";var_dump($dataList);exit;
		foreach($dataList as $product) {
			$mappedProductSku[] = $product->getProductSku();
			$tagMappedList[$product->getProductId()] = $product->getId();
		}
		
		
		if (count($mappedProductSku) > 0) {
			$productList = $this->getProductDataByProductSku($mappedProductSku,$filterParameters);
		}
		
		foreach($productList["data"]as $key => $product) {
			
			if (isset($tagMappedList[$product['product_id']])){
				$productList["data"][$key] = $product;
				$productList["data"][$key]['mapped_id'] = $tagMappedList[$product['product_id']];
			}
			else {
				unset($productList["data"][$key]);
			}
		}
		//print_r($productListNew["data"]);exit;
		$data['data'] = $productList["data"];
		$data['count'] = $productList["count"];
        
        $data['page_paramater']['tag_id'] = $id;
        $data['tag_name'] = $tagName;

        return $data;
    }

    /**
     * @author Employee Id: 5460
     * Description : Search skuname
     *
     * @param 1 : $searchParameters
     *
     * @return type Array
     *
     * @throws Exception: Null
     */
    public function searchSkuAndName($searchParameters,$filterParameters = '')
    {
    	$data = array();
    	$productKeyword = '';
    	$productSearchForm = new ProductSearchType();
    	
    	$finalRequest = array(
    		'sku' => $searchParameters['sku'],
    	);
    	if(isset($filterParameters['productSkuOrKeyword']) && $filterParameters['productSkuOrKeyword'] != '')
    	{
    		$finalRequest['keyword'] = $filterParameters['productSkuOrKeyword'];
    	}  	
    	
    	$productSearch = new ProductSearchData($this->getDoctrine()->getManager(), $searchParameters['language_id']);
    	$form = $this->createForm($productSearchForm, $productSearch, array(
    			'csrf_protection' => false,
    	));
    	$form->bind($finalRequest);
    
    	if ($form->isValid()) {
    		$productSearchData = $form->getData();
    		//$productDetailArray = $this->get('office_brain_search_manager')->searchResult($productSearchData, $searchParameters['facet'], $this->searchHelper);
    		$productDetailArray = $this->get('office_brain_search_manager')->searchResult($productSearchData);
    		$data = $productDetailArray ['search_result_array']['data'];
    	}
    
    	return $data;
    }
    
    /**
     * @author Employee Id: 4505
     * Description : Search Keyword.
     *
     * @param 1 : $searchParameters
     *
     * @return type Array
     *
     * @throws Exception: Null
     */
    public function searchKeyword($searchParameters)
    {
        $data = array();
        $productSearchForm = new ProductSearchType();
        $finalRequest = array(
          'keyword' => $searchParameters['search_query'],
        );
        $productSearch = new ProductSearchData($this->getDoctrine()->getManager(), $searchParameters['language_id']);
        $form = $this->createForm($productSearchForm, $productSearch, array(
          'csrf_protection' => false,
        ));
        $form->bind($finalRequest);

        if ($form->isValid()) {
            $productSearchData = $form->getData();
            //$productDetailArray = $this->get('office_brain_search_manager')->searchResult($productSearchData, $searchParameters['facet'], $this->searchHelper);
            $productDetailArray = $this->get('office_brain_search_manager')->searchResult($productSearchData);
            $data = $productDetailArray ['search_result_array']['data'];
        }

        return $data;
    }
    
    public function getProductDataByProductSku($mappedProductSku,$filterParameters)
    {
		
    	$this->request->query->set('search_query', $filterParameters['productSkuOrKeyword']);
    	$this->request->query->set('search_type', 'all');
    	$this->request->query->set('sku', implode(",",$mappedProductSku));
    	$this->request->query->set('sort_by', 'title::asc');
    	$this->searchManager->setRecordPerPage(count($mappedProductSku));
    	$searchResult =$this->searchManager->searchService();
    	    	
    	$data['data'] = $searchResult['search_result_array']['data'];
    	$data['totalCount'] = count($searchResult['search_result_array']['data']);
    	$data['count'] = count($searchResult['search_result_array']['data']);
    	//echo "<pre>";
    	//print_r($data); die;
    	unset($searchResult);
    	
    	return $data;
    }
}
