<?php
function lorem_func() {
    if(isset($_GET['partner'])) {
        $partner = $_GET['partner'];    
        if ($partner == "SF") {
            $txt = "<img src='https://codebreakertech.com/wp-content/uploads/2020/03/SF-Logo.png'>";
        } else {
            $txt = "";
        }    
    } else {
        $txt = "";
    }
 return $txt;
}

function entryUrlCookie(){
    $actual_link = '';
    if(isset($_COOKIE['_referringURL'])) {
      $actual_link = urldecode($_COOKIE['_referringURL']);
    } else {
      $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    }
    return $actual_link;
}

function check_CBT_partner(){
      if(isset($_GET['partner'])) {
        $partner = $_GET['partner'];    
        if ($partner == "SF") {
            $txt = "SF";
        } else {
            $txt = "CB";
        }    
    } else {
        $txt = "CB";
    }
return $txt;
}
function check_params_for_form(){
      $output = ""; 
        $firstRun = true; 
        foreach($_GET as $key=>$val) { 
        if($key != $parameter) { 
            if(!$firstRun) { 
                $output .= "&"; 
            } else { 
                $firstRun = false; 
            } 
            $output .= $key."=".$val;
         } 
    } 

    return $output;
}
add_shortcode('check_params_for_form', 'check_params_for_form');
add_shortcode('check_CBT_partner', 'check_CBT_partner');
add_shortcode('footer_BP_SF_img', 'lorem_func');

function checkIfThankYouPageIsCartFlow(){
    $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    if (strpos($actual_link, 'wcf-order') !== false) {
        if(isset($_REQUEST['wcf-order'])){
            $order_id = $_REQUEST['wcf-order'];
            sendPaymentToSperseAndMainDB( $order_id );
        }
    }
}


function has_bought($userId) {
    // Get all customer orders
    $customer_orders = get_posts( array(
        'numberposts' => 1, // one order is enough
        'meta_key'    => '_customer_user',
        'meta_value'  => $userId,
        'post_type'   => 'shop_order', // WC orders post type
        'post_status' => 'wc-processing', // Only orders with "processing" status
        'fields'      => 'ids', // Return Ids "processing"
    ) );

    // return "true" when customer has already at least one order (false if not)
   return count($customer_orders) == 1  ? true : false; 
}

function checkIfOrderIsNewOrRenewal( $orderId ) {
    
    $order = wc_get_order( $orderId );
    $userId   = $order->get_user_id();
    // $check = has_bought($userId);
    $checkOrderId = get_post_meta($orderId, '_subscription_renewal', true);
    if(!$checkOrderId) {
        
        $contactId = get_user_meta($userId, '_contactId');
        $leadId    = get_user_meta($userId, '_leadId');
        
        if($contactId) {
            // sendPaymentToSperseAndMainDBRenewel($orderId, null);
            if(wcs_order_contains_subscription($orderId)) {
                // $nextPaymentDate = get_post_meta( $orderId, '_schedule_next_payment' );
                
                $subscriptions_ids = wcs_get_subscriptions_for_order( $orderId );
                
                foreach( $subscriptions_ids as $subscription_id => $subscription_obj ) {
                    $subscription_id = $subscription_id;
                  
                }
                
                
                $getSubscription    = wcs_get_subscription( $subscription_id );
                $nextPaymentDate    =  $getSubscription->get_date( 'next_payment' );
                sendPaymentToSperseAndMainDBRenewel($orderId, $nextPaymentDate);
            } else {
                sendPaymentToSperseAndMainDBRenewel($orderId, null);
            }
        } else {
            sendPaymentToSperseAndMainDB($orderId);    
        }
        
        // sendPaymentToSperseAndMainDB($orderId);
        
    } else {
        
        //   sendPaymentToSperseAndMainDBRenewel($orderId, null);
        
    }
    
}

function add_subs_to_csvv($subscription, $order) {
    $renewalOrderId = $order->get_id();
    
    $subscriptionNexd   = $subscription->get_date( 'next_payment' );
    sendPaymentToSperseAndMainDBRenewel($renewalOrderId, $subscriptionNexd);
}


function sendRefundedOrders($orderId) {
    
    $apiKey = APIKEY;
    $ADDBANKCARDPAYMENT = ADDBANKCARDPAYMENT;

    $meta_value;
    $subscriptions = [];
    $price; 
    $get_period;
    $product_name;
    $wpOrder = wc_get_order( $orderId );
    $user_id   = $wpOrder->get_user_id();
    
    $order_data = $wpOrder->get_data();
      global $wpdb;
      
      $resultsOr = $wpdb->get_results( "SELECT * FROM `wp_postmeta` WHERE `meta_key` LIKE '_customer_user' AND meta_value = '".$user_id."' ORDER BY post_id ASC LIMIT 1", OBJECT );
      $pOrderId = $resultsOr[0]->post_id;
      
      
      $resultsOrSub = $wpdb->get_results( "SELECT * FROM `wp_postmeta` WHERE `meta_key` LIKE '_customer_user' AND meta_value = '".$user_id."' ORDER BY post_id ASC LIMIT 1,1", OBJECT );
      $pSubOrderId = $resultsOrSub[0]->post_id;
      
      
      $results = $wpdb->get_results( "SELECT * FROM `wp_postmeta` WHERE post_id = '".$pOrderId."' AND meta_key = '_createLeadResponse'", OBJECT );
      foreach ($results as $key => $value) {
        $meta_value = $value->meta_value;
      }
      
      $getOrderCreatedDate = $wpdb->get_results( "SELECT post_date FROM `wp_posts` WHERE ID = '".$orderId."'", OBJECT );
      $OrderCreatedDate = $getOrderCreatedDate[0]->post_date;
      
      
      $meta_value = json_decode($meta_value);
      $contactId  = get_user_meta( $user_id, '_contactId', true );
      $leadId     = get_user_meta( $user_id, '_leadId', true );
      
    
          
      $subscription_products = $wpOrder->get_items();
      $subscription = [];
      $lines = [];
      $line = [];
      $order_discount_amount = null;
      if ( sizeof( $subscription_items = $wpOrder->get_items() ) > 0 ) {
          foreach ( $subscription_items as $item_id => $item ) {
            $product = $item->get_product();
            $product_id = $product->get_id();
            $product_name = $product->get_title();
            $get_period = WC_Subscriptions_Product::get_period( $product_id );
            $price = WC_Subscriptions_Product::get_price( $product_id );
            
            
            
            $product_rp = wc_get_product( $item['product_id'] );
	    $line_t = $product_rp->get_regular_price();
            
            // calculate commissionable value
	    $item_total = $wpOrder->get_item_meta($item_id, '_line_total', true);
	    $item_sub_total = $wpOrder->get_item_meta($item_id, '_line_subtotal', true);

	    $item_total_check = (int) $item_total;
	    $commissionableAmount = 0;
	   
	     $exclusiveProductIds = array(406, 407, 408, 536, 539, 42195);

	     
	     $productIdCheck = false;
	     foreach($exclusiveProductIds as $val) {
	         
	         if($val == $item['product_id']) {
	             
	             $productIdCheck = true;
	             
	         }
	         
	     }
	     if(!$productIdCheck) {
	         
	         if($item_total_check != 0) {
	                 
	                 $whole = floor($item_total);
                     $lastDigit = substr($whole,-1);
                     
                     if($lastDigit == 4 || $lastDigit == 9) {
                         $commissionableAmount = $whole + 1;
                         
                     } else {
                         $item_total = $item_total;
                     }
	                 
	             }
	         
	     }

                if(!$get_period) {
                   $get_period  = "Piece";    
                }
                
            
                $line['unitId'     ] = $get_period;  
                $line['description'] = $item['name'];
        	    $line['productCode'] = $item['product_id'];
        	    $line['commissionableAmount'] = $commissionableAmount;
        	   // $line['rate'] = $line_t;
        	    $line['rate'] = $item_sub_total;
        	    $line['quantity'] = $item['quantity'];
        	    $line['sortOrder'] = 1;
        	   // $line['total'] = $line_t * $line['quantity'];
        	    $line['total'] = $item_sub_total * $line['quantity'];
	    
	    
              array_push($lines, $line);
            
          }
      }
      $object_bill_addr = new stdClass();
      $object_bill_addr->countryId = $order_data['billing']['country'];
      if($order_data['billing']['country'] == "US" || $order_data['billing']['country'] == "CA") {
        $object_bill_addr->stateId   = $order_data['billing']['state']; 
      } else {
        $object_bill_addr->stateName = $order_data['billing']['state'];
      }
      $object_bill_addr->city        = $order_data['billing']['city'];
      $object_bill_addr->zip         = $order_data['billing']['postcode'];
      $object_bill_addr->address1    = $order_data['billing']['address_1'];
      $object_bill_addr->address2    = $order_data['billing']['address_2'];
      $object_bill_addr->firstName   = $order_data['billing']['first_name'];
      $object_bill_addr->lastName    = $order_data['billing']['last_name'];
      $object_bill_addr->email       = $order_data['billing']['email'];
      $object_bill_addr->phone       = $order_data['billing']['phone'];
      $object_shipp_add = new stdClass();
      $object_shipp_add->countryId   = $order_data['billing']['country'];
      if($order_data['billing']['country'] == "US" || $order_data['billing']['country'] == 'CA') {
        $object_shipp_add->stateId   = $order_data['billing']['state']; 
      } else {
        $object_shipp_add->stateName = $order_data['billing']['state'];
      }
      $object_shipp_add->city        = $order_data['billing']['city'];
      $object_shipp_add->zip         = $order_data['billing']['postcode'];
      $object_shipp_add->address1    = $order_data['billing']['address_1'];
      $object_shipp_add->address2    = $order_data['billing']['address_2'];
      $object_shipp_add->firstName   = $order_data['billing']['first_name'];
      $object_shipp_add->lastName    = $order_data['billing']['last_name'];
      
      ## CHANGED STATUS FROM DRAFT TO PAID USING AddBankCardPayment API.
     
      
      
      $transactionId       = get_post_meta( $orderId, '_transaction_id' ,true );
      $authorizationCode   = get_post_meta( $orderId, '_wc_authorize_net_cim_credit_card_authorization_code' ,true );
      $transactionDate = get_post_meta( $orderId, '_paid_date' ,true );
      $createInvoiceResponse = get_post_meta( $orderId, '_createInvoiceResponse' ,true );
      if(!$createInvoiceResponse) {
          $createInvoiceResponse = get_post_meta( $orderId, '_createInvoiceResponseRenewal' ,true );
          if($createInvoiceResponse) {
              
              $createInvoiceResponse = json_decode($createInvoiceResponse);
              $invoiceId = $createInvoiceResponse->result;
              
          } else {
              $invoiceId = null;
          }
      }  else {
          $createInvoiceResponse = json_decode($createInvoiceResponse);
          $invoiceId = $createInvoiceResponse->result;
      }
      
      $invoiceId = $invoiceId;
    
        $addBankCardPaymentJson = array(
          "invoiceId"   =>$invoiceId,
          "date"        =>$transactionDate,
          "description" =>"Codebreaker Order #".$orderId,
          "orderStage"  => null,
          "amount" =>  - $wpOrder->get_total(),
          "gatewayTransactionId" => $transactionId,
          "authorizationCode" => $authorizationCode,
          "gatewayName" =>"Authorize.net",
          "bankCardInfo"=>array(
            "holderName"         =>$order_data['billing']['first_name']." ".$order_data['billing']['last_name'],
            "cardNumber"         =>"4444444444444444",
            "expirationMonth"    =>"10",
            "expirationYear"     =>"2070",
            "billingAddress"     =>$order_data['billing']['address_1']." ".$order_data['billing']['address_2'],
            "billingZip"         =>$order_data['billing']['postcode'],
            "billingCity"        =>$order_data['billing']['city'],
            "billingStateCode"   =>$order_data['billing']['state'],
            "billingCountryCode" =>$order_data['billing']['country']
          )
        );
        
      $addBankCardPaymentJson = json_encode($addBankCardPaymentJson);
      $curl = curl_init();
      curl_setopt_array($curl, array(
        CURLOPT_URL => $ADDBANKCARDPAYMENT,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $addBankCardPaymentJson,
        CURLOPT_HTTPHEADER => array(
          "Content-Type: application/json",
          "Postman-Token: 10346306-aae0-4d03-be44-a1ca4d4e292c",
          "api-key: ".$apiKey,
          "cache-control: no-cache,no-cache"
        ),
      ));
      $response = curl_exec($curl);
      $err = curl_error($curl);
      curl_close($curl);
      $addBankCardPaymentRequest = $addBankCardPaymentJson;
      
      
      if ($err) {
        
           $wpOrder->update_meta_data('addBankCardPaymentRequestRefunded', $addBankCardPaymentRequest);
      
            $wpOrder->update_meta_data('_addBankCardPaymentResponseRefunded', $err);
            $wpOrder->save();
      } else {
        
             $wpOrder->update_meta_data('addBankCardPaymentRequestRefunded', $addBankCardPaymentRequest);
        
             $wpOrder->update_meta_data('_addBankCardPaymentResponseRefunded', $response);
             $wpOrder->save();
        }
        
    
    
}


