<?php
/**
 * Stablezact Payment Gateway.
 *
 * Provides a Cryptocurrency Payment Gateway for WooCommerce.
 *
 * @class       Stablezact_Gateway
 * @extends     WC_Payment_Gateway
 * @version     1.0.0
 * @package     Stablezact
 */

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

/**
 * Stablezact_Gateway Class.
 */
class Stablezact_Gateway extends WC_Payment_Gateway {

    /**
     * Test mode flag
     *
     * @var bool
     */
    protected $testmode;

    /**
     * Public key (replaces api_key + api_secret)
     *
     * @var string
     */
    protected $public_key;

    /**
     * Why the gateway may not be enabled on this save, or null if it may be.
     * Set by validate_fields(), applied by process_admin_options().
     *
     * @var string|null
     */
    protected $enable_blocked_reason = null;

    /**
     * Debug mode flag
     *
     * @var bool
     */
    protected $debug;

    /**
     * Show currency selector flag
     *
     * @var bool
     */
    protected $show_currency_selector;

    /**
     * API instance
     *
     * @var Stablezact_API
     */
    protected $api;

    /**
     * Payment timeout in seconds
     *
     * @var string
     */
    protected $payment_timeout;

    /**
     * Ethereum wallet address
     *
     * @var string
     */
    protected $ethereum_wallet;

    /**
     * BSC wallet address
     *
     * @var string
     */
    protected $bsc_wallet;

    /**
     * Polygon wallet address
     *
     * @var string
     */
    protected $polygon_wallet;

    /**
     * Solana wallet address
     *
     * @var string
     */
    protected $solana_wallet;

    /**
     * TRON wallet address
     *
     * @var string
     */
    protected $tron_wallet;

    /**
     * Algorand wallet address
     *
     * @var string
     */
    protected $algorand_wallet;

    /**
     * Fee charged to (customer or merchant)
     *
     * @var string
     */
    protected $fee_charged_to;

    /**
     * Current fee percentage
     *
     * @var float
     */
    protected $current_fee_percentage;

    /**
     * Constructor for the gateway.
     */
    public function __construct() {
        $this->id                 = 'stablezact';
        $this->icon              = $this->get_icon_url();
        $this->has_fields        = true;
        $this->method_title      = __('Stablezact', 'stablezact-crypto-payments');
        $this->method_description = __('Accept cryptocurrency payments through Stablezact.', 'stablezact-crypto-payments');
        $this->supports          = array(
            'products',
            'refunds',
        );

        // Load the settings
        $this->init_form_fields();
        $this->init_settings();

        // Define user set variables
        $this->title        = $this->get_option('title');
        $this->description  = $this->get_option('description');
        $this->enabled      = $this->get_option('enabled');
        $this->testmode     = 'yes' === $this->get_option('testmode');
        $this->debug        = 'yes' === $this->get_option('debug');
        $this->public_key   = $this->get_option('public_key');
        $this->payment_timeout = $this->get_option('payment_timeout', '300'); // Default 5 minutes
        
        // Wallet addresses
        $this->ethereum_wallet = $this->get_option('ethereum_wallet');
        $this->bsc_wallet = $this->get_option('bsc_wallet');
        $this->polygon_wallet = $this->get_option('polygon_wallet');
        $this->solana_wallet = $this->get_option('solana_wallet');
        $this->tron_wallet = $this->get_option('tron_wallet');
        $this->algorand_wallet = $this->get_option('algorand_wallet');
        
        // Fee configuration
        $this->fee_charged_to = $this->get_option('fee_charged_to', 'customer');
        $this->current_fee_percentage = floatval($this->get_option('current_fee_percentage', STABLEZACT_DEFAULT_FEE_PERCENTAGE));

        // Initialize API if the class exists
        if (class_exists('Stablezact_API')) {
            $this->api = new Stablezact_API($this->public_key, $this->testmode, $this->debug);
        } else {
            // Include the API class if not already included
            require_once STABLEZACT_PLUGIN_DIR . 'includes/class-stablezact-api.php';
            $this->api = new Stablezact_API($this->public_key, $this->testmode, $this->debug);
        }

        // Fetch fee settings from API if credentials are set
        if ($this->public_key) {
            $this->refresh_fee_settings();
        }
        
        // Debug current fee value
        if ($this->debug) {
        }

        // Actions
        add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
        add_action('woocommerce_api_stablezact', array($this, 'webhook_handler'));
        add_action('wp_enqueue_scripts', array($this, 'payment_scripts'));
        add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'));
        add_action('admin_init', array($this, 'maybe_refresh_fee_settings'));
        
        // Payment description filter
        add_filter('woocommerce_gateway_description', array($this, 'enhance_payment_description'), 10, 2);
        
        // Save cryptocurrency preference
        add_action('woocommerce_checkout_update_order_meta', array($this, 'save_preferred_cryptocurrency'));
        
        // AJAX action for order updates after payment
        add_action('wp_ajax_stablezact_update_order', array($this, 'update_order_after_payment'));
        add_action('wp_ajax_nopriv_stablezact_update_order', array($this, 'update_order_after_payment'));
        
        // Removed old wallet connection AJAX actions - now using CoinleyVanilla SDK
        
        // AJAX action for testing currency conversion
        add_action('wp_ajax_stablezact_test_conversion', array($this, 'test_currency_conversion'));
        
        // Removed old Stablezact API AJAX actions - now using CoinleyVanilla SDK
    }
    
    /**
     * Display payment fields on checkout.
     */
    public function payment_fields() {
        // Show description only, no form fields (DePay style)
        if ($this->description) {
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Output is sanitized by wp_kses_post
            echo wpautop(wp_kses_post($this->description));
        }

        if ($this->testmode) {
            echo '<div style="background: #fff3cd; border: 1px solid #ffeaa7; padding: 10px; margin: 10px 0; border-radius: 4px; color: #856404;">';
            echo '<strong>' . esc_html__('TEST MODE ENABLED', 'stablezact-crypto-payments') . '</strong> - ' . esc_html__('Use test cryptocurrencies only', 'stablezact-crypto-payments');
            echo '</div>';
        }
    }
    
    /**
     * Get a list of available cryptocurrencies.
     *
     * @return array
     */
    private function get_available_cryptocurrencies() {
        // In a real implementation, this would be fetched from the API
        return array(
            'btc'  => __( 'Bitcoin (BTC)', 'stablezact-crypto-payments' ),
            'eth'  => __( 'Ethereum (ETH)', 'stablezact-crypto-payments' ),
            'usdt' => __( 'Tether (USDT)', 'stablezact-crypto-payments' ),
            'usdc' => __( 'USD Coin (USDC)', 'stablezact-crypto-payments' ),
            'bnb'  => __( 'Binance Coin (BNB)', 'stablezact-crypto-payments' ),
            'xrp'  => __( 'Ripple (XRP)', 'stablezact-crypto-payments' ),
            'sol'  => __( 'Solana (SOL)', 'stablezact-crypto-payments' ),
            'ada'  => __( 'Cardano (ADA)', 'stablezact-crypto-payments' ),
            'doge' => __( 'Dogecoin (DOGE)', 'stablezact-crypto-payments' ),
        );
    }
    
    /**
     * Save preferred cryptocurrency to order meta.
     *
     * @param int $order_id Order ID.
     */
    public function save_preferred_cryptocurrency( $order_id ) {
        // phpcs:disable WordPress.Security.NonceVerification.Missing -- Runs on a WooCommerce checkout hook; WooCommerce verifies the checkout nonce before this fires.
        if ( isset( $_POST['stablezact_preferred_crypto'] ) && ! empty( $_POST['stablezact_preferred_crypto'] ) ) {
            $crypto = sanitize_text_field( wp_unslash( $_POST['stablezact_preferred_crypto'] ) );
            // phpcs:enable WordPress.Security.NonceVerification.Missing
            $order = wc_get_order( $order_id );
            if ( $order ) {
                $order->update_meta_data( '_stablezact_preferred_crypto', $crypto );
                $order->save();
            }
        }
    }
    
    /**
     * Get the payment icon URL.
     * 
     * @return string
     */
    private function get_icon_url() {
        $svg_logo = STABLEZACT_PLUGIN_URL . 'assets/images/stablezact-logo.png';
        $png_icon = STABLEZACT_PLUGIN_URL . 'assets/images/stablezact-icon.png';
        
        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '';
        
        // If it's an older IE browser, use PNG
        if (preg_match('/MSIE\s[1-8]\./', $user_agent)) {
            return apply_filters('stablezact_icon', $png_icon);
        }
        
        // For all other browsers, use SVG logo
        return apply_filters('stablezact_icon', $svg_logo);
    }
    
