<?php

namespace OfficeBrain\Bundle\PageBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use OfficeBrain\Bundle\CacheBundle\Document\RedisKey;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use OfficeBrain\Bundle\SearchBundle\Form\Type\ProductSearchType;
use OfficeBrain\Bundle\SearchBundle\Form\Data\ProductSearchData;

class HomePageController extends Controller {

  /**
     * @author Employee Id: 4834
     * set default value
     * @return NULL
     */
    public function __construct()
    {
        $this->queueApiManager = null;
        $this->newsLetter = null;
        $this->locale = null;
        $this->translator = null;
    }

    /**
     * @author Employee Id: 4834
     * unset default value
     * @return NULL
     */
    public function __destruct()
    {
        unset($this->request);
        unset($this->projectSetting);
        unset($this->session);
        unset($this->newsLetter);
        unset($this->locale);
        unset($this->translator);
    }
    /**
     *
     * @author Employee Id: 4273
     *
     *         Create various objects required action in this class
     *
     * @return NULL
     */
    public function initAction()
    {

        $this->request = $this->getRequest();
        $this->session = $this->request->getSession();
        $this->projectSetting = $this->request->get('project_setting');
        $this->serviceGroupId = $this->projectSetting['service_group_id'];
        $this->instanceId = $this->projectSetting['instance_id'];
        $this->userId = $this->projectSetting['user_id'];
        $this->site_module = $this->get('office_brain_page_site_module');
        $this->projectSetting = $this->getRequest()->get('project_setting');
        $this->siteModuleRepo = $this->getDoctrine()->getRepository('OfficeBrainPageBundle:SiteModule');
        $this->searchManager = $this->get('office_brain_search_manager');
        $this->languageId = $this->searchManager->getLanguageId();
        $this->entityManager = $this->getDoctrine()->getManager();
        $this->productSearchForm = new ProductSearchType();
        $this->newsLetter = $this->get('office_brain_newsletter_manager');
        $this->locale = $this->projectSetting['locale_language'];
        $this->translator = $this->get('translator');
    }

    /**
     * @Route("/",
     * 	name="office_brain_page_homepage",
     * )
     * @Route("/{_locale}",
     * 	name="office_brain_page_homepage_view",
     * )
     *
     * @Template("OfficeBrainPageBundle:HomePage:index.html.twig")
     */
	public function indexAction()
    {
        $this->initAction();

        $locale=$this->locale;

        $arrLocale=explode("_", $locale);
        $data=array();

        $countryId = $this->container->getParameter('country')[$arrLocale[1]]['id'];

        // Brand List
        //$data['brandList']=$this->get("officebrain_brand_api_manager")->getList($arrLocale[0]);

        $data['brandList']=$this->get('office_brain_subshop_manager')->frontGetBrands($this->get("officebrain_brand_api_manager"),$arrLocale[0],$this->projectSetting['instance_id']);
        $data['bestSelling']=$this->get('office_brain_subshop_manager')->frontGetPromotionalProducts($this->get('office_brain_product_detail_manager'),$locale,$countryId,$this->projectSetting['instance_id'],'best_selling');
        $data['recommended']=$this->get('office_brain_subshop_manager')->frontGetPromotionalProducts($this->get('office_brain_product_detail_manager'),$locale,$countryId,$this->projectSetting['instance_id'],'recommended');

        return $data;
    }
    /**
     * @Route("/{_locale}/get-site-block-data/{block}/{slug}",
     * 	name="office_brain_page_homepage_sitemodule_data",
     * )
     * @Template("OfficeBrainPageBundle:HomePage:siteModule.html.twig")
     */
    public function getsiteProductBlockAction($block,$slug= null){

    	if(empty($slug))
    		return array();

    	$this->initAction();

    	$data = $this->siteModuleRepo->findOneBy(array('slug'=>$slug,'instanceId'=>$this->projectSetting['instance_id']));
    	if(!$data){
    		return array();
		}
    	$criteria = json_decode($data->getCriteria(),true);
    	if(!$criteria)
    		return array();
    	
    	$result = array();


    	/* $this->productSearchData = new ProductSearchData($this->entityManager, $this->languageId);
    	$this->form = $this->createForm($this->productSearchForm, $this->productSearchData, array('csrf_protection' => false));
    	$this->form->bind($criteria);
    	$this->responseArray = $this->searchManager->searchResult($this->form->getData()); */
    	
    	// Call Search Services
    	foreach ($criteria['product_search'] as $key => $value){
    		$this->request->query->set($key, $value);
    	}
    	$this->responseArray = $this->searchManager->searchService();



    			$data=array();
    			//$data = $this->site_module->getProduct($criteria);
    			#print_r(array_keys((array)$this->responseArray['search_result_array']));
    			#echo(array_keys($this->responseArray['search_result_array']));exit;
    			$data['search_result_array'] = $this->responseArray['search_result_array'];
    			$data['product_box_bootstrap_class']='item';
                        $data['render_model']=0;
    			//return $this->render('OfficeBrainPageBundle:tempUIElements:recommendProducts.html.twig', $data);
    			return $data;
    }

    /**
     * @Route("/{_locale}/newsletter", name="office_brain_newsletter_send")
     *
     * @Template()
     */
    public function newsLetterAction()
    {
        $this->initAction();
        $emailId = $this->request->get('email_send');
        $this->newsLetterId=$this->newsLetter->insertEmailId($emailId);

		if ($this->newsLetterId == 'EMAIL_ALREADY_EXISTS'){
            $this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('newsletter.front.errors.email_already_exists'));
            $pathToRedirect = 'office_brain_page_homepage_view';
        }else{
            if($this->newsLetterId > 0){
                $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('newsletter.front.success'));
                $pathToRedirect = 'office_brain_page_thank_you';
            }else{
                $pathToRedirect = 'office_brain_page_homepage_view';
            }
        }

        return $this->redirect($this->generateUrl($pathToRedirect, array('_locale' => $this->locale)));
    }

}