function sendPaymentToSperseAndMainDB( $order_id ){
    $checkOrderId = get_post_meta($order_id, '_subscription_renewal', true);
     if(!$checkOrderId) {
    ## GET ALL ORDER DETAILS BY USING ORDER ID
    $order_id;
    $access_code = '';
    $WP_HOME = WP_HOME;
    $referrerUrl = '';
    $http_user_agent = $_SERVER['HTTP_USER_AGENT'];
    $phoneNumber = '';
    $ip = getUserIpAddr();
    $actual_link = '';
    if(isset($_COOKIE['_referringURL'])) {
      $referrerUrl = urldecode($_COOKIE['_referringURL']);
    }
    if(isset($_COOKIE['_entryUrl'])) {
      $actual_link = urldecode($_COOKIE['_entryUrl']);
    }
    if(isset($_COOKIE['wp_user_phone_number_hidden_check'])) {
      $phoneNumber = urldecode($_COOKIE['wp_user_phone_number_hidden_check']);
    }
    unset($_COOKIE['wp_user_phone_number_hidden_check']);
    setcookie("wp_user_phone_number_hidden_check", null, -1, "/");    
    ## GET AFFILIATE ID FROM COOKIES IF EXISTS
    if(isset($_COOKIE['affwp_ref'])) {
      global $wpdb;
      $aff_id = $_COOKIE['affwp_ref']; 
      if($aff_id == 0) {
        $aff_id = 9;
      }
      $results = $wpdb->get_results( "SELECT * FROM wp_affiliate_wp_affiliates WHERE affiliate_id = '".$aff_id."'", OBJECT );
      foreach ($results as $key => $value) {
        $user_id = $value->user_id;
        $user_email = $value->payment_email;
        $data['user_email'] = $user_email;
      }
      $user_info = get_userdata($user_id);
      $data['access_code']  = $user_info->user_login;
      $access_code = $user_info->user_login;
    }

    ## SEND ACCESS CODE AND ORDER ID TO ANOTHER FILE NAMED SPERSE.PHP
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => $WP_HOME."sperse.php",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => "order_id=".$order_id."&access_code=".$access_code."&referrerUrl=".$referrerUrl."&actual_link=".$actual_link."&http_user_agent=".$http_user_agent."&phoneNumber=".$phoneNumber."&client_ip=".$ip."&undefined=",
      CURLOPT_HTTPHEADER => array(
        "Content-Type: application/x-www-form-urlencoded",
        "Postman-Token: 42086d72-835b-43a6-98e5-c3b75dd7d279",
        "cache-control: no-cache"
      ),
    ));
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) {
      $err = json_decode($err);
    } else {
      $response =  json_decode($response);
    }
  }
}

function endCycleDT($d1, $months)
{
    $date = new DateTime($d1);

    // call second function to add the months
    $newDate = $date->add(add_monthsDT($months, $date));

    // goes back 1 day from date, remove if you want same day of month
    $newDate->sub(new DateInterval('P1D')); 

    //formats final date to Y-m-d form
    $dateReturned = $newDate->format('Y-m-d H:i:s'); 

    return $dateReturned;
}

function add_monthsDT($months, DateTime $dateObject) 
    {
        $next = new DateTime($dateObject->format('Y-m-d H:i:s'));
        $next->modify('last day of +'.$months.' month');

        if($dateObject->format('d') > $next->format('d')) {
            return $dateObject->diff($next);
        } else {
            return new DateInterval('P'.$months.'M');
        }
    }

function get_crm_next_payment_date( $order ) {
    if ( ! class_exists( 'WC_Subscriptions') ) {
        return;
    }
    if ( WC_Subscriptions_Renewal_Order::is_renewal( $order ) ) {
        $parent_id = WC_Subscriptions_Renewal_Order::get_parent_order_id( $order ); /* This gets the original parent order id */
        $parent_order = new WC_Order( $parent_id );
        foreach ( $parent_order->get_items() as $item ) { /* This loops through each item in the order */
            $date = WC_Subscriptions_Order::get_next_payment_date ( $parent_order, $item['product_id'] ); /* This should get the next payment date... */
            if ( $date ) {
                return date( 'Y-m-d H:i:s', strtotime( $date ) );
            }
        }
    } elseif ( WC_Subscriptions_Order::order_contains_subscription( $order ) ) {
        foreach ( $order->get_items() as $item ) { /* This loops through each item in the order */
            $date = WC_Subscriptions_Order::get_next_payment_date ( $order, $item['product_id'] ); /* This should get the next payment date... */
            if ( $date ) {
                return date( 'Y-m-d H:i:s', strtotime( $date ) );
            }
        }
    }
}



function sendPaymentToSperseAndMainDBRenewel($subscription_id, $nextPaymentDate){
    
     
    
    
    $SAVEREMOTEORDER      = SAVEREMOTEORDER;
    $CREATELEAD           = CREATECONTACT;
    $apiKey               = APIKEY;
    $CreateUserForContact = CreateUserForContact;
    $CREATEINVOICE        = CREATEINVOICE;
    $affiliateProduct     = affiliateProduct;
    $ADDBANKCARDPAYMENT   = ADDBANKCARDPAYMENT;
    $OrderSubscription    = OrderSubscription;
    $meta_value;
    $vaultSubscriptionActive = false;
    $subscriptions = [];
    // $wpOrder = new WC_Subscription( $subscription_id );
    // $order_id = method_exists( $wpOrder, 'get_parent_id' ) ? $wpOrder->get_parent_id() : $wpOrder->order->id;  
    // $orderId = $order_id;
    $orderId = $subscription_id;
    // $order = method_exists( $wpOrder, 'get_parent' ) ? $wpOrder->get_parent() : $wpOrder->order;
    // $order_data = $order->get_data();
    $price; 
    $get_period;
    $product_name;
    $wpOrder = wc_get_order( $orderId );
    $user_id   = $wpOrder->get_user_id();
    $order_data = $wpOrder->get_data();
    global $wpdb;
    
    
    // 18-10-2020
    $getSubscriptionId = 0;
    $gettingSubscriptionId = $wpdb->get_results( "Select * FROM wp_postmeta WHERE meta_key = '_customer_user' and meta_value = '".$user_id."' ORDER BY post_id ASC LIMIT 1,1", OBJECT );
    if(isset($gettingSubscriptionId[0]->post_id)){
        $getSubscriptionId     = $gettingSubscriptionId[0]->post_id;    
    }
    // 18-10-2020
    
    
      
      $resultsOr = $wpdb->get_results( "SELECT * FROM `wp_postmeta` WHERE `meta_key` LIKE '_customer_user' AND meta_value = '".$user_id."' ORDER BY post_id ASC LIMIT 1", OBJECT );
      $pOrderId = $resultsOr[0]->post_id;
      
    //   $resultsOrSub = $wpdb->get_results( "SELECT * FROM `wp_postmeta` WHERE `meta_key` LIKE '_customer_user' AND meta_value = '".$user_id."' ORDER BY post_id ASC LIMIT 1,1", OBJECT );
    //   $pSubOrderId = $resultsOrSub[0]->post_id;
      
      
      $results = $wpdb->get_results( "SELECT * FROM `wp_postmeta` WHERE post_id = '".$pOrderId."' AND meta_key = '_createLeadResponse'", OBJECT );
      foreach ($results as $key => $value) {
        $meta_value = $value->meta_value;
      }
      
      $meta_value = json_decode($meta_value);
      $contactId  = get_user_meta( $user_id, '_contactId', true );
      $leadId     = get_user_meta( $user_id, '_leadId', true );
      $subscription_products = $wpOrder->get_items();
      $subscription = [];
      $lines = [];
      $line = [];
      if ( sizeof( $subscription_items = $wpOrder->get_items() ) > 0 ) {
          foreach ( $subscription_items as $item_id => $item ) {
            $product = $item->get_product();
            $product_id = $product->get_id();
            $product_name = $product->get_title();
            $get_period = WC_Subscriptions_Product::get_period( $product_id );
            $price = WC_Subscriptions_Product::get_price( $product_id );
            
            // 18-10-2020
            // get Next Payment Date
                // if($getSubscriptionId) {
                    // sleep(5);
                    // $nextPaymentDate = get_post_meta( $getSubscriptionId, '_schedule_next_payment' );
                    if(is_null($nextPaymentDate)) {
                        $nextPaymentDate = NULL;
                    } else {
                        $nextPaymentDate  =  $nextPaymentDate;    
                    }
                    
                    
                // } else {
                //     $nextPaymentDate = NULL;
                // }
                
            // 18-10-2020
            
            if($product_id              == '718') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'BANKPASS';
              
	    	  $subscription['endDate'] = $nextPaymentDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            }
            if($item['product_id'     ] == '695') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'DISCOVER-BANKPASS';
              
	    	  $subscription['endDate'] = $nextPaymentDate;
            
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            }
            if($item['product_id'     ] == '69026') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'DISCOVER-BANKPASS';
              
	    	  $subscription['endDate'] = $nextPaymentDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            } 
            if($item['product_id'     ] == '69028') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'DISCOVER-BANKPASS';
              
	    	  $subscription['endDate'] = $nextPaymentDate;
              
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            } 
            if($item['product_id'     ] == '12988') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'EXPLORE-BANKPASS';
              $vaultSubscriptionActive = true;
	    	  $subscription['endDate'] = $nextPaymentDate;
              $subscription['amount'  ] = 59;
              array_push($subscriptions, $subscription);
              $subscription1 = [];
              $subscription1['code'   ] = 'BANKVAULT';
              $subscription1['name'   ] = 'EXPLORE-BANKVAULT';
	    	  $subscription1['endDate'] = $nextPaymentDate;
              $subscription1['amount' ] = 40;
              array_push($subscriptions, $subscription1); 
            }
            if($item['product_id'     ] == '52330') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'EXPLORE-BANKPASS';
              
	    	  $subscription['endDate'] = $nextPaymentDate;
              $subscription['amount'  ] = 59;
              array_push($subscriptions, $subscription);
              $subscription1 = [];
              $subscription1['code'   ] = 'BANKVAULT';
              $subscription1['name'   ] = 'EXPLORE-BANKVAULT';
              $vaultSubscriptionActive = true;
	    	  $subscription['endDate'] = $nextPaymentDate;
              $subscription1['amount' ] = 40;
              array_push($subscriptions, $subscription1); 
            }
            if($item['product_id'     ] == '18309') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'BANKPASS';
              
	    	  $subscription['endDate'] = $nextPaymentDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            } 
            if($item['product_id'     ] == '10442') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'BANKPASS';
              
	    	  $subscription['endDate'] = $nextPaymentDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            }
            if($item['product_id'     ] == '111824') {
              $subscription['code'    ] = 'Connect';
              $subscription['name'    ] = 'Connect';
              
	    	  $subscription['endDate'] = $nextPaymentDate;  
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            }
            if($item['product_id'     ] == '3687') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'BANKPASS';
              
	    	  $subscription['endDate'] = $nextPaymentDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            }
            if($item['product_id'     ] == '8367') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'BANKPASS';
              
	    	  $subscription['endDate'] = $nextPaymentDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            }
            if($item['product_id'     ] == '8362') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'BANKPASS';
              
	    	  $subscription['endDate'] = $nextPaymentDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            }
            if($item['product_id'     ] == '8367') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'BANKPASS';
              
	    	  $subscription['endDate'] = $nextPaymentDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            }
            if($item['product_id'     ] == '3809') {
              $subscription['code'    ] = 'Affiliate';
              $subscription['name'    ] = 'Affiliate';
              
	    	  $subscription['endDate'] = $nextPaymentDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);  
            } 
            if($item['product_id'     ] == '546') {
              $subscription['code'    ] = 'BANKVAULT';
              $subscription['name'    ] = 'BANKVAULT';
              $subscription['amount'  ] = $item['line_total'];
              $vaultSubscriptionActive = true;
	    	  $subscription['endDate'] = $nextPaymentDate;
                array_push($subscriptions, $subscription);  
            }
            if($item['product_id'     ] == '399') {
              $subscription['code'    ] = 'WTB eBook';
              $subscription['name'    ] = 'WTB eBook';
              $subscription['amount'  ] = $item['line_total'];
              
	    	  $subscription['endDate'] = $nextPaymentDate;
                array_push($subscriptions, $subscription);  
            }
            $product_rp = wc_get_product( $item['product_id'] );
	        $line_t = $product_rp->get_regular_price();
	        // calculate commissionable value
	    $item_total = $wpOrder->get_item_meta($item_id, '_line_total', true);
	    $item_sub_total = $wpOrder->get_item_meta($item_id, '_line_subtotal', true);
	    $item_total_check = (int) $item_total;
	    $commissionableAmount = 0;
	   
	     $exclusiveProductIds = array(406, 407, 408, 536, 539);
	     
	     $productIdCheck = false;
	     foreach($exclusiveProductIds as $val) {
	         
	         if($val == $item['product_id']) {
	             
	             $productIdCheck = true;
	             
	         }
	         
	     }
	     if(!$productIdCheck) {
	         
	         if($item_total_check != 0) {
	                 
	                 $whole = floor($item_total);
                     $lastDigit = substr($whole,-1);
                     
                     if($lastDigit == 4 || $lastDigit == 9) {
                         $commissionableAmount = $whole + 1;
                         
                     } else {
                         $item_total = $item_total;
                     }
	                 
	             }
	         
	     }
	     
	     
	     
	    if(!$get_period) {
                   $get_period  = "Piece";    
                }
                
            
        $line['unitId'     ] = $get_period; 
        $line['productCode'] = $item['product_id'];
	    $line['description'] = $item['name'];
	    $line['commissionableAmount'] = $commissionableAmount;
	   // $line['rate'] = $line_t;
	    $line['rate'] = $item_sub_total;
	    $line['quantity'] = $item['quantity'];
	    $line['sortOrder'] = 1;
	   // $line['total'] = $line_t * $line['quantity'];
	   $line['total'] = $item_sub_total * $line['quantity'];

        

	    

	    
	    array_push($lines, $line);
            
          }
      }
      $object_bill_addr = new stdClass();
      $object_bill_addr->countryId = $order_data['billing']['country'];
      if($order_data['billing']['country'] == "US" || $order_data['billing']['country'] == "CA") {
        $object_bill_addr->stateId   = $order_data['billing']['state']; 
      } else {
        $object_bill_addr->stateName = $order_data['billing']['state'];
      }
      $object_bill_addr->city        = $order_data['billing']['city'];
      $object_bill_addr->zip         = $order_data['billing']['postcode'];
      $object_bill_addr->address1    = $order_data['billing']['address_1'];
      $object_bill_addr->address2    = $order_data['billing']['address_2'];
      $object_bill_addr->firstName   = $order_data['billing']['first_name'];
      $object_bill_addr->lastName    = $order_data['billing']['last_name'];
      $object_bill_addr->email       = $order_data['billing']['email'];
      $object_bill_addr->phone       = $order_data['billing']['phone'];
      $object_shipp_add = new stdClass();
      $object_shipp_add->countryId   = $order_data['billing']['country'];
      if($order_data['billing']['country'] == "US" || $order_data['billing']['country'] == 'CA') {
        $object_shipp_add->stateId   = $order_data['billing']['state']; 
      } else {
        $object_shipp_add->stateName = $order_data['billing']['state'];
      }
      $object_shipp_add->city        = $order_data['billing']['city'];
      $object_shipp_add->zip         = $order_data['billing']['postcode'];
      $object_shipp_add->address1    = $order_data['billing']['address_1'];
      $object_shipp_add->address2    = $order_data['billing']['address_2'];
      $object_shipp_add->firstName   = $order_data['billing']['first_name'];
      $object_shipp_add->lastName    = $order_data['billing']['last_name'];
      //   $object_shipp_add = json_encode($object_shipp_add);
      //   add tax total
            $total_tax_amount = $wpOrder->get_total_tax();
            
            if(!$total_tax_amount) {
                $total_tax_amount = null;
            }
            
            // add coupons amount
            $order_discount_amount = null;
            $coupon_items = $wpOrder->get_items('coupon');
            foreach( $coupon_items as $item_id => $item ){
            //   echo "coupons discount: ".$item_id."<br>";
                $getOrder_discount_amount = wc_get_order_item_meta( $item_id, 'discount_amount', true );
                if($getOrder_discount_amount) {
                    $order_discount_amount += $getOrder_discount_amount;
                }
            }
            
            // add shipping cost
            $order_shipping_cost = null;
            foreach( $wpOrder->get_items( 'shipping' ) as $item_id => $shipping_item_obj ){
                $getOrder_shipping_cost = wc_get_order_item_meta( $item_id, 'cost', true );
                $getOrder_shipping_cost_check = (int) $getOrder_shipping_cost;
                if($getOrder_shipping_cost_check) {
                   $order_shipping_cost  += $getOrder_shipping_cost;
                }
            }
            
    

      $getOrderCreatedDate = $wpdb->get_results( "SELECT post_date FROM `wp_posts` WHERE ID = '".$orderId."'", OBJECT );
      $OrderCreatedDate = $getOrderCreatedDate[0]->post_date;
      // Calling Create Invoice API
      $createInvoiceJson = array(
        "leadId"=>$leadId,
        "contactId"=>$contactId,
        "systemType"=>"BANKCODE",
        "orderId"=>"",
        "orderNumber"=>$orderId,
        "status"=>"Sent",
        "number"=>$orderId,
        "date"=>$OrderCreatedDate,
        "dueDate"=>$OrderCreatedDate,
        "discountTotal"=> $order_discount_amount,
        "shippingTotal"=> $order_shipping_cost,
        "taxTotal"    => $total_tax_amount,
        "grandTotal"=>$wpOrder->get_total(),
        "billingAddress"=>$object_bill_addr,
        "shippingAddress"=>$object_shipp_add,
        "description"=> "Codebreaker Order #".$orderId,
        "lines"=>$lines,
        "bypassValidation" => true
      );
      $createInvoiceJson = json_encode($createInvoiceJson);
      $curl = curl_init();
      curl_setopt_array($curl, array(
      CURLOPT_URL => $CREATEINVOICE,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => $createInvoiceJson,
      CURLOPT_HTTPHEADER => array(
          "Content-Type: application/json",
          "Postman-Token: f89ab21d-2c31-445f-80e6-9fa4b45e66c3",
          "api-key: ".$apiKey,
          "cache-control: no-cache,no-cache"
      ) ,
      ));
      $response = curl_exec($curl);
      $err = curl_error($curl);
      curl_close($curl);
    ## CHECK IF THERE IS ERRORS IN API THEN LOG TO DATABASE TABLE NAMED POST META
    $createInvoiceRequest = $createInvoiceJson;
    if ($err)
    {   // echo "cURL Error #:" . $err;
        $wpOrder->update_meta_data('createInvoiceRequestRenewal', $createInvoiceRequest);
        $wpOrder->update_meta_data('_createInvoiceResponseRenewal', $err);
      $wpOrder->save();
    }
    else
    {
      $wpOrder->update_meta_data('createInvoiceRequestRenewal', $createInvoiceRequest);
      $wpOrder->update_meta_data('_createInvoiceResponseRenewal', $response);
      $wpOrder->save();
      // echo $response;
      ## CHANGED STATUS FROM DRAFT TO PAID USING AddBankCardPayment API.
      $results = json_decode($response);
      $invoiceId = $results->result;
      $responsStatus = $results->success;
      if($responsStatus) {
          
          $transactionId       = get_post_meta( $orderId, '_transaction_id' ,true );
          $authorizationCode   = get_post_meta( $orderId, '_wc_authorize_net_cim_credit_card_authorization_code' ,true );
          $transactionDate  =  get_post_meta( $orderId, '_paid_date' ,true );
          
        $addBankCardPaymentJson = array(
          "invoiceId"   =>$invoiceId,
          "date"        =>$transactionDate,
          "description" =>"Codebreaker Order #".$orderId,
          "amount"      =>$wpOrder->get_total(),
          "gatewayTransactionId" => $transactionId,
          "authorizationCode" => $authorizationCode,
          "gatewayName" =>"Authorize.net",
          "bankCardInfo"=>array(
            "holderName"         =>$order_data['billing']['first_name']." ".$order_data['billing']['last_name'],
            "cardNumber"         =>"4444444444444444",
            "expirationMonth"    =>"10",
            "expirationYear"     =>"2070",
            "billingAddress"     =>$order_data['billing']['address_1']." ".$order_data['billing']['address_2'],
            "billingZip"         =>$order_data['billing']['postcode'],
            "billingCity"        =>$order_data['billing']['city'],
            "billingStateCode"   =>$order_data['billing']['state'],
            "billingCountryCode" =>$order_data['billing']['country']
          )
        );
      $addBankCardPaymentJson = json_encode($addBankCardPaymentJson);
      $curl = curl_init();
      curl_setopt_array($curl, array(
        CURLOPT_URL => $ADDBANKCARDPAYMENT,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $addBankCardPaymentJson,
        CURLOPT_HTTPHEADER => array(
          "Content-Type: application/json",
          "Postman-Token: 10346306-aae0-4d03-be44-a1ca4d4e292c",
          "api-key: ".$apiKey,
          "cache-control: no-cache,no-cache"
        ),
      ));
      $response = curl_exec($curl);
      $err = curl_error($curl);
      curl_close($curl);
      $addBankCardPaymentRequest = $addBankCardPaymentJson;
      if ($err) {
        // echo "cURL Error #:" . $err;
        $wpOrder->update_meta_data('addBankCardPaymentRequestRenewal', $addBankCardPaymentRequest);
        $wpOrder->update_meta_data('_addBankCardPaymentResponseRenewal', $err);
            $wpOrder->save();
      } else {
        // echo $response;
        $wpOrder->update_meta_data('addBankCardPaymentRequestRenewal', $addBankCardPaymentRequest);
        $wpOrder->update_meta_data('_addBankCardPaymentResponseRenewal', $response);
            $wpOrder->save();
        }
       }
      }
      $orderSubscriptionJson = array(
        "contactId"=>$contactId,
        "orderNumber"=>$orderId,
        "systemType"=>"BANKCODE",
        "subscriptions"=>$subscriptions,
        "updateThirdParty"=>$vaultSubscriptionActive
      );
      $orderSubscriptionJson = json_encode($orderSubscriptionJson);
      $curl = curl_init();
      curl_setopt_array($curl, array(
      CURLOPT_URL => $OrderSubscription,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "PUT",
      CURLOPT_POSTFIELDS => $orderSubscriptionJson,
      CURLOPT_HTTPHEADER => array(
          "Content-Type: application/json",
          "Postman-Token: f89ab21d-2c31-445f-80e6-9fa4b45e66c3",
          "api-key: ".$apiKey,
          "cache-control: no-cache,no-cache"
      ) ,
      ));
      $response = curl_exec($curl);
      $err = curl_error($curl);
      curl_close($curl);

      ## CHECK IF THERE IS ERRORS IN API THEN LOG TO DATABASE TABLE NAMED POST META
      $orderSubscriptionRequest = $orderSubscriptionJson;
      if ($err)
      {
          // echo "cURL Error #:" . $err;
          $wpOrder->update_meta_data('orderSubscriptionRequestRenewal', $orderSubscriptionRequest);
          $wpOrder->update_meta_data('_orderSubscriptionResponseRenewal', $err);
        $wpOrder->save();
      }
      else
      {
        $wpOrder->update_meta_data('orderSubscriptionRequestRenewal', $orderSubscriptionRequest);
        $wpOrder->update_meta_data('_orderSubscriptionResponseRenewal', $response);
        $wpOrder->save();
      }
}

