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


if(!function_exists('cybersource_add_mdd_fields')){

  add_filter( 'cybersource_add_signed_field_names', 'rps_cybersource_add_mdd_fields', 9, 1 );

  function rps_cybersource_add_mdd_fields( $order_id ){

    global $woocommerce;

    $settings = get_option( 'woocommerce_cybsawm_settings' );

    $order 	= wc_get_order( $order_id );
    
    $consumer_id = get_current_user_id();
    $previous_customer = ( $consumer_id == 0 ? 'NO' : 'YES' ); 
    
    // Get Cart Items
    $cart_items = $woocommerce->cart->get_cart();	

    $cb_items = array();

    if( ! empty( $cart_items ) ){

      if( count($cart_items) == 1 ){
        
        $x = 0;
        foreach( $cart_items  as $values ){
          
          if( $values[ 'product_id' ] ){
            $product = wc_get_product( $values['product_id']);
            $products_cats = $product->get_category_ids();
          } else {
            $product = wc_get_product( $values['variation_id']);
            $products_cats = $product->get_category_ids();
          }
          
          
          $_product = $values['data']->post;

          $mdd4 = str_replace(array('&','"', "'",'<', '>','(',')','-'), '', $_product->post_title);
          $cb_items[ 'merchant_defined_data4' ] = esc_html( substr($mdd4, 0, 99) );
        
          if( is_array($products_cats) && ! empty($products_cats)){
            $c = array();
            foreach ($products_cats as $value) {
              if( $term = get_term_by( 'id', $value, 'product_cat' ) ){
              $c[] = $term->name;
            }	
            }

            $products_cats = implode( ',', $c );
          } else {
            $products_cats = '';
          }

          $mdd3 = $products_cats;
          $mdd3 = strlen($mdd3) > 100 ? substr($mdd3,0,100) : $mdd3;
          $mdd3 = str_replace(array('&','"', "'",'<', '>','(',')','-'), '', $mdd3);
          $cb_items[ 'merchant_defined_data3' ] = esc_html($mdd3);

          $x++;
        }

      } else {


        $x = 0;
        foreach( $cart_items  as $values ){
          
          if( $values[ 'product_id' ] ){
            $product = wc_get_product( $values['product_id']);
            $products_cats = $product->get_category_ids();
          } else {
            $product = wc_get_product( $values['variation_id']);
            $products_cats = $product->get_category_ids();
          }
          
          
          $_product 				= $values['data']->post;
          
          $mdd_product[ 'name' ][]  = $_product->post_title; 

          if( ! empty($products_cats) && is_array($products_cats)){
            foreach ( $products_cats as $key => $value) {
              $mdd_product[ 'cats' ][]  = $value; 
            }
          } else {
            $mdd_product[ 'cats' ]  = $products_cats; 
          }
          

          $x++;
        }

        if( ! empty( $mdd_product[ 'name' ] ) && is_array($mdd_product[ 'name' ])){
          $mdd4 = implode( ',', $mdd_product[ 'name' ] );
          $mdd4 = str_replace(array('&','"', "'",'<', '>','(',')','-'), '', $mdd4);
          $cb_items[ 'merchant_defined_data4' ] = esc_html(substr($mdd4, 0, 99));
        }

        if( ! empty($mdd_product[ 'cats' ]) && is_array($mdd_product[ 'cats' ] )){
          $c = array();

          foreach ($mdd_product[ 'cats' ] as  $value) {
            if( $term = get_term_by( 'id', $value, 'product_cat' ) ){
              $c[] = $term->name;
            }
          }
          
          $mdd3 = implode( ',', $c);
          $mdd3 = strlen($mdd3) > 100 ? substr($mdd3,0,100) : $mdd3;
          $mdd3 = str_replace(array('&','"', "'",'<', '>','(',')','-'), '', $mdd3);
          $cb_items[ 'merchant_defined_data3' ] = esc_html($mdd3);
          
        }
        
      }

    }


    $shipping_class = array_values($cart_items);
    

    if( ! empty( $shipping_class)){
      $shipping_class = $shipping_class[0]['data']->get_shipping_class();
      
      if( empty($shipping_class) ){
          $shipping_class = WC()->session->get('chosen_shipping_methods');

         if(!empty($shipping_class)){
          $shipping_class = $shipping_class[0];
         } else {
          $shipping_class = 'NA';
         }
      }
      
    } else {
      $shipping_class = 'No shipping method available';
    }

    if( $consumer_id > 0 ){
      $user_info 		= get_userdata($consumer_id);
      $customer_name 	= get_user_meta( $consumer_id, 'billing_first_name', true ) . ' ' .get_user_meta( $consumer_id, 'billing_last_name', true );
      $customer_email =  get_user_meta( $consumer_id, 'billing_email', true );
      $customer_phone =  get_user_meta( $consumer_id, 'billing_phone', true );
    } else {
      $customer_name 	= 'NA';
      $customer_email = 'NA';
      $customer_phone = 'NA';
    } 

    $customer_ip 	= ! empty( $_SERVER['HTTP_X_FORWARD_FOR'] ) ? $_SERVER['HTTP_X_FORWARD_FOR'] : $_SERVER['REMOTE_ADDR'];
    
    // Get the WC_Customer instance Object for the current user
    $customer = new WC_Customer( $consumer_id );

    // Get the last WC_Order Object instance from current customer
    $last_order = $customer->get_last_order();
    
    if ( is_user_logged_in() ) {

      if($last_order){
        $lo = $last_order->get_date_created()->format ('Y-m-d');
        if(date('Y-m-d') == $lo ){
          $mdd_13 = '0';
        } else {
          $mdd_13 = (date('Y-m-d') - $last_order->get_date_created()->format ('Y-m-d')); //Number of days since the last purchase
        }
      } else {
        $mdd_13 = '0';
      }
       
       $mdd_14 = $last_order->get_total(); //Average purchase amount in the last 6 months		
      
    
    } else {
      // Guest user;
      
      $mdd_13 = '0'; //Number of days since the last purchase
      $mdd_14 = '0'; //Average purchase amount in the last 6 months
          
    }	
    
    $notes = ! empty ($order->get_customer_note()) ? strtoupper($order->get_customer_note()) : 'NONE';
      
    
    $mdd1 =  array(
        'merchant_defined_data1'  => 'WC',  // Chanel of Operation
          'merchant_defined_data2'  => 'YES', // 3D secure
          'merchant_defined_data5'  =>  $previous_customer, // Previous Customer 
          //'merchant_defined_data6'  =>  $shipping_class, // Shipping Method
          'merchant_defined_data6'  =>  'Standard', // Shipping Method
          'merchant_defined_data7'  =>  WC()->cart->get_cart_contents_count(), // Number of Items Sold
          'merchant_defined_data8'  =>  $woocommerce->customer->get_country(), // Product Shipping Country
        
        'merchant_defined_data9'  =>  "1", //How many different payment methods has the client used in the past
        'merchant_defined_data10'  =>  "yes", //was the Email entered manually or copied and pasted? (Yes or No)
        'merchant_defined_data11'  =>  "1", //Number of attempts for the same card
        'merchant_defined_data12'  =>  "1", //Number of attempts of a card
        'merchant_defined_data13'  =>  $mdd_13, //Number of days since the last purchase
        'merchant_defined_data14'  =>  $mdd_14, //Average purchase amount in the last 6 months
        'merchant_defined_data15'  =>  $notes, //Notes or comments included with the order
        'merchant_defined_data19'  => $order_id, // reference Order Id
        'merchant_defined_data20'  => __( 'NO', 'woocommerce'  ), // VIP Customer
          
      );

    // $cb_items[ 'merchant_defined_data3' ] = "";  
    // $cb_items[ 'merchant_defined_data4' ] = "";  

    $mdd = array_merge( $mdd1, $cb_items );

    //* Override Shipping address


    if($settings['enable_shipping_fields'] == 'yes' ){

      $shipping_address = array(

        'ship_to_address_line1' =>  get_option( 'ship_to_address_line1_text' ),
        'ship_to_address_line2' =>  get_option( 'ship_to_address_line2_text' )
      );
  
      $mdd = array_merge( $mdd, $shipping_address );

    }

    return $mdd;

  }

} 
/*
  Woocommerce Hooks 
 */