    /**
     * Enqueue payment scripts.
     */
    public function payment_scripts() {
        if ( ! is_checkout() || 'no' === $this->enabled ) {
            return;
        }
        
        wp_enqueue_style( 'stablezact-checkout-styles', STABLEZACT_PLUGIN_URL . 'assets/css/checkout.css', array(), STABLEZACT_VERSION );
        
        // Removed old wallet connect CSS - CoinleyVanilla SDK provides its own styles

        // Removed Solana Web3 library - CoinleyVanilla SDK handles all blockchain interactions
        
        // Enqueue the CoinleyVanilla SDK — bundled locally (WordPress.org disallows
        // loading non-core scripts remotely). Use the self-contained vanilla build
        // (exposes the global `CoinleyVanilla`); the package's index.umd.js is the
        // React build and externalizes React, so it cannot run standalone here.
        wp_enqueue_script(
            'coinley-vanilla-sdk',
            STABLEZACT_PLUGIN_URL . 'assets/vendor/stablezact-pay/coinley-vanilla.min.js',
            array(),
            STABLEZACT_VERSION,
            true
        );

        // Enqueue Bricolage Grotesque font (required for SDK modal)
        wp_enqueue_style(
            'coinley-bricolage-font',
            'https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,200..800&display=swap',
            array(),
            STABLEZACT_VERSION
        );

        // Enqueue CoinleyVanilla SDK styles — bundled locally (see note above).
        wp_enqueue_style(
            'coinley-vanilla-styles',
            STABLEZACT_PLUGIN_URL . 'assets/vendor/stablezact-pay/style.css',
            array('coinley-bricolage-font'),
            STABLEZACT_VERSION
        );

        // Enqueue refactored payment modal script for CoinleyVanilla SDK integration (high priority)
        wp_enqueue_script(
            'stablezact-payment-modal',
            STABLEZACT_PLUGIN_URL . 'assets/js/payment-modal.js',
            array('jquery', 'coinley-vanilla-sdk'),
            STABLEZACT_VERSION,
            true
        );
        
        // Old wallet connect script removed - using CoinleyVanilla SDK
        
        // Prepare payment data with currency conversion
        $payment_data = array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('stablezact_nonce'),
            'checkout_url' => wc_get_checkout_url(),
            'use_react_modals' => false,
            'site_name' => get_bloginfo('name'),
            'site_url' => get_site_url(),
            'merchant_wallets' => $this->get_merchant_wallets(),
            'fee_charged_to' => $this->fee_charged_to,
            'current_fee_percentage' => $this->current_fee_percentage,
            'payment_timeout' => $this->payment_timeout * 1000 // Convert seconds to milliseconds for JavaScript
        );

        // Add currency conversion info if on checkout page and cart exists
        if (WC()->cart && !WC()->cart->is_empty()) {
            $cart_total = WC()->cart->get_total('');
            $currency = get_woocommerce_currency();
            
            // Convert cart total if not USD
            if ($currency !== 'USD') {
                $conversion_result = $this->convert_to_usd($cart_total, $currency);
                
                if (!is_wp_error($conversion_result)) {
                    $payment_data['currency_conversion'] = array(
                        'original_amount' => $conversion_result['original_amount'],
                        'original_currency' => $conversion_result['original_currency'],
                        'converted_amount' => $conversion_result['converted_amount'],
                        'converted_currency' => $conversion_result['converted_currency'],
                        'exchange_rate' => $conversion_result['exchange_rate'],
                        'conversion_info' => $conversion_result['conversion_info']
                    );
                    
                    // Log the conversion for debugging
                }
            }
        }

        // Removed old wallet connect localization - no longer needed with CoinleyVanilla SDK

        // Prepare CoinleyVanilla SDK configuration for payment modal
        // Uses merchant's configured public key from settings
        $stablezact_params = array(
            // Stablezact public key from plugin settings
            'publicKey' => $this->public_key,
            'apiUrl' => 'https://hub.stablezact.com',  // Production API endpoint (SDK adds /api/ automatically)

            // WordPress-specific parameters
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('stablezact_nonce'),
            'merchantName' => get_bloginfo('name'),
            'merchantWallets' => $this->get_merchant_wallets(),  // Network-specific wallets from backend
            'callbackUrl' => rest_url('stablezact/v1/webhook'),
            'debug' => $this->debug,  // Use debug setting from admin
        );

        // Add order-specific data if on checkout
        if (is_checkout() && WC()->cart && !WC()->cart->is_empty()) {
            $cart_total = WC()->cart->get_total('edit');
            $currency = get_woocommerce_currency();
            
            // Convert to USD if needed
            if ($currency !== 'USD') {
                $conversion_result = $this->convert_to_usd($cart_total, $currency);
                if (!is_wp_error($conversion_result)) {
                    $stablezact_params['total'] = $conversion_result['converted_amount'];
                    $stablezact_params['currency'] = 'USD';
                } else {
                    $stablezact_params['total'] = $cart_total;
                    $stablezact_params['currency'] = $currency;
                }
            } else {
                $stablezact_params['total'] = $cart_total;
                $stablezact_params['currency'] = $currency;
            }
            
            $stablezact_params['orderReceivedUrl'] = $this->get_return_url(wc_get_order());
        }

