<?php
/**
 * File: advanced-emt-payment-gateway/advanced-emt-payment-gateway.php
 * Plugin Name: Interac e-Transfer / Email Money Transfer (EMT) Gateway for WooCommerce
 * Plugin URI:  https://wordpress.org/plugins/advanced-emt-payment-gateway/
 * Description: Accept Interac e-Transfer / Email Money Transfer (EMT) in WooCommerce with dynamic secret answers, order notes, and customizable instructions. Supports Block and Classic checkout.
 * Version:     2.1.1
 * Author:      CaphLabs
 * Author URI:  https://profiles.wordpress.org/ipodguy79/
 * License:     GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Requires at least: 5.8
 * Tested up to: 7.0
 * Requires PHP: 7.4
 * WC requires at least: 6.0
 * WC tested up to: 8.6
 * WC blocks support: yes
 * Text Domain: advanced-emt-payment-gateway
 * Domain Path: /languages
 */

if ( !defined( 'ABSPATH' ) ) {
    exit;
}

if ( ! function_exists( 'advanced_emt_free_resolve_pro_conflict_early' ) ) {
    /**
     * During activation, the other version may already be loaded in-memory.
     * Deactivate it first and short-circuit this request to avoid function redeclare fatals.
     *
     * @return bool True when the pro plugin was active at request start.
     */
    function advanced_emt_free_resolve_pro_conflict_early() {
        $pro_plugin_rel_path = 'advanced-emt-payment-gateway-pro/advanced-emt-payment-gateway-pro.php';

        if ( ! function_exists( 'is_plugin_active' ) || ! function_exists( 'deactivate_plugins' ) || ! function_exists( 'is_plugin_active_for_network' ) ) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $was_active = function_exists( 'is_plugin_active' ) && is_plugin_active( $pro_plugin_rel_path );
        $was_network_active = is_multisite() && function_exists( 'is_plugin_active_for_network' ) && is_plugin_active_for_network( $pro_plugin_rel_path );
        // Activation sandbox can load active plugins before option state is updated.
        $pro_loaded_in_memory = function_exists( 'advanced_emt_get_blocks_data_payload' );

        if ( ( $was_active || $was_network_active || $pro_loaded_in_memory ) && function_exists( 'deactivate_plugins' ) ) {
            deactivate_plugins( $pro_plugin_rel_path, true, $was_network_active );
        }

        return ( $was_active || $was_network_active || $pro_loaded_in_memory );
    }
}

if ( advanced_emt_free_resolve_pro_conflict_early() ) {
    // The pro plugin was already loaded in this request, so avoid duplicate symbol declarations.
    return;
}


