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


class UPSHelper extends ShippingEstimatorAbstract
{
	public function __construct($type,$shippinEstiConfi){
		
		$yaml = new Parser();
		$this->upsConfig = $yaml->parse(file_get_contents(__DIR__.'/../Resources/config/ups_config_param.yml'));
		$this->environment = $this->upsConfig['parameters']['environment'];
		$this->licenceNumber = $this->upsConfig['parameters']['account_license_number_'.$this -> environment];
		$this->accessUseId = $this->upsConfig['parameters']['access_userid_'.$this -> environment];
		$this->accessPassword = $this->upsConfig['parameters']['access_password_'.$this -> environment];
		$this->accountCountry = $this->upsConfig['parameters']['access_country_'.$this -> environment];
		$this->accountNumber = $this->upsConfig['parameters']['account_number_'.$this -> environment];
		$this->type = $type;
		
		$this->credential = array(
			'API_ACCESS_LICENSE_NUMBER' => $this -> licenceNumber,
			'API_ACCESS_USERID' => $this -> accessUseId,
			'API_ACCESS_PASSWORD' => $this -> accessPassword,
			'API_ACCESS_ACCOUNT_NUMBER' => $this -> accountNumber
		);

		//$this->rateRequest = new ComplexType\RateRequest();
	}
	
	public function setAuthenticationDetail()
	{
		
		/*$aurtho = "<?xml version=\"1.0\" ?".">
								<AccessRequest xml:lang=\"en-US\">
								<AccessLicenseNumber>1CF36E0A07BE2146</AccessLicenseNumber>
									<UserId>officebeacon </UserId><Password> XbbZC4DEaY9bpF </Password>
								</AccessRequest>";*/
		
		$aurthoxml =$this->upsConfig['parameters']['api_request_format']['options']['authentication_xml'];
		$aurtho=$this->prepareRequestData($aurthoxml,$this->credential);
		return $aurtho;
	}
	
