<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/
//
//$Id: eWayModel.php, v 1.0 2011/06/14 20:52:11

//
class fedex extends CartModel
{
	public function __construct ()
	{
		parent::__construct();
		$ObjShippingMethod		= new ShippingmethodModel();
		$this->_key				= $ObjShippingMethod->getShippingSettingsByKey('fedex','fedex_key');
		$this->_password		= $ObjShippingMethod->getShippingSettingsByKey('fedex','fedex_password');
		$this->_accNumber		= $ObjShippingMethod->getShippingSettingsByKey('fedex','fedex_account_no');
		$this->_meterNumber		= $ObjShippingMethod->getShippingSettingsByKey('fedex','fedex_meter_no');
	} 
	
	public function getShippingRate($shippingParams,$type='list',$section='cart')
	{
	$taxAmount			= 0;
	$shippingCharge 	= 0;
	$extraCharge 		= 0;
	$maxQtyPerShipping 	= 0;
	$shippingStateSelectedType 	= (trim(stripslashes(isset($shippingProvince)!=''))) ? 'province' : 'state' ;

		extract($shippingParams);
		$ObjCountry			= new CountryModel();
		$ObjState			= new StateModel();
		$ObjShippingMethod 	= new ShippingmethodModel();
		$ObjProduct			= new ProductModel();
		$languageIDs['Current']	= 1;
		if(empty($shippingParams['orderExtraData']))
		{
			$resCartDetails	= $this->getCartDetails($cartID);
			$resCartItemDetails	= $this->getCartItemDimensions($cartID,$productID);
		}
		else
		{
			$resCartDetails['extra']	= $shippingParams['orderExtraData'];
			$resCartItemDetails		= $shippingParams['measurementDetails'];
		}
		$resCartItemDetails = extract(unserialize($resCartItemDetails));
		$measurementLength	= (isset($measurementLength))?$measurementLength:4;
		$measurementWeight	= (isset($measurementWeight))?$measurementWeight:6;
		$measurementLength	= $this->productSizeToUnit($measurementLength);
		$measurementWeight	= $this->productSizeToUnit($measurementWeight);
		$packageLength	= (isset($packageLength))?$packageLength:1;
		$packageWidth	= (isset($packageWidth))?$packageWidth:1;
		$packageHeight	= (isset($packageHeight))?$packageHeight:1;
		$packageWeight	= (isset($packageWeight))?$packageWeight:1;
		// Converting to CM
		if($measurementLength == 'mm')
		{
			$packageLength 	= ($packageLength * $orderItemQuantity) / 10;
			$packageWidth	= ($packageWidth * $orderItemQuantity) / 10;
			$packageHeight	= ($packageHeight * $orderItemQuantity) / 10;
		}
		else if ($measurementLength == 'Inch')
		{
			$packageLength 	= $packageLength * $orderItemQuantity * 2.54 ;
			$packageWidth	= $packageWidth * $orderItemQuantity * 2.54;
			$packageHeight	= $packageHeight * $orderItemQuantity * 2.54;
		}
		else if ($measurementLength == 'ft')
		{
			$packageLength 	= $packageLength * $orderItemQuantity * 30.48;
			$packageWidth	= $packageWidth * $orderItemQuantity * 30.48;
			$packageHeight	= $packageHeight * $orderItemQuantity * 30.48;
		}
		else if ($measurementLength == 'cm')
		{
			$packageLength 	= $packageLength * $orderItemQuantity ;
			$packageWidth	= $packageWidth * $orderItemQuantity ;
			$packageHeight	= $packageHeight * $orderItemQuantity ;
		}
		// Convert weight to KG
		if($measurementWeight == 'gm')
		{
			$packageWeight = $packageWeight * $orderItemQuantity / 1000;
		}
		else if($measurementWeight == 'Ounce')
		{
			$packageWeight = $packageWeight * $orderItemQuantity * 0.0283495;
		}
		else if($measurementWeight == 'Pound')
		{
			$packageWeight = $packageWeight * $orderItemQuantity * 0.453592;
		}
		else if($measurementWeight == 'Kg')
		{
			$packageWeight = $packageWeight * $orderItemQuantity ;
		}
		$resBasic	= $ObjProduct->getBasicByproductID($productID);

		$shipping_origin_type  	= $shippingSetting	= $resBasic['shippingSetting'];
		$BusinessID				= $resBasic['businessID'];

		if ($shippingSetting)
		  $ShipSettingManage=$shippingSetting;			 
		else{
		    
		     if ($shipping_origin_type=='biz')			      
		      {
			$ShipSettingManage="biz";
			}
		     else
		       {
			$ShipSettingManage="admin";
			}
		    
	 }
	 if($ShipSettingManage=='admin')
	 {
		$shipper = array(
		'Contact' => array(
			'PersonName' => 'ISPG ISPG',
			'CompanyName' => 'ISPG',
			'PhoneNumber' => '9012638716'
		),
		'Address' => array(
			'StreetLines' => array(''),
			'City' => $shippingParams['globalShippingCity'],
			'StateOrProvinceCode' => $ObjState->getStateShortNameByName($shippingParams['globalShippingState'],$languageIDs),
			'PostalCode' => $shippingParams['globalShippingZipcode'],
			'CountryCode' => $ObjCountry->getCountryCodeByName($shippingParams['globalShippingCountry'],$languageIDs)
		)
		);
	 }
	 else{
		
		$resBusLoc				= $ObjProduct->getShippingBusinessLocations($BusinessID,$languageIDs);
		if($resBusLoc[0]['locProvince'] != '')
			$extraDetails['userBillingAddress']['stateCode'] 	= $ObjState->getProvinceShortCode($resBusLoc[0]['locProvince']);
		else
			$shipperStateShortCode	= $ObjState->getStateShortNameByID($resBusLoc[0]['locStateID']);
		$shipper = array(
		'Contact' => array(
			'PersonName' => $resBusLoc[0]['locName'],
			'CompanyName' => $resBusLoc[0]['locName'],
			'PhoneNumber' => $resBusLoc[0]['locPhone']
		),
		'Address' => array(
			'StreetLines' => array($resBusLoc[0]['locAddress1'],$resBusLoc[0]['locAddress2']),
			'City' => $resBusLoc[0]['locCity'],
			'StateOrProvinceCode' => $shipperStateShortCode,
			'PostalCode' => $resBusLoc[0]['locZip'],
			'CountryCode' => $ObjCountry->getCountryCode($resBusLoc[0]['locCountryID'])
		)
		);
	 }
		$extraDetails	= unserialize($resCartDetails['extra']);
                
                if(!empty($extraDetails) && !array_key_exists('userBillingAddress', $extraDetails)) {
                    $extraDetails['userBillingAddress'] = array();                    
                } 
                if(empty($extraDetails['userBillingAddress'])) {
                    $extraDetails['userBillingAddress']['billingProvince'] = '';
                    $extraDetails['userBillingAddress']['billingState'] = '';
                    $extraDetails['userBillingAddress']['billingCountry'] = '';
                }
                
                 if(!empty($extraDetails) && !array_key_exists('userShippingAddress', $extraDetails)) {
                    $extraDetails['userShippingAddress'] = array();
                   
                }
                if(empty($extraDetails['userShippingAddress'])) {
                    $extraDetails['userShippingAddress']['shippingCountryID'] = '';
                    $extraDetails['userShippingAddress']['shippingFname'] = '';
                    $extraDetails['userShippingAddress']['shippingLname'] = '';
                    $extraDetails['userShippingAddress']['shippingAddress1'] = '';
                    $extraDetails['userShippingAddress']['shippingAddress2'] = '';
                    $extraDetails['userShippingAddress']['shippingCountry'] = '';
                    $extraDetails['userShippingAddress']['shippingCity'] = '';
                    $extraDetails['userShippingAddress']['shippingZip'] = '';
                    $extraDetails['userShippingAddress']['shippingProvince'] = '';
                    $extraDetails['userShippingAddress']['shippingStateID'] = '';
                }
                
		if(empty($extraDetails['userBillingAddress']['billingProvince']))
			$extraDetails['userBillingAddress']['stateCode'] 	= $ObjState->getStateShortNameByID($extraDetails['userBillingAddress']['billingState']);
		else
			$extraDetails['userBillingAddress']['stateCode'] 	= $ObjState->getProvinceShortCode($extraDetails['userBillingAddress']['billingProvince']);
		if($extraDetails['userShippingAddress']['shippingProvince'] == '')
			$extraDetails['userShippingAddress']['stateCode'] 	= $ObjState->getStateShortNameByID($extraDetails['userShippingAddress']['shippingStateID']);
		else
			$extraDetails['userShippingAddress']['stateCode'] 	= $ObjState->getProvinceShortCode($extraDetails['userShippingAddress']['shippingProvince']);

		$extraDetails['userBillingAddress']['countryCode']	= $ObjCountry->getCountryCode($extraDetails['userBillingAddress']['billingCountry']);
		$extraDetails['userShippingAddress']['countryCode']	= $ObjCountry->getCountryCode($extraDetails['userShippingAddress']['shippingCountryID']);

		$resShippingMethods	=	$this->listShippingMethodsByShippingService($productID,$settingsGroupID);

		$shippingTypeKey	= $ObjShippingMethod->getShippingServiceAndKey($resShippingMethods[0]['shippingtoproductID']);
		$shippingSettings	= $ObjShippingMethod->listShippingSettings($shippingTypeKey['shippingServiceID']);
		foreach($shippingSettings as $settings)
		{
			if($settings['settingKey'] == 'fedex_package')
				$packageType = $settings['settingValue'];
			if($settings['settingKey'] == 'fedex_drop_off_type')
				$dropOffType = $settings['settingValue'];
		}

		if(count($resShippingMethods)>0)
		{
			$shippingCharge 	= 99999999;
			$shippingTaxClassID	=0;
			foreach ($resShippingMethods as $key => $method)
        	{
				$shippingMethodsdeliveryZones = $this->listShippingMethodsDeliveryZones($method['shippingtoproductID'],$productID);
				if(count($shippingMethodsdeliveryZones)>0)
				{
					$deliveryZoneFound=false;
					foreach ($shippingMethodsdeliveryZones as $key1 => $zone)
					{
						$deliveryZoneDetails = $this->getDeliveryZoneDetails(array(),$zone['deliveryZoneID']);
						if(count($deliveryZoneDetails)>0)
						{
							foreach ($deliveryZoneDetails as $key1 => $zoneReg)
							{
								if($zoneReg['countryID']==$shippingCountryID &&  $shippingCountryID>0 )
								{
									if($zoneReg['StateID']==$shippingStateID && $shippingStateID>0)
									{
										if(($zoneReg['zipCodes']!='' || $zoneReg['isRange']=='Yes') && $shippingZip!='')
										{
											if($zoneReg['isRange']=='Yes')
											{
												if($shippingZip >= $zoneReg['rangeFrom'] && $shippingZip <= $zoneReg['rangeTo'])
												{
													$deliveryZoneFound=true;
													break;
												}
											}
											else if(substr($zoneReg['zipCodes'], -1)=='*')
											{
												$zipArray 			= explode('*',$zoneReg['zipCodes']);
												$startingZip		= $zipArray[0];
												$starting_str_len	= strlen($startingZip);
												$user_sub_zip		= substr($shippingZip,0,$starting_str_len);
												if($user_sub_zip==$startingZip)
												{
													$deliveryZoneFound=true;
													break;
												}
											}
											else
											{
												$zipArray = explode(',',$zoneReg['zipCodes']);
												if(in_array($shippingZip,$zipArray))
												{
													$deliveryZoneFound=true;
													break;
												}
											}
										}
										else if($zoneReg['zipCodes']=='')
										{
											$deliveryZoneFound=true;
											break;
										}
									}
									else if($shippingStateSelectedType=='province' && $zoneReg['zipCodes']!='' && $shippingZip!='')
									{
										$zipArray = explode(',',$zoneReg['zipCodes']);
										if(in_array($shippingZip,$zipArray))
										{
											$deliveryZoneFound=true;
											break;
										}
									}
									else if($zoneReg['zipCodes']=='' && $zoneReg['StateID'] <1)
									{
										$deliveryZoneFound=true;
										break;
									}
								}
							}
						}
						if($deliveryZoneFound)
						break;
					}
					if($deliveryZoneFound)
					{
						if($type=='list')
						{
							if($section=='cart')
							{
								$paramsArray	= array('tableName'=>'cart_items',
								'fieldName'=>'sum(orderItemQuantity) as orderItemQuantity',
								'conditionField'=>'productID',
								'condition'=>'=',
								'conditionValue'=>$productID,
								'conditionField1'=>'cartID',
								'condition1'=>'=',
								'conditionValue1'=>$cartID,
								'conditionFieldType'=>'',
								'conditionField2'=>'freeProduct',
								'condition2'=>'=',
								'conditionValue2'=>'No'
								);
								$resOrderItemQty 	= $this->getFieldValue($paramsArray);
								$orderItemQuantity	= $resOrderItemQty['orderItemQuantity'];
							}
							else
							{
								$orderItemQuantity	= $orderItemQuantity;
							}
						}
						else
						{
							if($section=='cart')
							{
								$paramsArray	= array('tableName'=>'cart_items',
								'fieldName'=>'orderItemQuantity',
								'conditionField'=>'cartItemID',
								'condition'=>'=',
								'conditionValue'=>$cartItemID,
								'conditionField1'=>'freeProduct',
								'condition1'=>'=',
								'conditionValue1'=>'No',
								'conditionFieldType'=>''
								);
								$resOrderItemQty = $this->getFieldValue($paramsArray);
								$orderItemQuantity	= $resOrderItemQty['orderItemQuantity'];
							}
							else
							{
								$orderItemQuantity	= $orderItemQuantity;
							}
						}
						if($orderItemQuantity >0)
						{
							if($orderItemQuantity > $method['maxQtyPerShipping'])
							{
								$extraQty = $orderItemQuantity-$method['maxQtyPerShipping'];

								$tempextraCharge = $extraQty*$method['chargePerExtraQty'];
								$tempShippingCharge = ($method['baseCharge'])+$method['handlingCharge']+$tempextraCharge;
								if($shippingCharge>$tempShippingCharge)
								{
									$shippingCharge		= $tempShippingCharge;
									$shippingTaxClassID	= $method['taxClassID'];
									$extraCharge 		= $tempextraCharge;
									$maxQtyPerShipping	= $method['maxQtyPerShipping'];
								}
							}
							else
							{
								/* REAL TIME CALCULATION _ API */
								require_once('fedex-common.php');
								$path_to_wsdl = dirname(__FILE__)."/wsdl/RateService_v14.wsdl";
								ini_set("soap.wsdl_cache_enabled", "0");
								$client = new SoapClient($path_to_wsdl, array('trace' => 1));
								$request['WebAuthenticationDetail'] = array(
									'UserCredential' =>array(
										'Key' => $this->_key, 
										'Password' => $this->_password
									)
								); 
								$request['ClientDetail'] = array(
									'AccountNumber' => $this->_accNumber, 
									'MeterNumber' => $this->_meterNumber
								);
								$request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request v14 using PHP ***');
								$request['Version'] = array(
									'ServiceId' => 'crs', 
									'Major' => '14', 
									'Intermediate' => '0', 
									'Minor' => '0'
								);
								$request['ReturnTransitAndCommit'] = true;
								$request['RequestedShipment']['DropoffType'] = $dropOffType; // valid values REGULAR_PICKUP, REQUEST_COURIER, ...
								$request['RequestedShipment']['ShipTimestamp'] = date('c');
								$request['RequestedShipment']['ServiceType'] = $shippingTypeKey['shippingTypeKey']; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND,INTERNATIONAL_PRIORITY ...
								$request['RequestedShipment']['PackagingType'] = $packageType; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
								$request['RequestedShipment']['TotalInsuredValue']=array(
									'Ammount'=>100,
									'Currency'=>'USD'
								);
								$request['RequestedShipment']['Shipper'] = $shipper;
								$request['RequestedShipment']['Recipient'] = 	$recipient = array(
																		'Contact' => array(
																			'PersonName' => $extraDetails['userShippingAddress']['shippingFname'].' '.$extraDetails['userShippingAddress']['shippingLname'],
																			'CompanyName' => '',
																			'PhoneNumber' => '9012637906'
																		),
																		'Address' => array(
																			'StreetLines' => array($extraDetails['userShippingAddress']['shippingAddress1'],$extraDetails['userShippingAddress']['shippingAddress2']),
																			'City' => $extraDetails['userShippingAddress']['shippingCity'],
																			'StateOrProvinceCode' => $extraDetails['userShippingAddress']['stateCode'],
																			'PostalCode' => $extraDetails['userShippingAddress']['shippingZip'],
																			'CountryCode' => $extraDetails['userShippingAddress']['countryCode'],
																			'Residential' => false
																		)
																	);
								$request['RequestedShipment']['ShippingChargesPayment'] = $this->addShippingChargesPayment();
								$request['RequestedShipment']['RateRequestTypes'] = 'ACCOUNT'; 
								$request['RequestedShipment']['RateRequestTypes'] = 'LIST'; 
								$request['RequestedShipment']['PackageCount'] = '1';
								$request['RequestedShipment']['RequestedPackageLineItems'] = array(
																							'SequenceNumber'=>1,
																							'GroupPackageCount'=>1,
																							'Weight' => array(
																								'Value' => ($packageWeight < 1)? 1 : round($packageWeight,2),
																								'Units' =>'KG' //strtoupper($measurementWeight)
																							),
																							'Dimensions' => array(
																								'Length' => ($packageLength < 1) ? 1 : round($packageLength,2),
																								'Width' => ($packageWidth < 1) ? 1 : round($packageWidth,2),
																								'Height' => ($packageHeight < 1) ? 1 : round($packageHeight,2),
																								'Units' => "CM"//strtoupper($measurementLength)
																							)
																						);
								$response = $client -> getRates($request);
								if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR'){  	
									$rateReply = $response -> RateReplyDetails;
									$shippingCharge	= $rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount;

								} else{
									$shippingCharge	= 'error';
								}


							/* END REAL TIME CALCULATION _ API */
							}
						}
						else
						{
							$shippingCharge	= 0;
						}
					}
				
				}
			}
		}
		if($deliveryZoneFound==false)
		{
			$shippingCharge	= 0;
			$this->resetShippingMethod($cartID,$productID);
			
		}
		if($shippingTaxClassID && $shippingTaxable=='Yes')
		{
			$taxParams['taxClassID']= $shippingTaxClassID;
			$taxParams['countryID']	= $shippingCountryID;
			$taxParams['stateID']	= $shippingStateID;
			$resTaxRate	=	$this->getTaxRateByTaxClassID($taxParams);
			if($resTaxRate['taxRate']>0)
			{
				$taxAmount 	= $shippingCharge*($resTaxRate['taxRate']/100);
				$shippingCharge=$shippingCharge+$taxAmount;
			}
		}
		if($shippingCountryID<1 && $shippingStateID<1 && $shippingZip=='')
		{
			$shippingCharge=0;
		}
		if($type=='list')
		{	
			return array($taxAmount,$shippingCharge);
		}
		else
		{
			return array($shippingCharge,$extraCharge,$maxQtyPerShipping);
		}
	}
	
	// CREATE SHIPMENTS
	public function createShipment($param=array())
	{
		require_once('fedex-common.php');
		$path_to_wsdl = dirname(__FILE__)."/wsdl/ShipService_v13.wsdl";

		ini_set("soap.wsdl_cache_enabled", "0");

		$client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information

		$request['WebAuthenticationDetail'] = array(
			'UserCredential' => array(
				'Key' => $this->_key, 
				'Password' => $this->_password
			)
		); 
		$request['ClientDetail'] = array(
			'AccountNumber' => $this->_accNumber, 
			'MeterNumber' => $this->_meterNumber
		);
		$request['TransactionDetail'] = array('CustomerTransactionId' => '*** Pending Shipment Request v13 using PHP ***');
		$request['Version'] = array(
			'ServiceId' => 'ship', 
			'Major' => '13', 
			'Intermediate' => '0', 
			'Minor' => '0'
		);
		$request['RequestedShipment']['DropoffType'] = $param['dropOffType']; // valid values REGULAR_PICKUP, REQUEST_COURIER, ...
		$request['RequestedShipment']['ShipTimestamp'] = date('c');
		$request['RequestedShipment']['ServiceType'] = $param['shippingService']; // valid values INTERNATIONAL_PRIORITY,STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
		$request['RequestedShipment']['PackagingType'] = $param['packageType']; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
		$request['RequestedShipment']['Shipper'] = array(
				'Contact' => array(
					'PersonName' => $param['businessName'],
					'CompanyName' => $param['businessName'],
					'PhoneNumber' => '1234567890'
				),
				'Address' => array(
					'StreetLines' => array($param['businessAddress1'],$param['businessAddress2']),
					'City' => $param['businessCity'],
					'StateOrProvinceCode' => $param['businessStateShortName'],
					'PostalCode' => $param['businessZip'],
					'CountryCode' => $param['businessCountryShortName'],
					'Residential' => false
				)
			);
		$request['RequestedShipment']['Recipient'] = array(
				'Contact' => array(
					'PersonName' => $param['shippingFname'].' '.$param['shippingLname'],
					'CompanyName' => 'Test',
					'PhoneNumber' => ($param['shippingPhone']) ? $param['shippingPhone'] : '1234567890'
				),
				'Address' => array(
					'StreetLines' => array($param['shippingAddress1'],$param['shippingAddress2']),
					'City' => $param['shippingCity'],
					'StateOrProvinceCode' => $param['shippingStateShortName'],
					'PostalCode' => $param['shippingZip'],
					'CountryCode' => $param['shippingCountryShortName'],
					'Residential' => false
				)
			);										   
		$request['RequestedShipment']['ShippingChargesPayment'] = getProperty('shippingchargespayment');
		$request['RequestedShipment']['SpecialServicesRequested'] = array(
			'SpecialServiceTypes' => array ( 'PENDING_SHIPMENT'),
			'EMailNotificationDetail' => array(
				'PersonalMessage' => 'PersonalMessage',
				'Recipients' => array(
					'EMailNotificationRecipientType' => 'RECIPIENT',
					'EMailAddress' => $param['notificationEmail'],
					'Format' => 'HTML',
					'Localization' => array(
						'LanguageCode' => 'EN', 
						'LocaleCode' => 'IN'
					)
				)
			),
			
			'PendingShipmentDetail' => array(
				'Type' => 'EMAIL', 
				'ExpirationDate' => getProperty('expirationdate'),
				'EmailLabelDetail' => array(
					'NotificationEMailAddress' => $param['notificationEmail'],
					'NotificationMessage' => ''
				)
			)
		);                                                                                                                                
		$request['RequestedShipment']['LabelSpecification'] = array(
			'LabelFormatType' => 'COMMON2D',
			'ImageType' => 'PNG'
		);
		$request['RequestedShipment']['RateRequestTypes'] = 'ACCOUNT'; 
		$request['RequestedShipment']['RateRequestTypes'] = 'LIST'; 
		$request['RequestedShipment']['PackageDetail'] = 'INDIVIDUAL_PACKAGES';
		$ObjOrder 		= new OrderModel();
		$resOrderItems	= $ObjOrder->getOrderItemsByOrderID($param['masterOrderID'],'','','',1);
		$arrayKey	= 0;
		foreach($resOrderItems as $key => $item)
		{
			if(in_array($item['orderItemID'],$param['checkshippingIDs']))
			{
				$extra 	= unserialize($item['extra']);
				$measurementLength	= (isset($extra['measurementLength']))? $extra['measurementLength']:4;
				$measurementWeight	= (isset($extra['measurementWeight']))?$extra['measurementWeight']:6;
				$measurementLength	= $this->productSizeToUnit($measurementLength);
				$measurementWeight	= $this->productSizeToUnit($measurementWeight);
				$packageLength	= (isset($extra['packageLength']))?$extra['packageLength']:1;
				$packageWidth	= (isset($extra['packageWidth']))?$extra['packageWidth']:1;
				$packageHeight	= (isset($extra['packageHeight']))?$extra['packageHeight']:1;
				$packageWeight	= (isset($extra['packageWeight']))?$extra['packageWeight']:1;//echo $orderItemQuantity;exit;
				$orderItemQuantity	= $param['shippingQuantity_'.$item['orderItemID']];
				// Converting to CM
				if($measurementLength == 'mm')
				{
					$packageLength 	= ($packageLength * $orderItemQuantity) * 0.0393701;
					$packageWidth	= ($packageWidth * $orderItemQuantity) * 0.0393701;
					$packageHeight	= ($packageHeight * $orderItemQuantity) * 0.0393701;
				}
				else if ($measurementLength == 'Inch')
				{
					$packageLength 	= $packageLength * $orderItemQuantity  ;
					$packageWidth	= $packageWidth * $orderItemQuantity ;
					$packageHeight	= $packageHeight * $orderItemQuantity ;
				}
				else if ($measurementLength == 'ft')
				{
					$packageLength 	= $packageLength * $orderItemQuantity * 12;
					$packageWidth	= $packageWidth * $orderItemQuantity * 12;
					$packageHeight	= $packageHeight * $orderItemQuantity * 12;
				}
				else if ($measurementLength == 'cm')
				{
					$packageLength 	= $packageLength * $orderItemQuantity * 0.393701;
					$packageWidth	= $packageWidth * $orderItemQuantity * 0.393701;
					$packageHeight	= $packageHeight * $orderItemQuantity * 0.393701;
				}
				// Convert weight to KG
				if($measurementWeight == 'gm')
				{
					$packageWeight = $packageWeight * $orderItemQuantity * 0.00220462;
				}
				else if($measurementWeight == 'Ounce')
				{
					$packageWeight = $packageWeight * $orderItemQuantity * 0.0625;
				}
				else if($measurementWeight == 'Pound')
				{
					$packageWeight = $packageWeight * $orderItemQuantity;
				}
				else if($measurementWeight == 'Kg')
				{
					$packageWeight = $packageWeight * $orderItemQuantity * 2.20462;
				}
				 $tempArray[$arrayKey] =
					 array(
						'SequenceNumber' => $arrayKey+1,
						'InsuredValue' => array(
							'Amount' => 20.0,
							'Currency' => 'USD'
						),
						'ItemDescription' => $extra['productTitle'],
						'Weight' => array(
							'Value' => ($packageWeight > 0.1) ? $packageWeight : 0.1,
							'Units' => 'LB'
						),
						'Dimensions' => array(
							'Length' => ($packageLength > 1) ? $packageLength : 1.0,
							'Width' => ($packageWidth > 1)? $packageWidth : 1.0,
							'Height' => ($packageHeight > 1)?$packageHeight : 1.0,
							'Units' => 'IN'
						),
						'CustomerReferences' => array(
							'CustomerReferenceType' => 'CUSTOMER_REFERENCE',
							'Value' => 'Undergraduate application'
						)
					);
			$arrayKey++;
			}
		}
		$request['RequestedShipment']['PackageCount'] = count($tempArray);
		$request['RequestedShipment']['RequestedPackageLineItems'] = $tempArray;
		$response = $client ->createPendingShipment($request);
		if (is_soap_fault($response))
		{
			$shipmentResult['successCode']	= 'ERROR';
			$shipmentResult['message']	= 'Error in fedex Api call';
			return $shipmentResult;
			exit;
		}

		if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR' )
		{
			$shipmentResult['successCode']	= $response -> HighestSeverity;
			$shipmentResult['url']	= $response -> CompletedShipmentDetail -> AccessDetail -> EmailLabelUrl;
			$shipmentResult['userID']	= $response -> CompletedShipmentDetail -> AccessDetail -> UserId;
			$shipmentResult['password']	= $response -> CompletedShipmentDetail -> AccessDetail -> Password;
			if(  is_object($response -> CompletedShipmentDetail -> CompletedPackageDetails)){
				$shipmentResult['trackingNumber']	= $response -> CompletedShipmentDetail -> CompletedPackageDetails -> TrackingIds -> TrackingNumber;
			}else{
				$shipmentResult['trackingNumber']	= $response -> CompletedShipmentDetail -> MasterTrackingId -> TrackingNumber;
			}
			if(  is_object($response -> Notifications))
			{
				$shipmentResult['message']	= $response -> Notifications -> Message;
			}else{
				$shipmentResult['message']	= $response -> Notifications[0] -> Message;
			}
		}
		else
		{
			$shipmentResult['successCode']	= $response -> HighestSeverity;
			if(  is_object($response -> Notifications))
			{
				$shipmentResult['message']	= $response -> Notifications -> Message;
			}else{
				$shipmentResult['message']	= $response -> Notifications[0] -> Message;
			}
		}
		return $shipmentResult;
}

	// CREATE PICK UP SERVICE
	public function createPickup($param=array())
	{
		require_once('fedex-common.php');
		$path_to_wsdl = dirname(__FILE__)."/wsdl/PickupService_v6.wsdl";
		ini_set("soap.wsdl_cache_enabled", "0");

		$client = new SoapClient($path_to_wsdl, array('trace' => 1));
		$request['WebAuthenticationDetail'] = array(
			'UserCredential' => array(
				'Key' => $this->_key, 
				'Password' => $this->_password
			)
		);
		$request['ClientDetail'] = array(
			'AccountNumber' => $this->_accNumber, 
			'MeterNumber' => $this->_meterNumber
		);
		$request['TransactionDetail'] = array('CustomerTransactionId' => '*** Create Pickup Request v6 using PHP ***');
		$request['Version'] = array(
			'ServiceId' => 'disp', 
			'Major' => 6, 
			'Intermediate' => 0, 
			'Minor' => 0
		);
		$request['OriginDetail'] = array(
			'PickupLocation' => array(
				'Contact' => array(
					'PersonName' => 'Contact Name',
					'CompanyName' => $param['businessName'],
					'PhoneNumber' => '1234567890'
				),
				'Address' => array(
					'StreetLines' => array($param['businessAddress1'],$param['businessAddress2']),
					'City' => $param['businessCity'],
					'StateOrProvinceCode' => $param['businessStateShortName'],
					'PostalCode' => $param['businessZip'],
					'CountryCode' => $param['businessCountryShortName'])
				),
			'PackageLocation' => 'FRONT', // valid values NONE, FRONT, REAR and SIDE
			'BuildingPartCode' => 'SUITE', // valid values APARTMENT, BUILDING, DEPARTMENT, SUITE, FLOOR and ROOM
			'BuildingPartDescription' => '3B',
			'ReadyTimestamp' => strtotime((isset($param['pickupDate']) && $param['pickupDate'] != '')? $param['pickupDate'] :  date('Y-m-d H:i',strtotime('+30 minutes'))),//getProperty('pickuptimestamp'), // Replace with your ready date time
			'CompanyCloseTime' => (isset($param['pickupClosingTime']) && $param['pickupClosingTime'] != '') ? $param['pickupClosingTime'].':00' : '18:00:00'
		);
		$request['PackageCount'] = '1';
		$request['TotalWeight'] = array(
			'Value' => $param['grossWeight'], 
			'Units' => 'LB' // valid values LB and KG
		); 
		$request['CarrierCode'] = 'FDXE'; // valid values FDXE-Express, FDXG-Ground, FDXC-Cargo, FXCC-Custom Critical and FXFR-Freight
		$request['CourierRemarks'] = 'This is a test.  Do not pickup';


			if(setEndpoint('changeEndpoint')){
				$newLocation = $client->__setLocation(setEndpoint('endpoint'));
			}
			
			$response = $client ->createPickup($request);
			if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR')
			{
				$returnArray['successCode']	= $response -> HighestSeverity;
				$returnArray['PickupConfirmationNumber']	= $response -> PickupConfirmationNumber;
				$returnArray['Location']	= $response -> Location;
			}
			else
			{
				$returnArray['successCode']	= $response -> HighestSeverity;
				$returnArray['message']		= $response -> Notifications -> Message;
			}
		return $returnArray;
		exit;
	}
	
	// END PICK UP
	public function cancelShipment($param=array())
	{
		require_once('fedex-common.php');


		$path_to_wsdl = dirname(__FILE__)."/wsdl/ShipService_v13.wsdl";

		ini_set("soap.wsdl_cache_enabled", "0");

		$client = new SoapClient($path_to_wsdl, array('trace' => 1));

		$request['WebAuthenticationDetail'] = array(
			'UserCredential' => array(
				'Key' => $this->_key, 
				'Password' => $this->_password
			)
		);
		$request['ClientDetail'] = array(
			'AccountNumber' => $this->_accNumber, 
			'MeterNumber' => $this->_meterNumber
		);
		$request['TransactionDetail'] = array('CustomerTransactionId' => '*** CancelEMailLabel Request v13 using PHP ***');
		$request['Version'] = array(
			'ServiceId' => 'ship', 
			'Major' => '13', 
			'Intermediate' => '0', 
			'Minor' => '0'
		);
		$request['TrackingId'] = array(
			'TrackingIdType' => 'EXPRESS',
			'TrackingNumber' => $param['trackingNumber'],
		); 


			$response = $client ->cancelPendingShipment($request);
			return true;
}
	
	function getAuthenticateDetails()
	{
		getShippingSettingsByKey($settingsGroupKey,$settingsKey);
	}
	
	function addShipper()
	{
		$shipper = array(
			'Contact' => array(
				'PersonName' => 'Shemil R',
				'CompanyName' => 'ISPG',
				'PhoneNumber' => '9012638716'
			),
			'Address' => array(
				'StreetLines' => array('44 Main street'),
				'City' => 'Boston',
				'StateOrProvinceCode' => 'MA',
				'PostalCode' => '02116',
				'CountryCode' => 'US'
			)
		);
		return $shipper;
	}
	
	function addRecipient()
	{
		$recipient = array(
			'Contact' => array(
				'PersonName' => 'Shemil R',
				'CompanyName' => 'ISPG',
				'PhoneNumber' => '9012637906'
			),
			'Address' => array(
				'StreetLines' => array('Edapally'),
				'City' => 'Cochin',
				'StateOrProvinceCode' => 'KL',
				'PostalCode' => '682024',
				'CountryCode' => 'IN',
				'Residential' => false
			)
		);
		return $recipient;	                                    
	}

	function addShippingChargesPayment()
	{
	$shippingChargesPayment = array(
		'PaymentType' => 'SENDER', // valid values RECIPIENT, SENDER and THIRD_PARTY
		'Payor' => array(
			'ResponsibleParty' => array(
				'AccountNumber' => getProperty('billaccount'),
				'CountryCode' => 'US'
			)
		)
	);
	return $shippingChargesPayment;
}

	function addLabelSpecification()
	{
	$labelSpecification = array(
		'LabelFormatType' => 'COMMON2D', // valid values COMMON2D, LABEL_DATA_ONLY
		'ImageType' => 'PDF',  // valid values DPL, EPL2, PDF, ZPLII and PNG
		'LabelStockType' => 'PAPER_7X4.75'
	);
	return $labelSpecification;
}

	function addSpecialServices()
	{
	$specialServices = array(
		'SpecialServiceTypes' => array('COD'),
		'CodDetail' => array(
			'CodCollectionAmount' => array(
				'Currency' => 'USD', 
				'Amount' => 150
			),
			'CollectionType' => 'ANY' // ANY, GUARANTEED_FUNDS
		)
	);
	return $specialServices; 
}

	function addPackageLineItem1()
	{
	$packageLineItem = array(
		'SequenceNumber'=>1,
		'GroupPackageCount'=>1,
		'Weight' => array(
			'Value' => $packageWeight,
			'Units' => strtoupper($measurementWeight)
		),
		'Dimensions' => array(
			'Length' => $packageLength,
			'Width' => $packageWidth,
			'Height' => $packageHeight,
			'Units' => strtoupper($measurementLength)
		)
	);
	return $packageLineItem;
}
}