<?php
if (! defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}
// Load email template class
if (! class_exists('SensFRX_email_template')) {
    require_once plugin_dir_path(__FILE__) . 'email-templates/class-sensfrx-email-template.php';
}
class SensFRX_Payment_Attempt
{
    public function payment_attempt($order_id, $posted_data, $order)
    {
        $sensfrx_policy_options = get_option('sensfrx_policy_options', SensFRX::default_policy_options());
        $sensfrx_before_payment_fraud_allow = $sensfrx_policy_options['sensfrx_before_payment_fraud'];
        if ($sensfrx_before_payment_fraud_allow) {
            $sensfrx_before_payment_fraud_allow = true;
        } else {
            $sensfrx_before_payment_fraud_allow = false;
        }
        if (true == $sensfrx_before_payment_fraud_allow) {
            if (is_user_logged_in()) {
                global $wpdb;
                $sensfrx_custom_matched_fields = [];
                $sensfrx_fetch_results_custom = SensFRX_DB_Helper::safe_select(
                    'sensfrx_custome_filed',
                    'id, sensfrx_custom_field',
                    '',
                    [],
                    '',
                    ARRAY_A
                );
                if (! empty($sensfrx_fetch_results_custom)) {
                    foreach ($sensfrx_fetch_results_custom as $row) {
                        // Sanitize expected field name from database
                        $expected_field = sanitize_key($row['sensfrx_custom_field']);
                        foreach ($_POST as $post_key => $post_value) {
                            // Sanitize POST key to prevent XSS injection
                            $sanitized_key = sanitize_key($post_key);
                            // Validate key format (alphanumeric, underscore, dash only)
                            if (! empty($sanitized_key) && $sanitized_key === $expected_field) {
                                // Sanitize POST value
                                $sanitized_value = is_array($post_value) ?
                                array_map('sanitize_text_field', $post_value) :
                                sanitize_text_field($post_value);
                                if (! empty($sanitized_value)) {
                                    // Use sanitized key, not original POST key
                                    array_push($sensfrx_custom_matched_fields, $sanitized_key);
                                }
                            }
                        }
                    }
                }
                $device_id = null;
                $device_id_1 = null;
                $device_id_2 = null;
                $device_id_3 = null;
                $device_id_4 = 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;
                }
                $cart = WC()->cart;
                // Get the shipping total
                $shipping_cost = $cart->get_shipping_total();
                $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 = [];
                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'],
                    ]);
                }
                $customer = WC()->customer;
                $username = $customer->get_username();
                $user_id = $customer->get_id();
                $first_name = $customer->get_first_name();
                $last_name = $customer->get_last_name();
                $email = $customer->get_email();
                $phone_number = WC()->customer->get_billing_phone();
                $formattedDate = gmdate('Y-F-d');
                $cart = WC()->cart;
                $product_total = $cart->get_total();
                // Remove the Indian Rupee symbol (₹) from the total value
                $total_value_without_rs = preg_replace('/[^\d.]/', '', $product_total);
                // Convert the modified total value to a numeric format (float)
                $total_float = (float) $total_value_without_rs;
                $total_array = str_split($total_float);
                // Remove the first,second,third and four value from the array
                $removedValue = array_shift($total_array);
                $removedValue = array_shift($total_array);
                // Convert array into string
                $total_price = implode('', $total_array);
                $current_user = wp_get_current_user();
                $user_login_id = $current_user->user_login;
                // Get current user IP and User Agent
                $customer_ip_address = WC_Geolocation::get_ip_address() ?: null;
                $customer_user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : null;
                // Access the WooCommerce cart
                $cart = WC()->cart;
                // Get payment method details
                $payment_method = WC()->session->get('chosen_payment_method') ?: null;
                $payment_method_title = $payment_method ? WC()->payment_gateways->payment_gateways()[$payment_method]->get_title() : null;
                // Billing details
                $b_country = WC()->customer->get_billing_country() ?: null;
                $b_state = WC()->customer->get_billing_state() ?: null;
                $b_city = WC()->customer->get_billing_city() ?: null;
                $b_fname = WC()->customer->get_billing_first_name() ?: null;
                $b_lname = WC()->customer->get_billing_last_name() ?: null;
                $b_company = WC()->customer->get_billing_company() ?: null;
                $b_address1 = isset($_POST['billing_address_1']) ? sanitize_text_field($_POST['billing_address_1']) : null;
                $b_address2 = isset($_POST['billing_address_2']) ? sanitize_text_field($_POST['billing_address_2']) : null;
                $b_phone_number = isset($_POST['billing_phone']) ? sanitize_text_field($_POST['billing_phone']) : null;
                $b_email = WC()->customer->get_billing_email() ?: null;
                $b_zipcode = WC()->customer->get_billing_postcode() ?: null;
                // Shipping details
                $sh_fname        = $this->sensfrx_safe_shipping_field($order, '_shipping_first_name', 'get_shipping_first_name');
                $sh_lname        = $this->sensfrx_safe_shipping_field($order, '_shipping_last_name', 'get_shipping_last_name');
                $sh_company      = $this->sensfrx_safe_shipping_field($order, '_shipping_company', 'get_shipping_company');
                $sh_address1     = $this->sensfrx_safe_shipping_field($order, '_shipping_address_1', 'get_shipping_address_1');
                $sh_address2     = $this->sensfrx_safe_shipping_field($order, '_shipping_address_2', 'get_shipping_address_2');
                $sh_city         = $this->sensfrx_safe_shipping_field($order, '_shipping_city', 'get_shipping_city');
                $sh_state        = $this->sensfrx_safe_shipping_field($order, '_shipping_state', 'get_shipping_state');
                $sh_country      = $this->sensfrx_safe_shipping_field($order, '_shipping_country', 'get_shipping_country');
                $sh_phone_number = $this->sensfrx_safe_shipping_field($order, '_shipping_phone', 'get_shipping_phone');
                $sh_zipcode      = $this->sensfrx_safe_shipping_field($order, '_shipping_postcode', 'get_shipping_postcode');
                // Get shipping method
                $shipping_methods = WC()->session->get('chosen_shipping_methods');
                // $shipping_method = isset($shipping_methods[0]) ? $shipping_methods[0] : null;
                $chosen_rate_id = !empty($shipping_methods) && isset($shipping_methods[0]) ? $shipping_methods[0] : null;
                $shipping_method = null;
                $shipping_packages = WC()->shipping()->get_packages();
                $shipping_rates = !empty($shipping_packages) && isset($shipping_packages[0]['rates']) ? $shipping_packages[0]['rates'] : array();
                if (isset($shipping_rates[$chosen_rate_id])) {
                    $shipping_method = $shipping_rates[$chosen_rate_id]->get_label(); // "Same Day Delivery"
                }
                // Order details
                $currency = get_woocommerce_currency();
                $total_price = $cart->get_total('edit'); // Total amount
                $order_key = uniqid('order_'); // You can use this as a temporary key before the order is created
                $payment_date = current_time('mysql'); // Current time as payment date
                $date_paid = ''; // Not available until payment is confirmed
                $transaction_id = get_post_meta($order_id, '_sensfrx_trans_id', true);
                if (empty($transaction_id)) {
                    $transaction_id = uniqid();
                    update_post_meta($order_id, '_sensfrx_trans_id', $transaction_id);
                }
                // Get coupon codes
                $applied_coupons = $cart->get_applied_coupons();
                $coupon_code = ! empty($applied_coupons) ? implode(', ', $applied_coupons) : null;
                // Get discount details
                $discount_amount = $cart->get_discount_total() ?: null;
                $currency = get_woocommerce_currency() ?: null;
                $transaction_currency = $currency; // Assuming it's the same as order currency
                $item_p = [];
                $item_s = [];
                foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
                    $product_id = $cart_item['product_id'];
                    $product = wc_get_product($product_id);
                    $product_name = $product->get_name();
                    $product_price = $product->get_price();
                    $product_type = get_the_terms($product_id, 'product_tag');
                    // adding item type
                    $item_type = null;
                    foreach ($order->get_items() as $order_item) {
                        if ($order_item->get_product_id() === $product_id) {
                            $item_type = $order_item->get_meta('product_type');
                            break;
                        }
                    }
                    $tag_names = [];
                    $tag_names_string = null;
                    if ($product_type && ! is_wp_error($product_type)) {
                        foreach ($product_type as $tag) {
                            $tag_names[] = $tag->name;
                        }
                    }
                    if (! empty($sensfrx_fetch_results_custom)) {
                        foreach ($sensfrx_fetch_results_custom as $row) {
                            foreach ($tag_names as $woo_tag) {
                                if ($woo_tag === $row['sensfrx_custom_field']) {
                                    $tag_names_string .= ',' . $woo_tag;
                                }
                            }
                        }
                    }
                    $quantity = $cart_item['quantity'];
                    $terms = wp_get_post_terms($product_id, 'product_cat');
                    $category_slugs = [];
                    foreach ($terms as $term) {
                        $category_slugs = array_merge($category_slugs, $this->get_category_ancestors($term));
                    }
                    $category_slugs = array_unique($category_slugs);
                    $product_categories = implode(',', $category_slugs);
                    $product_categories = $product_categories . $tag_names_string;
                    $item_p = [
                        'item_name'     => $product_name,
                        'item_price'    => $product_price,
                        'item_id'       => $product_id,
                        'item_quantity' => $quantity,
                        'item_category' => $product_categories,
                        'item_type'     => $item_type,
                    ];
                    array_push($item_s, $item_p);
                }
                $all_sensfrx_custom_matched_fields = array_unique($sensfrx_custom_matched_fields);
                $sensfrx_custom_matched_fields_string = implode(',', $all_sensfrx_custom_matched_fields);
                if ($sensfrx_custom_matched_fields_string) {
                    foreach ($item_s as &$item) {
                        $item['item_category'] .= ',' . $sensfrx_custom_matched_fields_string;
                    }
                }
                $user = get_userdata($user_id); // Replace $user_id with actual ID
                $created_at = ($user && isset($user->user_registered)) ? $user->user_registered : ''; // This returns in 'Y-m-d H:i:s' format (UTC)
                $transactionExtras = [
                    'email'                => $email,
                    'first_name'           => $first_name,
                    'last_name'            => $last_name,
                    'user_id'              => $user_id,
                    'username'             => $username,
                    'transaction_type'     => 'purchase',
                    'transaction_amount'   => $total_price,
                    'phone_no'             => $phone_number,
                    'transaction_id'       => $transaction_id,
                    'items'                => wp_json_encode($item_s),
                    'shipping_cost'        => $shipping_cost,
                    'order_id'             => $order_id, // Not available at this stage
                    'payment_status'       => '', // Not available at this stage
                    'currency'             => $currency,
                    'transaction_currency' => $transaction_currency, // This might be the same as $currency, depending on the gateway
                    'payment_date'         => '',
                    'total_amount'         => $total_price,
                    'order_key'            => '',
                    'payment_mode'         => $payment_method,
                    'payment_provider'     => $payment_method_title,
                    'customer_ip_address'  => $customer_ip_address,
                    'customer_user_agent'  => $customer_user_agent,
                    'date_paid'            => '',
                    'billing_country'      => $b_country,
                    'billing_state'        => $b_state,
                    'billing_city'         => $b_city,
                    'billing_fullname'     => $b_fname . ' ' . $b_lname,
                    'billing_company'      => $b_company,
                    'billing_address'      => $b_address1 . ' ' . $b_address2,
                    'billing_email'        => $b_email,
                    'billing_zip'          => $b_zipcode,
                    'billing_phone'        => $b_phone_number,
                    'shipping_country'     => $sh_country,
                    'shipping_state'       => $sh_state,
                    'shipping_city'        => $sh_city,
                    'shipping_fullname'    => $sh_fname . ' ' . $sh_lname,
                    'shipping_company'     => $sh_company,
                    'shipping_address'     => $sh_address1 . ' ' . $sh_address2,
                    'shipping_zip'         => $sh_zipcode,
                    'shipping_phone'       => $sh_phone_number,
                    'shipping_method'      => $shipping_method,
                    'discount_amount'      => $discount_amount,
                    'coupon_code'          => $coupon_code,
                    'user_created_at'      => $created_at,
                ];
                global $wpdb;
                $sensfrx_approve = null;
                $sensfrx_master_fraud_allow = $sensfrx_policy_options['sensfrx_master_fraud'];
                if ($sensfrx_master_fraud_allow) {
                    $sensfrx_master_fraud_allow = true;
                } else {
                    $sensfrx_master_fraud_allow = false;
                }
                if (true == $sensfrx_master_fraud_allow) {
                    $sensfrx_before_payment_allow = $sensfrx_policy_options['sensfrx_before_payment_fraud'];
                    if ($sensfrx_before_payment_allow) {
                        $sensfrx_before_payment_allow = true;
                    } else {
                        $sensfrx_before_payment_allow = false;
                    }
                    if (true == $sensfrx_before_payment_allow) {
                        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'],
                            ]);
                            $res = $obj->transactionAttempt('attempt_succeeded', $device_id, $transactionExtras);
                            // Administrator Access Approved
                            $sensfrx_whitelisting_check = null;
                            $sensfrx_whitelisting_check_email = $email;
                            $sensfrx_white_list_admin_users = get_users(['role' => 'administrator']);
                            $sensfrx_white_list_admin_info_array = [];
                            foreach ($sensfrx_white_list_admin_users as $user_data) {
                                if ($user_data->user_email === $sensfrx_whitelisting_check_email) {
                                    $sensfrx_whitelisting_check = true;
                                    break;
                                }
                            }
                            $sensfrx_whitelisting_check_checkbox_allow = $sensfrx_policy_options['sensfrx_whitle_list_email'];
                            if ($sensfrx_whitelisting_check_checkbox_allow) {
                                $sensfrx_whitelisting_check_checkbox_allow = true;
                            } else {
                                $sensfrx_whitelisting_check_checkbox_allow = false;
                            }
                            if (true === $sensfrx_whitelisting_check && true === $sensfrx_whitelisting_check_checkbox_allow) {
                                return;
                            } else {
                                if (isset($res) && gettype($res) !== 'string') {
                                    if (isset($res['status']) && $res['status'] === 'error' && $res['error'] === 'USE_CASE_DISABLED') {
                                        $errorMessage = $res['message'] ?? 'Something went wrong';
                                        $insert_data  = "Order #" . $order_id . " | " . $email . " | Transaction approved | Reason: " . $errorMessage;
                                        SensFRX_DB_Helper::insert_activity_log('Transaction (Before Payment)', $insert_data);
                                    } else {
                                        $res_shadow = SensFRX_DB_Helper::safe_select(
                                            'sensfrx_shadow_activity',
                                            'sensfrx_shadow_status',
                                            '',
                                            [],
                                            '',
                                            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' || $status == 'low') {
                                                        $sensfrx_approve = 'approved';
                                                    } else if ($status == 'challenge') {
                                                        $sensfrx_approve = 'on-hold';
                                                    } else {
                                                        $sensfrx_approve = $status;
                                                    }
                                                    $site_title = get_bloginfo('name');
                                                    $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;
                                                    }
                                                    if ('allow' == $status && 'medium' == $severity) {
                                                        if (true == $checkbox_allow) {
                                                            $device = $res['device'];
                                                            $device = (array) $device;
                                                            $to = $email;
                                                            // Get default email content (no database customization)
                                                            $default_email        = SensFRX_email_template::get_default_message('transaction_allow');
                                                            $trans_medium_subject = $default_email['subject'];
                                                            $trans_medium_message = $default_email['message'];
                                                            $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}'             => $product_total,
                                                                '{$default_brand_name}' => $site_title,
                                                            ];
                                                            // Use universal email wrapper for professional formatting
                                                            $mailResult = SensFRX_email_template::wrap_and_send($to, $trans_medium_subject, $trans_medium_message, $site_title, $replacements);
                                                            $insert_data = "Order #" . $order_id . " | " . $email . " | Transaction " . $sensfrx_approve . " | Risk: " . $severity;
                                                            SensFRX_DB_Helper::insert_activity_log('Transaction (Before Payment)', $insert_data);
                                                        } else {
                                                            $insert_data = "Order #" . $order_id . " | " . $email . " | Transaction approved (Allow policy off) | Risk: " . $severity;
                                                            SensFRX_DB_Helper::insert_activity_log('Transaction (Before Payment)', $insert_data);
                                                        }
                                                    }
                                                    if ('challenge' == $status && 'high' == $severity) {
                                                        if (true == $checkbox_challenge) {
                                                            $device = $res['device'];
                                                            $device = (array) $device;
                                                            $to = $email;
                                                            // Get default email content (no database customization)
                                                            $default_email           = SensFRX_email_template::get_default_message('transaction_challenge');
                                                            $trans_challenge_subject = $default_email['subject'];
                                                            $trans_challenge_message = $default_email['message'];
                                                            $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}'             => $product_total,
                                                                '{$default_brand_name}' => $site_title,
                                                            ];
                                                            // Use universal email wrapper for professional formatting
                                                            $mailResult = SensFRX_email_template::wrap_and_send($to, $trans_challenge_subject, $trans_challenge_message, $site_title, $replacements);
                                                            $insert_data = "Order #" . $order_id . " | " . $email . " | Transaction " . $sensfrx_approve . " | Risk: " . $severity;
                                                            SensFRX_DB_Helper::insert_activity_log('Transaction (Before Payment)', $insert_data);
                                                            $order->update_status('pending', __('Sensfrx - On hold due to fraud detection by Sensfrx', 'Sensfrx'));
                                                            $table_name_shadow_table = esc_sql($wpdb->prefix . 'sensfrx_pre_payment_order');
                                                            $existing_record = $wpdb->get_var(
                                                                $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_shadow_table} WHERE pre_order_id = %s",
                                                                    $order_id
                                                                )
                                                            );
                                                            if ($existing_record == 0) {
                                                                $data = [
                                                                    'pre_order_id' => $order_id,
                                                                ];
                                                                $results = $wpdb->insert($table_name_shadow_table, $data);
                                                            }
                                                            throw new Exception('Sensfrx - We have detected unusual activity with your recent transaction, and as a precautionary measure, your order status has been temporarily placed On Hold.');
                                                            // throw new Exception('Sensfrx - We have detected unusual activity with your recent transaction, and as a precautionary measure, We cannot proceed with processing your order at this time due to detected unusual activity. Please try again later.');
                                                        } else {
                                                            $insert_data = "Order #" . $order_id . " | " . $email . " | Transaction approved (Challenge policy off) | Risk: " . $severity;
                                                            SensFRX_DB_Helper::insert_activity_log('Transaction (Before Payment)', $insert_data);
                                                        }
                                                    }
                                                    if ('deny' == $status && 'critical' == $severity) {
                                                        if (true == $checkbox_deny) {
                                                            $device = $res['device'];
                                                            $device = (array) $device;
                                                            $to = $email;
                                                            // Get default email content (no database customization)
                                                            $default_email      = SensFRX_email_template::get_default_message('transaction_deny');
                                                            $trans_deny_subject = $default_email['subject'];
                                                            $trans_deny_message = $default_email['message'];
                                                            $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,
                                                                '{$fullname}'           => $first_name . ' ' . $last_name,
                                                                '{$time}'               => $time,
                                                                '{$date}'               => $date,
                                                                '{$amount}'             => $product_total,
                                                                '{$default_brand_name}' => $site_title,
                                                            ];
                                                            $subject = strtr($trans_deny_subject, $replacements);
                                                            // Use universal email wrapper for professional formatting
                                                            $mailResult = SensFRX_email_template::wrap_and_send($to, $trans_deny_subject, $trans_deny_message, $site_title, $replacements);
                                                            $current_user = wp_get_current_user();
                                                            $results = retrieve_password($current_user->user_login);
                                                            $order->update_status('cancelled', __('Sensfrx - Cancelled due to fraud detection by Sensfrx', 'Sensfrx'));
                                                            $insert_data = "Order #" . $order_id . " | " . $email . " | Transaction " . $sensfrx_approve . " | Risk: " . $severity;
                                                            SensFRX_DB_Helper::insert_activity_log('Transaction (Before Payment)', $insert_data);
                                                            throw new Exception('Sensfrx - We have detected suspicious activity with your recent transaction. As a precaution, we cannot proceed with processing your order at this time. Please try again later.');
                                                        } else {
                                                            $insert_data = "Order #" . $order_id . " | " . $email . " | Transaction approved (Deny policy off) | Risk: " . $severity;
                                                            SensFRX_DB_Helper::insert_activity_log('Transaction (Before Payment)', $insert_data);
                                                        }
                                                    }
                                                    if ('allow' == $status && 'low' == $severity) {
                                                        global $wpdb;
                                                        $insert_data = "Order #" . $order_id . " | " . $email . " | Transaction " . $sensfrx_approve . " | Risk: " . $severity;
                                                        SensFRX_DB_Helper::insert_activity_log('Transaction (Before Payment)', $insert_data);
                                                    }
                                                } else {
                                                    $insert_data = "Order #" . $order_id . " | " . $email . " | Transaction approved | Reason: API error fallback";
                                                    SensFRX_DB_Helper::insert_activity_log('Transaction (Before Payment)', $insert_data);
                                                }
                                            } else {
                                                $insert_data = "Order #" . $order_id . " | " . $email . " | Transaction allowed (Shadow Mode) | Risk: " . $res['severity'];
                                                SensFRX_DB_Helper::insert_activity_log('Transaction (Before Payment)', $insert_data);
                                            }
                                        } else {
                                            $insert_data = "Order #" . $order_id . " | " . $email . " | Transaction error | Reason: Shadow Mode data fetch failed";
                                            SensFRX_DB_Helper::insert_activity_log('Transaction (Before Payment)', $insert_data);
                                        }
                                    }
                                } else {
                                    $insert_data = "Order #" . $order_id . " | " . $email . " | Transaction error | Reason: Unformatted API response";
                                    SensFRX_DB_Helper::insert_activity_log('Transaction (Before Payment)', $insert_data);
                                }
                            }
                        }
                    }
                }
            } else {
                $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 = [];
                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'],
                    ]);
                }
                global $wpdb;
                $sensfrx_custom_matched_fields = [];
                $sensfrx_fetch_results_custom = SensFRX_DB_Helper::safe_select(
                    'sensfrx_custome_filed',
                    'id, sensfrx_custom_field',
                    '',
                    [],
                    '',
                    ARRAY_A
                );
                if (! empty($sensfrx_fetch_results_custom)) {
                    foreach ($sensfrx_fetch_results_custom as $row) {
                        // Sanitize expected field name from database
                        $expected_field = sanitize_key($row['sensfrx_custom_field']);
                        foreach ($_POST as $post_key => $post_value) {
                            // Sanitize POST key to prevent XSS injection
                            $sanitized_key = sanitize_key($post_key);
                            // Validate key format (alphanumeric, underscore, dash only)
                            if (! empty($sanitized_key) && $sanitized_key === $expected_field) {
                                // Sanitize POST value
                                $sanitized_value = is_array($post_value) ?
                                array_map('sanitize_text_field', $post_value) :
                                sanitize_text_field($post_value);
                                if (! empty($sanitized_value)) {
                                    // Use sanitized key, not original POST key
                                    array_push($sensfrx_custom_matched_fields, $sanitized_key);
                                }
                            }
                        }
                    }
                }
                $device_id = null;
                $device_id_1 = null;
                $device_id_2 = null;
                $device_id_3 = null;
                $device_id_4 = 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;
                }
                $cart = WC()->cart;
                $payment_method = WC()->session->get('chosen_payment_method') ?: null;
                $payment_method_title = $payment_method ? WC()->payment_gateways->payment_gateways()[$payment_method]->get_title() : null;
                $shipping_methods = WC()->session->get('chosen_shipping_methods');
                // $shipping_method = isset($shipping_methods[0]) ? $shipping_methods[0] : null;
                $chosen_rate_id = !empty($shipping_methods) && isset($shipping_methods[0]) ? $shipping_methods[0] : null;
                $shipping_method = null;
                $shipping_packages = WC()->shipping()->get_packages();
                $shipping_rates = !empty($shipping_packages) && isset($shipping_packages[0]['rates']) ? $shipping_packages[0]['rates'] : array();
                if (isset($shipping_rates[$chosen_rate_id])) {
                    $shipping_method = $shipping_rates[$chosen_rate_id]->get_label(); // "Same Day Delivery"
                }
                $currency = get_woocommerce_currency() ?: null;
                $transaction_currency = $currency; // Assuming it's the same as order currency
                $product_total = $cart->get_total();
                $total_value_without_rs = preg_replace('/[^\d.]/', '', $product_total);
                $total_float = (float) $total_value_without_rs;
                $total_array = str_split($total_float);
                $removedValue = array_shift($total_array);
                $removedValue = array_shift($total_array);
                $total_price = implode('', $total_array);
                $formattedDate = gmdate('Y-F-d');
                $transaction_id = get_post_meta($order_id, '_sensfrx_trans_id', true);
                if (empty($transaction_id)) {
                    $transaction_id = uniqid();
                    update_post_meta($order_id, '_sensfrx_trans_id', $transaction_id);
                }
                $applied_coupons = $cart->get_applied_coupons();
                $coupon_code = ! empty($applied_coupons) ? implode(', ', $applied_coupons) : null;
                $discount_amount = $cart->get_discount_total() ?: null;
                $shipping_cost = $cart->get_shipping_total();
                $customer_ip_address = WC_Geolocation::get_ip_address() ?: null;
                $customer_user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : null;
                // Billing details
                $b_fname = isset($_POST['billing_first_name']) ? sanitize_text_field($_POST['billing_first_name']) : null;
                $b_lname = isset($_POST['billing_last_name']) ? sanitize_text_field($_POST['billing_last_name']) : null;
                $b_company = isset($_POST['billing_company']) ? sanitize_text_field($_POST['billing_company']) : null;
                $b_address1 = isset($_POST['billing_address_1']) ? sanitize_text_field($_POST['billing_address_1']) : null;
                $b_address2 = isset($_POST['billing_address_2']) ? sanitize_text_field($_POST['billing_address_2']) : null;
                $b_city = isset($_POST['billing_city']) ? sanitize_text_field($_POST['billing_city']) : null;
                $b_zipcode = isset($_POST['billing_postcode']) ? sanitize_text_field($_POST['billing_postcode']) : null;
                $b_country = isset($_POST['billing_country']) ? sanitize_text_field($_POST['billing_country']) : null;
                $b_state = isset($_POST['billing_state']) ? sanitize_text_field($_POST['billing_state']) : null;
                $b_email = isset($_POST['billing_email']) ? sanitize_email($_POST['billing_email']) : null;
                $b_phone_number = isset($_POST['billing_phone']) ? sanitize_text_field($_POST['billing_phone']) : null;
                // Shipping details
                $sh_fname        = $this->sensfrx_safe_shipping_field($order, 'shipping_first_name', 'get_shipping_first_name');
                $sh_lname        = $this->sensfrx_safe_shipping_field($order, 'shipping_last_name', 'get_shipping_last_name');
                $sh_company      = $this->sensfrx_safe_shipping_field($order, 'shipping_company', 'get_shipping_company');
                $sh_address1     = $this->sensfrx_safe_shipping_field($order, 'shipping_address_1', 'get_shipping_address_1');
                $sh_address2     = $this->sensfrx_safe_shipping_field($order, 'shipping_address_2', 'get_shipping_address_2');
                $sh_city         = $this->sensfrx_safe_shipping_field($order, 'shipping_city', 'get_shipping_city');
                $sh_state        = $this->sensfrx_safe_shipping_field($order, 'shipping_state', 'get_shipping_state');
                $sh_country      = $this->sensfrx_safe_shipping_field($order, 'shipping_country', 'get_shipping_country');
                $sh_zipcode      = $this->sensfrx_safe_shipping_field($order, 'shipping_postcode', 'get_shipping_postcode');
                $sh_phone_number = $this->sensfrx_safe_shipping_field($order, 'shipping_phone'); // custom field
                $item_p = [];
                $item_s = [];
                foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
                    $product_id = $cart_item['product_id'];
                    $product = wc_get_product($product_id);
                    $product_name = $product->get_name();
                    $product_price = $product->get_price();
                    $product_type = get_the_terms($product_id, 'product_tag');
                    $item_type = null;
                    foreach ($order->get_items() as $order_item) {
                        if ($order_item->get_product_id() === $product_id) {
                            $item_type = $order_item->get_meta('product_type');
                            break;
                        }
                    }
                    $tag_names = [];
                    $tag_names_string = null;
                    if ($product_type && ! is_wp_error($product_type)) {
                        foreach ($product_type as $tag) {
                            $tag_names[] = $tag->name;
                        }
                    }
                    if (! empty($sensfrx_fetch_results_custom)) {
                        foreach ($sensfrx_fetch_results_custom as $row) {
                            foreach ($tag_names as $woo_tag) {
                                if ($woo_tag === $row['sensfrx_custom_field']) {
                                    $tag_names_string .= ',' . $woo_tag;
                                }
                            }
                        }
                    }
                    $quantity = $cart_item['quantity'];
                    $terms = wp_get_post_terms($product_id, 'product_cat');
                    $category_slugs = [];
                    foreach ($terms as $term) {
                        $category_slugs = array_merge($category_slugs, $this->get_category_ancestors($term));
                    }
                    $category_slugs = array_unique($category_slugs);
                    $product_categories = implode(',', $category_slugs);
                    $product_categories = $product_categories . $tag_names_string;
                    $item_p = [
                        'item_name'     => $product_name,
                        'item_price'    => $product_price,
                        'item_id'       => $product_id,
                        'item_quantity' => $quantity,
                        'item_category' => $product_categories,
                        'item_type'     => $item_type,
                    ];
                    array_push($item_s, $item_p);
                }
                $all_sensfrx_custom_matched_fields = array_unique($sensfrx_custom_matched_fields);
                $sensfrx_custom_matched_fields_string = implode(',', $all_sensfrx_custom_matched_fields);
                if ($sensfrx_custom_matched_fields_string) {
                    foreach ($item_s as &$item) {
                        $item['item_category'] .= ',' . $sensfrx_custom_matched_fields_string;
                    }
                }
                $transactionExtras = [
                    'email'                => $b_email,
                    'first_name'           => $b_fname,
                    'last_name'            => $b_lname,
                    'user_id'              => '',
                    'username'             => '',
                    'transaction_type'     => 'purchase',
                    'transaction_amount'   => $total_price,
                    'phone_no'             => '',
                    'transaction_id'       => $transaction_id,
                    'items'                => wp_json_encode($item_s),
                    'shipping_cost'        => $shipping_cost,
                    'order_id'             => $order_id, // Not available at this stage
                    'payment_status'       => '', // Not available at this stage
                    'currency'             => $currency,
                    'transaction_currency' => $transaction_currency, // This might be the same as $currency, depending on the gateway
                    'payment_date'         => '',
                    'total_amount'         => $total_price,
                    'order_key'            => '',
                    'payment_mode'         => $payment_method,
                    'payment_provider'     => $payment_method_title,
                    'customer_ip_address'  => $customer_ip_address,
                    'customer_user_agent'  => $customer_user_agent,
                    'date_paid'            => '',
                    'billing_country'      => $b_country,
                    'billing_state'        => $b_state,
                    'billing_city'         => $b_city,
                    'billing_fullname'     => $b_fname . ' ' . $b_lname,
                    'billing_company'      => $b_company,
                    'billing_address'      => $b_address1 . ' ' . $b_address2,
                    'billing_email'        => $b_email,
                    'billing_zip'          => $b_zipcode,
                    'billing_phone'        => $b_phone_number,
                    'shipping_country'     => $sh_country,
                    'shipping_state'       => $sh_state,
                    'shipping_city'        => $sh_city,
                    'shipping_fullname'    => $sh_fname . ' ' . $sh_lname,
                    'shipping_company'     => $sh_company,
                    'shipping_address'     => $sh_address1 . ' ' . $sh_address2,
                    'shipping_zip'         => $sh_zipcode,
                    'shipping_phone'       => '',
                    'shipping_method'      => $shipping_method,
                    'discount_amount'      => $discount_amount,
                    'coupon_code'          => $coupon_code,
                    'user_created_at'      => '',
                ];
                global $wpdb;
                $sensfrx_approve = null;
                $sensfrx_master_fraud_allow = $sensfrx_policy_options['sensfrx_master_fraud'];
                if ($sensfrx_master_fraud_allow) {
                    $sensfrx_master_fraud_allow = true;
                } else {
                    $sensfrx_master_fraud_allow = false;
                }
                if (true == $sensfrx_master_fraud_allow) {
                    $sensfrx_before_payment_allow = $sensfrx_policy_options['sensfrx_before_payment_fraud'];
                    if ($sensfrx_before_payment_allow) {
                        $sensfrx_before_payment_allow = true;
                    } else {
                        $sensfrx_before_payment_allow = false;
                    }
                    if (true == $sensfrx_before_payment_allow) {
                        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'],
                            ]);
                            $res = $obj->transactionAttempt('attempt_succeeded', $device_id, $transactionExtras);
                            if (isset($res) && gettype($res) !== 'string') {
                                if (isset($res['status']) && $res['status'] === 'error' && $res['error'] === 'USE_CASE_DISABLED') {
                                    $errorMessage = $res['message'] ?? 'Something went wrong';
                                    $insert_data  = "Order #" . $order_id . " | " . $email . " | Transaction approved | Reason: " . $errorMessage;
                                    SensFRX_DB_Helper::insert_activity_log('Transaction (Before Payment)', $insert_data);
                                } else {
                                    $res_shadow = SensFRX_DB_Helper::safe_select(
                                        'sensfrx_shadow_activity',
                                        'sensfrx_shadow_status',
                                        '',
                                        [],
                                        '',
                                        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' || $status == 'low') {
                                                    $sensfrx_approve = 'approved';
                                                } else if ($status == 'challenge') {
                                                    $sensfrx_approve = 'on-hold';
                                                } else {
                                                    $sensfrx_approve = $status;
                                                }
                                                $site_title = get_bloginfo('name');
                                                $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;
                                                }
                                                if ('allow' == $status && 'medium' == $severity) {
                                                    if (true == $checkbox_allow) {
                                                        $device = $res['device'];
                                                        $device = (array) $device;
                                                        $to = $b_email;
                                                        global $wpdb;
                                                        $template_trans_medium = 'Trans_medium_severity_Mail_Send 123';
                                                        $table_name = esc_sql($wpdb->prefix . 'sensfrx_email_templates');
                                                        $template_medium_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
                                                            )
                                                        );
                                                        if ($template_medium_trans) {
                                                            $trans_medium_subject = $template_medium_trans->subject1;
                                                            $trans_medium_message = $template_medium_trans->message1;
                                                        } else {
                                                            $trans_medium_subject = 'Default Subject';
                                                            $trans_medium_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}'             => $product_total,
                                                            '{$default_brand_name}' => $site_title,
                                                        ];
                                                        // Use universal email wrapper for professional formatting
                                                        $mailResult = SensFRX_email_template::wrap_and_send($to, $trans_medium_subject, $trans_medium_message, $site_title, $replacements);
                                                        $insert_data = "Order #" . $order_id . " | " . $b_email . " | Transaction " . $sensfrx_approve . " | Risk: " . $severity;
                                                        SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                    } else {
                                                        $insert_data = "Order #" . $order_id . " | " . $b_email . " | Transaction approved (Allow policy off) | Risk: " . $severity;
                                                        SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                    }
                                                }
                                                if ('challenge' == $status && 'high' == $severity) {
                                                    if (true == $checkbox_challenge) {
                                                        $device = $res['device'];
                                                        $device = (array) $device;
                                                        $to = $b_email;
                                                        global $wpdb;
                                                        $template_trans_challenge = 'Trans_challenge_severity_Mail_Send 123';
                                                        $table_name = esc_sql($wpdb->prefix . 'sensfrx_email_templates');
                                                        $template_challenge_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_challenge
                                                            )
                                                        );
                                                        if ($template_challenge_trans) {
                                                            $trans_challenge_subject = $template_challenge_trans->subject1;
                                                            $trans_challenge_message = $template_challenge_trans->message1;
                                                        } else {
                                                            $trans_challenge_subject = 'Default Subject';
                                                            $trans_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}'             => $product_total,
                                                            '{$default_brand_name}' => $site_title,
                                                        ];
                                                        // Use universal email wrapper for professional formatting
                                                        $mailResult = SensFRX_email_template::wrap_and_send($to, $trans_challenge_subject, $trans_challenge_message, $site_title, $replacements);
                                                        $insert_data = "Order #" . $order_id . " | " . $b_email . " | Transaction " . $sensfrx_approve . " | Risk: " . $severity;
                                                        SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                        $order->update_status('pending', __('Sensfrx - On hold due to fraud detection by Sensfrx', 'Sensfrx'));
                                                        $table_name_shadow_table = esc_sql($wpdb->prefix . 'sensfrx_pre_payment_order');
                                                        $existing_record = $wpdb->get_var(
                                                            $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_shadow_table} WHERE pre_order_id = %s",
                                                                $order_id
                                                            )
                                                        );
                                                        if ($existing_record == 0) {
                                                            $data = [
                                                                'pre_order_id' => $order_id,
                                                            ];
                                                            $results = $wpdb->insert($table_name_shadow_table, $data);
                                                        }
                                                        throw new Exception('Sensfrx - We have detected unusual activity with your recent transaction, and as a precautionary measure, your order status has been temporarily placed On Hold.');
                                                    } else {
                                                        $insert_data = "Order #" . $order_id . " | " . $b_email . " | Transaction approved (Challenge policy off) | Risk: " . $severity;
                                                        SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                    }
                                                }
                                                if ('deny' == $status && 'critical' == $severity) {
                                                    if (true == $checkbox_deny) {
                                                        $device = $res['device'];
                                                        $device = (array) $device;
                                                        $to = $b_email;
                                                        // Get default email content (no database customization)
                                                        $default_email      = SensFRX_email_template::get_default_message('transaction_deny');
                                                        $trans_deny_subject = $default_email['subject'];
                                                        $trans_deny_message = $default_email['message'];
                                                        $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,
                                                        ];
                                                        // Use universal email wrapper for professional formatting
                                                        $mailResult = SensFRX_email_template::wrap_and_send($to, $trans_deny_subject, $trans_deny_message, $site_title, $replacements);
                                                        $insert_data = "Order #" . $order_id . " | " . $b_email . " | Transaction " . $sensfrx_approve . " | Risk: " . $severity;
                                                        SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                        $order->update_status('cancelled', __('Sensfrx - Cancelled due to fraud detection by Sensfrx', 'Sensfrx'));
                                                        throw new Exception('Sensfrx - We have detected suspicious activity with your recent transaction. As a precaution, we cannot proceed with processing your order at this time. Please try again later.');
                                                    } else {
                                                        $insert_data = "Order #" . $order_id . " | " . $b_email . " | Transaction approved (Deny policy off) | Risk: " . $severity;
                                                        SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                    }
                                                }
                                                if ('allow' == $status && 'low' == $severity) {
                                                    $insert_data = "Order #" . $order_id . " | " . $b_email . " | Transaction " . $sensfrx_approve . " | Risk: " . $severity;
                                                    SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                }
                                            } else {
                                                $insert_data = "Order #" . $order_id . " | " . $b_email . " | Transaction approved | Reason: API error fallback";
                                                SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                            }
                                        } else {
                                            $insert_data = "Order #" . $order_id . " | " . $b_email . " | Transaction allowed (Shadow Mode) | Risk: " . $res['severity'];
                                            SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                        }
                                    } else {
                                        $insert_data = "Order #" . $order_id . " | " . $b_email . " | Transaction error | Reason: Shadow Mode data fetch failed";
                                        SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                    }
                                }
                            } else {
                                $insert_data = "Order #" . $order_id . " | " . $b_email . " | Transaction error | Reason: Unformatted API response";
                                SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                            }
                        }
                    }
                }
            }
        }
    }
    private function sensfrx_safe_shipping_field($order, $meta_key, $getter = null)
    {
        $value = null;
        // Prefer the official WooCommerce getter (if provided)
        if ($getter && method_exists($order, $getter)) {
            $value = $order->$getter();
        }
        // If getter didn’t return anything, check order meta (some plugins store here)
        // Only use get_meta for non-internal meta keys (custom fields)
        // Internal meta keys (starting with _) should use getters only
        if (empty($value) && substr($meta_key, 0, 1) !== '_') {
            $value = $order->get_meta($meta_key);
        }
        // Normalize empty values
        return ! empty($value) ? $value : null;
    }
    private function get_category_ancestors($term)
    {
        $ancestors = [];
        if (! is_wp_error($term) && ! empty($term)) {
            $ancestors[] = $term->slug;
        }
        while (! is_wp_error($term) && $term->parent != 0) {
            $term = get_term($term->parent, 'product_cat');
            if (! is_wp_error($term) && ! empty($term)) {
                $ancestors[] = $term->slug;
            } else {
                break;
            }
        }
        return $ancestors;
    }
}