	public function setRateRequestDetail($shippingEstiDetail,$shippingEstiConfi)
	{
		$ratereq="<?xml version=\"1.0\" ?".">
						<RatingServiceSelectionRequest xml:lang=\"en-US\">
							<Request>
								<TransactionReference>
									<CustomerContext>Bare Bones Rate Request</CustomerContext>
									<XpciVersion>1.0001</XpciVersion>
								</TransactionReference>
								<RequestAction>Rate</RequestAction>
								<RequestOption>Shop</RequestOption>
							</Request>
							<PickupType>
								<Code>".$shippingEstiConfi['pickup_type']['status']."</Code>
							</PickupType>
							<CustomerClassification>
								<Code>".$shippingEstiConfi['customer_classification']['status']."</Code>
							</CustomerClassification>
							<Shipment>
								<Shipper>
									<ShipperNumber>".$this->accountNumber."</ShipperNumber>
									<Address>
										<StateProvinceCode>".$shippingEstiDetail['shipper']['shipperState']."</StateProvinceCode>
										<PostalCode>".$shippingEstiDetail['shipper']['shipperZip']."</PostalCode>
										<CountryCode>".$shippingEstiDetail['shipper']['shipperCountry']."</CountryCode>
									</Address>
								</Shipper>";
		
								/*if client need  negotiation rate then set is_display_negotiation_rate = 1 
								 *  if client need nego rate with login then is_display_negotiation_rate_with_login should be 1 
								 *  if client need nego rate without login then is_display_negotiation_rate_with_login should be 0
								 *  if we select nego rate without login then in db we need to set customer_classification to 01 which is basically set to 03
								 *  if we do not set this we will not get nego rate without login
								 *  i.e conditions : 
								 *  if client need UPS public rate (which has highest rate ) then is_display_negotiation_rate = 0 and is_display_negotiation_rate_with_login = 0 and customer_classification = 01
								 *  if client need UPS negotiation rate with shipper account with login (which has lowest rate ) then is_display_negotiation_rate = 1 and is_display_negotiation_rate_with_login = 1 and customer_classification = 01 
								 *  if client need UPS negotiation rate with shipper account without login (which has mid rate ) then is_display_negotiation_rate = 1 and is_display_negotiation_rate_with_login = 0 and customer_classification = 03
								 * */
								if($shippingEstiConfi['is_display_negotiation_rate']['status']=='1')
								{
									if($shippingEstiConfi['is_display_negotiation_rate']['option']['is_display_negotiation_rate_with_login'] == '1')
									{
									
										$ratereq .= "<RateInformation>
														<NegotiatedRatesIndicator/>
													</RateInformation>";
									}
									else
									{
										$ratereq .= "<RateInformation>
														<RateChartIndicator/>
													</RateInformation>";
									}
								}
								$ratereq .= "<ShipTo>
									<Address>
										<PostalCode>".$shippingEstiDetail['reciver']['userZip']."</PostalCode>
										<CountryCode>".$shippingEstiDetail['reciver']['userCountry']."</CountryCode>";
										if($shippingEstiDetail['reciver']['userIsResident']=='1')
										{
											$ratereq .="<ResidentialAddressIndicator>True</ResidentialAddressIndicator>";
										}
						$ratereq .=	"</Address>
								</ShipTo>
								<ShipFrom>
									<Address>
										<StateProvinceCode>".$shippingEstiDetail['shipper']['shipperState']."</StateProvinceCode>
										<PostalCode>".$shippingEstiDetail['shipper']['shipperZip']."</PostalCode>
										<CountryCode>".$shippingEstiDetail['shipper']['shipperCountry']."</CountryCode>
									</Address>
								</ShipFrom>
								";
								for($i=0;$i<$shippingEstiDetail['noOfBox'];$i++)
								{
						$ratereq .= "
									<Package>
										<PackagingType>
											<Code>".$shippingEstiConfi['packing_type']['status']."</Code>
											<Description>Package</Description>
										</PackagingType>
										<Description>Rating a Specific Service</Description>";
						if($shippingEstiDetail['cartonLength']!=0 && $shippingEstiDetail['cartonWidth']!=0 && $shippingEstiDetail['cartonWidth']!=0)
						{
							$ratereq .= "
											<Dimensions>
												<Length>".round($shippingEstiDetail['cartonLength'],2)."</Length>
												<Width>".round($shippingEstiDetail['cartonWidth'],2)."</Width>
												<Height>".round($shippingEstiDetail['cartonHeight'],2)."</Height>
											</Dimensions>";
						}
						$ratereq .= "	<PackageWeight>
											<Weight>".$shippingEstiDetail['totalWeight'][$i]."</Weight>
										</PackageWeight>
									</Package>";
								}
				$ratereq .= "</Shipment>
						</RatingServiceSelectionRequest>";
						
		return $ratereq;
	}
	
	public function setTrackRequestDetail($shippingEstiDetail)
	{
		$trackreq="<?xml version=\"1.0\"?>
						<TrackRequest>
							<Request>
								<TransactionReference>
									<CustomerContext>
										<InternalKey>blah</InternalKey>
									</CustomerContext>
									<XpciVersion>1.0</XpciVersion>
								</TransactionReference>
								<RequestAction>Track</RequestAction>
							</Request>
							<TrackingNumber>".$shippingEstiDetail."</TrackingNumber>
						</TrackRequest>";
		return $trackreq;
	}

