<?php

namespace OfficeBrain\Bundle\SearchBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use OfficeBrain\Bundle\SearchBundle\Form\Type\ProductSearchType;
use OfficeBrain\Bundle\SearchBundle\Form\Data\ProductSearchData;
use Symfony\Component\HttpFoundation\Session\Session;
use OfficeBrain\Bundle\CoreBundle\Cache\RedisCacheService;

class BrowseCategoryController extends Controller
{
	/**
	 *
	 * @author Employee Id: 4532
	 * 
	 * To set member variables default value
	 * 
	 * @return NULL
	 */
	public function __construct()
	{
		$this->form = null;
		$this->categoryBreadCrumbsList = array();
		$this->translator = null;
		$this->request = null;
		$this->statsh_cache_wrapper = RedisCacheService::create();
	}
	
	/**
	 *
	 * @author Employee Id: 4861
	 *
	 * Desciption: To unset member variables
	 *
	 * @param NULL
	 *
	 * @return null
	 *
	 * @throws NULL
	 */
	public function __destruct()
	{
		unset($this->form);
		unset($this->categoryBreadCrumbsList);
		unset($this->translator);
		unset($this->request);
		unset($this->statsh_cache_wrapper);
	}
	
	
	/**
	 *
	 * @author Employee Id: 4532
	 *
	 * Create various objects required action in this class
	 *
	 * @return 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->translator = $this->get('translator');
		$this->productDetailManager = $this->get('office_brain_product_detail_manager');
		$this->freeFreightAllowCategoryList = $this->getParameter('free_freight_allow_category_list');
		$this->categoryApiManager = $this->get("officebrain_category_api_manager");
	}
	
    /**
     * @author Employee Id: 4532
     * 
	 * Browse by category
	 * 
	 * @param string category slug
	 * 
	 * @return if result found return parent category  else null
	 * 
	 * @Route("/{_locale}/browse-category", name="office_brain_search_bundle_browse_category", options={"expose"=true})
	 * 
	 * @Method({"GET"})
	 * 
     * @Template("OfficeBrainSearchBundle:BrowseCategory:browseCategory.html.twig")
     */
    public function browseCategoryAction()
    {
    	//$this->initAction();
    	$this->responseArray['parent_category_list'] = $this->get('office_brain_search_manager')->getCategorySubCategoryList();
    	$this->settingManager = $this->get('office_brain_setting_email_manager');
    	// see slug from db;
    	$allProductPage = $this->settingManager->getSettingPageBySlugActive('all-product-page','Active');
    	if($allProductPage!=NULL){
    		$this->responseArray['all_page_content'] = $allProductPage->getContent();
    	}
    	/*echo "<pre>";
    	print_r($this->responseArray['parent_category_list']); die; */
    	if ($this->getRequest()->isXmlHttpRequest ()) {
    		if (is_array ( $this->responseArray['parent_category_list'] ) && array_key_exists ( 'data', $this->responseArray['parent_category_list'] ) && ! count ( $this->responseArray['parent_category_list'] )) {
    			return new JsonResponse ( array('error' => 'END_OF_PAGINATION' ) );
    		}
    		return $this->responseArray;
    	}
    	return $this->responseArray;
    }
    
    
    /**
     * @author Employee Id: 4532
     * 
     * Browse by sub category
     * 
     * @param string category slug
     * 
     * @return if result found return sub category list  else null
     * 
     * @Route("/{_locale}/browse-sub-category/{category_slug}", name="office_brain_search_bundle_browse_sub_category", options={"expose"=true})
     
     * @Method({"GET"})
     * 
     * @Template("OfficeBrainSearchBundle:BrowseCategory:browseSubCategory.html.twig")
     */
    public function browseSubCategoryAction()
    {
    	$this->initAction();
    	$categoryBrand = array();
    	$searchcategoriesList = array();
    	$categoryObj = $this->container->get('office_brain_category_manager');
    	$categorySlug = $this->request->get('category_slug');
    	$this->responseArray['category_id'] = $categoryObj->getCategoryIdFromSlug($categorySlug);
    	$main_category_name = $categoryObj->getCategoryNameFromSlug($categorySlug);
    	$subCategoryList = $categoryObj->getSubCategoryList($this->responseArray['category_id']);
    	if(isset($subCategoryList['child'])){	
    		$this->responseArray['sub_category_list'] = $subCategoryList['child'];
    	}else{
    		$this->responseArray['sub_category_list'] = null;
    	}
    	if(isset($subCategoryList['name'])){
    		$this->responseArray['category_name'] = $subCategoryList['name'];
    		$main_category_name = $subCategoryList['name'];
    	}else{
    		$this->responseArray['category_name'] = '';
    	}
    	if(isset($subCategoryList['parent'])){
    		$this->responseArray['parent_category_info'] = $subCategoryList['parent'];
    	}

    	$searchQuery = $this->searchManager->getSearchArray();
    	
    	if($this->responseArray['sub_category_list']!=null){
    		$searchcategoriesList = array_keys($this->responseArray['sub_category_list']);
    	}
    	//$searchcategoriesList[] = (int)$this->responseArray['category_id'];
    	//array_push($searchcategoriesList,$this->responseArray['category_id']);
    	//print_r($searchcategoriesList); die;
       	$searchcategoriesList = json_encode($searchcategoriesList);
    	$category_count= 0;
    	$searchQuery = $this->searchManager->getSearchArray();
    	$this->prepareSearchForm($searchQuery['product_search'],$searchcategoriesList);
    	if ($this->form->isValid()) {

    		$categoriesArrayResult =  $this->searchManager->searchResult($this->form->getData());

    		$category_count = $categoriesArrayResult['search_result_array']['totalCount'];

    		$categoryBrandMapping = $this->searchManager->searchResult($this->form->getData(),true,'line_name_id_i');
    		$categoryBrand = array_column($categoryBrandMapping['search_result_array']['data'],'line_name_id');

    	}

    	$categoryBrandunique = array_unique($categoryBrand);
    	
    	// -----------------------------------------------------------------------
    	$brandsArray = array();
        $cacheSiteKey = array($locale,$this->container->getParameter('kernel.environment'));
		$this->moduleCachePrefix='__HomePageBrandList__:';
		$cacheKey = $this->moduleCachePrefix.RedisCacheService::generateKey($this->statsh_cache_wrapper,$cacheSiteKey);
		$cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
		if($cacheData){
			$brandsArray = json_decode($cacheData,true);
		}else{
			$brandsArray = $this->get("officebrain_brand_api_manager")->getList('en');
			if(!empty($cacheKey))
			{
				RedisCacheService::saveCacheData($this->statsh_cache_wrapper,$cacheKey,json_encode($brandsArray));
			}
		}
		//-------------------------------------------------------------------------------
    	//$brandsArray = $this->get("officebrain_brand_api_manager")->getList('en');
    	/*echo "<pre>";
    	print_r($brandsArray); die;*/
    	$brandsArrayKeys = array_keys($brandsArray['en']);
    	//array_push($categoryBrandunique,1733);
    	$this->responseArray['categoryBrandunique']= array_intersect($brandsArrayKeys,$categoryBrandunique);

    	$this->responseArray['category_count']= $category_count;
    	$this->responseArray['main_category_name'] = $main_category_name;
    	$this->responseArray['brandList']= $brandsArray;
    	$seoDetail = $this->entityManager->getRepository("OfficeBrainSeoBundle:SeoCategory")->getSeoCategoryBySlug($categorySlug,'browse-sub-category');
    	if($seoDetail!=NULL){	
    		$this->responseArray['seo_detail'] = $seoDetail;
    	}
    	if ($this->request->isXmlHttpRequest ()) {
    		if (is_array ( $this->responseArray['sub_category_list'] ) && array_key_exists ( 'data', $this->responseArray['sub_category_list'] ) && ! count ( $this->responseArray['sub_category_list'] )) {
    			return new JsonResponse ( array( 'error' => 'END_OF_PAGINATION' ) );
    		}
    		return $this->responseArray;
    	}
    	return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4532
     *
     * Browse by Parent category
     *
     * @param string category slug
     *
     * @return if result found return product related list of parent categories  else null
     *
     * @Route("/{_locale}/browse-category-search/{category_slug}", name="office_brain_search_bundle_browse_category_search", options={"expose"=true})
      
     * @Method({"GET"})
     *
     * @Template("OfficeBrainSearchBundle:BrowseCategory:browseCategorySearchPage.html.twig")
     */
    public function browseCategorySearchAction()
    {
    	$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);
    	$categoryObj = $this->container->get('office_brain_category_manager');
    	$categorySlug = $this->request->get('category_slug');
    	
    	$categoryid = $categoryObj->getCategoryIdFromSlug($categorySlug); 
    	$categoryBySlug = $this->getCategoryBySlug($categorySlug);
    	if($categoryid==NULL){
			$categoryid = $categoryBySlug['en']['pms_id']; 
		}
    	//$categoryid = $categoryObj->getCategoryIdFromSlug($categorySlug); 
    	
    	$subCategoryList = $categoryObj->getSubCategoryList($categoryid);
    	$this->session = $this->request->getSession();
    	 
    	if(isset($subCategoryList['child'])){
			$categoriesList = array_keys($subCategoryList['child']);
    	}
        $categoriesList[] = (int)$categoryid;
        $categoriesList = json_encode($categoriesList);
    	if($this->session->get("brandId"))
    	{
    		$this->request->query->set("main_filter",$this->session->get("brandId"));
    	}
    	//echo $this->request->get("main_filter")." - ".$this->session->get("brandId");
    	//echo "<pre>"; print_r($this->responseArray['category_name']);exit;
    	//echo "<pre>"; print_r($this->responseArray['sub_category_list']);exit;
    	$searchQuery = $this->searchManager->getSearchArray();
    //	echo "<pre>";print_r($searchQuery['product_search']);exit;
		//echo "<pre>"; print_r($categoriesList);
		//echo "<pre>"; print_r($subCategoryList);
		//die;
    	$this->prepareSearchForm($searchQuery['product_search'],$categoriesList);
    	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());
    		}
    	}
    	$this->responseArray['sub_category_list'] = $categoriesList;
    	$this->responseArray['category_id'] = $categoryid;
    	if(isset($subCategoryList['name'])){
    		$this->responseArray['category_name'] = $subCategoryList['name'];
    	}else{
    		$this->responseArray['category_name'] = '';
    	}
    	
    	if(isset($subCategoryList['parent'])){
    		$this->responseArray['parent_category_info'] = $subCategoryList['parent'];
    	}
    	
    	$categoryAndSubCategoryList = array();
    	$categoryarray = array();
    	foreach($categoriesList as $key=>$value){ echo $value;
    		$catData =  explode("|", $value);
    		$categoryarray[$catData[0]] = $catData[0];
    	}
        
        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];
        }
    	
    	$this->responseArray['breadcrumbs'] = $this->productDetailManager->productDetailBreadcrumbs($this->responseArray['category_id']);
    	$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();
    	$recentSearch = $this->request->query->get('is_filter','check');
    	if($recentSearch == 'check'){
    		$this->searchManager->setRecentSearch();
    	}
    	
    	$this->responseArray['category_breadcrumb']= array($this->translator->trans('breadcrumb_category'),(isset($this->responseArray['category_name'])?$this->responseArray['category_name']:''));
    	$this->responseArray['category_slug'] = $categorySlug;

    	$seoDetail = $this->entityManager->getRepository("OfficeBrainSeoBundle:SeoCategory")->getSeoCategoryBySlug($categorySlug,'browse-category-search');
    	if($seoDetail!=NULL){
    		
    		$this->responseArray['seo_detail'] = $seoDetail;
    	}
    	//$categoryBySlug = $this->getCategoryBySlug($categorySlug);
    	if(isset($categoryBySlug['en'])){
    		$this->responseArray['h1_title'] = $categoryBySlug['en']['name'];
    	}
    	unset($categoryObj);
    	unset($categorySlug);
    	unset($subCategoryList);
    	unset($categoriesList);
    	unset($searchQuery);
    	unset($recentSearch);
    	return $this->responseArray;