        wp_localize_script('stablezact-payment-modal', 'stablezactParams', $stablezact_params);
    }

    /**
     * Enqueue admin scripts for gateway settings
     */
    public function admin_enqueue_scripts($hook) {
        // Only load on gateway settings page
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only check of which admin page is loading; no state is changed.
        if ($hook === 'woocommerce_page_wc-settings' && isset($_GET['section']) && $_GET['section'] === 'stablezact') {
            // Enqueue admin JavaScript
            wp_enqueue_script(
                'stablezact-admin',
                STABLEZACT_PLUGIN_URL . 'assets/js/admin.js',
                array('jquery'),
                STABLEZACT_VERSION,
                true
            );

            // Get current conversion rate for display
            $current_rate = '';
            $store_currency = get_woocommerce_currency();
            if ($store_currency !== 'USD') {
                $conversion_result = $this->convert_to_usd(1000, $store_currency);
                if (!is_wp_error($conversion_result) && isset($conversion_result['conversion_info'])) {
                    $current_rate = $conversion_result['conversion_info'];
                } else {
                    $current_rate = sprintf('Unable to fetch current rate for %s → USD. Click "Refresh Rate" to try again.', $store_currency);
                }
            } else {
                $current_rate = 'No conversion needed - your store already uses USD';
            }
            
            // Localize script with proper nonce and AJAX URL
            wp_localize_script('stablezact-admin', 'stablezact_admin', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('stablezact_admin_nonce'),
                'current_conversion_rate' => $current_rate,
                'store_currency' => $store_currency,
                'strings' => array(
                    'loading' => __('Loading...', 'stablezact-crypto-payments'),
                    'error' => __('An error occurred', 'stablezact-crypto-payments'),
                    'success' => __('Success', 'stablezact-crypto-payments'),
                    'saving' => __('Saving...', 'stablezact-crypto-payments'),
                    'validating' => __('Validating...', 'stablezact-crypto-payments'),
                    'refreshing' => __('Refreshing...', 'stablezact-crypto-payments'),
                    'wallets_updated' => __('Wallets updated successfully', 'stablezact-crypto-payments'),
                    'refresh_failed' => __('Failed to refresh data', 'stablezact-crypto-payments'),
                    'credential_warning' => __('API credentials may be invalid', 'stablezact-crypto-payments'),
                    'credential_warning_desc' => __('Please check your API credentials', 'stablezact-crypto-payments'),
                    'refresh_credentials' => __('Refresh Credentials', 'stablezact-crypto-payments')
                )
            ));
        }
    }
    
    /**
     * Enhance payment method description with benefits list.
     * 
     * @param string $description Gateway description.
     * @param string $payment_id Payment method ID.
     * @return string
     */
    public function enhance_payment_description( $description, $payment_id ) {
        if ( $payment_id !== $this->id ) {
            return $description;
        }
        
        // Add benefits list and security badge
        $enhanced_description = $description;
        $enhanced_description .= '<ul class="stablezact-benefits">';
        $enhanced_description .= '<li>' . __( 'Low transaction fees - save up to 80% on payment costs', 'stablezact-crypto-payments' ) . '</li>';
        $enhanced_description .= '<li>' . __( 'Instant settlements - no more waiting for days', 'stablezact-crypto-payments' ) . '</li>';
        $enhanced_description .= '<li>' . __( 'No chargebacks - fraud protection for merchants', 'stablezact-crypto-payments' ) . '</li>';
        $enhanced_description .= '<li>' . __( 'Global payments - accept payments from anywhere', 'stablezact-crypto-payments' ) . '</li>';
        $enhanced_description .= '</ul>';
        
        $enhanced_description .= '<div class="stablezact-security">';
        $enhanced_description .= '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">';
        $enhanced_description .= '<path d="M8 1L2 3V8C2 11.3137 4.68629 14 8 14C11.3137 14 14 11.3137 14 8V3L8 1Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>';
        $enhanced_description .= '<path d="M6 8L7 9L10 6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>';
        $enhanced_description .= '</svg>';
        $enhanced_description .= __( 'Secured by advanced blockchain technology and encryption', 'stablezact-crypto-payments' );
        $enhanced_description .= '</div>';
        
        return $enhanced_description;
    }

    /**
     * Initialize Gateway Settings Form Fields.
     */
    public function init_form_fields() {
        $this->form_fields = array(
            'enabled' => array(
                'title'       => __('Enable/Disable', 'stablezact-crypto-payments'),
                'label'       => __('Enable Stablezact Payment', 'stablezact-crypto-payments'),
                'type'        => 'checkbox',
                'description' => '',
                'default'     => 'yes'
            ),
            'title' => array(
                'title'       => __('Title', 'stablezact-crypto-payments'),
                'type'        => 'text',
                'description' => __('This controls the title which the user sees during checkout.', 'stablezact-crypto-payments'),
                'default'     => __('Pay with Cryptocurrency', 'stablezact-crypto-payments'),
                'desc_tip'    => true,
            ),
            'description' => array(
                'title'       => __('Description', 'stablezact-crypto-payments'),
                'type'        => 'textarea',
                'description' => __('This controls the description which the user sees during checkout.', 'stablezact-crypto-payments'),
                'default'     => __('Pay securely using cryptocurrency through Stablezact.', 'stablezact-crypto-payments'),
                'desc_tip'    => true,
            ),
            'public_key' => array(
                'title'       => __('Public Key', 'stablezact-crypto-payments'),
                'type'        => 'text',
                'description' => __('Your Stablezact public key (starts with pk_). Get this from your Stablezact merchant dashboard.', 'stablezact-crypto-payments'),
                'default'     => '',
                'desc_tip'    => true,
                'placeholder' => 'pk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
            ),
            'testmode' => array(
                'title'       => __('Test mode', 'stablezact-crypto-payments'),
                'label'       => __('Enable Test Mode', 'stablezact-crypto-payments'),
                'type'        => 'checkbox',
                'description' => __('Place the payment gateway in test mode.', 'stablezact-crypto-payments'),
                'default'     => 'yes',
                'desc_tip'    => true,
            ),
            'debug' => array(
                'title'       => __('Debug log', 'stablezact-crypto-payments'),
                'type'        => 'checkbox',
                'label'       => __('Enable logging', 'stablezact-crypto-payments'),
                'default'     => 'no',
                'description' => __('Log Stablezact events, such as API requests.', 'stablezact-crypto-payments'),
            ),
            'payment_timeout' => array(
                'title'       => __('Payment Timeout', 'stablezact-crypto-payments'),
                'type'        => 'number',
                'description' => __('Time in seconds before payment modal times out. Default is 300 seconds (5 minutes).', 'stablezact-crypto-payments'),
                'default'     => '300',
                'desc_tip'    => true,
                'custom_attributes' => array(
                    'min' => '60',
                    'max' => '1800',
                    'step' => '30'
                )
            ),
            'webhook_secret' => array(
                'title'       => __('Webhook Secret', 'stablezact-crypto-payments'),
                'type'        => 'text',
                'description' => __('Your webhook secret for verifying payment notifications. This is automatically generated and cannot be edited directly.', 'stablezact-crypto-payments'),
                'default'     => wp_generate_password(32, false),
                'desc_tip'    => true,
                'custom_attributes' => array(
                    'readonly' => 'readonly',
                    'style' => 'background-color: #f8fafc; color: #64748b;'
                ),
            ),
            'callback_url' => array(
                'title'       => __('Callback URL', 'stablezact-crypto-payments'),
                'type'        => 'text',
                'description' => __('The URL where Stablezact will send payment notifications. This will be automatically set.', 'stablezact-crypto-payments'),
                'default'     => home_url('/wc-api/stablezact'),
                'desc_tip'    => true,
                'custom_attributes' => array(
                    'readonly' => 'readonly'
                )
            ),

            'currency_section_title' => array(
                'title' => __('💱 Currency Conversion', 'stablezact-crypto-payments'),
                'type'  => 'title',
                'description' => __('<strong>Automatic Currency Conversion:</strong> If your store uses a currency other than USD, payments will be automatically converted to USD using real-time exchange rates from the Stablezact service.', 'stablezact-crypto-payments'),
            ),
            'currency_converter' => array(
                'title'       => __('Currency Converter', 'stablezact-crypto-payments'),
                'type'        => 'button',
                'description' => sprintf(
                    /* translators: %s: store currency code */
                    __('Preview currency conversion from %s to USD with real-time rates. Click to refresh with latest rates. <br><br><strong>💡 How it works:</strong><br>• If your store uses USD, no conversion is needed<br>• Other currencies are automatically converted to USD during checkout<br>• Exchange rates are cached for 1 hour to improve performance<br>• The rate is fetched automatically when you load this page<br><br><em>ℹ️ Rates are provided by the Stablezact service - no API key required! <br>❓ <strong>Need help?</strong> This tool is for testing only - your store will work even if this test fails.</em>', 'stablezact-crypto-payments'),
                    get_woocommerce_currency()
                ),
                'default'     => __('Refresh Rate', 'stablezact-crypto-payments'),
                'class'       => 'button-secondary',
                'custom_attributes' => array(
                    'onclick' => 'stablezact_test_conversion(); return false;'
                )
            ),
            
            'conversion_rate_display' => array(
                'title'       => __('Current Conversion Rate', 'stablezact-crypto-payments'),
                'type'        => 'text',
                'description' => __('This field shows the current conversion rate and updates automatically when you load the page. Click "Refresh Rate" above to get the latest rate.', 'stablezact-crypto-payments'),
                'default'     => '', // This will be populated by JavaScript
                'custom_attributes' => array(
                    'readonly' => 'readonly',
                    'style' => 'background-color: #f9f9f9; cursor: not-allowed; font-family: monospace; font-size: 14px;'
                )
            ),

            'fee_section_title' => array(
                'title' => __('💰 Fee Configuration', 'stablezact-crypto-payments'),
                'type'  => 'title',
                'description' => __('<strong>Fee Settings:</strong> The Stablezact fee is deducted from your payout — your customer is never charged extra. On a 100.00 order at 1%, the customer pays 100.00 and you receive 99.00. These values are set by Stablezact and cannot be changed here.', 'stablezact-crypto-payments'),
            ),
            // Read-only display. The value itself lives in the 'fee_charged_to'
            // option, which is maintained solely by refresh_fee_settings() from
            // the merchant account. Deliberately NOT an editable form field:
            // the merchant account is the source of truth, and an editable copy
            // here would be overwritten on the next settings-page load anyway.
            'fee_charged_to_info' => array(
                'title'       => __('Fee Charged To', 'stablezact-crypto-payments'),
                'type'        => 'text',
                'description' => __('The Stablezact fee is always deducted from your payout, never added to what the customer pays. This cannot be changed.', 'stablezact-crypto-payments'),
                'default'     => $this->get_fee_charged_to_label(),
                'desc_tip'    => true,
                'custom_attributes' => array(
                    'readonly' => 'readonly',
                    'style' => 'background-color: #f9f9f9; color: #333; font-weight: bold;'
                )
            ),
            'current_fee_info' => array(
                'title'       => __('Current Fee Percentage', 'stablezact-crypto-payments'),
                'type'        => 'text',
                'description' => __('Your current fee percentage as set by Stablezact admin. This is read-only and automatically updated when you login.', 'stablezact-crypto-payments'),
                'default'     => number_format(($this->current_fee_percentage ?? STABLEZACT_DEFAULT_FEE_PERCENTAGE) * 100, 2) . '%',
                'desc_tip'    => true,
                'custom_attributes' => array(
                    'readonly' => 'readonly',
                    'style' => 'background-color: #f9f9f9; color: #333; font-weight: bold;'
                )
            ),
        );
    }

    /**
     * Human-readable label for who the transaction fee is charged to.
     *
     * @return string
     */
    private function get_fee_charged_to_label() {
        // Deliberately fixed, and deliberately NOT read from the merchant
        // account's feeChargedTo field. The fee is always taken out of the
        // payment: the settlement service computes it as
        // (amount x feePercentage) and routes it to the platform wallet without
        // ever branching on feeChargedTo, so the customer is never charged a
        // surcharge. Mirroring that field made this box claim the opposite
        // whenever an account happened to be set to "customer", which is a false
        // statement about the merchant's money.
        //
        // Kept short: this renders in a fixed-width settings input, and a longer
        // sentence is silently truncated on screen.
        return __('Merchant (deducted from your payout)', 'stablezact-crypto-payments');
    }

    /**
     * Override get_option so the read-only fee displays always reflect the
     * current values rather than whatever was last written to the form.
     */
    public function get_option($key, $empty_value = null) {
        if ($key === 'current_fee_info') {
            return number_format($this->current_fee_percentage * 100, 2) . '%';
        }
        if ($key === 'fee_charged_to_info') {
            return $this->get_fee_charged_to_label();
        }
        return parent::get_option($key, $empty_value);
    }

    /**
     * Validate public key format
     *
     * @return bool
     */
    public function validate_public_key() {
        if (empty($this->public_key)) {
            return false;
        }

        // Public key should start with pk_
        if (strpos($this->public_key, 'pk_') !== 0) {
            return false;
        }

        return true;
    }

    /**
     * Verify API connection
     */
    public function test_api_connection() {
        if (!$this->api || empty($this->public_key)) {
            return new WP_Error('no_credentials', __('Public key not configured', 'stablezact-crypto-payments'));
        }

        if (!$this->validate_public_key()) {
            return new WP_Error('invalid_key', __('Invalid public key format - should start with pk_', 'stablezact-crypto-payments'));
        }

        return array(
            'success' => true,
            'message' => __('Public key configured', 'stablezact-crypto-payments'),
        );
    }

    /**
     * Create payment using enhanced API method
     */
    public function create_payment_with_network($amount, $currency, $network, $customer_email, $metadata = array()) {
        if (!$this->api) {
            return new WP_Error('no_api', __('API not configured', 'stablezact-crypto-payments'));
        }

        try {
            return $this->api->create_payment_enhanced($amount, $currency, $network, $customer_email, $metadata);
        } catch (Exception $e) {
            return new WP_Error('payment_creation_failed', $e->getMessage());
        }
    }

    /**
     * Process payment using enhanced API method
     */
    public function process_payment_with_details($payment_id, $transaction_hash, $network = null, $sender_address = null) {
        if (!$this->api) {
            return new WP_Error('no_api', __('API not configured', 'stablezact-crypto-payments'));
        }

        try {
            return $this->api->process_payment_enhanced($payment_id, $transaction_hash, $network, $sender_address);
        } catch (Exception $e) {
            return new WP_Error('payment_processing_failed', $e->getMessage());
        }
    }

    /**
     * Admin Panel Options
     */
    public function admin_options() {
        // Add notification container for enhanced notifications
        echo '<div id="stablezact-notification-container" style="margin-bottom: 20px;"></div>';

        // Show public key status
        if (!$this->validate_public_key()) {
            echo '<div class="notice notice-warning"><p>';
            echo '<strong>' . esc_html__('Stablezact Setup Required:', 'stablezact-crypto-payments') . '</strong> ';
            echo esc_html__('Please enter your Public Key from your Stablezact merchant dashboard to accept crypto payments.', 'stablezact-crypto-payments');
            echo '</p></div>';
        } else {
            // Check wallet configuration
            $wallets = $this->get_merchant_wallets();
            if (empty($wallets)) {
                echo '<div class="notice notice-warning"><p>';
                echo '<strong>' . esc_html__('Wallet Configuration Required:', 'stablezact-crypto-payments') . '</strong> ';
                printf(
                    /* translators: %1$s: opening link tag, %2$s: closing link tag */
                    esc_html__('You need to configure wallet addresses to receive payments. %1$sGo to Stablezact > Settings%2$s to add your wallet addresses.', 'stablezact-crypto-payments'),
                    '<a href="' . esc_url(admin_url('admin.php?page=stablezact-wallet-settings')) . '">',
                    '</a>'
                );
                echo '</p></div>';
            } else {
                echo '<div class="notice notice-info" style="border-left-color: #7C3AED;"><p>';
                echo '<strong>' . esc_html__('Wallet Addresses:', 'stablezact-crypto-payments') . '</strong> ';
                printf(
                    /* translators: %1$d: wallet count, %2$s: opening link tag, %3$s: closing link tag */
                    esc_html__('You have %1$d wallet(s) configured. %2$sManage wallets in Stablezact > Settings%3$s', 'stablezact-crypto-payments'),
                    count($wallets),
                    '<a href="' . esc_url(admin_url('admin.php?page=stablezact-wallet-settings')) . '">',
                    '</a>'
                );
                echo '</p></div>';
            }
        }

        // Display settings
        parent::admin_options();
    }
    
    /**
     * Display wallet synchronization status
     */
    private function display_wallet_sync_status() {
        if (empty($this->public_key)) {
            return;
        }
        
        echo '<div class="stablezact-wallet-sync-status" style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 8px; border-left: 4px solid #7C3AED;">';
        echo '<h4 style="margin: 0 0 10px 0; color: #7C3AED;"><span class="dashicons dashicons-admin-network" style="margin-right: 5px;"></span>' . esc_html__('Wallet Synchronization Status', 'stablezact-crypto-payments') . '</h4>';
        
        try {
            $wallet_addresses = $this->get_merchant_wallets();
            
            if (empty($wallet_addresses)) {
                echo '<p style="color: #d63638; margin: 0;"><span class="dashicons dashicons-warning" style="margin-right: 5px;"></span>';
                echo esc_html__('No wallet addresses configured. Please add wallet addresses in your Stablezact dashboard.', 'stablezact-crypto-payments');
                echo '</p>';
            } else {
                echo '<p style="color: #00a32a; margin: 0 0 10px 0;"><span class="dashicons dashicons-yes-alt" style="margin-right: 5px;"></span>';
                echo esc_html__('Active wallet addresses from Stablezact:', 'stablezact-crypto-payments');
                echo '</p>';
                
                echo '<div style="display: grid; gap: 10px;">';
                
                // Define network display order
                $network_order = array('ethereum', 'bsc', 'solana', 'tron', 'algorand');
                
                // Display wallets in order
                foreach ($network_order as $network) {
                    if (!isset($wallet_addresses[$network])) {
                        continue;
                    }
                    
                    $wallet_data = $wallet_addresses[$network];
                    $address = '';
                    $network_name = '';
                    $tokens = array();
                    
                    // Extract data based on structure
                    if (is_string($wallet_data)) {
                        $address = $wallet_data;
                        $network_name = ucfirst($network);
                    } elseif (is_array($wallet_data)) {
                        $address = $wallet_data['address'] ?? '';
                        $network_name = $wallet_data['networkName'] ?? ucfirst($network);
                        $tokens = $wallet_data['supportedTokens'] ?? array();
                    }
                    
                    if (empty($address)) continue;
                    
                    // Create short address for display
                    $short_address = strlen($address) > 20 ? 
                        substr($address, 0, 10) . '...' . substr($address, -8) : 
                        $address;
                    
                    // Network icons
                    $network_icons = array(
                        'ethereum' => '⟠',
                        'bsc' => '🔶',
                        'solana' => '◉',
                        'tron' => '🔷',
                        'algorand' => '🔵'
                    );
                    
                    $icon = $network_icons[$network] ?? '●';
                    
                    echo '<div style="display: flex; align-items: center; padding: 8px; background: white; border: 1px solid #e2e8f0; border-radius: 6px;">';
                    echo '<span style="font-size: 20px; margin-right: 10px;">' . esc_html($icon) . '</span>';
                    echo '<div style="flex: 1;">';
                    echo '<strong style="color: #1e293b; display: block; margin-bottom: 2px;">' . esc_html($network_name) . '</strong>';
                    echo '<code style="background: #f1f5f9; padding: 4px 8px; border-radius: 4px; font-size: 12px; color: #475569;" title="' . esc_attr($address) . '">' . esc_html($short_address) . '</code>';
                    
                    if (!empty($tokens)) {
                        echo '<div style="margin-top: 4px;">';
                        echo '<span style="font-size: 11px; color: #64748b;">Supported tokens: </span>';
                        foreach ($tokens as $token) {
                            echo '<span style="display: inline-block; background: #7C3AED; color: white; padding: 2px 6px; border-radius: 3px; font-size: 10px; margin-left: 4px;">' . esc_html($token) . '</span>';
                        }
                        echo '</div>';
                    }
                    
                    echo '</div>';
                    echo '</div>';
                }
                
                // Display any additional networks not in the standard order
                foreach ($wallet_addresses as $network => $wallet_data) {
                    if (in_array($network, $network_order)) {
                        continue; // Already displayed
                    }
                    
                    $address = is_string($wallet_data) ? $wallet_data : ($wallet_data['address'] ?? '');
                    if (empty($address)) continue;
                    
                    $short_address = strlen($address) > 20 ? 
                        substr($address, 0, 10) . '...' . substr($address, -8) : 
                        $address;
                    
                    echo '<div style="display: flex; align-items: center; padding: 8px; background: white; border: 1px solid #e2e8f0; border-radius: 6px;">';
                    echo '<span style="font-size: 20px; margin-right: 10px;">●</span>';
                    echo '<div style="flex: 1;">';
                    echo '<strong style="color: #1e293b; display: block; margin-bottom: 2px;">' . esc_html(ucfirst($network)) . '</strong>';
                    echo '<code style="background: #f1f5f9; padding: 4px 8px; border-radius: 4px; font-size: 12px; color: #475569;" title="' . esc_attr($address) . '">' . esc_html($short_address) . '</code>';
                    echo '</div>';
                    echo '</div>';
                }
                
                echo '</div>';
                
                // Show sync info
                echo '<div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid #e2e8f0;">';
                echo '<p style="margin: 0; font-size: 12px; color: #64748b;">';
                echo '<span class="dashicons dashicons-info" style="font-size: 14px; margin-right: 4px;"></span>';
                echo esc_html__('These addresses are automatically synced to your Stablezact dashboard. You can also add addresses manually in the settings above.', 'stablezact-crypto-payments');
                echo '</p>';
                echo '</div>';
            }

        } catch (Exception $e) {
            echo '<p style="color: #d63638; margin: 0;"><span class="dashicons dashicons-warning" style="margin-right: 5px;"></span>';
            printf(
                /* translators: %s: error message */
                esc_html__('Error checking wallet sync status: %s', 'stablezact-crypto-payments'),
                esc_html($e->getMessage())
            );
            echo '</p>';
        }
        
        echo '</div>';
    }

    /**
     * Process the payment and return the result.
     *
     * @param int $order_id Order ID.
     * @return array
     */
    public function process_payment($order_id) {
        $order = wc_get_order($order_id);

        if (!$order) {
            wc_add_notice(__('Order not found. Please try again.', 'stablezact-crypto-payments'), 'error');
            return array('result' => 'failure');
        }

        // Convert order amount to USD if needed
        $order_total = $order->get_total();
        $order_currency = $order->get_currency();
        
        $conversion_result = $this->convert_to_usd($order_total, $order_currency);
        
        if (is_wp_error($conversion_result)) {
            wc_add_notice(__('Currency conversion failed. Please try again.', 'stablezact-crypto-payments'), 'error');
            return array('result' => 'failure');
        }

        // Mark as pending payment (awaiting crypto payment via modal)
        $order->update_status('pending', __('Awaiting cryptocurrency payment via Stablezact', 'stablezact-crypto-payments'));
        
        // Save payment pending status and conversion data
        $order->update_meta_data('_stablezact_payment_pending', true);
        $order->update_meta_data('_stablezact_original_amount', $conversion_result['original_amount']);
        $order->update_meta_data('_stablezact_original_currency', $conversion_result['original_currency']);
        $order->update_meta_data('_stablezact_converted_amount', $conversion_result['converted_amount']);
        $order->update_meta_data('_stablezact_converted_currency', $conversion_result['converted_currency']);
        $order->update_meta_data('_stablezact_exchange_rate', $conversion_result['exchange_rate']);
        
        // Add conversion note if conversion happened
        if ($conversion_result['conversion_info']) {
            $order->add_order_note(
                sprintf(
                    /* translators: %s: conversion details */
                    __('Payment amount converted: %s', 'stablezact-crypto-payments'),
                    $conversion_result['conversion_info']
                )
            );
        }
        
        $order->save();
        
        // DON'T reduce stock or empty cart yet - wait for actual payment
        // This will be done after successful payment via AJAX
        
        // For WooCommerce Blocks, we need to handle this differently
        if ($this->is_blocks_checkout()) {
            // Return success for blocks, the JavaScript will handle the modal
            $response = array(
                'result' => 'success',
                'redirect' => false,
                'messages' => array(),
                'stablezact_order_data' => array(
                    'order_id' => $order_id,
                    'order_key' => $order->get_order_key(),
                    'order_total' => $conversion_result['converted_amount'],
                    'original_total' => $conversion_result['original_amount'],
                    'original_currency' => $conversion_result['original_currency'],
                    'converted_currency' => $conversion_result['converted_currency'],
                    'conversion_info' => $conversion_result['conversion_info']
                )
            );
            
            // Dispatch the blocks-checkout response as an inline script attached to a
            // registered (src-less) handle, per the wp_enqueue policy. This wp_footer
            // callback runs at priority 10, before footer scripts print at 20.
            add_action('wp_footer', function() use ($order_id, $order, $conversion_result) {
                $detail = wp_json_encode(array(
                    'order_id'           => $order_id,
                    'order_key'          => $order->get_order_key(),
                    'order_total'        => $conversion_result['converted_amount'],
                    'original_total'     => $conversion_result['original_amount'],
                    'original_currency'  => $conversion_result['original_currency'],
                    'converted_currency' => $conversion_result['converted_currency'],
                    'conversion_info'    => $conversion_result['conversion_info'],
                ));
                $inline = 'document.addEventListener("DOMContentLoaded", function() {'
                    . 'window.dispatchEvent(new CustomEvent("stablezact_blocks_checkout_response", { detail: ' . $detail . ' }));'
                    . '});';
                wp_register_script('stablezact-blocks-response', false, array(), STABLEZACT_VERSION, true);
                wp_enqueue_script('stablezact-blocks-response');
                wp_add_inline_script('stablezact-blocks-response', $inline);
            });
        } else {
            // Classic checkout handling
            $response = array(
                'result' => 'success',
                'redirect' => false,
                'stablezact_show_modal' => true,
                'order_data' => array(
                    'order_id' => $order_id,
                    'order_key' => $order->get_order_key(),
                    'order_total' => $conversion_result['converted_amount'],
                    'original_total' => $conversion_result['original_amount'],
                    'original_currency' => $conversion_result['original_currency'],
                    'converted_currency' => $conversion_result['converted_currency'],
                    'conversion_info' => $conversion_result['conversion_info']
                )
            );
        }
        
        // Debug logging
        
        return $response;
    }

    /**
     * Validate that public key and wallets are configured before enabling gateway
     */
    public function validate_fields() {
        // Reasons the gateway may not be enabled are recorded here rather than
        // returned as a hard failure. Failing the save outright discarded the
        // Public Key the merchant had just entered, which made first-time setup
        // unrecoverable: the key was never persisted, so the wallet lookup that
        // needs it could never succeed, so the save failed again. See
        // process_admin_options(), which applies the block by keeping the
        // gateway disabled instead of throwing the settings away.
        $this->enable_blocked_reason = null;

        // Check if public key is configured when enabling the gateway.
        // phpcs:disable WordPress.Security.NonceVerification.Missing -- Runs during WooCommerce settings save (process_admin_options), which verifies the settings nonce.
        if (isset($_POST['woocommerce_' . $this->id . '_enabled']) &&
            $_POST['woocommerce_' . $this->id . '_enabled'] === '1') {

            $public_key = isset($_POST['woocommerce_' . $this->id . '_public_key'])
                ? sanitize_text_field(wp_unslash($_POST['woocommerce_' . $this->id . '_public_key']))
                : $this->get_option('public_key');
            // phpcs:enable WordPress.Security.NonceVerification.Missing

            if (empty($public_key)) {
                $this->enable_blocked_reason = __('Stablezact was not enabled: please enter your Public Key first. Your other settings have been saved.', 'stablezact-crypto-payments');
            } elseif (strpos($public_key, 'pk_') !== 0) {
                $this->enable_blocked_reason = __('Stablezact was not enabled: that Public Key looks wrong — it should start with "pk_". Your other settings have been saved.', 'stablezact-crypto-payments');
            } else {
                // Check the key being submitted, not the one already stored. On
                // first-time setup nothing is stored yet, so checking the stored
                // value found no API credentials and reported "no wallets" no
                // matter how the dashboard was configured.
                $wallets = $this->get_merchant_wallets($public_key);
                if (empty($wallets)) {
                    // Plain text on purpose: WC_Admin_Settings::show_messages()
                    // prints these through esc_html(), so any markup here would
                    // be shown to the merchant literally.
                    $this->enable_blocked_reason = __('Stablezact was not enabled: no wallet addresses were found for this Public Key. Add at least one wallet address in your Stablezact dashboard, then enable the gateway. Your Public Key has been saved.', 'stablezact-crypto-payments');
                }
            }
        }

        // Always let the save proceed. process_admin_options() enforces the block.
        return true;
    }

    /**
     * Process admin options and sync fee settings with API
     */
    public function process_admin_options() {
        // Determine whether the gateway may be enabled. This never blocks the
        // save itself, so the merchant's credentials are always persisted.
        $this->validate_fields();

        // Save the options
        $saved = parent::process_admin_options();

        if ($saved) {
            // If enabling was blocked, keep the gateway switched off and explain
            // why. The rest of the settings — crucially the Public Key — stay saved,
            // so the merchant can fix the cause and simply enable it afterwards.
            if (!empty($this->enable_blocked_reason)) {
                $this->update_option('enabled', 'no');
                $this->enabled = 'no';
                WC_Admin_Settings::add_error($this->enable_blocked_reason);
            }

            // Check if we have public key
            $public_key = $this->get_option('public_key');

            if (!empty($public_key)) {
                // Clear wallet cache to fetch fresh data
                delete_transient('stablezact_merchant_wallets');

                WC_Admin_Settings::add_message(
                    __('Settings saved successfully! Wallet addresses are managed in your Stablezact Dashboard.', 'stablezact-crypto-payments')
                );
            } else {
                WC_Admin_Settings::add_message(
                    __('Settings saved locally. Add your Public Key to connect with Stablezact.', 'stablezact-crypto-payments')
                );
            }
        }

        return $saved;
    }

    /**
     * Sync wallet addresses to Stablezact API before saving locally
     * Note: Wallets are now managed in the Stablezact dashboard, so this method is mostly deprecated
     */
    private function sync_wallet_addresses_to_api_before_save() {
        $public_key = $this->get_option('public_key');

        if (empty($public_key)) {
            return true; // Allow save without API sync
        }

        // Wallets are managed in Stablezact dashboard, not WooCommerce
        return true;
        
        // Collect wallet addresses from form
        $wallets_to_update = array();
        $wallet_fields = array(
            'ethereum_wallet' => array('network' => 'ethereum', 'tokens' => ['USDT', 'USDC', 'DAI']),
            'bsc_wallet' => array('network' => 'bsc', 'tokens' => ['USDT', 'USDC']),
            'tron_wallet' => array('network' => 'tron', 'tokens' => ['USDT', 'USDC']),
            'algorand_wallet' => array('network' => 'algorand', 'tokens' => ['USDT', 'USDC']),
            'solana_wallet' => array('network' => 'solana', 'tokens' => ['USDT', 'USDC'])
        );
        
        foreach ($wallet_fields as $field => $config) {
            $address = $this->get_field_value($field, $this->form_fields[$field]);
            if (!empty($address) && $this->validate_wallet_address($address, $field)) {
                $wallets_to_update[] = array(
                    'networkShortName' => $config['network'],
                    'walletAddress' => $address,
                    'supportedTokens' => $config['tokens']
                );
            }
        }
        
        // If no wallets to update, still allow save
        if (empty($wallets_to_update)) {
            return true;
        }
        
        try {
            // Prepare the update payload
            $update_payload = array('wallets' => $wallets_to_update);
            
            
            $response = $api->update_merchant_wallets($update_payload);
            
            if (is_wp_error($response)) {
                WC_Admin_Settings::add_error(
                    /* translators: %s: error message */
                    sprintf(__('Failed to sync wallet addresses to Stablezact: %s', 'stablezact-crypto-payments'), $response->get_error_message())
                );
                return false;
            }
            
            // Clear the wallet cache so fresh data is fetched
            delete_transient('stablezact_merchant_wallets');
            
            return true;
            
        } catch (Exception $e) {
            WC_Admin_Settings::add_error(
                /* translators: %s: error message */
                sprintf(__('Failed to sync wallet addresses: %s', 'stablezact-crypto-payments'), $e->getMessage())
            );
            return false;
        }
    }

    /**
     * Sync wallet addresses to Stablezact API (legacy method - now unused)
     */
    private function sync_wallet_addresses_to_api() {
        // This method is now unused - keeping for backward compatibility
        // The new flow syncs before saving in sync_wallet_addresses_to_api_before_save()
        return;
    }

    /**
     * Sync fee settings to Stablezact API
     */
    private function sync_fee_settings_to_api() {
        // Only sync if API is configured
        if (empty($this->public_key) || !$this->api) {
            return;
        }

        // Get the fee_charged_to setting that was just saved
        $fee_charged_to = $this->get_option('fee_charged_to', 'customer');

        try {
            // Update merchant profile with fee setting
            $profile_data = array(
                'feeChargedTo' => $fee_charged_to
            );

            $response = $this->api->update_merchant_profile($profile_data);

            if (is_wp_error($response)) {
            }

        } catch (Exception $e) {
        }
    }

    /**
     * Check if the gateway is available for use
     */
    public function is_available() {
        if ('yes' !== $this->enabled) {
            return false;
        }

        // Check if public key is set
        if (empty($this->public_key)) {
            return false;
        }

        return true;
    }

    /**
     * Validate wallet address format based on network type
     *
     * @param string $address Wallet address to validate
     * @param string $wallet_type Type of wallet (ethereum_wallet, bsc_wallet, tron_wallet, algorand_wallet, solana_wallet)
     * @return bool
     */
    private function validate_wallet_address($address, $wallet_type) {
        if (empty($address)) {
            return false;
        }

        switch ($wallet_type) {
            case 'ethereum_wallet':
            case 'bsc_wallet':
                // Ethereum-compatible addresses (0x + 40 hex characters)
                return preg_match('/^0x[a-fA-F0-9]{40}$/', $address);
                
            case 'tron_wallet':
                // TRON addresses (T + 33 Base58 characters)
                return preg_match('/^T[a-zA-Z0-9]{33}$/', $address);
                
            case 'algorand_wallet':
                // Algorand addresses (58 Base32 characters)
                return preg_match('/^[A-Z2-7]{58}$/', $address);
                
            case 'solana_wallet':
                // Solana addresses (Base58 encoded, 32-44 characters)
                return preg_match('/^[1-9A-HJ-NP-Za-km-z]{32,44}$/', $address);
                
            default:
                return false;
        }
    }

    /**
     * Get configured wallet addresses for display/usage
     *
     * @return array Array of configured wallet addresses
     */
    public function get_configured_wallets() {
        $wallets = array();
        $wallet_fields = array(
            'ethereum_wallet' => __('Ethereum', 'stablezact-crypto-payments'),
            'bsc_wallet' => __('Binance Smart Chain', 'stablezact-crypto-payments'),
            'tron_wallet' => __('TRON', 'stablezact-crypto-payments'),
            'algorand_wallet' => __('Algorand', 'stablezact-crypto-payments'),
            'solana_wallet' => __('Solana', 'stablezact-crypto-payments')
        );

        foreach ($wallet_fields as $field => $name) {
            $address = $this->get_option($field);
            if (!empty($address) && $this->validate_wallet_address($address, $field)) {
                $wallets[$field] = array(
                    'name' => $name,
                    'address' => $address
                );
            }
        }

        return $wallets;
    }

    /**
     * Get merchant wallet addresses (API first, local cache fallback)
     */
    public function get_merchant_wallets($public_key_override = null) {
        // When a specific key is supplied (validating credentials that have been
        // submitted but are not saved yet), probe the API for that key directly:
        // skip the cache here and the stored-wallet fallback further down, so the
        // result reflects only the credentials being validated.
        $is_probe = !empty($public_key_override);

        $cached_wallets = $is_probe ? false : get_transient('stablezact_merchant_wallets');
        
        if ($cached_wallets !== false) {
            return $cached_wallets;
        }
        
        $api = $this->get_api_instance($public_key_override);
        if ($api) {
            try {
                $response = $api->get_merchant_wallets();
                
                if (!is_wp_error($response)) {
                    $formatted_wallets = $this->format_api_wallet_response($response);
                    
                    if (!empty($formatted_wallets)) {
                        // Simplify for JavaScript usage - only include configured wallets
                        $simple_wallets = array();
                        foreach ($formatted_wallets as $network => $data) {
                            if (is_array($data) && isset($data['address']) && !empty($data['address'])) {
                                $simple_wallets[$network] = $data['address'];
                            } elseif (is_string($data) && !empty($data)) {
                                $simple_wallets[$network] = $data;
                            }
                        }
                        
                        // Cache for 5 minutes
                        set_transient('stablezact_merchant_wallets', $simple_wallets, 5 * MINUTE_IN_SECONDS);
                        
                        // Also save the full data for admin display
                        update_option('stablezact_merchant_wallets_full', $formatted_wallets);
                        
                        return $simple_wallets;
                    }
                }
            } catch (Exception $e) {
            }
        }
        
        // A probe must not fall back to stored wallets: those belong to whichever
        // key was configured previously, and would wrongly validate a new key that
        // has no wallets of its own.
        if ($is_probe) {
            return array();
        }

        // Fallback to cached wallets
        $cached = get_option('stablezact_merchant_wallets_full', array());
        $simple_wallets = array();
        
        foreach ($cached as $network => $data) {
            if (is_array($data) && isset($data['address']) && !empty($data['address'])) {
                $simple_wallets[$network] = $data['address'];
            } elseif (is_string($data) && !empty($data)) {
                $simple_wallets[$network] = $data;
            }
        }
        
        return $simple_wallets;
    }
    /**
     * Format API wallet response to expected format
     */
    private function format_api_wallet_response($response) {
        $formatted_wallets = array();
        
        // Debug log the raw response
        
        // Handle the actual API response format
        if (isset($response['success']) && $response['success'] === true && isset($response['wallets']) && is_array($response['wallets'])) {
            $wallets_data = $response['wallets'];
            
            // Process each wallet entry
            foreach ($wallets_data as $wallet) {
                // Skip if no network short name
                if (!isset($wallet['networkShortName'])) {
                    continue;
                }
                
                $network = $this->normalize_network_name($wallet['networkShortName']);
                $wallet_address = $wallet['walletAddress'] ?? '';
                
                // Store wallet data including unconfigured wallets
                $formatted_wallets[$network] = array(
                    'address' => $wallet_address,
                    'networkName' => $wallet['networkName'] ?? ucfirst($network),
                    'networkType' => $wallet['networkType'] ?? $network,
                    'networkId' => $wallet['networkId'] ?? null,
                    'networkLogo' => $wallet['networkLogo'] ?? '',
                    'isConfigured' => $wallet['isConfigured'] ?? !empty($wallet_address),
                    'supportedTokens' => array()
                );
                
                // Handle both string and object wallet addresses for backward compatibility
                if (is_array($wallet_address) && isset($wallet_address['address'])) {
                    $formatted_wallets[$network]['address'] = $wallet_address['address'];
                    $formatted_wallets[$network]['supportedTokens'] = $wallet_address['supportedTokens'] ?? array();
                    $formatted_wallets[$network]['isConfigured'] = !empty($wallet_address['address']);
                }
            }
        }
        
        
        return $formatted_wallets;
    }
    

    /**
     * Normalize network name to expected format
     */
    private function normalize_network_name($network_name) {
        $network_mapping = array(
            'ethereum' => 'ethereum',
            'bsc' => 'bsc', 
            'tron' => 'tron',
            'algorand' => 'algorand',
            'solana' => 'solana',
            'sepolia' => 'sepolia',
            // Handle alternative names
            'eth' => 'ethereum',
            'bnb' => 'bsc',
            'trx' => 'tron'
        );
        
        $normalized = strtolower(trim($network_name));
        return $network_mapping[$normalized] ?? $normalized;
    }

    /**
     * Get API instance if available
     */
    private function get_api_instance($public_key_override = null) {
        $public_key = !empty($public_key_override)
            ? $public_key_override
            : $this->get_option('public_key');

        if (empty($public_key)) {
            return null;
        }

        if (!class_exists('Stablezact_API')) {
            require_once plugin_dir_path(__FILE__) . 'class-stablezact-api.php';
        }

        return new Stablezact_API(
            $public_key,
            $this->get_option('testmode') === 'yes',
            $this->get_option('debug') === 'yes'
        );
    }

    /**
     * Check if we're using WooCommerce Blocks checkout
     */
    private function is_blocks_checkout() {
        // phpcs:disable WordPress.Security.NonceVerification.Missing -- Read-only detection of the checkout context during WooCommerce's own nonce-verified checkout request; no state is changed.
        $payment_method = isset($_POST['payment_method']) ? sanitize_text_field(wp_unslash($_POST['payment_method'])) : '';
        $request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';

        return $payment_method === 'stablezact' &&
               (isset($_POST['payment_data']) ||
                strpos($request_uri, 'store/checkout') !== false ||
                (function_exists('wc_has_block_in_page') && wc_has_block_in_page(null, 'woocommerce/checkout')));
        // phpcs:enable WordPress.Security.NonceVerification.Missing
    }




    /**
     * Process a refund if supported.
     *
     * @param int    $order_id Order ID.
     * @param float  $amount Refund amount.
     * @param string $reason Refund reason.
     * @return bool|WP_Error
     */
    public function process_refund( $order_id, $amount = null, $reason = '' ) {
        $order = wc_get_order( $order_id );

        if ( ! $order ) {
            return new WP_Error( 'invalid_order', __( 'Invalid order ID.', 'stablezact-crypto-payments' ) );
        }

        $payment_id = $order->get_meta( '_stablezact_payment_id' );

        if ( ! $payment_id ) {
            return new WP_Error( 'invalid_payment', __( 'Cannot refund as no payment ID was found.', 'stablezact-crypto-payments' ) );
        }

        $refund = $this->api->refund_payment(
            $payment_id,
            array(
                'amount' => $amount,
                'reason' => $reason,
            )
        );

        if ( is_wp_error( $refund ) ) {
            return $refund;
        }

        return true;
    }

    /**
     * Handle webhook requests.
     */
    public function webhook_handler() {
        // Get the request body. The payload is HMAC signature-verified below before
        // any use, and every field read from it is sanitized on use (sanitize_text_field
        // / absint), so the raw decode itself is not trusted output.
        $request_body = file_get_contents( 'php://input' );
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- signature-verified below; decoded fields sanitized field-by-field on use.
        $data = json_decode( $request_body, true );

        if ( ! $data || ! isset( $data['event'] ) || ! isset( $data['data'] ) ) {
            status_header( 400 );
            exit( 'Invalid webhook data' );
        }

        // Verify webhook signature.
        $signature = isset($_SERVER['HTTP_STABLEZACT_SIGNATURE']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_STABLEZACT_SIGNATURE'])) : '';
        if ( ! $this->api->verify_webhook_signature( $request_body, $signature ) ) {
            status_header( 403 );
            exit( 'Invalid signature' );
        }

        // The payload is signature-verified above, but sanitize the decoded values on use.
        $event = sanitize_text_field( $data['event'] );
        $payment_data = $data['data'];

        // Get the order.
        $order_id = isset( $payment_data['metadata']['order_id'] ) ? absint( $payment_data['metadata']['order_id'] ) : 0;
        $order = wc_get_order( $order_id );

        if ( ! $order ) {
            status_header( 404 );
            exit( 'Order not found' );
        }

        // Handle different event types.
        switch ( $event ) {
            case 'payment.succeeded':
                $order->payment_complete( isset( $payment_data['id'] ) ? sanitize_text_field( $payment_data['id'] ) : '' );
                $order->add_order_note( __( 'Stablezact payment complete.', 'stablezact-crypto-payments' ) );
                break;
                
            case 'payment.failed':
                $order->update_status( 'failed', __( 'Stablezact payment failed.', 'stablezact-crypto-payments' ) );
                break;
                
            case 'payment.refunded':
                if ( ! $order->has_status( 'refunded' ) ) {
                    $order->update_status( 'refunded', __( 'Stablezact payment refunded.', 'stablezact-crypto-payments' ) );
                }
                break;
        }

        status_header( 200 );
        exit( 'Webhook processed' );
    }

    /**
     * Handle AJAX request to create WooCommerce Blocks order after successful payment.
     */
    public function handle_blocks_order_creation() {
        // Check nonce
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'stablezact_nonce')) {
            wp_send_json_error('Invalid security token');
            exit;
        }
        
        // Extract payment data from flattened POST parameters
        $payment_data = array(
            'transaction_hash' => isset($_POST['transaction_hash']) ? sanitize_text_field(wp_unslash($_POST['transaction_hash'])) : '',
            'currency' => isset($_POST['currency']) ? sanitize_text_field(wp_unslash($_POST['currency'])) : '',
            'network' => isset($_POST['network']) ? sanitize_text_field(wp_unslash($_POST['network'])) : '',
            'amount' => isset($_POST['amount']) ? sanitize_text_field(wp_unslash($_POST['amount'])) : '',
            'order_total' => isset($_POST['order_total']) ? sanitize_text_field(wp_unslash($_POST['order_total'])) : '',
            'temporary_id' => isset($_POST['temporary_id']) ? sanitize_text_field(wp_unslash($_POST['temporary_id'])) : ''
        );
        
        // Parse JSON data. Sanitizing the raw JSON string before decoding would corrupt it,
        // so unslash and decode first, then sanitize every decoded value with map_deep().
        // phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- decoded JSON is sanitized field-by-field via map_deep().
        $billing_data = isset($_POST['billing_data']) ? map_deep((array) json_decode(wp_unslash($_POST['billing_data']), true), 'sanitize_text_field') : array();
        $shipping_data = isset($_POST['shipping_data']) ? map_deep((array) json_decode(wp_unslash($_POST['shipping_data']), true), 'sanitize_text_field') : array();
        $cart_data = isset($_POST['cart_data']) ? map_deep((array) json_decode(wp_unslash($_POST['cart_data']), true), 'sanitize_text_field') : array();
        // phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        
        // Fallback for billing/shipping data if JSON parsing failed
        if (!is_array($billing_data)) $billing_data = array();
        if (!is_array($shipping_data)) $shipping_data = array();
        if (!is_array($cart_data)) $cart_data = array();
        
        // Debug: Log essential payment info
        $start_time = microtime(true);
        
        if (empty($payment_data['transaction_hash'])) {
            wp_send_json_error('Missing transaction hash in payment data');
            exit;
        }
        
        try {
            // Create a new WooCommerce order
            $order = wc_create_order();
            
            if (is_wp_error($order)) {
                throw new Exception('Failed to create order: ' . $order->get_error_message());
            }
            
            // Add cart items to the order
            $this->add_cart_items_to_order($order);
            
            // Set billing address
            if (!empty($billing_data)) {
                $order->set_address($billing_data, 'billing');
            }
            
            // Set shipping address
            if (!empty($shipping_data)) {
                $order->set_address($shipping_data, 'shipping');
            }
            
            // Set payment method
            $order->set_payment_method('stablezact');
            $order->set_payment_method_title($this->title);
            
            // Calculate totals
            $order->calculate_totals();
            
            // Update order meta with payment details
            $order->update_meta_data('_stablezact_transaction_hash', $payment_data['transaction_hash']);
            $order->update_meta_data('_stablezact_currency', $payment_data['currency']);
            $order->update_meta_data('_stablezact_network', $payment_data['network']);
            $order->update_meta_data('_stablezact_amount', $payment_data['amount']);
            
            // Add order note
            $order->add_order_note(
                sprintf(
                    /* translators: %1$s: currency code, %2$s: network name, %3$s: transaction hash */
                    __('Cryptocurrency payment completed via Stablezact Blocks. Currency: %1$s, Network: %2$s, Transaction Hash: %3$s', 'stablezact-crypto-payments'),
                    $payment_data['currency'],
                    $payment_data['network'],
                    $payment_data['transaction_hash']
                )
            );
            
            // Mark as completed and paid (this also saves the order)
            $order->payment_complete($payment_data['transaction_hash']);
            
            // Crypto payments are instant - mark as completed immediately
            $order->update_status('completed', __('Cryptocurrency payment completed instantly via Stablezact', 'stablezact-crypto-payments'));
            
            // Debug logging
            
            // Reduce stock levels
            wc_reduce_stock_levels($order->get_id());
            
            // Clear the cart
            if (WC()->cart) {
                WC()->cart->empty_cart();
            }
            
            // Performance logging
            $end_time = microtime(true);
            $execution_time = round($end_time - $start_time, 2);
            
            wp_send_json_success(array(
                'message' => 'Order created successfully',
                'order_id' => $order->get_id(),
                'redirect_url' => $order->get_checkout_order_received_url(),
                'execution_time' => $execution_time
            ));
            
        } catch (Exception $e) {
            wp_send_json_error('Order creation failed: ' . $e->getMessage());
        }
        
        exit;
    }

    /**
     * Add cart items to order for blocks checkout
     */
    private function add_cart_items_to_order($order) {
        if (!WC()->cart || WC()->cart->is_empty()) {
            return;
        }
        
        foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
            $product = $cart_item['data'];
            $quantity = $cart_item['quantity'];
            
            // Add item to order
            $item_id = $order->add_product(
                $product,
                $quantity,
                array(
                    'variation' => isset($cart_item['variation']) ? $cart_item['variation'] : array(),
                    'totals' => array(
                        'subtotal' => $cart_item['line_subtotal'],
                        'subtotal_tax' => $cart_item['line_subtotal_tax'],
                        'total' => $cart_item['line_total'],
                        'tax' => $cart_item['line_tax'],
                        'tax_data' => $cart_item['line_tax_data']
                    )
                )
            );
        }
        
        // Add fees
        foreach (WC()->cart->get_fees() as $fee) {
            $order->add_fee($fee);
        }
        
        // Add shipping
        foreach (WC()->cart->get_shipping_packages() as $package_key => $package) {
            if (isset($package['rates'])) {
                foreach ($package['rates'] as $rate) {
                    $order->add_shipping($rate);
                }
            }
        }
        
        // Add coupons
        foreach (WC()->cart->get_applied_coupons() as $coupon_code) {
            $coupon = new WC_Coupon($coupon_code);
            $order->apply_coupon($coupon);
        }
    }

    /**
     * Convert currency amount to USD using the Stablezact backend rates endpoint
     *
     * @param float $amount Amount to convert
     * @param string $from_currency Source currency code
     * @return array|WP_Error Conversion result or error
     */
    private function convert_to_usd($amount, $from_currency) {
        // If already USD, no conversion needed
        if ($from_currency === 'USD') {
            return [
                'original_amount' => $amount,
                'original_currency' => $from_currency,
                'converted_amount' => $amount,
                'converted_currency' => 'USD',
                'exchange_rate' => 1.0,
                'conversion_info' => null
            ];
        }

        // Check cache first (cache for 1 hour)
        $cache_key = 'stablezact_rate_' . strtolower($from_currency) . '_usd';
        $cached_rate = get_transient($cache_key);
        
        if ($cached_rate !== false) {
            $converted_amount = $amount / $cached_rate;
            return [
                'original_amount' => $amount,
                'original_currency' => $from_currency,
                'converted_amount' => round($converted_amount, 2),
                'converted_currency' => 'USD',
                'exchange_rate' => (1 / $cached_rate),
                'conversion_info' => sprintf(
                    '%s %s → $%s USD (Rate: 1 USD = %s %s)',
                    number_format($amount, 2),
                    $from_currency,
                    number_format($converted_amount, 2),
                    number_format($cached_rate, 4),
                    $from_currency
                )
            ];
        }

        // Fetch fresh rates from the Stablezact backend, which proxies and caches the
        // upstream rate provider server-side. The plugin never calls a third-party CDN.
        $api_url = 'https://hub.stablezact.com/api/currency/rates';

        $response = wp_remote_get($api_url, [
            'timeout' => 10,
            'headers' => [
                'User-Agent' => 'Stablezact/1.0'
            ]
        ]);

        if (is_wp_error($response)) {
            return new WP_Error('api_error', 'Currency conversion service unavailable');
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        // Backend responds: { success, cached, data: { usd: { <code>: <rate> } } }
        $rates = isset($data['data']['usd']) ? $data['data']['usd'] : null;
        if (!$rates) {
            return new WP_Error('invalid_response', 'Invalid currency data received');
        }

        $currency_key = strtolower($from_currency);
        if (!isset($rates[$currency_key])) {
            return new WP_Error('currency_not_found', 'Currency not supported: ' . $from_currency);
        }

        $rate = $rates[$currency_key]; // How many units of from_currency = 1 USD
        $converted_amount = $amount / $rate;

        // Cache the rate for 1 hour
        set_transient($cache_key, $rate, HOUR_IN_SECONDS);

        return [
            'original_amount' => $amount,
            'original_currency' => $from_currency,
            'converted_amount' => round($converted_amount, 2),
            'converted_currency' => 'USD',
            'exchange_rate' => (1 / $rate),
                         'conversion_info' => sprintf(
                 '%s %s → $%s USD (Rate: 1 USD = %s %s)',
                 number_format($amount, 2),
                 $from_currency,
                 number_format($converted_amount, 2),
                 number_format($rate, 4),
                 $from_currency
             )
         ];
     }

    /**
     * Handle AJAX request to test currency conversion
     */
    public function test_currency_conversion() {
        try {
            // Check nonce - try both WooCommerce settings nonce and admin nonce
            $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
            $nonce_valid = wp_verify_nonce($nonce, 'woocommerce-settings') ||
                          wp_verify_nonce($nonce, 'stablezact_admin_nonce');
            
            if (!$nonce_valid) {
                wp_send_json_error('Invalid security token. Please refresh the page and try again.');
                return;
            }
            
            if (!current_user_can('manage_woocommerce')) {
                wp_send_json_error('Insufficient permissions to perform this action.');
                return;
            }
            
            $test_amount = 1000; // Test with 1000 units of store currency
            $store_currency = get_woocommerce_currency();
            
            // Validate store currency
            if (empty($store_currency)) {
                wp_send_json_error('Store currency is not configured. Please check your WooCommerce settings.');
                return;
            }
            
            $start_time = microtime(true);
            $conversion_result = $this->convert_to_usd($test_amount, $store_currency);
            $end_time = microtime(true);
            
            $response_time = round(($end_time - $start_time) * 1000, 2);
            
            if (is_wp_error($conversion_result)) {
                $error_message = $conversion_result->get_error_message();
                
                // Provide more helpful error messages
                if (strpos($error_message, 'HTTP request failed') !== false) {
                    $error_message = 'Unable to connect to currency exchange service. Please check your internet connection or try again later.';
                } elseif (strpos($error_message, 'Invalid response') !== false) {
                    $error_message = 'Currency exchange service returned invalid data. This may be a temporary issue.';
                }
                
                wp_send_json_error($error_message);
                return;
            }
            
            // Ensure conversion_result is properly formatted
            if (!is_array($conversion_result)) {
                wp_send_json_error('Invalid conversion result format. Please try again.');
                return;
            }
            
            $message = 'Currency conversion is working perfectly!';
            if ($store_currency === 'USD') {
                $message = 'Your store already uses USD - no conversion needed!';
            }
            
            // Safe fallback for conversion info
            $conversion_info = '';
            if (isset($conversion_result['conversion_info']) && !empty($conversion_result['conversion_info'])) {
                $conversion_info = $conversion_result['conversion_info'];
            } else {
                $conversion_info = sprintf('%s %s = %s USD (1:1 ratio)', 
                    number_format($test_amount, 2), 
                    $store_currency, 
                    number_format($test_amount, 2)
                );
            }
            
            wp_send_json_success([
                'message' => $message,
                'conversion_info' => $conversion_info,
                'response_time' => $response_time . 'ms',
                'api_source' => 'Stablezact currency service',
                'cache_status' => get_transient('stablezact_rate_' . strtolower($store_currency) . '_usd') ? 'Used cached rate' : 'Fetched fresh rate'
            ]);
            
        } catch (Exception $e) {
            wp_send_json_error('An unexpected error occurred during currency conversion. Please try again or contact support if the issue persists.');
        }
    }

    /**
     * Handle updating fee settings via AJAX
     * REMOVED: Fee settings are now handled through standard admin settings save
     */

    /**
     * Old AJAX handlers removed - CoinleyVanilla SDK handles all payment processing
     * The following methods were removed as they're no longer needed:
     * - handle_payment_processing()
     * - handle_wallet_connection()  
     * - handle_payment_cancellation()
     * - handle_create_stablezact_payment()
     * - handle_process_stablezact_payment()
     */


    /**
     * Maybe refresh fee settings on admin pages
     */
    public function maybe_refresh_fee_settings() {
        // Only refresh on WooCommerce settings pages.
        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only check of which admin page is loading; no state is changed.
        if (is_admin() && isset($_GET['page']) && $_GET['page'] === 'wc-settings' &&
            isset($_GET['tab']) && $_GET['tab'] === 'checkout' &&
            isset($_GET['section']) && $_GET['section'] === 'stablezact') {
            // phpcs:enable WordPress.Security.NonceVerification.Recommended

            if ($this->public_key) {
                $this->refresh_fee_settings();
            }
        }
    }

    /**
     * Refresh fee settings from the API using the same endpoint as admin dashboard
     */
    private function refresh_fee_settings() {
        try {
            if ($this->debug) {
            }
            
            // Use the same API call as admin dashboard
            $response = $this->api->get_comprehensive_merchant_data();
            
            if ($this->debug) {
            }
            
            if (!is_wp_error($response) && isset($response['merchant'])) {
                $merchant = $response['merchant'];
                
                // Get fee percentage from merchant data (same as dashboard)
                $fee_percentage = floatval($merchant['customFeePercentage'] ?? STABLEZACT_DEFAULT_FEE_PERCENTAGE);
                $fee_charged_to = $merchant['feeChargedTo'] ?? 'customer';
                
                // Update instance variables
                $this->current_fee_percentage = $fee_percentage;
                $this->fee_charged_to = $fee_charged_to;
                
                // Update the settings in WP options
                $this->update_option('current_fee_percentage', $this->current_fee_percentage);
                $this->update_option('fee_charged_to', $this->fee_charged_to);
                
                if ($this->debug) {
                }
            } else {
                if ($this->debug) {
                    if (is_wp_error($response)) {
                    } else {
                    }
                }
            }
        } catch (Exception $e) {
            if ($this->debug) {
                wc_get_logger()->debug(
                    'Failed to refresh fee settings: ' . $e->getMessage(),
                    array('source' => 'stablezact')
                );
            }
        }
    }
} 