<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class WC_API_Cybersource_WM extends WC_API_Cybersource_SAWM 
{
	function __construct(){
		parent::__construct();

		$this->supports = array(
			'products',
			'refunds'
		 );

		add_action( 'woocommerce_receipt_' .  $this->id , array( $this, 'receipt_page' ), 10, 1 );
		add_action( 'woocommerce_thankyou', array( $this , 'cybersource_thankyou_processing_order_status' ), 10 ,1);
		add_action('woocommerce_order_status_completed', array( $this, 'capture_order_status_completed' ), 10, 2 );
	}

	public function payment_fields(){

		if ( $this->mode == 's' ){
			echo '<p>';
				echo esc_html__( 'TEST MODE/SANDBOX ENABLED', 'woocommerce' );
				echo '<br>';
				echo esc_html__( 'Secure Acceptance Web/Mobile', 'woocommerce' );
				echo '<br>';
				echo '<br>';
				echo  esc_html__( 'Test Cards:', 'woocommerce' );
				echo '<br>';
				echo  esc_html__( 'MasterCard: 5555 5555 5555 4444', 'woocommerce' );
				echo '<br>';
				echo  esc_html__( 'VISA: 4111 1111 1111 1111', 'woocommerce' );
			echo '<p>';
		}

		if( $this->description ){
			echo wp_kses_post( wpautop( wptexturize( $this->description ) ) );
		}
	}		

	public function process_payment( $order_id ){

		global $woocommerce;

    	$order = wc_get_order( $order_id );
		
		$date_completed = $order->get_date_completed();
		$status = $order->get_status();

		if(!empty($date_completed) && $status == 'completed'){

			$duplicate_order_number = array(
				'order_id' => $order_id,
				'status' => $order->get_status(),
				'date_completed' => $order->get_date_completed(),
				'old_billing_email' => $order->get_billing_email(),
				'new_billing_email' => wc_clean($_REQUEST['billing_email']),
			);

			parent::log( 'Cybersource WM Request - Duplicate Order number: ' . print_r( $duplicate_order_number, true ) );

			wc_add_notice( __( sprintf( "Error when processing payment: '%s'", "Sorry something went wrong on your order, Please contact the support!" ) , 'woocommerce'), "error" );
			return false;

		}


    	// create transaction UUID
		$cb_uuid = uniqid() . '-' . $order_id;
		
		// if ( ! add_post_meta(  $order_id , '_cb_transaction_uuid' , $cb_uuid , true ) ) {
		// 		update_post_meta ( $order_id, '_cb_transaction_uuid' , $cb_uuid );
		// }

		// if ( ! add_post_meta(  $order_id , '_cb_integration' , 'sawm' , true ) ) {
		// 	update_post_meta ( $order_id, '_cb_integration' , 'sawm' );
		// }

		// Get mobile number for payer_authentication
		$billing_mobile_phone = !empty($_POST['billing_mobile_phone']) ? $_POST['billing_mobile_phone'] : ''; 
		$customer_browser_screen_height = !empty($_POST['customer_browser_screen_height']) ? $_POST['customer_browser_screen_height'] : '';
		$customer_browser_screen_width = !empty($_POST['customer_browser_screen_width']) ? $_POST['customer_browser_screen_width'] : ''; 


		$order->update_meta_data( '_cb_transaction_uuid', $cb_uuid );
		$order->update_meta_data( '_cb_integration', 'sawm' );
		$order->update_meta_data( 'billing_mobile_phone', wc_clean($billing_mobile_phone));
		$order->update_meta_data( 'billing_browser_screen_height', wc_clean($customer_browser_screen_height));
		$order->update_meta_data( 'billing_browser_screen_width', wc_clean($customer_browser_screen_width));
		$order->save();

		// WPML Get current lang by page	

		if ( is_plugin_active( 'sitepress-multilingual-cms/sitepress.php' ) ) {

			$my_current_lang = apply_filters( 'wpml_current_language', NULL );

			// if ( ! add_post_meta(  $order_id , '_cybersource_wpml' , $my_current_lang , true ) ) {
			// 	update_post_meta ( $order_id, '_cybersource_wpml' , $my_current_lang );
			// }

			$order->update_meta_data( '_cybersource_wpml', $my_current_lang );
			$order->save();

		} else {
			//update_post_meta ( $order_id, '_cybersource_wpml' , "" );
			$order->update_meta_data( '_cybersource_wpml', "" );
			$order->save();
		}

		if($this->dont_send_billing_fields === false ){

			parent::cybersource_custom_validate_address_fields();
			$this->validate_address_fields($order_id);
			

		}
		
		$checkout_url_args 	= array( 'order-pay' => $order_id, 'key' => $order->get_order_key() );
		$checkout_url 		= add_query_arg( $checkout_url_args, wc_get_checkout_url() );

		if(  $order_id > 0 ){
			return array(
				'result'    => 'success',
				'redirect'  => esc_url_raw( $checkout_url )
			);
		} 

		else {
			wc_add_notice( 
				__( sprintf( "Error when processing payment: '%s'", "Invalid Order ID!" ) , 'woocommerce' ), "error" );
			return false;

		}

	}

	public function validate_address_fields($order_id){

		global $woocommerce;

    	$order = wc_get_order( $order_id );
		
		// Billing Fields Validate

		$addres_max_length = ! empty($this->address_input_size) ? $this->address_input_size : 41;

		if(! empty($order->get_billing_address_1()) && strlen($order->get_billing_address_1()) >= $addres_max_length ){

			if( $this->enable_auto_split_address === false ){
				wc_add_notice( __( sprintf( "Error when processing payment: '%s'", "Invalid Billing Address 1 Maximum Character Length Exceeded!" ) , 'woocommerce'), "error" );
				return false;
			}

				
		}

		if(! empty($order->get_billing_address_2()) && strlen($order->get_billing_address_2()) >= $addres_max_length ){
			
			if( $this->enable_auto_split_address === false ){
				wc_add_notice( __( sprintf( "Error when processing payment: '%s'", "Invalid Billing Address 2 Maximum Character Length Exceeded!" ) , 'woocommerce'), "error" );
				return false;
			}
			
			
		}

		// Shipping Fields Validate

		$addres_max_length = ! empty($this->address_input_size) ? $this->address_input_size : 41;

		if(! empty($order->get_shipping_address_1()) && strlen($order->get_shipping_address_1()) >= $addres_max_length ){
				
			if( $this->enable_auto_split_address === false ){
				wc_add_notice( __( sprintf( "Error when processing payment: '%s'", "Invalid Shipping Address 1 Maximum Character Length Exceeded!" ) , 'woocommerce'), "error" );
				return false;

			}
		}

		if(! empty($order->get_shipping_address_2()) && strlen($order->get_shipping_address_2()) >= $addres_max_length ){			

			if( $this->enable_auto_split_address === false ){
				wc_add_notice( __( sprintf( "Error when processing payment: '%s'", "Invalid Shipping Address 2 Maximum Character Length Exceeded!" ) , 'woocommerce'), "error" );
				return false;
			}
		}

	}

	public function receipt_page( $order_id ){
		global $woocommerce;

		wp_enqueue_style( 'wc-cybersource-receipt-css', plugins_url( 'assets/css/wc-cybersource-receipt.min.css' , __FILE__ )  ); 
	    wp_enqueue_script( 'wc-cybersource-jquery-js', "https://code.jquery.com/jquery-3.6.0.min.js" , 'jquery' );
		wp_enqueue_script( 'wc-cybersource-jquery-block-js', "https://cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.70/jquery.blockUI.min.js" , 'jquery' );
		wp_enqueue_script( 'wc-cybersource-receipt-js', plugins_url( 'assets/js/wc-cybersource-receipt.min.js' , __FILE__ ) , 'jquery' ); 
		
		 $order = wc_get_order( $order_id );

		 //Validate the billing fields

		 $created_via = $order->get_created_via();

		if($this->dont_send_billing_fields === false ){

			if($this->validate_address_fields($order_id) === false ){
				if($created_via == "admin" ){
					wp_redirect( $order->get_checkout_payment_url() );
				} else {
					wp_redirect( wc_get_checkout_url() );
				}
				
			};

		}

		// MDD Fields ( Merchant Custom Fields)	
		if( $this->enable_mdd_fields === true ){
			$mdd_fields = apply_filters( 'cybersource_add_signed_field_names', $order_id );

			// remove the mdd field before submit

			if( is_array( $this->remove_mdd_field_names ) && !empty($this->remove_mdd_field_names)){

				foreach ($this->remove_mdd_field_names as $k => $v ){
					unset($mdd_fields[$v]);
				}
			}


		}else{
			$mdd_fields = array();
		}

		if( ! empty ( $this->signed_field_names ) ) {

			if( is_array(  $mdd_fields ) && ! empty( $mdd_fields ) ){
				$signed_field_names = array_merge( $this->signed_field_names, array_keys( $mdd_fields ) );
				$signed_field_names = implode(',', $signed_field_names);	
			} else {
				$signed_field_names = implode(',', $this->signed_field_names);		
			}

			
		}
		
		else {
			$signed_field_names = "";
		}

		if( ! empty( $this->unsigned_field_names ) ){
			$unsigned_field_names = implode(',', $this->unsigned_field_names);	
		} else {
			$unsigned_field_names = "";
		}
		
		if ( ! empty( $this->merchant_reference ) ){
			$reference = str_replace( '{ORDERNO}', $order->get_order_number() , $this->merchant_reference );
		}
		
		else {
			$reference = sprintf( __( '%s - Order %s', 'woocommerce' ), esc_html( get_bloginfo() ), $order->get_order_number() );
		}
		
		$amount = $order->get_total();
		$currency = get_woocommerce_currency();

        // check amount if <= 0 
		if($amount == "" ){
			$order->add_order_note( sprintf( "Transaction Error: '%s'","Zero Amount Generated" ) );
			wc_add_notice( __( sprintf( "%s","Something went wrong. Please try again." ) , 'woocommerce'), "error" );
			wp_redirect( wc_get_checkout_url() ); exit;		
		}

		if( $this->line_items == 'yes' ){
			// Get Cart Items
			$cart_items = $woocommerce->cart->get_cart();
            
			$cb_sf_line_times = array();
			if( ! empty( $cart_items ) ){
				$x = 0;
				foreach( $cart_items  as $values ){
					
					if( $values[ 'product_id' ] ){
						$product = wc_get_product( $values['product_id']);
						$product_sku  = $product->get_sku();
						$products_cats = $product->get_category_ids();
					} else {
						$product = wc_get_product( $values['variation_id']);
						$product_sku = $product->get_sku();
						$products_cats = $product->get_category_ids();
					}
					
					if( ! empty( $product_sku ) ){
						$sku = $product_sku;
					} else {
						$sku = "EMPTY";
					}
					
					
					if( $this->round_line_taxamount === false ){
						$line_tax_amount = (double) number_format($values['line_tax'], 2, ".", "");		
					} else {
						$line_tax_amount = round( $values['line_tax'] );	
					}

					if ( $this->round_line_unitprice === false ) {
						$line_unit_price = (double) number_format($values['line_total'], 2, ".", "");	
					} else {
						$line_unit_price = round($values['line_total']);
					}

					$units_of_measurement = !empty($this->settings['units_of_measurement']) ? $this->settings['units_of_measurement'] : '';
					$item_commodity_code = !empty($this->settings['item_commodity_code']) ? $this->settings['item_commodity_code'] : ''; 
						

					
					$_product 									= wc_get_product( $values['product_id'] );
					$cb_sf_line_times['item_'.$x.'_name'] 		= sanitize_text_field($_product->get_name());
					$cb_sf_line_times['item_'.$x.'_code'] 		= $values['product_id'];
					$cb_sf_line_times['item_'.$x.'_quantity'] 	= $values['quantity'];
					$cb_sf_line_times['item_'.$x.'_sku'] 		=  $sku;
					$cb_sf_line_times['item_'.$x.'_unit_price'] = $line_unit_price;
					$cb_sf_line_times['item_'.$x.'_tax_amount'] = $line_tax_amount;

					$processing_level = $this->processing_level;

					if( $processing_level !== 'none' ){
						
						//$cb_sf_line_times['item_'.$x.'_alternate_tax_rate'] 		= WC()->cart->get_taxes_total();
						//$cb_sf_line_times['item_'.$x.'_discount_amount'] 			= WC()->cart->get_discount_total();
						//$cb_sf_line_times['item_'.$x.'_total_amount'] 			= WC()->cart->total;
						//$cb_sf_line_times['item_'.$x.'_local_tax'] 				= WC()->cart->get_taxes_total();
						//$cb_sf_line_times['item_'.$x.'_national_tax'] 			= WC()->cart->get_taxes_total();
						//$cb_sf_line_times['item_'.$x.'_alternate_tax_id'] 		= "1";						
						//$cb_sf_line_times['item_'.$x.'_alternate_tax_type'] 		= "00";
						//$cb_sf_line_times['item_'.$x.'_alternate_tax_amount'] 	= WC()->cart->get_taxes_total();
						//$cb_sf_line_times['item_'.$x.'_alternate_tax_applied'] 	= "0";

						$cb_sf_line_times['item_'.$x.'_invoice_number'] 		= $order->get_order_number();
						

						if(!empty($units_of_measurement)){
							$cb_sf_line_times[ 'item_'.$x.'_unit_of_measure'] = $units_of_measurement;
						}

						if(!empty($item_commodity_code)){
							$cb_sf_line_times['item_'.$x.'_commodity_code'] = $item_commodity_code;
						}

					}

					$cb_sf_line_times['line_item_count'] 		= count($cart_items);

					$x++;
				}
			}	
		}

		// Get Configuration before redirect to cybersource

		$profile_id = $this->profile_id;
		$access_key = $this->access_key;
		$secret_key = $this->secret_key;
		$cb_action_url = $this->wm_cb_url;
		$transaction_type  = $this->trans_type_web_standard_create;
		
		$payment_token = "";
		
		$signed_field_names = explode( ',', $signed_field_names );
		$key = array_search( 'payment_token' , $signed_field_names);

		if (false !== $key) {
			unset($signed_field_names[$key]);
		}
		
		if( $this->line_items == 'yes' ){
			$signed_field_names = array_merge( array_keys($cb_sf_line_times), $signed_field_names ) ;
			$signed_field_names = implode(',',$signed_field_names);		
		} 

		else {
		    $signed_field_names = implode(',',$signed_field_names);		
		}

		if( wp_is_mobile() ){
			$thank_you_redirecting_message = __( 'Please wait...', 'woocommerce' );	
		} else {
			$thank_you_redirecting_message = __( 'Thank you for your order. We are now redirecting you to CyberSource Secure Acceptance payment page. Please wait...' , 'woocommerce' );	
		}


		if( $this->round_total_amount === false ){
			$amount = (double) number_format($amount, 2, ".", "");
		} else {
			$amount = round($amount);
		}

		if( $this->round_line_taxamount === false ){
			$tax_amount =  (double) number_format($order->get_total_tax(), 2, ".", "");
		} else {
			$tax_amount = round( $order->get_total_tax() );	
		}
		
		//$cb_uuid = get_post_meta( $order_id , '_cb_transaction_uuid', true );

		$cb_uuid = $order->get_meta( '_cb_transaction_uuid' );
		
		echo '
		<form id="cb_payment_confirmation" action="'.esc_url($cb_action_url).'" method="POST" >
			';
		?>	
       
		<?php
		// Fingerprinting text input     
		do_action( 'cybersource_device_fingerprint_profiler' );

		$consumer_id = $order->get_customer_id();

		if( empty($consumer_id) || $consumer_id == 0 ){
			$consumer_id = $order_id.time();
		} 


		// controlling billing address not send to cybersource

		if($this->dont_send_billing_fields === true ){
			$get_billing_city = "";
			$get_billing_country = "";
			$get_billing_address_1 = "";
			$get_billing_address_2 = "";
			$get_billing_postcode = "";
			$get_billing_state = "";

		} else {
			$get_billing_city = sanitize_text_field($this->strip_extra_char($order->get_billing_city()));
			$get_billing_country = sanitize_text_field($order->get_billing_country());
			$get_billing_address_1 = sanitize_text_field($this->strip_extra_char($order->get_billing_address_1()));
			$get_billing_address_2 = sanitize_text_field($this->strip_extra_char($order->get_billing_address_2()));
			$get_billing_postcode = sanitize_text_field($order->get_billing_postcode());
			$get_billing_state = sanitize_text_field($order->get_billing_state());


		}

		// Default Address

		$get_shipping_address1 = sanitize_text_field($this->strip_extra_char($order->get_shipping_address_1()));
		$get_shipping_address2 = sanitize_text_field($this->strip_extra_char($order->get_shipping_address_2()));

		if( $this->enable_auto_split_address === true ){

			$addres_max_length = ! empty($this->address_input_size) ? $this->address_input_size : 41;

			if( ! empty($get_billing_address_1) && strlen($get_billing_address_1) > $addres_max_length ){

				$split_billing_address	= str_split($get_billing_address_1,$addres_max_length);
				$get_billing_address_1    	= $split_billing_address[0];  		
				
				if(empty($get_billing_address_2)){
					$get_billing_address_2 	= $split_billing_address[1];
				} else {
					$get_billing_address_2 	= $split_billing_address[1] . " ". $get_billing_address_2;
					// if $get_billing_address_2 > $addres_max_length the validation is on the cybersource
				}

			}

			if( ! empty($get_shipping_address1) && strlen($get_shipping_address1) > $addres_max_length ){

				$split_shipping_address		= str_split($get_shipping_address1,$addres_max_length);
				$get_shipping_address1    	= $split_shipping_address[0];  		
				
				if(empty($get_shipping_address2)){
					$get_shipping_address2 	= $split_shipping_address[1];
				} else {
					$get_shipping_address2 	= $split_shipping_address[1] . " ". $get_shipping_address2;
					// if $get_shipping_address2 > $addres_max_length the validation is on the cybersource
				}

			}

		}

		


		if( strtolower($this->enable_billing_mobile_phone) == 'yes' ){
			$payer_authentication_mobile_phone = $order->get_meta('billing_mobile_phone');
		} else {
			$payer_authentication_mobile_phone = $order->get_billing_phone();
		}

		$payer_authentication_mobile_phone = str_replace("+","",sanitize_text_field($payer_authentication_mobile_phone));
		$payer_authentication_mobile_phone = str_replace(" ","",sanitize_text_field($payer_authentication_mobile_phone));

		 // Check if the "Ship to a different address?" checkbox is selected
		$ship_to_different_address = isset($_POST['ship_to_different_address']) ? wc_string_to_bool($_POST['ship_to_different_address']) : false;

		if( $ship_to_different_address === false ){
			
			$ship_to_address_city 			= $get_billing_city;
			$ship_to_address_country 		= $get_billing_country;
		  	$ship_to_address_line1			= $get_billing_address_1;
		  	$ship_to_address_line2			= $get_billing_address_2;
		  	$ship_to_address_postal_code	= $get_billing_postcode;
		  	$ship_to_address_state			= $get_billing_state;
		  	$ship_to_phone					= str_replace("+","",sanitize_text_field($order->get_billing_phone()));
			$ship_to_phone					= str_replace(" ","", $ship_to_phone);			
		  	$ship_to_forename				= sanitize_text_field($this->strip_extra_char($order->get_billing_first_name()));
		  	$ship_to_surname				= sanitize_text_field($this->strip_extra_char($order->get_billing_last_name()));

		} else {

			$ship_to_address_city 			= sanitize_text_field($this->strip_extra_char($order->get_shipping_city()));
			$ship_to_address_country 		= sanitize_text_field($order->get_shipping_country());
		  	$ship_to_address_line1			= $get_shipping_address1;
		  	$ship_to_address_line2			= $get_shipping_address2;
		  	$ship_to_address_postal_code	= $get_billing_postcode;
		  	$ship_to_address_state			= sanitize_text_field($order->get_shipping_postcode());
		  	$ship_to_phone					= str_replace("+","",sanitize_text_field($order->get_billing_phone()));
			$ship_to_phone					= str_replace(" ","",$ship_to_phone);
		  	$ship_to_forename				= sanitize_text_field($this->strip_extra_char($order->get_shipping_first_name()));
		  	$ship_to_surname				= sanitize_text_field($this->strip_extra_char($order->get_shipping_last_name()));


		} 

		// sanitize phone number
		$bill_to_phone = str_replace("+","",sanitize_text_field($order->get_billing_phone()));
		$bill_to_phone = str_replace(" ","",sanitize_text_field($bill_to_phone));


		$cb_args = array(
		  'transaction_uuid' 		=> sanitize_text_field($cb_uuid),
		  'signed_date_time' 		=> gmdate("Y-m-d\TH:i:s\Z") ,
		  'access_key' 				=> sanitize_text_field($access_key),
		  'profile_id' 				=> sanitize_text_field($profile_id),
		  'signed_field_names' 		=> $signed_field_names,
		  'unsigned_field_names'	=> $unsigned_field_names ,
		  'locale' 					=> $this->locale,
		  'transaction_type' 		=> sanitize_text_field($transaction_type) ,
		  'reference_number' 		=> sanitize_text_field($order->get_order_number()) ,
		  'amount' 					=> $amount,
		  'tax_amount'				=> $tax_amount,	
		  'currency' 				=> $currency,
		  'bill_city'				=> $get_billing_city,
		  'bill_to_address_city'	=> $get_billing_city,
		  'bill_to_address_country'	=> $get_billing_country,
		  'bill_address1'			=> $get_billing_address_1,
		  'bill_to_address_line1'	=> $get_billing_address_1,
		  'bill_to_address_line2'	=> $get_billing_address_2,
		  'bill_to_address_postal_code'=> $get_billing_postcode,
		  'bill_to_address_state'	=> $get_billing_state,
		  'bill_to_company_name'	=> sanitize_text_field($this->strip_extra_char(substr($order->get_billing_company(),0,40))),
		  'bill_to_email'			=> sanitize_text_field($order->get_billing_email()) ,
		  'bill_to_forename'		=> sanitize_text_field($this->strip_extra_char($order->get_billing_first_name())),
		  'bill_to_phone'			=> $bill_to_phone,
		  'bill_to_surname'			=> sanitize_text_field($this->strip_extra_char($order->get_billing_last_name())),
		  'ship_to_address_city'	=> $ship_to_address_city,
		  'ship_to_address_country'	=> $ship_to_address_country,
		  'ship_to_address_line1'	=> $ship_to_address_line1,
		  'ship_to_address_line2'	=> $ship_to_address_line2,
		  'ship_to_address_postal_code'	=> $ship_to_address_postal_code,
		  'ship_to_address_state'	=> $ship_to_address_state,
		  'ship_to_phone'			=> $ship_to_phone,
		  'ship_to_forename'		=> $ship_to_forename,
		  'ship_to_surname'			=> $ship_to_surname,
		  'consumer_id'				=> sanitize_text_field($consumer_id),
		  'merchant_id'				=> sanitize_text_field($this->merchant_id),
		  'customer_ip_address'	    => WC_Geolocation::get_ip_address(),
		  'device_fingerprint_id'   => apply_filters( 'cybersource_session_id', false ),
		  'payer_authentication_mobile_phone' => $payer_authentication_mobile_phone,
		  'customer_browser_screen_height' => sanitize_text_field($order->get_meta('billing_browser_screen_height')),
		  'customer_browser_screen_width' => sanitize_text_field($order->get_meta('billing_browser_screen_width')),
		  
				 	
		);

		$processing_level = $this->processing_level;

		if( $processing_level !== 'none' ){

			$purchase_level = array(
				//'auth_card_level_3_eligible'
				'duty_amount'				=> $amount,
				'discount_amount'			=> $order->get_discount_total(),
				'purchasing_level' 			=> $this->processing_level,
				'ship_from_postal_code'     => $get_billing_postcode,				
				'user_po'					=> $order->get_order_number(),
				//'freight_amount'			=> $order->get_shipping_total(),
				//'vat_invoice_reference_number' => $order->get_order_number(),
				//'vat_tax_amount' 				=> $order->get_total_tax(),
				//'vat_tax_rate' 				=> 0.99,				
				//'purchaser_vat_registration_number' => '123456',
				//'alternate_tax_amount'      	=> $order->get_total_tax(),
				//'alternate_tax_indicator'   	=> "1",
			);

			$cb_args = array_merge($cb_args, $purchase_level);

		}
		
		//Unset Payment fields
		if( $this->enable_mdd_fields === true ){
			$cb_args = apply_filters( 'cybersource_unset_field_names', $cb_args );
		}

		if( $this->line_items == 'yes' ){
			$cb_args = array_merge( $cb_args, $cb_sf_line_times );
		}	


		if( is_array(  $mdd_fields ) && ! empty( $mdd_fields ) ){
				$cb_args = array_merge( $cb_args, $mdd_fields );
		}		

		$cb_signature = array( 'signature' => $this->sign( $cb_args , $secret_key ) );
		$cb_combined_params =  array_merge( $cb_args, $cb_signature);		

		parent::log( 'Cybersource Request - WM API: ' . print_r( $cb_combined_params, true ) );

		// controlling billing address not send to cybersource		

		$cb_args_array = array();
		foreach($cb_combined_params as $key => $value){

			$cb_args_array[] = '<input type="hidden" name="'.esc_attr($key).'" value="'.sanitize_text_field($value).'" />';

			
		}

		
		echo implode('', $cb_args_array);
		echo '
		<input type="submit" class="button-alt" id="submit_cb_payment_form" value="'.esc_attr( __( 'Pay via CyberSource Secure Acceptance', 'woocommece') ) .'" /> 
		<a class="button-alt" href="'.esc_url($order->get_cancel_order_url()).'">'. __('Cancel order', 'woocommece').'</a>
		';
		 ?>
		
        
    <?php
     echo "</form>"; 
	 
	}

	public function cybersource_thankyou_processing_order_status( $order_id ){

		//$order = new WC_Order( $order_id );
		$order = wc_get_order( $order_id );
		$order_data = $order->get_data();

		$transaction_id = get_post_meta( $order_id, '_cyber_transaction_id' , true );
		$decision_id = get_post_meta( $order_id, '_cyber_decision_id',  true );

		$order_status = parent::virtual_order_payment_complete_order_status( $order_id );

		// some paid transaction not change the order status 'processing'
		if ( 'pending' == $order_data['status'] && $decision_id == 'ACCEPT' && ! empty($transaction_id) ) {
			if($order_status == 'completed' ){
			    $order->update_status( 'completed' );
        	} else {
        		$order->update_status( 'processing' );
        	}	
		}
			
	}

	public function capture_order_status_completed( $order_id, $order ){

		if( $this->transaction_type == 'sale' ) return;

		$transaction_id = get_post_meta( $order_id, '_'. $this->id .'_transaction_id' , true );
		$request_token = get_post_meta( $order_id, '_'. $this->id .'_request_token' , true );
		$amount = $order->get_total();
		
		if ( ! $transaction_id ) {
			return new WP_Error( $this->id . '_capture_error',
				esc_html__( sprintf(
					'%s Capture failed because the Request ID is missing.',
					ucwords($this->id)
				), 'woocommerce' )
			);
		}

		$soap = $this->soaptoolkit_request(); 
		$request = $soap->createRequest( $order->get_currency());
		
		$request->clientLibrary 		= "WooCommerce PHP Client";
		$request->clientLibraryVersion 	= phpversion();
		$request->clientEnvironment 	= php_uname();
		$request->merchantID 			= $this->merchant_id;			
		$request->merchantReferenceCode = $order_id;

		if( !empty($transaction_id) && !empty($request_token)  ){

				$capture_service = new stdClass();
				$capture_service->run = 'true';
				$capture_service->authRequestToken = $request_token;

				if ( isset( $transaction_id ) )
				{
					$capture_service->authRequestID = $transaction_id;
				}

				$request->ccCaptureService = $capture_service;
				//$request->purchaseTotals->grandTotalAmount = (double) number_format( $amount, 2, ".", "");
				$request->purchaseTotals = (object) array( 'grandTotalAmount' => (double) number_format( $amount, 2, ".", "") );
				
				parent::log( 'Cybersource Request - SOP: ' . print_r( $request, true ) );

				$response = $soap->runTransaction( $request );

				parent::log( 'Cybersource Response - SOP: ' . print_r( $response, true ) );

				if(!empty($response->requestID) && $response->reasonCode == 100 && $response->decision == 'ACCEPT' ){

					$request_ID 	= $response->requestID; 
					$request_token  = $response->requestToken; 
					// update_post_meta( $order_id, '_' . $this->id . '_capture_request_id', $request_ID );
					// update_post_meta( $order_id, '_' . $this->id . '_request_token', $request_token );
					// update_post_meta( $order_id, '_' . $this->id . '_capture', 1 );

					$order->update_meta_data( '_' . $this->id . '_capture_request_id', $request_ID );
					$order->update_meta_data(  '_' . $this->id . '_request_token', $request_token );
					$order->update_meta_data( '_' . $this->id . '_capture', 1 );
					$order->save();
					
					$order->add_order_note(
						esc_html__( sprintf(
							'%1$s Capture %2$s with Request ID of %3$s',
							$this->method_title,
							sanitize_text_field($response->decision),
							sanitize_text_field($response->requestID)
						), 'woocommerce' )
					);

					return true;

				} else {

					$err_msg = esc_html__($this->reason_code($response->ccCaptureReply->reasonCode));

					$order->update_status( 'failed' );
					$order->add_order_note(
						esc_html__( sprintf(
							'%1$s Capture %2$s,  %3$s',
							$this->method_title,
							sanitize_text_field($response->decision),
							sanitize_text_field($err_msg)
						), 'woocommerce' )
					);
					
					return new WP_Error( $this->id . '_capture_error', esc_html__( ucwords($this->method_title). ' ' . 'Payment Capture Failed, '. sanitize_text_field($err_msg)  , '' ,'woocommerce' ) );

				}
				return false;
		
		}
		return $response;
	}

	public function process_refund( $order_id, $amount = null, $reason = '' ){

		if( $this->transaction_type == 'authorization' ){
			return parent::reversal_payment ( $order_id, $amount = null, $reason = '' );
		} else {
			return parent::void_payment ( $order_id, $amount = null, $reason = '' );
		}
		
	}
	
}