<?php
namespace  OfficeBrain\Bundle\ShippingEstimatorBundle\Helper;
use OfficeBrain\Bundle\ShippingEstimatorBundle\Manager\AbstractManager\ShippingEstimatorAbstract;
use Symfony\Component\Yaml\Parser;


class UPSOAuthHelper extends ShippingEstimatorAbstract
{
	public function __construct($type,$shippinEstiConfi){
		
		$yaml = new Parser();
		$this->upsConfig = $yaml->parse(file_get_contents(__DIR__.'/../Resources/config/ups_oauth_config.yml'));
		$this->environment = $this->upsConfig['parameters']['environment'];
		$this->credential = $this->upsConfig['parameters'][$this->environment];
		$this->type = $type;
	}
	
	public function getOAuth2Token()
	{
		if (
        isset($_SESSION['ups_access_token'], $_SESSION['ups_token_expiry']) &&
        time() < $_SESSION['ups_token_expiry']
	    ) {
	        return $_SESSION['ups_access_token'];
	    }

		$endpoint = $this->credential['url'].'/security/v1/oauth/token';
		$credential = $this->credential['client_id'].':'.$this->credential['client_secret'];
		$encodedCredential =  base64_encode($credential);
		$method = 'POST';
		$payload = "grant_type=client_credentials";
		$header  = array(
			"Content-Type: application/x-www-form-urlencoded",
		    "Authorization: Basic " . $encodedCredential
		);
		$token = $this->callApi($endpoint,$method,$payload,$header);
		//return json_decode($token,true);

		$_SESSION['ups_access_token'] = json_decode($token,true);
    	$_SESSION['ups_token_expiry'] = time() + 3600;
    	return $_SESSION['ups_access_token'];
	}

	public function getRates($token,$payload){
		$endpoint = $this->credential['url'].'/api/rating/v2409/Shop';
		$method = 'POST';
		$header  = array(
			"Content-Type: application/json",
		    "Authorization: Bearer " . $token,
		);
		$rates = $this->callApi($endpoint,$method,$payload,$header);
		return json_decode($rates,true);
	}

	private function callApi($endpoint,$method,$payload,$header)
	{

		$curl = curl_init();

		$curlOptions = array(
		  CURLOPT_URL => $endpoint,
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => '',
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 0,
		  CURLOPT_FOLLOWLOCATION => true,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => $method,
		  CURLOPT_HTTPHEADER => $header
		);
		if($method=="POST"){
			$curlOptions[CURLOPT_POSTFIELDS] = $payload;
		}
		curl_setopt_array($curl, $curlOptions);
		$response = curl_exec($curl);
		curl_close($curl);
		return $response;
	}
	
	public function setRateRequestDetail($shippingEstiDetail,$shippingEstiConfi)
	{
		$package=array();
		//print_r($shippingEstiConfi); die;
		for($i=0;$i<$shippingEstiDetail['noOfBox'];$i++)
		{
			$packageDetail=array();
			$packageDetail['PackagingType']['Code'] = '02';//$shippingEstiConfi['packing_type']['status'];
			$packageDetail['PackagingType']['Description'] = 'Package';
			if($shippingEstiDetail['cartonLength']!=0 && $shippingEstiDetail['cartonWidth']!=0 && $shippingEstiDetail['cartonWidth']!=0)
			{
				$packageDetail['Dimensions']['UnitOfMeasurement']['Code']='IN'; //CM
				$packageDetail['Dimensions']['Length']=(string) round($shippingEstiDetail['cartonLength'],2);
				$packageDetail['Dimensions']['Width']=(string)round($shippingEstiDetail['cartonWidth'],2);
				$packageDetail['Dimensions']['Height']=(string)round($shippingEstiDetail['cartonHeight'],2);
			}
			$packageDetail['PackageWeight']['UnitOfMeasurement']['Code'] = 'LBS';
			$packageDetail['PackageWeight']['Weight'] = (string) $shippingEstiDetail['totalWeight'][$i];
			$package[] = $packageDetail;
		}
		 $rateRequest = [
            'RateRequest' => [
                'Request' => [
                    'RequestOption' => 'Shop',
                    'TransactionReference' => [
                        'CustomerContext' => 'Get all services'
                    ]
                ],
                'PickupType' => [
					'Code' => $shippingEstiConfi['pickup_type']['status']
                ],
                'CustomerClassification' => [
					'Code' => $shippingEstiConfi['customer_classification']['status'] //00
                ],
                'Shipment' => [
                    'Shipper' => [
                        'Name' => 'ShipperName',
                        'ShipperNumber'=>$this->credential['billing_account_no'],
                        'Address' => [
                            'StateProvinceCode' => $shippingEstiDetail['shipper']['shipperState'],
                            'PostalCode' => $shippingEstiDetail['shipper']['shipperZip'],
                            'CountryCode' => $shippingEstiDetail['shipper']['shipperCountry']
                        ]
                    ],
                    'ShipTo' => [
                        'Name' => 'Recipient',
                        'Address' => [
                            'StateProvinceCode' => $shippingEstiDetail['reciver']['userState'],
                            'PostalCode' => $shippingEstiDetail['reciver']['userZip'], //'35203'
                            'CountryCode' => $shippingEstiDetail['reciver']['userCountry']
                        ]
                    ],
                    'ShipFrom' => [
                        'Name' => 'ShipperName',
                        'Address' => [
                            'StateProvinceCode' => $shippingEstiDetail['shipper']['shipperState'],
                            'PostalCode' => $shippingEstiDetail['shipper']['shipperZip'],
                            'CountryCode' => $shippingEstiDetail['shipper']['shipperCountry']
                        ]
                    ],
                    'ShipmentRatingOptions' => [
                    	'NegotiatedRatesIndicator' => 'Y',
                    	'TPFCNegotiatedRatesIndicator' => 'Y'
                    ],
                    'Package' => $package
                ]
            ]
        ];
		//echo "<pre>"; print_r($rateRequest); die; 
		//echo json_encode($rateRequest); die;
		return json_encode($rateRequest);
	}

}
