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

use OfficeBrain\Bundle\ShippingEstimatorBundle\Manager\AbstractManager\ShippingEstimatorAbstract;
use OfficeBrain\Bundle\ShippingEstimatorBundle\Manager\Service\ShippingEstimatorService;
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 RateLoomisExpressExtended extends ShippingEstimatorAbstract
{

	public $soapApi;
	
	public function __construct($entityManager, $request, $session, $productDetailService, $soapManager) {
		parent::__construct($entityManager, $request, $session, $productDetailService);
		$this->soapApi = $soapManager;
	}
		
	public function __destruct() {
		parent::__destruct();
	}
	
	public function getProductDetailForShipping($productId,$qty)
	{
		$productShippingDetail=parent::getProductDetailForShipping($productId,$qty);
		return $productShippingDetail;
	}
	
	public function callRequest($shippingEstiDetail, $shippingEstiConfi, $callFrom)
	{
		$soapRequestArray = $this->generateSoapRequest($shippingEstiDetail);
	
		$soapRequest = array_merge($soapRequestArray, array("Id" => $this->soapApi->getSoapParameter('loomis_express','soap_auth', 'svc', 'user'), "Password" => $this->soapApi->getSoapParameter('loomis_express','soap_auth', 'svc', 'password')));
		$this->soapApi->init('loomis_express_public_rate');
		$this->soapApi->setCallParameters($soapRequestArray);
		$this->soapApi->doProcess();
		if ($this->soapApi->isSuccess()) {
	
			$data = $this->soapApi->getResultArray();
			$apiResult = $this->soapApi->simpleXmlToArray($data);
			$errorDetail = $this->soapApi->getInnerArrayValue('ax29:error', $apiResult);
			if(is_array($errorDetail))
			{
				$responseArray = $this->soapApi->getInnerArrayValue('ax29:getRatesResult', $apiResult);
				if(count($responseArray)>0)
				{
					$result= $this->formatRateLoomisForShippingDetail($responseArray);
				}
				else
				{
					$result[0]['error_msg'] = 'We are experiencing an issue, please check back later.';
				}
			}
			else
			{
				$result[0]['error_msg'] = $errorDetail;
			}
		}
		else
		{
			$result[0]['error_msg'] = 'Loomis Express API is not working';
		}
		return $result;
	}
	
	public function formatRateLoomisForShippingDetail($responseArray)
	{
		$data = array();
		$this->shippinEstiConfi = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['ups']['option']['ups_rate']['option'];
		$quote_array =array();
		$i = 0;
		$tot_charge = 0;
		$transitTime = 0;
		foreach($responseArray as $quote)
		{
			$service_id = $quote['ax211:shipment']['ax211:service_type'];
			$tot_charge = $quote['ax211:shipment']['ax211:shipment_info_num'][1]['ax211:value'];
			if(!is_array($quote['ax211:shipment']['ax211:transit_time']))
			{
				$transitTime = $quote['ax211:shipment']['ax211:transit_time'];
			}
			$quote_array[$i]['price'] = $tot_charge;
			$quote_array[$i]['transitTime'] = $transitTime;
				
			switch ($service_id){
				case 'DD':
					$quote_array[$i]['method'] ='Loomis Ground';
					break;
				case 'D9':
					$quote_array[$i]['method'] ='Loomis Express 9:00';
					break;
				case 'DN':
					$quote_array[$i]['method'] ='Loomis Express 12:00';
					break;
				case 'DE':
					$quote_array[$i]['method'] ='Loomis Express 18:00';
					break;
				case 'WD':
					$quote_array[$i]['method'] ='WD';
					break;
				case 'WW':
					$quote_array[$i]['method'] ='WW';
					break;
				case 'WM':
					$quote_array[$i]['method'] ='WM';
					break;
				default:
					$quote_array[$i]['method'] = $service_id;
					break;
			}
			$i++;
		}
	
		if(is_array($quote_array))
		{
			$i=1;
			foreach ($quote_array as $key=>$value)
			{
				$lommisAmount=$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'];
						$lommisAmount = $value['price']+number_format($addOnPrice, 2);
					}
					else
					{
						$lommisAmount = $topValue+$value['price'];
					}
				}
				
				if($lommisAmount > 0)
				{
					$data[$i]['method'] = $value['method'];
					$data[$i]['amount'] = round($lommisAmount,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 generateSoapRequest($shippingEstiDetail)
	{
		$requestArray = array();
		$shipper = $shippingEstiDetail['shipper'];
		$reciver = $shippingEstiDetail['reciver'];
		$currentdate = date('Ymd'); 
		$weightArray = array();
		foreach ($shippingEstiDetail['totalWeight'] as $key=>$perboxWeight)
		{
			$weightArray[$key]['reported_weight'] =$perboxWeight;
		}
		
		$shipmentPackage = array();
	
		/*as fob is not proper we are using static data */
		$requestArrayFOB = array('shipment' => array(
												'courier' => 'L', // use to Courier Code L = Loomis Express. Static value.
												/*'delivery_city' => 'MISSISSAUGA',
												'delivery_country' => 'CA',
												'delivery_postal_code' => 'L5R3R3',
												'delivery_province' => 'ON',*/
												'delivery_city' => 'ATLANTA',
												'delivery_country' => 'US',
												'delivery_postal_code' => '30301',
												'delivery_province' => 'GA', 
												'dimension_unit' => 'I', // Unit of Measure of package dimensions I = Imperial M = Metric
												'pickup_city' => 'MISSISSAUGA',
												'pickup_postal_code' => 'L4W1E6',
												'pickup_province' => 'ON',
												'reported_weight_unit' => 'L', // Unit of Measure for weight L = Pounds K = Kilograms
												'service_type' => 'ALL',  //we want all shipping method so we will pass ALL
												'shipping_date' => $currentdate,
												//'packages' => array(0=>array('reported_weight'=>28),1 => array('reported_weight'=>17))
												'packages'=>$weightArray
										));
		
		$requestArray = array('shipment' => array(
												'courier' => 'L', // use to Courier Code L = Loomis Express. Static value.
												'delivery_city' => $reciver['userCity'],
												'delivery_country' => $reciver['userCountry'],
												'delivery_postal_code' => str_replace(' ','',$reciver['userZip']),
												'delivery_province' => $reciver['userState'],
												'dimension_unit' => 'I', // Unit of Measure of package dimensions I = Imperial M = Metric
												'pickup_city' => $shipper['shipperCity'],
												'pickup_postal_code' => str_replace(' ','',$shipper['shipperZip']),
												'pickup_province' => $shipper['shipperState'],
												'reported_weight_unit' => 'L', // Unit of Measure for weight L = Pounds K = Kilograms
												'service_type' => 'ALL',  //we want all shipping method so we will pass ALL
												'shipping_date' => $currentdate,
												'packages'=>$weightArray
									));
		return $requestArray;
	}
}