function updateSubOnCRM($orderId) {
    
   
    $SAVEREMOTEORDER      = SAVEREMOTEORDER;
    $CREATELEAD           = CREATECONTACT;
    $apiKey               = APIKEY;
    $CreateUserForContact = CreateUserForContact;
    $CREATEINVOICE        = CREATEINVOICE;
    $affiliateProduct     = affiliateProduct;
    $ADDBANKCARDPAYMENT   = ADDBANKCARDPAYMENT;
    $OrderSubscription    = OrderSubscription;
    $meta_value;
    $subscriptions = [];
    // $wpOrder = new WC_Subscription( $subscription_id );
    // $order_id = method_exists( $wpOrder, 'get_parent_id' ) ? $wpOrder->get_parent_id() : $wpOrder->order->id;  
    // $orderId = $order_id;
    // $orderId = $subscription_id;
    // $order = method_exists( $wpOrder, 'get_parent' ) ? $wpOrder->get_parent() : $wpOrder->order;
    // $order_data = $order->get_data();
    $price; 
    $get_period;
    $product_name;
    $wpOrder = wc_get_order( $orderId );
    // $wpOrder->update_meta_data('_orderSubscriptionResponseRenewalExtended', 112210);
    // $wpOrder->save();
    $user_id   = $wpOrder->get_user_id();
    $order_data = $wpOrder->get_data();
    $user_id   = $wpOrder->get_user_id();
      global $wpdb;
      
      $resultsOr = $wpdb->get_results( "SELECT * FROM `wp_postmeta` WHERE `meta_key` LIKE '_customer_user' AND meta_value = '".$user_id."' ORDER BY post_id ASC LIMIT 1", OBJECT );
      $pOrderId = $resultsOr[0]->post_id;
      
      
      
      $results = $wpdb->get_results( "SELECT * FROM `wp_postmeta` WHERE post_id = '".$pOrderId."' AND meta_key = '_createLeadResponse'", OBJECT );
      foreach ($results as $key => $value) {
        $meta_value = $value->meta_value;
      }
      
      $meta_value = json_decode($meta_value);
      $contactId  = get_user_meta( $user_id, '_contactId', true );
      $leadId     = get_user_meta( $user_id, '_leadId', true );
      $subscription_products = $wpOrder->get_items();
      $subscription = [];
      $lines = [];
      $line = [];
      if ( sizeof( $subscription_items = $wpOrder->get_items() ) > 0 ) {
          foreach ( $subscription_items as $item_id => $item ) {
            $product = $item->get_product();
            $product_id = $product->get_id();
            $product_name = $product->get_title();
            $get_period = WC_Subscriptions_Product::get_period( $product_id );
            $price = WC_Subscriptions_Product::get_price( $product_id );
            if($product_id              == '718') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'BANKPASS';
              $startDate = date("Y-m-d H:i:s"); 
              $endDate = date('Y-m-d', strtotime($startDate. ' + 5 days'));
              $subscription['endDate' ] = $endDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            }
            if($item['product_id'     ] == '695') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'DISCOVER-BANKPASS';
              $startDate = date("Y-m-d H:i:s"); 
              $endDate = date('Y-m-d', strtotime($startDate. ' + 5 days'));
              $subscription['endDate' ] = $endDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            }
            if($item['product_id'     ] == '69026') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'DISCOVER-BANKPASS';
              $startDate = date("Y-m-d H:i:s"); 
              $endDate = date('Y-m-d', strtotime($startDate. ' + 5 days'));
              $subscription['endDate' ] = $endDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            } 
            if($item['product_id'     ] == '69028') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'DISCOVER-BANKPASS';
              $startDate = date("Y-m-d H:i:s"); 
              $endDate = date('Y-m-d', strtotime($startDate. ' + 5 days'));
              $subscription['endDate' ] = $endDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            } 
            if($item['product_id'     ] == '12988') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'EXPLORE-BANKPASS';
              $startDate = date("Y-m-d H:i:s"); 
              $endDate = date('Y-m-d', strtotime($startDate. ' + 5 days'));
              $subscription['endDate' ] = $endDate;
              $subscription['amount'  ] = 59;
              array_push($subscriptions, $subscription);
              $subscription1 = [];
              $subscription1['code'   ] = 'BANKVAULT';
              $subscription1['name'   ] = 'EXPLORE-BANKVAULT';
              $subscription1['endDate'] = $endDate;
              $subscription1['amount' ] = 40;
              array_push($subscriptions, $subscription1); 
            }
            if($item['product_id'     ] == '52330') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'EXPLORE-BANKPASS';
              $startDate = date("Y-m-d H:i:s"); 
              $endDate = date('Y-m-d', strtotime($startDate. ' + 5 days'));
              $subscription['endDate' ] = $endDate;
              $subscription['amount'  ] = 59;
              array_push($subscriptions, $subscription);
              $subscription1 = [];
              $subscription1['code'   ] = 'BANKVAULT';
              $subscription1['name'   ] = 'EXPLORE-BANKVAULT';
              $subscription1['endDate'] = $endDate;
              $subscription1['amount' ] = 40;
              array_push($subscriptions, $subscription1); 
            }
            if($item['product_id'     ] == '18309') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'BANKPASS';
              $startDate = date("Y-m-d H:i:s"); 
              $endDate = date('Y-m-d', strtotime($startDate. ' + 5 days'));
              $subscription['endDate' ] = $endDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            } 
            if($item['product_id'     ] == '10442') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'BANKPASS';
              $startDate = date("Y-m-d H:i:s"); 
              $endDate = date('Y-m-d', strtotime($startDate. ' + 5 days'));
              $subscription['endDate' ] = $endDate;         
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            }
            if($item['product_id'     ] == '111824') {
              $subscription['code'    ] = 'Connect';
              $subscription['name'    ] = 'Connect';
              $startDate = date("Y-m-d H:i:s"); 
              $endDate = date('Y-m-d', strtotime($startDate. ' + 5 days'));
              $subscription['endDate' ] = $endDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            }
            if($item['product_id'     ] == '3687') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'BANKPASS';
              $startDate = date("Y-m-d H:i:s"); 
              $endDate = date('Y-m-d', strtotime($startDate. ' + 5 days'));
              $subscription['endDate' ] = $endDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            }
            if($item['product_id'     ] == '8367') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'BANKPASS';
              $startDate = date("Y-m-d H:i:s"); 
              $endDate = date('Y-m-d', strtotime($startDate. ' + 5 days'));
              $subscription['endDate' ] = $endDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            }
            if($item['product_id'     ] == '8362') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'BANKPASS';
              $startDate = date("Y-m-d H:i:s"); 
              $endDate = date('Y-m-d', strtotime($startDate. ' + 5 days'));
              $subscription['endDate' ] = $endDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            }
            if($item['product_id'     ] == '8367') {
              $subscription['code'    ] = 'BANKPASS';
              $subscription['name'    ] = 'BANKPASS';
              $startDate = date("Y-m-d H:i:s"); 
              $endDate = date('Y-m-d', strtotime($startDate. ' + 5 days'));
              $subscription['endDate' ] = $endDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);
            }
            if($item['product_id'     ] == '3809') {
              $subscription['code'    ] = 'Affiliate';
              $subscription['name'    ] = 'Affiliate';
              $startDate = date("Y-m-d H:i:s"); 
              $endDate = date('Y-m-d', strtotime($startDate. ' + 5 days'));
              $subscription['endDate' ] = $endDate;
              $subscription['amount'  ] = $price;
              array_push($subscriptions, $subscription);  
            } 
            if($item['product_id'     ] == '546') {
              $subscription['code'    ] = 'BANKVAULT';
              $subscription['name'    ] = 'BANKVAULT';
              $subscription['amount'  ] = $item['line_total'];
              $startDate = date("Y-m-d H:i:s"); 
              $endDate = date('Y-m-d', strtotime($startDate. ' + 5 days'));
              $subscription['endDate' ] = $endDate;
                array_push($subscriptions, $subscription);  
            }
            if($item['product_id'     ] == '399') {
              $subscription['code'    ] = 'WTB eBook';
              $subscription['name'    ] = 'WTB eBook';
              $subscription['amount'  ] = $item['line_total'];
              $startDate = date("Y-m-d H:i:s"); 
              $endDate = date('Y-m-d', strtotime($startDate. ' + 5 days'));
              $subscription['endDate' ] = $endDate;
                array_push($subscriptions, $subscription);  
            }
          }
      }
      
      
      $orderSubscriptionJson = array(
        "contactId"=>$contactId,
        "orderNumber"=>$orderId,
        "systemType"=>"BANKCODE",
        "subscriptions"=>$subscriptions
      );
      $orderSubscriptionJson = json_encode($orderSubscriptionJson);
      $curl = curl_init();
      curl_setopt_array($curl, array(
      CURLOPT_URL => $OrderSubscription,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "PUT",
      CURLOPT_POSTFIELDS => $orderSubscriptionJson,
      CURLOPT_HTTPHEADER => array(
          "Content-Type: application/json",
          "Postman-Token: f89ab21d-2c31-445f-80e6-9fa4b45e66c3",
          "api-key: ".$apiKey,
          "cache-control: no-cache,no-cache"
      ) ,
      ));
      $response = curl_exec($curl);
      $err = curl_error($curl);
      curl_close($curl);

      ## CHECK IF THERE IS ERRORS IN API THEN LOG TO DATABASE TABLE NAMED POST META
      $orderSubscriptionRequest = $orderSubscriptionJson;
      if ($err)
      {
          // echo "cURL Error #:" . $err;
          $wpOrder->update_meta_data('orderSubscriptionRequestRenewalExtended', $orderSubscriptionRequest);
          $wpOrder->update_meta_data('_orderSubscriptionResponseRenewalExtended', $err);
          $wpOrder->save();
      }
      else
      {
        $wpOrder->update_meta_data('orderSubscriptionRequestRenewalExtended', $orderSubscriptionRequest);
        $wpOrder->update_meta_data('_orderSubscriptionResponseRenewalExtended', $response);
        $wpOrder->save();
      }
    
    
}

 ## FUNCTION CALLS WHEN SUBMIT THE BANKPASS FORM. (gform_after_submission_4)
