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

use OfficeBrain\Bundle\ShippingEstimatorBundle\Manager\AbstractManager\ShippingEstimatorAbstract;
use OfficeBrain\Bundle\ShippingEstimatorBundle\Manager\Service\ShippingEstimatorService;
use OfficeBrain\Bundle\ShippingEstimatorBundle\Helper\UPSHelper;
use OfficeBrain\Bundle\ShippingEstimatorBundle\Helper\UPSOAuthHelper;

Class RateUPSExtended 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,$shippingEstiConfi,$callFrom,$xml=false)
	{
		if($xml){
			$ObjUPS = new UPSHelper('rate',$shippingEstiConfi);
			$webAuthenticationDetail=$ObjUPS->setAuthenticationDetail();
			$rateRequest=$ObjUPS->setRateRequestDetail($shippingEstiDetail,$shippingEstiConfi);
			$ratereq = $webAuthenticationDetail.$rateRequest;
			
			$data = shell_exec('/usr/bin/curl -k -d '.escapeshellarg($ratereq).' https://onlinetools.ups.com/ups.app/xml/Rate ');
			if(substr($data, 0, 5) == "<?xml") {
				$main_heading = '';
				$deXml = simplexml_load_string($data);
				$deJson = json_encode($deXml);
				$xml_array = json_decode($deJson,TRUE);
			}
			$xml_data['RatingServiceSelectionResponse'] = $xml_array;
			$result=$this->formatRateUPSForShippingDetail($xml_data);
		}else{

			$ObjUPS = new UPSOAuthHelper('rate',$shippingEstiConfi);
			$token = $ObjUPS->getOAuth2Token();
			if(isset($token['access_token'])){
				$rateRequest=$ObjUPS->setRateRequestDetail($shippingEstiDetail,$shippingEstiConfi);
				$rates = $ObjUPS->getRates($token['access_token'],$rateRequest);
				$result=$this->formatRateUPSForShippingDetailOAuthReponse($rates);
			}else{
				$data['error']="Invalid access token";
				$result=$this->formatRateUPSForShippingDetailOAuthReponse($data);
			}
		}
		return $result;
	}
	
	public function callRequestMobileApi($shippingEstiDetail,$shippingEstiConfi)
	{
		$ObjUPS = new UPSHelper('rate',$shippingEstiConfi);
		$webAuthenticationDetail=$ObjUPS->setAuthenticationDetail();
		$rateRequest=$ObjUPS->setRateRequestDetail($shippingEstiDetail,$shippingEstiConfi);
		$ratereq = $webAuthenticationDetail.$rateRequest;
		$data = shell_exec('/usr/bin/curl -k -d '.escapeshellarg($ratereq).' https://onlinetools.ups.com/ups.app/xml/Rate ');
		if(substr($data, 0, 5) == "<?xml") {
			$main_heading = '';
			$deXml = simplexml_load_string($data);
			$deJson = json_encode($deXml);
			$xml_array = json_decode($deJson,TRUE);
		}
		$xml_data['RatingServiceSelectionResponse'] = $xml_array;
				
		$result=$this->formatRateUPSForMobileApi($xml_data);
		
		return $result;
	}
	
	public function formatRateUPSForShippingDetail($quote)
	{
		$data = array();
		$this->shippinEstiConfi = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['ups']['option']['ups_rate']['option'];
		$this->isDisplayNegositionRate = $this->shippinEstiConfi['is_display_negotiation_rate']['status'];
		$quote_array =array();
		$i = 0;
		$tot_charge = 0;
		$transitTime = 0;
	
		if(array_key_exists('RatedShipment',$quote['RatingServiceSelectionResponse']))
		{
			reset($quote['RatingServiceSelectionResponse']['RatedShipment']);
			$firstKey = key($quote['RatingServiceSelectionResponse']['RatedShipment']);
			if($firstKey == '0')
			{
				foreach($quote['RatingServiceSelectionResponse']['RatedShipment'] as $key){
						
					$service_id = $quote['RatingServiceSelectionResponse']['RatedShipment'][$i]['Service']['Code'];
					$tot_charge = $quote['RatingServiceSelectionResponse']['RatedShipment'][$i]['TotalCharges']['MonetaryValue'];
					if($this->isDisplayNegositionRate == 1)
					{
						if(key_exists('NegotiatedRates',$quote['RatingServiceSelectionResponse']['RatedShipment'][$i]))
						{
							// if client wants to display nagotioan price which is provided by UPS special to that shipper account number
							$tot_charge = $quote['RatingServiceSelectionResponse']['RatedShipment'][$i]['NegotiatedRates']['NetSummaryCharges']['GrandTotal']['MonetaryValue'];
						}
						else
						{
							$tot_charge = $quote['RatingServiceSelectionResponse']['RatedShipment'][$i]['TotalCharges']['MonetaryValue'];
						}
					}
					if(!is_array($quote['RatingServiceSelectionResponse']['RatedShipment'][$i]['GuaranteedDaysToDelivery']))
					{
						$transitTime = $quote['RatingServiceSelectionResponse']['RatedShipment'][$i]['GuaranteedDaysToDelivery'];
					}
					$quote_array[$i]['price'] = $tot_charge;
					$quote_array[$i]['transitTime'] = $transitTime;
						
					switch ($service_id){
						case '03':
							$quote_array[$i]['method'] ='UPS Ground';
							$quote_array[$i]['transitTime'] = 5; // as ups api is not returing transit time so set 5 days
							break;
						case '12':
							$quote_array[$i]['method'] ='UPS 3 Day Select';
							break;
						case '02':
							$quote_array[$i]['method'] ='UPS 2nd Day Air';
							break;
						case '01':
							$quote_array[$i]['method'] ='Next Day Air';
							break;
						case '59':
							$quote_array[$i]['method'] ='2nd Day Air AM';
							break;
						case '13':
							$quote_array[$i]['method'] ='Next Day Air Saver';
							break;
						case '14':
							$quote_array[$i]['method'] ='UPS Next Day Air Early AM';
							break;
						case '07':
							$quote_array[$i]['method'] ='UPS Worldwide Express';
							break;
						case '08':
							$quote_array[$i]['method'] ='Worldwide Expedited';
							break;
						case '11':
							$quote_array[$i]['method'] ='UPS Standard';
							break;
						case '65':
							$quote_array[$i]['method'] ='UPS World Wide Saver';
							break;
						case '54':
							$quote_array[$i]['method'] ='UPS Worldwide Express Plus';
							break;
					}
						
					$i++;
				}
			}
			else
			{
				$i =0;
				$service_id = $quote['RatingServiceSelectionResponse']['RatedShipment']['Service']['Code'];
				if($this->isDisplayNegositionRate == 1)
				{
					if(key_exists('NegotiatedRates',$quote['RatingServiceSelectionResponse']['RatedShipment'][$i]))
					{
						$tot_charge = $quote['RatingServiceSelectionResponse']['RatedShipment']['NegotiatedRates']['NetSummaryCharges']['GrandTotal']['MonetaryValue'];
					}
					else 
					{
						$tot_charge = $quote['RatingServiceSelectionResponse']['RatedShipment']['TotalCharges']['MonetaryValue'];
					}
				}
				else
				{
					$tot_charge = $quote['RatingServiceSelectionResponse']['RatedShipment']['TotalCharges']['MonetaryValue'];
				}
				if(!is_array($quote['RatingServiceSelectionResponse']['RatedShipment']['GuaranteedDaysToDelivery']))
				{
					$transitTime = $quote['RatingServiceSelectionResponse']['RatedShipment']['GuaranteedDaysToDelivery'];
				}
				$quote_array[$i]['price'] = $tot_charge;
				$quote_array[$i]['transitTime'] = $transitTime;
				
				switch ($service_id){
					case '03':
						$quote_array[$i]['method'] ='UPS Ground';
						$quote_array[$i]['transitTime'] = 5; // as ups api is not returing transit time so set 5 days
						break;
					case '12':
						$quote_array[$i]['method'] ='UPS 3 Day Select';
						break;
					case '02':
						$quote_array[$i]['method'] ='UPS 2nd Day Air';
						break;
					case '01':
						$quote_array[$i]['method'] ='Next Day Air';
						break;
					case '59':
						$quote_array[$i]['method'] ='2nd Day Air AM';
						break;
					case '13':
						$quote_array[$i]['method'] ='Next Day Air Saver';
						break;
					case '14':
						$quote_array[$i]['method'] ='UPS Next Day Air Early AM';
						break;
					case '07':
						$quote_array[$i]['method'] ='UPS Worldwide Express';
						break;
					case '08':
						$quote_array[$i]['method'] ='Worldwide Expedited';
						break;
					case '11':
						$quote_array[$i]['method'] ='UPS Standard';
						break;
					case '65':
						$quote_array[$i]['method'] ='UPS World Wide Saver';
						break;
					case '54':
						$quote_array[$i]['method'] ='UPS Worldwide Express Plus';
						break;
				}
			}
		}
		if(is_array($quote_array))
		{
			$i=1;
			foreach ($quote_array as $key=>$value)
			{
				$upsAmount=$value['price'];
				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
					$topValue=$this->shippinEstiConfi['is_customer_price_margin']['option']['amount']['status'];
					if($type=='percentage')
					{
						$addOnPrice=($topValue / 100) * $value['price'];
						$upsAmount = $value['price']+number_format($addOnPrice, 2);
					}
					else
					{
						$upsAmount = $topValue+$value['price'];
					}
				}
				/*if(isset($value['method']))
				{
					$data .= "<li data-service='".$value['method']."'  data-value='".round($upsAmount,2)."'  data-transit-time='".$value['transitTime']."'><a href='javascript:void(0)'>".$value['method'];
					$data .= " $". round($upsAmount,2) ."</a></li>";
				}*/
				
				$data[$i]['method'] = $value['method'];
				$data[$i]['amount'] = round($upsAmount,2);
				$data[$i]['transitTime'] = $value['transitTime'];
				$i++;
			}
		}
		else
		{
			$data[0]['error_msg'] ='We are experiencing an issue, please check back later.';
		}
		return $data;
	}
	
	public function formatRateUPSForShippingDetailOAuthReponse($result)
	{
		if(isset($result['error'])){
			//$data="<li style='color:red;'>".$result['error']."</li>";
			return array('status'=>'error','error'=>'other','error_msg'=>$result['error']);
		}else{
			if(isset($result['response']['errors']))
			{
				return array('status'=>'error','error'=>'other','error_msg'=>$result['response']['errors'][0]['message']);
			}else{
				$data="<li style='color:red;'>We are experiencing an issue, please check back later.</li>";
			}
			if(isset($result['RateResponse']))
			{
				//print_r($result); die;
				$this->shippinEstiConfi = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['ups']['option']['ups_rate']['option'];
				$this->isDisplayNegositionRate = $this->shippinEstiConfi['is_display_negotiation_rate']['status'];
				$data=array();
				$quote_array =array();
				$i = 0;
				$tot_charge = 0;
				if(array_key_exists('RatedShipment',$result['RateResponse']))
				{	

					foreach ($result['RateResponse']['RatedShipment'] as $shipment) {
					
					$service_id =$shipment['Service']['Code'];
					$tot_charge = $shipment['TotalCharges']['MonetaryValue'];
					if($this->isDisplayNegositionRate == 1)
					{
						if(key_exists('NegotiatedRateCharges',$shipment))
						{
							// if client wants to display nagotioan price which is provided by UPS special to that shipper account number
							$tot_charge = $shipment['NegotiatedRateCharges']['TotalCharge']['MonetaryValue'];
						}
					}
					if(key_exists('GuaranteedDelivery',$result['RateResponse']['RatedShipment'])){
						$transitTime = $shipment['GuaranteedDelivery']['BusinessDaysInTransit'];
					}
					$quote_array[$i]['price'] = $tot_charge;
					$quote_array[$i]['transitTime'] = $transitTime;
					switch ($service_id){
					case '03':
						$quote_array[$i]['method'] ='UPS Ground';
						$quote_array[$i]['transitTime'] = 5; // as ups api is not returing transit time so set 5 days
						break;
					case '12':
						$quote_array[$i]['method'] ='UPS 3 Day Select';
						break;
					case '02':
						$quote_array[$i]['method'] ='UPS 2nd Day Air';
						break;
					case '01':
						$quote_array[$i]['method'] ='Next Day Air';
						break;
					case '59':
						$quote_array[$i]['method'] ='2nd Day Air AM';
						break;
					case '13':
						$quote_array[$i]['method'] ='Next Day Air Saver';
						break;
					case '14':
						$quote_array[$i]['method'] ='UPS Next Day Air Early AM';
						break;
					case '07':
						$quote_array[$i]['method'] ='UPS Worldwide Express';
						break;
					case '08':
						$quote_array[$i]['method'] ='Worldwide Expedited';
						break;
					case '11':
						$quote_array[$i]['method'] ='UPS Standard';
						break;
					case '65':
						$quote_array[$i]['method'] ='UPS World Wide Saver';
						break;
					case '54':
						$quote_array[$i]['method'] ='UPS Worldwide Express Plus';
						break;
					}
					$i++;
				}	
					if(is_array($quote_array))
					{
						$i=0;
						foreach ($quote_array as $key=>$value)
						{
							$upsAmount=$value['price'];
							if($this->shippinEstiConfi['is_customer_price_margin']['status']==1) // 1 or 0
							{
								
								$type=$this->shippinEstiConfi['is_customer_price_margin']['option']['type']['status']; // it can be percentage or flat
									$topValue = $this->shippinEstiConfi['is_customer_price_margin']['option']['amount']['status']/100;
									if($type=='percentage')
									{
										//$addOnPrice=($topValue / 100) * $value['price'];
										//$upsAmount = $value['price']+number_format($addOnPrice, 2);
										
										$markupPrice=(1-$topValue);
										$addOnPrice = 1/$markupPrice;
										$addOnPrice = number_format($addOnPrice, 4);
										$upsAmount = $value['price']*$addOnPrice;
									}
									else
									{
										$upsAmount = $topValue+$value['price'];
									}
							}
							/*if(isset($value['method']))
							{
								$data .= "<li data-service='".$value['method']."'  data-value='".round($upsAmount,2)."'  data-transit-time='".$value['transitTime']."'><a href='javascript:void(0)'>".$value['method'];
								$data .= " $". round($upsAmount,2) ."</a></li>";
							}*/
							
							if (is_array($value) && isset($value['method'])) {
								$data[$i]['method'] = $value['method'];
								$data[$i]['amount'] = round($upsAmount,2);
								$data[$i]['transitTime'] = $value['transitTime'];
								$i++;
							}
						}
					}
				}
			}
			
		}
		return $data;
	}
	
	public function formatRateUPSForMobileApi($quote)
	{		
		$this->shippinEstiConfi = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['ups']['option']['ups_rate']['option'];
		$quote_array =array();
		$i = 0;
		foreach($quote['RatingServiceSelectionResponse']['RatedShipment'] as $key){
		
			$service_id = $quote['RatingServiceSelectionResponse']['RatedShipment'][$i]['Service']['Code'];
			$tot_charge = $quote['RatingServiceSelectionResponse']['RatedShipment'][$i]['TotalCharges']['MonetaryValue'];
		
			switch ($service_id){
				case '03':
					$quote_array['UPS Ground'] = $tot_charge;
					break;
				case '12':
					$quote_array['UPS 3 Day Select'] = $tot_charge;
					break;
				case '02':
					$quote_array['UPS 2nd Day Air'] = $tot_charge;
					break;
				case '01':
					$quote_array['Next Day Air'] = $tot_charge;
					break;
				case '59':
					$quote_array['2nd Day Air AM'] = $tot_charge;
					break;
				case '13':
					$quote_array['Next Day Air Saver'] = $tot_charge;
					break;
				case '14':
					$quote_array['UPS Next Day Air Early AM'] = $tot_charge;
					break;
				case '07':
					$quote_array['UPS Worldwide Express'] = $tot_charge;
					break;
				case '08':
					$quote_array['UPS Worldwide Expedited'] = $tot_charge;
					break;
				case '11':
					$quote_array['UPS Standard'] = $tot_charge;
					break;
		
			}
		
			$i++;
		}
		$returnAry = array();
		if(is_array($quote_array))
		{
			
			foreach ($quote_array as $key=>$value)
			{
				$upsAmount=$value;
				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
					$topValue=$this->shippinEstiConfi['is_customer_price_margin']['option']['amount']['status'];
					if($type=='percentage') 
					{
						$addOnPrice=($topValue / 100) * $value;
						$upsAmount = $value+number_format($addOnPrice, 2);
					}
					else 
					{
						$upsAmount = $topValue+$value;
					}
				}
				$returnAry[$key] = "$". round($upsAmount,2) ;
			}
		}
		return $returnAry;
	}	
}
