<?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;


Class ShipUPSExtended 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)
	{
		$ObjFedex = new UPSHelper('ship',$shippingEstiConfi);
		$webAuthenticationDetail=$ObjFedex->setAuthenticationDetail();
		$shipRequest=$ObjFedex->setShipRequestDetail($shippingEstiDetail,$shippingEstiConfi);
		$shipreq = $webAuthenticationDetail.$shipRequest;

		$data = shell_exec('/usr/bin/curl -k -d '.escapeshellarg($shipreq).' https://onlinetools.ups.com/ups.app/xml/ShipConfirm ');
		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;

		$label =$webAuthenticationDetail."
				<?xml version=\"1.0\" ?>
				<ShipmentAcceptRequest>
				    <Request>
				        <RequestAction>ShipAccept</RequestAction>
				    </Request>
				    <ShipmentDigest>".$xml_data['RatingServiceSelectionResponse']['ShipmentDigest']."</ShipmentDigest>
				</ShipmentAcceptRequest>
				";
		
		$xmlLabel = shell_exec('/usr/bin/curl -k -d '.escapeshellarg($label).' https://onlinetools.ups.com/ups.app/xml/ShipAccept ');
		preg_match_all( "/\<ShipmentAcceptResponse\>(.*?)\<\/ShipmentAcceptResponse\>/s",$xmlLabel, $bookblocks );
		foreach( $bookblocks[1] as $block )
		{
			preg_match_all( "/\<GraphicImage\>(.*?)\<\/GraphicImage\>/",$block, $author ); // GET LABEL
			preg_match_all( "/\<TrackingNumber\>(.*?)\<\/TrackingNumber\>/",$block, $tracking ); // GET TRACKING NUMBER
		}
		
		$trackingNo= $tracking[1][0];
		$filename='../web/upsShipLabel/shiplabel'.'_'.date('mdYhis').'gif';
		$ifp = fopen($filename, "wb"); 
	    fwrite($ifp, base64_decode($author[1][0])); 
	    fclose($ifp); 

		return '<a href="../../'.$filename.'">UPS Label</a> and tracking no : '.$trackingNo;
	}
}