function set_post_content_to_Sperse_and_http_post( $entry, $form ) {
    global $CREATELEAD;
    global $apiKey;
    global $saveremotecodecrack;
    $referrerUrl = '';
    // $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    if(isset($_COOKIE['_referringURL'])) {
      $referrerUrl = urldecode($_COOKIE['_referringURL']);
    }
    if(isset($_COOKIE['_entryUrl'])) {
      $actual_link = urldecode($_COOKIE['_entryUrl']);
    } else {
        $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    }
    /* ----------------------------------------- 
    WORDPRESS to SPERSE(CRM)
   ----------------------------------------- */
    $firstName = rgar( $entry, '1' );
    $lastName  = rgar( $entry, '9' );
    $country   = rgar( $entry, '5' );
    $email     = rgar( $entry, '2' );
    $industry  = rgar( $entry, '7' );
    // if(isset($_REQUEST['input_5_3_hidden'])) {
    // if($_REQUEST['input_5_3_hidden'] == "valid") {
    // $phoneNumber = $_REQUEST['input_5_3_hidden_value'];
    // } else {
    // $phoneNumber = rgar( $entry, '45' );    
    // }
    // } else {
    $phoneNumber = rgar( $entry, '6' );  
    // }
    $ip = getUserIpAddr();
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => $CREATELEAD,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => "{\n\t \"firstName\": \"".$firstName."\",\n\t \"lastName\": \"".$lastName."\",\n\t\t \"trackingInfo\": {\n\t    \"channelCode\": \"WP\",\n\t    \"refererUrl\": \"".$referrerUrl."\",\n\t    \"entryUrl\": \"".$actual_link."\",\n\t    \"userAgent\": \"".$_SERVER['HTTP_USER_AGENT']."\",\n\t    \"clientIp\": \"".$ip."\"\n\t\t},\n\t \"phoneNumbers\": [{\n                    \"phoneNumber\": \"".$phoneNumber."\",\n                    \"phoneExtension\": \"\", \n                    \"isActive\": true,\n                    \"usageTypeId\": \"M\"\n                }],\n      \"emailAddresses\": [{\n            \"emailAddress\": \"".$email."\",\n            \"isActive\": true,\n            \"usageTypeId\": \"P\"\n        }],          \n     \"industry\": \"".$industry."\",\n\t \"contactGroupId\": \"C\",\n\t \"matchExisting\": \"true\",\n\t \"matchByEmail\": true\n}",
      CURLOPT_HTTPHEADER => array(
        "Content-Type: application/json",
        "api-key: ".$apiKey,
        "cache-control: no-cache,no-cache"
      ),
    ));
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) {
      // echo "cURL Error #:" . $err;
        gform_update_meta( $entry['id'], 'wp_to_crm', "Error :" . $err );
    } else {
        gform_update_meta( $entry['id'], 'wp_to_crm', $response );
    }

    /* ----------------------------------------- 
        WORDPRESS to HTTP POST
       ----------------------------------------- */
      $curl = curl_init();
      curl_setopt_array($curl, array(
        CURLOPT_URL => $saveremotecodecrack,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "source=bankcode&accesscode=noAccessCode&bankcode=BANK&fname=".$firstName."&lname=".$lastName."&email=".$email."&phone=".$phoneNumber."&country=".$country."&occupation=".$industry."&ipaddress=".$ip."&undefined=",
        CURLOPT_HTTPHEADER => array(
          "Content-Type: application/x-www-form-urlencoded",
          "cache-control: no-cache,no-cache"
        ),
      ));
      $response = curl_exec($curl);
      $err = curl_error($curl);
      curl_close($curl);
      if ($err) {
        gform_update_meta( $entry['id'], 'wp_to_http_post', "Error :" . $err );
      } else {
        gform_update_meta( $entry['id'], 'wp_to_http_post', $response);
      }
}

## FUNCTION CALLS WHEN SUBMIT THE START-NOW FORM. (gform_after_submission_5)
function set_post_content_to_Sperse_and_http_post_5($entry, $form) {
  global $CREATELEAD;
  global $apiKey;
  global $saveremotecodecrack;
  $referrerUrl = '';
  $access_code = '';
  $affiliateCode = '';
//   $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  if(isset($_COOKIE['_referringURL'])) {
      $referrerUrl = urldecode($_COOKIE['_referringURL']);
    }
    if(isset($_COOKIE['_entryUrl'])) {
      $actual_link = urldecode($_COOKIE['_entryUrl']);
    } else {
        $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    }
    ## GET AFFILIATE ID FROM COOKIES IF EXISTS
    if(isset($_COOKIE['affwp_ref'])) {
      global $wpdb;
      $aff_id = $_COOKIE['affwp_ref'];     
      $results = $wpdb->get_results( "SELECT * FROM wp_affiliate_wp_affiliates WHERE affiliate_id = '".$aff_id."'", OBJECT );
      foreach ($results as $key => $value) {
        $user_id = $value->user_id;
        $user_email = $value->payment_email;
        $data['user_email'] = $user_email;
      }
      $user_info = get_userdata($user_id);
      $access_code = $user_info->user_login;
    }
    if(empty($access_code)) {
    $affiliateCode = '';
    $access_code = 'noAccessCode';
    } else {
      $affiliateCode = $access_code;
      $access_code = $access_code;
    }
    $trackingInformation = new stdClass();
    $trackingInformation->affiliateCode = $affiliateCode;
    $trackingInformation->referringUrl  = $referrerUrl;
    $trackingInformation->entryUrl      = $_SERVER['HTTP_REFERER'];
    $trackingInformation->userAgent     = $_SERVER['HTTP_USER_AGENT'];
    $trackingInformation->ipAddress     = getUserIpAddr();
    $trackingInformation = json_encode($trackingInformation);

  /* ----------------------------------------- 
    WORDPRESS to SPERSE(CRM)
   ----------------------------------------- */
  if(isset($_REQUEST['input_5_3_hidden'])) {
      if($_REQUEST['input_5_3_hidden'] == "valid") {
        $phoneNumber = $_REQUEST['input_5_3_hidden_value'];
      } else {
        $phoneNumber = rgar( $entry, '3' );    
      }
    } else {
      $phoneNumber = rgar( $entry, '3' );  
    }
  $firstName = rgar( $entry, '1' );
  $email = rgar( $entry, '2' );
  $phoneNumber = rgar( $entry, '3' );
  $bankcode = 'BANK';
  // $trackingInformation = {};
  $ip = getUserIpAddr();
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => $CREATELEAD,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "{\n\t\"firstName\": \"".$firstName."\",\n\t\"trackingInfo\": {\n    \"affiliateCode\": \"".$affiliateCode."\",\n\t    \"channelCode\": \"WP\",\n    \"refererUrl\": \"".$referrerUrl."\",\n    \"entryUrl\": \"".$actual_link."\",\n    \"userAgent\": \"".$_SERVER['HTTP_USER_AGENT']."\",\n    \"clientIp\": \"".$ip."\"\n\t},\n\t \"phoneNumbers\": [{\n                    \"phoneNumber\": \"".$phoneNumber."\",\n                    \"phoneExtension\": \"\", \n                    \"isActive\": true,\n                    \"usageTypeId\": \"M\"\n                }], \n\t \"emailAddresses\": [{\n            \"emailAddress\": \"".$email."\",\n            \"isActive\": true,\n            \"usageTypeId\": \"P\"\n        }],\n\t \"contactGroupId\": \"C\",\n\t \"matchExisting\": \"true\",\n\t \"bypassValidation\": \"true\",\n\t \"matchByEmail\": true\n}",
    CURLOPT_HTTPHEADER => array(
      "Content-Type: application/json",
      "Postman-Token: f0a741fe-af60-4b6e-bde5-a29a3e0124a1",
      "api-key: ".$apiKey,
      "cache-control: no-cache,no-cache"
    ),
  ));

  $response = curl_exec($curl);
  $err = curl_error($curl);
  curl_close($curl);
  if ($err) {
    // echo "cURL Error #:" . $err;
    gform_update_meta( $entry['id'], 'wp_to_crm', "Error :" . $err );
  } else {
    // echo $response;
    gform_update_meta( $entry['id'], 'wp_to_crm', $response );
  }
  /* ----------------------------------------- 
        WORDPRESS to HTTP POST
  ----------------------------------------- */
    $curl = curl_init();
    curl_setopt_array($curl, array(
    CURLOPT_URL => $saveremotecodecrack,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "source=bankcode&accesscode=".$access_code."&bankcode=".$bankcode."&fname=".$firstName."&email=".$email."&phone=".$phoneNumber."&ipaddress=".$ip."&undefined=",
    CURLOPT_HTTPHEADER => array(
      "Content-Type: application/x-www-form-urlencoded",
      "cache-control: no-cache,no-cache"
     ),
    ));
