<?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 OfficeBrain\Bundle\ShippingEstimatorBundle\Helper\FedexHelper;
use OfficeBrain\Bundle\ShippingEstimatorBundle\Form\ShippingEstimatiorType as ShippingEstimatiorType;
use Symfony\Component\HttpFoundation\JsonResponse;
use FedEx\RateService;
use FedEx\RateService\ComplexType;
use FedEx\RateService\SimpleType;


class FedexController extends Controller
{
	
	/**
	 *
	 * @author Employee Id: 4471
	 *
	 * To set member variables default value
	 *
	 * @return NULL
	 */
	public function __construct()
	{
		$this->userId = null;
		$this->request = null;
		$this->refererUrl = null;
		$this->responseArray = array();
		$this->commonLibrary = null;
	}
	
	/**
	 *
	 * @author Employee Id: 4074
	 *
	 *         To unset member variables
	 *
	 * @return NULL
	 */
	public function __destruct()
	{
		unset($this->userId);
		unset($this->request);
		unset($this->refererUrl);
		unset($this->commonLibrary);
		unset($this->responseArray);
	}
	
	/**
	 *
	 * @author Employee Id: 4074
	 *
	 * Create various objects required action in this class
	 *
	 * @return NULL
	 */
	public function initAction()
	{
		$this->request = $this->getRequest();
		$this->productId = $this->request->get('productId', null);
		$this->cultureProductId = $this->request->get('cultureProductId', null);
		$this->responseArray['product_id'] = $this->productId;
		$this->responseArray['status'] = 'error';
	
		$this->projectSetting = $this->request->get('project_setting');
		$this->cultureId = $this->projectSetting['culture_id'];
		$this->userId = $this->projectSetting['user_id'];
	
		$this->commonLibrary = $this->get('office_brain_common_library');
		$this->shippingEstimatorManager = $this->get('office_brain_shipping_estimator_manager_fedex');
		$this->country = array('US'=>'USA','CA'=>'Canada');
	}
	
	/**
     * @author Employee Id: 4471
     * Description : get shipping rate fedex
     * @param 1 : No paramater
     * @throws Exception: Null
	 * @Route("/{_locale}/calculate-fedex-shipping-rate-estimator-submit",
     * name="officebrain_shippingestimatorbundle_calculatefedexshippingrateestimator_submit",
     * options={"expose"=true}
     * )
     * @Template()
     * 
     */
	
	public function submitCalculateFedexShippingRateEstimatorAction()
	{
		$this->initAction();
		if ($this->request->getMethod() == 'POST')
		{
			$id=$this->request->get('productId');
	        $this->form = $this->createForm(new ShippingEstimatiorType($this->country));
	        $this->form->handleRequest($this->request);
	    	if ($this->form->isValid()) {
	    		
				$qty = $this->form['qty']->getData();
				/*$userAdd = $this->form['address']->getData();
				$userCity = $this->form['city']->getData();
				$userState = $this->form['state']->getData();*/
				$userAdd='';
				$userCity ='';
				$userState = '';
				$userZipcode = $this->form['zip_code']->getData();
				$userCountry = $this->form['country']->getData();
				$userIsResiden = $this->form['is_resident']->getData();
				$userDetail=array('reciver'=>array('userAdd'=>$userAdd,'userCity'=>$userCity,'userState'=>$userState ,'userZip'=>$userZipcode, 'userCountry' =>$userCountry,'userPhone'=>'','userName'=>'','userIsResident'=>$userIsResiden));
				$this->responseArray ['shipping_data'] =$this->rateCalculateAction($id,$qty,$userDetail);
				$this->responseArray ['status'] = 'success';
	    	}
	    	else
	    	{
			
	   			$this->responseArray = $this->commonLibrary->prepareFormJsonError($this->form);
				$this->responseArray ['status'] = 'error';
	    	}
    	}
    	return new JsonResponse($this->responseArray);
	}
	
