<?php
 /**
  @name       loadedpayments.php   
  @version    1.0.0 | 05-21-2012 | datazen
  @author     Loaded Commerce Core Team
  @copyright  (c) 2012 LOADEDPAYMENTS.com
  @license    GPL2
*/
class loadedpayments {
  var $code, $title, $subtitle, $description, $sort_order, $enabled, $version, $form_action_url, $pci, $allowed_types = array();

  // class constructor
  function __construct() {
    $this->code = 'loadedpayments';
    $this->title = (defined('MODULE_PAYMENT_LOADEDPAYMENTS_TEXT_TITLE') && MODULE_PAYMENT_LOADEDPAYMENTS_TEXT_TITLE != NULL) ? MODULE_PAYMENT_LOADEDPAYMENTS_TEXT_TITLE : NULL;
    $this->subtitle = (defined('MODULE_PAYMENT_LOADEDPAYMENTS_TEXT_SUBTITLE') && MODULE_PAYMENT_LOADEDPAYMENTS_TEXT_SUBTITLE != NULL) ? MODULE_PAYMENT_LOADEDPAYMENTS_TEXT_SUBTITLE : NULL;
    $this->description = (defined('MODULE_PAYMENT_LOADEDPAYMENTS_TEXT_DESCRIPTION') && MODULE_PAYMENT_LOADEDPAYMENTS_TEXT_DESCRIPTION != NULL) ? MODULE_PAYMENT_LOADEDPAYMENTS_TEXT_DESCRIPTION : NULL;
    $this->sort_order = (defined('MODULE_PAYMENT_LOADEDPAYMENTS_SORT_ORDER') && MODULE_PAYMENT_LOADEDPAYMENTS_SORT_ORDER != NULL) ? (int)MODULE_PAYMENT_LOADEDPAYMENTS_SORT_ORDER : NULL;
    $this->enabled = (defined('MODULE_PAYMENT_LOADEDPAYMENTS_STATUS') && MODULE_PAYMENT_LOADEDPAYMENTS_STATUS == 'True') ? TRUE : FALSE;
    $this->version = (!file_exists(DIR_WS_CLASSES . 'rci.php')) ? 'OSC' : 'LC'; 
    //$this->form_action_url = 'loadedpayments.php';  
    $this->pci = TRUE;
    // create the credit card array
    $card_types = array('American Express' => MODULE_PAYMENT_LOADEDPAYMENTS_TEXT_AMEX,
                        'Mastercard' => MODULE_PAYMENT_LOADEDPAYMENTS_TEXT_MASTERCARD,
                        'Discover' => MODULE_PAYMENT_LOADEDPAYMENTS_TEXT_DISCOVER,
                        'Visa' => MODULE_PAYMENT_LOADEDPAYMENTS_TEXT_VISA);    

    $cc_array = (defined('MODULE_PAYMENT_LOADEDPAYMENTS_ACCEPTED_CC') && MODULE_PAYMENT_LOADEDPAYMENTS_ACCEPTED_CC != NULL) ? explode(', ', MODULE_PAYMENT_LOADEDPAYMENTS_ACCEPTED_CC) : array();
	foreach($cc_array as $key=>$value) {
      $this->allowed_types[$value] = $card_types[$value];
    }
    $_SESSION['payform_url'] = (defined('MODULE_PAYMENT_LOADEDPAYMENTS_TESTMODE') && MODULE_PAYMENT_LOADEDPAYMENTS_TESTMODE != 'Test') ? 'https://secure1.payleap.com/plcheckout.aspx' : 'https://uat.payleap.com/plcheckout.aspx'; 
    $this->url = (defined('MODULE_PAYMENT_LOADEDPAYMENTS_TESTMODE') && MODULE_PAYMENT_LOADEDPAYMENTS_TESTMODE != 'Test') ? 'https://secure1.payleap.com/TransactServices.svc/' : 'https://uat.payleap.com/TransactServices.svc/';   
    //Set the select action
    $this->setPageCode();
  }
 /**
  * Update the module status
  *
  * @access public
  * @return void
  */  
  function update_status() {
    global $order;
    if ( ($this->enabled == true) && ((int)MODULE_PAYMENT_LOADEDPAYMENTS_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_LOADEDPAYMENTS_ZONE . "' and zone_country_id = '" . $order->billing['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->billing['zone_id']) {
          $check_flag = true;
          break;
        }
      }
      if ($check_flag == false) {
        $this->enabled = false;
      }
    }
  }  
  //This function called when user select the radio button
  function setPageCode() {
	global $obj_catalog;
	$str_js = 'if(value == \'loadedpayments\'){
		  $(\'#ccbox_loadedpayments\').show(500);
		  $(\'#process_payment\').css(\'display\',\'inline-block\');
		}';
	if(is_object($obj_catalog))
		$obj_catalog->set_hooks_js($str_js, 'onselectAction');
  }
 /**
  * Javascript validation logic
  *
  * @access public
  * @return boolean
  */  
  function javascript_validation() {
    return false;
  }
 /**
  * Get the card image string
  *
  * @access public
  * @return string
  */ 
  function get_cc_images() {
    $cc_images = '';
    reset($this->allowed_types);
	foreach($this->allowed_types as $key=>$value) {
      if ($key == 'American Express') $key = 'amex'; 
      $cc_images .= tep_image(DIR_WS_IMAGES . 'cards/lp_' . strtolower(str_replace(" ", "", $key)) . '.gif', $value);
    }

    return $cc_images;
  }
 /**
  * Create the payment selection string
  *
  * @access public
  * @return array
  */    
  function selection() {
  	  $list = array(array('id' => '', 'text' => 'Select Card'));
  	  $list[]= array('id' => 'newcard', 'text' => 'Add New Card');
  	  $existing_payment_query  = tep_db_query("SELECT * FROM customers_cc_info WHERE customers_id = '".$_SESSION['customer_id']."' AND cc_type = 'loadedpayments' order by date_added");
  	  if(tep_db_num_rows($existing_payment_query) > 0){
  	  	  $loop =1;
  		  while($rw_list = tep_db_fetch_array($existing_payment_query)){
  		  	  if($loop == 1){
  		  	    $sel_payment_profile_id = $rw_list['customers_token_id'];
  		  	  }
  			  $list[] = array('id' => $rw_list['customers_token_id'],
                                'text' => $rw_list['customers_card_number']);
  
                         $loop++;
  		  }
  	  }

	  $selection = array('id' => $this->code,
		'module' => $this->title,
		'fields' => array(
					array('title' => 'CUSTOMCC', 'field' => 'CUSTOMCC'),
					array('title' => 'HIDDEN', 'field' => '<input type="hidden" name="loadedpayment_token" id="loadedpayment_token" value=""/><input type="hidden" name="loadedpayment_sessionid" id="loadedpayment_sessionid" value=""/>')
			  ));
			  
   /* $selection = array('id' => $this->code,
                       'module' => '<table><tr><td width="260px" class="main" style=:font-weight:bold;">' . $this->title . '</td><td>' . $this->get_cc_images() . '</td></tr><tr><td colspan="2" class="main" style="font-weight:normal;">' . MODULE_PAYMENT_LOADEDPAYMENTS_BUTTON_DESCRIPTION . '</td></tr></table>');
                       */
    return $selection;
  }
 /**
  * Perform the pre confirmaiton actions
  *
  * @access public
  * @return boolean
  */  
  function pre_confirmation_check() {
    global $cart;
    if (isset($cart->cartID) && $cart->cartID != '') {
      $cartID = $cart->cartID;     
    } else {
      $cartID = $cart->generate_cart_id();
    }
    if ((!isset($_SESSION['cartID'])) || (isset($_SESSION['cartID']) && $_SESSION['cartID'] == '')) {
      $_SESSION['cartID'] = $cartID;
    }
    return true;
  }
 /**
  * Perform the confirmation actions
  *
  * @access public
  * @return array
  */
  function confirmation() {
   false;
  }
 /**
  * Create the process button string
  *
  * @access public
  * @return string
  */
    function process_button() {
     // Change made by using ADC Direct Connection
      $process_button_string = tep_draw_hidden_field('x_Card_Code', str_replace('_','',$_POST['authorizenet_cc_checkcode'])) .
                               tep_draw_hidden_field('x_Card_Num', $this->cc_card_number) .
                                tep_draw_hidden_field('x_Exp_Date', $this->cc_expiry_year.'-'.$this->cc_expiry_month);

      $process_button_string .= tep_draw_hidden_field(tep_session_name(), tep_session_id());
      return $process_button_string;
    }

 /**
  * Perform before process actions
  *
  * @access public
  * @return string
  */    
    function before_process() {
	global $response,$insert_id,$order, $messageStack, $lc_createOrder;
	//print_r($order);exit;
	$noerror = 0;
	if(trim($_POST['loadedpayment_token']) != '' ||  trim($_POST['loadedpayments_existing_card']) != '') {
		$payment_processing_method = 'nonce';	
		$noerror = 1;
        } 
	 if($noerror)
	 {
	 
		$token = (isset($_POST['loadedpayments_existing_card']) &&  $_POST['loadedpayments_existing_card'] != '')? $_POST['loadedpayments_existing_card']: $_POST['loadedpayment_token'];
		$sessionid = $_POST['loadedpayment_sessionid'];
		$transaction_mode = 'Sale';
		$transaction_array = array();
		$total =  number_format($order->info['total'], 2, '.', '');
		$ExtData= '<InvNum>'.$insert_id.'</InvNum><CustomerId>'.$_SESSION['customer_id'].'</CustomerId><BillTo><Name>'.$order->billing['firstname'].' '.$order->billing['firstname'].'</Name><Address>'.$order->billing['street_address'].'</Address><City>'.$order->billing['city'].'</City><State>'.$order->billing['state'].'</State><Zip>'.$order->billing['postcode'].'</Zip><Email>'.$order->billing['email_address'].'</Email></BillTo>';
		$process_url = $this->url.'ProcessDebitOrCreditCardWithAccountToken?UserName='.MODULE_PAYMENT_LOADEDPAYMENTS_USERNAME.'&Password='.MODULE_PAYMENT_LOADEDPAYMENTS_TRANSKEY.'&TransType='.$transaction_mode.'&accounttoken='.$token.'&Amount='.$total.'&PNRef=&ExtData='.urlencode($ExtData);
		
		
		$debugRequest = $process_url;
		
		$response = $this->curl_process($process_url);
		$debugResponse = $response;
		//print_r($response);exit;
		$debugdata = array('request'=>$debugRequest, 'respose'=>$debugResponse);
		$lc_createOrder->appendDebugData($insert_id, 'loadedPaymentData', $debugdata);
		if($response['Result'] == '0'){
		   $trasnaction_id = $response['AuthCode'];
		   $card_type = $response['CardType'];
		   $approval_code = $response['PNRef'];	
		   $monthyear = $response['ExpDate'];
		   $exp_month =  substr($monthyear,0,2);
		   $exp_year =  substr($monthyear,-2,2);
		   
		   if(isset($_POST['loadedpayment_token']) &&  $_POST['loadedpayment_token'] != ''){
		     //INSERT TO CC INFO TABLE
		     $card_number = "XXXX-XXXX-XXXX-" . $response['LastFourOfCard'];
		     $monthyear = explode('/',$_POST['loadedpayments_cc_expires']);
		     $meta_data_arr['loaded_token_id'] = $token;
		     $meta_data = json_encode($meta_data_arr);
		     tep_db_query("INSERT INTO  customers_cc_info set customers_id = '".$_SESSION['customer_id']."', card_number = '".$card_number."',card_type = '".$card_type."',
			  exp_month = '".$exp_month."', exp_year = '".$exp_year."', meta_data = '".$meta_data."' , cc_type = 'loadedpayments', date_added = now()");
		  
		   }
		   //Update the transaction ID to the order
		   tep_db_query("UPDATE " . TABLE_ORDERS . " SET transaction_id='".$trasnaction_id."', approval_code='".$approval_code."', is_capture = 1, orders_status = '".MODULE_PAYMENT_LOADEDPAYMENTS_ORDER_STATUS_ID."' where orders_id = '" . (int)$insert_id . "'");
		}else{
		    $errormsg = $response['RespMSG'];
		    tep_db_query('delete from ' . TABLE_ORDERS_TOTAL . ' where orders_id = "' . (int)$insert_id . '"');
		    tep_db_query('delete from ' . TABLE_ORDERS_STATUS_HISTORY . ' where orders_id = "' . (int)$insert_id . '"');
		    tep_db_query('delete from ' . TABLE_ORDERS_PRODUCTS . ' where orders_id = "' . (int)$insert_id . '"');
		    $messageStack->add_session('checkout',$errormsg, 'error');
		    tep_redirect(tep_href_link(FILENAME_CHECKOUT, '', 'SSL', true, false));
		}
		
	  }
	  
    }

    function after_process() {
      return false;
    }

 /**
  * Send the order email
  *
  * @access public
  * @return boolean
  */  
	function curl_process($curl_url){
		   $crl = curl_init();
		   curl_setopt($crl, CURLOPT_URL, $curl_url);
		   curl_setopt($crl, CURLOPT_FRESH_CONNECT, true);
		   curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);
		   $response = curl_exec($crl);
		   if(!response){
		      die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
		   }
		   curl_close($crl);
		   $repdata = simplexml_load_string($response); 
		   $encodedata = json_encode($repdata); 
		   $dataarr = json_decode($encodedata, true); 

			return $dataarr;
	}
	function header_js() {
		$jstags = '';
		if($this->enabled == true) {
			if(MODULE_PAYMENT_LOADEDPAYMENTS_TESTMODE != 'Test') {
			 $jstags = '<script type="text/javascript" src="https://secure1.payleap.com/js/tokenizer_v2.4.js" charset="utf-8"> </script>';
			}else{
			  $jstags = '<script type="text/javascript" src="https://uat.payleap.com/js/tokenizer_uat_v2.4.js" charset="utf-8"></script>';
			}
		}
		return $jstags;
	}  

	function rpc_get_session_id() {
		echo self::get_session_id();
	}

	private static function get_session_id() {
		   $creaturl = (defined('MODULE_PAYMENT_LOADEDPAYMENTS_TESTMODE') && MODULE_PAYMENT_LOADEDPAYMENTS_TESTMODE != 'Test') ? 'https://secure1.payleap.com/TransactServices.svc/CreateTransactionSession' : 'https://uat.payleap.com/TransactServices.svc/CreateTransactionSession'; 
		   //$creaturl.'?UserName='.MODULE_PAYMENT_LOADEDPAYMENTS_USERNAME.'&Password='.MODULE_PAYMENT_LOADEDPAYMENTS_TRANSKEY;
		   $curl_url = $creaturl.'?UserName='.urlencode(MODULE_PAYMENT_LOADEDPAYMENTS_USERNAME).'&Password='.urlencode(MODULE_PAYMENT_LOADEDPAYMENTS_TRANSKEY);
		   $crl = curl_init();
		   curl_setopt($crl, CURLOPT_URL, $curl_url);
		   curl_setopt($crl, CURLOPT_FRESH_CONNECT, true);
		   curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);
		   $response = curl_exec($crl);
		   if(!response){
		      die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
		   }
		   curl_close($crl);
		   $repdata = simplexml_load_string($response); 
		   $encodedata = json_encode($repdata); 
		   $dataarr = json_decode($encodedata, true); 
		   if(isset($dataarr['SessionId']) && $dataarr['SessionId'] != ''){
		     $return_data =  $dataarr['SessionId'];
		   }else{
		   $return_data =  'ERROR';
		   }
		return $return_data;
	}