// //     	if ($this->request->isXmlHttpRequest ()) {
// //     		if (is_array ( $this->responseArray['sub_category_list'] ) && array_key_exists ( 'data', $this->responseArray['sub_category_list'] ) && ! count ( $this->responseArray['sub_category_list'] )) {
// //     			return new JsonResponse ( array( 'error' => 'END_OF_PAGINATION' ) );
// //     		}
// //     		return $this->responseArray;
// //     	}
    	
    }


    public function getCategoryBySlug($slug)
    {
        $data = array();
        $this->productApi = $this->get('office_brain_product_api');
        $this->productApi->init('get_category_by_slug');
        $this->productApi->setCallParameters(array('category_slug'=>$slug,'active_culture'=>'en','cultures'=>array('en','fr')));
        $this->productApi->setCulture($culture);
        $this->productApi->doProcess();
        if ($this->productApi->isSuccess()) {
            $data = $this->productApi->getResultArray();
        }
       
        return $data;
    }

    public function create_slug($string)
    {
   		$slug=str_replace('-',' ',$string);
   		return $slug;
	}
    
    /**
     * @author Employee Id: 4532
     * 
     * Product listing accordingly parent category
     * 
     * @param string category id
     * 
     * @return if result found return category products else null
     * 
     * @Route("/{_locale}/category-product-list/{category_slug}", name="office_brain_search_bundle_category_product_list", options={"expose"=true})
     *
     * @Method({"GET"})
     * 
     * @Template("OfficeBrainSearchBundle:BrowseCategory:browseCategoryPage.html.twig")
     */
    public function categoryProductListAction()
    {
    	$this->initAction();
    	
    	$searchQuery = $this->searchManager->getSearchArray();
    	$categoryFilter = $this->request->get('category_filter','');
        $categoryslug = $this->request->get('category_slug');
        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);
    	$categoryObj = $this->container->get('office_brain_category_manager');
    	$categoryId = $categoryObj->getCategoryIdFromSlug($categoryslug);
    	$subCategoryList = $categoryObj->getSubCategoryList($categoryId);

    	if($categoryFilter == ''){
	    	$caregoryArray[] = $categoryId;
	    	$categoryListJson = json_encode($caregoryArray);
    	}else{
    		$categoryListJson = $categoryFilter;
    	}
    	$this->prepareSearchForm($searchQuery['product_search'],$categoryListJson);
    	$this->responseArray = array();
    	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());
    		}
    	}
    	$this->responseArray['breadcrumbs'] = $this->productDetailManager->productDetailBreadcrumbs($categoryId);
    	$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();
    	$recentSearch = $this->request->query->get('is_filter','check');
    	if($recentSearch == 'check'){
    		$this->searchManager->setRecentSearch();
    	}
    	$this->responseArray['category_breadcrumb']= array($this->translator->trans('breadcrumb_category'),(isset($subCategoryList['name'])?$subCategoryList['name']:''));
    	$this->responseArray['category_slug'] = $categoryslug;
    	$this->responseArray['category_id'] = $categoryId;
    	return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4532
     * 
     * Perform search to find attribute list for given search criteria
     * 
     * @param string search_query
     * 
     * @return if result found return attribute list along with product count else null
     * 
     * @Route("/{_locale}/category-attribute-filter-list",
     * 
     * name="office_brain_search_bundle_category_attribute_filter_list", options={"expose"=true})
     * 
     * @Method({"GET","POST"})
     * 
     * @Template("OfficeBrainSearchBundle:Search:searchAttributeFilterList.html.twig")
     */
    public function categoryAttributeFilterListAction()
    {	
    	$this->initAction();
    	
    	$searchQuery = $this->searchManager->getSearchArray();
    	
    	$categoryFilter = $this->request->get('category_filter','');
    	$categoryId = $this->request->get('parent_category_id','');
    	
    	if($categoryFilter == ''){
    		$caregoryArray[] = $categoryId;
    		$categoryListJson = json_encode($caregoryArray);
    	}else{
    		$categoryListJson = $categoryFilter;
    	}
    	$this->prepareSearchForm($searchQuery['product_search'],$categoryListJson);
    	$this->responseArray['search_attribute_filter_array'] = array();
    	if ($this->form->isValid()) {
    		$this->responseArray['search_attribute_filter_array'] = $this->searchManager->searchFilter($this->form->getData());
    	}
    	$this->responseArray['category_id'] = $categoryId;
    	return $this->responseArray;
    }
    
    private function prepareSearchForm($searchArray,$categoryListJson) {
    	$searchArray['categoryId'] = $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);
    }
    
    /**
     * @author Employee Id: 5429
     *
     * Product listing accordingly parent category
     *
     * @param string category id
     *
     * @return if result found return category products else null
     *
     * @Route("/{_locale}/subcategory-product-list", name="office_brain_search_bundle_subcategory_product_list", options={"expose"=true})
     *
     * @Method({"GET"})
     *
     * @Template()
     */
    public function subCategoryProductPageAction()
    {
    	$this->initAction();
    	$recordparpage=1200;
    	$searchQuery = $this->searchManager->getSearchArray();
    	unset($searchQuery['product_search']['searchType']);
    	$data = $this->request->get('data','');
    	$serchtype = $this->request->get('search_type','');
    	
    	if($serchtype==1)
    	{
    		$categoryListJson='['.$data.']';
    		$this->prepareSearchForm($searchQuery['product_search'],$categoryListJson);
    	}
    	else
    	{
    		$this->prepareSearchForm($searchQuery['product_search'],'');
    	}
    	$this->responseArray = array();
//     	$this->form->getErrors();
//     	var_dump($this->form->getErrorsAsString());die;
    	if ($this->form->isValid()) {
    		$this->responseArray['productdata'] = $this->searchManager->searchResult($this->form->getData(),'',$recordparpage);
    	}
    	return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 5429
     *
     * Download product images.
     *
     *  @param string product sku
     *
     *  @param integer supplier id
     *
     *  @return download product template
     * @Route("/{_locale}/download-imagecontent", name="office_brain_custom_bundle_search_download_image_content", options={"expose"=true})
     *
     * @Method({"GET"})
     *
     * @Template()
     */
    public function downloadImageContentAction()
    {
    	$this->initAction();
    	$path = $this->request->get('path', null);
    	$filename=end(explode('/',$path));
    	$response = new Response();
    	$response->headers->set('Content-Disposition','attachment;filename='.$filename);
    	$response->headers->set('Content-Type', 'image/jpg');
    	$response->setContent(file_get_contents($path));
    	return $response;
    	//$status_info = $this->productDetailManager->downloadPdfTemplatearray($productSKU, $supplierId);die;
    }
}
