<?php

namespace OfficeBrain\Bundle\QuickQuoteBundle\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\JsonResponse;
use Symfony\Component\Translation\Translator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use OfficeBrain\Bundle\QuickQuoteBundle\Form\QuickQuoteType;


/**
 *
 *
 * @Route("", defaults={"rule_service"="rule_charges"})
 */
class QuickQuoteController extends Controller
{
    
    /**
     * @author Employee Id: 4248
     * To set member variables default value
     * @return NULL
     */
    public function __construct()
    {
        $this->form = null;
        $this->request = null;
        $this->userId = null;
        $this->productId = null;
        $this->refererUrl = null;
        $this->projectSetting = null;
        $this->responseArray = array();
        $this->cultureProductId = null;
        $this->quickQuoteManager = null;
        $this->quickquoteProducts = null;
        $this->inlineViewProductMaxLimit = null;
        $this->commonLibraryManager = null;
        $this->quickQuoteManager = null;
        $this->refererUrl = null;
    }
    
    /**
     * @author Employee Id: 4248
     * To unset member variables
     * @return NULL
     */
    public function __destruct()
    {
        unset($this->form);
        unset($this->userId);
        unset($this->request);
        unset($this->productId);
        unset($this->refererUrl);
        unset($this->responseArray);
        unset($this->commonLibraryManager);
        unset($this->projectSetting);
        unset($this->cultureProductId);
        unset($this->quickQuoteManager);
        unset($this->quickquoteProducts);
        unset($this->inlineViewProductMaxLimit);
        unset($this->refererUrl);
    }
    
    /**
     *
     * @author Employee Id: 4248
     * Create various objects required action in this class
     * @return NULL
     */
    public function initAction()
    {
        $this->request = $this->getRequest();
        $this->productId = $this->request->get('product_id', null);
        $this->cultureProductId = $this->request->get('culture_product_id', null);
        $this->projectSetting = $this->request->get('project_setting');
        $this->inlineViewProductMaxLimit = $this->projectSetting['configuration_rule']['transaction']['quick_quote']['inline_view']['option']['no_of_product'];
        $this->userId = $this->projectSetting['user_id'];
        $this->responseArray['product_id'] = $this->productId;
        $this->responseArray['status'] = 'error';
        $this->categoryApiManager = $this->get("officebrain_category_api_manager");
        $this->commonLibraryManager = $this->get('office_brain_common_library');
        $this->quickQuoteManager = $this->get('office_brain_quick_quote_manager');
        $this->freeFreightAllowCategoryList = $this->getParameter('free_freight_allow_category_list');
    }
    
    /**
      *  @author Employee Id: 4248
      *   Add to quick quote list
      *  @param integer productId
      *  @param integer cultureProductId
      *  @return
      * @Route("/{_locale}/add-to-quick-quote",
      * name="office_brain_quickquotebundle_quickquote_addproducttoquickquote",
      *  options={"expose"=true}
      * )
      * @Template()
    * */
    public function addProductToQuickQuoteAction()
    {
        $this->initAction();
        if ($this->productId && $this->cultureProductId) {
            $status = $this->quickQuoteManager->setQuickQuote();
            switch ($status) {
                case 'ERROR_MAX_LIMIT_REACHED':
                    $this->responseArray['error_message'] = $this->get('translator')->trans('quick_quote.max_product_quickquote', array('%count%'=>$this->inlineViewProductMaxLimit));
                    break;
                case 'ERROR_PRODUCT_ALREADY_EXISTS':
                    $this->responseArray['error_message'] = $this->get('translator')->trans('quick_quote.product_already_exists');
                    break;
                case 'SUCCESS':
                    $this->responseArray['status'] = 'success';
                    $this->responseArray['success_message'] = $this->get('translator')->trans('quick_quote.add_success_message');
                    $this->refererUrl = $this->commonLibraryManager->getRefererRouteName();
                    break;
            }
        }

        if ($this->refererUrl=='office_brain_quickquotebundle_quickquote_quickquote') {
        		$this->responseArray['page_url'] = $this->generateUrl('office_brain_quickquotebundle_quickquote_quickquote');
        } else {
        		$this->responseArray['total_product'] = $this->quickQuoteManager->getTotalCount();
        }
        return new JsonResponse($this->responseArray);
    }
    
    /**
     * To get recent product quickquote list
     *
     * @Route("/{_locale}/recent-quick-quote",
     * 	name="office_brain_quickquotebundle_quickquote_recentquickquote",
     *  options={"expose"=true}
     * )
     *
     * @Method({"GET"})
     * @Template("OfficeBrainQuickQuoteBundle:QuickQuote:recentQuickQuoteList.html.twig")
     */
    public function recentQuickQuoteListAction()
    {
        $this->initAction();
        $this->responseArray['record_set'] = $this->quickQuoteManager->getMaxNoOfQuickQuote($this->inlineViewProductMaxLimit);
        $this->responseArray['total_product'] = $this->quickQuoteManager->getTotalCount();
        
        $this->quickQuoteManager->setContinueShoppingUrl($this->commonLibraryManager->getRefererRouteName(), $this->commonLibraryManager->getRefererUrl());
        return $this->responseArray;
    }

