<?php

namespace OfficeBrain\Bundle\ShippingEstimatorBundle\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 OfficeBrain\Bundle\ShippingEstimatorBundle\Form\ShippingEstimatiorType as ShippingEstimatiorType;
use Symfony\Component\HttpFoundation\JsonResponse;
use OfficeBrain\Bundle\ShippingEstimatorBundle\Helper\ShippingEstimatorHelper as ShippingEstimatorHelper;


class ShippingEstimatorController extends Controller
{
	
	/**
	 *
	 * @author Employee Id: 4471
	 *
	 * To set member variables default value
	 *
	 * @return NULL
	 */
	public function __construct()
	{
		$this->country= array();
		$this->sessionManager = null;
	}
	
	/**
	 *
	 * @author Employee Id: 4471
	 *
	 * To unset member variables
	 *
	 * @return NULL
	 */
	public function __destruct()
	{
		unset($this->country);
		unset($this->sessionManager);
	}
	
	public function initAction()
	{
		$this->request = $this->getRequest();
		$this->projectSetting = $this->request->get('project_setting');
		$this->cultureId = $this->projectSetting['culture_id'];
		$this->userId = $this->projectSetting['user_id'];
		$this->commonLibraryManager = $this->get('office_brain_common_library');
		$this->fedexShippingEstimatorManager = $this->get('office_brain_shipping_estimator_manager_fedex');
		$this->upsShippingEstimatorManager = $this->get('office_brain_shipping_estimator_manager_ups');
		$this->loomisExpressShippingEstimatorManager = $this->get('office_brain_shipping_estimator_manager_loomis_express');
		$this->cmsThirdPartyManager = $this->get('office_brain_cms_third_party_service_manager'); 
		$this->userContactBookManager = $this->get('office_brain_user_contact_book_manager');
		$this->coreManager = $this->get('office_brain_core_manager');
		$this->sessionManager = $this->get('office_brain_session_manager');
		if($this->userId!='0')
		{
			$this->seviceType = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['rate']['option']['service']['option']['service_selected'];
			$this->shippingEstinCalSeviceType = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['rate']['option']['shipping_estimator_calculation_service']['option']['service_selected'];
			$this->isResi = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['rate']['option']['shipping_estimator_calculation_service']['option']['is_resident'];
			$this->isStateDisplay = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['rate']['option']['shipping_estimator_calculation_service']['option']['is_state_list'];
			$this->isCityDisplay = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['rate']['option']['shipping_estimator_calculation_service']['option']['is_city_list'];
			$this->isCountryList = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['rate']['option']['shipping_estimator_calculation_service']['option']['is_country_list']['status'];
			if($this->isCountryList==1)
				$this->defaultCountry = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['rate']['option']['shipping_estimator_calculation_service']['option']['is_country_list']['option']['default_country_code'];
			else
				$this->defaultCountry = '';
		}
		else
		{
			$this->seviceType = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['guest_user']['option']['rate']['option']['service']['option']['service_selected'];
			$this->shippingEstinCalSeviceType = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['guest_user']['option']['rate']['option']['shipping_estimator_calculation_service']['option']['service_selected'];
			$this->isResi = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['guest_user']['option']['rate']['option']['shipping_estimator_calculation_service']['option']['is_resident'];
			$this->isStateDisplay = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['guest_user']['option']['rate']['option']['shipping_estimator_calculation_service']['option']['is_state_list'];
			$this->isCityDisplay = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['guest_user']['option']['rate']['option']['shipping_estimator_calculation_service']['option']['is_city_list'];
			$this->isCountryList = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['guest_user']['option']['rate']['option']['shipping_estimator_calculation_service']['option']['is_country_list']['status'];
			if($this->isCountryList==1)
				$this->defaultCountry = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['guest_user']['option']['rate']['option']['shipping_estimator_calculation_service']['option']['is_country_list']['option']['default_country_code'];
			else 
				$this->defaultCountry = '';
		}
		
		//$this->country = array('CA'=>'Canada','US'=>'USA');
		$this->country = $this->coreManager->getCountryDataWithCode();
	}
	
