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

/**
 * @author OfficeBrain 4505 <info@officebrain.com>
 *
 * Description : Public Tag Controller
 *
 * @Route("/admin/{_locale}/public-tag")
 */
class PublicTagAdminController extends Controller
{
    public function __construct()
    {
        $this->viewTwigData = null;
        $this->request = null;
        $this->productTagManager = null;
        $this->countryLanguage = null;
        $this->translator = null;
        $this->countryMaster = null;
        $this->searchHelper = null;
        $this->searchManager = null;
        $this->paginationManager = null;
        $this->arrayToPaginationManager = null;
        $this->projectSetting = null;
    }

    public function __destruct()
    {
        unset($this->viewTwigData);
        unset($this->request);
        unset($this->productTagManager);
        unset($this->countryLanguage);
        unset($this->translator);
        unset($this->countryMaster);
        unset($this->searchHelper);
        unset($this->searchManager);
        unset($this->paginationManager);
        unset($this->arrayToPaginationManager);
        unset($this->projectSetting);
    }

    public function initAction()
    {
        $this->request = $this->getRequest();
        $this->projectSetting = $this->request->get('project_setting');
        $this->productTagManager = $this->container->get('office_brain_product_tag_manager');
        $this->translator = $this->get('translator');
        $this->countryLanguage = $this->container->getParameter('language');
        $this->country = $this->container->getParameter('country');
        $this->productImagesUrl = $this->container->getParameter('product_image.base_url');
        $this->countryMaster = $this->productTagManager->showCountryLanguage($this->container->getParameter('country'), $this->container->getParameter('language'));
        //$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 : Listing of Product Tag.
     *
     * @param 1 : null
     *
     * @return type Array
     *
     * @throws Exception: Null
     *
     * @Route("/list/{page}", name="office_brain_producttagbundle_publictagadmin_list",
     * requirements={"records_per_page"="2|4|8|16|996","page"="\d+"},
     * defaults={"tag_type"="public","records_per_page"=8,"page"=1,"country"=""})
     *
     * @Method("GET")
     *
     * @Template("OfficeBrainProductTagBundle:Admin:/PublicTag/listPublicTag.html.twig")
     */
    public function listAction()
    {
        $this->initAction();

        $pagingSettings = $this->productTagManager->pageParameters($this->countryMaster);
        $productTagList = $this->productTagManager->getPublicTagList($pagingSettings);
        $data = $this->setPaggingData($productTagList, $pagingSettings);

        return $data;
    }

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

        $pagingSettings = $this->productTagManager->pageParameters($this->countryMaster);
        $productTagList = $this->productTagManager->getPublicTagList($pagingSettings);
        
        $data = $this->setPaggingData($productTagList, $pagingSettings);

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

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

    /**
     * @author Employee Id: 4505
     * Description : Twig response
     *
     * @param 1 : $form
     * @param 2 : $featuredIcon
     *
     * @return type Array
     *
     * @throws Exception: Null
     */
    public function setTwigResponse($form, $featuredIcon = '')
    {
        $this->initAction();

        $this->viewTwigData['form'] = $form->createView();
        $this->viewTwigData['featuredIconUrl'] = $this->featuredIconUrl;
        $this->viewTwigData['tmpImgIcon'] = $this->webImagesUrl.'no_image.gif';
        $this->viewTwigData['featuredIconName'] = $featuredIcon;
        $this->viewTwigData['current_languages'] = $this->countryLanguage;
    }

    /**
     * @author Employee Id: 4505
     * Description : To arrange Pagging Data
     *
     * @param 1 : productTagList
     * @param 2 : pagingSettings
     *
     * @return type Array
     *
     * @throws Exception: Null
     */
    public function setPaggingData($productTagList, $pagingSettings)
    {
        $data = array();
        $count = 0;
        
        if(!empty($productTagList)){
            $data['pagination'] = array();
            $data['pagination']['items'] = array();
            $count = $productTagList['count'];
            $publicTagList = $productTagList['data'];
        }
        
        if ($count > 0) {
            $paginator = $this->get('knp_paginator');
            $data['pagination'] = $paginator->paginate($publicTagList, $pagingSettings['page'], $pagingSettings['records_per_page'], array(), $count);
            unset($publicTagList);
        }
        
        $country = key($this->country);
        $data['languages'] = $this->countryLanguage;
        $data['country_code'] = $this->country[$country]['short_name'];
        $data['page_paramater'] = $pagingSettings;
        $data['records_per_page'] = $pagingSettings['records_per_page'];
        $data['page'] = $pagingSettings['page'];
        return $data;
    }

    /**
     * @author Employee Id: 4505
     * Description : Public tag product mapping action
     *
     * @param 1 : $id
     *
     * @return type Array
     *
     * @throws Exception: Null
     *
     * @Route("/product-mapping/{id}", name="office_brain_producttagbundle_publictagadmin_productmapping",
     * defaults={"tag_type"="public"})
     *
     * @Template("OfficeBrainProductTagBundle:Admin:/PublicTag/publicTagProductMapping.html.twig")
     */
    public function publicProductMappingAction($id)
    {
        $this->initAction();

        $searchParameters = $this->productTagManager->pageParameters($this->countryMaster);
        $searchParameters['tag_id'] = $id;
        $searchParameters['tag_name'] =  $this->productTagManager->getPublicTagDetailById($id,$searchParameters['language_id'])['data'][0]['tagName'] ;
        $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 : Public tag product mapping action
     *
     * @param 1 : null
     *
     * @return type Array
     *
     * @throws Exception: Null
     *
     * @Route("/public-tag/map-product-in-tag/{tag_id}/{product_id}", name="office_brain_producttagbundle_publictagadmin_mappproductintag",
     * defaults={"tag_type"="public"})
     *
     * @Template()
     */
    public function mapPublicProductInTagAction()
    {
        $this->initAction();

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

        return $this->redirect($this->generateUrl('office_brain_producttagbundle_publictagadmin_productmapping', array('id' => $data['tag_id'], 'response_data' => $data)));
    }
    /**
     * @author Employee Id: 4505
     * Description : Delete public product action
     *
     * @param 1 : $id
     *
     * @return type Array
     *
     * @throws Exception: Null
     *
     * @Route("/delete-product/", name="office_brain_producttagbundle_publictagadmin_deletepublicproduct",
     * defaults={"tag_type"="public"})
     */
    public function deletePublicProductAction()
    {
        $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');
        } else {
            $this->responseArray['status'] = 'error';
            $this->responseArray['success_message'] = $this->translator->trans('tag.action.tag_delete_error');
        }
        
        return new JsonResponse($this->responseArray);

        /* if ($response['count'] > 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 : Public Mapped product list
     *
     * @param 1 : $id
     *
     * @return type Array
     *
     * @throws Exception: Null
     *
     * @Route("/mapped-product-list/{id}/{page}", name="office_brain_producttagbundle_publictagadmin_mappedproductlist",
     * requirements={"records_per_page"="2|4|8|16|996","page"="\d+"},
     * defaults={"tag_type"="public","records_per_page"=8,"page"=1,"type"="sku"})
     *
     * @Template("OfficeBrainProductTagBundle:Admin:/PublicTag/publicTagMappedList.html.twig")
     */
    public function publicMappedProductListAction($id)
    {
    $this->initAction();
        
		$filterParameters = array();
        $filterQuerySkuOrKeyword = $this->request->query->get('filter_query_sku_or_keyword','');
        if($filterQuerySkuOrKeyword != "")
        {
        	$filterParameters["productSkuOrKeyword"] = $filterQuerySkuOrKeyword;
        }

        $data = $this->generatePublicMappedArray($id,$filterParameters);
        $data['tag_name'] = $this->productTagManager->getPublicTagDetailById($id,$data['page_paramater'] ['language_id'])['data'][0]['tagName'] ;

//         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:/PublicTag/publicTagMappedList.html.twig', $data);

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

    /**
     * @author Employee Id: 4505
     * Description : Bind form data add.
     *
     * @param 1 : $searchParameters
     *
     * @return type Array
     *
     * @throws Exception: Null
     */
    public function generatePublicMappedArray($id,$filterParameters = "")
    {
        $productList = array();
        $data = $this->productTagManager->setPaggingParameters($this->countryMaster);
        $dataList = $this->productTagManager->getMappedList($id);
		
        foreach ($dataList['data'] as $values) {
            $searchParameters = $data['page_paramater'];

            if (trim($values['product_sku']) != '') {
                $searchParameters['sku'] = $values['product_sku'];
                $result = $this->searchSkuAndName($searchParameters,$filterParameters);
                if(isset($result) && (!(empty($result))) && $result != '')
                {
                	$result[0]['mapped_id'] = $values['id'];
                	$productList[] = $result[0];
                }                
            }

            unset($searchParameters);
        }

        $data['data'] = $productList;
        $data['count'] = count($productList);
        $data['page_paramater']['tag_id'] = $id;

        return $data;
    }

    /**
     * @author Employee Id: 5460
     * Description : Search Keyword.
     *
     * @param 1 : $searchParameters
     *
     * @return type Array
     *
     * @throws Exception: Null
     */
    public function searchSkuAndName($searchParameters,$filterParameters = '')
    {
    	$data = array();
    	$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;
    }
}