    /**
     * get list of product quick quote
     *
     * @Route("/{_locale}/quick-quote",
     * 	name="office_brain_quickquotebundle_quickquote_quickquote",
     *  options={"expose"=true}
     * )
     * @Method({"GET", "POST"})
     * @Template("OfficeBrainQuickQuoteBundle:QuickQuote:quickQuote.html.twig")
     */
    public function quickQuoteAction()
    {
        $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);
        $this->responseArray['total_product'] = $this->quickQuoteManager->getTotalCount();
        $this->responseArray['record_set'] = $this->quickQuoteManager->getQuickQuote();
        $categoryAndSubCategoryList = array();
        foreach($this->responseArray['record_set'] as $key=> $value){  
        	 $productId =$value['product_id'];
        	$categoryAndSubCategoryList[$productId] = $this->categoryApiManager->getParentChildCategoryList($categoryAndSubCategoryData,$value['category'],$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];
        }
        
        
        return $this->responseArray;
    }
        
    /**
     * @author Employee Id: 4248
     *
     * Delete product from quick quote product
     * @Route("/{_locale}/quick-quote-delete",
     * 	name="office_brain_quickquotebundle_quickquote_deletequickquote",
     *  options={"expose"=true}
     * )
     *
     * @Template()
     */
    public function deleteQuickQuoteAction()
    {
        $this->initAction();
        
        if ($this->productId && $this->cultureProductId) {
            $status=$this->quickQuoteManager->deleteQuickQuote($this->productId, $this->cultureProductId);
            switch ($status) {
                case 'ERROR_PRODUCT_ALREADY_EXISTS':
                    $this->responseArray['error_message'] = $this->get('translator')->trans('quick_quote.product_already_exists');
                    break;
                case 'SUCCESS':
                    $this->responseArray['status'] = 'success';
                    $this->responseArray['success_message'] = $this->get('translator')->trans('quick_quote.remove_success_message');
    
                    $this->refererUrl = $this->commonLibraryManager->getRefererRouteName();
                    break;
            }
        }
    	
        if ($this->refererUrl=='office_brain_quickquotebundle_quickquote_quickquote') {
        	$this->responseArray['page_url'] = $this->generateUrl('office_brain_quickquotebundle_quickquote_quickquote');
        } else {
        	$this->responseArray['total_product'] = $this->quickQuoteManager->getTotalCount();
        }

        return new JsonResponse($this->responseArray);
    }
    
    
    /**
     * @author Employee Id: 4248
     *
     * Delete product from quick quote product
     * @Route("/{_locale}/add-quick-quote",
     * 	name="office_brain_quickquotebundle_quickquote_addquickquote",
     *  options={"expose"=true}
     * )
     * @Method({"GET"})
     * @Template("OfficeBrainQuickQuoteBundle:QuickQuote:addQuickQuote.html.twig")
     */
    public function addQuickQuoteAction()
    {
        $this->initAction();
        $this->form=$this->createForm(new QuickQuoteType());
        $this->responseArray['form']=$this->form->createView();
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4248
     *
     * Delete product from quick quote product
     * @Route("/{_locale}/add-quick-quote",
     * 	name="office_brain_quickquotebundle_quickquote_precessquickquote",
     *  options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template("OfficeBrainQuickQuoteBundle:QuickQuote:addQuickQuote.html.twig")
     */
    public function processQuickQuoteAction()
    {
        $this->initAction();
        $this->form=$this->createForm(new QuickQuoteType());
        $this->form->handleRequest($this->request);
        if ($this->form->isValid()) {
        	$this->quickQuoteManager->sendMailQuickQuote($this->form->getData());
        	$this->quickQuoteManager->deleteAllQuickQuote();
        	$this->responseArray['status']='success';
        	$this->responseArray['goto_url']=$this->generateUrl('office_brain_quickquotebundle_quickquote_thankyou');
        	return new JsonResponse($this->responseArray);
        } elseif ($this->request->isXmlHttpRequest()) {
        	return new JsonResponse($this->commonLibraryManager->prepareFormJsonError($this->form));
        }
        return array(
                'form' => $this->form->createView(),
        );
    }
    
    /**
    * @author Employee Id: 4248
    *
    * Delete product from quick quote product
    * @Route("/{_locale}/quick-quote/thank-you",
    * 	name="office_brain_quickquotebundle_quickquote_thankyou",
    * )
    * @Method({"GET"})
    * @Template("OfficeBrainQuickQuoteBundle:QuickQuote:thankYou.html.twig")
    */
    public function thankYouAction()
    {
        return array();
    }
    
    
    /**
     * @return 302 Redirection Response
     * @throws NULL
     * @Route("/{_locale}/continue-shopping-from-quick-quote",
     * 	name="office_brain_quickquotebundle_quickquote_continueshopping"
     * )
     *
     * @Method({"GET"})
     *
     */
    public function continueShoppingAction()
    {
    	return $this->redirect($this->generateUrl('office_brain_searchbundle_search_continueshopping'));
    	/*
    	 $this->initAction();
    	return $this->redirect($this->compareProductManager->getContinueShoppingUrl());
    	*/
    }
    
}