	/**
	 * @author Employee Id: 4471
	 *
	 * This is used get shipping rate
	 *
	 *
	 * @Route("/{_locale}/calculate-shipping-rate-estimator",
	 * name="officebrain_shippingestimatorbundle_calculateshippingrateestimator",
	 * options={"expose"=true}
	 * )
	 * @Template()
	 *
	 */
	public function calculateShippingRateEstimatorAction()
	{
		$this->initAction();
		$productId = $this->request->get('productId', null);
		$productName = $this->request->get('productName', null);
		$productSku = $this->request->get('productsku', null);
		$this->form = $this->createForm(new ShippingEstimatiorType($this->country,$this->shippingEstinCalSeviceType,$this->isResi,$this->defaultCountry,$this->isStateDisplay,$this->isCityDisplay,$this->coreManager));
		$this->responseArray['form'] = $this->form->createView();
		$this->responseArray['productDetail'] = array('productId'=>$productId,'productName'=>$productName,'productSku'=>$productSku);
		return $this->responseArray;
	}
	
	
	/**
     * @author Employee Id: 4471
     * Description : get shipping rate
     * @param 1 : No paramater
     * @throws Exception: Null
     * 
	 * @Route("/{_locale}/calculate-shipping-rate-estimator-submit",
     * name="officebrain_shippingestimatorbundle_calculateshippingrateestimator_submit",
     * options={"expose"=true}
     * )
     * @Method({"POST"})
     * @Template()
     * 
     */
	
