<?php

namespace OfficeBrain\Bundle\SearchBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Translation\Translator;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Doctrine\ORM\Query\ResultSetMapping;
use OfficeBrain\Bundle\SearchBundle\Form\Type\ProductSearchType;
use OfficeBrain\Bundle\SearchBundle\Form\Data\ProductSearchData;
use OfficeBrain\Bundle\CategoryBundle\Entity\CultureCategory;
use OfficeBrain\Bundle\ProductBundle\Entity\CultureAttributeMaster;
use OfficeBrain\Bundle\ProductBundle\Entity\AttributeValues;
use OfficeBrain\Bundle\SearchBundle\Helper\SearchHelper;
use OfficeBrain\Bundle\SolrBundle\Helper\StandardHelper;

   /**
    * Default Search Controller
    *
    * @author Employee Id: 4861
    *
    * Desciption: This is a search controler returns search results
    *
    * @param NULL
    *
    * @return Html Response
    *
    * @throws NULL
    *
    * @Route("/{_locale}")
    */
class SearchController extends Controller
{
    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: To set member variables default value
     *
     * @param NULL
     *
     * @return null
     *
     * @throws NULL
     **/

    public function __construct()
    {
        $this->request = false;
        $this->entityManager = false;
        $this->form = null;
        $this->responseArray = array();
        $this->translator = null;
        $this->sessionManager = null;
        $this->dynamicFilterArray = array();
    }

    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: To unset member variables
     *
     * @param NULL
     *
     * @return null
     *
     * @throws NULL
     */
    public function __destruct()
    {
        unset($this->request);
        unset($this->entityManager);
        unset($this->translator);
        unset($this->sessionManager);
        unset($this->dynamicFilterArray);
    }

    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: Create various objects required action in this class
     *
     * @param NULL
     *
     * @return NULL
     *
     * @throws NULL
     */
    public function initAction()
    {
        $this->request = $this->getRequest();
        $this->entityManager = $this->getDoctrine()->getManager();
        $this->searchManager = $this->get('office_brain_search_manager');
        $this->languageId = $this->searchManager->getLanguageId();
        $this->productSearchForm = new ProductSearchType();
        $this->projectSetting = $this->request->get('project_setting');
        $this->projectId = $this->projectSetting['project_id'];
        $this->instanceId = $this->projectSetting['instance_id'];
        $this->cultureId = $this->projectSetting['culture_id'];
        $this->translator = $this->get('translator');
        $this->sessionManager = $this->get('office_brain_session_manager');
        $this->categoryApiManager = $this->get("officebrain_category_api_manager");
        $this->sessionRecentSearchKey = 'recent-search-'.$this->instanceId.'-'.$this->cultureId;
        $this->freeFreightAllowCategoryList = $this->getParameter('free_freight_allow_category_list');
    }
    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: Perform search based on search query in selected culture
     *
     * @param string search_query
     *
     * @return Html/json Response
     *
     * @throws if result found search result page else no record found error
     *
     * @Route("/search", name="office_brain_search_bundle_search", options={"expose"=true})
     *
     * @Method({"GET","POST"})
     *
     * @Template("OfficeBrainSearchBundle:Search:search.html.twig")
     *
     */
    public function searchAction()
    {
    	$this->initAction();
        $searchQuery = $this->searchManager->getSearchArray();
        $renderFromModel =  $searchQuery['render_model'];
        $this->prepareSearchForm($searchQuery['product_search']);
        $this->responseArray['search_result_array'] = array();
        /* 6799: Added Code For Token */
        // $submittedToken = $this->request->get('token');
        // if ($this->form->isValid() && $this->isCsrfTokenValid('search-products', $submittedToken)) {
        	$data = $this->request->request->all();
        	$data = json_encode($data,true);
        	$this->sessionManager->set('advance_search_form_data',$data);
      		$this->responseArray = $this->searchManager->searchResult($this->form->getData());
        	if (!$this->request->get('page', null)) {
        		$this->searchManager->setContinueShoppingUrl();
        		$this->responseArray['search_attribute_filter_array'] = $this->searchManager->searchFilter($this->form->getData());
        	}else{
        	$this->responseArray['search_attribute_filter_array'] = $this->searchManager->searchFilter($this->form->getData());
        	}
        // }
//echo "<pre>";print_r($this->responseArray['search_attribute_filter_array']);exit;

        $this->responseArray['attr_value_id'] =  $this->searchManager->getFilterAttributeValueId($this->request->get('color_filter_id', ''));
        $this->responseArray['render_model'] = $renderFromModel;

        if ($this->request->isXmlHttpRequest()) {
        	//echo "<pre>";print_r($this->responseArray);
            if (is_array($this->responseArray['search_result_array']) && array_key_exists('data', $this->responseArray['search_result_array']) && ! count($this->responseArray['search_result_array']['data'])) {
                return new JsonResponse(array( 'status'=>'error','error_code' => 'END_OF_PAGINATION','error_message' => 'error_message' ));
            }
            return $this->responseArray;
        }

        $this->responseArray['search_query'] = $searchQuery['search']['query'];
        $this->responseArray['main_filter'] = $searchQuery['search']['main_filter'];
        $this->responseArray['form'] = $this->form->createView();
        $this->responseArray['save_search'] = $this->searchManager->getSaveSearch();
        $recentSearch = $this->request->query->get('is_filter', 'check');
        if ($recentSearch == 'check') {
            $this->searchManager->setRecentSearch();
        }
		$isBrandHead = $this->request->query->get('brand_filter',NULL);
		if($isBrandHead!=NULL){
			if (is_array($this->responseArray['search_result_array']) && array_key_exists('data', $this->responseArray['search_result_array'])) {
				$this->responseArray['brand_title']  = $this->responseArray['search_result_array']['data'][0]['line_name'];
			}
		}
        return $this->responseArray;
    }

