<?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\PrivateCampaignProductMapping;
use OfficeBrain\Bundle\ProductTagBundle\Form\PrivateCampaignMasterType;
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 Campaign Controller
 *
 * @Route("/admin/{_locale}/private-campaign")
 */
class ProductCampaignAdminController extends Controller
{
    public function __construct()
    {
        $this->productCampaignManager = 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='__ProductCampaignManagement__';
    }

    public function __destruct()
    {
        unset($this->productCampaignManager);
        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->productCampaignManager = $this->get('office_brain_product_campaign_manager');
        $this->translator = $this->get('translator');
        $this->countryMaster = $this->productCampaignManager->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_campaign.icon_url').'featured-icon/';
        $this->featuredIconPath = $this->getParameter('private_campaign.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 Campaign
     *
     * @param 1 : null
     *
     * @return type Array
     *
     * @throws Exception: Null
     *
     * @Route("/add", name="office_brain_producttagbundle_privatecampaignadmin_add",
     * defaults={"campaign_type"="private"})
     *
     * @Template("OfficeBrainProductTagBundle:Admin:/PrivateCampaign/addPrivateCampaign.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 Campaign
     *
     * @param 1 : null
     *
     * @return Array
     *
     * @throws Exception: Null
     *
     * @Route("/add", name="office_brain_producttagbundle_privatecampaignadmin_processadd",
     * defaults={"campaign_type"="private"})
     *
     * @Template("OfficeBrainProductTagBundle:Admin:/PrivateCampaign/addPrivateCampaign.html.twig")
     *
     * @Method({"POST"})
     */
    public function processAddAction()
    {
        $this->initAction();
		
		
        $addForm = $this->addFormBind();
        $form = $this->productCampaignManager->filterFormData($addForm['form_object'], $this->countryMaster);
		
        $errors = $this->productCampaignManager->getErrorMessages($form);
       // print_r($errors);
        //echo $form->getErrorsAsString();exit;
        if ($form->isValid()) {

			$slugValue = '';
        	foreach ($form->getData()->getCampaigns() as $key=>$val){
        		$slugValue = $val->getSlug();
        	}
        	if($slugValue != ''){
        		$result = $this->productCampaignManager->getCampaignIdFromSlugForAdmin($slugValue);
        		if(!empty($result)){
        			$this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('campaign.action.slug_match'));
        			$addForm['form_data_response']['form'] = $form->createView(); 
        			return $addForm['form_data_response'];
        		}
        	}
            $add = $this->productCampaignManager->add($form, $this->countryMaster, $this->featuredIconPath);
            $countryShort = $this->productCampaignManager->getCountryName($this->countryMaster, $add->getCountryId());
            $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('campaign.action.campaign_add_success'));

            return $this->redirect($this->generateUrl('office_brain_producttagbundle_privatecampaignadmin_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 Campaign
     *
     * @param 1 : $id
     *
     * @return Array
     *
     * @throws Exception: Null
     *
     * @Route("/edit/{id}", name="office_brain_producttagbundle_privatecampaignadmin_edit",
     * defaults={"campaign_type"="private"}))
     *
     * @Template("OfficeBrainProductTagBundle:Admin:/PrivateCampaign/editPrivateCampaign.html.twig")
     */
    public function editAction($id)
    {
        $this->initAction();

        $editForm = $this->editFormBind();
        $form = $editForm['form_object'];
        if ($form->isValid()) {
        	$slugValue = '';
        	foreach ($form->getData()->getCampaigns() as $key=>$val){
        		$slugValue = $val->getSlug();
        	}
        	if($slugValue != ''){
        		$result = $this->productCampaignManager->getCampaignIdFromSlugForAdmin($slugValue);
        		if(!empty($result) && $id != $result['id']){
        			$this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('campaign.action.slug_match'));
        			$editForm = $this->editFormBind();
        			$form = $editForm['form_object'];
        			return $editForm['form_data_response'];
        		}
        	}
            $formData = $form->getData();
            //var_dump($this->request->get('sync_in_solr'))."==========="; die;
            $edit = $this->productCampaignManager->edit($formData, $this->container, $this->featuredIconPath,$editForm['form_data_response']['iconArray']);
            $countryShort = $this->productCampaignManager->getCountryName($this->countryMaster, $edit->getCountryId());
            /* Solr sync when update private campaign 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');
					/*if($editForm['show_on_web']=="yes"){	
						$this->productCampaignManager->syncPrivateCampaignTags($this->solrObj,$value['product_id'],$localization_to_update,$this->projectSetting['project_id'],$env,$this->projectSetting['instance_id'],'update');
					}else{
						$this->productCampaignManager->syncPrivateCampaignTags($this->solrObj,$value['product_id'],$localization_to_update,$this->projectSetting['project_id'],$env,$this->projectSetting['instance_id'],'delete');
					}*/
            	}
            }
            
            RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
            
            /* Solr sync when update private campaign end - 5836 */
            $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('campaign.action.campaign_edit_success'));

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

        return $editForm['form_data_response'];
    }

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

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

        return $data;
    }

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

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

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

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

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

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