	public function submitCalculateShippingRateEstimatorAction()
	{
		$this->initAction();
		
		if ($this->request->getMethod() == 'POST')
		{
			$id=$this->request->get('product_id');
	        $this->form = $this->createForm(new ShippingEstimatiorType($this->country,$this->shippingEstinCalSeviceType,$this->isResi,$this->defaultCountry,$this->isStateDisplay,$this->isCityDisplay,$this->coreManager));
	        $this->form->handleRequest($this->request);
	    	if ($this->form->isValid()) {
	    		$rateObj= new ShippingEstimatorHelper($this->fedexShippingEstimatorManager,$this->upsShippingEstimatorManager,$this->loomisExpressShippingEstimatorManager,$this->coreManager);
	    		//call fedex and/or ups and/or loomis express
	    		$rateData = $rateObj->getShippingEstimatorRate($this->form->getData(),$id,$this->projectSetting,'shippingEstimator');
	    		if ($rateData['status']=='success') {
	    			$this->responseArray ['status'] = 'success';
	    			$resultArray['result'] = $rateData;
	    			$this->responseArray['shipping_data'] = $this->renderView("OfficeBrainShippingEstimatorBundle:ShippingEstimator:setShippingEstimatorRate.html.twig" , $resultArray );
	    		} else {
					$this->responseArray ['form_status'] = 'error';
					if($rateData['error']== 'product_detail_error')
					{
						$result['result']['status'] = 'error';
						$result['result']['error_msg'] = $this->get('translator')->trans('shipping_estimator.form.product_detail_missing');
						$this->responseArray['error_set']  = $this->renderView("OfficeBrainShippingEstimatorBundle:ShippingEstimator:setShippingEstimatorRate.html.twig" , $result );
					}
					elseif ($rateData['error']== 'no_of_box_error')
					{
						$result['result']['status'] = 'error';
						$result['result']['error_msg'] = $this->get('translator')->trans('shipping_estimator.form.no_of_box_error');
						$this->responseArray['error_set']  = $this->renderView("OfficeBrainShippingEstimatorBundle:ShippingEstimator:setShippingEstimatorRate.html.twig" , $result );
					}
					elseif ($rateData['error']== 'fob_error')
					{
						$result['result']['status'] = 'error';
						$result['result']['error_msg'] = $this->get('translator')->trans('shipping_estimator.form.fob_error');
						$this->responseArray['error_set']  = $this->renderView("OfficeBrainShippingEstimatorBundle:ShippingEstimator:setShippingEstimatorRate.html.twig" , $result );
					}
				}
		   	} else {
	   			$this->responseArray = $this->commonLibraryManager->prepareFormJsonError($this->form);
	    	}
    	}

    	return new JsonResponse($this->responseArray);
	}
	/**
	 * @author Employee Id: 4471
	 *
	 * get available shipping service according to country 
	 *
	 *
	 * @Route("/{_locale}/get-shipping-method-by-country",
	 * name="officebrain_shippingestimatorbundle_getshippingmethodbycountry",
	 * options={"expose"=true}
	 * )
	 * @Template()
	 *
	 */
	public function getShippingMethodByCountryAction()
	{
		$this->initAction();
		$shippingMethod ='';
		$countryName = $this->request->get('countryName', 'us');
		$listShippingMethod=$this->cmsThirdPartyManager->getShippingCountryWise($countryName);
		foreach ($listShippingMethod as $index=>$val) {
			$shippingMethod .= "<li data-value='".$index."'><a href='javascript:void(0)'>".$val."</a></li>";
		}
		return new JsonResponse($shippingMethod);
	}
	
	
	/**
	 * @author Employee Id: 4471
	 *
	 * get shipping service rate 
	 *
	 *
	 * @Route("/{_locale}/get-shipping-rate-data",
	 * name="officebrain_shippingestimatorbundle_getshippingratedata",
	 * options={"expose"=true}
	 * )
	 * @Template()
	 *
	 */
	public function getShippingRateDataAction()
	{
		$this->initAction();
		$productId= $this->request->get('productId');
		$shippingMethod = $this->request->get('shippingMethod', 'fedex'); 
		$shippingaddId = $this->request->get('shippingaddId');
		$counter = $this->request->get('counter');
		$requestType = $this->request->get('request_type');
		$qty = $this->request->get('qty');
		$data['qty']= $qty ;
		$userIsResident = 0;
		if($this->userId>0){
			$contactBookArray = $this->userContactBookManager->getSingleContactBook($shippingaddId);
			
			$userZipcode = $contactBookArray->getZipcode();
			$userCountry= $this->coreManager->getCountryCode($contactBookArray->getCountryId());
			if ($contactBookArray->getIsOffice()==0) {
				$userIsResident = '1';
			}
			$data['zip_code'] = $userZipcode;
			$data['city'] = $contactBookArray->getCityId();
			$data['state'] =$contactBookArray->getStateId();
			$data['country'] = $userCountry; 
			$data['is_resident'] = $userIsResident ;
		}else{
			if($requestType=="request_quote"){
				if($this->sessionManager->has('guest_shipping_address') && count($this->sessionManager->has('guest_shipping_address')) > 0 )
				{
					$sessionData = $this->sessionManager->get('guest_shipping_address');
				}else{
					$inputData = $this->sessionManager->get('request_quotes');
	    			$sessionData = $inputData[$productId]['guest_shipping_detail'];
				}
			}
			
			if($requestType=="request_order"){
				if($this->sessionManager->has('order_guest_shipping_address') && count($this->sessionManager->has('order_guest_shipping_address')) > 0 )
				{
					$sessionData = $this->sessionManager->get('order_guest_shipping_address');
				}else{
					$inputData = $this->sessionManager->get('request_quotes');
					$sessionData = $inputData[$productId]['guest_shipping_detail'];
				}
			}
			
			if(array_key_exists('standard',$sessionData[$productId])){
				$shipDetail = $sessionData[$productId]['standard'][$counter];
			}
			if(array_key_exists('split',$sessionData[$productId])){
				$shipDetail = $sessionData[$productId]['split'][$counter];
			}
			$data['zip_code'] = $shipDetail['zipcode'];
			$data['city'] = $shipDetail['cityId'];
			$data['state'] =$shipDetail['stateId'];
			$data['country'] = $this->coreManager->getCountryCode($shipDetail['countryId']);
			$data['is_resident'] = $userIsResident ; 
		}
		$data['shipping_type'] =  array('0' => $shippingMethod );
		$rateObj= new ShippingEstimatorHelper($this->fedexShippingEstimatorManager,$this->upsShippingEstimatorManager,$this->loomisExpressShippingEstimatorManager,$this->coreManager);
		$rateData=$rateObj->getShippingEstimatorRate($data,$productId,$this->projectSetting,'shippingDetail');

		if(isset($rateData['error']))
		{
			if(isset($rateData['error'])){
				if($rateData['error']== 'product_detail_error')
				{
					$result['result']['status'] = 'error';
					$result['result']['error_msg'] = $this->get('translator')->trans('shipping_estimator.form.product_detail_missing');
					//$shippingRate['record_set']  = $this->renderView("OfficeBrainShippingEstimatorBundle:ShippingEstimator:setShippingRateData.html.twig" , $result );
				}
				elseif ($rateData['error']== 'no_of_box_error')
				{
					$result['result']['status'] = 'error';
					$result['result']['error_msg'] = "The number of boxes in a single shipment should not exceed 150.";
					//$shippingRate['record_set']  = $this->renderView("OfficeBrainShippingEstimatorBundle:ShippingEstimator:setShippingRateData.html.twig" , $result );
				}
				elseif ($rateData['error']== 'fob_error')
				{
					$result['result']['status'] = 'error';
					$result['result']['error_msg'] = 'Fob Detail is missing';
					//$shippingRate['record_set']  = $this->renderView("OfficeBrainShippingEstimatorBundle:ShippingEstimator:setShippingRateData.html.twig" , $result );
				}else{
					$result['result']['status'] = 'error';
					$result['result']['error_msg'] = $rateData['error_message'];
					//$shippingRate['record_set']  = $this->renderView("OfficeBrainShippingEstimatorBundle:ShippingEstimator:setShippingRateData.html.twig" , $result );
				}
			}
			return new JsonResponse($result['result']);
		}elseif(isset($rateData['data']['error'])){
			
			if($rateData['data']['error']== 'product_detail_error')
			{
				$result['result']['status'] = 'error';
				$result['result']['error_msg'] = $this->get('translator')->trans('shipping_estimator.form.product_detail_missing');
				//$shippingRate['record_set']  = $this->renderView("OfficeBrainShippingEstimatorBundle:ShippingEstimator:setShippingRateData.html.twig" , $result );
			}
			elseif ($rateData['data']['error']== 'no_of_box_error')
			{
				$result['result']['status'] = 'error';
				$result['result']['error_msg'] = $this->get('translator')->trans('shipping_estimator.form.no_of_box_error');
				//$shippingRate['record_set']  = $this->renderView("OfficeBrainShippingEstimatorBundle:ShippingEstimator:setShippingRateData.html.twig" , $result );
			}
			elseif ($rateData['data']['error']== 'fob_error')
			{
				$result['result']['status'] = 'error';
				$result['result']['error_msg'] = $this->get('translator')->trans('shipping_estimator.form.fob_error');
				//$shippingRate['record_set']  = $this->renderView("OfficeBrainShippingEstimatorBundle:ShippingEstimator:setShippingRateData.html.twig" , $result );
			}else{
				$result['result']['status'] = 'error';
				$result['result']['error_msg'] = $rateData['data']['error_msg'];
			}
			
			return new JsonResponse($result['result']);		
		}else{
			if ($rateData['status']=='success') {

			$keys = array_column($rateData['data'], 'amount');
			array_multisort($keys, SORT_ASC, $rateData['data']);
			$resultArray['result'] = $rateData;
			$shippingRate['record_set'] = $this->renderView("OfficeBrainShippingEstimatorBundle:ShippingEstimator:setShippingRateData.html.twig" , $resultArray );
			}
		}
		return new JsonResponse($shippingRate);
	}
	
	
	/**
	 * @Route("/{_locale}/lomiss-express-rate-calculate",
	 * name="officebrain_shippingestimatorbundle_lomiss_express_rate_calculation" ,
	 * options={"expose"=true})
	 * @Template()
	 */
	// for Testing Purpose
	public function rateLoomisExpressCalculateAction()
	{
		$this->initAction();
		if($this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['fedex']['option']['fedex_rate']['status']==1)
		{
			//$this->qty = $qty;
			$this->qty = 3;
			$id = 332931;
			$this->shippinEstiConfi = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['fedex']['option']['fedex_rate']['option'];
				
			$this->userAdd= $this->request->get('address', array('1750-1798 N 9th St'));
			$this->userCity= $this->request->get('city', 'Kansas City');
			$this->userState = $this->request->get('state', 'KS');
			$this->userZipcode = $this->request->get('pincode', '66101');
			$this->userCountry = $this->request->get('country','US');
			$this->userPhone = $this->request->get('phone','620-123-4567');
			$this->userName = $this->request->get('contact_name','XYZ');
			$this->userIsResiden = $this->request->get('is_resident','0');
				
			$userDetail=array('reciver'=>array('userAdd'=>$this->userAdd,'userCity'=>$this->userCity,'userState'=>$this->userState ,'userZip'=>$this->userZipcode, 'userCountry' =>$this->userCountry,'userPhone'=>'','userName'=>'','userIsResident'=>$this->userIsResiden));
			$this->productId = $this->request->get('product_id',$id);
			$this->productSlug = $this->request->get('product_slug');
			$productDetail = $this->loomisExpressShippingEstimatorManager->getProductDetailForShipping($this->productId,$this->qty);
				
			unset($productDetail['shipper']);
			$shipperDetail = array('shipper'=>array('shipperAdd'=>array('Herndon Centennial Golf Course','909 Ferndale Ave'),'shipperCity'=>'Herndon','shipperState'=>'VA' ,'shipperZip'=>'20170', 'shipperCountry' =>'US','shipperPhone'=>'123-123-1234','shipperCompanyName'=>'Company Name','shipperEmail'=>'test@xyz.com','shipperName'=>'XYZ Name'));
	
			$shippingEstiDetail=array_merge($productDetail,$userDetail,$shipperDetail) ;
			$result = $this->loomisExpressShippingEstimatorManager->callRequest($shippingEstiDetail,$this->shippinEstiConfi,'shippingEstimator');
			print_r($result); exit();
			return $result;
		}
		else
		{
			echo "Contact admin for more setting !!";
		}
	}
	
	
}
?>