<?php
namespace OfficeBrain\Bundle\ShippingEstimatorBundle\Manager\Extended;

use FedEx\RateService;
use FedEx\RateService\ComplexType;
use FedEx\RateService\SimpleType;
use OfficeBrain\Bundle\ShippingEstimatorBundle\Manager\AbstractManager\ShippingEstimatorAbstract;
use OfficeBrain\Bundle\ShippingEstimatorBundle\Manager\Service\ShippingEstimatorService;
use OfficeBrain\Bundle\ShippingEstimatorBundle\Helper\FedexHelper;
use Symfony\Component\HttpFoundation\JsonResponse;
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 Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;

Class RateFedexExtended extends ShippingEstimatorAbstract
{
	public function __construct($entityManager, $request, $session, $productDetailService)
	{
		parent::__construct($entityManager, $request, $session, $productDetailService);
	}
	
	public function __destruct()
	{
		parent::__destruct();
	}
	
	public function getProductDetailForShipping($productId,$qty)
	{
		$productShippingDetail=parent::getProductDetailForShipping($productId,$qty);
		return $productShippingDetail;
	}
	
	public function callRequest($shippingEstiDetail,$shippinEstiConfi,$callFrom)
	{
		$this->rateRequest = new ComplexType\RateRequest();
		$ObjFedex = new FedexHelper('rate',$shippinEstiConfi);
		
		
		//WebAuthenticationDetail
		$webAuthenticationDetail=$ObjFedex->setAuthenticationDetail();
		$this->rateRequest->setWebAuthenticationDetail($webAuthenticationDetail);
		
		//$this->setRateReplyDetail();
		
		//ClientDetail
		$clientDetail=$ObjFedex->setClientDetail();
		$this->rateRequest -> setClientDetail($clientDetail);
		
		//TransactionDetail
		$transactionDetail=$ObjFedex->setTransaction();
		$this->rateRequest->setTransactionDetail($transactionDetail);
		
		//Version
		$version=$ObjFedex->setVersionDetail();
		$this->rateRequest->setVersion($version);
		
		//ReturnTransitAndCommit
		$this->rateRequest->setReturnTransitAndCommit(true);
		$this->requestedShipment=$ObjFedex->setShipmentDetail($shippingEstiDetail);
		$this->rateRequest->setRequestedShipment($this->requestedShipment);
		
		//$this->reply = new RateService\Request('../src/OfficeBrain/Bundle/ShippingEstimatorBundle/wsdl/RateService_v9.wsdl'); // test mode
		$this->reply = new RateService\Request('../src/OfficeBrain/Bundle/ShippingEstimatorBundle/wsdl/RateService_v16.wsdl'); // production/live mode 
		$this->result=$this->reply->getGetRatesReply($this->rateRequest);
		$this->response=$this->formateRateFedexForShippingDetail($this->result);
		
		return $this->response;
	}
	
	public function callRequestMobileApi($shippingEstiDetail,$shippinEstiConfi)
	{
		$this->rateRequest = new ComplexType\RateRequest();
		$ObjFedex = new FedexHelper('rate',$shippinEstiConfi);
		
		
		//WebAuthenticationDetail
		$webAuthenticationDetail=$ObjFedex->setAuthenticationDetail();
		$this->rateRequest->setWebAuthenticationDetail($webAuthenticationDetail);
		
		//$this->setRateReplyDetail();
		
		//ClientDetail
		$clientDetail=$ObjFedex->setClientDetail();
		$this->rateRequest -> setClientDetail($clientDetail);
		
		//TransactionDetail
		$transactionDetail=$ObjFedex->setTransaction();
		$this->rateRequest->setTransactionDetail($transactionDetail);
		
		//Version
		$version=$ObjFedex->setVersionDetail();
		$this->rateRequest->setVersion($version);
		
		//ReturnTransitAndCommit
		$this->rateRequest->setReturnTransitAndCommit(true);
		$this->requestedShipment=$ObjFedex->setShipmentDetail($shippingEstiDetail);
		$this->rateRequest->setRequestedShipment($this->requestedShipment);
		
		$this->reply = new RateService\Request('../src/OfficeBrain/Bundle/ShippingEstimatorBundle/wsdl/RateService_v9.wsdl'); // test mode
		//$this->reply = new RateService\Request('../src/OfficeBrain/Bundle/ShippingEstimatorBundle/wsdl/RateService_v16.wsdl'); // production mode
		$this->result=$this->reply->getGetRatesReply($this->rateRequest);
		
		$this->response=$this->formateRateFedexForMobileApi($this->result);
		
		return $this->response;
	}
	
	
	public function formateRateFedexForShippingDetail($result)
	{
		$data=  array();
		$this->shippinEstiConfi = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['fedex']['option']['fedex_rate']['option'];
		$currentDate = Date('Y-m-d');
		if(isset($result->RateReplyDetails))
		{
			$rateReply=$result->RateReplyDetails;
			if(is_array($rateReply))
			{
				$count=count(($rateReply));
				for($i=0;$i<$count;$i++)
				{
					$resultArray[$i]['ServiceType']=$rateReply[$i]->ServiceType;
					$resultArray[$i]['CommitDetails']=$rateReply[$i]->CommitDetails;
			    	$resultArray[$i]['ActualRateType']=$rateReply[$i]->ActualRateType;
		    		$resultArray[$i]['SignatureOption']=$rateReply[$i]->SignatureOption;
					$shipmentarray=$rateReply[$i]->RatedShipmentDetails;
					$resultArray[$i]['ShipmentRateDetail']['RateType']=$shipmentarray[0]->ShipmentRateDetail->RateType;
					$resultArray[$i]['ShipmentRateDetail']['TotalNetCharge']=$shipmentarray[0]->ShipmentRateDetail->TotalNetCharge;
					$fedexAccountPrice =$shipmentarray[0]->ShipmentRateDetail->TotalNetCharge->Amount; // PAYOR_ACCOUNT_PACKAGE use to get your price of fedex account
					$fedexBasePrice =$shipmentarray[0]->ShipmentRateDetail->TotalBaseCharge->Amount;
					if($resultArray[$i]['ServiceType']=='FEDEX_GROUND')
					{
						$count=count($rateReply[$i]->RatedShipmentDetails);
						for($m=0;$m<$count;$m++)
						{
							$ratetype=$shipmentarray[$m]->ShipmentRateDetail->RateType;
							if ($ratetype=='PAYOR_ACCOUNT_PACKAGE') // use to get public rate
							//if ($ratetype=='PAYOR_LIST_PACKAGE') 
							{
								$fedexPublicPrice=$shipmentarray[$m]->ShipmentRateDetail->TotalNetCharge->Amount;
								$transitTime = 5; // need to change this right now static because time stamp is in word
							}
						}
					}
					else
					{
						$DeliveryTimestamp=$rateReply[$i]->DeliveryTimestamp;
						$DeliveryTimestampDate= explode('T',$DeliveryTimestamp);
						// $fedexPublicPrice=$shipmentarray[count($shipmentarray)-1]->ShipmentRateDetail->TotalNetCharge->Amount; // if you want public rate then uncomment this. this is comment as manget client change
						$date1 = new DateTime($currentDate);
						$date2 = new DateTime($DeliveryTimestampDate[0]);
						$interval = $date1->diff($date2);
						$transitTime= $interval->format('%a');
					}
					//$finalPrice = $fedexPublicPrice;
					$finalPrice = $fedexAccountPrice;
	    			if($this->shippinEstiConfi['is_customer_price_margin']['status']==1)
	    			{
	    				$type=$this->shippinEstiConfi['is_customer_price_margin']['option']['type']['status']; // it can be percentage or flat
	    				$value=$this->shippinEstiConfi['is_customer_price_margin']['option']['amount']['status'];
	    				if($type=='percentage')
	    				{
	    					//$addOnPrice=($value / 100) * $fedexPublicPrice;
	    					//$finalPrice = $fedexPublicPrice+number_format($addOnPrice, 2);
	    					$addOnPrice=($value / 100) * $fedexAccountPrice;
	    					$shippingPrice = $fedexAccountPrice+number_format($addOnPrice, 2);
	    				}
	    				else
	    				{
	    					//$finalPrice = $fedexPublicPrice+$value;
	    					$shippingPrice = $fedexAccountPrice+$value;
	    				}
	    				
	    				if($shippingPrice>$fedexBasePrice)
	    				{
	    					$finalPrice = $fedexBasePrice;
	    				}
	    				else
	    				{
	    					$finalPrice = $shippingPrice;
	    				}
	    			}
	    			
	    			$data[$i]['method'] =str_replace('_', ' ', $resultArray[$i]['ServiceType']);
	    			$data[$i]['amount'] = round($finalPrice,2);
	    			$data[$i]['transitTime'] = $transitTime;
	    		}
			}
			else
			{
				$resultArray['ServiceType']=$rateReply->ServiceType;
    			$resultArray['CommitDetails']=$rateReply->CommitDetails;
    			$resultArray['ActualRateType']=$rateReply->ActualRateType;
    			$resultArray['SignatureOption']=$rateReply->SignatureOption;
    			$shipmentarray=$rateReply->RatedShipmentDetails;
    			$resultArray['ShipmentRateDetail']['RateType']=$shipmentarray[0]->ShipmentRateDetail->RateType;
    			$resultArray['ShipmentRateDetail']['TotalNetCharge']=$shipmentarray[0]->ShipmentRateDetail->TotalNetCharge;
				$amount=$shipmentarray[0]->ShipmentRateDetail->TotalNetCharge->Amount;
				$fedexBasePrice =$shipmentarray[count($shipmentarray)-1]->ShipmentRateDetail->TotalBaseCharge->Amount;
    			$fedexamount=$shipmentarray[count($shipmentarray)-1]->ShipmentRateDetail->TotalNetCharge->Amount;
    			if($this->shippinEstiConfi['is_customer_price_margin']['status']==1)
    			{
    				$type=$this->shippinEstiConfi['is_customer_price_margin']['option']['type']['status']; // it can be percentage or flat
					$value=$this->shippinEstiConfi['is_customer_price_margin']['option']['amount']['status'];
    				if($type=='percentage')
					{
						$addOnPrice=($value / 100) * $fedexamount;
    					$shippingPrice = $fedexamount+number_format($addOnPrice, 2);
    				}
    				else
    				{
    					$shippingPrice = $fedexamount+$value;
    				}
    				
    				if($shippingPrice>$fedexBasePrice)
    				{
    					$finalPrice = $fedexBasePrice;
    				}
    				else
    				{
    					$finalPrice = $shippingPrice;
    				}
    			}
    			$data[0]['method'] =str_replace('_', ' ', $resultArray['ServiceType']);
    			$data[0]['amount'] = round($finalPrice,2);
    			$data[0]['transitTime'] = 5;
			}
		}
		else
		{
			if(isset ($result->HighestSeverity) && ($result->HighestSeverity=='ERROR' || $result->HighestSeverity=='WARNING' ))
    		{
    			if( isset($result->Notifications->Message))
    			{
    				$data[0]['error_msg'] = $result->Notifications->Message;
    			}
    		}
    		else
    		{
    			$data[0]['error_msg'] = 'We are experiencing an issue, please check back later.';
    		}
		}
	return $data;
	}
	public function formateRateFedexForMobileApi($result)
	{
		$returnAry = array();
		$this->shippinEstiConfi = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['fedex']['option']['fedex_rate']['option'];
		if(isset($result->RateReplyDetails)){
			$rateReply=$result->RateReplyDetails;
			if(is_array($rateReply)){
				$count=count(($rateReply));
				for($i=0;$i<$count;$i++){
					$resultArray[$i]['ServiceType']=$rateReply[$i]->ServiceType;
					$resultArray[$i]['CommitDetails']=$rateReply[$i]->CommitDetails;
			    	$resultArray[$i]['ActualRateType']=$rateReply[$i]->ActualRateType;
		    		$resultArray[$i]['SignatureOption']=$rateReply[$i]->SignatureOption;
					$shipmentarray=$rateReply[$i]->RatedShipmentDetails;
					$resultArray[$i]['ShipmentRateDetail']['RateType']=$shipmentarray[0]->ShipmentRateDetail->RateType;
					$resultArray[$i]['ShipmentRateDetail']['TotalNetCharge']=$shipmentarray[0]->ShipmentRateDetail->TotalNetCharge;
					$fedexAccountPrice =$shipmentarray[0]->ShipmentRateDetail->TotalNetCharge->Amount; // PAYOR_ACCOUNT_PACKAGE use to get your price of fedex account
					if($resultArray[$i]['ServiceType']=='FEDEX_GROUND'){
						$count=count($rateReply[$i]->RatedShipmentDetails);
						for($m=0;$m<$count;$m++){
							$ratetype=$shipmentarray[$m]->ShipmentRateDetail->RateType;
							if ($ratetype=='PAYOR_LIST_PACKAGE') {// use to get public rate
								$fedexPublicPrice=$shipmentarray[$m]->ShipmentRateDetail->TotalNetCharge->Amount;
							}
						}
					}else{
						$fedexPublicPrice=$shipmentarray[count($shipmentarray)-1]->ShipmentRateDetail->TotalNetCharge->Amount;
					}
					$finalPrice = $fedexPublicPrice;
					if($this->shippinEstiConfi['is_customer_price_margin']['status']==1){
						$type=$this->shippinEstiConfi['is_customer_price_margin']['option']['type']['status']; // it can be percentage or flat
						$value=$this->shippinEstiConfi['is_customer_price_margin']['option']['amount']['status'];
						if($type=='percentage') {
							$addOnPrice=($value / 100) * $fedexPublicPrice;
							$finalPrice = $fedexPublicPrice+number_format($addOnPrice, 2);
						}else{
							$finalPrice = $fedexPublicPrice+$value;
						}
					}
					$returnAry [$resultArray[$i]['ServiceType']] =  "$".$finalPrice;					
				}
			} else {
				$resultArray['ServiceType']=$rateReply->ServiceType;
				$resultArray['CommitDetails']=$rateReply->CommitDetails;
				$resultArray['ActualRateType']=$rateReply->ActualRateType;
				$resultArray['SignatureOption']=$rateReply->SignatureOption;
				$shipmentarray=$rateReply->RatedShipmentDetails;
				$resultArray['ShipmentRateDetail']['RateType']=$shipmentarray[0]->ShipmentRateDetail->RateType;
				$resultArray['ShipmentRateDetail']['TotalNetCharge']=$shipmentarray[0]->ShipmentRateDetail->TotalNetCharge;
				$amount=$shipmentarray[0]->ShipmentRateDetail->TotalNetCharge->Amount;
				$fedexamount=$shipmentarray[count($shipmentarray)-1]->ShipmentRateDetail->TotalNetCharge->Amount;
				
				if($this->shippinEstiConfi['is_customer_price_margin']['status']==1){
					$type=$this->shippinEstiConfi['is_customer_price_margin']['option']['type']['status']; // it can be percentage or flat
					$value=$this->shippinEstiConfi['is_customer_price_margin']['option']['amount']['status'];
					if($type=='percentage') {
						$addOnPrice=($value / 100) * $fedexamount;
						$finalPrice = $fedexamount+number_format($addOnPrice, 2);
					} else {
						$finalPrice = $fedexamount+$value;
					}
				}
				$returnAry [$resultArray['ServiceType']] =  "$".$finalPrice;
			}
		}
		
		return $returnAry;
	}
}