// 
      $response = curl_exec($curl);
      $err = curl_error($curl);
      curl_close($curl);
      if ($err) {
        gform_update_meta( $entry['id'], 'wp_to_http_post', "Error :" . $err );
      } else {
        gform_update_meta( $entry['id'], 'wp_to_http_post', $response);
      }
}

function sendEmailToSale($firstName,$email, $cFirstName, $cLastName, $bankCode, $lng, $user_login, $templateId, $pPhoneNumber,$pEmailAddress){
//   if(strtoupper($user_login) == strtoupper("SuccessFactory")) {
//     // $pdfReportLink = "https://www.codebreakertech.com/reports/SF/".$lng."/Sales/".$bankCode."-SALES-REPORT.pdf";
//     sendGridEmailSales($firstName,$cFirstName, $cLastName, $bankCode,$email, $templateId, $lng, "SF");
//   } else {
//     sendGridEmailSales($firstName,$cFirstName, $cLastName, $bankCode,$email, $templateId, $lng, "SF");
//     // $pdfReportLink = "http://www.codebreakertech.com/reports/".$lng."/sales/".$bankCode."-SALES-REPORT.pdf";
//   }

if(!isset($_GET['partner'])) {
} else {
    $refURL = $_GET['partner'];
    if ($refURL == "SF") {
        sendGridEmailSales($firstName,$cFirstName, $cLastName, $bankCode,$email, $templateId, $lng, "SF", $pPhoneNumber,$pEmailAddress, $user_login);
    } else {
        sendGridEmailSales($firstName,$cFirstName, $cLastName, $bankCode,$email, $templateId, $lng, "CB", $pPhoneNumber,$pEmailAddress, $user_login);
    }
  }
}