if ( function_exists( 'aemt_fs' ) ) {
    aemt_fs()->set_basename( false, __FILE__ );
} else {
    /**
     * DO NOT REMOVE THIS IF, IT IS ESSENTIAL FOR THE
     * `function_exists` CALL ABOVE TO PROPERLY WORK.
     */
    if ( !function_exists( 'aemt_fs' ) ) {
        // Create a helper function for easy SDK access.
        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound -- Freemius SDK helper name.
        function aemt_fs() {
            // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Freemius SDK global.
            global $aemt_fs;
            if ( !isset( $aemt_fs ) ) {
                // Include Freemius SDK.
                require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';
                $aemt_fs = fs_dynamic_init( array(
                    'id'             => '22811',
                    'slug'           => 'advanced-emt-payment-gateway',
                    'premium_slug'   => 'advanced-emt-payment-gateway-pro',
                    'type'           => 'plugin',
                    'public_key'     => 'pk_fadebfd7252355cfeb75e92107b63',
                    'is_premium'     => false,
                    'premium_suffix' => 'Pro',
                    'has_addons'     => false,
                    'has_paid_plans' => true,
                    'trial'          => array(
                        'days'               => 7,
                        'is_require_payment' => true,
                    ),
                    'menu'           => array(
                        'slug'       => 'advanced-emt-payment-gateway',
                        'contact'    => false,
                        'support'    => false,
                        'parent'     => array(
                            'slug' => 'woocommerce',
                        ),
                        'first-path' => 'plugins.php',
                    ),
                    'is_live'        => true,
                ) );
            }
            return $aemt_fs;
        }

        // Init Freemius.
        aemt_fs();
        // Signal that SDK was initiated.
        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Freemius SDK bootstrap hook.
        do_action( 'aemt_fs_loaded' );
    }
}
// After opt-in/connect (or skip), go back to Plugins like other Freemius plugins do.
if ( function_exists( 'aemt_fs' ) ) {
    // Freemius standard behavior: deactivate the other version on activation.
    aemt_fs()->add_filter( 'deactivate_on_activation', '__return_true' );

    aemt_fs()->add_filter( 'after_connect_url', function ( $url ) {
        return ( is_network_admin() ? network_admin_url( 'plugins.php' ) : admin_url( 'plugins.php' ) );
    } );
    aemt_fs()->add_filter( 'after_skip_url', function ( $url ) {
        return ( is_network_admin() ? network_admin_url( 'plugins.php' ) : admin_url( 'plugins.php' ) );
    } );
}
add_action( 'admin_menu', function () {
    if ( !function_exists( 'WC' ) ) {
        return;
    }
    add_submenu_page(
        'woocommerce',
        __( 'Advanced EMT', 'advanced-emt-payment-gateway' ),
        __( 'Advanced EMT', 'advanced-emt-payment-gateway' ),
        'manage_woocommerce',
        'advanced-emt-payment-gateway',
        function () {
            if ( !function_exists( 'aemt_fs' ) ) {
                wp_safe_redirect( admin_url( 'admin.php?page=wc-settings&tab=checkout&section=advanced_emt' ) );
                exit;
            }
            $fs = aemt_fs();
            // Freemius flow can be GET or POST depending on step.
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Freemius SDK flow detection only; nonce handling is performed by the SDK render flow.
            $is_fs_flow = isset( $_REQUEST['fs_action'] ) || isset( $_REQUEST['fs_nonce'] ) || isset( $_REQUEST['fs_id'] ) || isset( $_REQUEST['fs_uid'] ) || isset( $_REQUEST['fs_redirect'] ) || isset( $_REQUEST['nonce'] );
            // If not registered yet, the first hit often has NO fs_* params.
            $needs_connect = method_exists( $fs, 'is_registered' ) && !$fs->is_registered();
            // Some SDK flows use activation mode without fs_* params.
            $activation_mode = method_exists( $fs, 'is_activation_mode' ) && $fs->is_activation_mode( false );
            if ( ($is_fs_flow || $needs_connect || $activation_mode) && method_exists( $fs, '_connect_page_render' ) ) {
                $fs->_connect_page_render();
                exit;
            }
            // Normal submenu click → your gateway settings.
            wp_safe_redirect( admin_url( 'admin.php?page=wc-settings&tab=checkout&section=advanced_emt' ) );
            exit;
        }
    );
}, 99 );

if (!defined('ABSPATH')) exit;

require_once plugin_dir_path(__FILE__) . 'includes/advanced-emt-review.php';


/* === EMT harden: plain stored title + scrub "Payment via ..." note for NEW orders === */
if (!function_exists('advanced_emt_scrub_new_order')) {
    function advanced_emt_scrub_new_order($order_id) {
        $order = wc_get_order($order_id);
        if (!$order instanceof WC_Order) return;
        if ($order->get_payment_method() !== 'advanced_emt') return;

        if ($order->get_meta('_emt_scrubbed')) return; // run once

        // Store plain payment method title
        $stored = (string) $order->get_payment_method_title();
        $plain  = trim(wp_strip_all_tags($stored));
        if ($plain !== '' && $plain !== $stored) {
            $order->set_payment_method_title($plain);
            $order->save();
        }

        // Scrub first "Payment via ..." system note
        $notes = wc_get_order_notes([
            'order_id' => $order_id,
            'type'     => 'system',
            'orderby'  => 'date_created',
            'order'    => 'ASC',
        ]);
        foreach ($notes as $note) {
            if (stripos($note->content ?? '', 'Payment via') === 0) {
                $clean = trim(wp_strip_all_tags($note->content));
                if ($clean !== '' && $clean !== $note->content) {
                    wp_update_comment([
                        'comment_ID'      => $note->id,
                        'comment_content' => $clean,
                    ]);
                }
                break;
            }
        }

        $order->update_meta_data('_emt_scrubbed', 1);
        $order->save();
    }
    add_action('woocommerce_new_order',                'advanced_emt_scrub_new_order', 99);
    add_action('woocommerce_checkout_order_processed', 'advanced_emt_scrub_new_order', 99, 1);
    add_action('woocommerce_thankyou',                 'advanced_emt_scrub_new_order', 99, 1);
}

