<?php

// Check to ensure this file is included in Freeway!
defined('_FEXEC') or die();


class anz {
	// Variable Decleration
	var $code;
	var $title;
	var $description;
	var $enabled,$text_title;	

	function anz() {		
		global $order;
		// Specify Object operation parameters
		$this->code = 'anz';
		
		$name = "ANZ Bank";
		$image = "";
		$path = "";
		if(MODULE_PAYMENT_ANZ_DISPLAY_NAME != "MODULE_PAYMENT_ANZ_DISPLAY_NAME")$name = MODULE_PAYMENT_ANZ_DISPLAY_NAME;
		if(MODULE_PAYMENT_ANZ_IMAGE != "MODULE_PAYMENT_ANZ_IMAGE")$image = MODULE_PAYMENT_ANZ_IMAGE;
		if(DIR_WS_ADMIN != "DIR_WS_ADMIN" && DIR_WS_ADMIN != "")$path = "../";
		if($image != "" && file_exists($path . DIR_WS_IMAGES . $image)){
			$image = '<img src="' . HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . $image . '" width="103" height="33">';
		}else{
			$image_array = array('.gif','.jpg','.jpeg','.png');
			$image_check = true;
			for($i=0;$i<sizeof($image_array);$i++){
				if($image_check && $image != "" && file_exists($path . DIR_WS_IMAGES . $image . $image_array[$i])){
					$image = '<img src="'. HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . $image . $image_array[$i] . '" width="103" height="33">';
					$image_check = false;
				}
			}
			if($image_check)$image = "";
		}
		define('MODULE_PAYMENT_ANZ_TEXT_TITLE', $name . '&nbsp;&nbsp;' . $image);
		define('MODULE_PAYMENT_ANZ_TEXT_TEXT_TITLE', $name);
		
		$this->title = (defined('MODULE_PAYMENT_ANZ_TEXT_TITLE') ? MODULE_PAYMENT_ANZ_TEXT_TITLE : 'ANZ Bank'); // Change this for changing what appears on your site 
		$this->text_title=MODULE_PAYMENT_ANZ_TEXT_TITLE;
		$this->description = (defined('MODULE_PAYMENT_ANZ_TEXT_DESCRIPTION') ? MODULE_PAYMENT_ANZ_TEXT_DESCRIPTION : 'ANZ Payment Module');
		
		/* Ensure that everything appears complete to enable this payment processor */
		if(defined('MODULE_PAYMENT_ANZ_STATUS') && strtoupper(MODULE_PAYMENT_ANZ_STATUS) == 'TRUE') {
		$merchantID = (defined('MODULE_PAYMENT_ANZ_MERCHANT_ID') ? MODULE_PAYMENT_ANZ_MERCHANT_ID : null);
		$this->enabled = true;
			if(empty($merchantID)) 
				 $this->enabled = false;
		} 
		else 
			$this->enabled = false;
		
		// Specify the form action url
		$this->form_action_url = $this->getActionURL();
		$this->sort_order = MODULE_PAYMENT_ANZ_SORT_ORDER;
		if ((int)MODULE_PAYMENT_ANZ_ORDER_STATUS_ID > 0) 
			$this->order_status = MODULE_PAYMENT_ANZ_ORDER_STATUS_ID;

		if (is_object($order)) $this->update_status();
	}
	

	/**
	 * Return with the Javascript validation for receiving CC details
	 * from the form (help make validation more efficient/effective)
	 * 
	 * @return String Validation to be used in the checkout form if required 
	 */
	function javascript_validation() {
		// If operating as Merchant Hosted Web Payment Pages

			// Specify Javascript to validate the form elements
			// Credits: OSCommerce Javascript Validation from cc.php
			$js = '  if (payment_value == "' . $this->code . '") {' . "\n" .
			    '    var cc_owner = document.checkout_payment.cc_via_migs_cc_owner.value;' . "\n" .
			    '    var cc_number = document.checkout_payment.cc_via_migs_cc_number.value;' . "\n" .
			    '    if (cc_owner == "" || cc_owner.length < ' . CC_OWNER_MIN_LENGTH . ') {' . "\n" .
			    '      payment_error = payment_error + "' . MODULE_PAYMENT_ANZ_TEXT_JS_CC_OWNER . '";' . "\n" .
			    '      error = 1;' . "\n" .
			    '    }' . "\n" .
			    '    if (cc_number == "" || cc_number.length < ' . CC_NUMBER_MIN_LENGTH . ') {' . "\n" .
			    '      payment_error = payment_error + "' . MODULE_PAYMENT_ANZ_TEXT_JS_CC_NUMBER . '";' . "\n" .
			    '      error = 1;' . "\n" .
			    '    }' . "\n" .
			    '  }' . "\n";
			
			return $js;

	}
	