function sendGridEmailProspects($firstName, $lastName, $bankCode,$email, $templateId, $lang, $partner, $refAffiliateCode) {
    global $partnerCheck;
    // $email = "ahmad@sperse.com";
    $body = "Hey";
    $subject = "Your requested BANKCODE revealed";
    $headers = array(
        'Authorization: Bearer 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',
        'Content-Type: application/json'
    );
    $data = array(
        "personalizations" => array(
            array(
                "to" => array(
                    array(
                        "email" => $email,
                        "name" => $firstName,
                    )
                ),
                "dynamic_template_data" => array(
                    "first_name" => $firstName,
                    "last_name" => $lastName,
                    "bankCode" => $bankCode,
                    "language" => $lang,
                    "partner" => $partner,
                    "refAffiliateCode" => $refAffiliateCode,
                    "eto" => $email
                ),
            )
        ),
        "from" => array(
            "email" => "no-reply@codebreakertech.com",
            "name" => "Codebreaker Technologies Inc",
        ),
        "subject" => $subject,
        "content" => array(
            array(
                "type" => "text/html",
                "value" => $body
            )
        ),
        "template_id"=> $templateId,
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.sendgrid.com/v3/mail/send");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    curl_close($ch);
    // echo $response;
}

function registrantEmailtoAffiliate($sFirstName, $sEmailAddress,$firstName, $lastName, $access_code, $pPhoneNumber, $pEmailAddress) {
    $body = "Hey";
    $subject = "Your requested BANKCODE revealed";
    $headers = array(
        'Authorization: Bearer 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',
        'Content-Type: application/json'
    );
    $data = array(
        "personalizations" => array(
            array(
                "to" => array(
                    array(
                        "email" => $sEmailAddress,
                        "name" => $sFirstName,
                    )
                ),
                "dynamic_template_data" => array(
                "sFirstName" => $sFirstName,
                "first_name" => $firstName,
                "last_name" => $lastName,
                "refAffiliateCode" => $access_code,
                "pPhoneNumber" => $pPhoneNumber,
                "prospectEmailAddress" => $pEmailAddress
                ),
            )
        ),
        "from" => array(
            "email" => "no-reply@codebreakertech.com",
            "name" => "Codebreaker Technologies Inc",
        ),
        "subject" => $subject,
        "content" => array(
            array(
                "type" => "text/html",
                "value" => $body
            )
        ),
        "template_id"=> 'd-78e866b454fd49d3ab1cbb1881b61c2b',
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.sendgrid.com/v3/mail/send");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    curl_close($ch);
}

function registrantConfirmationEmail($firstName, $lastName, $email, $access_code) {
    $body = "Hey";
    $subject = "Your requested BANKCODE revealed";
    $headers = array(
        'Authorization: Bearer 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',
        'Content-Type: application/json'
    );
    $data = array(
        "personalizations" => array(
            array(
                "to" => array(
                    array(
                        "email" => $email,
                        "name" => $firstName,
                    )
                ),
                "dynamic_template_data" => array(
                    "first_name" => $firstName,
                    "last_name" => $lastName,
                    "refAffiliateCode" => $access_code
                ),
            )
        ),
        "from" => array(
            "email" => "no-reply@codebreakertech.com",
            "name" => "Codebreaker Technologies Inc",
        ),
        "subject" => $subject,
        "content" => array(
            array(
                "type" => "text/html",
                "value" => $body
            )
        ),
        "template_id"=> 'd-0983a180287b4984be8129b1cda4750c',
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.sendgrid.com/v3/mail/send");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    curl_close($ch);
}

function sendGridEmailSales($sFirstName,$firstName, $lastName, $bankCode,$email, $templateId, $lang, $partner, $pPhoneNumber,$pEmailAddress, $user_login) {
    // $email = "ahmad@sperse.com";
    $body = "Hey";
    $subject = "Your requested BANKCODE revealed";
    $headers = array(
        'Authorization: Bearer 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',
        'Content-Type: application/json'
    );
    $data = array(
        "personalizations" => array(
            array(
                "to" => array(
                    array(
                        "email" => $email,
                        "name" => $firstName,
                    )
                ),
                "dynamic_template_data" => array(
                "sFirstName" => $sFirstName,
                "first_name" => $firstName,
                "last_name" => $lastName,
                "bankCode" => $bankCode,
                "language" => $lang,
                "partner" => $partner,
                "eto" => $email,
                "pPhoneNumber" => $pPhoneNumber,
                "pEmailAddress" => $pEmailAddress
                ),
            )
        ),
        "from" => array(
            "email" => "no-reply@codebreakertech.com",
            "name" => "Codebreaker Technologies Inc",
        ),
        "subject" => $subject,
        "content" => array(
            array(
                "type" => "text/html",
                "value" => $body
            )
        ),
        "template_id"=> $templateId,
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.sendgrid.com/v3/mail/send");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    curl_close($ch);
    // echo $response;
}

// call affiliate webhook
function get_all_get_for_webhook($bankCode)
{
        
        $output = "?";
        // $output = "";
        $firstRun = true; 
        $associativeArray = array();
        $associativeArray['bankCode'] = $bankCode;
        foreach($_GET as $key=>$val) { 
        if($key != $parameter) { 
            if(!$firstRun) { 
                $output .= "&"; 
            } else { 
                $firstRun = false; 
            } 
            $associativeArray[$key] = $val;
            $output .= $key."=".$val;
         } 
    } 

    // return $output;
    return $associativeArray;
}  
function callAffiliateWebHook($bankCode, $refAC) {
    global $wpdb;
    $data = get_all_get_for_webhook($bankCode);
    $data = json_encode($data);
    
    $curl = curl_init();
    
    $refAC = strtolower($refAC);
    
    switch ($refAC) {
      case "letip": 
          $url = 'https://api.letipwired.com/webhooks/bank'; 
          break;
      case "ascira": 
          $url = ""; 
          break;
      case "mentor": 
          $url = ""; 
          break;
      default: 
          $url="https://codebreakertech.com/scripts/webhookRec.php"; 
    }
    
    
    // $url = 'https://codebreakertech.com/scripts/webhookRec.php';
     
    $ch = curl_init($url); 
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 
    $result = curl_exec($ch);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     
     
     
    $table_name = $wpdb->prefix . "webhooks";
    $wpdb->insert($table_name, array('url' => $url, 'request' => $data, 'response' => $result, 'status' => $httpcode )); 
     
    curl_close($curl);
}


## FUNCTION CALLS WHEN BANKPASS gform_after_submission_13. (gform_after_submission_13)

function set_post_content_to_Sperse_and_http_post_13($entry, $form) {
  global $CREATELEAD;
  global $apiKey;
  global $saveremotecodecrack;
  $referrerUrl = '';
  $access_code = '';
  $affiliateCode = '';
  $pPhoneNumber = rgar( $entry, '45' );
  $pEmailAddress = rgar( $entry, '41' );
  $bankCode     = rgar ( $entry, '44' );
//   $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    if(rgar ( $entry, '2' ) == "ENGLISH") {
    $lng = 'EN';
  } else if(rgar ( $entry, '2' ) == "ARABIC") {
    $lng = 'AR';
  } else if(rgar ( $entry, '2' ) == "RUSSIAN") {
    $lng = 'RU';
  } else if(rgar ( $entry, '2' ) == "SPANISH") {
    $lng = 'ES';
  } else {
    $lng = 'EN';
  }
  if(isset($_COOKIE['_referringURL'])) {
      $referrerUrl = urldecode($_COOKIE['_referringURL']);
    }
    if(isset($_COOKIE['_entryUrl'])) {
      $actual_link = urldecode($_COOKIE['_entryUrl']);
    } else {
        $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    }
    ## GET AFFILIATE ID FROM COOKIES IF EXISTS
    if(isset($_GET['ref'])) {
      global $wpdb;
      $aff_id = $_GET['ref'];     
      $results = $wpdb->get_results( "SELECT * FROM wp_users WHERE user_login = '".$aff_id."'", OBJECT );
      foreach ($results as $key => $value) {
        $user_id            = $value->ID;
        $user_info          = get_userdata($user_id);
        $first_name         = $user_info->first_name;
        $user_email         = $value->user_email;
        $user_login         = $user_info->user_login; 
        $data['user_email'] = $user_email;
        $affiliateEmail     = $user_info->user_email;
        $firstName          = rgar( $entry, '60' );
        $lastName           = rgar( $entry, '39' );
        $bankCode           = rgar( $entry, '44' );
        $primaryCode        = $bankCode[0];
        // set template Ids
         if(!isset($_GET['partner'])) {
          } else {
              $refURL = $_GET['partner'];
              if ($refURL == "SF") {
                  if(rgar ( $entry, '2' ) == "ENGLISH") {
                      $templateId  = "d-5e7e28907199426b96b345fdda335921";
                      $sTemplateId = "d-f10d7cd9f26a49a58835fc737f7c86d7";
                    } else if(rgar ( $entry, '2' ) == "ARABIC") {
                      $templateId  = "d-7dbdaf1a5b1043308e924b5e5e6cded8";
                      $sTemplateId = "d-3d549a8f577743cd8a329180287b4447";
                    } else if(rgar ( $entry, '2' ) == "RUSSIAN") {
                      $templateId  = "d-8ef79f253d8244a08a5116d3a40c3564";
                      $sTemplateId = "d-c513d640a1d14a669fbc3cd449a6c868";
                    } else if(rgar ( $entry, '2' ) == "SPANISH") {
                      $templateId  = "d-9567245fcf884fa8a559685028281e3c";
                      $sTemplateId = "d-0c3d91a5475c48ab8651c19d02e3589e";
                    } else {
                      $templateId  = "d-5e7e28907199426b96b345fdda335921";
                      $sTemplateId = "d-f10d7cd9f26a49a58835fc737f7c86d7";
                    }
              } else {
                  if(rgar ( $entry, '2' ) == "ENGLISH") {
                    switch ($primaryCode) {
                    case 'B': $templateId  = 'd-119b33db58a144f98f7404cc9b0b913d';
                              $sTemplateId = 'd-292b9a34def643798d9528712cd88e37'; break;
                    case 'A': $templateId  = 'd-b7cfc4b9072b4ba695c46a25bde6d7b8'; 
                              $sTemplateId = 'd-60388ffac46e47019e08efa5383f862f'; break;
                    case 'N': $templateId  = 'd-117c5dbb660a4b99ac6e36b30006c909'; 
                              $sTemplateId = 'd-7ce2f2cec6554e118462168802ff142f'; break;
                    case 'K': $templateId  = 'd-dbe57adcfc6c4d1fa819c3f7851a7df9';
                              $sTemplateId = 'd-655b500d20c94af5b978c77d3bd1308d'; break;
                    default:  $templateId  = 'd-bb5d0362dada4834bf3cb8ce7812bd0a';
                              $sTemplateId = 'd-567940ff3f094c01ac015a74488f0e47'; break;
                    }
                  } else if(rgar ( $entry, '2' ) == "ARABIC") {
                    switch ($primaryCode) {
                    case 'B': $templateId  = 'd-940d603090594d5db09e19861b7f873e';
                              $sTemplateId = 'd-ff2387dc2d5345c2b09e31ba90501624'; break;
                    case 'A': $templateId  = 'd-940d603090594d5db09e19861b7f873e'; 
                              $sTemplateId = 'd-ff2387dc2d5345c2b09e31ba90501624'; break;
                    case 'N': $templateId  = 'd-940d603090594d5db09e19861b7f873e'; 
                              $sTemplateId = 'd-ff2387dc2d5345c2b09e31ba90501624'; break;
                    case 'K': $templateId  = 'd-940d603090594d5db09e19861b7f873e';
                              $sTemplateId = 'd-ff2387dc2d5345c2b09e31ba90501624'; break;
                    default:  $templateId  = 'd-940d603090594d5db09e19861b7f873e';
                              $sTemplateId = 'd-ff2387dc2d5345c2b09e31ba90501624'; break;
                    }
                  } else if(rgar ( $entry, '2' ) == "RUSSIAN") {
                    switch ($primaryCode) {
                    case 'B': $templateId  = 'd-61dc08b59e6542238535c80f42f4525c';
                              $sTemplateId = 'd-4cf24ae4ce2244e0b035ec1e7578ee92'; break;
                    case 'A': $templateId  = 'd-61dc08b59e6542238535c80f42f4525c'; 
                              $sTemplateId = 'd-4cf24ae4ce2244e0b035ec1e7578ee92'; break;
                    case 'N': $templateId  = 'd-61dc08b59e6542238535c80f42f4525c'; 
                              $sTemplateId = 'd-4cf24ae4ce2244e0b035ec1e7578ee92'; break;
                    case 'K': $templateId  = 'd-61dc08b59e6542238535c80f42f4525c';
                              $sTemplateId = 'd-4cf24ae4ce2244e0b035ec1e7578ee92'; break;
                    default:  $templateId  = 'd-61dc08b59e6542238535c80f42f4525c';
                              $sTemplateId = 'd-4cf24ae4ce2244e0b035ec1e7578ee92'; break;
                    }
                  } else if(rgar ( $entry, '2' ) == "SPANISH") {
                    switch ($primaryCode) {
                    case 'B': $templateId  = 'd-25d5aca73a7c4614b4106b42f9a6632d';
                              $sTemplateId = 'd-e41f59fd51424dca8b5d9790ed905a05'; break;
                    case 'A': $templateId  = 'd-25d5aca73a7c4614b4106b42f9a6632d'; 
                              $sTemplateId = 'd-e41f59fd51424dca8b5d9790ed905a05'; break;
                    case 'N': $templateId  = 'd-25d5aca73a7c4614b4106b42f9a6632d'; 
                              $sTemplateId = 'd-e41f59fd51424dca8b5d9790ed905a05'; break;
                    case 'K': $templateId  = 'd-25d5aca73a7c4614b4106b42f9a6632d';
                              $sTemplateId = 'd-e41f59fd51424dca8b5d9790ed905a05'; break;
                    default:  $templateId  = 'd-25d5aca73a7c4614b4106b42f9a6632d';
                              $sTemplateId = 'd-e41f59fd51424dca8b5d9790ed905a05'; break;
                    }
                  } else {
                    $templateId  = "d-bb5d0362dada4834bf3cb8ce7812bd0a";
                    $sTemplateId = "d-567940ff3f094c01ac015a74488f0e47";
                  }
              }
          }
        sendEmailToSale($first_name, $user_email, $firstName, $lastName, $bankCode, $lng, $user_login, $sTemplateId, $pPhoneNumber, $pEmailAddress);
        $refAC = $_GET['ref'];
        if(strtoupper($refAC) == strtoupper('letip')) {
            callAffiliateWebHook($bankCode, $refAC);
        }
        
      }
      $user_info = get_userdata($user_id);
      $access_code = $user_info->user_login;
    }
    if(empty($access_code)) {
    $affiliateCode = '';
    $access_code = 'noAccessCode';
    } else {
      $affiliateCode = $access_code;
      $access_code = $access_code;
    }
    $trackingInformation = new stdClass();
    $trackingInformation->affiliateCode = $affiliateCode;
    $trackingInformation->referringUrl = $referrerUrl;
    $trackingInformation->entryUrl = $_SERVER['HTTP_REFERER'];
    $trackingInformation->userAgent = $_SERVER['HTTP_USER_AGENT'];
    $trackingInformation->ipAddress = getUserIpAddr();
    $trackingInformation = json_encode($trackingInformation);
  /* ----------------------------------------- 
    WORDPRESS to SPERSE(CRM)
   ----------------------------------------- */
   $bankPassLang  =  "BANKPASS ENGLISH";
  if($form['id']  == 8 ) {
    $firstName    = rgar( $entry, '60' );
    $lastName     = rgar( $entry, '39' );
    $email        = rgar( $entry, '41' );
    $phoneNumber  = rgar( $entry, '45' );
    $bankCode     = rgar ( $entry, '44' );
    $bankPassLang = "BANKPASS ".rgar ( $entry, '2' );
    if(empty($bankCode)) {
        $bankcode = 'BANK';
      }
  } else if($form['id'] == 9) {
    $firstName    = rgar( $entry, '60' );
    $lastName     = rgar( $entry, '39' );
    $email        = rgar( $entry, '41' );
    $phoneNumber  = rgar( $entry, '45' );
    $bankCode     = rgar ( $entry, '44' );
    $bankPassLang = "BANKPASS ".rgar ( $entry, '2' );
    if(empty($bankCode)) {
        $bankcode = 'BANK';
      }
  } else if($form['id'] == 10) {
    $firstName    = rgar( $entry, '60' );
    $lastName     = rgar( $entry, '39' );
    $email        = rgar( $entry, '41' );
    $phoneNumber  = rgar( $entry, '45' );
    $bankCode     =  rgar ( $entry, '44' );
    $bankPassLang =  "BANKPASS ".rgar ( $entry, '2' );
    if(empty($bankCode)) {
        $bankcode = 'BANK';
      }
  } else if($form['id'] == 11) {
    $firstName    = rgar( $entry, '60' );
    $lastName     = rgar( $entry, '39' );
    $email        = rgar( $entry, '41' );
    $phoneNumber  = rgar( $entry, '45' );
    $bankCode     = rgar ( $entry, '44' );
    $bankPassLang = "BANKPASS ".rgar ( $entry, '2' );
    if(empty($bankCode)) {
        $bankcode = 'BANK';
      }
  }
//send email
if(!isset($_GET['partner'])) {
} else {
    $refURL = $_GET['partner'];
    if ($refURL == "SF") {
        sendGridEmailProspects($firstName, $lastName, $bankCode,$email, $templateId, $lng, "SF", $user_login);
    } else {
        sendGridEmailProspects($firstName, $lastName, $bankCode,$email, $templateId, $lng, "CB", $user_login);
    }
}
    //send email
    $phoneNumbers = [];
    $phoneArray = [];
    if(!empty($phoneNumber)){
      $phoneArray['phoneNumber'] = $phoneNumber;
    }
  if(!empty($phoneArray)) {
        $phoneArray['usageTypeId'] = 'M';
        array_push($phoneNumbers, $phoneArray);
    }
  $ip = getUserIpAddr();
  
  if(isset($_GET['xRef'])  &&  !empty($_GET['xRef'])) {
      $xRef = $_GET['xRef'];
  } else {
      $xRef = Null;
  }
  
  $createOrUpdateContactJson = array(
                "firstName"=>$firstName,
                "lastName" => $lastName,
                "bankCode" => $bankCode,
                "PersonAffiliateCode"=>$personal_access_code,
                "trackingInfo" => array(
                  "affiliateCode"=>$affiliateCode,
                  "channelCode"=>'WP',
                  "refererUrl"=>$referrerUrl,
                  "userAgent"=>$_SERVER['HTTP_USER_AGENT'],
                  "entryUrl"=>$actual_link,
                  "clientIp"=>$ip
                ),
                "lists" => array(array(
                  "name" => $bankPassLang
                )),
                "phoneNumbers"=>$phoneNumbers,
                "emailAddresses"=> array(array(
                "emailAddress"=>$email,
                "usageTypeId"=>"P"
                )),
                "contactXRef"      =>$xRef, 
                "addresses"=>$address,
                "contactGroupId"=>"C",
                "matchExisting"=>true,
                "bypassValidation" => true
                );
    $createOrUpdateContactJson = json_encode($createOrUpdateContactJson);
  // $trackingInformation = {};
  
  $ip = getUserIpAddr();
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => $CREATELEAD,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    // CURLOPT_POSTFIELDS => "{\n\t\"firstName\": \"".$firstName."\",\n\t\"lastName\": \"".$lastName."\",\n\t \"bankCode\": \"".$bankCode."\",\n\t\"trackingInfo\": {\n    \"affiliateCode\": \"".$affiliateCode."\",\n\t    \"channelCode\": \"WP\",\n    \"refererUrl\": \"".$referrerUrl."\",\n    \"entryUrl\": \"".$actual_link."\",\n    \"userAgent\": \"".$_SERVER['HTTP_USER_AGENT']."\",\n    \"clientIp\": \"".$ip."\"\n\t}, \n\t \"emailAddresses\": [{\n            \"emailAddress\": \"".$email."\",\n            \"isActive\": true,\n            \"usageTypeId\": \"P\"\n        }],\n\t \"lists\": [{\n            \"name\": \"".$bankPassLang."\"}],\n\t \"contactGroupId\": \"C\",\n\t \"matchExisting\": \"true\",\n\t \"matchByEmail\": true\n}",
    CURLOPT_POSTFIELDS => $createOrUpdateContactJson,
    CURLOPT_HTTPHEADER => array(
      "Content-Type: application/json",
      "Postman-Token: f0a741fe-af60-4b6e-bde5-a29a3e0124a1",
      "api-key: ".$apiKey,
      "cache-control: no-cache,no-cache"
    ),
  ));

  $response = curl_exec($curl);
  $err = curl_error($curl);
  curl_close($curl);
  if ($err) {
    // echo "cURL Error #:" . $err;
    gform_update_meta( $entry['id'], 'wp_to_crm', "Error :" . $err );
  } else {
    // echo $response;
    gform_update_meta( $entry['id'], 'wp_to_crm', $response );
  }
  
  //////test admin sperse
  
//   $ip = getUserIpAddr();
//       $curl = curl_init();
//       curl_setopt_array($curl, array(
//         CURLOPT_URL => "https://testadmin.sperse.com/api/services/CRM/Contact/CreateOrUpdateContact",
//         CURLOPT_RETURNTRANSFER => true,
//         CURLOPT_ENCODING => "",
//         CURLOPT_MAXREDIRS => 10,
//         CURLOPT_TIMEOUT => 30,
//         CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//         CURLOPT_CUSTOMREQUEST => "POST",
//         // CURLOPT_POSTFIELDS => "{\n\t\"firstName\": \"".$firstName."\",\n\t\"lastName\": \"".$lastName."\",\n\t \"bankCode\": \"".$bankCode."\",\n\t\"trackingInfo\": {\n    \"affiliateCode\": \"".$affiliateCode."\",\n\t    \"channelCode\": \"WP\",\n    \"refererUrl\": \"".$referrerUrl."\",\n    \"entryUrl\": \"".$actual_link."\",\n    \"userAgent\": \"".$_SERVER['HTTP_USER_AGENT']."\",\n    \"clientIp\": \"".$ip."\"\n\t}, \n\t \"emailAddresses\": [{\n            \"emailAddress\": \"".$email."\",\n            \"isActive\": true,\n            \"usageTypeId\": \"P\"\n        }],\n\t \"lists\": [{\n            \"name\": \"".$bankPassLang."\"}],\n\t \"contactGroupId\": \"C\",\n\t \"matchExisting\": \"true\",\n\t \"matchByEmail\": true\n}",
//         CURLOPT_POSTFIELDS => $createOrUpdateContactJson,
//         CURLOPT_HTTPHEADER => array(
//           "Content-Type: application/json",
//           "api-key: 000785-QUDAHP-983R45-9ZK6J7-9ESFEK",
//           "cache-control: no-cache,no-cache"
//         ),
//       ));
    
//       $response = curl_exec($curl);
//       $err = curl_error($curl);
//       curl_close($curl);
//       $err = curl_error($curl);
//   curl_close($curl);
//   if ($err) {
//     // echo "cURL Error #:" . $err;
//     gform_update_meta( $entry['id'], 'wp_to_crmSperse', "Error :" . $err );
//   } else {
//     // echo $response;
//     gform_update_meta( $entry['id'], 'wp_to_crmSperse', $response );
//   }
  
  
  //////test admin sperse

  /* ----------------------------------------- 
        WORDPRESS to HTTP POST
  ----------------------------------------- */
      $curl = curl_init();
      curl_setopt_array($curl, array(
        CURLOPT_URL => $saveremotecodecrack,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "source=bankcode&accesscode=".$access_code."&bankcode=".$bankCode."&fname=".$firstName."&email=".$email."&ipaddress=".$ip."&undefined=",
        CURLOPT_HTTPHEADER => array(
          "Content-Type: application/x-www-form-urlencoded",
          "cache-control: no-cache,no-cache"
        ),
      ));
      $response = curl_exec($curl);
      $err = curl_error($curl);
      curl_close($curl);
      if ($err) {
        gform_update_meta( $entry['id'], 'wp_to_http_post', "Error :" . $err );
      } else {
        gform_update_meta( $entry['id'], 'wp_to_http_post', $response);
      }
}


// direct analytics 19
function set_post_content_to_Sperse_and_http_post_19($entry, $form) {
  global $CREATELEAD;
  global $apiKey;
  global $saveremotecodecrack;
  global $wpdb;
  $referrerUrl = '';
  $access_code = '';
  $affiliateCode = '';
//   $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  if(isset($_COOKIE['_referringURL'])) {
      $referrerUrl = urldecode($_COOKIE['_referringURL']);
    }
    if(isset($_COOKIE['_entryUrl'])) {
      $actual_link = urldecode($_COOKIE['_entryUrl']);
    } else {
        $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    }
    ## GET AFFILIATE ID FROM COOKIES IF EXISTS
    $firstName    = rgar( $entry, '1' );
    $companyName  = rgar( $entry, '2' );
    $phoneNumber  = rgar( $entry, '3' );
    $email        = rgar( $entry, '4' );
    $title        = rgar( $entry, '5' );
    $industry        = rgar( $entry, '6' );
    
    $accessCode   = rgar( $entry, '5' );
    $accessCode   = trim($accessCode);
    
    if(!empty($accessCode)) {
        $access_code = $accessCode;
        $results2 = $wpdb->get_results( "SELECT * FROM wp_users WHERE user_login = '".$access_code."'", OBJECT );
        if(!empty($results2)) {
            foreach ($results2 as $key => $value) {
                $user_id            = $value->ID;
                $user_info          = get_userdata($user_id);
                $first_name         = $user_info->first_name;
                $access_code        = $user_info->user_login; 
                $affiliateEmail     = $user_info->user_email;
              }
            $resultsAffId = $wpdb->get_results( "SELECT * FROM wp_affiliate_wp_affiliates WHERE user_id = '".$user_id."'", OBJECT ); 
            $affiliateId = $resultsAffId[0]->affiliate_id;
            $cookie_name = "affwp_ref";
            $cookie_value = $affiliateId;
            setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
            
        }
    } else {
            if(isset($_COOKIE['affwp_ref'])) {
              global $wpdb;
              $affwp_ref = $_COOKIE['affwp_ref'];     
              $results = $wpdb->get_results( "SELECT * FROM wp_affiliate_wp_affiliates WHERE affiliate_id = '".$affwp_ref."'", OBJECT );
              $userId = $results[0]->user_id;
              $results1 = $wpdb->get_results( "SELECT * FROM wp_users WHERE ID = '".$userId."'", OBJECT );
              
              foreach ($results1 as $key => $value) {
                $user_id            = $value->ID;
                $user_info          = get_userdata($user_id);
                $first_name         = $user_info->first_name;
                $access_code         = $user_info->user_login; 
                $affiliateEmail     = $user_info->user_email;
              }
              
            //   $user_info = get_userdata($user_id);
            //   $access_code = $user_info->user_login;
            }
    }
    if(empty($access_code)) {
    $affiliateCode = '';
    $access_code = 'noAccessCode';
    } else {
      $affiliateCode = $access_code;
      $access_code = $access_code;
    }
    $trackingInformation = new stdClass();
    $trackingInformation->affiliateCode = $affiliateCode;
    $trackingInformation->referringUrl = $referrerUrl;
    $trackingInformation->entryUrl = $_SERVER['HTTP_REFERER'];
    $trackingInformation->userAgent = $_SERVER['HTTP_USER_AGENT'];
    $trackingInformation->ipAddress = getUserIpAddr();
    $trackingInformation = json_encode($trackingInformation);
  /* ----------------------------------------- 
    WORDPRESS to SPERSE(CRM)
   ----------------------------------------- */
   
    
    if(empty($bankCode)) {
        $bankcode = 'BANK';
      }
 
//send email
    
    //send email
    $phoneNumbers = [];
    $phoneArray = [];
    if(!empty($phoneNumber)){
      $phoneArray['phoneNumber'] = $phoneNumber;
    }
  if(!empty($phoneArray)) {
        $phoneArray['usageTypeId'] = 'M';
        array_push($phoneNumbers, $phoneArray);
    }
  $ip = getUserIpAddr();
  $createOrUpdateContactJson = array(
                "firstName"=>$firstName,
                "companyName" => $companyName,
                "trackingInfo" => array(
                  "affiliateCode"=>$affiliateCode,
                  "channelCode"=>'WP',
                  "refererUrl"=>$referrerUrl,
                  "userAgent"=>$_SERVER['HTTP_USER_AGENT'],
                  "entryUrl"=>$actual_link,
                  "clientIp"=>$ip
                ),
                "lists" => array(array(
                  "name" => "Direct Analytics"
                )),
                "phoneNumbers"=>$phoneNumbers,
                "emailAddresses"=> array(array(
                "emailAddress"=>$email,
                "usageTypeId"=>"P"
                )),
                "title" => $title,
                "industry" => $industry,
                "contactGroupId"=>"C",
                "matchExisting"=>true,
                "bypassValidation" => true
                );
    $createOrUpdateContactJson = json_encode($createOrUpdateContactJson);
  // $trackingInformation = {};
  
  $ip = getUserIpAddr();
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => $CREATELEAD,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    // CURLOPT_POSTFIELDS => "{\n\t\"firstName\": \"".$firstName."\",\n\t\"lastName\": \"".$lastName."\",\n\t \"bankCode\": \"".$bankCode."\",\n\t\"trackingInfo\": {\n    \"affiliateCode\": \"".$affiliateCode."\",\n\t    \"channelCode\": \"WP\",\n    \"refererUrl\": \"".$referrerUrl."\",\n    \"entryUrl\": \"".$actual_link."\",\n    \"userAgent\": \"".$_SERVER['HTTP_USER_AGENT']."\",\n    \"clientIp\": \"".$ip."\"\n\t}, \n\t \"emailAddresses\": [{\n            \"emailAddress\": \"".$email."\",\n            \"isActive\": true,\n            \"usageTypeId\": \"P\"\n        }],\n\t \"lists\": [{\n            \"name\": \"".$bankPassLang."\"}],\n\t \"contactGroupId\": \"C\",\n\t \"matchExisting\": \"true\",\n\t \"matchByEmail\": true\n}",
    CURLOPT_POSTFIELDS => $createOrUpdateContactJson,
    CURLOPT_HTTPHEADER => array(
      "Content-Type: application/json",
      "Postman-Token: f0a741fe-af60-4b6e-bde5-a29a3e0124a1",
      "api-key: ".$apiKey,
      "cache-control: no-cache,no-cache"
    ),
  ));

  $response = curl_exec($curl);
  $err = curl_error($curl);
  curl_close($curl);
  if ($err) {
    // echo "cURL Error #:" . $err;
    gform_update_meta( $entry['id'], 'wp_to_crm', "Error :" . $err );
  } else {
    // echo $response;
    gform_update_meta( $entry['id'], 'wp_to_crm', $response );
  }

  /* ----------------------------------------- 
        WORDPRESS to HTTP POST
  ----------------------------------------- */
      $curl = curl_init();
      curl_setopt_array($curl, array(
        CURLOPT_URL => $saveremotecodecrack,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "source=bankcode&accesscode=".$access_code."&bankcode=".$bankCode."&fname=".$firstName."&email=".$email."&ipaddress=".$ip."&undefined=",
        CURLOPT_HTTPHEADER => array(
          "Content-Type: application/x-www-form-urlencoded",
          "cache-control: no-cache,no-cache"
        ),
      ));
      $response = curl_exec($curl);
      $err = curl_error($curl);
      curl_close($curl);
      if ($err) {
        gform_update_meta( $entry['id'], 'wp_to_http_post', "Error :" . $err );
      } else {
        gform_update_meta( $entry['id'], 'wp_to_http_post', $response);
      }
}
// master class form 18