    /**
     *
     * @author Employee Id: 4532
     *
     * Desciption: Perform search based on search query in selected culture give only search product array
     *
     * @param string search_query
     *
     * @return Html/json Response
     *
     * @throws if result found search result page else no record found error
     *
     * @Route("/search-only-product", name="office_brain_search_bundle_search_only_product", options={"expose"=true})
     *
     * @Method({"GET","POST"})
     *
     * @Template("OfficeBrainSearchBundle:Search:searchOnlyProduct.html.twig")
     *
     */
    public function searchOnlyProductAction()
    {
    	$this->initAction();
    	$renderFromModel =  $this->request->get('render_model');	
    	$searchQuery = $this->searchManager->getSearchArray();
    	$this->prepareSearchForm($searchQuery['product_search']);
    	$this->responseArray['search_result_array'] = array();
    	if ($this->form->isValid()) {
    		$this->responseArray = $this->searchManager->searchResult($this->form->getData());
    	}
    	if ($this->request->isXmlHttpRequest()) {
    		if (is_array($this->responseArray['search_result_array']) && array_key_exists('data', $this->responseArray['search_result_array']) && ! count($this->responseArray['search_result_array'])) {
    			return new JsonResponse(array( 'error' => 'END_OF_PAGINATION' ));
    		}

    		if(isset($renderFromModel) and $renderFromModel == 2){
    		    $this->responseArray['page_paramater'] =  json_decode($this->request->get('page_paramater'));
    		    return $this->render(
    		        "OfficeBrainProductTagBundle:Admin:tabProductListContents.html.twig",
    		        $this->responseArray
    		    );
    		}
    		return $this->responseArray;
    	}
    	return $this->responseArray;
    }


    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: Perform search if no result found on search
     *
     * @param string search_query
     *
     * @return json Response
     *
     * @throws if result found search result page else no record found error
     *
     * @Route("/search-no-result", name="office_brain_search_bundle_search_no_result", options={"expose"=true})
     *
     * @Method({"GET","POST"})
     *
     * @Template("OfficeBrainSearchBundle:Search:noResultFound.html.twig")
     *
     */
    public function searchNoResultAction()
    {
        $this->initAction();

        $searchQuery = $this->searchManager->getSearchArray();
        $this->prepareSearchForm($searchQuery['product_search']);
        if ($this->form->isValid()) {
            $this->responseArray = $this->searchManager->searchResult($this->form->getData());
        }
		if (!array_key_exists('data', $this->responseArray['search_result_array']) || ! count($this->responseArray['search_result_array']['data'])) {
				return new JsonResponse(array( 'status' => 'END_OF_PAGINATION' ));
		}
        unset($searchQuery);

        return $this->responseArray;
    }

    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: Perform search to find attribute list for given search criteria
     *
     * @param string search_query
     *
     * @return json Response
     *
     * @throws if result found return attribute list along with product count else null
     *
     * @Route("/search-attribute-filter-list",
     * name="office_brain_search_bundle_search_attribute_filter_list", options={"expose"=true})
     *
     * @Method({"GET","POST"})
     *
     * @Template("OfficeBrainSearchBundle:Search:searchAttributeFilterList.html.twig")
     *
     */
    public function searchAttributeFilterListAction()
    {
        $this->initAction();
        list($defaultCulture,$defaultCountry) = explode("_",$this->request->get("_locale"));
        $culture = $this->request->get('language',$defaultCulture);
        $activeCulture = $culture;
        $cultureCategory =  $activeCulture . "_" . $country;
        $categoryAndSubCategoryData = $this->categoryApiManager->getList(array($cultureCategory),array(),true);
        
        $searchQuery = $this->searchManager->getSearchArray();
        $this->prepareSearchForm($searchQuery['product_search']);
        $this->responseArray['search_attribute_filter_array'] = array();
        if ($this->form->isValid()) {
            $this->responseArray['search_attribute_filter_array'] = $this->searchManager->searchFilter($this->form->getData());
        }
        $categoryarray = array();
        $categoryAndSubCategoryList = array();
        
        foreach($this->responseArray['search_result_array']['data'] as $searchKey => $searchValue)
        {
        	$productId = $searchValue['product_id'];
        	foreach($searchValue['category_name_id_ss'] as $value){
        		$catData =  explode("|", $value);
        		$categoryarray[$catData[0]] = $catData[0];
        	}
        	//$categoryAndSubCategoryList[$productId] = $this->categoryApiManager->getParentChildCategoryList($categoryAndSubCategoryData,$categoryarray,$activeCulture);
        	//$existValue[$productId] = 0;
        	/*foreach($this->freeFreightAllowCategoryList as $key => $value){
        		if(array_key_exists($value,$categoryAndSubCategoryList[$productId]['parent_id'])){
        			$existValue[$productId] = 1;
        			break;
        		}else{
        			if(count($categoryAndSubCategoryList[$productId]['parent_id'][$value]['child'])>0){
        				if(array_key_exists($value,$categoryAndSubCategoryList[$productId][$value]['child'])){
        					$existValue[$productId] = 1;
        					break;
        				}
        			}
        		}
        	}*/
        
        	//$this->responseArray['dispalyText'][$productId] = $existValue[$productId];
        }
        unset($searchQuery);
        return $this->responseArray;
    }

    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: Advance search options
     *
     * @param string search_query
     *
     * @return json Response
     *
     * @throws if result found return attribute list along with product count else null
     *
     * @Route("/advance-search-attribute-filter-list",
     * name="office_brain_search_bundle_advance_search_attribute_filter_list", options={"expose"=true})
     *
     * @Method({"GET","POST"})
     *
     * @Template("OfficeBrainSearchBundle:Search:advanceSearchPage.html.twig")
     *
     */
    public function advanceSearchAttributeFilterListAction()
    {
    	$this->initAction();

    	$this->responseArray['finalArray'] = $this->searchManager->advanceSearchService();

    	$this->responseArray['render_model'] = $this->request->get('render_model','');
        $this->responseArray['page_paramater'] =  $this->request->get('page_paramater','');
        return $this->responseArray;
    }


    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: advance search model.
     *
     * @param loacle
     *
     * @return json Response advance search template
     *
     * @throws NULL
     *
     * @Route("/advance-search-page", name="officebrain_search_bundle_search_advance_page", options={"expose"=true})
     *
	 * @Method({"GET"})
     *
     * @Template("OfficeBrainSearchBundle:Search:advanceSearchPage.html.twig")
     *
     */
    public function advanceSearchAction()
    {
    	$this->initAction();

    	$this->responseArray['finalArray'] = $this->searchManager->advanceSearchService();

    	$this->responseArray['render_model'] = $this->request->get('render_model','');
        $this->responseArray['page_paramater'] =  $this->request->get('page_paramater','');
        return $this->responseArray;
    }

    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: Save search from advance search and normal search.
     *
     * @param NULL
     *
     * @return json Response  id,name
     *
     * @throws NULL
     *
     * @Route("/save-search",
     * 	name="officebrain_search_bundle_search_save_search", options={"expose"=true}
     * )
     *
	 * @Method({"GET"})
	 *
     * @Template()
     *
     */
    public function saveSearchAction()
    {
        $this->initAction();

        $saveSearchId = $this->searchManager->setSaveSearch($this->request->query->all());
        $this->responseArray['save_search_tab'] = 'tab2';
        $this->saveSearchRecentSearch('saved_successfully');

        return new JsonResponse($this->responseArray);
    }

    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: Display save search in tab.
     *
     * @param NULL
     *
     * @return json Response
     *
     * @throws NULL
     *
     * @Route("/save-search-tab",
     * 	name="officebrain_search_bundle_search_save_search_tab", options={"expose"=true}
     * )
     *
 	 * @Method({"GET", "POST"})
     *
     * @Template()
     *
     */
    public function saveSearchTabAction()
    {
        $this->initAction();

        $this->saveSearchRecentSearch('saved_succesfully');
        return new JsonResponse($this->responseArray);
    }

    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: delete Save search.
     *
     * @param local,id of save search
     *
     * @return json Response
     *
     * @throws NULL
     *
     * @Route("/delete-save-search/{saveId}",
     * 	name="officebrain_search_bundle_search_delete_save_search", options={"expose"=true}
     * )
     *
     * @Method({"GET", "POST"})
     *
     * @Template()
     *
     */
    public function deleteSaveSearchAction($saveId)
    {
        $this->initAction();

        $this->searchManager->deleteSaveSearch($saveId);
        $this->saveSearchRecentSearch('deleted_successfully');
        return new JsonResponse($this->responseArray);
    }


    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: Save saerch list in my account.
     *
     * @param loacle
     *
     * @return Html Response
     *
     * @throws NULL
     *
     * @Route("/my-account/save-search",
     * 	name="officebrain_search_bundle_search_my_account_save_search", options={"expose"=true}
     * )
     *
     * @Method({"GET"})
     *
     * @Template("OfficeBrainSearchBundle:MyAccount:MyAccountSaveSearch.html.twig")
     *
     */
    public function myAccountSaveSearchAction()
    {
        $this->initAction();

        $this->responseArray['save_search'] = $this->searchManager->getAllSaveSearch();
        return $this->responseArray;
    }

    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: check if name exist.
     *
     * @param loacle, save_search_name
     *
     * @return json Response
     *
     * @throws NULL
     *
     * @Route("/save-search-check/{name}",
     * 	name="officebrain_search_bundle_search_save_search_check", options={"expose"=true}
     * )
     *
     * @Method({"GET", "POST"})
     *
     * @Template()
     *
     */
    public function saveSearchCheckAction($name)
    {
    	$this->initAction();

    	$this->responseArray = $this->searchManager->checkSaveSearch($name);

    	return new JsonResponse($this->responseArray);
    }