	function footer_js() {
		$jscode = '';
		if($this->enabled == true && (defined('MODULE_PAYMENT_LOADEDPAYMENTS_USERNAME') && trim(MODULE_PAYMENT_LOADEDPAYMENTS_USERNAME) != '')) {
		$jscode = '
			if(sel_method == \'loadedpayments\') {
			if($("#loadedpayments_existing_card").val() == ""){
				var params = \'\';
				$.ajax({
					type:\'post\',
					data: params,
					url:\'ajax_handler.php?action=loadedpayments/get_session_id\',
					success:function(retval)
					{
					    if(retval != \'ERROR\'){

						var expdateformat = $("#loadedpayments-cc-exp").val();
						var expdate = expdateformat.replace("/", "");		  

						  TokenUtility.setSessionId({
						     SessionId: retval
						  });
						  TokenUtility.CreateAccountToken({
							 SessionId: retval,
							 nameoncard: $("#loadedpayments-cc-name").val(),
							 cardnum: $("#loadedpayments-cc-number").val(),
							 expdate: expdate
						     },
						     function(response) {

							if("0"== response.Result) {
							   //alert(response.AccountToken);
							   var token =  $("#loadedpayment_token").val(response.AccountToken);
							    $("#loadedpayment_sessionid").val(retval);
							    $("#loadedpayments-cc-number").val(\'\');
							    $("#loadedpayments-card-code").val(\'\');
							    document.getElementById("checkout_payment").submit();
							}
							else{
							   alert(response.Message);
							}
						     });
					    }
					}
				});			  
				return false;
			      }
			}

			';
		}
		return $jscode;
	}  
 /**
  * Check the status of the payment module
  *
  * @access public
  * @return integer
  */
  function check() {
    if (!isset($this->_check)) {
      $check_query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_LOADEDPAYMENTS_STATUS'");
      $this->_check = tep_db_num_rows($check_query);
    }
    return $this->_check;
  }
 /**
  * Install the module
  *
  * @access public
  * @return void
  */
  function install() {
    $check_query = tep_db_query("select orders_status_id from " . TABLE_ORDERS_STATUS . " where orders_status_name = 'Preparing [Loaded Payments]' limit 1");
    if (tep_db_num_rows($check_query) < 1) {
      $status_query = tep_db_query("select max(orders_status_id) as status_id from " . TABLE_ORDERS_STATUS);
      $status = tep_db_fetch_array($status_query);
      $status_id = $status['status_id']+1;
      $languages = tep_get_languages();
      for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
        tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . $status_id . "', '" . $languages[$i]['id'] . "', 'Preparing [Loaded Payments]')");
      }
      $flags_query = tep_db_query("describe " . TABLE_ORDERS_STATUS . " public_flag");
      if (tep_db_num_rows($flags_query) == 1) {
        tep_db_query("update " . TABLE_ORDERS_STATUS . " set public_flag = 0 and downloads_flag = 0 where orders_status_id = '" . $status_id . "'");
      }
    } else {
      $check = tep_db_fetch_array($check_query);
      $status_id = $check['orders_status_id'];
    }    
    // remove any old test mode value
    tep_db_query("delete from " . TABLE_CONFIGURATION . " WHERE configuration_key = 'MODULE_PAYMENT_LOADEDPAYMENTS_TESTMODE'");    
    // insert the new values
    tep_db_query("insert ignore into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable Loaded Payments Module', 'MODULE_PAYMENT_LOADEDPAYMENTS_STATUS', 'True', 'Do you want to accept transparent payments through Loaded Payments?', '6', '0', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
    tep_db_query("insert ignore into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('API Username', 'MODULE_PAYMENT_LOADEDPAYMENTS_USERNAME', '', 'Enter your Loaded Payments API Username', '6', '0', now())");
    tep_db_query("insert ignore into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Transaction Key', 'MODULE_PAYMENT_LOADEDPAYMENTS_TRANSKEY', '', 'Enter your Loaded Payments Transaction Key', '6', '0', now())");
    //tep_db_query("insert ignore into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Configured Form URL', 'MODULE_PAYMENT_LOADEDPAYMENTS_FORM_URL', '', 'Enter your Loaded Payments Configured Form URL.  Leave blank to use the Programatic Form Method with custom stylesheet. ', '6', '0', now())");
    if ($this->version == 'OSC') {
      tep_db_query("insert ignore into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Credit Cards Display', 'MODULE_PAYMENT_LOADEDPAYMENTS_ACCEPTED_CC', 'MasterCard, Visa', 'The credit card images you want displayed on the payment page.', '6', '0', now())");  
    } else {
      tep_db_query("insert ignore into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Credit Cards Display', 'MODULE_PAYMENT_LOADEDPAYMENTS_ACCEPTED_CC', 'MasterCard, Visa', 'The credit card images you want displayed on the payment page.', '6', '0', '_selectLPOptions(array(\'American Express\',\'Discover\',\'MasterCard\',\'Visa\'), ', now())");
    }    
    tep_db_query("insert ignore 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_LOADEDPAYMENTS_TESTMODE', 'Test', 'Transaction mode used for processing orders', '6', '0', 'tep_cfg_select_option(array(\'Test\', \'Production\'), ', now())");
    tep_db_query("insert ignore into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort Order', 'MODULE_PAYMENT_LOADEDPAYMENTS_SORT_ORDER', '0', 'Sort order of display (lowest is displayed first)', '6', '0', now())");
    tep_db_query("insert ignore into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Payment Zone', 'MODULE_PAYMENT_LOADEDPAYMENTS_ZONE', '0', 'If a zone is selected, only enable this payment method for that zone', '6', '2', 'tep_get_zone_class_title', 'tep_cfg_pull_down_zone_classes(', now())");
    tep_db_query("insert ignore into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Pending Order Status', 'MODULE_PAYMENT_LOADEDPAYMENTS_ORDER_STATUS_ID', '0', 'For Pending orders, set the status of orders made with this payment module to this value.  Default is \'Preparing [Loaded Payments]\'', '6', '0', 'tep_cfg_pull_down_order_statuses(', 'tep_get_order_status_name', now())");
    tep_db_query("insert ignore into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Completed Order Status', 'MODULE_PAYMENT_LOADEDPAYMENTS_ORDER_STATUS_COMPLETE_ID', '0', 'For Completed orders, set the status of orders made with this payment module to this value', '6', '0', 'tep_cfg_pull_down_order_statuses(', 'tep_get_order_status_name', now())");

    if ($this->version == 'OSC') {                  
      tep_db_query("ALTER IGNORE TABLE `orders` ADD `payment_info` TEXT;");                     
    }  
  }
 /**
  * Remove the payment module
  *
  * @access public
  * @return void
  */    
  function remove() {
    tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
    // remove order status 
    tep_db_query("delete from " . TABLE_ORDERS_STATUS . " where orders_status_name = 'Preparing [Loaded Payments]'");
    if ($this->version == 'OSC') {                  
      tep_db_query("ALTER IGNORE TABLE `orders` DROP `payment_info`;");                     
    }    
  }
 /**
  * Return the configuration values
  *
  * @access public
  * @return array
  */
  function keys() {
    return array('MODULE_PAYMENT_LOADEDPAYMENTS_STATUS', 
                 'MODULE_PAYMENT_LOADEDPAYMENTS_USERNAME', 
                 'MODULE_PAYMENT_LOADEDPAYMENTS_TRANSKEY', 
                 //'MODULE_PAYMENT_LOADEDPAYMENTS_FORM_URL', 
                 'MODULE_PAYMENT_LOADEDPAYMENTS_ACCEPTED_CC',
                 'MODULE_PAYMENT_LOADEDPAYMENTS_TESTMODE', 
                 'MODULE_PAYMENT_LOADEDPAYMENTS_SORT_ORDER',
                 'MODULE_PAYMENT_LOADEDPAYMENTS_ZONE',
                 'MODULE_PAYMENT_LOADEDPAYMENTS_ORDER_STATUS_ID',
                 'MODULE_PAYMENT_LOADEDPAYMENTS_ORDER_STATUS_COMPLETE_ID');
  }
} // end class
/**
* Create the checkbox options string
*
* @access public
* @return array
*/
function _selectLPOptions($select_array, $key_value, $key = '') {
  for ($i=0; $i<(sizeof($select_array)); $i++) {
    $name = (($key) ? 'configuration[' . $key . '][]' : 'configuration_value');
    $string .= '<br><input type="checkbox" name="' . $name . '" value="' . $select_array[$i] . '"';
    $key_values = explode(", ", $key_value);
    if (in_array($select_array[$i], $key_values)) $string .= ' checked="checked"';
    $string .= '> ' . $select_array[$i];
  }
  
  return $string;
}
if (!function_exists('tep_db_decoder')) {
  function tep_db_decoder($string) {
    $string = str_replace('&#39;', "'", $string);
    $string = str_replace('&#39', "'", $string); //backward compatabiliy
    return $string;
  }
}  
?>