<?php
if (! defined('ABSPATH')) {
    die('No direct access.');
}
// 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
{
    public function payment_complete($order_id)
    {
        $sensfrx_policy_options = get_option('sensfrx_policy_options', SensFRX::default_policy_options());
        $sensfrx_after_payment_fraud_allow = $sensfrx_policy_options['sensfrx_after_payment_fraud'];
        if ($sensfrx_after_payment_fraud_allow) {
            $sensfrx_after_payment_fraud_allow = true;
        } else {
            $sensfrx_after_payment_fraud_allow = false;
        }
        if (true == $sensfrx_after_payment_fraud_allow) {
            if (is_user_logged_in()) {
                global $wpdb;
                $order = wc_get_order($order_id);
                $sensfrx_entries = $order->get_meta_data();
                $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) {
                        foreach ($sensfrx_entries as $sensfrx_mets_data) {
                            $sensfrx_custom_value = $sensfrx_mets_data->get_data()['key'];
                            $sensfrx_value = $sensfrx_mets_data->get_data()['value'];
                            if (! empty($sensfrx_custom_value) && $sensfrx_custom_value == '_' . $row['sensfrx_custom_field']) {
                                if (! empty($sensfrx_value)) {
                                    array_push($sensfrx_custom_matched_fields, $row['sensfrx_custom_field']);
                                }
                            }
                        }
                    }
                }
                $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 = [];
                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;
                $user_id = $customer->get_id();
                $first_name = $customer->get_first_name();
                $last_name = $customer->get_last_name();
                $email = $customer->get_email();
                $order = wc_get_order($order_id);
                $userdata = get_userdata($user_id);
                $discount_total = $order->get_discount_total();
                $shipping_total = $order->get_shipping_total();
                $current_username = $userdata->user_login;
                $orderid = $order_id;
                $formattedDate = gmdate('Y-F-d');
                $payment_status = $order->get_status(); // processing,
                $payment_status1 = $order->get_status(); // processing,
                $currency = $order->get_currency();
                $payment_date = $order->get_date_created();
                $total_amount = $order->get_total();
                $Order_Key = $order->get_order_key();
                $payment_method = $order->get_payment_method();
                $payment_method_title = $order->get_payment_method_title();
                $transaction_id = $order->get_meta('_sensfrx_trans_id');
                if (empty($transaction_id)) {
                    // Fallback for legacy orders only
                    $transaction_id = uniqid();
                    $order->update_meta_data('_sensfrx_trans_id', $transaction_id);
                    $order->save();
                }
                $customer_ip_address = $order->get_customer_ip_address();
                $customer_user_agent = $order->get_customer_user_agent();
                $date_paid = $order->get_date_paid();
                $b_fname = $order->get_billing_first_name();
                $b_lname = $order->get_billing_last_name();
                $b_company = $order->get_billing_company();
                $b_address1 = $order->get_billing_address_1();
                $b_address2 = $order->get_billing_address_2();
                $b_city = $order->get_billing_city();
                $b_state = $order->get_billing_state();
                $b_country = $order->get_billing_country();
                $b_email = $order->get_billing_email();
                $b_phone_number = $order->get_billing_phone();
                $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');
                $s_zipcode       = $this->sensfrx_safe_shipping_field($order, '_shipping_postcode', 'get_shipping_postcode');
                $b_zipcode = $order->get_billing_postcode();
                $shipping_methods = $order->get_shipping_methods();
                $shipping_method_names = [];
                foreach ($shipping_methods as $shipping_method) {
                    $shipping_method_names[] = $shipping_method->get_name();
                }
                $first_shipping_method = ! empty($shipping_method_names) ? $shipping_method_names[0] : null;
                $item_s = [];
                $item_p = [];
                $cart = WC()->cart;
                $product_total = $cart->get_total();
                $order = wc_get_order($order_id);
                $item_s = [];
                $Total_Expense = 0;
                $items = $order->get_items();
                foreach ($items as $item_id => $item) {
                    $product_name = $item->get_name();
                    $quantity = $item->get_quantity();
                    $product_id = $item->get_product_id();
                    $product_type = get_the_terms($product_id, 'product_tag');
                    $item_type = $item->get_meta('product_type');
                    $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;
                                }
                            }
                        }
                    }
                    $product = wc_get_product($product_id);
                    $product_total = $product->get_price();
                    $total = $item->get_total();
                    $Total_Expense += $total;
                    $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_id'       => $product_id,
                        'item_name'     => $product_name,
                        'item_price'    => $product_total,
                        'item_quantity' => $quantity,
                        'item_category' => $product_categories,
                        'item_type'     => $item_type,
                    ];
                    array_push($item_s, $item_p);
                }
                if ('cod' == $payment_method) {
                    $transaction_id = $order->get_meta('_sensfrx_trans_id');
                }
                if (empty($transaction_id)) {
                    // Fallback for legacy orders only
                    $transaction_id = uniqid();
                    $order->update_meta_data('_sensfrx_trans_id', $transaction_id);
                    $order->save();
                }
                $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)
                $transactionFields = [
                    'user_id'              => $user_id,
                    'first_name'           => $first_name,
                    'last_name'            => $last_name,
                    'username'             => $current_username,
                    'transaction_type'     => 'purchase',
                    'order_id'             => $orderid,
                    'email'                => $email,
                    'payment_status'       => $payment_status, // ev
                    'currency'             => $currency,
                    'transaction_currency' => $currency,
                    'transaction_amount'   => $total_amount,
                    'payment_date'         => $payment_date,
                    'total_amount'         => $total_amount,
                    'order_key'            => $Order_Key,
                    'payment_mode'         => $payment_method,
                    'payment_provider'     => $payment_method_title,
                    'transaction_id'       => $transaction_id,
                    'customer_ip_address'  => $customer_ip_address,
                    'customer_user_agent'  => $customer_user_agent,
                    'date_paid'            => $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'         => $s_zipcode,
                    'shipping_phone'       => $sh_phone_number,
                    'shipping_method'      => $first_shipping_method,
                    'shipping_cost'        => $shipping_total,
                    'discount_amount'      => $discount_total,
                    'items'                => wp_json_encode($item_s),
                    'user_created_at'      => $created_at,
                ];
                if ('pending' === $payment_status) {
                    $payment_status = 'transaction_succeeded';
                } elseif ('failed' === $payment_status) {
                    $payment_status = 'transaction_failed';
                } elseif ('processing' === $payment_status) {
                    $payment_status = 'transaction_succeeded';
                } elseif ('completed' === $payment_status) {
                    $payment_status = 'transaction_succeeded';
                } elseif ('on-hold' === $payment_status) {
                    $payment_status = 'transaction_succeeded';
                } elseif ('cancelled' === $payment_status) {
                    $payment_status = 'transaction_failed';
                } elseif ('refunded' === $payment_status) {
                    $payment_status = 'transaction_failed';
                } else {
                    $payment_status = 'transaction_succeeded';
                }
                $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_after_payment_allow = $sensfrx_policy_options['sensfrx_after_payment_fraud'];
                    if ($sensfrx_after_payment_allow) {
                        $sensfrx_after_payment_allow = true;
                    } else {
                        $sensfrx_after_payment_allow = false;
                    }
                    if (true == $sensfrx_after_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'],
                            ]);
                            global $wpdb;
                            $sensfrx_approve = null;
                            $res = $obj->transactionAttempt($payment_status, $device_id, $transactionFields);
                            // 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';
                                        $user_email_ato = $b_email;
                                        $insert_data    = "User " . $user_email_ato . " succeeded a transaction. The transaction was approved. Cause: " . $errorMessage;
                                        SensFRX_DB_Helper::insert_activity_log('Transaction (After 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') {
                                                        $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) {
                                                        if (true == $checkbox_allow) {
                                                            $lost_pass_url = wp_lostpassword_url();
                                                            $device = $res['device'];
                                                            $device = (array) $device;
                                                            if (empty($device)) {
                                                                $device['ip'] = 'NA';
                                                            }
                                                            $to = $email;
                                                            // Get default email content (no database customization)
                                                            $default_email              = SensFRX_email_template::get_default_message('transaction_allow_after');
                                                            $trans_medium_after_subject = $default_email['subject'];
                                                            $trans_medium_after_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}'             => $Total_Expense,
                                                                '{$default_brand_name}' => $site_title,
                                                                '{$order_id}'           => $orderid,
                                                                '{$currency}'           => $currency,
                                                                '{$payment_method}'     => $payment_method_title,
                                                            ];
                                                            // Use universal email wrapper for professional formatting
                                                            $mailResult = SensFRX_email_template::wrap_and_send($to, $trans_medium_after_subject, $trans_medium_after_message, $site_title, $replacements);
                                                            // Log email send activity
                                                            if ($mailResult) {
                                                                $insert_data = "Order #" . $orderid . " | Customer: " . $b_email . " | Subject: Order Confirmation - Payment Approved | Status: Sent Successfully";
                                                                SensFRX_DB_Helper::insert_activity_log('Email: Low Risk Approved', $insert_data);
                                                            }
                                                            $user_email_ato = $b_email;
                                                            $insert_data = $user_email_ato . " attempted to transaction. The transaction was " . $sensfrx_approve . " due to risk score level of " . $severity . ".";
                                                            SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                        } else {
                                                            $user_email_ato = $b_email;
                                                            $insert_data = "User " . $user_email_ato . " succeeded a transaction. Sensfrx flagged the transaction with a " . $severity . " risk score. However, since your Transaction Security policy [ Allow ] is turned off, the transaction was approved.";
                                                            SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                        }
                                                    }
                                                    if ('challenge' == $status && 'high' == $severity) {
                                                        if (true == $checkbox_challenge) {
                                                            $lost_pass_url = wp_lostpassword_url();
                                                            $device = $res['device'];
                                                            $device = (array) $device;
                                                            if (empty($device)) {
                                                                $device['ip'] = 'NA';
                                                            }
                                                            $to = $email;
                                                            // Get default email content (no database customization)
                                                            $default_email                 = SensFRX_email_template::get_default_message('transaction_challenge_after');
                                                            $trans_after_challenge_subject = $default_email['subject'];
                                                            $trans_after_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}'             => $Total_Expense,
                                                                '{$default_brand_name}' => $site_title,
                                                                '{$order_id}'           => $orderid,
                                                                '{$currency}'           => $currency,
                                                                '{$payment_method}'     => $payment_method_title,
                                                            ];
                                                            // Use universal email wrapper for professional formatting
                                                            $mailResult = SensFRX_email_template::wrap_and_send($to, $trans_after_challenge_subject, $trans_after_challenge_message, $site_title, $replacements);
                                                            // Log email send activity
                                                            if ($mailResult) {
                                                                $insert_data = "Order #" . $orderid . " | Customer: " . $b_email . " | Subject: Order Verification Required - Security Review | Status: Sent Successfully";
                                                                SensFRX_DB_Helper::insert_activity_log('Email: Medium Risk Under Review', $insert_data);
                                                            }
                                                            $user_email_ato = $b_email;
                                                            $insert_data = $user_email_ato . " attempted to transaction. The transaction was " . $sensfrx_approve . " due to risk score level of " . $severity . ".";
                                                            SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                            if (! $order_id) {
                                                                return;
                                                            }
                                                            $order = wc_get_order($order_id);
                                                            $order->update_status('on-hold', 'Sensfrx - Order placed on hold due to detected issues.');
                                                            wc_print_notice('Sensfrx - We have detected unusual activity with your recent transaction, and as a precautionary measure, your order status has been temporarily placed On Hold.', 'error');
                                                        } else {
                                                            $user_email_ato = $b_email;
                                                            $insert_data = "User " . $user_email_ato . " attempted a transaction. Sensfrx flagged the transaction with a " . $severity . " risk score. However, since your Transaction Security policy [ Challenge ] is turned off, the transaction was approved.";
                                                            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 = $email;
                                                            global $wpdb;
                                                            // Get default email content (no database customization)
                                                            $default_email            = SensFRX_email_template::get_default_message('transaction_deny_after');
                                                            $trans_after_deny_subject = $default_email['subject'];
                                                            $trans_after_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,
                                                                '{$order_id}'           => $orderid,
                                                                '{$currency}'           => $currency,
                                                                '{$payment_method}'     => $payment_method_title,
                                                            ];
                                                            // Use universal email wrapper for professional formatting
                                                            $mailResult = SensFRX_email_template::wrap_and_send($to, $trans_after_deny_subject, $trans_after_deny_message, $site_title, $replacements);
                                                            // Log email send activity
                                                            if ($mailResult) {
                                                                $insert_data = 'Order #' . $orderid . ' | Customer: ' . $b_email . ' | Subject: ' . $subject . ' | Status: Sent Successfully';
                                                                SensFRX_DB_Helper::insert_activity_log('Email: High Risk Blocked', $insert_data);
                                                            }
                                                            $user_email_ato = $b_email;
                                                            $insert_data = $user_email_ato . " attempted to transaction. The transaction was " . $sensfrx_approve . " due to risk score level of " . $severity . ".";
                                                            SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                            $current_user = wp_get_current_user();
                                                            $payment_method = $order->get_payment_method();
                                                            $order->update_status('cancelled', 'Sensfrx - Order marked as cancelled due to fraudulent activity.');
                                                            $refund_args = [
                                                                'amount'         => $order->get_total(),
                                                                'order_id'       => $order_id,
                                                                'reason'         => 'Refund due to detected fraudulent activity.',
                                                                'refund_payment' => true,
                                                            ];
                                                            try {
                                                                $refund = wc_create_refund($refund_args);
                                                                if (is_wp_error($refund)) {
                                                                    $order->add_order_note('Sensfrx - Refund failed: ' . $refund->get_error_message());
                                                                } else {
                                                                    $order->add_order_note('Sensfrx - Refund processed successfully for the cancelled order.');
                                                                }
                                                            } catch (Exception $e) {
                                                                $order->add_order_note('Sensfrx - Error during refund: ' . $e->getMessage());
                                                            }
                                                            wc_print_notice('Sensfrx - We have detected suspicious activity with your recent transaction. As a precaution, we cannot proceed with your order and your order is cancelled. Please try again later.', 'error');
                                                            sleep(3);
                                                            $results = retrieve_password($current_user->data->user_login);
                                                        } else {
                                                            $user_email_ato = $b_email;
                                                            $insert_data = "User " . $user_email_ato . " attempted a transaction. Sensfrx flagged the transaction with a " . $severity . " risk score. However, since your Transaction Security policy [ Deny ] is turned off, the transaction was approved.";
                                                            SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                        }
                                                    }
                                                    if ('allow' == $status && 'low' == $severity) {
                                                        $user_email_ato = $b_email;
                                                        $insert_data = $user_email_ato . " attempted to transaction. The transaction was " . $sensfrx_approve . " due to risk score level of " . $severity . ".";
                                                        SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                    }
                                                } else {
                                                    $user_email_ato = $b_email;
                                                    $insert_data = "User " . $user_email_ato . " succeeded a transaction. Sensfrx encountered an error, so the transaction was approved.";
                                                    SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                }
                                            } else {
                                                $user_email_ato = $b_email;
                                                $insert_data = "User " . $user_email_ato . " succeeded in a transaction. 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('Transaction (After Payment)', $insert_data);
                                            }
                                        } else {
                                            $user_email_ato = $b_email;
                                            $insert_data = "User " . $user_email_ato . " succeeded a transaction. An error occurred while fetching Shadow Mode data.";
                                            SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                        }
                                    }
                                } else {
                                    $user_email_ato = $b_email;
                                    $insert_data = "User " . $user_email_ato . " succeeded a transaction. However, Sensfrx returned an unformatted response, causing an issue.";
                                    SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                }
                            }
                        }
                    }
                }
            } else {
                global $wpdb;
                $order = wc_get_order($order_id);
                $sensfrx_entries = $order->get_meta_data();
                $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) {
                        foreach ($sensfrx_entries as $sensfrx_mets_data) {
                            $sensfrx_custom_value = $sensfrx_mets_data->get_data()['key'];
                            $sensfrx_value = $sensfrx_mets_data->get_data()['value'];
                            if (! empty($sensfrx_custom_value) && $sensfrx_custom_value == '_' . $row['sensfrx_custom_field']) {
                                if (! empty($sensfrx_value)) {
                                    array_push($sensfrx_custom_matched_fields, $row['sensfrx_custom_field']);
                                }
                            }
                        }
                    }
                }
                $device_id = WC()->session->get('custom_field_value');
                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 = [];
                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'],
                    ]);
                }
                $order = wc_get_order($order_id);
                $discount_total = $order->get_discount_total();
                $shipping_total = $order->get_shipping_total();
                $orderid = $order_id;
                $payment_status = $order->get_status(); // processing,
                $payment_status1 = $order->get_status(); // processing,
                $currency = $order->get_currency();
                $payment_date = $order->get_date_created();
                $total_amount = $order->get_total();
                $Order_Key = $order->get_order_key();
                $payment_method = $order->get_payment_method();
                $payment_method_title = $order->get_payment_method_title();
                $transaction_id = $order->get_meta('_sensfrx_trans_id');
                if (empty($transaction_id)) {
                    // Fallback for legacy orders only
                    $transaction_id = uniqid();
                    $order->update_meta_data('_sensfrx_trans_id', $transaction_id);
                    $order->save();
                }
                $customer_ip_address = $order->get_customer_ip_address();
                $customer_user_agent = $order->get_customer_user_agent();
                $date_paid = $order->get_date_paid();
                $b_fname = $order->get_billing_first_name();
                $b_lname = $order->get_billing_last_name();
                $b_company = $order->get_billing_company();
                $b_address1 = $order->get_billing_address_1();
                $b_address2 = $order->get_billing_address_2();
                $b_city = $order->get_billing_city();
                $b_state = $order->get_billing_state();
                $b_country = $order->get_billing_country();
                $b_email = $order->get_billing_email();
                $b_phone_number = $order->get_billing_phone();
                $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');
                $s_zipcode       = $this->sensfrx_safe_shipping_field($order, '_shipping_postcode', 'get_shipping_postcode');
                $b_zipcode = $order->get_billing_postcode();
                $shipping_methods = $order->get_shipping_methods();
                $shipping_method_names = [];
                foreach ($shipping_methods as $shipping_method) {
                    $shipping_method_names[] = $shipping_method->get_name();
                }
                $first_shipping_method = ! empty($shipping_method_names) ? $shipping_method_names[0] : null;
                $formattedDate = gmdate('Y-F-d');
                $item_s = [];
                $item_p = [];
                $cart = WC()->cart;
                $product_total = $cart->get_total();
                $order = wc_get_order($order_id);
                $item_s = [];
                $Total_Expense = 0;
                $items = $order->get_items();
                foreach ($items as $item_id => $item) {
                    $product_name = $item->get_name();
                    $quantity = $item->get_quantity();
                    $product_id = $item->get_product_id();
                    $product_type = get_the_terms($product_id, 'product_tag');
                    $item_type = $item->get_meta('product_type');
                    $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;
                                }
                            }
                        }
                    }
                    $product = wc_get_product($product_id);
                    $product_total = $product->get_price();
                    $total = $item->get_total();
                    $Total_Expense += $total;
                    $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_id'       => $product_id,
                        'item_name'     => $product_name,
                        'item_price'    => $product_total,
                        'item_quantity' => $quantity,
                        'item_category' => $product_categories,
                        'item_type'     => $item_type,
                    ];
                    array_push($item_s, $item_p);
                }
                if ('cod' == $payment_method) {
                    $transaction_id = $order->get_meta('_sensfrx_trans_id');
                }
                if (empty($transaction_id)) {
                    // Fallback for legacy orders only
                    $transaction_id = uniqid();
                    $order->update_meta_data('_sensfrx_trans_id', $transaction_id);
                    $order->save();
                }
                $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;
                    }
                }
                $transactionFields = [
                    'user_id'              => '',
                    'first_name'           => $b_fname,
                    'last_name'            => $b_lname,
                    'username'             => '',
                    'transaction_type'     => 'purchase',
                    'order_id'             => $orderid,
                    'email'                => $b_email,
                    'payment_status'       => $payment_status, // ev
                    'currency'             => $currency,
                    'transaction_currency' => $currency,
                    'transaction_amount'   => $total_amount,
                    'payment_date'         => $payment_date,
                    'total_amount'         => $total_amount,
                    'order_key'            => $Order_Key,
                    'payment_mode'         => $payment_method,
                    'payment_provider'     => $payment_method_title,
                    'transaction_id'       => $transaction_id,
                    'customer_ip_address'  => $customer_ip_address,
                    'customer_user_agent'  => $customer_user_agent,
                    'date_paid'            => $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'         => $s_zipcode,
                    'shipping_phone'       => $sh_phone_number,
                    'shipping_method'      => $first_shipping_method,
                    'shipping_cost'        => $shipping_total,
                    'discount_amount'      => $discount_total,
                    'items'                => wp_json_encode($item_s),
                    'user_created_at'      => '',
                ];
                if ('pending' === $payment_status) {
                    $payment_status = 'transaction_succeeded';
                } elseif ('failed' === $payment_status) {
                    $payment_status = 'transaction_failed';
                } elseif ('processing' === $payment_status) {
                    $payment_status = 'transaction_succeeded';
                } elseif ('completed' === $payment_status) {
                    $payment_status = 'transaction_succeeded';
                } elseif ('on-hold' === $payment_status) {
                    $payment_status = 'transaction_succeeded';
                } elseif ('cancelled' === $payment_status) {
                    $payment_status = 'transaction_failed';
                } elseif ('refunded' === $payment_status) {
                    $payment_status = 'transaction_failed';
                } else {
                    $payment_status = 'transaction_succeeded';
                }
                $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_after_payment_allow = $sensfrx_policy_options['sensfrx_after_payment_fraud'];
                    if ($sensfrx_after_payment_allow) {
                        $sensfrx_after_payment_allow = true;
                    } else {
                        $sensfrx_after_payment_allow = false;
                    }
                    if (true == $sensfrx_after_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'],
                            ]);
                            global $wpdb;
                            $sensfrx_approve = null;
                            $res = $obj->transactionAttempt($payment_status, $device_id, $transactionFields);
                            if (isset($res) && gettype($res) !== 'string') {
                                if (isset($res['status']) && $res['status'] === 'error' && $res['error'] === 'USE_CASE_DISABLED') {
                                    $errorMessage   = $res['message'] ?? 'Something went wrong';
                                    $user_email_ato = $b_email;
                                    $insert_data    = "User " . $user_email_ato . " succeeded a transaction. The transaction was approved. Cause: " . $errorMessage;
                                    SensFRX_DB_Helper::insert_activity_log('Transaction (After 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') {
                                                    $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) {
                                                    if (true == $checkbox_allow) {
                                                        $lost_pass_url = wp_lostpassword_url();
                                                        $device = $res['device'];
                                                        $device = (array) $device;
                                                        if (empty($device)) {
                                                            $device['ip'] = 'NA';
                                                        }
                                                        $to = $b_email;
                                                        // Get default email content (no database customization)
                                                        $default_email              = SensFRX_email_template::get_default_message('transaction_allow_after');
                                                        $trans_medium_after_subject = $default_email['subject'];
                                                        $trans_medium_after_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}'             => $Total_Expense,
                                                            '{$default_brand_name}' => $site_title,
                                                            '{$order_id}'           => $orderid,
                                                            '{$currency}'           => $currency,
                                                            '{$payment_method}'     => $payment_method_title,
                                                        ];
                                                        // Use universal email wrapper for professional formatting
                                                        $mailResult = SensFRX_email_template::wrap_and_send($to, $trans_medium_after_subject, $trans_medium_after_message, $site_title, $replacements);
                                                        // Log email send activity
                                                        if ($mailResult) {
                                                            $insert_data = "Order #" . $orderid . " | Customer: " . $b_email . " | Subject: Order Confirmation - Payment Approved | Status: Sent Successfully";
                                                            SensFRX_DB_Helper::insert_activity_log('Email: Low Risk Approved', $insert_data);
                                                        }
                                                        $user_email_ato = $b_email;
                                                        $insert_data = $user_email_ato . " attempted to transaction. The transaction was " . $sensfrx_approve . " due to risk score level of " . $severity . ".";
                                                        SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                    } else {
                                                        $user_email_ato = $b_email;
                                                        $insert_data = "User " . $user_email_ato . " succeeded a transaction. Sensfrx flagged the transaction with a " . $severity . " risk score. However, since your Transaction Security policy [ Allow ] is turned off, the transaction was approved.";
                                                        SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                    }
                                                }
                                                if ('challenge' == $status && 'high' == $severity) {
                                                    if (true == $checkbox_challenge) {
                                                        $lost_pass_url = wp_lostpassword_url();
                                                        $device = $res['device'];
                                                        $device = (array) $device;
                                                        if (empty($device)) {
                                                            $device['ip'] = 'NA';
                                                        }
                                                        $to = $b_email;
                                                        // Get default email content (no database customization)
                                                        $default_email                 = SensFRX_email_template::get_default_message('transaction_challenge_after');
                                                        $trans_after_challenge_subject = $default_email['subject'];
                                                        $trans_after_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}'             => $Total_Expense,
                                                            '{$default_brand_name}' => $site_title,
                                                            '{$order_id}'           => $orderid,
                                                            '{$currency}'           => $currency,
                                                            '{$payment_method}'     => $payment_method_title,
                                                        ];
                                                        // Use universal email wrapper for professional formatting
                                                        $mailResult = SensFRX_email_template::wrap_and_send($to, $trans_after_challenge_subject, $trans_after_challenge_message, $site_title, $replacements);
                                                        // Log email send activity
                                                        if ($mailResult) {
                                                            $insert_data = "Order #" . $orderid . " | Customer: " . $b_email . " | Subject: Order Verification Required - Security Review | Status: Sent Successfully";
                                                            SensFRX_DB_Helper::insert_activity_log('Email: Medium Risk Under Review', $insert_data);
                                                        }
                                                        $user_email_ato = $b_email;
                                                        $insert_data = $user_email_ato . " attempted to transaction. The transaction was " . $sensfrx_approve . " due to risk score level of " . $severity . ".";
                                                        SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                        if (! $order_id) {
                                                            return;
                                                        }
                                                        $order = wc_get_order($order_id);
                                                        $order->update_status('on-hold', 'Sensfrx - Order placed on hold due to detected issues.');
                                                        wc_print_notice('Sensfrx - We have detected unusual activity with your recent transaction, and as a precautionary measure, your order status has been temporarily placed On Hold.', 'error');
                                                    } else {
                                                        $user_email_ato = $b_email;
                                                        $insert_data = "User " . $user_email_ato . " attempted a transaction. Sensfrx flagged the transaction with a " . $severity . " risk score. However, since your Transaction Security policy [ Challenge ] is turned off, the transaction was approved.";
                                                        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_after');
                                                        $trans_after_deny_subject = $default_email['subject'];
                                                        $trans_after_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,
                                                            '{$order_id}'           => $orderid,
                                                            '{$currency}'           => $currency,
                                                            '{$payment_method}'     => $payment_method_title,
                                                        ];
                                                        // Use universal email wrapper for professional formatting
                                                        $mailResult = SensFRX_email_template::wrap_and_send($to, $trans_after_deny_subject, $trans_after_deny_message, $site_title, $replacements);
                                                        // Log email send activity
                                                        if ($mailResult) {
                                                            $insert_data = 'Order #' . $orderid . ' | Customer: ' . $b_email . ' | Subject: Order Cannot Be Processed - Security Review | Status: Sent Successfully';
                                                            SensFRX_DB_Helper::insert_activity_log('Email: High Risk Blocked', $insert_data);
                                                        }
                                                        $user_email_ato = $b_email;
                                                        $insert_data = $user_email_ato . " attempted to transaction. The transaction was " . $sensfrx_approve . " due to risk score level of " . $severity . ".";
                                                        SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                        $current_user = wp_get_current_user();
                                                        $payment_method = $order->get_payment_method();
                                                        $order->update_status('cancelled', 'Sensfrx - Order marked as cancelled due to fraudulent activity.');
                                                        $refund_args = [
                                                            'amount'         => $order->get_total(),
                                                            'order_id'       => $order_id,
                                                            'reason'         => 'Refund due to detected fraudulent activity.',
                                                            'refund_payment' => true,
                                                        ];
                                                        try {
                                                            $refund = wc_create_refund($refund_args);
                                                            if (is_wp_error($refund)) {
                                                                $order->add_order_note('Sensfrx - Refund failed: ' . $refund->get_error_message());
                                                            } else {
                                                                $order->add_order_note('Sensfrx - Refund processed successfully for the cancelled order.');
                                                            }
                                                        } catch (Exception $e) {
                                                            $order->add_order_note('Sensfrx - Error during refund: ' . $e->getMessage());
                                                        }
                                                        wc_print_notice('Sensfrx - We have detected suspicious activity with your recent transaction. As a precaution, we cannot proceed with your order and your order is cancelled. Please try again later.', 'error');
                                                    } else {
                                                        $user_email_ato = $b_email;
                                                        $insert_data = "User " . $user_email_ato . " attempted a transaction. Sensfrx flagged the transaction with a " . $severity . " risk score. However, since your Transaction Security policy [ Deny ] is turned off, the transaction was approved.";
                                                        SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                    }
                                                }
                                                if ('allow' == $status && 'low' == $severity) {
                                                    $user_email_ato = $b_email;
                                                    $insert_data = $user_email_ato . " attempted to transaction. The transaction was " . $sensfrx_approve . " due to risk score level of " . $severity . ".";
                                                    SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                                }
                                            } else {
                                                $user_email_ato = $b_email;
                                                $insert_data = "User " . $user_email_ato . " succeeded a transaction. Sensfrx encountered an error, so the transaction was approved.";
                                                SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                            }
                                        } else {
                                            $user_email_ato = $b_email;
                                            $insert_data = "User " . $user_email_ato . " succeeded in a transaction. 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('Transaction (After Payment)', $insert_data);
                                        }
                                    } else {
                                        $user_email_ato = $b_email;
                                        $insert_data = "User " . $user_email_ato . " succeeded a transaction. An error occurred while fetching Shadow Mode data.";
                                        SensFRX_DB_Helper::insert_activity_log('Transaction (After Payment)', $insert_data);
                                    }
                                }
                            } else {
                                $user_email_ato = $b_email;
                                $insert_data = "User " . $user_email_ato . " succeeded a transaction. However, Sensfrx returned an unformatted response, causing an issue.";
                                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;
    }
}