        $id = $this->request->get('id');
        $this->productCampaignManager->setDeleteProductByCampaignId($id);
        $response = $this->productCampaignManager->setDelete($id);
        
        if ($response > 0) {
            $this->responseArray['status'] = 'success';
            $this->responseArray['success_message'] = $this->translator->trans('campaign.action.campaign_delete_success');

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

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

        if ($this->request->isXmlHttpRequest()) {
            return new JsonResponse(array('success' => 'success', 'page_url' => $this->generateUrl('office_brain_producttagbundle_privatecampaignadmin_list', array())));
        } else {
            return $this->redirect($this->generateUrl('office_brain_producttagbundle_privatecampaignadmin_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_privatecampaignadmin_showmakecopy")
     *
     * @Template("OfficeBrainProductTagBundle:Admin:makecopy.html.twig")
     */
    public function showMakeCopyAction($country_id)
    {
        $this->initAction();

        $finalCountryList = $this->productCampaignManager->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 Campaign.
     *
     * @param : null
     *
     * @return type : Array
     *
     * @throws Exception: Null
     *
     * @Route("/makecopy", name="office_brain_producttagbundle_privatecampaignadmin_makecopy")
     *
     * @Template()
     */
    public function makeCopyAction()
    {
        $this->initAction();

        $country = $this->request->get('country');
        $productCampaignId = $this->request->get('submit_id');
        $countryList = $this->request->get('country_list');
        $countryListAction = $this->request->get('country_list_action');
        $productCampaignMaster = $this->productCampaignManager->makeCopy($this->countryMaster, $productCampaignId, $countryList, $countryListAction);

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

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

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

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

        if ($productCampaignMaster->getFeaturedIcon()) {
            $formData['featuredIconName'] = $productCampaignMaster->getFeaturedIcon();
        }
        if ($productCampaignMaster->getCampaignIcon()) {
            $formData['campaignIconName'] = $productCampaignMaster->getCampaignIcon();
        }

        if ($productCampaignMaster->getCountryId()) {
            $formData['country_short'] = $this->productCampaignManager->getCountryName($this->countryMaster, $productCampaignMaster->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->productCampaignManager->getCountries($this->countryMaster);
        $formData['featuredIconUrl'] = $this->featuredIconUrl;
        $formData['campaignIconUrl'] = $this->featuredIconUrl;
        $formData['tmpImgIcon'] = $this->webImagesUrl.'no-image-available.png';
        $formData['tmpCampaignImgIcon'] = $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';
        $productCampaignMaster = $this->productCampaignManager->bindAddFormData($this->countryMaster);
        $form = $this->createForm(new PrivateCampaignMasterType($this->container, $this->validationParams, $productCampaignMaster), $productCampaignMaster);
        $form->handleRequest($this->request);
        $formDataResponse = $this->renderDataInForm($productCampaignMaster);
        $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';
        $campaignId = $this->request->get('id');
        $productCampaignMaster = $this->productCampaignManager->getDetail($campaignId);
        $productCampaignMaster = $this->productCampaignManager->bindEditFormData($productCampaignMaster);
        
        $featuredIcon = $productCampaignMaster->getFeaturedIcon();
        $campaignIcon = $productCampaignMaster->getCampaignIcon();
        $countryId = $productCampaignMaster->getCountryId();
        $form = $this->createForm(new PrivateCampaignMasterType($this->container, $this->validationParams, $productCampaignMaster), $productCampaignMaster);
        $form->handleRequest($this->request);
        
        $formDataResponse = $this->renderDataInForm($productCampaignMaster);
        $formDataResponse['product_campaign_id'] = $productCampaignMaster->getId();
        $formDataResponse['show_on_web'] = $productCampaignMaster->getShowOnweb();
        $formDataResponse['form'] = $form->createView();
        $formDataResponse['iconArray']['featuredIconName'] = $featuredIcon;
        $formDataResponse['iconArray']['campaignIconName'] = $campaignIcon;
        $formDataResponse['country_id'] = $countryId;
        $formDataResponse['_locale'] = $this->request->get('_locale');

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

    /**
     * @author Employee Id: 4505
     * Description : Private campaign product mapping action
     *
     * @param 1 : $id
     *
     * @return type Array
     *
     * @throws Exception: Null
     *
     * @Route("/product-mapping/{id}", name="office_brain_producttagbundle_privatecampaignadmin_productmapping",
     * defaults={"campaign_type"="private"})
     *
     * @Template("OfficeBrainProductTagBundle:Admin:/PrivateCampaign/privateCampaignProductMapping.html.twig")
     */
    public function privateProductMappingAction($id)
    {
        $this->initAction();
        
        $searchParameters = $this->productCampaignManager->pageParameters($this->countryMaster);
        $searchParameters['campaign_id'] = $id;
        $searchParameters['campaign_name'] =  $this->productCampaignManager->getDetail($id)->getCampaigns()->first()->getCampaignName();
        $searchParameters['advance_search_form_fields'] = $this->searchManager->advanceSearchService();
        
        if(!empty($_REQUEST['advance_search_product_mapping'])){
        	$this->request->query->set('display_campaign_product', '1');
            $searchParameters['search_result_array'] = $this->searchManager->searchService();
            
            if(!empty($searchParameters['search_result_array'])){
                $searchParameters['search_result_array'] = $this->productCampaignManager->isAlreadyInCampaign($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 campaign product mapping action
     *
     * @param 1 : null
     *
     * @return type Array
     *
     * @throws Exception: Null
     *
     * @Route("/map-product-in-campaign/{campaign_id}/{product_id}", name="office_brain_producttagbundle_privatecampaignadmin_mappproductincampaign",
     * defaults={"campaign_type"="private"})
     *
     * @Template()
     */
    public function mapPrivateProductInCampaignAction()
    {
        $this->initAction();
        $data = $this->productCampaignManager->addToCampaign($this->solrObj);

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

        return $this->redirect($this->generateUrl('office_brain_producttagbundle_privatecampaignadmin_productmapping', array('id' => $data['campaign_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_privatecampaignadmin_deleteprivateproduct",
     * defaults={"campaign_type"="private"})
     */
    public function deletePrivateProductAction()
    {
        $this->initAction();
        
        $id = $this->request->get('id');
        $response = $this->productCampaignManager->setDeleteProduct($id);
        
        if ($response > 0) {
            $this->responseArray['status'] = 'success';
            $this->responseArray['success_message'] = $this->translator->trans('campaign.action.campaign_delete_success');
            
            RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);

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

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

        if ($this->request->isXmlHttpRequest()) {
            return new JsonResponse(array('success' => 'success', 'page_url' => $this->generateUrl('office_brain_producttagbundle_privatecampaignadmin_list', array())));
        } else {
            return $this->redirect($this->generateUrl('office_brain_producttagbundle_privatecampaignadmin_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_privatecampaignadmin_mappedproductlist",
     * requirements={"records_per_page"="2|4|8|16|996","page"="\d+"},
     * defaults={"campaign_type"="private","records_per_page"=8,"page"=1,"type"="sku"})
     *
     * @Template("OfficeBrainProductTagBundle:Admin:/PrivateCampaign/privateCampaignMappedList.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);
        $data['campaign_id'] = $id;
        $data['filter_query_sku_or_keyword'] = $filterQuerySkuOrKeyword;
       // 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']);
             //unset($data['data']);
         }

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

            return new JsonResponse($varJason);
        } else {
            return $this->render('OfficeBrainProductTagBundle:Admin:/PrivateCampaign/privateCampaignMappedList.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 = $campaignMappedList = array();
         
        $data = $this->productCampaignManager->setPaggingParameters($this->countryMaster);
        
        list($dataList, $campaignName) = $this->productCampaignManager->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();
			$campaignMappedList[$product->getProductId()] = $product->getId();
		}
		//echo "<pre>"; print_r($mappedProductSku);exit;
		
		if (count($mappedProductSku) > 0) {
			$productList = $this->getProductDataByProductSku($mappedProductSku,$filterParameters);
		}
		//echo "<pre>"; print_r($productList);exit;
		foreach($productList["data"]as $key => $product) {
			
			if (isset($campaignMappedList[$product['product_id']])){
				$productList["data"][$key] = $product;
				$productList["data"][$key]['mapped_id'] = $campaignMappedList[$product['product_id']];
			}
			else {
				unset($productList["data"][$key]);
			}
		}
		//print_r($productListNew["data"]);exit;
		$data['data'] = $productList["data"];
		$data['count'] = $productList["count"];
        
        $data['page_paramater']['campaign_id'] = $id;
        $data['campaign_name'] = $campaignName;

        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->request->query->set('display_campaign_product', '1');
    	
    	$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']);
    	
    	unset($searchResult);
    	
    	return $data;
    }
}