//master class form 18
function set_post_content_to_Sperse_and_http_post_18($entry, $form) {
  global $CREATELEAD;
  global $apiKey;
  global $saveremotecodecrack;
  global $wpdb;
  $referrerUrl = '';
  $access_code = '';
  $affiliateCode = '';
//   $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  if(isset($_COOKIE['_referringURL'])) {
      $referrerUrl = urldecode($_COOKIE['_referringURL']);
    }
    if(isset($_COOKIE['_entryUrl'])) {
      $actual_link = urldecode($_COOKIE['_entryUrl']);
    } else {
        $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    }
    ## GET AFFILIATE ID FROM COOKIES IF EXISTS
    $firstName    = rgar( $entry, '1' );
    $lastName     = rgar( $entry, '2' );
    $email        = rgar( $entry, '3' );
    $phoneNumber  = rgar( $entry, '4' );
    $accessCode   = rgar( $entry, '5' );
    $accessCode   = trim($accessCode);
    
    if(!empty($accessCode)) {
        $access_code = $accessCode;
        $results2 = $wpdb->get_results( "SELECT * FROM wp_users WHERE user_login = '".$access_code."'", OBJECT );
        if(!empty($results2)) {
            foreach ($results2 as $key => $value) {
                $user_id            = $value->ID;
                $user_info          = get_userdata($user_id);
                $first_name         = $user_info->first_name;
                $access_code        = $user_info->user_login; 
                $affiliateEmail     = $user_info->user_email;
              }
            $resultsAffId = $wpdb->get_results( "SELECT * FROM wp_affiliate_wp_affiliates WHERE user_id = '".$user_id."'", OBJECT ); 
            $affiliateId = $resultsAffId[0]->affiliate_id;
            $cookie_name = "affwp_ref";
            $cookie_value = $affiliateId;
            setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
            registrantEmailtoAffiliate($first_name, $affiliateEmail, $firstName, $lastName, $access_code, $phoneNumber, $email);
        }
    } else {
            if(isset($_COOKIE['affwp_ref'])) {
              global $wpdb;
              $affwp_ref = $_COOKIE['affwp_ref'];     
              $results = $wpdb->get_results( "SELECT * FROM wp_affiliate_wp_affiliates WHERE affiliate_id = '".$affwp_ref."'", OBJECT );
              $userId = $results[0]->user_id;
              $results1 = $wpdb->get_results( "SELECT * FROM wp_users WHERE ID = '".$userId."'", OBJECT );
              
              foreach ($results1 as $key => $value) {
                $user_id            = $value->ID;
                $user_info          = get_userdata($user_id);
                $first_name         = $user_info->first_name;
                $access_code         = $user_info->user_login; 
                $affiliateEmail     = $user_info->user_email;
              }
              registrantEmailtoAffiliate($first_name, $affiliateEmail, $firstName, $lastName, $access_code, $phoneNumber, $email);
            //   $user_info = get_userdata($user_id);
            //   $access_code = $user_info->user_login;
            }
    }
    if(empty($access_code)) {
    $affiliateCode = '';
    $access_code = 'noAccessCode';
    } else {
      $affiliateCode = $access_code;
      $access_code = $access_code;
    }
    $trackingInformation = new stdClass();
    $trackingInformation->affiliateCode = $affiliateCode;
    $trackingInformation->referringUrl = $referrerUrl;
    $trackingInformation->entryUrl = $_SERVER['HTTP_REFERER'];
    $trackingInformation->userAgent = $_SERVER['HTTP_USER_AGENT'];
    $trackingInformation->ipAddress = getUserIpAddr();
    $trackingInformation = json_encode($trackingInformation);
  /* ----------------------------------------- 
    WORDPRESS to SPERSE(CRM)
   ----------------------------------------- */
   
    $bankPassLang = "BANKPASS ".rgar ( $entry, '2' );
    if(empty($bankCode)) {
        $bankcode = 'BANK';
      }
 
//send email
    registrantConfirmationEmail($firstName, $lastName, $email, $access_code);
    //send email
    $phoneNumbers = [];
    $phoneArray = [];
    if(!empty($phoneNumber)){
      $phoneArray['phoneNumber'] = $phoneNumber;
    }
  if(!empty($phoneArray)) {
        $phoneArray['usageTypeId'] = 'M';
        array_push($phoneNumbers, $phoneArray);
    }
  $ip = getUserIpAddr();
  $createOrUpdateContactJson = array(
                "firstName"=>$firstName,
                "lastName" => $lastName,
                "trackingInfo" => array(
                  "affiliateCode"=>$affiliateCode,
                  "channelCode"=>'WP',
                  "refererUrl"=>$referrerUrl,
                  "userAgent"=>$_SERVER['HTTP_USER_AGENT'],
                  "entryUrl"=>$actual_link,
                  "clientIp"=>$ip
                ),
                "lists" => array(array(
                  "name" => "Masterclass Webinar Series"
                )),
                "phoneNumbers"=>$phoneNumbers,
                "emailAddresses"=> array(array(
                "emailAddress"=>$email,
                "usageTypeId"=>"P"
                )),
                "contactGroupId"=>"C",
                "matchExisting"=>true,
                "bypassValidation" => true
                );
    $createOrUpdateContactJson = json_encode($createOrUpdateContactJson);
  // $trackingInformation = {};
  
  $ip = getUserIpAddr();
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => $CREATELEAD,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    // CURLOPT_POSTFIELDS => "{\n\t\"firstName\": \"".$firstName."\",\n\t\"lastName\": \"".$lastName."\",\n\t \"bankCode\": \"".$bankCode."\",\n\t\"trackingInfo\": {\n    \"affiliateCode\": \"".$affiliateCode."\",\n\t    \"channelCode\": \"WP\",\n    \"refererUrl\": \"".$referrerUrl."\",\n    \"entryUrl\": \"".$actual_link."\",\n    \"userAgent\": \"".$_SERVER['HTTP_USER_AGENT']."\",\n    \"clientIp\": \"".$ip."\"\n\t}, \n\t \"emailAddresses\": [{\n            \"emailAddress\": \"".$email."\",\n            \"isActive\": true,\n            \"usageTypeId\": \"P\"\n        }],\n\t \"lists\": [{\n            \"name\": \"".$bankPassLang."\"}],\n\t \"contactGroupId\": \"C\",\n\t \"matchExisting\": \"true\",\n\t \"matchByEmail\": true\n}",
    CURLOPT_POSTFIELDS => $createOrUpdateContactJson,
    CURLOPT_HTTPHEADER => array(
      "Content-Type: application/json",
      "Postman-Token: f0a741fe-af60-4b6e-bde5-a29a3e0124a1",
      "api-key: ".$apiKey,
      "cache-control: no-cache,no-cache"
    ),
  ));

  $response = curl_exec($curl);
  $err = curl_error($curl);
  curl_close($curl);
  if ($err) {
    // echo "cURL Error #:" . $err;
    gform_update_meta( $entry['id'], 'wp_to_crm', "Error :" . $err );
  } else {
    // echo $response;
    gform_update_meta( $entry['id'], 'wp_to_crm', $response );
  }

  /* ----------------------------------------- 
        WORDPRESS to HTTP POST
  ----------------------------------------- */
      $curl = curl_init();
      curl_setopt_array($curl, array(
        CURLOPT_URL => $saveremotecodecrack,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "source=bankcode&accesscode=".$access_code."&bankcode=".$bankCode."&fname=".$firstName."&email=".$email."&ipaddress=".$ip."&undefined=",
        CURLOPT_HTTPHEADER => array(
          "Content-Type: application/x-www-form-urlencoded",
          "cache-control: no-cache,no-cache"
        ),
      ));
      $response = curl_exec($curl);
      $err = curl_error($curl);
      curl_close($curl);
      if ($err) {
        gform_update_meta( $entry['id'], 'wp_to_http_post', "Error :" . $err );
      } else {
        gform_update_meta( $entry['id'], 'wp_to_http_post', $response);
      }
}
// direct analytics 19


