<?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;

/**
 * @author OfficeBrain 4045 <info@officebrain.com>
 * Description : Private Campaign Controller
 *
 * @Route("/{_locale}/product-campaign")
 */
class ProductCampaignController extends Controller
{
    public function __construct()
    {
    	$this->form = null;
        $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;
    }

    public function __destruct()
    {
    	unset($this->form);
        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);
    }

    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->solrObj = $this->get('solarium.client.product_en'); //EMP4464: Original Line
         
        //EMP4464: Changed above line with below code: Start
        $this->locale = $this->projectSetting['locale_language'];
        $culture = explode('_', $this->locale);
        //$solrCore = 'solarium.client.product_'.$culture[0];
        $solrCore = 'solarium.client.product_'.$this->locale;
        $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');
        $this->entityManager = $this->getDoctrine()->getManager();
        $this->languageId = $this->searchManager->getLanguageId();
        $this->productSearchForm = new ProductSearchType();
    }

    /**
     * @author Employee Id: 4045
     * Description : Listing of Product Campaign.
     * @param : null
     *
     * @Route("/private-campaigns-list", name="office_brain_pagebundle_privatecampaign_list",
     * requirements={"records_per_page"="2|4|8|16|996"},
     * defaults={"campaign_type"="private","records_per_page"=8,"page"=1,"language"="en"})
     *
     * @Template("OfficeBrainProductTagBundle:Front:/listPrivateCampaign.html.twig")
     */
    public function listPrivateCampaignsAction()
    {
    	$this->initAction();
    
    	$data = $this->productCampaignManager->setPaggingParameters($this->countryMaster);
    	$data['page_paramater']['status']=1;
    	$data['page_paramater']['current_date']=true;
    	$data['page_paramater']['event_category_id']=$this->request->get("cat",null);
    	
    	$productCampaignMasterList = $this->productCampaignManager->getList($data['page_paramater']);
    
    	$data['campaigns']= $productCampaignMasterList;
    	$data['show_title']=$this->request->get("show_title",1);
    	
    	//$data['icon_url'] = $this->getParameter('private_campaign.icon_url');
    	$data['icon_url'] = $this->featuredIconUrl;
    	
    	return $this->render('OfficeBrainProductTagBundle:Front:/listPrivateCampaign.html.twig', $data);
    }
        
    /**
     * @author Employee Id: 4045
     * Description : List of mapped products
     *
     * @param 1 : $id
     *
     * @return type Array
     *
     * @throws Exception: Null
     *
     * @Route("/mapped-product-list/{id}/{page}", name="office_brain_producttagbundle_privatecampaign_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:Front:/privateCampaignMappedList.html.twig")
     */
    public function privateMappedProductListAction($id)
    {
        $this->initAction();

        $data = $this->generatePrivateMappedArray($id);
        $this->arrayToPaginationManager->setPaginationArray($data);
        $this->arrayToPaginationManager->doConvert();
        $data['pagination'] = $this->arrayToPaginationManager->getPagination();
        
        $data['search_attribute_filter_array'] = array();

        return $data;
    }
    /**
     * @author Employee Id: 4505
     * Description : Generate Private Mapped Array
     *
     * @param 1 : $id
     *
     * @return type Array
     *
     * @throws Exception: Null
     */
    public function generatePrivateMappedArray($id)
    {
    	$productList = 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['search_query'] = $values->getProductSku();
    			$result = $this->searchKeyword($searchParameters);
    			if(!empty($result))
    			{
    			  $result[0]['product_box_bootstrap_class']='item';
                        $result[0]['render_model']=0;
      			$result[0]['mapped_id'] = $values->getId();
      			$productList[] = $result[0];
          }
    		}
    		unset($searchParameters);
    	}
    
    	$data['data'] = $productList;
    	$data['totalCount'] = count($productList);
    	$data['count'] = count($productList);
    	$data['campaign_name'] = $campaignName;
    	$data['page_paramater']['campaign_id'] = $id;
      //print_r($data['data']);exit;
    	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;
    }
    
    
    /**
     * @author Employee Id: 4532
     *
     * Product campaign search page
     *
     * @param string campaign slug
     *
     * @return 
     *
     * @Route("/{slug}", name="office_brain_producttagbundle_privatecampaign_searchcampaignproduct", options={"expose"=true})
     
     * @Method({"GET"})
     *
     * @Template("OfficeBrainProductTagBundle:Front:/searchCampaignProduct.html.twig")
     */
    public function searchCampaignProductAction()
    {
    	$this->initAction();
    	$slug = $this->request->get('slug');
    	
    	$campaignData = $this->productCampaignManager->getCampaignIdFromSlug($slug);
    	$campaignId = $campaignData['id'];
    	$campaignIdJson = json_encode(array($campaignId));
    	
    	$searchQuery = $this->searchManager->getSearchArray();
    	$this->prepareSearchForm($searchQuery['product_search'],$campaignIdJson);
    	
    	if ($this->form->isValid()) {
    		$this->responseArray = $this->searchManager->searchResult($this->form->getData());
    		if (!$this->request->get('page', null)) {
    			$this->responseArray['search_attribute_filter_array'] = $this->searchManager->searchFilter($this->form->getData());
    		}
    	}
    	
    	$host = $this->request->getHost();
    	$baseUrl = $this->request->getBaseUrl();
    	$baseUrl = str_replace("/app_dev.php","",$baseUrl);
    	//echo $baseUrl; die;
    	$campaignBannerPath = 'http://'.$host.$baseUrl.'/images/uploads/product-campaign/featured-icon/';
    	
    	$this->responseArray['campaign_name'] = $campaignData['campaignName'];
    	$this->responseArray['featured_icon'] = $campaignBannerPath.$campaignData['featuredIcon'];
    	$this->responseArray['campaign_url'] = $campaignData['campaignUrl'];
    	$this->responseArray['banner_url'] = $campaignData['bannerUrl'];
    	$this->responseArray['search_query'] = $searchQuery['search']['query'];
    	$this->responseArray['main_filter'] = $searchQuery['search']['main_filter'];
    	$this->responseArray['form'] = $this->form->createView();
    	$this->responseArray['Recent_search'] = $this->request->getSession()->get('recent_search');
    	$this->responseArray['save_search'] = $this->searchManager->getSaveSearch();
    	$this->responseArray['search_campaign_id'] = $campaignIdJson;
    	$recentSearch = $this->request->query->get('is_filter','check');
    	if(!empty($campaignData)){
    		$this->responseArray['total_count_val'] = count($campaignData);
    	}else{
    		$this->responseArray['total_count_val'] = 0;
    	}
    	if($recentSearch == 'check'){
    		$this->searchManager->setRecentSearch();
    	}
    
    	return $this->responseArray;
    	
    }
    
    private function prepareSearchForm($searchArray,$categoryListJson) {
    	$searchArray['campaignId'] = $categoryListJson;
    	$this->productSearchData = new ProductSearchData($this->entityManager, $this->languageId);
    	$this->form = $this->createForm($this->productSearchForm, $this->productSearchData, array('csrf_protection' => false));
    	$this->form->bind($searchArray);
    }

}