    /**
     *
     * @author Employee Id: 4074
     *
     * Desciption: This function allow user go back to last search page.
     *
     * @param NULL
     *
     * @return 302 Redirection Response
     *
     * @throws NULL
     *
     * @Route("/continue-shopping-to-search",
     * 	name="office_brain_searchbundle_search_continueshopping", options={"expose"=true}
     * )
     *
     * @Method({"GET"})
     *
     */
    public function continueShoppingAction()
    {
    	$this->initAction();
    	return $this->redirect($this->searchManager->getContinueShoppingUrl($this));
    }

    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: Bind request paramater with form
     *
     * @param Array paramaters
     *
     * @return NULL
     *
     * @throws NULL
    */
    private function prepareSearchForm($searchArray)
    {
        $this->productSearchData = new ProductSearchData($this->entityManager, $this->languageId);
        $this->form = $this->createForm($this->productSearchForm, $this->productSearchData, array('csrf_protection' => false));
        $this->form->bind($searchArray);
    }

    private function saveSearchRecentSearch($message)
    {
    	$this->responseArray['save_search'] = $this->searchManager->getSaveSearch();
    	$this->responseArray['recent_search'] = $this->sessionManager->get($this->sessionRecentSearchKey);
    	$this->responseArray['data']= $this->renderView('OfficeBrainSearchBundle:Search:saveSearchRecentSearch.html.twig', array('data'=>$this->responseArray));
    	$this->responseArray['save_search_message'] = $this->translator->trans($message);
    	$this->responseArray['status']= 'success';

    	unset($this->responseArray['save_search']);
    	unset($this->responseArray['recent_search']);
    }
}