	/**
	 * @Route("/{_locale}/fedex-rate-calculate",
	 * name="officebrain_shippingestimatorbundle_fedex_ratecalculation" ,
	 * options={"expose"=true})
	 * @Template()
	 */
	// for Testing Purpose
	//public function rateCalculateAction($id,$qty,$userDetail)
	public function rateCalculateAction()
	{
		$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 = 901;
			$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->shippingEstimatorManager->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->shippingEstimatorManager->callRequest($shippingEstiDetail,$this->shippinEstiConfi,'shippingEstimator');
			print_r($result); exit();
			return $result;
		}
		else
		{
			echo "Contact admin for more setting !!";
		}
	}
	
	/**
	 * @Route("/{_locale}/fedex-track-shipment",
	 * name="officebrain_shippingestimatorbundle_fedex_trackshipment" ,
	 * options={"expose"=true})
	 * @Template()
	 */
	
	public function trackShipmentAction()
	{
		$this->initAction();
		$trackingNumber = '122816215025810'; //403934084723025
		
		if($this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['fedex']['option']['fedex_track']['status']==1)
		{
			$this->shippinEstiConfi = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['fedex']['option']['fedex_track']['option'];
			$response = $this->shippingEstimatorManager->callRequest($trackingNumber,$this->shippinEstiConfi,'shippingDetail');
			
			// ISSUE
			//797806677146 = International shipment release 
			//568838414941 = At destination sort facility
		
			$msg ='';
			$notification =$response->Notifications;
			$severity=$notification->Severity;
			if($severity=='SUCCESS')
			{
				if(isset($response->TrackDetails))
				{
					$trackDetail=$response->TrackDetails;
				
					$trackingNumber=$trackDetail->TrackingNumber;
					$msg .= 'Tracking number is ' .$trackingNumber;
					$msg .=  "<br/>";
				
					$statusDescription=$trackDetail->StatusDescription;
					$statusCode=$trackDetail->StatusCode;
					
					$msg .= 'Status Description is ' .$statusCode."----".$statusDescription;
					$msg .=  "<br/>";
					
					if(isset($trackDetail->ServiceCommitMessage))
					{
						$serviceCommitMessage=$trackDetail->ServiceCommitMessage;
						if($serviceCommitMessage!='')
						{
							$msg .= 'Service Commit Message : ' .$serviceCommitMessage;
							$msg .=  "<br/>";
						}
					}
					
					$serviceInfo=$trackDetail->ServiceInfo;
					$msg .= 'Service Info is ' .$serviceInfo;
					$msg .=  "<br/>";
				
					$serviceType=$trackDetail->ServiceType;
					$serviceType=str_replace('_',' ', $serviceType);
					$msg .= 'Service Type is ' .$serviceType;
					$msg .=  "<br/>";
					$msg .=  "<br/>";
					$msg .=  "<br/>";
				
					$evants=$trackDetail->Events;
					if(is_array($evants))
					{
						foreach($evants as $id => $evant)
						{
							$timeStamp = $evant->Timestamp;
							$timeStamp = str_replace('T0',' T0 ', $timeStamp);
							$stype=$evant->EventType;
							$type=$evant->EventDescription;
							$arrivalLocation = $evant->ArrivalLocation;
							$arrivalLocation = str_replace('_',' ', $arrivalLocation);
							//$city=$evant->Address->City;
							$pincode=$evant->Address->PostalCode;
							$msg .= $timeStamp."---".$type."---".$stype."----".$arrivalLocation."--".$pincode;
							$msg .=  "<br/>";
						}
					}
					else
					{
						$timeStamp = $evants->Timestamp;
						$timeStamp = str_replace('T0',' T0 ', $timeStamp);
						$type=$evants->EventDescription;
						$arrivalLocation = $evants->ArrivalLocation;
						$arrivalLocation = str_replace('_',' ', $arrivalLocation);
						
						$pincode=$evants->Address->PostalCode;
						$msg .= $timeStamp."---".$type."---".$arrivalLocation."--".$pincode;
						$msg .=  "<br/>";
					}
				}
				else {
					echo "error";
				}
			
			}
			else
			{
				$msg = $notification->Message;
			
			}
			echo $msg;
			die;
			exit();
		}
		else {
			echo "contact admin for more setting !!";
		}
	}
	
	/**
	 * @Route("/{_locale}/fedex-create-shipment",
	 * name="officebrain_shippingestimatorbundle_fedex_createshipment" ,
	 * options={"expose"=true})
	 * @Template()
	 */
	
	public function createShipmentAction()
	{
		$this->initAction();
		if($this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['fedex']['option']['fedex_shipment']['status']==1)
		{
			$this->qty = $this->request->get('qty', 3);
			
			$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');
			$this->weight = $this->request->get('weight', 0);
			$this->serviceType = $this->request->get('serviceType', 'FIRST_OVERNIGHT');
			
			$this->productId = $this->request->get('product_id','203');
			$this->productSlug = $this->request->get('product_slug');
			
			
			$userDetail=array('reciver'=>array('userAdd'=>$this->userAdd,'userCity'=>$this->userCity,'userState'=>$this->userState ,'userZip'=>$this->userZipcode, 'userCountry' =>$this->userCountry,'userPhone'=>$this->userPhone,'userName'=>$this->userName,'userIsResident'=>$this->userIsResiden),'serviceType'=> $this->serviceType);
			$productDetail = $this->shippingEstimatorManager->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) ;
			
			$this->shippinEstiConfi = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['fedex']['option']['fedex_shipment']['option'];
			$response = $this->shippingEstimatorManager->callRequest($shippingEstiDetail,$this->shippinEstiConfi);
			print_r($response);
			exit();
		}
		else
		{
			echo "Permission deny contact admin for setting ";
		}	
			
		
	}
}