/* Admin safety: strip any HTML from stored titles in wp-admin */
add_filter('woocommerce_order_get_payment_method_title', function ($title, $order) {
    if (!is_admin()) return $title;
    return trim(wp_strip_all_tags((string) $title));
}, 10, 2);

/* === Existing plugin code (unchanged UI) === */


add_action('admin_enqueue_scripts', function($hook) {
    if (strpos($hook, 'woocommerce') === false) return;
    wp_enqueue_script(
        'advanced-emt-admin',
        plugin_dir_url(__FILE__) . 'assets/build/admin-emt.js',
        ['jquery'],
        '1.0.0',
        true
    );
    wp_localize_script('advanced-emt-admin', 'emtDefaults', [
        'instructions' => advanced_emt_get_default_instructions()
    ]);
});



add_action('wp_enqueue_scripts', function () {
    // Enqueue classic checkout handler to trigger discount recalculation
    if (is_checkout() && !has_block('woocommerce/checkout')) {
        $classic_version = filemtime( plugin_dir_path(__FILE__) . 'assets/classic-checkout.js' );
        wp_enqueue_script(
            'advanced-emt-classic-checkout',
            plugins_url('assets/classic-checkout.js', __FILE__),
            ['jquery'],
            $classic_version,
            true
        );
        wp_localize_script('advanced-emt-classic-checkout', 'wc_emt_params', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce'    => wp_create_nonce('wc_emt_nonce'),
        ]);
    }

    // For blocks checkout, add inline script directly
    if (is_checkout() && has_block('woocommerce/checkout')) {
        $blocks_version = filemtime( plugin_dir_path(__FILE__) . 'assets/blocks-checkout.js' );
        wp_enqueue_script(
            'advanced-emt-blocks-checkout',
            plugins_url('assets/blocks-checkout.js', __FILE__),
            ['wp-data', 'wc-blocks-registry', 'wc-blocks-data-store'],
            $blocks_version,
            true
        );
        wp_localize_script('advanced-emt-blocks-checkout', 'wc_emt_params', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('wc_emt_nonce')
        ]);
        
        // Debug block removed for production
    }

    if (function_exists('is_order_received_page') && is_order_received_page()) {
        wp_enqueue_style(
            'advanced-emt-thankyou',
            plugins_url('assets/aemt.css', __FILE__),
            [],
            '2.0.3'
        );
    }
}, 20);

add_action('before_woocommerce_init', function () {
    if (class_exists('Automattic\\WooCommerce\\Utilities\\FeaturesUtil')) {
        Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility(
            'custom_order_tables',
            __FILE__,
            true
        );
    }
});

// ✅ EMT Default Instructions
if ( ! function_exists( 'advanced_emt_get_default_instructions' ) ) {
    function advanced_emt_get_default_instructions() {
        return "Send an EMT to your@email.com

Secret Question: Your Order Number [order]
Secret Answer: [answer]

Thank you!";
    }
}

add_filter('woocommerce_payment_gateways', function ($methods) {
    $methods[] = 'WC_Gateway_Advanced_EMT';
    return $methods;
});