// Display the mobile phone field
function cybersource_hcca_checkout_fields( $fields ) {

  $settings = get_option( 'woocommerce_cybsawm_settings' );

  if(strtolower($settings['enabled']) == 'yes' && strtolower($settings['enable_billing_mobile_phone']) == 'yes' ){

    $fields['billing']['billing_mobile_phone'] = array(
      'label' => __('Mobile Phone', 'woocommerce'),
      'placeholder' => _x('Mobile Phone', 'placeholder', 'woocommerce'),
      'required' => true,
      'class' => array('form-row-wide'),
    );

  }

  return $fields;
 
}

add_filter( 'woocommerce_checkout_fields' , 'cybersource_hcca_checkout_fields' ); 

//Validate the custom fields

add_action( 'woocommerce_after_checkout_validation', 'cybersource_hcca_wc_check_confirm_phone_matches_checkout', 10, 2 );

function cybersource_hcca_wc_check_confirm_phone_matches_checkout( $posted ) {

    $settings = get_option( 'woocommerce_cybsawm_settings' );

    if(strtolower($settings['enabled']) == 'yes' && strtolower($settings['enable_billing_mobile_phone']) == 'yes' ){

      $checkout = WC()->checkout;

      if ( !is_numeric($posted['billing_mobile_phone'])) {
        wc_add_notice( __( 'Invalid Mobile Phone number do not match.', 'woocommerce' ), 'error' );
      }

    }

    
} 

