<?php
// Check to ensure this file is included in Freeway!
defined('_FEXEC') or die();
/*
  $Id: esec/securepay.php,v 1.2 2003/12/24

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
  
  Freeway eCommerce from ZacWare
http://www.zac-ware.com/freeway

Copyright 2007 ZacWare Pty. Ltd
*/

  class oneworld {
    var $code, $title, $description, $enabled, $states;

// class constructor
    function oneworld() {

      $this->code = 'oneworld';
      $this->title = MODULE_FULFILLER_ONEWORLD_TEXT_TITLE;
      $this->description = MODULE_FULFILLER_ONEWORLD_TEXT_DESCRIPTION;
      $this->sort_order = MODULE_FULFILLER_ONEWORLD_SORT_ORDER;
      $this->enabled = ((MODULE_FULFILLER_ONEWORLD_STATUS == 'True') ? true : false);

      $this->form_action_url = "https://secure.owd.com/webapps/api/api.jsp";
    }

	function process(){
		global $order,$parser,$messageStack,$shipping;
		if (($order->content_type == 'virtual') || ($order->content_type == 'virtual_weight') || ((float)$order->info["shipping_cost"]==0)) return;
		if (!$this->enabled) return;
		$xml_request.='<?xml version="1.0"?>';
		$xml_request.='<OWD_API_REQUEST	api_version="1.1"
		
          		client_id="' .MODULE_FULFILLER_ONEWORLD_CLIENT_ID . '"

          		client_authorization="' . MODULE_FULFILLER_ONEWORLD_CLIENT_AUTH . '" 

          		testing="' . (MODULE_FULFILLER_ONEWORLD_TESTMODE=="Production"?"FALSE":"TRUE") . '">';
				
		$xml_request.='<OWD_ORDER_CREATE_REQUEST order_reference="mPulse' . $order->info["id"] . '" 

				order_source="Intranet"

				is_gift="NO"

				backorder_rule="' .PRODUCT_FULFILLER . '">';
				
		$xml_request.='<SHIPPING_INFO last_name="' . $order->delivery["lastname"] .'" first_name="' . $order->delivery["firstname"] . '"

			address_one="' . $order->delivery['street_address'] . '" 

			city="' . $order->delivery['city'] . '" 

			state="' . $order->delivery['state'] . '" 

			zip="' . $order->delivery['postcode'] . '" 

			country="' . $order->delivery['country']['title'] . '" 

			phone="' . $order->customer['telephone'] . '" 

			email="' . $order->customer['email_address'] . '" 

			ship_cost="' . number_format($order->info["owd_cost"],2) .'" 
			
			ship_type="' . tep_get_owd_shipping_type($shipping["id"]) . '"

			/>';
			
		$xml_request.='<BILLING_INFO last_name="' . $order->billing["lastname"] .'" 

			first_name="' . $order->billing["firstname"] . '"

			address_one="' . $order->billing['street_address'] . '" 
			
			paid="YES"

	  		payment_type="CLIENT" 

			city="' . $order->billing['city'] . '" 

			state="' . $order->billing['state'] . '" 

			zip="' . $order->billing['postcode'] . '" 

			country="' . $order->billing['country']['title'] . '" 

			phone="' . $order->customer['telephone'] . '" 

			email="' . $order->customer['email_address'] . '" 

			/>';
		$temp_xml_request="";
		for ($icnt=0, $n=sizeof($order->products); $icnt<$n; $icnt++) {
			if ($order->products[$icnt]['element_type']=='P'){
				$temp_xml_request.='<LINE_ITEM part_reference="' . $order->products[$icnt]['sku'] .'"
		
					description="' . $order->products[$icnt]['name'] . '"
		
					requested="' . $order->products[$icnt]['qty'] . '"
		
					cost="' . tep_add_tax($order->products[$icnt]['final_price'],$order->products[$icnt]['tax']) . '" />';
			}
		}
		if ($temp_xml_request=="") return;
		$xml_request.=$temp_xml_request;
        $xml_request.='</OWD_ORDER_CREATE_REQUEST></OWD_API_REQUEST>';
		$xml_response="";
		/*
			$ch = curl_init(); 
			curl_setopt($ch, CURLOPT_URL,"https://secure.owd.com/webapps/api/api.jsp"); 
			curl_setopt($ch, CURLOPT_FAILONERROR, 1); 
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_POST, 1); 
			curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_request);
			$xml_response = curl_exec($ch);
			curl_close ($ch);
			*/
		$xml_response=$this->get_xml_response($xml_request);



		if ($xml_response==""){
			$messageStack->add_session("checkout_success",ERR_FULFILLER_EMPTY_RESPONSE);
			return;
		}
		$parser->parse($xml_response,true);
		$result=&$parser->structure;
		if (!isset($result[0]) || $result[0]['Tag']!='OWD_API_RESPONSE'){
			$messageStack->add_session("checkout_success",ERR_FULFILLER_EMPTY_RESPONSE);
			return;
		}
		
		if ($result[0]['Attributes']['results']=="SUCCESS"){
			$messageStack->add_session("checkout_success",FULFILLER_ORDER_REQUEST_SUCCESS,"success");
			tep_db_query("update orders set fulfiller_status='" . $result["0,0"]['Attributes']['status'] . "' where orders_id=" . $order->info["id"]);
		} else {
			$type=$result[0]['Attributes']['error_type'];
			$text=$result[0]['Attributes']['error_response'];
			if (defined('ERR_FULFILLER_REQUEST_' . $type)) $text=constant('ERR_FULFILLER_REQUEST_' . $type) . $text;
			$messageStack->add_session("checkout_success",$text);
		}
	}

	function process_status($order_id){
		global $order,$parser,$messageStack;
		if (!$this->enabled) return;
		$xml_request.='<?xml version="1.0"?>';
		$xml_request.='<OWD_API_REQUEST	api_version="1.1"
		
          		client_id="' .MODULE_FULFILLER_ONEWORLD_CLIENT_ID . '"

          		client_authorization="' . MODULE_FULFILLER_ONEWORLD_CLIENT_AUTH . '" 

          		testing="' . (MODULE_FULFILLER_ONEWORLD_TESTMODE=="Production"?"FALSE":"TRUE") . '">';
				
		$xml_request.='<OWD_ORDER_STATUS_REQUEST clientOrderId="' .  $order_id . '">
		
						</OWD_ORDER_STATUS_REQUEST>
						
						</OWD_API_REQUEST>';
		$xml_response="";
		$xml_response=$this->get_xml_response($xml_request);
		$parser->parse($xml_response,true);
		$result=&$parser->structure;
		$res_array=array("error"=>'',"status"=>'');
		if (!isset($result[0]) || $result[0]['Tag']!='OWD_API_RESPONSE' || $result[0]['Attributes']['results']!="SUCCESS"){
			$type=$result[0]['Attributes']['error_type'];
			$text=$result[0]['Attributes']['error_response'];
			if (defined('ERR_FULFILLER_REQUEST_' . $type)) $text=constant('ERR_FULFILLER_REQUEST_' . $type) . $text;
			$res_array["error"]=$text;
		} else {
			foreach($result as $row){
				if($row['Tag']=='OWD_ORDER_STATUS_RESPONSE'){
					$res_array['status']=$row['Attributes']['status'];
					break;
				}
			}
		}
		return $res_array;
	}

function process_out_of_stock()
{
		global $parser;

		if (!$this->enabled) return;
		$xml_request.='<?xml version="1.0"?>';
		$xml_request.='<OWD_API_REQUEST	api_version="1.0"
		
          		client_id="' .MODULE_FULFILLER_ONEWORLD_CLIENT_ID . '"

          		client_authorization="' . MODULE_FULFILLER_ONEWORLD_CLIENT_AUTH . '" 

          		testing="' . (MODULE_FULFILLER_ONEWORLD_TESTMODE=="Production"?"FALSE":"TRUE") . '">';
				
		$xml_request.='<OWD_INVENTORY_COUNT_REQUEST>
		
				       </OWD_INVENTORY_COUNT_REQUEST>
						  
				 	</OWD_API_REQUEST>';
		$xml_response="";
		$xml_response=$this->get_xml_response($xml_request);
		
		
		$parser->parse($xml_response,true);
		$result=&$parser->structure;
		$res_array=array('error'=>'','content'=>array());
		
		if (!isset($result[0]) || $result[0]['Tag']!='OWD_API_RESPONSE' || $result[0]['Attributes']['results']!="SUCCESS"){
			$type=$result[0]['Attributes']['error_type'];
			$text=$result[0]['Attributes']['error_response'];
			if (defined('ERR_FULFILLER_REQUEST_' . $type)) $text=constant('ERR_FULFILLER_REQUEST_' . $type) . $text;
			$res_array["error"]=$text;
		} else {
			foreach($result as $row)
			{
				if($row['Tag']=='COUNT')
					$res_array['content'][$row['Attributes']['part_reference']]=$row['Attributes']['quantity_on_hand'];
			}	
		}
		
		return $res_array;
}


	function get_xml_response($xml_request)
	{
			$header="";
			$xml_response="";
			$header .= "POST /webapps/api/api.jsp HTTP/1.0\r\n";
			$header .= "Content-Type: text/xml\r\n";
			$header .= "Content-Length: " . strlen ($xml_request) . "\r\n\r\n";
			$fp = @fsockopen ("ssl://secure.owd.com", 443, $errno, $errstr, 50);
			if ($fp){
				fputs ($fp, $header . $xml_request);
				while (!feof($fp)) {
				  $xml_response .= fgets($fp, 1024);
				};
				fclose ($fp);
			}
			if ($xml_response!=""){
				$temp_splt=split(chr(13). chr(10) .chr(13) .chr(10),$xml_response);
				$xml_response=$temp_splt[1];
			}
			return($xml_response);
	}


    function check() {
      if (!isset($this->_check)) {
        $check_query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_FULFILLER_ONEWORLD_STATUS'");
        $this->_check = tep_db_num_rows($check_query);
      }
      return $this->_check;
    }
    function install() {
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable OneWorld', 'MODULE_FULFILLER_ONEWORLD_STATUS', 'True', 'Do you want to activate OneWorld FulFiller Interface?', '6', '1', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now());");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Transaction Mode', 'MODULE_FULFILLER_ONEWORLD_TESTMODE', 'Test', 'Transaction mode used for processing OneWorld Service', '6', '2', 'tep_cfg_select_option(array(\'Test\', \'Production\'), ', now());");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Client ID', 'MODULE_FULFILLER_ONEWORLD_CLIENT_ID', 'OWD001', 'The Client ID Assigned by OneWorld', '6', '3', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Client Authorization', 'MODULE_FULFILLER_ONEWORLD_CLIENT_AUTH', 'OWDAUTH', 'The Client Authentication Assigned by OneWorld', '6', '4', now());");
  	  tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Cost Per Order', 'MODULE_FULFILLER_ONEWORLD_COST_PER_ORDER', '0', 'Assign Cost Per Order', '6', '5', now())");
	  tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Cost Per Packing', 'MODULE_FULFILLER_ONEWORLD_COST_PER_PACKING', '0', 'Assign Cost Per Packing', '6', '6', now())");
	  tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Cost Per Item', 'MODULE_FULFILLER_ONEWORLD_COST_PER_ITEM', '0', 'Assign Cost Per Item', '6', '7', now())");
	  tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Overweight Handling Fee', 'MODULE_FULFILLER_ONEWORLD_OVERWEIGHT_HANDLING_FEE', '0', 'Assign OverWeight Handling Fee', '6', '8', now())");
	  tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort order of Display.', 'MODULE_FULFILLER_ONEWORLD_SORT_ORDER', '0', 'Sort order of display. Lowest is displayed first.', '6', '9', now())");
    }

    function remove() {
      tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
    }

    function keys() {
      return array('MODULE_FULFILLER_ONEWORLD_STATUS', 'MODULE_FULFILLER_ONEWORLD_CLIENT_ID', 'MODULE_FULFILLER_ONEWORLD_CLIENT_AUTH','MODULE_FULFILLER_ONEWORLD_TESTMODE','MODULE_FULFILLER_ONEWORLD_COST_PER_ORDER','MODULE_FULFILLER_ONEWORLD_COST_PER_PACKING','MODULE_FULFILLER_ONEWORLD_COST_PER_ITEM','MODULE_FULFILLER_ONEWORLD_OVERWEIGHT_HANDLING_FEE','MODULE_FULFILLER_ONEWORLD_SORT_ORDER');
    }
	function _get_template($type){
		$result='<?xml version="1.0"?>
				<OWD_API_REQUEST	api_version="1.1" client_id="{{CLIENT_ID}}" client_authorization="{{CLIENT_AUTH}}" testing="{{TESTING}}">
				<OWD_ORDER_CREATE_REQUEST order_reference="{{ORDER_ID}}" order_source="Intranet" is_gift="NO" backorder_rule="PARTIALSHIP">
				<SHIPPING_INFO last_name="{{LAST_NAME}}" first_name="{{FIRST_NAME}}">
				';
				
	}
  }
?>