// Apply EMT discount when order is created (for blocks checkout)
add_action('woocommerce_checkout_create_order', function ($order, $data) {
    if ($data['payment_method'] !== 'advanced_emt') return;
    
    $settings = get_option('woocommerce_advanced_emt_settings', []);
    $discount_percent = floatval($settings['discount_percent'] ?? 0);
    
    if ($discount_percent > 0) {
        $subtotal = 0;
        foreach ($order->get_items('line_item') as $item) {
            $subtotal += $item->get_subtotal();
        }
        $discount = $subtotal * ($discount_percent / 100);
        
        $fee = new WC_Order_Item_Fee();
        $fee->set_name(__('EMT Discount', 'advanced-emt-payment-gateway'));
        $fee->set_amount(-$discount);
        $fee->set_tax_class('');
        $order->add_item($fee);
    }
}, 10, 2);

// Handle fee calculation for both classic and blocks checkout
add_action('woocommerce_cart_calculate_fees', function ($cart) {
    if (is_admin() && !defined('DOING_AJAX')) return;
    
    $chosen_gateway = WC()->session->get('chosen_payment_method');
    if ($chosen_gateway !== 'advanced_emt') return;

    $settings = get_option('woocommerce_advanced_emt_settings', []);
    $discount_percent = floatval($settings['discount_percent'] ?? 0);
    
    if ($discount_percent > 0) {
        $subtotal = 0;
        foreach ($cart->get_cart() as $item) {
            $subtotal += $item['line_subtotal'];
        }
        $discount = $subtotal * ($discount_percent / 100);
        $cart->add_fee(__('EMT Discount', 'advanced-emt-payment-gateway'), -$discount);
    }
}, 10, 1);

add_action('wp_ajax_wc_emt_set_payment_method', function () {
    check_ajax_referer('wc_emt_nonce', 'nonce');
    
    $payment_method = isset($_POST['payment_method']) ? sanitize_text_field(wp_unslash($_POST['payment_method'])) : '';
    WC()->session->set('chosen_payment_method', $payment_method);
    WC()->session->save_data();
    wp_send_json_success(array('message' => 'Payment method set', 'method' => $payment_method));
}, 0);

add_action('wp_ajax_nopriv_wc_emt_set_payment_method', function () {
    check_ajax_referer('wc_emt_nonce', 'nonce');
    
    $payment_method = isset($_POST['payment_method']) ? sanitize_text_field(wp_unslash($_POST['payment_method'])) : '';
    WC()->session->set('chosen_payment_method', $payment_method);
    WC()->session->save_data();
    wp_send_json_success(array('message' => 'Payment method set', 'method' => $payment_method));
}, 0);

// Translators: %s is the discount percentage value
add_filter('woocommerce_gateway_title', function ($title, $gateway_id) {
    if ($gateway_id !== 'advanced_emt') return $title;

    // Frontend checkout only; allow AJAX fragments so it stays visible
    if (is_admin()) return $title;
    if (!function_exists('is_checkout') || !is_checkout()) return $title;
    if (function_exists('is_wc_endpoint_url') && (is_wc_endpoint_url('order-pay') || is_wc_endpoint_url('order-received'))) return $title;

    $logo = '<img src="' . esc_url(plugin_dir_url(__FILE__) . 'assets/interac.png') . '" alt="EMT" style="height:28px;vertical-align:middle;margin-right:8px;" />';
    $decorated = $logo . $title;

    $settings = get_option('woocommerce_advanced_emt_settings', []);
    $discount_percent = isset($settings['discount_percent']) ? (float) $settings['discount_percent'] : 0.0;
    $notice_template  = isset($settings['discount_notice']) ? (string) $settings['discount_notice'] : '';

    if ($discount_percent > 0) {
        $notice = trim($notice_template) === ''
            ? 'Save ' . $discount_percent . '% when you pay with EMT. (discount applied at checkout)'
            : str_replace('[discount]', $discount_percent . '%', $notice_template);
        $decorated .= ' <em style="color:green;font-style:italic; font-weight:normal;">' . esc_html($notice) . '</em>';
    }

    return $decorated;
}, 10, 2);