function wbrubaker_redirect_to_cart( $found_in_cart ) {
if ( $found_in_cart ) {
wp_safe_redirect( wc_get_page_permalink( "cart" ) );
exit;
}
return $found_in_cart;
}

function hideViewCartButtons() {
    ?>
    <script>
    if(document.querySelectorAll('.button.wc-forward')[0] != null) {
        document.querySelectorAll('.button.wc-forward').forEach(function(n){
        if(n.innerText.toUpperCase() == "view cart".toUpperCase()){
                n.style.display = "none";
        }
        })
    }
    </script>
    <?php
}

## FUNCTION CALLS WHEN SUBMIT THE CONTACT US FORM. (gform_after_submission_6)
function set_post_content_to_Sperse_and_http_post_6($entry, $form) {
  global $CREATELEAD;
  global $apiKey;
  global $saveremotecodecrack;
  $referrerUrl = '';
  $access_code = '';
  $affiliateCode = '';
//   $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  if(isset($_COOKIE['_referringURL'])) {
      $referrerUrl = urldecode($_COOKIE['_referringURL']);
    }
    if(isset($_COOKIE['_entryUrl'])) {
      $actual_link = urldecode($_COOKIE['_entryUrl']);
    } else {
        $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    }

   ## GET AFFILIATE ID FROM COOKIES IF EXISTS
    if(isset($_COOKIE['affwp_ref'])) {
      global $wpdb;
      $aff_id = $_COOKIE['affwp_ref'];     
      $results = $wpdb->get_results( "SELECT * FROM wp_affiliate_wp_affiliates WHERE affiliate_id = '".$aff_id."'", OBJECT );
      foreach ($results as $key => $value) {
        $user_id = $value->user_id;
        $user_email = $value->payment_email;
        $data['user_email'] = $user_email;
      }
      $user_info = get_userdata($user_id);
      $access_code = $user_info->user_login;
    } 

   $firstName = rgar( $entry, '1' );
  // $lastName = rgar( $entry, '1.6' );
  $email = rgar( $entry, '3' );
  $phoneNumber = rgar( $entry, '2' );
  $bankcode = 'BANK';
  // $accesscode = 'noAccessCode';
  if(empty($access_code)) {
    $affiliateCode = '';
    $access_code = 'noAccessCode';
  } else {
    $affiliateCode = $access_code;
    $access_code = $access_code;
  }
  $ip = getUserIpAddr();

  $trackingInformation = new stdClass();
  $trackingInformation->affiliateCode = $affiliateCode;
  $trackingInformation->referringUrl = $referrerUrl;
  $trackingInformation->entryUrl = $_SERVER['HTTP_REFERER'];
  $trackingInformation->userAgent = $_SERVER['HTTP_USER_AGENT'];
  $trackingInformation->ipAddress = getUserIpAddr();
  $trackingInformation = json_encode($trackingInformation);

  /* ----------------------------------------- 
    WORDPRESS to SPERSE(CRM)
   ----------------------------------------- */
 $contactRequest  = "{\n\t\"firstName\": \"".$firstName."\",\n\t\"trackingInfo\": {\n    \"affiliateCode\": \"".$affiliateCode."\",\n\t    \"channelCode\": \"WP\",\n    \"refererUrl\": \"".$referrerUrl."\",\n    \"entryUrl\": \"".$actual_link."\",\n    \"userAgent\": \"".$_SERVER['HTTP_USER_AGENT']."\",\n    \"clientIp\": \"".$ip."\"\n\t},\n\t \"phoneNumbers\": [{\n                    \"phoneNumber\": \"".$phoneNumber."\",\n                    \"phoneExtension\": \"\", \n                    \"isActive\": true,\n                    \"usageTypeId\": \"M\"\n                }],\n\t \"emailAddresses\": [{\n            \"emailAddress\": \"".$email."\",\n            \"isActive\": true,\n            \"usageTypeId\": \"P\"\n        }],\n\t \"contactGroupId\": \"C\",\n\t \"matchExisting\": \"true\",\n\t \"bypassValidation\": \"true\",\n\t \"matchByEmail\": true\n}";
   
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => $CREATELEAD,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "{\n\t\"firstName\": \"".$firstName."\",\n\t\"trackingInfo\": {\n    \"affiliateCode\": \"".$affiliateCode."\",\n\t    \"channelCode\": \"WP\",\n    \"refererUrl\": \"".$referrerUrl."\",\n    \"entryUrl\": \"".$actual_link."\",\n    \"userAgent\": \"".$_SERVER['HTTP_USER_AGENT']."\",\n    \"clientIp\": \"".$ip."\"\n\t},\n\t \"phoneNumbers\": [{\n                    \"phoneNumber\": \"".$phoneNumber."\",\n                    \"phoneExtension\": \"\", \n                    \"isActive\": true,\n                    \"usageTypeId\": \"M\"\n                }],\n\t \"emailAddresses\": [{\n            \"emailAddress\": \"".$email."\",\n            \"isActive\": true,\n            \"usageTypeId\": \"P\"\n        }],\n\t \"contactGroupId\": \"C\",\n\t \"matchExisting\": \"true\",\n\t \"bypassValidation\": \"true\",\n\t \"matchByEmail\": true\n}",
    CURLOPT_HTTPHEADER => array(
      "Content-Type: application/json",
      "Postman-Token: f0a741fe-af60-4b6e-bde5-a29a3e0124a1",
      "api-key: ".$apiKey,
      "cache-control: no-cache,no-cache"
    ),
  ));
  $response = curl_exec($curl);
  $err = curl_error($curl);
  curl_close($curl);
  
  $contactRequest = json_decode($contactRequest);
  $contactRequest = json_encode($contactRequest);
  
  if ($err) {
    // echo "cURL Error #:" . $err;
    gform_update_meta( $entry['id'], 'wp_to_crm_request', $contactRequest );
    gform_update_meta( $entry['id'], 'wp_to_crm', "Error :" . $err );
  } else {
    // echo $response;
    gform_update_meta( $entry['id'], 'wp_to_crm_request', $contactRequest );
    gform_update_meta( $entry['id'], 'wp_to_crm', $response );
  }

  /* ----------------------------------------- 
        WORDPRESS to HTTP POST
    ----------------------------------------- */
      $curl = curl_init();
      curl_setopt_array($curl, array(
        CURLOPT_URL => $saveremotecodecrack,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "source=bankcode&accesscode=".$access_code."&bankcode=".$bankcode."&fname=".$firstName."&lname=".$lastName."&email=".$email."&ipaddress=".$ip."&undefined=",
        CURLOPT_HTTPHEADER => array(
          "Content-Type: application/x-www-form-urlencoded",
          "cache-control: no-cache,no-cache"
        ),
      ));
      $response = curl_exec($curl);
      $err = curl_error($curl);
      curl_close($curl);
      if ($err) {
        gform_update_meta( $entry['id'], 'wp_to_http_post', "Error :" . $err );
      } else {
        gform_update_meta( $entry['id'], 'wp_to_http_post', $response);
      }
}

function getUserIpAddr(){
    if(!empty($_SERVER['HTTP_CLIENT_IP'])){
        //ip from share internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
        //ip pass from proxy
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

function comment_validation_init() {
{
    ?>
    <?php if( ! is_cart() ) { ?>
      <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <?php } ?>
    <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function($) {
       var $form = jQuery("#gform_4");

$form.validate({
    rules: {
        input_38: {
            required: true,
        },
        input_39: {
            required: true,
        },
        input_40: {
            required: true,
        },
        input_41: {
            email: true,
            required: true,
        },
        input_45: {
            required: true,
        },
        input_43: {
            required: true,
        },
    }, 
    highlight: function(element) {
        $(element).parent('div').parent('li').addClass('gfield_error');
        $(element).next().addClass('gfield_description validation_message');
    },
    unhighlight: function(element) {
        $(element).parent('div').parent('li').removeClass('gfield_error');
        $(element).next().removeClass('gfield_description validation_message');
    }
});

jQuery("#gform_submit_button_4").on('click', function(){
    if($form.valid()){
      var ip_address = localStorage.getItem('ip_address');
      var country_code = localStorage.getItem('country_code');
      var firstName = $('#input_4_38').val().trim();
      var email = $('#input_4_41').val().trim();
      var number = $('#input_4_45').val().replace(/\D/g,'').trim();
      var input_4_45_hidden = $('#input_4_45_hidden').val().trim();
      var input_4_45_hidden_value = $('#input_4_45_hidden_value').val().trim();
      var user_agent = navigator.userAgent;
      xhr = new XMLHttpRequest();
      var url = "https://codebreakertech.com/webServices/verify_apis/verify.php";
      xhr.open("POST", url, true);
      xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
      xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
        var response = JSON.parse(xhr.responseText);
      if(response.email != false && (input_4_45_hidden == "valid" || input_4_45_hidden == "")) {
        $form.submit();
      } else {
        if(input_4_45_hidden == "invalid") {
          // $('#input_4_45').next('<label generated="true" for="input_4_45" class="error">Phone Number is Invalid</label>');
          // $('#input_4_45').parent('div').parent('li').addClass('gfield_error');
          // $('#input_4_45').next().addClass('gfield_description validation_message');
        } else {
          // $('#input_4_45').parent('div').parent('li').removeClass('gfield_error');
          // $('#input_4_45').next().removeClass('gfield_description validation_message');
        }
        if(response.email == false) {
          $('#input_4_41').after('<label generated="true" for="input_4_41" class="error">Email is Invalid</label>');
          $('#input_4_41').parent('div').parent('li').addClass('gfield_error');
          $('#input_4_41').next().addClass('gfield_description validation_message');
        } else {
          $('#input_4_41').parent('div').parent('li').removeClass('gfield_error');
          $('#input_4_41').next().removeClass('gfield_description validation_message');
        }
      }
    }
  }
          var data = JSON.stringify({
          "email": email,
          "ip": ip_address,
          "ua": user_agent,
          "gender": firstName,
          "country_code": country_code
        });
          xhr.send(data);
          return false;
    }
});
    });
    </script>
    <?php
}
}

add_action('wp_footer', 'comment_validation_init');
// add_action('woocommerce_checkout_process', 'wh_phoneValidateCheckoutFields');

function wh_phoneValidateCheckoutFields() {
    $firstName = filter_input(INPUT_POST, 'billing_first_name');
    $email = filter_input(INPUT_POST, 'billing_email');
    $phone_number = filter_input(INPUT_POST, 'billing_phone');
    $ip = getUserIpAddr();
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $country_code = ip_visitor_country();
    if(!empty($email) && !empty($phone_number)) {
      $curl = curl_init();
      curl_setopt_array($curl, array(
        CURLOPT_URL => "https://codebreakertech.com/webServices/verify_apis/verify.php",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "\t\n{\n\t\"email\": \"".$email."\",\n\t\"number\": \"".$phone_number."\",\n\t\"ip\": \"".$ip."\",\n\t\"ua\": \"".$user_agent."\",\n\t\"gender\": \"".$firstName."\",\n\t\"country_code\": \"US\"\n}",
        CURLOPT_HTTPHEADER => array(
          "Content-Type: application/json",
          "cache-control: no-cache"
        ),
      ));
      $response = curl_exec($curl);
      $err = curl_error($curl);
      $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
      curl_close($curl);
      if(!$err) {
        $resp = json_decode($response);
        $number_error = $resp->number;
        $email_error = $resp->email;
        if(!empty($phone_number)) {
          if($number_error == false) {
          wc_add_notice(__('<strong>Invalid Phone Number</strong>, please check your input.'), 'error');
        }  
        }
        if(!empty($email))
        {
          if($email_error == false) {
          wc_add_notice(__('<strong>Invalid Email</strong>, please check your input.'), 'error');
          }
        }
      }
    }
}

function ip_visitor_country()
{
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];
    $country  = "Unknown";
    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://www.geoplugin.net/json.gp?ip=".$ip);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $ip_data_in = curl_exec($ch); // string
    curl_close($ch);
    $ip_data = json_decode($ip_data_in,true);
    $ip_data = str_replace('&quot;', '"', $ip_data); // for PHP 5.2 see stackoverflow.com/questions/3110487/
    if($ip_data && $ip_data['geoplugin_countryName'] != null) {
        $country = $ip_data['geoplugin_countryName'];
        $country_code = $ip_data['geoplugin_countryCode'];
    }
    return $country_code;
}

// my_setcookie() set the cookie on the domain and directory WP is installed on
function setCookiesforAutoLoginLink(){
    $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $a = 'How are you?';
    // if (strpos($actual_link, 'thank-you') !== false) {
        if(isset($_REQUEST['wcf-order'])){
            $post_id = $_REQUEST['wcf-order'];
            global $wpdb;
            $createUserForContact = $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE (post_id = '".$post_id."' AND meta_key = '_createLeadResponse')");
            foreach( $createUserForContact as $result ) {
                $data = json_decode($result->meta_value);
                $autoLoginLink = $data->result->autoLoginLink;
                $path = parse_url(get_option('siteurl'), PHP_URL_PATH);    
                $host = parse_url(get_option('siteurl'), PHP_URL_HOST);
                $expiry = strtotime('+1 day');
                setcookie('autoLoginLink', $autoLoginLink, $expiry, $path, $host);
            }
        }
    // }
}




/************************
* Author:    Ahmad khalid
* Created:   25.10.2019
*************************/
?>