# This patch file was generated by NetBeans IDE
# It uses platform neutral UTF-8 encoding and \n newlines.
--- HEAD
+++ Modified In Working Tree
@@ -61,6 +61,60 @@
     '#description' => t('The merchant id used for the beanstream.com service.'),
   );
 
+    //////// "User/password validation" fieldset ////////
+ 
+  $form['beanstr_settings']['beanstr_userpassvalidation'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Username/password validation against transaction'),
+    '#description' => t('Only required if you checked "Use username/password validation against transaction", '
+            . 'in your beanstream account on the "order settings" page '
+            . '(under "admnistration" -> "account settings" -> "order settings").' ),
+    '#weight' => -10,
+  );  
+  $form['beanstr_settings']['beanstr_userpassvalidation']['beanstr_username'] = array(
+    '#type' => 'textfield',
+    '#title' => t('User Name'),
+    '#default_value' => variable_get('beanstr_username', ''),
+    '#description' => t('The same username that you entered on the beanstream "order settings" page.' ),
+  );
+    $form['beanstr_settings']['beanstr_userpassvalidation']['beanstr_password'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Password'),
+    '#default_value' => variable_get('beanstr_password', ''),
+    '#description' => t('The same password that you entered on the beanstream "order settings" page.' ),
+  );
+
+  
+  
+  //////// "Beanstream order entries" fieldset ////////
+
+  $form['beanstr_settings']['beanstr_orderentries'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Templates for filling in order entries on Beanstream'),
+    '#description' => t('When someone places an order, a transaction record is created in beanstream. '
+            . 'Here, we give you some control over exactly what information is populated '
+            . 'into the fields of that record on beanstream. See the list of possible tokens, below.'),
+    '#weight' => -9,
+  );  
+  $form['beanstr_settings']['beanstr_orderentries']['beanstr_order_num'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Order Number'),
+    '#default_value' => variable_get('beanstr_order_num', '[order-id]'),
+    '#description' => t('the value to fill into the "Order Number" field.  This does not need to be a number.' ),
+  );
+  $form['beanstr_settings']['beanstr_orderentries']['beanstr_order_comments'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Comments'),
+    '#default_value' => variable_get('beanstr_order_comments', '[order-comments]'),
+    '#description' => t('When people are making their order, they can leave comments. '.
+            'If you want to prepend or append some extra information in that field, this is the place to do it.'),
+  );
+    $form['beanstr_settings']['beanstr_orderentries']['tokens'] = array(
+  '#theme' => 'token_tree',
+  '#token_types' => array('order'),
+  );
+
+  
  /* Beanstream doesn't have a test mode. Instead it relies on a different merchantID
   $form['beanstr_settings']['beanstr_transaction_mode'] = array(
     '#type' => 'select',
@@ -106,7 +160,7 @@
     return array('success' => FALSE);
   }
 
-  global $user, $response;
+  global $user;
   $order = uc_order_load($order_id);
   
   //assemble description of products purchased
@@ -117,7 +171,7 @@
         $description .= ' / ';
       }
       $description .= $product->title .' x'. $product->qty;
-      if (is_array($product->data['attributes'])) {
+      if (isset($product->data['attributes']) && is_array($product->data['attributes'])) {
         foreach ($product->data['attributes'] as $key => $value) {
           $description .= ', '. $key .': '. $value;
         }
@@ -137,6 +191,14 @@
     $expdate = $order->payment_details['cc_exp_month'];
   }
 
+  $replacements = array('order' => $order);  // for token replacement.
+  $tokenized_vals = array(
+    'order_num' =>
+        token_replace(variable_get('beanstr_order_num',      '[order-id]'      ), 'order', $order),
+    'comments' =>
+        token_replace(variable_get('beanstr_order_comments', '[order-comments]'), 'order', $order),
+  );
+  
   $request_data = array(
     'requestType' => 'BACKEND',
     'merchant_id' => variable_get('beanstr_login_id', ''),
@@ -146,7 +208,8 @@
     'trnCardNumber' => $order->payment_details['cc_number'],
     'trnExpMonth' => $expdate, 
     'trnExpYear' => substr($order->payment_details['cc_exp_year'], 2, 2), 
-    'trnOrderNumber' => $order_id, 
+    'trnOrderNumber' => $tokenized_vals['order_num'],
+//    'trnOrderNumber' => "DUES-$order_id",
     'trnAmount' => uc_currency_format($amount, FALSE, FALSE, '.'), 
     'trnCardCvd' => $order->payment_details['cc_cvv'], 
     'ordEmailAddress' => $order->primary_email, 
@@ -161,13 +224,26 @@
     'ordProvince' => uc_get_zone_code($order->billing_zone),
     'ordPostalCode' => $order->billing_postal_code,
     'ordCountry' => $ord_country,
+    'trnComments' => $tokenized_vals['comments'],
   );
 
+  // If a Username/Password is being used with the account, they have to match what is stored 
+  //    in the beanstream account, under "administration  ->  account settings  ->  order settings".
+  if (variable_get('beanstr_username', '')) {
+    $request_data += array(
+      'username' => variable_get('beanstr_username', ''),
+      'password' => variable_get('beanstr_password', ''),
+    );
+  }
+  
+  
+  $request = '';
+
   while (list($key, $value) = each($request_data)) {
     $request .= $key .'='. urlencode(ereg_replace(',', '', $value)) .'&';
   }
    
-  //trim out last amphersand
+  // remove last ampersand
   $request = substr($request, 0, -1);
   
   //uncomment below to display request
@@ -187,38 +263,34 @@
   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
   curl_setopt($ch, CURLOPT_NOPROGRESS, 1); 
   curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0); 
-  $response = curl_exec($ch); 
+  $raw_response = curl_exec($ch); 
   curl_close($ch); 
 
-  //uncomment below to display response
-  //drupal_set_message('<pre><b>Response:</b> '. print_r($response, TRUE) .'</pre>');
+  $parsed_response = array();
   
-  $response_data = split('&', $response);
-  $response_code = explode('=', $response_data[0]);
-  $response_text = explode('=', $response_data[3]);
-  $approval_code = explode('=', $response_data[4]);
-  $message_id = $response_code[0];
-  $message_text = $response_text[0];
-  $auth_code = $approval_code[0];
-
-  //uncomment below to display response message
-  //drupal_set_message('<pre><b>Response Message:</b>'. print_r($response_data[3], TRUE) .'</pre>');
-
-  if ($response_code[1] != '1') {
-    $message = t('Credit card declined: !amount', array('!amount' => uc_currency_format($amount)));
+  $keyval_pairs = explode('&', $raw_response);
+  foreach ($keyval_pairs as $pair) {
+    list($key, $val) = explode('=', $pair, 2);
+    $parsed_response[$key] = urldecode($val);
+  }
+  if ($parsed_response['trnApproved'] != '1') {
+    $message = t('Credit card payment declined');
+    $message .= ($parsed_response['messageText'] == 'DECLINE' ? '.' 
+                      : ': "'. urldecode($parsed_response['messageText']) .'"' );
     $result = array(
       'success' => FALSE,
-      'comment' => t('Credit card payment declined: !text', array('!text' => $x_response_text)),
-      'message' => t('Credit card payment declined: !text', array('!text' => $x_response_text)),
+      'comment' => $message,
+      'message' => $message,
       'uid' => $user->uid,
     );
   }
   else {
-    $message = t('Credit card charged: !amount', array('!amount' => uc_currency_format($amount)));
+    $message = t('Credit card payment processed successfully. Approval code: !code', 
+                    array('!code' => $parsed_response['authCode'])  );
     $result = array(
       'success' => TRUE,
-      'comment' => t('Credit card payment processed successfully. Approval code: !code', array('!code' => $auth_code)),
-      'message' => t('Credit card payment processed successfully. Approval code: !code', array('!code' => $auth_code)),
+      'comment' => $message,
+      'message' => $message,
       'uid' => $user->uid,
     );
   }