// Additional description text for blocks (appears under title)
add_filter('woocommerce_gateway_description', function($description, $gateway_id) {
    if ($gateway_id !== 'advanced_emt') return $description;
    $settings = get_option('woocommerce_advanced_emt_settings', []);
    $discount_percent = isset($settings['discount_percent']) ? (float) $settings['discount_percent'] : 0.0;
    if ($discount_percent > 0) {
        /* translators: %s is the discount percentage */
        $notice = sprintf(__('A %s%% discount will be applied when you order with EMT.', 'advanced-emt-payment-gateway'), $discount_percent);
        return $description . ' <p class="emd-discount-notice" style="color:green;">' . esc_html($notice) . '</p>';
    }
    return $description;
}, 10, 2);
add_action(
    'woocommerce_blocks_loaded',
    function() {

        require_once __DIR__ . '/blocks/class-advanced-emt-blocks.php';

        add_action(
            'woocommerce_blocks_payment_method_type_registration',
            function( $payment_method_registry ) {
                $payment_method_registry->register(
                    new WC_Advanced_EMT_Blocks_Support()
                );
            }
        );

    }
);


add_action('woocommerce_loaded', function () {
    if (!class_exists('WC_Payment_Gateway')) return;

    require_once plugin_dir_path(__FILE__) . 'blocks/class-advanced-emt-blocks.php';

    class WC_Gateway_Advanced_EMT extends WC_Payment_Gateway {
        protected $use_random;
        protected $static_password;
        protected $instructions;

        public function __construct() {
            $this->id = 'advanced_emt';
            $this->has_fields = false;
            $this->method_title = __('Email Money Transfer', 'advanced-emt-payment-gateway');
            $this->method_description = __('Accept Email Money Transfers with dynamic or static passwords.', 'advanced-emt-payment-gateway');
            $this->init_form_fields();
            $this->init_settings();

            $this->title = $this->get_option('title');
            $this->description = $this->get_option('description');
            $this->instructions = $this->get_option('instructions');
            $use_random_option = $this->get_option('use_random', null);
            if ($use_random_option === null) {
                $use_random_option = 'yes';
            } elseif ($use_random_option === '') {
                $use_random_option = 'no';
            }
            $this->use_random = $use_random_option === 'yes';
            $this->static_password = $this->get_option('static_password', '');

            add_action('woocommerce_update_options_payment_gateways_' . $this->id, [$this, 'process_admin_options']);
            add_action('woocommerce_email_after_order_table', [$this, 'email_instructions'], 10, 4);
            add_action('woocommerce_thankyou', [$this, 'email_instructions'], 1);
            add_action('woocommerce_email_header', [$this, 'maybe_render_instructions'], 5, 2);
            add_action( 'woocommerce_sections_checkout', [ $this, 'maybe_show_upgrade_button' ], 5 );
        }

        public function supports_blocks() {
            return true;
        }

        public function init_form_fields() {
            $default_instructions = advanced_emt_get_default_instructions();

            $this->form_fields = [
                'enabled' => [
                    'title' => __('Enable/Disable', 'advanced-emt-payment-gateway'),
                    'type' => 'checkbox',
                    'label' => __('Enable EMT Payment', 'advanced-emt-payment-gateway'),
                    'default' => 'yes'
                ],
                'title' => [
                    'title' => __('Title', 'advanced-emt-payment-gateway'),
                    'type' => 'text',
                    'default' => __('Email Money Transfer', 'advanced-emt-payment-gateway')
                ],
                'description' => [
                    'title' => __('Description', 'advanced-emt-payment-gateway'),
                    'type' => 'textarea',
                    'default' => __('Pay via EMT (Email Money Transfer).', 'advanced-emt-payment-gateway')
                ],
                'instructions' => [
                    'title' => __('Instructions', 'advanced-emt-payment-gateway'),
                    'type' => 'textarea',
                    'default' => $default_instructions,
                    'description' => __('Use [order] and [answer] as placeholders.', 'advanced-emt-payment-gateway')
                ],
                'use_random' => [
                    'title' => __('Use Random Answer', 'advanced-emt-payment-gateway'),
                    'type' => 'checkbox',
                    'label' => __('Generate random answer per order (6 characters). If disabled, uses static answer.', 'advanced-emt-payment-gateway'),
                    'default' => 'yes'
                ],
                'static_password' => [
                    'title' => __('Static Answer', 'advanced-emt-payment-gateway'),
                    'type' => 'text',
                    'default' => '',
                    'description' => __('If random answer is disabled, this will be used.', 'advanced-emt-payment-gateway')
                ],
                'discount_percent' => [
                    'title' => __('Discount Percent', 'advanced-emt-payment-gateway'),
                    'type' => 'number',
                    'default' => '0',
                    'css' => 'width: 80px;',
                    'desc_tip' => true
                ],
                'discount_notice' => [
                    'title' => __('Discount Message', 'advanced-emt-payment-gateway'),
                    'type' => 'text',
                    'default' => '',
                    'desc_tip' => true,
                    'description' => __('Optional. Use [discount] where you want the percent to appear. If left blank, defaults to "Save X% when you pay with EMT."', 'advanced-emt-payment-gateway')
                ],
                'debug_mode' => [
                    'title' => __('Enable Debug Mode', 'advanced-emt-payment-gateway'),
                    'type' => 'checkbox',
                    'label' => __('Log diagnostic messages to the WooCommerce status logs.', 'advanced-emt-payment-gateway'),
                    'default' => 'no'
                ]
            ];
        }

            public function process_admin_options() {
                // Validate admin settings before saving: ensure static password
                // is provided when random answers are disabled.
                // phpcs:ignore WordPress.Security.NonceVerification.Missing -- WooCommerce handles nonce on payment settings form
                $posted_key = 'woocommerce_' . $this->id . '_settings';
                // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- data is sanitized by wc_clean below
                $posted = isset($_POST[ $posted_key ]) ? wc_clean( wp_unslash( $_POST[ $posted_key ] ) ) : array();
                $use_random = isset( $posted['use_random'] ) ? $posted['use_random'] : '';
                $static_password = isset( $posted['static_password'] ) ? $posted['static_password'] : '';

                // If the posted static password is empty, it's possible the field
                // was masked and not re-submitted; fall back to the saved value.
                if ( trim( $static_password ) === '' ) {
                    $static_password = $this->get_option('static_password', '');
                }

                if ( $use_random !== 'yes' && trim( $static_password ) === '' ) {
                    if ( class_exists( 'WC_Admin_Settings' ) ) {
                        WC_Admin_Settings::add_error( __( 'Warning: static answer is empty while random answers are disabled. Orders will receive a generated answer until a static answer is set.', 'advanced-emt-payment-gateway' ) );
                    }
                    // Do not abort saving; allow the admin to save other changes.
                }

                parent::process_admin_options();
            }

            public function maybe_show_upgrade_button() {
            if ( ! function_exists( 'aemt_fs' ) ) {
                return;
            }

            // Only show in FREE.
            if ( aemt_fs()->is_premium() ) {
                return;
            }

            // Only show on this gateway's section.
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- $_GET is sanitized; WooCommerce settings page doesn't use query nonce for section param
            $section = isset( $_GET['section'] ) ? sanitize_text_field( wp_unslash( $_GET['section'] ) ) : '';
            if ( $section !== $this->id ) {
                return;
            }

            // Show a boxed Freemius checkout CTA (keeps placement consistent)
            $checkout_url = esc_url( 'https://checkout.freemius.com/plugin/22811/plan/38275/?trial=paid' );
            echo '<div style="margin:12px 0 16px; padding:12px; border:1px solid #e1e1e1; background:#fff;">';
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $checkout_url is escaped with esc_url
            echo '<a class="button button-primary" href="' . esc_attr( $checkout_url ) . '" target="_blank" rel="noopener">' . esc_html__( 'Upgrade / Unlock Pro', 'advanced-emt-payment-gateway' ) . '</a>';
            echo '<p style="margin:8px 0 0; font-size:13px; color:#666;">' . esc_html__( 'Start a 7-day paid trial. No risk — cancel anytime.', 'advanced-emt-payment-gateway' ) . '</p>';
            echo '</div>';
        }

        public function generate_answer() {
            return strtoupper(substr(bin2hex(random_bytes(4)), 0, 6));
        }

        public function process_payment($order_id) {
            // Re-fetch options at the moment of payment, in case admin settings
            // have changed since the gateway object was constructed. This is a
            // particularly sensitive area: if random answer is disabled we must
            // absolutely use the configured static password.
            $use_random_option = $this->get_option('use_random', null);
            if ($use_random_option === null) {
                // no option saved, fall back to default yes for backwards compatibility
                $use_random = true;
            } elseif ($use_random_option === '') {
                $use_random = false;
            } else {
                $use_random = $use_random_option === 'yes';
            }

            $static_password = $this->get_option('static_password', '');
            if (! $use_random && $static_password === '') {
                // mis‑configured: random disabled but no static answer provided.
                // generate one so we don't leave orders without an answer.
                $use_random = true;
            }

            $order = wc_get_order($order_id);
            $answer = $use_random ? $this->generate_answer() : $static_password;

            // store in meta and note, same as before
            $order->update_meta_data('_emt_answer', $answer);
            $order->add_order_note(__('EMT Secret Answer: ', 'advanced-emt-payment-gateway') . $answer);
            $order->update_status('on-hold', __('Awaiting EMT payment.', 'advanced-emt-payment-gateway'));
            $order->save();
            wc_reduce_stock_levels($order_id);
            WC()->cart->empty_cart();
            return ['result' => 'success', 'redirect' => $this->get_return_url($order)];
        }

        public function maybe_render_instructions($email_heading, $email) {
            if (! $email instanceof WC_Email || $email->id !== 'customer_on_hold_order') return;
            $order = $email->object instanceof WC_Order ? $email->object : null;
            if (! $order || $order->get_payment_method() !== $this->id) return;

            $answer = $order->get_meta('_emt_answer');
            $output = str_replace(
                ['[amount]', '[order]', '[answer]'],
                [wp_strip_all_tags(wc_price($order->get_total())), $order->get_order_number(), $answer],
                $this->instructions
            );

            echo wp_kses_post('<table role="presentation" border="0" cellpadding="0" cellspacing="0" width="100%" style="margin:0 0 30px 0;">
                <tr>
                    <td style="padding:20px; background:#d9edf7; border:1px solid #bce8f1; color:#31708f; font-family:Arial, sans-serif; font-size:14px; line-height:1.5;">
                        ' . wpautop(esc_html($output)) . '
                    </td>
                </tr>
            </table>');
        }

        public function email_instructions($order, $sent_to_admin = false, $plain_text = false, $email = null) {
            static $emt_already_output = false;
            if ($emt_already_output) return;
            $emt_already_output = true;

            if (! $order instanceof WC_Order && is_numeric($order)) {
                $order = wc_get_order($order);
            }
            $is_email = $email instanceof WC_Email;
            $is_thankyou = !is_admin() && is_order_received_page();
            if ($is_email && isset($email->id) && $email->id !== 'customer_on_hold_order') return;
            if (!($is_email || $is_thankyou)) return;
            $method = $order instanceof WC_Order ? $order->get_payment_method() : null;
            if ($method !== $this->id || $sent_to_admin) return;
            $answer = $order->get_meta('_emt_answer');
            $output = str_replace(
                ['[amount]', '[order]', '[answer]'],
                [wp_strip_all_tags(wc_price($order->get_total())), $order->get_order_number(), $answer],
                $this->instructions
            );
            $body = wpautop(esc_html($output));

            if ($is_thankyou) {
                // Thank-you page: wrap with unique classes so users can style it with CSS.
                echo wp_kses_post(
                    '<section class="aemt-instructions aemt-instructions--thankyou" role="note">' .
                        '<div class="aemt-instructions__body">' . $body . '</div>' .
                    '</section>'
                );
                return;
            }

            // Emails (and anything else): keep original output behavior.
            echo wp_kses_post($body);
        }
    }
});