	/**
	 * Update the status of whether this payment module is available
	 * to check out with
	 * Reference: OSCommerce Payment Module
	 */
	function update_status() {
		/* Check whether the zones/geo_zones is valid */
		global $order;
		if (((int) MODULE_PAYMENT_ANZ_VALID_ZONE > 0)) {
			$check_flag = false;
			$check_query = tep_db_query("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . MODULE_PAYMENT_ANZ_VALID_ZONE . "' and zone_country_id = '".$order->delivery['country']['id']."' order by zone_id");
			while ($check = tep_db_fetch_array($check_query)) {
				if ($check['zone_id'] < 1) {
					$check_flag = true;
					break;
				}
				elseif ($check['zone_id'] == $order->delivery['zone_id']) {
					$check_flag = true;
					break;
				}
			}
			/* Set whether this should be valid or not */
			if ($check_flag == false) {
				$this->enabled = false;
			}
		}
	}

	

	/**
	 * Creates a selection array that defines the required fields 
	 * when providing this module as a potential payment method
	 * @return Array containing the module/form information to be used rendering
	 * 				 the form
	 */
	function selection() {
		// If operating as Merchant Hosted Web Payment Pages

			// Specify the required form fields	
      		global $order;
			// Determine Expiry Month Field
			for ($i = 1; $i < 13; $i ++) {
				$expires_month[] = array ('id' => sprintf('%02d', $i), 'text' => strftime('%B', mktime(0, 0, 0, $i, 1, 2000)));
			}
			// Determine Expiry Year Field
			$today = getdate();
			for ($i = $today['year']; $i < $today['year'] + 10; $i ++) {
				$expires_year[] = array ('id' => strftime('%y', mktime(0, 0, 0, 1, 1, $i)), 'text' => strftime('%Y', mktime(0, 0, 0, 1, 1, $i)));
			}
			// Build the array with the fields
			// TODO: Use hidden Payment Attempt field
			$selection = array ('id' => $this->code, 'module' => $this->title, 'fields' => array (array ('title' => MODULE_PAYMENT_ANZ_TEXT_CREDIT_CARD_OWNER, 'field' => tep_draw_input_field('cc_via_migs_cc_owner', $order->billing['firstname'].' '.$order->billing['lastname'])), array ('title' => MODULE_PAYMENT_ANZ_TEXT_CREDIT_CARD_NUMBER, 'field' => tep_draw_input_field('cc_via_migs_cc_number')), array ('title' => MODULE_PAYMENT_ANZ_TEXT_CREDIT_CARD_EXPIRES, 'field' => tep_draw_pull_down_menu('cc_via_migs_cc_expires_month', $expires_month).'&nbsp;'.tep_draw_pull_down_menu('cc_via_migs_cc_expires_year', $expires_year)), array ('title' => MODULE_PAYMENT_ANZ_TEXT_CREDIT_CARD_CARD_SECURITY_CODE, 'field' => tep_draw_input_field('cc_via_migs_cc_securitycode', '', 'size="4" maxlength="4"').'&nbsp;<small>'.MODULE_PAYMENT_ANZ_TEXT_CREDIT_CARD_CARD_SECURITY_CODE_LOCATION.'</small>')));			
			return $selection;	
			

	}

	/**
	 * Performs required validation to check and ensure that the 
	 * submitted form information appears correct before performming the 
	 * transaction through the confirmation screen.
	 * 
	 * Uses the cc_validation.php class to check the CC Number, expiry date
	 * and redirects an $error string containing the Friendly Error Message
	 * to the Checkout Payment screen
	 */
	function pre_confirmation_check() {
		// If operating as Merchant Hosted Web Payment Pages

			global $HTTP_POST_VARS;			
			include (DIR_WS_CLASSES.'cc_validation.php');
			
			// Perform validation through the cc_validation class
			$cc_validation = new cc_validation();
			$result = $cc_validation->validate($HTTP_POST_VARS['cc_via_migs_cc_number'], $HTTP_POST_VARS['cc_via_migs_cc_expires_month'], $HTTP_POST_VARS['cc_via_migs_cc_expires_year']);			
			$error = '';
			switch ($result) {
				case -1 :
					$error = sprintf(TEXT_CCVAL_ERROR_UNKNOWN_CARD, substr($cc_validation->cc_number, 0, 4));
					break;
				case -2 :
				case -3 :
				case -4 :
					$error = TEXT_CCVAL_ERROR_INVALID_DATE;
					break;
				case false :
					$error = TEXT_CCVAL_ERROR_INVALID_NUMBER;
					break;
			}

			// Redirect the user if contains an error			
			if (($result == false) || ($result < 1)) {
				$payment_error_return = 'payment_error='.$this->code.'&error='.urlencode($error).'&cc_owner='.urlencode($HTTP_POST_VARS['cc_via_migs_cc_owner']).'&cc_via_migs_cc_expires_month='.$HTTP_POST_VARS['cc_via_migs_cc_expires_month'].'&cc_via_migs_cc_expires_year='.$HTTP_POST_VARS['cc_via_migs_cc_expires_year'];			
				tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
			}
			
			// Treat the CC details to ensure they are ready to be sent to a payment gateway
			$this->cc_card_type = $cc_validation->cc_type;
			$this->cc_card_number = $cc_validation->cc_number;	
			$this->cc_expiry_month = $cc_validation->cc_expiry_month;
			$this->cc_expiry_year = $cc_validation->cc_expiry_year;

		// Else allow filter through as no validation required
	}

	/**
	 * Return form fields displaying the confirmation information that will
	 * be used once they press the process button.
	 * 
	 * @return Array Confirmation elements array required to process the
	 * 				 form
	 */
	function confirmation() {
		// If operating as Merchant Hosted Web Payment Pages

			// Display the form details back to the user masking the credit card details
			global $HTTP_POST_VARS;
			$confirmation = array ('title' => $this->title.': '.$this->cc_card_type, 'fields' => array (array ('title' => MODULE_PAYMENT_ANZ_TEXT_CREDIT_CARD_OWNER, 'field' => $HTTP_POST_VARS['cc_via_migs_cc_owner']), array ('title' => MODULE_PAYMENT_ANZ_TEXT_CREDIT_CARD_NUMBER, 'field' => substr($this->cc_card_number, 0, 4).str_repeat('X', (strlen($this->cc_card_number) - 8)).substr($this->cc_card_number, -4)), array ('title' => MODULE_PAYMENT_ANZ_TEXT_CREDIT_CARD_EXPIRES, 'field' => strftime('%B, %Y', mktime(0, 0, 0, $HTTP_POST_VARS['cc_via_migs_cc_expires_month'], 1, '20'.$HTTP_POST_VARS['cc_via_migs_cc_expires_year'])))));
			//return $confirmation;		

		return $confirmation;
	}

	/**
	 * Create the required Hidden Fields that contain the payment
	 * information to be used by the Payment Gateway (ANZ)
	 * 
	 * @return String Hidden Form Fields submitted to the action url
	 */
	function process_button() {
		global $HTTP_POST_VARS, $order;
		// If Submitting through the Merchant-Hosted Payment

			// Create all the required fields to be sent to the action url 
			// (Defined on page 44 of VPCIG) 
			// Required Fields
			$required_field_string = tep_draw_hidden_field('vpc_Version', 1) .
									 tep_draw_hidden_field('vpc_Command', 'pay') .
									 tep_draw_hidden_field('vpc_MerchTxnRef', $this->getMerchantTransactionReference()) .
									 // Don't include the Variables to the form
									 //tep_draw_hidden_field('vpc_AccessCode', $this->getAccessCode()) .
									 tep_draw_hidden_field('vpc_Merchant', $this->getMerchantID()) .
									 tep_draw_hidden_field('vpc_OrderInfo', $this->getCustId()) .
									 tep_draw_hidden_field('vpc_anzExtendedOrderInfo', $this->getCustName()) .
									 //tep_draw_hidden_field('vpc_Amount', intval((number_format($order->info['total'])) * 100)); // Convert to Cents by Multiplying by 100 
									 tep_draw_hidden_field('vpc_CardNum', $this->cc_card_number) .
									 tep_draw_hidden_field('vpc_CardExp', $HTTP_POST_VARS['cc_via_migs_cc_expires_year'] . $this->cc_expiry_month); // Optionally use: $HTTP_POST_VARS['cc_via_migs_cc_expires_month'] . $HTTP_POST_VARS['cc_via_migs_cc_expires_year']
			
			// Optional Fields
			$optional_field_string = '';
			if(!empty($HTTP_POST_VARS['cc_via_migs_cc_securitycode'])) {
				$optional_field_string .= tep_draw_hidden_field('vpc_CardSecurityCode' , $HTTP_POST_VARS['cc_via_migs_cc_securitycode']);
			}				 
			$optional_field_string .= tep_draw_hidden_field('vpc_TicketNo', $this->getTicketNumber());
			// Build the hidden fields
			$process_button_string = $required_field_string . $optional_field_string;
			return $process_button_string;			

	}

	/**
	 * Perform additional required tasks before the processing
	 * @return boolean Function response
	 */
	function before_process() {	
		global $order;
		$verifiedHash = false;
		$responseArray = array();
		// Check the status of the process
		if(empty($_GET['vpc_ReceiptNo'])) { // Payment hasn't been processed
			$verifiedHash = false;
			// Determine how to process the transaction

				// TODO: Process the Merchant hosted requirements				
				$verifiedHash = true;
				// Determine Required Fields
				$_POST['vpc_AccessCode'] = $this->getAccessCode(); 
//				$_POST['vpc_Amount'] = intval((number_format($order->info['total'])) * 100); // Convert to Cents by Multiplying by 100
				//$_POST['vpc_Amount'] = intval((round($order->info['total'],2)) * 100);

				if(MODULE_PAYMENT_ANZ_TEST_MODE=='Test')
					$_POST['vpc_Amount']=round($order->info['total'])*100;
				else 
					$_POST['vpc_Amount'] = number_format(($order->info['total']*100), 0, '', '');

				unset($_POST['x']);
				unset($_POST['y']);

				// Create the Request String
				$vpcURL = $this->getVPCUrl();
				$postRequestData = '';
				$amp = '';
				foreach($_POST as $key => $value) {
					if(!empty($value) && $key !== tep_session_name()) { // Eliminate the empty variables
						$postRequestData .= $amp . urlencode($key) . '=' . urlencode($value);
						$amp = '&';						
					}
				}


				
				if(function_exists("curl_init")){
				
				// Get the Secure Connection to the VPC and Buffer communication

				ob_start();
				$clientURL = curl_init();
				// Initialise the client url variables
				// REFER to curl_setopt for more options as suits your requirements
				// such as Verify SSL, Proxy etc
				

				curl_setopt( $clientURL, CURLOPT_SSL_VERIFYPEER, 0 );
				curl_setopt ($clientURL, CURLOPT_URL, $vpcURL);
				curl_setopt ($clientURL, CURLOPT_POST, 1);
				curl_setopt ($clientURL, CURLOPT_POSTFIELDS, $postRequestData);
				curl_exec ($clientURL); // Open connection
				$vpcResponse = ob_get_contents(); // Get result
				ob_end_clean(); // Finish with the buffer

				// Check for errors
				if(strchr($vpcResponse,"<html>")) $errorMessage = $vpcResponse;
				else if(curl_error($clientURL)) $errorMessage = "CURL ERROR: " . curl_errno($clientURL) . " " . curl_error($clientURL);
				// Communication Issues should be sent to Administrator, not to screen
				curl_close($clientURL); // Close the connection	
				} else {
				
				$host = 'migs.mastercard.com.au'; // domain only, no path info
				$path = '/vpcdps'; // path to cgi, asp, php program


				$fp = @fsockopen ("ssl://$host", 443, $errno, $errstr, 50);
				fputs($fp, "POST $path HTTP/1.1\r\n");
				fputs($fp, "Host: $host\r\n");
				fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
				fputs($fp, "Content-length: " . strlen($postRequestData) . "\r\n");

				fputs($fp, "Connection: close\r\n\r\n");
				fputs($fp, $postRequestData);

				while (!feof($fp)) {
					$data .= fgets($fp,128);
				}
				fclose($fp);

				// (OPTIONALLY strip header returned (for XML response only), use $data otherwise
				//ereg("<(.+)",$data,$matched);
				//$vpcResponse = $matched[1];
				$vpcResponse = $data;
				}

				$responseKeyVals = split("&", $vpcResponse);
			    foreach ($responseKeyVals as $val) {
			        $param = split("=", $val);
			        $responseArray[urldecode($param[0])] = urldecode($param[1]);
			    }
				if(!empty($errorMessage) && $responseArray['vpc_TxnResponseCode']=='') {
					$transactionResponse = '1';
				} else {
					// Process the results and determine the transactions status	
					$transactionResponse = $responseArray['vpc_TxnResponseCode'];
				}				

		} 

		// Check the status of the order
		if($transactionResponse !== '0') {
			// There was an error, redirect to appropriate screen and display text message	
		//tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'payment_error=' . urlencode((empty($responseArray['vpc_Message'])) ? MODULE_PAYMENT_ANZ_TEXT_ERROR : $responseArray['vpc_Message']), 'SSL', true, false));		
		tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'payment_error=ANZ', 'SSL', true, false));		
		} else {
			// Attempt to update some fields of the order in order to cache to database
			$order->info['cc_type'] = "AcqResponseCode: ".$responseArray['vpc_AcqResponseCode'];
			$order->info['cc_owner'] = "TransactionNo: " . $responseArray['vpc_TransactionNo'];
			$order->info['cc_number'] = "ReceiptNo: " . $responseArray['vpc_ReceiptNo'];
		}
	}

	/**
	 * Perform additional required tasks after the processing
	 * EG Mail details to store owner etc
	 * @return boolean Function response
	 */
	function after_process() {
		// TODO: Update Status of Order to Processing
		return false;	
	}

	/**
	 * Create an array that represents the possible module errors
	 * @return Array Errors that have arrived from HTTP 
	 */
	function get_error() {
		global $HTTP_GET_VARS;
		$error = array('title' => MODULE_PAYMENT_ANZ_TEXT_ERROR, 'error' => ((isset($HTTP_GET_VARS['error'])) ? stripslashes(urldecode($HTTP_GET_VARS['error'])) : MODULE_PAYMENT_ANZ_TEXT_ERROR_DESCRIPTION));
		return $error;
	}

	/**
	 * Checks whether the module has been installed 
	 * @return int 1 for installed
	 */
	function check() {
		if (!isset ($this->_check)) {
			$check_query = tep_db_query("select configuration_value from ".TABLE_CONFIGURATION." where configuration_key = 'MODULE_PAYMENT_ANZ_STATUS'");
			$this->_check = tep_db_num_rows($check_query);
		}

		return $this->_check;	
	}

	/**
	 * Performed when installing the ANZ Payment Processor
	 * SQL Inserts all the required configuration variables to be 
	 * assigned by the store owner in the administration screen
	 */
	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 ANZ Payment Module', 'MODULE_PAYMENT_ANZ_STATUS', 'False', 'Do you want to accept ANZ Bank?', '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_PAYMENT_ANZ_TEST_MODE', 'Test', 'Transaction mode used for processing orders', '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 ('ANZ Merchant ID', 'MODULE_PAYMENT_ANZ_MERCHANT_ID', '', 'The unique Merchant ID assigned to you by your Payment Provider. (alphanumeric, upto 16 digits long)', '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 ('ANZ Access Code', 'MODULE_PAYMENT_ANZ_ACCESS_CODE', '', 'The Access Code authenticates you on the Payment Server so that a merchant cannot access another merchant\'s Merchant ID (alphanumeric, 8 digits long)', '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 ('Sort order of display', 'MODULE_PAYMENT_ANZ_SORT_ORDER', '1', 'Sort order of display. Lowest is displayed first.', '6', '8', now())");
		tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('ANZ - Payment Zone', 'MODULE_PAYMENT_ANZ_ZONE', '3', 'ANZ - If a zone is selected, only enable this payment method for that zone.', '6', '8', 'tep_get_zone_class_title', 'tep_cfg_pull_down_zone_classes(', now())");
		tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('ANZ - Exclude these Countries', 'MODULE_PAYMENT_ANZ_EXCEPT_COUNTRY', '', 'ANZ - If countries are selected, disable this payment method for that countries.', '6', '9', 'tep_cfg_pull_down_zone_except_countries(MODULE_PAYMENT_ANZ_ZONE,', 'tep_get_zone_except_country', now())");
		tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('ANZ - Exclude these Zones', 'MODULE_PAYMENT_ANZ_EXCEPT_ZONE', '2', 'ANZ - If a zone is selected, disable this payment method for that zone.', '6', '10', 'tep_cfg_pull_down_zone_classes(','tep_get_zone_class_title', now())");
		tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('ANZ - Set Order Status', 'MODULE_PAYMENT_ANZ_ORDER_STATUS_ID', '2', 'ANZ - Set the status of orders made with this payment module to this value', '6', '11', 'tep_cfg_pull_down_order_statuses(', 'tep_get_order_status_name', now())");
		tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Display Name', 'MODULE_PAYMENT_ANZ_DISPLAY_NAME', 'ANZ Bank', 'Set the Display name to payment module', '6', '12', 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 ('Image', 'MODULE_PAYMENT_ANZ_IMAGE', 'anz', 'Set the Image of payment module', '6', '13', 'tep_cfg_file_field(', now())");

	}

	/**
	 * Performs a SQL delete statement to remove all configuration 
	 * variables for this payment module
	 */
	function remove() {
		$keys = $this->keys(); 
		foreach($keys as $configurationKeys) {
			tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key = '" . $configurationKeys . "'");	
		}
	}

	/**
	 * Returns immediately with a listing of all the keys used 
	 * with this payment module
	 * @return Array All the defined variables used by this module
	 */
	function keys() {
		return array('MODULE_PAYMENT_ANZ_STATUS',
					 'MODULE_PAYMENT_ANZ_ZONE',
					 'MODULE_PAYMENT_ANZ_EXCEPT_ZONE',
					 'MODULE_PAYMENT_ANZ_EXCEPT_COUNTRY',
					 'MODULE_PAYMENT_ANZ_SORT_ORDER',
					 'MODULE_PAYMENT_ANZ_MERCHANT_ID',
					 'MODULE_PAYMENT_ANZ_ACCESS_CODE',
					 'MODULE_PAYMENT_ANZ_TEST_MODE', 
					 'MODULE_PAYMENT_ANZ_VALID_ZONE',
					 'MODULE_PAYMENT_ANZ_BANKNAM',
					 'MODULE_PAYMENT_ANZ_ORDER_STATUS_ID',
					 'MODULE_PAYMENT_ANZ_DISPLAY_NAME',
					 'MODULE_PAYMENT_ANZ_IMAGE'
					 );
	}



	/**
	 * Returns immediately with whether this is operating in test mode
	 * References defined variable MODULE_PAYMENT_ANZ_TEST_MODE which
	 * should be configured in the administration panel.
	 * @return boolean Test Mode check
	 */
	function isTestMode() { 
		if(defined('MODULE_PAYMENT_ANZ_TEST_MODE') && MODULE_PAYMENT_ANZ_TEST_MODE == 'Test') 
			return true;	
		else if(defined('MODULE_PAYMENT_ANZ_TEST_MODE') && MODULE_PAYMENT_ANZ_TEST_MODE == 'Production')
			return false; 
		else
			return true;
	}

	/**
	 * Returns with the Action URL appropriate for this transaction
	 * Defaults to the Australian VPC URL
	 * Optional: Specify 
	 * MODULE_PAYMENT_ANZ_MERCHANT_HOSTED_PROCESS
	 * MODULE_PAYMENT_ANZ_SERVER_HOSTED_PROCESS
	 * in the define statements at top of the file to change the handler
	 * script
	 * @return String URL to action
	 */
	function getActionURL() {
	$handlerScript = FILENAME_CHECKOUT_PROCESS; // Don't change here, change at top of the file in the define(MODULE_PAYMENT_ANZ_MERCHANT_HOSTED_PROCESS)
	return tep_href_link($handlerScript, '', 'SSL');
	}

	/**
	 * Returns with the VPC used for Server Hosted Transactions
	 * Note: Specify the correct VPC for your application in the
	 * MODULE_PAYMENT_ANZ_INTEGRATION_MODEL_SERVER_HOSTED_VPC_URL
	 * MODULE_PAYMENT_ANZ_INTEGRATION_MODEL_MERCHANT_HOSTED_VPC_URL
	 * defined variable at the top of this message
	 * @return String VPC used for the Server Hosted Transactions
	 */
	function getVPCUrl() { 
		// Default is the Australian VPC
		return 'https://migs.mastercard.com.au/vpcdps'; // Don't Change here, change in the commented code at top of file		 
	}

	/**
	 * Returns with the Merchant ID
	 * References defined variable MODULE_PAYMENT_ANZ_MERCHANT_ID
	 * @return String Treated Merchant ID
	 */
	function getMerchantID() {
		// PREFIX the word 'TEST' to the merchant ID if in Simulator infrastructure
		if($this->isTestMode()) $prefix = 'TEST';
		return($prefix . trim(MODULE_PAYMENT_ANZ_MERCHANT_ID));
	}
	
	/**
	 * Returns immediately with the Access Code
	 * Note: Better to leave this to the migs_server_process.php
	 * @return String Alphanumeric MIGS Account Access Code
	 */
	function getAccessCode() { 
		if(defined('MODULE_PAYMENT_ANZ_ACCESS_CODE')) {
			return(trim(MODULE_PAYMENT_ANZ_ACCESS_CODE));
		}
		return 'notfound';
	}
	
	/**
	 * Returns with the Merchant Transaction Reference
	 * Builds from the order info
	 * @return String Merchant Transaction Reference 
	 */
	function getMerchantTransactionReference() { 
		// TODO: Integrate payment attempt logging
		$attempt = '1';
		return($this->getCustId() . '/' . $attempt);
	}
	
	/**
	 * Returns with the Order Information for the process
	 * @return String Order Info String
	 */
	function getCustId() {
		global $customer_id;
		// Todo: Set a way to match up the records
		$uniqueKey = $customer_id . 'AT' . date("YmdHis");
		// PREFIX the word 'test' to the merchant transaction reference if in Simulator infrastructure
		if($this->isTestMode()) $prefix = 'test';		
		// TODO: Use a unique Transaction Reference Number for this order		
		$transactionReferenceNumber = $uniqueKey; // Should be based off a shopping cart number, an order number or and invoice number
		return($prefix . $transactionReferenceNumber);		
	}
	
	function getCustName(){
		global $order; 
		// Remove any extra white space
		$name = trim($order->customer['firstname'].' '.$order->customer['lastname']);
		// Remove any troublesome quotes
		return  preg_replace('/(\s\s+|\'|\"|\`)/', '', $name);
	}

	/**
	 * Return with the Locale for this order
	 * Used in SSL type transactions for specifying the language that is used on the 
	 * Payment Server pages that are displayed to the cardholder.
	 * Specified using MODULE_PAYMENT_ANZ_LOCALE in the Language File 
	 * @return String Locale
	 */
	function getLocale() {
		// Get the locale from the language specification
		if(defined('MODULE_PAYMENT_ANZ_LOCALE')) {
			return MODULE_PAYMENT_ANZ_LOCALE;	
		}
		// Default for Australia
		return 'en_AU'; // Don't change here, change in the define(MODULE_PAYMENT_ANZ_LOCALE) in the language file
	}
	
	/**
	 * Return with the URL to forward the response from the server to
	 * The URL that is displayed to the cardholder's browser when the
	 * Payment Server sends the transaction response
	 * 
	 * Based off HTTPS_SERVER specified in OSCommerce Configuration
	 * and MODULE_PAYMENT_ANZ_RETURN_HANDLER
	 * 
	 * @return String URL handling the response from the Payment Server
	 */
	function getReturnURL() { 
		//$url = HTTPS_SERVER . MODULE_PAYMENT_ANZ_RETURN_HANDLER; // https://www.mink.net.au/migs_return.php 
		if(defined('MODULE_PAYMENT_ANZ_RETURN_HANDLER')) {
			$returnHandler = MODULE_PAYMENT_ANZ_RETURN_HANDLER;
		} else {
			$returnHandler = FILENAME_CHECKOUT_PROCESS; // Don't change here, change in the define(MODULE_PAYMENT_ANZ_RETURN_HANDLER) at top of file
		}
		$url = tep_href_link($returnHandler, '', 'SSL', false);		
		return($url);		
	}
	
	
	/**
	 * Returns with the Ticket Number to be associated with the Payment
	 * @return String Ticket Number
	 */
	function getTicketNumber() { 
		//TODO: Implement a way to uniquely identify the Order Contents (such as airline ticket number)
		global $customer_id;
		return($customer_id);
	}
	
}
?>