<?php
/*
  $Id: authorizenet.php,v 1.4 2020/03/05 00:36:42 devidash Exp $

  Loaded Commerce, Open Source E-Commerce Solutions
  https://www.loadedcommerce.com

  Copyright (c) 2020 loadedcommerce

 */

// define('FILENAME_AUTHORIZENET_HELP', 'authnet_help.html');

  class authorizenet {
    var $code, $title, $description, $enabled, $sort_order;
    var $accepted_cc, $card_types, $allowed_types;

// class constructor
  function __construct() {
    global $order;

    $this->pci = TRUE;
    $this->code = 'authorizenet';
    $this->title = lc_defined_constant('MODULE_PAYMENT_AUTHORIZENET_TEXT_TITLE');
    $this->description = lc_defined_constant('MODULE_PAYMENT_AUTHORIZENET_TEXT_DESCRIPTION');
    $this->sort_order = lc_defined_constant('MODULE_PAYMENT_AUTHORIZENET_SORT_ORDER');
    $this->enabled = (lc_check_constant_val('MODULE_PAYMENT_AUTHORIZENET_STATUS', 'True') ? true : false);
    $this->accepted_cc = lc_defined_constant('MODULE_PAYMENT_AUTHORIZENET_ACCEPTED_CC');

    if (lc_defined_constant_int('MODULE_PAYMENT_AUTHORIZENET_ORDER_STATUS_ID') > 0) {
        $this->order_status = MODULE_PAYMENT_AUTHORIZENET_ORDER_STATUS_ID;
    }
    $this->requestdata = '';
    if((lc_defined_constant('MODULE_PAYMENT_AUTHORIZENET_TESTMODE') == 'Test') || (lc_defined_constant('MODULE_PAYMENT_AUTHORIZENET_TESTMODE') == 'Test And Debug') ) {
     $this->url = 'https://apitest.authorize.net/xml/v1/request.api';
    }else{
      $this->url = 'https://api.authorize.net/xml/v1/request.api';
    }

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

    //array for credit card selection
    $this->card_types = array('Amex' => 'Amex',
        'Mastercard' => 'Mastercard',
        'Discover' => 'Discover',
        'Visa' => 'Visa');
    $this->allowed_types = array();

    // Credit card pulldown list
    $cc_array = explode(', ', $this->accepted_cc);
    foreach($cc_array as $key=>$value) {
      $this->allowed_types[$value] = $this->card_types[$value];
    }

    // Processing via Authorize.net AIM
    $filename_checkout_process = (defined('FILENAME_CHECKOUT_PROCESS') && FILENAME_CHECKOUT_PROCESS != '')?FILENAME_CHECKOUT_PROCESS:'checkout_process.php';
    $this->form_action_url = tep_href_link($filename_checkout_process, '', 'SSL', false);
    //Set the select action
    $this->setPageCode();
  }

// class methods
  function update_status() {
    global $order;
    if ( ($this->enabled == true) && ((int)MODULE_PAYMENT_AUTHORIZENET_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_AUTHORIZENET_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 == \'authorizenet\'){
		   $(\'#ccbox_authorizenet\').show(500);
		   $(\'#process_payment\').css(\'display\',\'inline-block\');
		}';
	if(is_object($obj_catalog))
		$obj_catalog->set_hooks_js($str_js, 'onselectAction');
  }
	//concatenate to get CC images
	function get_cc_images() {
	  $cc_images = '';
	  reset($this->allowed_types);
      foreach($this->allowed_types as $key=>$value) {
		$cc_images .= tep_image(DIR_WS_ICONS . $key . '.gif', $value);
	  }
	  return $cc_images;
	}

	function javascript_validation() {
		$js = '';
		return $js;
	}

    function selection() {
      global $order;
	  reset($this->allowed_types);
	  foreach ($this->allowed_types as $key => $value ) {
		$card_menu[] = array('id' => $key, 'text' => $value);
	  }

      for ($i=1; $i<13; $i++) {
        $expires_month[] = array('id' => sprintf('%02d', $i), 'text' => strftime('%B',mktime(0,0,0,$i,1,2000)));
      }

      $today = getdate();
      for ($i=$today['year']; $i < $today['year']+10; $i++) {
        $expires_year[] = array('id' => $i, 'text' => strftime('%Y',mktime(0,0,0,1,1,$i)));
      }
	  $selection = array('id' => $this->code,
		'module' => $this->title . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . $this->get_cc_images(),
		'fields' => array(
					array('title' => 'CUSTOMCC', 'field' => 'CUSTOMCC'),
					array('title' => 'HIDDEN', 'field' => '<input type="hidden" name="authnet-dataValue" id="authnet-dataValue" /><input type="hidden" name="authnet-dataDescriptor" id="authnet-dataDescriptor" />')
			  ));
     return $selection;
    }

    function pre_confirmation_check() {
      global $cvv,$messageStack;
	    $cc_array = explode(', ', MODULE_PAYMENT_AUTHORIZENET_ACCEPTED_CC);
		$cc_valid_error_msg = '';
		include(DIR_WS_CLASSES . 'CreditCard.php');
		$CreditCard = new CreditCard();
		//Vaidate the Credit card type
		$error = 0;

		if(trim($_POST['authorizenet_cc_firstname']) == '') {
		 $message = 'Please enter credit owner name.';
		 $messageStack->add_session('checkout', $message, 'error');
		 $error = 1;
		}
		if(trim($_POST['authorizenet_cc_number']) == '') {
		 $message = "Please enter credit card number.";
		 $messageStack->add_session('checkout', $message, 'error');
		 $error = 1;
		}
		$card = CreditCard::validCreditCard($_POST['authorizenet_cc_number']);
		if($card['valid']) {
			$type = $card['type'];
		}else{
			$cc_valid_error_msg = 'Please enter correct card number!';
			$messageStack->add_session('checkout', $cc_valid_error_msg, 'error');
			$error = 1;
		}
		$expireCard = explode('/',$_POST['authorizenet_cc_expires']);
		$_POST['authorizenet_cc_expires_month'] = $expireCard[0];
		$_POST['authorizenet_cc_expires_year'] = 2000 + $expireCard[1];
		$validDate = CreditCard::validDate($_POST['authorizenet_cc_expires_year'], $_POST['authorizenet_cc_expires_month']); // past date
		if(!$validDate){
			 $cc_valid_error_msg = 'Please enter correct expires year and month!';
			$messageStack->add_session('checkout', $cc_valid_error_msg, 'error');
			$error = 1;
		}


		if(trim(str_replace('_','',$_POST['authorizenet_cc_checkcode'])) == '') {
		 $message = "Please enter credit card cvv number.";
		 $messageStack->add_session('checkout', $message, 'error');
		 $error = 1;
		}
		$validCvc = CreditCard::validCvc(str_replace('_','',$_POST['authorizenet_cc_checkcode']), $type);
		if(!$validCvc) {
		 $cc_valid_error_msg = 'Please enter correct cvc number!';
		 $messageStack->add_session('checkout', $cc_valid_error_msg, 'error');
		 $error = 1;
		}

		if($error) {
			tep_redirect(tep_href_link(FILENAME_CHECKOUT, '', 'SSL', true, false));
			exit();
		}
	 // $expireCard = explode('/',$_POST['authorizenet_cc_expires']);
	 // $_POST['authorizenet_cc_expires_month'] = $expireCard[0];
	 // $_POST['authorizenet_cc_expires_year'] = 2000 + $expireCard[1];

      $this->cc_card_type_1 = $type;
      $this->cc_card_type = $type;
      $this->cc_card_number = $_POST['authorizenet_cc_number'];
      $this->cc_expiry_month = $_POST['authorizenet_cc_expires_month'];
      $this->cc_expiry_year = $_POST['authorizenet_cc_expires_year'];
      $this->x_Card_Code = str_replace('_','',$_POST['authorizenet_cc_checkcode']);
    }

    function confirmation() {
    return false;
   }
    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;
    }

    function before_process() {
	global $response,$insert_id,$order, $messageStack, $lc_createOrder;

	$noerror = 0;
	if(trim($_POST['authnet-dataDescriptor']) != '' && trim( $_POST['authnet-dataValue']) != '') {
		$payment_processing_method = 'nonce';	
		$noerror = 1;
    } elseif($_POST['authorizenet_cc_number'] != '' && $_POST['authorizenet_cc_expires'] != '' && $_POST['authorizenet_cc_checkcode'] != '') {
		$payment_processing_method = 'card';	
		$expireCard = explode('/',$_POST['authorizenet_cc_expires']);
		$_POST['authorizenet_cc_expires_month'] = $expireCard[0];
		$_POST['authorizenet_cc_expires_year'] = 2000 + $expireCard[1];
		$_POST['authorizenet_cc_checkcode'] = trim(str_replace('_','',$_POST['authorizenet_cc_checkcode']));

        $this->cc_card_number = $_POST['authorizenet_cc_number'];
        $this->cc_expiry_month = $_POST['authorizenet_cc_expires_month'];
        $this->cc_expiry_year = $_POST['authorizenet_cc_expires_year'];
        $this->x_Card_Code = str_replace('_','',$_POST['authorizenet_cc_checkcode']);

		$noerror = 1;
	}else {
		   tep_db_query('delete from ' . TABLE_ORDERS . ' where orders_id = "' . (int)$insert_id . '"');
		   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 . '"');

		   $errormsg = 'Invalid payment request please process again!';
		   $messageStack->add_session('checkout',$errormsg, 'error');
		   tep_redirect(tep_href_link(FILENAME_CHECKOUT, $message, 'SSL', true, false));
		   exit();
	 }
	 
	 if($noerror)
	 {

	      // ADC Direct Connection has broken the response up, just use it
		$total =  number_format($order->info['total'], 2, '.', '');
		$billto_data = array('firstName' =>$order->billing['firstname'],
				     'lastName' =>$order->billing['lastname'],
				     'company' =>$order->billing['company'],
				     'address' =>$order->billing['street_address'],
				     'city' =>$order->billing['city'],
				     'state' =>$order->billing['state'],
				     'zip' =>$order->billing['postcode'],
				     'country' =>$order->billing['country']['title']);
		$shipto_data = array('firstName' =>$order->delivery['firstname'],
				     'lastName' =>$order->delivery['lastname'],
				     'company' =>$order->delivery['company'],
				     'address' =>$order->delivery['street_address'],
				     'city' =>$order->delivery['city'],
				     'state' =>$order->delivery['state'],
				     'zip' =>$order->delivery['postcode'],
				     'country' =>$order->delivery['country']['title']);
		$transaction_mode = (MODULE_PAYMENT_AUTHORIZENET_CCMODE == 'Authorize')? 'authOnlyTransaction':'authCaptureTransaction';
		$transaction_array = array();
		$transaction_array['createTransactionRequest']['merchantAuthentication'] = array('name'=>MODULE_PAYMENT_AUTHORIZENET_LOGIN, 'transactionKey' => MODULE_PAYMENT_AUTHORIZENET_TRANSKEY);
		$transaction_array['createTransactionRequest']['refId'] = $insert_id;
		$transaction_array['createTransactionRequest']['transactionRequest']['transactionType'] = $transaction_mode;
		$transaction_array['createTransactionRequest']['transactionRequest']['amount'] = $total;
		if(defined('MODULE_PAYMENT_AUTHORIZENET_CLIENTKEY') && trim(MODULE_PAYMENT_AUTHORIZENET_CLIENTKEY) != '') // Use nonce for the payment processing else card info
		{
			$opaqueData = array('dataDescriptor' => $_POST['authnet-dataDescriptor'],'dataValue' => $_POST['authnet-dataValue']);
			$transaction_array['createTransactionRequest']['transactionRequest']['payment']['opaqueData'] = $opaqueData;
		} else {
			$cardinfo = array('cardNumber' => $this->cc_card_number,'expirationDate' => $this->cc_expiry_year.'-'.$this->cc_expiry_month,'cardCode' => $this->x_Card_Code);
			$transaction_array['createTransactionRequest']['transactionRequest']['payment']['creditCard'] = $cardinfo;
		}
		$transaction_array['createTransactionRequest']['transactionRequest']['order']['invoiceNumber'] = $insert_id;
		$transaction_array['createTransactionRequest']['transactionRequest']['order']['description'] = substr(STORE_NAME . ' Order', 0, 255);
		for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {
		  if($i < 30 )
		  {
			 $product_list = array();
			 $product_list['itemId'] =  $order->products[$i]['id'];
			 $product_list['name'] = substr(htmlspecialchars(strip_tags($order->products[$i]['name'])), 0, 30);
			 $product_list['description'] = substr(htmlspecialchars(strip_tags($order->products[$i]['name'])), 0, 255);
			 $product_list['quantity'] = $order->products[$i]['qty'];
			 $product_list['unitPrice'] = $order->products[$i]['price'];
			 $transaction_array['createTransactionRequest']['transactionRequest']['lineItems']['lineItem'][] = $product_list;
		  }
		}
		$transaction_array['createTransactionRequest']['transactionRequest']['customer']['id'] =$_SESSION['customer_id'];
		$transaction_array['createTransactionRequest']['transactionRequest']['billTo'] = $billto_data;
		$transaction_array['createTransactionRequest']['transactionRequest']['shipTo'] = $shipto_data;
		$transaction_array['createTransactionRequest']['transactionRequest']['customerIP'] = $_SERVER['REMOTE_ADDR'];

		//Code for custom fields
		$customFields[] = array('name' => 'sessionID', 'value' => $_COOKIE['lcsid']);
		$customFields[] = array('name' => 'websiteName', 'value' => STORE_NAME);
		$customFields[] = array('name' => 'software', 'value' => 'LoadedCommerce');
		$customFields[] = array('name' => 'processedBy', 'value' => $payment_processing_method);
		foreach($customFields as $customField) {
			$transaction_array['createTransactionRequest']['transactionRequest']['userFields']['userField'] = $customFields;
		}
		
		$jsondata = json_encode($transaction_array);
		$this->requestdata = $jsondata;
		$response = $this->curl_process();

	    //Store the payment data in debug
	    $debugRequest = $transaction_array;
		unset($debugRequest['createTransactionRequest']['merchantAuthentication']);
	    if($payment_processing_method == 'card')
	    {
			$cardNum = $debugRequest['createTransactionRequest']['transactionRequest']['payment']['creditCard']['cardNumber'];
			$debugRequest['createTransactionRequest']['transactionRequest']['payment']['creditCard']['cardNumber'] = 'xxxx-xxxx-xxxx-'.substr($cardNum, -5);
			$cardNum = '';
			unset($debugRequest['createTransactionRequest']['transactionRequest']['payment']['creditCard']['cardCode']);
			unset($debugRequest['createTransactionRequest']['transactionRequest']['payment']['creditCard']['expirationDate']);
		}
	    $debugResponse = $response;
	    $debugdata = array('request'=>$debugRequest, 'respose'=>$debugResponse);
		$lc_createOrder->appendDebugData($insert_id, 'authnetPaymentData', $debugdata);
		$transaction_array = array();
		//-----------------
		
		if($response['transactionResponse']['responseCode'] == 1){
		   
		   $trasnaction_id = $response['transactionResponse']['transId'];
		   $approval_code = $response['transactionResponse']['authCode'];
		   if(MODULE_PAYMENT_AUTHORIZENET_CCMODE == 'Authorize'){
		    tep_db_query("UPDATE " . TABLE_ORDERS . " SET transaction_id='".$trasnaction_id."',approval_code='".$approval_code."', is_capture = 0, orders_status = '".MODULE_PAYMENT_AUTHORIZENET_ORDER_STATUS_ID."' where orders_id = '" . (int)$insert_id . "'"); //Update the transaction ID to the order
		    }else{
		      tep_db_query("UPDATE " . TABLE_ORDERS . " SET transaction_id='".$trasnaction_id."', approval_code='".$approval_code."', is_capture = 1, orders_status = '".MODULE_PAYMENT_AUTHORIZENET_ORDER_STATUS_ID."' where orders_id = '" . (int)$insert_id . "'"); //Update the transaction ID to the order
		    }
		}else{
		    $errormsg = $response['transactionResponse']['errors'][0]['errorCode'].'--'.$response['transactionResponse']['errors'][0]['errorText'];
		    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;
    }

    function get_error() {
      $error = array('title' => MODULE_PAYMENT_AUTHORIZENET_TEXT_ERROR,
                     'error' => stripslashes(urldecode($_GET['error'])));
      return $error;
    }

    function check() {
      if (!isset($this->_check)) {
        $check_query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_AUTHORIZENET_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 Authorize.net Module', 'MODULE_PAYMENT_AUTHORIZENET_STATUS', 'True', 'Do you want to accept payments through Authorize.net?', '6', '0', '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, date_added) values ('Login Username', 'MODULE_PAYMENT_AUTHORIZENET_LOGIN', 'Your Login Name', 'The login username used for the Authorize.net service', '6', '0', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Login Transaction Key', 'MODULE_PAYMENT_AUTHORIZENET_TRANSKEY', 'Your Transaction Key', 'The transaction key used for the Authorize.net service', '6', '0', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Public Client Key', 'MODULE_PAYMENT_AUTHORIZENET_CLIENTKEY', 'Your Public Client Key', 'The public client key required for the accpet JS card nonce creation.', '6', '0', 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_AUTHORIZENET_TESTMODE', 'Test', 'Transaction mode used for processing orders', '6', '0', '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, set_function, date_added) values ('Processing Mode', 'MODULE_PAYMENT_AUTHORIZENET_CCMODE', 'Authorize', 'Credit card processing mode', '6', '0', 'tep_cfg_select_option(array(\'Sale\', \'Authorize\'), ', 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_AUTHORIZENET_SORT_ORDER', '200', 'The order in which this payment type is dislayed. Lowest is displayed first.', '6', '0' , 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 ('Accepted Credit Cards', 'MODULE_PAYMENT_AUTHORIZENET_ACCEPTED_CC', 'Mastercard, Visa', 'The credit cards you currently accept', '6', '0', '_selectOptions(array(\'Amex\',\'Discover\', \'Mastercard\', \'Visa\'), ', 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 ('Authorizenet - Payment Zone', 'MODULE_PAYMENT_AUTHORIZENET_ZONE', '0', 'Authorizenet - If a zone is selected, enable this payment method for that zone only.', '6', '2', '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, date_added) values ('Enable CCV code', 'MODULE_PAYMENT_AUTHORIZENET_CCV', 'True', 'Do you want to enable ccv code checking?', '6', '0', '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, use_function, date_added) values ('Authorizenet - Set Order Status', 'MODULE_PAYMENT_AUTHORIZENET_ORDER_STATUS_ID', '0', 'Authorizenet - 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())");
   }
    function remove() {
      $keys = '';
      $keys_array = $this->keys();
      for ($i=0; $i<sizeof($keys_array); $i++) {
        $keys .= "'" . $keys_array[$i] . "',";
      }
      $keys = substr($keys, 0, -1);
      tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in (" . $keys . ")");
    }

    function keys() {
      return array('MODULE_PAYMENT_AUTHORIZENET_STATUS', 'MODULE_PAYMENT_AUTHORIZENET_LOGIN', 'MODULE_PAYMENT_AUTHORIZENET_TRANSKEY', 'MODULE_PAYMENT_AUTHORIZENET_CLIENTKEY', 'MODULE_PAYMENT_AUTHORIZENET_TESTMODE', 'MODULE_PAYMENT_AUTHORIZENET_CCMODE', 'MODULE_PAYMENT_AUTHORIZENET_ACCEPTED_CC', 'MODULE_PAYMENT_AUTHORIZENET_ZONE', 'MODULE_PAYMENT_AUTHORIZENET_ORDER_STATUS_ID', 'MODULE_PAYMENT_AUTHORIZENET_CCV',  'MODULE_PAYMENT_AUTHORIZENET_SORT_ORDER');
    }
	function curl_process($data = ''){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $this->url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type:application/json'));
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $this->requestdata);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		// proxy option for godaddy hosted customers (required)
		//curl_setopt($ch, CURLOPT_PROXY,"http://proxy.shr.secureserver.net:3128");
		$response = curl_exec($ch);
		 curl_close($ch);
		 //echo $response;
		$final_result = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $response), true );
		 return $final_result;
	}

	function header_js() {
		$jstags = '';
		if($this->enabled == true && (defined('MODULE_PAYMENT_AUTHORIZENET_CLIENTKEY') && trim(MODULE_PAYMENT_AUTHORIZENET_CLIENTKEY) != '')) {
			if((MODULE_PAYMENT_AUTHORIZENET_TESTMODE == 'Test') || (MODULE_PAYMENT_AUTHORIZENET_TESTMODE == 'Test And Debug') ) {
			 $jstags = '<script type="text/javascript" src="https://jstest.authorize.net/v1/Accept.js" charset="utf-8"> </script>';
			}else{
			  $jstags = '<script type="text/javascript" src="https://js.authorize.net/v1/Accept.js" charset="utf-8"></script>';
			}
		}
		return $jstags;
	}

	function footer_js() {
		$jscode = '';
		if($this->enabled == true && (defined('MODULE_PAYMENT_AUTHORIZENET_CLIENTKEY') && trim(MODULE_PAYMENT_AUTHORIZENET_CLIENTKEY) != '')) {
		$jscode = '
			if(sel_method == \'authorizenet\') {
				var authData = {};
					authData.clientKey = "'. MODULE_PAYMENT_AUTHORIZENET_CLIENTKEY .'";
					authData.apiLoginID = "'. MODULE_PAYMENT_AUTHORIZENET_LOGIN .'";

					authnetExp = document.getElementById("authorizenet-cc-exp").value;
					arrExpDate = authnetExp.split("/");
					authnetcvvraw = document.getElementById("authorizenet-card-code").value;
					authnetcvv = authnetcvvraw.replace(\'_\', \'\');

				var cardData = {};
					cardData.cardNumber = document.getElementById("authorizenet-cc-number").value;
					cardData.month = arrExpDate[0];
					cardData.year = arrExpDate[1];
					cardData.cardCode = authnetcvv;


				var secureData = {};
					secureData.authData = authData;
					secureData.cardData = cardData;

				Accept.dispatchData(secureData, responseHandler);

				function responseHandler(response) {
					if (response.messages.resultCode === "Error") {
						var i = 0;
						errorMsg = "";
						while (i < response.messages.message.length) {
							console.log(
								response.messages.message[i].code + ": " +
								response.messages.message[i].text
							);
							errorMsg = errorMsg + "\n" + response.messages.message[i].text;
							i = i + 1;
						}
						alert(errorMsg);
					} else {
						document.getElementById("authnet-dataDescriptor").value = response.opaqueData.dataDescriptor;
						document.getElementById("authnet-dataValue").value = response.opaqueData.dataValue;

						// If using your own form to collect the sensitive data from the customer,
						// blank out the fields before submitting them to your server.
						document.getElementById("authorizenet-cc-number").value = "";
						document.getElementById("authorizenet-cc-exp").value = "";
						document.getElementById("authorizenet-card-code").value = "";

					    document.getElementById("checkout_payment").submit();
						
					}
				}
				return false;
			}

			';
		}
		return $jscode;
	}
  }

// Authorize.net Consolidated Credit Card Checkbox Implementation
// Code from UPS Choice v1.7 - Fritz Clapp (aka dreamscape, thanks Fritz!)
function _selectOptions($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;
}

?>