	public function setShipRequestDetail($shippingEstiDetail,$shippingEstiConfi)
	{
		$shipperDetail=$shippingEstiDetail['shipper'] ;
		$userDetail = $shippingEstiDetail['reciver'] ;
		
		$shipreq="<?xml version=\"1.0\" ?>
						<ShipmentConfirmRequest>
						    <Request>
						         <TransactionReference>
						              <CustomerContext>guidlikesubstance</CustomerContext>
						              <XpciVersion>1.0001</XpciVersion>
						         </TransactionReference>
						         <RequestAction>ShipConfirm</RequestAction>
						         <RequestOption>nonvalidate</RequestOption>
						    </Request>
						    <Shipment>
						        <Description>Rate Description</Description>
						         <Shipper>
						              <Name>".$shipperDetail['shipperCompanyName']."</Name>
						              <AttentionName>".$shipperDetail['shipperName']."</AttentionName>
						              <PhoneNumber>".$shipperDetail['shipperPhone']."</PhoneNumber>
						              <ShipperNumber>".$this-> accountNumber."</ShipperNumber>
						              <Address>
						                   <AddressLine1>".$shipperDetail['shipperAdd']."</AddressLine1>
						                   <City>".$shipperDetail['shipperCity']."</City>
						                   <StateProvinceCode>".$shipperDetail['shipperState']."</StateProvinceCode>
						                   <CountryCode>".$shipperDetail['shipperCountry']."</CountryCode>
						                   <PostalCode>".$shipperDetail['shipperZip']."</PostalCode>
						              </Address>
						         </Shipper>
						         <ShipTo>
						         		<CompanyName>".$userDetail['userName']."</CompanyName>
						              <AttentionName>".$userDetail['userName']."</AttentionName>
						              <PhoneNumber>".$userDetail['userPhone']."</PhoneNumber>
						              <Address>
						                   <AddressLine1>".$userDetail['userAdd']."</AddressLine1>
						                   <City>".$userDetail['userCity']."</City>
						                   <StateProvinceCode>".$userDetail['userState']."</StateProvinceCode>
						                   <CountryCode>".$userDetail['userCountry']."</CountryCode>
						                   <PostalCode>".$userDetail['userZip']."</PostalCode>";
						                   
										   if($userDetail['userIsResident']=='1')
											{
												$shipreq.= "<ResidentialAddressIndicator>True</ResidentialAddressIndicator>";
											}
										   
										   
						             $shipreq.=" </Address>
						         </ShipTo>
						         <PaymentInformation>
						                <Prepaid>
						                    <BillShipper>
						                        <AccountNumber>".$this-> accountNumber."</AccountNumber>
						                    </BillShipper>
						                </Prepaid>
						        </PaymentInformation>
						         <Service>
						              <Code>03</Code>
						              <Description>UPS Ground</Description>
						         </Service>
						        <Package>
						            <PackagingType>
						                <Code>".$shippingEstiConfi['packaging_type']['status']."</Code>
						            </PackagingType>
						            <PackageWeight>
						                <Weight>11</Weight>
						            </PackageWeight>
						        </Package>
						    </Shipment>
						    <LabelSpecification>
						        <LabelPrintMethod>
						            <Code>".$shippingEstiConfi['label_print_method']['status']."</Code>
						        </LabelPrintMethod>
						        <LabelImageFormat>
						            <Code>".$shippingEstiConfi['label_image_format']['status']."</Code>
						        </LabelImageFormat>
						    </LabelSpecification>
						</ShipmentConfirmRequest>";
		return $shipreq;
	}
	
	/*public function setShipRequestDetail($shippingEstiDetail,$shippingEstiConfi)
	{
		$aurthoxml =$this->upsConfig['parameters']['api_request_format']['options']['shipment_xml'];
		
		$ratereq="";
	}*/
	
	public  function prepareRequestData($xmlParameter,$setparameter)
	{
        	
            $search_key_array = array_keys($setparameter);
			
            $replace_value_array = array_values($setparameter);

            array_walk($search_key_array, function(&$value, $key) {
                $value = '##' . strtoupper($value) . '##';
               
            });
			
            $this -> final_request_data = str_replace($search_key_array, $replace_value_array, $xmlParameter);
            
            unset($search_key_array);
            unset($replace_value_array);

            if (preg_match('/##[A-Z_]+##/', $this -> final_request_data, $matches)) {
                $this -> setError('MISSING_CALL_PARAMETRES -> ' . str_replace('#', '', implode(', ', $matches)));
                return false;
            }
            else {
                return $this->final_request_data ;
            }
			exit();
    }
}
?>