<?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 OfficeBrain\Bundle\SearchBundle\Form\Type\ProductSearchType;
use OfficeBrain\Bundle\SearchBundle\Form\Data\ProductSearchData;

/**
 * @author OfficeBrain 4505 <info@officebrain.com>
 * Description : Product campaign mapping admin controller
 *
 * @Route("/admin/product-map")
 */
class ProductCampaignMappingAdminController 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->projectSetting = null;
    }

    public function __destruct()
    {
        //unset($this->viewTwigData);
        unset($this->productCampaignManager);
        unset($this->countryMaster);
        unset($this->translator);
        unset($this->validationParams);
        unset($this->webImagesUrl);
        unset($this->featuredIconUrl);
        unset($this->featuredIconPath);
        unset($this->projectSetting);
    }

    public function initAction()
    {
        $this->request = $this->getRequest();
        $this->projectSetting = $this->request->get('project_setting');
        $this->productCampaignManager = $this->container->get('office_brain_product_campaign_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->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->container->getParameter('web_image.base_url');
        $this->featuredIconUrl = $this->container->getParameter('private_campaign.icon_url').'featured-icon/';
        $this->featuredIconPath = $this->container->getParameter('private_campaign.icon_path').'featured-icon/';
    }

    /**
     * @author Employee Id: 4505
     * Description : Search product ajax action.
     *
     * @param 1 : $search_query
     *
     * @return type Array
     *
     * @throws Exception: Null
     *
     * @Route("/search-product/{search_query}/{type}/{culture}", name="office_brain_producttagbundle_productcampaignmappingadmin_searchproductajax",
     * requirements={"records_per_page"="2|4|8|16|996","page"="\d+"},
     * defaults={"campaign_type"="private","records_per_page"=8,"page"=1,"type"="sku", "culture"="en_us"})
     *
     * @Template()
     */
    public function searchProductAjaxAction($search_query)
    {
        $this->initAction();

        $data = $this->productCampaignManager->setPaggingParameters($this->countryMaster);
        $searchdata = $this->searchKeyword($data['page_paramater']);
        $data['count'] = count($searchdata);
        $data['data'] = $searchdata;

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

        $data['page_paramater']['campaign_id'] = $this->request->get('campaign_id');

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

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

    /**
     * @author Employee Id: 4505
     * Description : 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_productcampaignmappingadmin_mappproductincampaign",
     * defaults={"campaign_type"="private"},
     * options={"expose"=true})
     *
     * @Template()
     */
    public function mapProductInCampaignAction()
    {
        $this->initAction();

        $campaignId = $this->request->get('campaign_id');
        $campaignType = $this->request->get('campaign_type');
        $productId = $this->request->get('product_id');
        $productSku = $this->request->get('product_sku');

        if ($campaignType == 'private') {
            return $this->redirect($this->generateUrl('office_brain_producttagbundle_privatecampaignadmin_mappproductincampaign', array('campaign_id' => $campaignId, 'campaign_type' => $campaignType, 'product_id' => $productId, 'product_sku' => $productSku)));
        } else {
            return $this->redirect($this->generateUrl('office_brain_producttagbundle_publiccampaignadmin_mappproductincampaign', array('campaign_id' => $campaignId, 'campaign_type' => $campaignType, 'product_id' => $productId, 'product_sku' => $productSku)));
        }
    }

    /**
     * @author Employee Id: 4505
     * Description : Remove product from campaign action
     *
     * @param 1 : null
     *
     * @return type Array
     *
     * @throws Exception: Null
     *
     * @Route("/remove-product-from-campaign/{id}/{campaign_type}", name="office_brain_producttagbundle_productcampaignmappingadmin_removeproductfromcampaign",
     * defaults={"campaign_type"="private"})
     *
     * @Template()
     */
    public function removeProductFromCampaignAction()
    {
        $this->initAction();

        $id = $this->request->get('id');
        $campaignType = $this->request->get('campaign_type');

        if ($campaignType == 'private') {
            return $this->redirect($this->generateUrl('office_brain_producttagbundle_privatecampaignadmin_deleteprivateproduct', array('id' => $id)));
        } else {
            return $this->redirect($this->generateUrl('office_brain_producttagbundle_publiccampaignadmin_deletepublicproduct', array('id' => $id)));
        }
    }

    /**
     * @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);
            $data = $productDetailArray ['search_result_array']['data'];
        }

        return $data;
    }
}
