<?php



if (!defined('ABSPATH')) {



  exit; // Exit if accessed directly.



}







class SensFRX_Check_Order_Update {



  public function sensfrx_check_order_update_changes($post_id, $post) {



		$order = wc_get_order($post_id);



		$order_id = $order->get_id();



		global $wpdb;



		$before = [



			'shipping_address'    => $order->get_shipping_address_1() ?? '',



			'shipping_country'    => $order->get_shipping_country() ?? '',



			'shipping_state'      => $order->get_shipping_state() ?? '',



			'shipping_city'       => $order->get_shipping_city() ?? '',



			'shipping_zip'        => $order->get_shipping_postcode() ?? '',



			'shipping_phone'      => $order->get_billing_phone() ?? '',



			'shipping_fullname'   => ($order->get_shipping_first_name() ?? '') . ' ' . ($order->get_shipping_last_name() ?? ''),







			'billing_address'     => $order->get_billing_address_1() ?? '',



			'billing_country'     => $order->get_billing_country() ?? '',



			'billing_state'       => $order->get_billing_state() ?? '',



			'billing_city'        => $order->get_billing_city() ?? '',



			'billing_zip'         => $order->get_billing_postcode() ?? '',



			'billing_phone'       => $order->get_billing_phone() ?? '',



			'billing_fullname'    => ($order->get_billing_first_name() ?? '') . ' ' . ($order->get_billing_last_name() ?? ''),



			'billing_email'       => $order->get_billing_email() ?? '',







			'payment_mode'        => $order->get_payment_method_title() ?? '',



			'transaction_id'      => $order->get_transaction_id() ?? '',



			'transaction_status'  => $order->get_status() ?? '',



		];



		$after = [



			'shipping_address'    => isset($_POST['_shipping_address_1']) ? sanitize_text_field($_POST['_shipping_address_1']) : '',



			'shipping_country'    => isset($_POST['_shipping_country']) ? sanitize_text_field($_POST['_shipping_country']) : '',



			'shipping_state'      => isset($_POST['_shipping_state']) ? sanitize_text_field($_POST['_shipping_state']) : '',



			'shipping_city'       => isset($_POST['_shipping_city']) ? sanitize_text_field($_POST['_shipping_city']) : '',



			'shipping_zip'        => isset($_POST['_shipping_postcode']) ? sanitize_text_field($_POST['_shipping_postcode']) : '',



			'shipping_phone'      => isset($_POST['_billing_phone']) ? sanitize_text_field($_POST['_billing_phone']) : '',



			'shipping_fullname'   => (isset($_POST['_shipping_first_name']) ? sanitize_text_field($_POST['_shipping_first_name']) : '') . ' ' . (isset($_POST['_shipping_last_name']) ? sanitize_text_field($_POST['_shipping_last_name']) : ''),







			'billing_address'     => isset($_POST['_billing_address_1']) ? sanitize_text_field($_POST['_billing_address_1']) : '',



			'billing_country'     => isset($_POST['_billing_country']) ? sanitize_text_field($_POST['_billing_country']) : '',



			'billing_state'       => isset($_POST['_billing_state']) ? sanitize_text_field($_POST['_billing_state']) : '',



			'billing_city'        => isset($_POST['_billing_city']) ? sanitize_text_field($_POST['_billing_city']) : '',



			'billing_zip'         => isset($_POST['_billing_postcode']) ? sanitize_text_field($_POST['_billing_postcode']) : '',



			'billing_phone'       => isset($_POST['_billing_phone']) ? sanitize_text_field($_POST['_billing_phone']) : '',



			'billing_fullname'    => (isset($_POST['_billing_first_name']) ? sanitize_text_field($_POST['_billing_first_name']) : '') . ' ' . (isset($_POST['_billing_last_name']) ? sanitize_text_field($_POST['_billing_last_name']) : ''),



			'billing_email'       => isset($_POST['_billing_email']) ? sanitize_email($_POST['_billing_email']) : '',







			// These are read from the order, not editable in admin UI



			'payment_mode'        => $order->get_payment_method_title() ?: '',



			'transaction_id'      => $order->get_transaction_id() ?: '',



			'transaction_status'  => $order->get_status() ?: '',



		];



		$oex = [];



		foreach ($before as $key => $from_value) {



			$oex[$key] = [



				'from' => $from_value,



				'to'   => $after[$key],



			];



		}



		$current_user = wp_get_current_user();



		$tfs = [



			'transaction_type'   => 'Purchase',



			'email'              => $current_user->user_email,    



			'first_name'         => $current_user->first_name,



			'last_name'          => $current_user->last_name,



			'username'           => $current_user->user_login,



			'user_id'            => $current_user->ID,



			'payment_mode'       => $after['payment_mode'],



			'payment_provider'   => $order->get_payment_method(), // e.g., "paypal", "stripe"



			'card_fullname'      => '', // Placeholder



			'card_bin'           => '',



			'card_expire'        => '',



			'card_last'          => '',



			'cvv'                => '',



			'phone_no'           => $after['billing_phone'],



			'transaction_amount' => $order->get_total(),



			'transaction_currency' => $order->get_currency(),



			'items' => [],



			'shipping_method'    => $order->get_shipping_method(),



			'merchant_name'      => '',



			'merchant_category'  => '',



			'merchant_id'        => '', // You can use site ID or static



			'merchant_country'   => get_option('woocommerce_default_country'),



			'order_id' => $order_id,



		];



		foreach ($order->get_items() as $item) {



			$product = $item->get_product();



			// Default



			$category_names = [];



			if ($product) {



				// Get all categories (terms) assigned to this product



				$terms = get_the_terms($product->get_id(), 'product_cat');



				if (!empty($terms) && !is_wp_error($terms)) {



					foreach ($terms as $term) {



						// Include full parent hierarchy like: "Parent > Child"



						$full_category = [];



						$current_term = $term;



						while ($current_term->parent != 0) {



							$parent = get_term($current_term->parent, 'product_cat');



							if (!is_wp_error($parent)) {



								array_unshift($full_category, $parent->name);



								$current_term = $parent;



							} else {



								break;



							}



						}



						$full_category[] = $term->name;



						$category_names[] = implode(',', $full_category);



					}



				}



			}



			$tfs['items'][] = [



				'item_id'      => $product ? $product->get_id() : '',



				'item_name'    => $item->get_name(),



				'item_category'=> implode(',', $category_names),



				'item_quantity'=> $item->get_quantity(),



				'item_price'   => $item->get_total(),



				'item_url'     => $product ? get_permalink($product->get_id()) : '',



			];



		}



		$payload = [



			'oex' => $oex,



			'tfs' => $tfs,



		];



		$device_id = null;



		if (empty($device_id)) {



			$device_id = null;



			$device_id_1 = null;



			$device_id_2 = null;



			$device_id_3 = null;



			$device_id_4 = null;



			$res_bot = null;



			if (isset($_COOKIE['device0'])) {   



				$device_id_1 = sanitize_text_field($_COOKIE['device0']);



			} 



			if (isset($_COOKIE['device1'])) {   



				$device_id_2 = sanitize_text_field($_COOKIE['device1']);



			}  



			if (isset($_COOKIE['device2'])) {   



				$device_id_3 = sanitize_text_field($_COOKIE['device2']);



			}  



			if (isset($_COOKIE['device3'])) {   



				$device_id_4 = sanitize_text_field($_COOKIE['device3']);



			}   



			$device_id = $device_id_1 . $device_id_2 . $device_id_3 . $device_id_4;



			if ( empty($device_id) ) {



				$device_id = null;



			} 



		}



		$options = get_option('sensfrx_options', SensFRX::default_options());



		$sensfrx_policy_options = get_option('sensfrx_policy_options', SensFRX::default_policy_options());



		require_once(SENSFRX_DIR . 'sensfrx-php-sdk/SensFRX/autoload.php');



		$obj = array();



		if (isset($options['sensfrx_property_id']) && isset($options['sensfrx_property_secret'])) {



			$obj = new SensFRX\SensFRX([



				'property_id' => $options['sensfrx_property_id'],



				'property_secret' => $options['sensfrx_property_secret']



			]);



		}



		$obj = new SensFRX\SensFRX([



			'property_id' => $options['sensfrx_property_id'],



			'property_secret' => $options['sensfrx_property_secret']



		]);		



		$res = $obj->orderUpdate('order_update', $oex, $device_id, $tfs);



	if (isset($res) && gettype($res) !== 'string') {	



		$res_shadow = SensFRX_DB_Helper::safe_select(

			'sensfrx_shadow_activity',

			'sensfrx_shadow_status',

			'',

			array(),

			'',

			ARRAY_A

		);



		if (is_array($res_shadow) && !empty($res_shadow) && isset($res_shadow[0]['sensfrx_shadow_status'])) {



				if ( '0' == $res_shadow[0]['sensfrx_shadow_status'] ) {



					if (isset($res['status']) && null !== $res['status'] && isset($res['severity']) && null !== $res['severity']) {



						$status = $res['status'];



						$severity = $res['severity'];



						if($status == 'allow') {



							$sensfrx_approve = 'approved';



						} else if ( $status == 'challenge') {



							$sensfrx_approve = 'on hold';



						} else {



							$sensfrx_approve = $status;



						}



						$site_title = get_bloginfo( 'name' );



						/* The above code is checking the value of the variable . If the value is truthy



						(evaluates to true), it sets  to true. Otherwise, it sets  to false. */



						$checkbox_allow = $sensfrx_policy_options['sensfrx_allow_payment_email'];



						if ($checkbox_allow) {



							$checkbox_allow = true;



						} else {



							$checkbox_allow = false;



						}



						$checkbox_challenge = $sensfrx_policy_options['sensfrx_challenge_payment_email'];



						if ($checkbox_challenge) {



							$checkbox_challenge = true;



						} else { 



							$checkbox_challenge = false;



						}



						$checkbox_deny = $sensfrx_policy_options['sensfrx_deny_payment_email'];



						if ($checkbox_deny) {



							$checkbox_deny = true;



						} else { 



							$checkbox_deny = false;



						}



						$lost_pass_url = wp_lostpassword_url();



						$device = $res['device'];



						$device = (array) $device;



						if ( 'allow' == $status && 'medium' == $severity ) {



							$lost_pass_url = wp_lostpassword_url();



							$device = $res['device'];



							$device = (array) $device;



							if ( empty($device) ) {



								$device['ip'] = 'NA';



							}



							$to = $email;



							global $wpdb;



							$template_trans_medium_after = 'Trans_medium_severity_Mail_Send_succeeded 123';



							$table_name = esc_sql( $wpdb->prefix . 'sensfrx_email_templates' );



							$template_medium_after_trans = $wpdb->get_row(



								$wpdb->prepare(

									// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is sanitized with esc_sql(). WHERE value is properly prepared with %s placeholder.

									"SELECT * FROM {$table_name} WHERE name1 = %s",



									$template_trans_medium_after



								)



							);



							if ($template_medium_after_trans) {



								$trans_medium_after_subject = $template_medium_after_trans->subject1;



								$trans_medium_after_message = $template_medium_after_trans->message1;



							} else {



								$trans_medium_after_subject = 'Default Subject';



								$trans_medium_after_message = 'Default Msesage';



							}



							$date = date('Y M d');



							$time = date('H:i:s');



							$allowurl = site_url() . '?as_did_1337575=' . $device['device_id'] . '&asda_ac=1';



							$denyurl = site_url() . '?as_did_1337575=' . $device['device_id'] . '&asda_ac=0';



							$replacements = [



								'{$fullname}' => $first_name . ' ' . $last_name,



								'{$ip_address}' => $device['ip'],



								'{$location}' => $device['location'],



								'{$device_name}' => $device['name'],



								'{$time}' => $time,



								'{$date}' => $date,



								'{$amount}' => $Total_Expense,



								'{$default_brand_name}' => $site_title,



							];



							$subject = strtr($trans_medium_after_subject, $replacements);



							$message = strtr($trans_medium_after_message, $replacements);



							$headers = array('Content-Type: text/html; charset=UTF-8');



							$user_email_ato = $current_user->user_email;



							$insert_data = $user_email_ato . " attempted to update Order #" . $order_id . ". The update was " . $sensfrx_approve . " due to a risk score level of " . $severity . ".";



							SensFRX_DB_Helper::insert_activity_log('Order Update', $insert_data);



						} 



						if ( 'challenge' == $status && 'high' == $severity ) {



							$lost_pass_url = wp_lostpassword_url();



							$device = $res['device'];



							$device = (array) $device;



							if ( empty($device) ) {



								$device['ip'] = 'NA';



							}



							$to = $email;



							global $wpdb;



							$template_trans_after_challenge = 'Trans_challenge_severity_Mail_Send_succeeded 123';



							$table_name = esc_sql( $wpdb->prefix . 'sensfrx_email_templates' );



							$template_challenge_trans_after = $wpdb->get_row(



								$wpdb->prepare(

									// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is sanitized with esc_sql(). WHERE value is properly prepared with %s placeholder.

									"SELECT * FROM {$table_name} WHERE name1 = %s",



									$template_trans_after_challenge



								)



							);



							if ($template_challenge_trans_after) {



								$trans_after_challenge_subject = $template_challenge_trans_after->subject1;



								$trans_after_challenge_message = $template_challenge_trans_after->message1;



							} else {



								$trans_after_challenge_subject = 'Default Subject';



								$trans_after_challenge_message = 'Default Msesage';



							}



							$date = date('Y M d');



							$time = date('H:i:s');



							$allowurl = site_url() . '?as_did_1337575=' . $device['device_id'] . '&asda_ac=1';



							$denyurl = site_url() . '?as_did_1337575=' . $device['device_id'] . '&asda_ac=0';



							$replacements = [



								'{$fullname}' => $first_name . ' ' . $last_name,



								'{$allow_url}' => $allowurl,



								'{$deny_url}' => $denyurl,



								'{$time}' => $time,



								'{$date}' => $date,



								'{$amount}' => $Total_Expense,



								'{$default_brand_name}' => $site_title,



							];



							$subject = strtr($trans_after_challenge_subject, $replacements);



							$message = strtr($trans_after_challenge_message, $replacements);



							$headers = array('Content-Type: text/html; charset=UTF-8');



							$user_email_ato = $current_user->user_email;



							$insert_data = $user_email_ato . " attempted to update Order #" . $order_id . ". The update was " . $sensfrx_approve . " due to a risk score level of " . $severity . ".";



							SensFRX_DB_Helper::insert_activity_log('Order Update', $insert_data);



							$order = wc_get_order($order_id);



							$order->update_status('on-hold', 'Sensfrx - Order placed on hold due to detected issues.');



							wp_die('⚠️ The order update has been flagged for manual review. Please verify the provided information carefully before proceeding or contact your site administrator for further guidance.', 'Order Update Denied', ['back_link' => true]);



						} 



						if ('deny' == $status && 'critical' == $severity) {	



							$device = $res['device'];



							$device = (array) $device;



							$to = $email;



							global $wpdb;



							$template_trans_after_deny = 'Trans_deny_severity_Mail_Send_succeeded';



							$table_name =  esc_sql( $wpdb->prefix . 'sensfrx_email_templates' );



							$template_deny_trans_after = $wpdb->get_row(



								$wpdb->prepare(

									// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is sanitized with esc_sql(). WHERE value is properly prepared with %s placeholder.

									"SELECT * FROM {$table_name} WHERE name1 = %s",



									$template_trans_after_deny



								)



							);



							if ($template_deny_trans_after) {



								$trans_after_deny_subject = $template_deny_trans_after->subject1;



								$trans_after_deny_message = $template_deny_trans_after->message1;



							} else {



								$trans_after_deny_subject = 'Default Subject';



								$trans_after_deny_message = 'Default Msesage';



							}



							$date = date('Y M d');



							$time = date('H:i:s');



							$allowurl = site_url() . '?as_did_1337575=' . $device['device_id'] . '&asda_ac=1';



							$denyurl = site_url() . '?as_did_1337575=' . $device['device_id'] . '&asda_ac=0';



							$replacements = [



								'{$client_full_name}' => $first_name . ' ' . $last_name,



								'{$time}' => $time,



								'{$date}' => $date,



								'{$amount}' => $product_total,



								'{$default_brand_name}' => $site_title,



							];



							$subject = strtr($trans_after_deny_subject, $replacements);



							$message = strtr($trans_after_deny_message, $replacements);



							$headers = array('Content-Type: text/html; charset=UTF-8');



							$user_email_ato = $current_user->user_email;



							$insert_data = $user_email_ato . " attempted to update Order #" . $order_id . ". The update was " . $sensfrx_approve . " due to a risk score level of " . $severity . ".";



							SensFRX_DB_Helper::insert_activity_log('Order Update', $insert_data);



							$order = wc_get_order($order_id);



							$order->update_status('cancelled', 'Sensfrx - Order marked as cancelled due to fraudulent activity.');



							wp_die('⚠️ The order update was blocked due to a security validation check. Please review the changes and try again or contact your site administrator for assistance.', 'Order Update Denied', ['back_link' => true]);



						}



						if ( 'allow' == $status && 'low' == $severity ) {



							$user_email_ato = $current_user->user_email;



							$insert_data = $user_email_ato . " attempted to update Order #" . $order_id . ". The update was " . $sensfrx_approve . " due to a risk score level of " . $severity . ".";



							SensFRX_DB_Helper::insert_activity_log('Order Update', $insert_data);



						}



					} else {



						$user_email_ato = $current_user->user_email;



						$insert_data = $user_email_ato . " attempted to update Order #" . $order_id . ". Sensfrx encountered an error, so the order update was approved.";



						SensFRX_DB_Helper::insert_activity_log('Order Update', $insert_data);



					}	



				} else {



					$user_email_ato = $current_user->user_email;



					$insert_data = $user_email_ato . " attempted to update Order #" . $order_id . ". Sensfrx flagged the transaction with a " . $res['severity'] . " risk score. but since Shadow Mode was enabled, it was allowed.";



					SensFRX_DB_Helper::insert_activity_log('Order Update', $insert_data);



				}



			} else {



				$user_email_ato = $current_user->user_email;



				$insert_data = $user_email_ato . " attempted to update Order #" . $order_id . ". An error occurred while fetching Shadow Mode data.";



				SensFRX_DB_Helper::insert_activity_log('Order Update', $insert_data);



			} 



		} else {



			$user_email_ato = $current_user->user_email;



			$insert_data = $user_email_ato . " attempted to update Order #" . $order_id . ". However, Sensfrx returned an unformatted response, causing an issue.";



			SensFRX_DB_Helper::insert_activity_log('Order Update', $insert_data);



		}



	}



}



