<?php
/**
 * M2C Red Envelope Payment Gateway Class
 * 
 * Uses gateway ID 'f2c' to replace the old Factory 2 Consumer gateway
 */

defined('ABSPATH') || exit;

class WC_Gateway_M2C_Red_Envelope extends WC_Payment_Gateway {

    /**
     * Constructor
     */
    public function __construct() {
        // Unique gateway ID
        $this->id                 = 'red_envelope';
        $this->icon               = MRE_PLUGIN_URL . 'assets/icon.svg';
        $this->has_fields         = true;
        $this->method_title       = __('Red Envelope Payment', 'ab2bc-red-envelope');
        $this->method_description = __('Accept USDC payments via Red Envelope Wallet on AQY Chain. Customers receive AQY Coins rewards.', 'ab2bc-red-envelope');
        
        // Supported features
        $this->supports = array(
            'products',
            'refunds',
        );

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

        // Get settings
        $this->enabled          = $this->get_option('enabled', 'no');
        $this->title            = $this->get_option('title', 'Red Envelope Payment');
        $this->description      = $this->get_option('description', '');
        $this->merchant_wallet  = $this->get_option('merchant_wallet', '');
        $this->reward_percent   = $this->get_option('reward_percent', '60');
        $this->merchant_commission_pct = $this->get_option('merchant_commission_pct', '50');
        $this->aqy_base_price   = $this->get_option('aqy_base_price', '0.10');
        $this->api_endpoint     = $this->get_option('api_endpoint', 'https://m2c.ab2bc.com/api');
        $this->rpc_endpoint     = $this->get_option('rpc_endpoint', 'https://rpc.aqy.ab2bc.com');
        $this->auto_sync_catalog = $this->get_option('auto_sync_catalog', 'no');
        $this->auto_sync_orders  = $this->get_option('auto_sync_orders', 'no');

        // Hooks
        add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
        add_action('woocommerce_thankyou_' . $this->id, array($this, 'thankyou_page'));
        add_action('woocommerce_email_before_order_table', array($this, 'email_instructions'), 10, 3);
        
        // AJAX handlers for payment status polling
        add_action('wp_ajax_mre_check_payment', array($this, 'ajax_check_payment'));
        add_action('wp_ajax_nopriv_mre_check_payment', array($this, 'ajax_check_payment'));
        
        // AJAX handler for M2C verification
        add_action('wp_ajax_mre_verify_m2c_wallet', array($this, 'ajax_verify_m2c_wallet'));

        // AJAX handler for WC API key generation (AUY Utility connection)
        add_action('wp_ajax_mre_generate_wc_api_key', array($this, 'ajax_generate_wc_api_key'));

        // Global admin notices for unverified merchant
        add_action('admin_notices', array($this, 'admin_notice_unverified_merchant'));

        // WP Cron: periodic merchant verification health check
        add_action('mre_merchant_verification_check', array($this, 'cron_verify_merchant'));
        if (!wp_next_scheduled('mre_merchant_verification_check')) {
            wp_schedule_event(time(), 'twicedaily', 'mre_merchant_verification_check');
        }

        // Admin dashboard widget for merchant verification status
        add_action('wp_dashboard_setup', array($this, 'add_dashboard_widget'));
    }

    /**
     * Check if the merchant wallet has been verified as a valid M2C member.
     * Uses a cached transient (refreshed every 12 hours) to avoid API spam.
     * 
     * @return array|false  Verification result array or false if never verified
     */
    public function get_wallet_verification_status() {
        if (empty($this->merchant_wallet)) {
            return false;
        }
        return get_transient('mre_wallet_verified_' . md5($this->merchant_wallet));
    }

    /**
     * Store wallet verification result in transient cache.
     * 
     * @param string $wallet  Wallet address
     * @param array  $result  Verification result from verify_m2c_account()
     */
    private function cache_wallet_verification($wallet, $result) {
        // Cache for 12 hours if verified, 15 minutes if failed (so admin can retry quickly)
        $ttl = !empty($result['valid']) ? 12 * HOUR_IN_SECONDS : 15 * MINUTE_IN_SECONDS;
        set_transient('mre_wallet_verified_' . md5($wallet), $result, $ttl);
    }

    /**
     * Check if the merchant wallet is verified and valid.
     * 
     * @return bool
     */
    public function is_merchant_verified() {
        $status = $this->get_wallet_verification_status();
        return is_array($status) && !empty($status['valid']);
    }

    /**
     * WP Cron: Periodic merchant verification health check.
     * Runs twice daily. If verification has lapsed or fails, disables the gateway
     * and sends an email alert to the site admin and any WooCommerce admin.
     */
    public function cron_verify_merchant() {
        if (empty($this->merchant_wallet)) {
            return;
        }

        $previous_status = $this->get_wallet_verification_status();
        $was_verified = is_array($previous_status) && !empty($previous_status['valid']);

        // Re-verify against the M2C API
        $result = $this->verify_m2c_account($this->merchant_wallet);
        $this->cache_wallet_verification($this->merchant_wallet, $result);

        $is_verified = !empty($result['valid']);

        // --- Status change: was verified, now NOT verified ---
        if ($was_verified && !$is_verified) {
            // Force-disable the gateway
            $this->update_option('enabled', 'no');
            $this->enabled = 'no';

            error_log('[M2C Red Envelope] CRON: Merchant verification LOST for wallet ' . $this->merchant_wallet . '. Gateway disabled. Reason: ' . ($result['message'] ?? 'unknown'));

            $this->send_merchant_alert_email(
                'critical',
                '🚨 Red Envelope Payment DISABLED — Merchant Verification Lost',
                $result
            );
        }

        // --- Still not verified (already was failing) ---
        if (!$was_verified && !$is_verified && $this->get_option('enabled', 'no') === 'yes') {
            // Safety net: if somehow the gateway is still enabled, disable it
            $this->update_option('enabled', 'no');
            $this->enabled = 'no';

            error_log('[M2C Red Envelope] CRON: Gateway was enabled with unverified wallet. Force-disabled.');
        }

        // --- Re-verified after previous failure ---
        if (!$was_verified && $is_verified) {
            error_log('[M2C Red Envelope] CRON: Merchant verification RESTORED for wallet ' . $this->merchant_wallet);

            $this->send_merchant_alert_email(
                'resolved',
                '✅ M2C Merchant Verification Restored — Action Required to Re-Enable',
                $result
            );
        }
    }

    /**
     * Send an email alert to the site admin about merchant verification status changes.
     *
     * @param string $severity  'critical' | 'warning' | 'resolved'
     * @param string $subject   Email subject
     * @param array  $result    Verification result array
     */
    private function send_merchant_alert_email($severity, $subject, $result) {
        $admin_email = get_option('admin_email');
        $site_name   = get_bloginfo('name');
        $settings_url = admin_url('admin.php?page=wc-settings&tab=checkout&section=red_envelope');
        $wallet_short = substr($this->merchant_wallet, 0, 10) . '...' . substr($this->merchant_wallet, -8);

        $colors = array(
            'critical' => '#e74c3c',
            'warning'  => '#f39c12',
            'resolved' => '#27ae60',
        );
        $border_color = $colors[$severity] ?? '#999';

        $body = '<div style="font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif; max-width: 600px; margin: 0 auto;">';
        $body .= '<div style="background: ' . $border_color . '; color: white; padding: 20px; border-radius: 8px 8px 0 0;">';
        $body .= '<h2 style="margin: 0; color: white;">' . esc_html($subject) . '</h2>';
        $body .= '</div>';
        $body .= '<div style="background: #f9f9f9; padding: 20px; border: 1px solid #ddd; border-top: none; border-radius: 0 0 8px 8px;">';

        $body .= '<p><strong>Site:</strong> ' . esc_html($site_name) . '</p>';
        $body .= '<p><strong>Merchant Wallet:</strong> <code>' . esc_html($wallet_short) . '</code></p>';
        $body .= '<p><strong>Full Address:</strong> <code style="word-break: break-all; font-size: 12px;">' . esc_html($this->merchant_wallet) . '</code></p>';

        if ($severity === 'critical') {
            $body .= '<div style="background: #fdf2f2; border-left: 4px solid #e74c3c; padding: 15px; margin: 15px 0;">';
            $body .= '<p style="margin: 0 0 8px; font-weight: bold; color: #c0392b;">⚠️ IMMEDIATE ACTION REQUIRED</p>';
            $body .= '<p style="margin: 0;">The Red Envelope Payment gateway has been <strong>automatically disabled</strong> because your M2C merchant account verification has failed.</p>';
            $body .= '</div>';
            $body .= '<p><strong>Reason:</strong> ' . esc_html($result['message'] ?? 'Verification failed') . '</p>';
            $body .= '<p><strong>Impact:</strong> Customers <strong>cannot</strong> pay with Red Envelope Payment until this is resolved.</p>';
            $body .= '<h3>Steps to Resolve:</h3>';
            $body .= '<ol>';
            $body .= '<li>Open your <a href="https://re.ab2bc.com">Red Envelope Wallet</a> and ensure you have a merchant account</li>';
            $body .= '<li>Join M2C as a merchant through your wallet</li>';
            $body .= '<li>Complete the M2C Member approval process</li>';
            $body .= '<li>Go to <a href="' . esc_url($settings_url) . '">Red Envelope Settings</a></li>';
            $body .= '<li>Click "Verify M2C Account" and save changes</li>';
            $body .= '</ol>';
        } elseif ($severity === 'resolved') {
            $body .= '<div style="background: #f0fff4; border-left: 4px solid #27ae60; padding: 15px; margin: 15px 0;">';
            $body .= '<p style="margin: 0;">Your M2C merchant account has been successfully re-verified.</p>';
            $body .= '</div>';
            $body .= '<p><strong>Status:</strong> ' . esc_html($result['message'] ?? 'Verified') . '</p>';
            $body .= '<p>The gateway was previously disabled for safety. To <strong>re-enable</strong> it:</p>';
            $body .= '<ol>';
            $body .= '<li>Go to <a href="' . esc_url($settings_url) . '">Red Envelope Settings</a></li>';
            $body .= '<li>Check "Enable Red Envelope Payment"</li>';
            $body .= '<li>Save changes</li>';
            $body .= '</ol>';
        } else {
            $body .= '<p><strong>Status:</strong> ' . esc_html($result['message'] ?? 'Unknown') . '</p>';
        }

        $body .= '<p style="margin-top: 20px; padding-top: 15px; border-top: 1px solid #ddd; font-size: 12px; color: #999;">';
        $body .= 'This is an automated alert from the M2C Red Envelope Payment Gateway (v' . MRE_VERSION . '). ';
        $body .= 'Verification is checked every 12 hours. ';
        $body .= 'Time: ' . current_time('mysql') . '</p>';

        $body .= '</div></div>';

        $headers = array(
            'Content-Type: text/html; charset=UTF-8',
            'From: ' . $site_name . ' <' . $admin_email . '>',
        );

        wp_mail($admin_email, '[' . $site_name . '] ' . $subject, $body, $headers);

        // Also log to WooCommerce logger if available
        if (function_exists('wc_get_logger')) {
            $logger = wc_get_logger();
            $logger->log(
                $severity === 'critical' ? 'critical' : 'info',
                $subject . ' | Wallet: ' . $wallet_short . ' | ' . ($result['message'] ?? ''),
                array('source' => 'mre-merchant-verification')
            );
        }
    }

    /**
     * Add a dashboard widget showing the merchant verification status at a glance.
     */
    public function add_dashboard_widget() {
        if (!current_user_can('manage_woocommerce')) {
            return;
        }
        wp_add_dashboard_widget(
            'mre_merchant_status_widget',
            '🧧 Red Envelope — Merchant Status',
            array($this, 'render_dashboard_widget')
        );
    }

    /**
     * Render the dashboard widget content.
     */
    public function render_dashboard_widget() {
        $settings_url = admin_url('admin.php?page=wc-settings&tab=checkout&section=red_envelope');
        $is_enabled = $this->enabled === 'yes';

        if (empty($this->merchant_wallet)) {
            echo '<div style="padding: 10px; background: #fff3cd; border-left: 4px solid #f39c12; margin-bottom: 10px;">';
            echo '<strong>⚠️ No Merchant Wallet Configured</strong>';
            echo '<p style="margin: 5px 0 0;">Red Envelope Payment is not set up. Customers cannot use this payment method.</p>';
            echo '</div>';
            echo '<a href="' . esc_url($settings_url) . '" class="button button-primary">Configure Now</a>';
            return;
        }

        $status = $this->get_wallet_verification_status();
        $is_verified = is_array($status) && !empty($status['valid']);
        $wallet_short = substr($this->merchant_wallet, 0, 10) . '...' . substr($this->merchant_wallet, -8);

        if ($is_verified) {
            echo '<div style="padding: 10px; background: #d4edda; border-left: 4px solid #27ae60; margin-bottom: 10px;">';
            echo '<strong style="color: #155724;">✅ Merchant Verified</strong>';
            echo '<p style="margin: 5px 0 0; font-size: 13px;">';
            echo 'Wallet: <code style="font-size: 12px;">' . esc_html($wallet_short) . '</code><br>';
            if (!empty($status['membership']['username'])) {
                echo 'Account: <strong>' . esc_html($status['membership']['username']) . '</strong><br>';
            }
            if (!empty($status['membership']['membershipLevel'])) {
                echo 'Level: ' . esc_html(ucfirst($status['membership']['membershipLevel'])) . '<br>';
            }
            echo 'KYM: ' . (!empty($status['membership']['hasKYM']) ? '✅ Approved' : '⚠️ Not completed') . '<br>';
            echo 'Gateway: ' . ($is_enabled ? '<span style="color: #27ae60;">Active</span>' : '<span style="color: #e74c3c;">Disabled</span>');
            echo '</p></div>';
        } else {
            echo '<div style="padding: 10px; background: #f8d7da; border-left: 4px solid #e74c3c; margin-bottom: 10px;">';
            echo '<strong style="color: #721c24;">❌ Merchant NOT Verified</strong>';
            echo '<p style="margin: 5px 0 0; font-size: 13px;">';
            echo 'Wallet: <code style="font-size: 12px;">' . esc_html($wallet_short) . '</code><br>';
            if (is_array($status)) {
                echo 'Reason: <em>' . esc_html($status['message'] ?? 'Unknown') . '</em><br>';
            } else {
                echo 'Status: <em>Never verified</em><br>';
            }
            echo 'Gateway: <span style="color: #e74c3c;"><strong>Disabled</strong> (payments blocked)</span>';
            echo '</p></div>';
            echo '<p style="color: #c0392b; font-weight: bold;">⚠️ Customers cannot pay with Red Envelope until verified.</p>';
        }

        // Next scheduled check
        $next_check = wp_next_scheduled('mre_merchant_verification_check');
        if ($next_check) {
            $time_until = human_time_diff(time(), $next_check);
            echo '<p style="font-size: 12px; color: #666;">Next auto-check: in ' . esc_html($time_until) . '</p>';
        }

        echo '<a href="' . esc_url($settings_url) . '" class="button">Go to Settings</a>';
    }

    /**
     * Display persistent admin notice when merchant is unverified.
     * Shows on ALL admin pages — not just WooCommerce settings —
     * because the merchant must be aware the payment method is non-functional.
     * Also shows when gateway is disabled due to failed verification.
     */
    public function admin_notice_unverified_merchant() {
        // Only show to WooCommerce admins
        if (!current_user_can('manage_woocommerce')) {
            return;
        }

        $settings_url = admin_url('admin.php?page=wc-settings&tab=checkout&section=red_envelope');

        // Case 1: Gateway enabled but wallet empty
        if ($this->enabled === 'yes' && empty($this->merchant_wallet)) {
            echo '<div class="notice notice-error is-dismissible" style="border-left: 4px solid #e74c3c; background: #fdf2f2;">';
            echo '<p><strong>🚨 Red Envelope Payment Gateway — Merchant Wallet Missing</strong></p>';
            echo '<p>The gateway is <strong>enabled</strong> but no merchant wallet is configured. ';
            echo '<strong>Customers cannot checkout</strong> with Red Envelope Payment.</p>';
            echo '<p><a href="' . esc_url($settings_url) . '" class="button button-primary">Configure Merchant Wallet</a></p>';
            echo '</div>';
            return;
        }

        // Case 2: Wallet is set but NOT verified (regardless of enabled state)
        if (!empty($this->merchant_wallet) && !$this->is_merchant_verified()) {
            $status = $this->get_wallet_verification_status();
            $msg = is_array($status) ? ($status['message'] ?? 'Verification failed') : 'Wallet has not been verified yet';
            $error_type = is_array($status) ? ($status['error_type'] ?? '') : '';
            $wallet_short = substr($this->merchant_wallet, 0, 10) . '...' . substr($this->merchant_wallet, -8);

            echo '<div class="notice notice-error" style="border-left: 4px solid #e74c3c; background: #fdf2f2;">';
            echo '<p><strong>🚨 Red Envelope Payment Gateway — M2C Merchant Verification FAILED</strong></p>';
            echo '<p>Wallet <code>' . esc_html($wallet_short) . '</code> is <strong>not verified</strong> as an active M2C member.</p>';
            echo '<p><strong>Reason:</strong> <em>' . esc_html($msg) . '</em></p>';

            if ($this->enabled === 'yes') {
                echo '<p style="color: #c0392b; font-weight: bold;">⚠️ The gateway is enabled but payments will be BLOCKED until verification passes.</p>';
            } else {
                echo '<p>The gateway has been <strong>automatically disabled</strong>. Payments are blocked.</p>';
            }

            echo '<div style="background: #fff; border: 1px solid #ddd; padding: 12px; border-radius: 4px; margin: 10px 0;">';
            echo '<strong>Steps to resolve:</strong>';
            echo '<ol style="margin: 5px 0 0 20px;">';
            echo '<li>Open your <a href="https://re.ab2bc.com" target="_blank">Red Envelope Wallet</a> and ensure you have a merchant account</li>';
            echo '<li>Join M2C as a merchant and complete the approval process</li>';
            if ($error_type === 'network') {
                echo '<li>Check that the M2C API endpoint is reachable from your server</li>';
            }
            echo '<li>Go to <a href="' . esc_url($settings_url) . '">Red Envelope Settings</a> and click <strong>"Verify M2C Account"</strong></li>';
            echo '<li>Save changes to re-enable the gateway</li>';
            echo '</ol></div>';

            echo '<p>';
            echo '<a href="' . esc_url($settings_url) . '" class="button button-primary">Go to Settings &amp; Verify</a> ';
            echo '<a href="https://re.ab2bc.com" target="_blank" class="button">Open Red Envelope Wallet</a>';
            echo '</p>';
            echo '</div>';
            return;
        }

        // Case 3: Verified but gateway disabled (reminder to re-enable)
        if ($this->is_merchant_verified() && $this->enabled !== 'yes') {
            // Only show this as an info notice, not error
            echo '<div class="notice notice-info is-dismissible" style="border-left: 4px solid #3498db;">';
            echo '<p><strong>ℹ️ Red Envelope Payment Gateway — Verified but Disabled</strong></p>';
            echo '<p>Your M2C merchant account is verified, but the payment gateway is currently <strong>disabled</strong>. ';
            echo 'Enable it to start accepting Red Envelope payments.</p>';
            echo '<p><a href="' . esc_url($settings_url) . '" class="button button-primary">Enable Payment Gateway</a></p>';
            echo '</div>';
        }
    }
    
    /**
     * Verify if a wallet address has an active M2C account
     * 
     * @param string $wallet_address The wallet address to verify
     * @return array ['valid' => bool, 'message' => string, 'membership' => array|null]
     */
    public function verify_m2c_account($wallet_address) {
        $api_endpoint = !empty($this->api_endpoint) 
            ? rtrim($this->api_endpoint, '/') 
            : 'https://m2c.ab2bc.com/api';
        
        // Call M2C Backend to verify membership
        $url = $api_endpoint . '/bonds/wallet/' . $wallet_address . '/membership';
        
        $response = wp_remote_get($url, array(
            'timeout' => 10,
            'headers' => array(
                'Accept' => 'application/json',
            ),
        ));
        
        if (is_wp_error($response)) {
            return array(
                'valid' => false,
                'message' => 'Could not verify M2C membership: ' . $response->get_error_message(),
                'membership' => null,
                'verified' => false,
            );
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!$data || !isset($data['success'])) {
            return array(
                'valid' => false,
                'message' => 'Invalid response from M2C backend',
                'membership' => null,
                'verified' => false,
            );
        }
        
        if (!$data['success'] || !$data['isMember']) {
            return array(
                'valid' => false,
                'message' => 'This wallet is not registered as an M2C member. Please open your Red Envelope Wallet at re.ab2bc.com, join M2C as a merchant, and complete the approval process.',
                'membership' => null,
                'verified' => true,
            );
        }
        
        // Check for KYM (merchant verification)
        $has_kym = !empty($data['hasKYM']) && $data['kymStatus'] === 'approved';
        
        return array(
            'valid' => true,
            'message' => $has_kym 
                ? 'M2C Merchant verified' 
                : 'M2C Member verified (consider KYM for enhanced features)',
            'membership' => array(
                'userId' => $data['userId'] ?? null,
                'username' => $data['username'] ?? null,
                'referralCode' => $data['referralCode'] ?? null,
                'hasKYC' => $data['hasKYC'] ?? false,
                'hasKYM' => $has_kym,
                'hasKYG' => $data['hasKYG'] ?? false,
                'membershipLevel' => $data['membershipLevel'] ?? 'basic',
            ),
            'verified' => true,
        );
    }
    
    /**
     * AJAX handler to verify M2C wallet
     */
    public function ajax_verify_m2c_wallet() {
        check_ajax_referer('mre_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(array('message' => 'Unauthorized'));
            return;
        }
        
        $wallet_address = sanitize_text_field($_POST['wallet_address'] ?? '');
        
        if (empty($wallet_address)) {
            wp_send_json_error(array('message' => 'Wallet address is required'));
            return;
        }
        
        // Validate wallet format
        if (!preg_match('/^0x[a-fA-F0-9]{40,64}$/', $wallet_address)) {
            wp_send_json_error(array('message' => 'Invalid wallet address format'));
            return;
        }
        
        $result = $this->verify_m2c_account($wallet_address);
        
        // Cache the verification result
        $this->cache_wallet_verification($wallet_address, $result);
        
        if ($result['valid']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result);
        }
    }

    /**
     * AJAX: Generate WooCommerce REST API keys for AUY Utility connection.
     * Creates a read-only key pair so the merchant can import products into AUY.
     */
    public function ajax_generate_wc_api_key() {
        check_ajax_referer('mre_admin_nonce', 'nonce');

        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(array('message' => 'Unauthorized'));
            return;
        }

        global $wpdb;
        $user_id = get_current_user_id();
        $table   = $wpdb->prefix . 'woocommerce_api_keys';

        // Check if an AUY key already exists for this user
        $existing = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$table} WHERE user_id = %d AND description LIKE %s",
            $user_id, '%AUY Utility%'
        ));

        if ($existing) {
            wp_send_json_error(array(
                'message' => 'An AUY Utility API key already exists. Delete it from WooCommerce → Settings → Advanced → REST API if you need a new one.',
                'consumer_key' => 'ck_' . str_repeat('•', 30) . ' (already generated — shown only once at creation)',
            ));
            return;
        }

        // Ensure WC hashing helpers are loaded (defensive — they live in wc-api-functions.php)
        if (!function_exists('wc_rand_hash') || !function_exists('wc_api_hash')) {
            if (defined('WC_ABSPATH') && file_exists(WC_ABSPATH . 'includes/wc-api-functions.php')) {
                require_once WC_ABSPATH . 'includes/wc-api-functions.php';
            }
        }
        if (!function_exists('wc_rand_hash') || !function_exists('wc_api_hash')) {
            wp_send_json_error(array('message' => 'WooCommerce API helpers unavailable (wc_rand_hash / wc_api_hash). Ensure WooCommerce is active.'));
            return;
        }

        // Generate key pair using WC's own method
        $consumer_key    = 'ck_' . wc_rand_hash();
        $consumer_secret = 'cs_' . wc_rand_hash();

        $data = array(
            'user_id'         => $user_id,
            'description'     => 'AUY Utility — Catalog Import (auto-generated by Red Envelope plugin)',
            'permissions'     => 'read',
            'consumer_key'    => wc_api_hash($consumer_key),
            'consumer_secret' => $consumer_secret,
            'truncated_key'   => substr($consumer_key, -7),
            'last_access'     => null,
        );

        // Suppress "errors" param hiding so we can read $wpdb->last_error
        $prev_show = $wpdb->show_errors(false);
        $prev_supp = $wpdb->suppress_errors(true);
        $ok = $wpdb->insert($table, $data, array('%d', '%s', '%s', '%s', '%s', '%s', '%s'));
        $insert_id = $wpdb->insert_id;
        $last_err  = $wpdb->last_error;
        $wpdb->show_errors($prev_show);
        $wpdb->suppress_errors($prev_supp);

        if ($ok !== false && $insert_id) {
            // Persist a marker so admin page can still detect the key after reload, even if
            // a future schema check fails. We only store the truncated tail + key_id.
            update_user_meta($user_id, 'mre_auy_wc_api_key_id', (int) $insert_id);
            update_user_meta($user_id, 'mre_auy_wc_api_key_truncated', substr($consumer_key, -7));
            update_user_meta($user_id, 'mre_auy_wc_api_key_created', current_time('mysql'));

            wp_send_json_success(array(
                'consumer_key'    => $consumer_key,
                'consumer_secret' => $consumer_secret,
                'key_id'          => (int) $insert_id,
                'message'         => 'API keys generated! Copy them now — the secret will not be shown again.',
            ));
        } else {
            wp_send_json_error(array(
                'message'   => 'Failed to create API key. ' . ($last_err ? 'DB: ' . $last_err : 'No row inserted.'),
                'table'     => $table,
                'db_error'  => $last_err,
                'wp_result' => $ok,
            ));
        }
    }

    /**
     * Override process_admin_options to enforce wallet verification on save.
     */
    public function process_admin_options() {
        // Save options first
        $saved = parent::process_admin_options();

        // Reload settings after save
        $this->init_settings();
        $wallet = $this->get_option('merchant_wallet', '');
        $enabled = $this->get_option('enabled', 'no');

        if (!empty($wallet)) {
            // Verify the wallet whenever settings are saved
            $result = $this->verify_m2c_account($wallet);
            $this->cache_wallet_verification($wallet, $result);

            if (!$result['valid'] && $enabled === 'yes') {
                // Force-disable the gateway — unverified wallet must not accept payments
                $this->update_option('enabled', 'no');
                $this->enabled = 'no';
                WC_Admin_Settings::add_error(
                    __('🚨 Red Envelope Payment has been DISABLED because the merchant wallet is not verified as an active M2C member. ', 'ab2bc-red-envelope') .
                    __('Reason: ', 'ab2bc-red-envelope') . ($result['message'] ?? 'Verification failed.') . ' ' .
                    __('Please open your Red Envelope Wallet at re.ab2bc.com, join M2C as a merchant, then click "Verify M2C Account" and save again.', 'ab2bc-red-envelope')
                );
            } elseif ($result['valid']) {
                WC_Admin_Settings::add_message(
                    '✅ ' . ($result['message'] ?? 'M2C Merchant verified') .
                    (!empty($result['membership']['username']) ? ' — Account: ' . $result['membership']['username'] : '')
                );
            }
        } elseif ($enabled === 'yes') {
            // No wallet but trying to enable
            $this->update_option('enabled', 'no');
            $this->enabled = 'no';
            WC_Admin_Settings::add_error(
                __('🚨 Red Envelope Payment cannot be enabled without a Merchant Wallet Address. Please enter your wallet address and verify your M2C account.', 'ab2bc-red-envelope')
            );
        }

        return $saved;
    }

    /**
     * Check if gateway needs setup - controls "Complete setup" button.
     * Requires BOTH a wallet address AND verified M2C membership.
     */
    public function needs_setup() {
        if (empty($this->merchant_wallet)) {
            return true;
        }
        return !$this->is_merchant_verified();
    }

    /**
     * Admin Panel Options
     */
    public function admin_options() {
        // Auto-verify on settings page load if wallet is set but not yet verified
        $verification_status = null;
        if (!empty($this->merchant_wallet)) {
            $verification_status = $this->get_wallet_verification_status();
            if (!$verification_status) {
                // Never verified — do it now
                $verification_status = $this->verify_m2c_account($this->merchant_wallet);
                $this->cache_wallet_verification($this->merchant_wallet, $verification_status);
            }
        }
        $is_verified = is_array($verification_status) && !empty($verification_status['valid']);
        ?>
        <h2><?php _e('Red Envelope Payment Gateway', 'ab2bc-red-envelope'); ?> 
            <span style="background: linear-gradient(135deg, #f39c12, #e74c3c); color: white; padding: 3px 10px; border-radius: 12px; font-size: 12px;">v<?php echo MRE_VERSION; ?></span>
            <?php if ($is_verified) : ?>
                <span style="background: #27ae60; color: white; padding: 3px 10px; border-radius: 12px; font-size: 12px; margin-left: 5px;">✅ Merchant Verified</span>
            <?php elseif (!empty($this->merchant_wallet)) : ?>
                <span style="background: #e74c3c; color: white; padding: 3px 10px; border-radius: 12px; font-size: 12px; margin-left: 5px;">❌ Not Verified</span>
            <?php endif; ?>
        </h2>
        <p><?php _e('Accept USDC payments on AQY Chain. Customers pay with their Red Envelope Wallet and receive AQY Coins rewards.', 'ab2bc-red-envelope'); ?></p>
        
        <?php if (empty($this->merchant_wallet)) : ?>
        <div class="notice notice-warning" style="border-left-color: #f39c12; padding: 12px;">
            <p><strong>⚠️ <?php _e('Setup Required', 'ab2bc-red-envelope'); ?></strong></p>
            <p><?php _e('Please enter your Merchant Wallet Address and verify your M2C account to start accepting payments.', 'ab2bc-red-envelope'); ?></p>
            <p><?php _e('Don\'t have an M2C account? Open your', 'ab2bc-red-envelope'); ?> <a href="https://re.ab2bc.com" target="_blank">Red Envelope Wallet</a> <?php _e('and join M2C as a merchant.', 'ab2bc-red-envelope'); ?></p>
        </div>
        <?php elseif (!$is_verified) : ?>
        <div class="notice notice-error" style="border-left-color: #e74c3c; padding: 12px;">
            <p><strong>🚨 <?php _e('M2C Merchant Account Not Verified', 'ab2bc-red-envelope'); ?></strong></p>
            <p><?php _e('Your wallet address is not registered as an active M2C merchant member.', 'ab2bc-red-envelope'); ?>
            <?php if (is_array($verification_status) && !empty($verification_status['message'])) : ?>
                <br><em><?php echo esc_html($verification_status['message']); ?></em>
            <?php endif; ?></p>
            <p><strong><?php _e('The payment gateway will be disabled until your M2C account is verified.', 'ab2bc-red-envelope'); ?></strong></p>
            <p><?php _e('Steps to resolve:', 'ab2bc-red-envelope'); ?></p>
            <ol>
                <li><?php _e('Open your', 'ab2bc-red-envelope'); ?> <a href="https://re.ab2bc.com" target="_blank"><?php _e('Red Envelope Wallet', 'ab2bc-red-envelope'); ?></a> <?php _e('and join M2C as a merchant', 'ab2bc-red-envelope'); ?></li>
                <li><?php _e('Complete KYM (Know Your Merchant) verification', 'ab2bc-red-envelope'); ?></li>
                <li><?php _e('Click "Verify M2C Account" below to confirm', 'ab2bc-red-envelope'); ?></li>
                <li><?php _e('Save changes to enable the gateway', 'ab2bc-red-envelope'); ?></li>
            </ol>
        </div>
        <?php else : ?>
        <div class="notice notice-success" style="border-left-color: #27ae60; padding: 12px;">
            <p><strong>✅ <?php _e('M2C Merchant Account Verified', 'ab2bc-red-envelope'); ?></strong></p>
            <p><?php
                echo esc_html($verification_status['message'] ?? 'Account verified');
                if (!empty($verification_status['membership']['username'])) {
                    echo ' — ' . __('Account:', 'ab2bc-red-envelope') . ' <strong>' . esc_html($verification_status['membership']['username']) . '</strong>';
                }
                if (!empty($verification_status['membership']['membershipLevel'])) {
                    echo ' (Level: ' . esc_html(ucfirst($verification_status['membership']['membershipLevel'])) . ')';
                }
            ?></p>
        </div>
        <?php endif; ?>

        <table class="form-table">
            <?php $this->generate_settings_html(); ?>
        </table>

        <hr style="margin: 30px 0;">
        <h3>🔌 <?php _e('AUY Utility Connection — WooCommerce API Keys', 'ab2bc-red-envelope'); ?></h3>
        <p style="color: #666;"><?php _e('To import your WooCommerce products into the <strong>AUY Utility</strong> dashboard ("Import from WordPress"), you need WooCommerce REST API keys. Use the button below to generate a read-only key pair, then paste them into the AUY Utility import form.', 'ab2bc-red-envelope'); ?></p>
        
        <?php
        // Check for existing AUY keys. Note: WooCommerce's wp_woocommerce_api_keys table has
        // NO date_created column on current WC versions — only key_id, user_id, description,
        // permissions, consumer_key, consumer_secret, nonces, truncated_key, last_access.
        global $wpdb;
        $current_uid = get_current_user_id();
        $auy_key = $wpdb->get_row($wpdb->prepare(
            "SELECT key_id, truncated_key, last_access FROM {$wpdb->prefix}woocommerce_api_keys WHERE user_id = %d AND description LIKE %s ORDER BY key_id DESC LIMIT 1",
            $current_uid, '%AUY Utility%'
        ));
        // Fallback: use user_meta marker written at generation time (covers schema variants and
        // ensures the success state persists across reload even if the SELECT is somehow null).
        if (!$auy_key) {
            $meta_id        = (int) get_user_meta($current_uid, 'mre_auy_wc_api_key_id', true);
            $meta_truncated = (string) get_user_meta($current_uid, 'mre_auy_wc_api_key_truncated', true);
            $meta_created   = (string) get_user_meta($current_uid, 'mre_auy_wc_api_key_created', true);
            if ($meta_id && $meta_truncated) {
                $auy_key = (object) array(
                    'key_id'        => $meta_id,
                    'truncated_key' => $meta_truncated,
                    'last_access'   => null,
                    '_meta_created' => $meta_created,
                );
            }
        }
        ?>
        
        <?php if ($auy_key) : ?>
        <div style="background: #d4edda; border: 1px solid #28a745; padding: 15px; border-radius: 6px; margin-bottom: 15px;">
            <p style="margin: 0;">✅ <strong><?php _e('AUY Utility API key exists', 'ab2bc-red-envelope'); ?></strong>
                — <?php _e('Key ending in:', 'ab2bc-red-envelope'); ?> <code>...<?php echo esc_html($auy_key->truncated_key); ?></code>
                <?php if (!empty($auy_key->_meta_created)) : ?>
                    (<?php _e('created:', 'ab2bc-red-envelope'); ?> <?php echo esc_html(date_i18n(get_option('date_format'), strtotime($auy_key->_meta_created))); ?>)
                <?php elseif (!empty($auy_key->last_access)) : ?>
                    (<?php _e('last used:', 'ab2bc-red-envelope'); ?> <?php echo esc_html(date_i18n(get_option('date_format'), strtotime($auy_key->last_access))); ?>)
                <?php endif; ?>
            </p>
            <p style="margin: 8px 0 0; color: #155724; font-size: 13px;">
                <?php _e('The keys were shown only once when generated. If you lost them, delete this key from', 'ab2bc-red-envelope'); ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=wc-settings&tab=advanced&section=keys')); ?>"><?php _e('WooCommerce → Advanced → REST API', 'ab2bc-red-envelope'); ?></a>
                <?php _e('and generate new ones here.', 'ab2bc-red-envelope'); ?>
            </p>
        </div>
        <?php else : ?>
        <div id="mre-auy-keys-section" style="background: #fff3cd; border: 1px solid #ffc107; padding: 15px; border-radius: 6px; margin-bottom: 15px;">
            <p style="margin: 0 0 10px;">
                <strong>⚠️ <?php _e('No AUY Utility API key found.', 'ab2bc-red-envelope'); ?></strong>
                <?php _e('Click below to generate a read-only key pair for catalog import.', 'ab2bc-red-envelope'); ?>
            </p>
            <button type="button" class="button button-primary" id="mre-generate-wc-key">
                🔑 <?php _e('Generate API Keys for AUY Utility', 'ab2bc-red-envelope'); ?>
            </button>
        </div>
        <div id="mre-auy-keys-result" style="display: none; background: #d4edda; border: 1px solid #28a745; padding: 20px; border-radius: 6px; margin-bottom: 15px;">
            <h4 style="margin-top: 0; color: #155724;">✅ <?php _e('API Keys Generated — Copy Them Now!', 'ab2bc-red-envelope'); ?></h4>
            <p style="color: #e74c3c; font-weight: bold; font-size: 13px;">⚠️ <?php _e('The Consumer Secret will NOT be shown again. Copy both values now and paste into AUY Utility.', 'ab2bc-red-envelope'); ?></p>
            <table style="width: 100%; border-collapse: collapse;">
                <tr>
                    <td style="padding: 8px; font-weight: bold; width: 150px;"><?php _e('Consumer Key:', 'ab2bc-red-envelope'); ?></td>
                    <td style="padding: 8px;"><input type="text" id="mre-ck" readonly style="width: 100%; font-family: monospace; background: #f8f9fa; border: 1px solid #ccc; padding: 8px;"></td>
                    <td style="padding: 8px; width: 60px;"><button type="button" class="button mre-copy-btn" data-target="mre-ck">📋 <?php _e('Copy', 'ab2bc-red-envelope'); ?></button></td>
                </tr>
                <tr>
                    <td style="padding: 8px; font-weight: bold;"><?php _e('Consumer Secret:', 'ab2bc-red-envelope'); ?></td>
                    <td style="padding: 8px;"><input type="text" id="mre-cs" readonly style="width: 100%; font-family: monospace; background: #f8f9fa; border: 1px solid #ccc; padding: 8px;"></td>
                    <td style="padding: 8px;"><button type="button" class="button mre-copy-btn" data-target="mre-cs">📋 <?php _e('Copy', 'ab2bc-red-envelope'); ?></button></td>
                </tr>
            </table>
            <p style="margin-top: 12px; font-size: 13px; color: #155724;">
                <?php _e('Paste these into the AUY Utility → Manage Catalogs → Import from WordPress form.', 'ab2bc-red-envelope'); ?>
            </p>
        </div>
        <?php endif; ?>
        
        <p style="color: #888; font-size: 12px; margin-bottom: 20px;">
            <?php _e('You can also manage API keys manually at:', 'ab2bc-red-envelope'); ?>
            <a href="<?php echo esc_url(admin_url('admin.php?page=wc-settings&tab=advanced&section=keys')); ?>"><?php _e('WooCommerce → Settings → Advanced → REST API', 'ab2bc-red-envelope'); ?></a>
        </p>

        <h3><?php _e('How It Works', 'ab2bc-red-envelope'); ?></h3>
        <ol>
            <li><?php _e('Customer selects Red Envelope Payment at checkout', 'ab2bc-red-envelope'); ?></li>
            <li><?php _e('Customer scans QR code with Red Envelope Wallet app', 'ab2bc-red-envelope'); ?></li>
            <li><?php _e('Customer pays in USDC on AQY Chain', 'ab2bc-red-envelope'); ?></li>
            <li><?php _e('Customer receives AQY Coins rewards instantly', 'ab2bc-red-envelope'); ?></li>
            <li><?php _e('You receive USDC in your merchant wallet', 'ab2bc-red-envelope'); ?></li>
        </ol>
        
        <script>
        jQuery(function($) {
            // Add verify button after merchant_wallet field
            var $walletField = $('#woocommerce_red_envelope_merchant_wallet');
            if ($walletField.length) {
                var $verifyBtn = $('<button type="button" class="button button-primary" id="mre-verify-wallet" style="margin-left: 10px; vertical-align: middle;">Verify M2C Account</button>');
                var $statusSpan = $('<span id="mre-wallet-status" style="margin-left: 10px; display: inline-block; vertical-align: middle;"></span>');
                $walletField.after($statusSpan).after($verifyBtn);
                
                // Show current verification status from PHP
                <?php if ($is_verified) : ?>
                    $statusSpan.html('<span style="color: green; font-weight: bold;">✅ Verified M2C Merchant</span>');
                <?php elseif (!empty($this->merchant_wallet) && is_array($verification_status)) : ?>
                    $statusSpan.html('<span style="color: red; font-weight: bold;">❌ <?php echo esc_js($verification_status['message'] ?? 'Not verified'); ?></span>' +
                        '<br><small style="color: #666;">Open your <a href="https://re.ab2bc.com" target="_blank">Red Envelope Wallet</a>, join M2C as a merchant, then retry.</small>');
                <?php endif; ?>
                
                $verifyBtn.on('click', function() {
                    var wallet = $walletField.val().trim();
                    if (!wallet) {
                        $statusSpan.html('<span style="color: orange; font-weight: bold;">⚠️ Please enter a wallet address first</span>');
                        return;
                    }
                    if (!/^0x[a-fA-F0-9]{40,64}$/.test(wallet)) {
                        $statusSpan.html('<span style="color: red;">❌ Invalid wallet format. Must start with 0x followed by 40-64 hex characters.</span>');
                        return;
                    }
                    
                    $verifyBtn.prop('disabled', true).text('Verifying...');
                    $statusSpan.html('<span style="color: blue;">🔄 Checking M2C membership...</span>');
                    
                    $.ajax({
                        url: ajaxurl,
                        method: 'POST',
                        data: {
                            action: 'mre_verify_m2c_wallet',
                            nonce: '<?php echo wp_create_nonce('mre_admin_nonce'); ?>',
                            wallet_address: wallet
                        },
                        success: function(response) {
                            $verifyBtn.prop('disabled', false).text('Verify M2C Account');
                            if (response.success) {
                                var m = response.data.membership || {};
                                var msg = m.hasKYM ? '✅ M2C Merchant Verified' : '✅ M2C Member Verified';
                                var detail = m.username ? ' — Account: ' + m.username : '';
                                detail += m.membershipLevel ? ' (Level: ' + m.membershipLevel + ')' : '';
                                $statusSpan.html('<span style="color: green; font-weight: bold;">' + msg + detail + '</span>' +
                                    '<br><small style="color: #27ae60;">Account verified. Save changes to enable the gateway.</small>');
                                // Flash the save button to remind admin to save
                                $('button.woocommerce-save-button, .woocommerce-save-button').css('background', '#27ae60').delay(2000).queue(function(n) { $(this).css('background', ''); n(); });
                            } else {
                                var errorMsg = response.data.message || 'Verification failed';
                                $statusSpan.html(
                                    '<span style="color: red; font-weight: bold;">❌ ' + errorMsg + '</span>' +
                                    '<br><small style="color: #e74c3c;">⚠️ The gateway will be <strong>disabled</strong> until verification passes.</small>' +
                                    '<br><small style="color: #666;">Open your <a href="https://re.ab2bc.com" target="_blank">Red Envelope Wallet</a>, join M2C as a merchant, then retry.</small>'
                                );
                            }
                        },
                        error: function() {
                            $verifyBtn.prop('disabled', false).text('Verify M2C Account');
                            $statusSpan.html('<span style="color: red;">❌ Network error — could not reach M2C server</span>');
                        }
                    });
                });
                
                // Auto-verify when wallet field changes
                var verifyTimeout;
                $walletField.on('input', function() {
                    clearTimeout(verifyTimeout);
                    $statusSpan.html('<span style="color: #999;">Type wallet address then click Verify...</span>');
                });
            }
            
            // AUY Utility API key generation
            $('#mre-generate-wc-key').on('click', function() {
                var $btn = $(this);
                $btn.prop('disabled', true).text('Generating...');
                $.ajax({
                    url: ajaxurl,
                    method: 'POST',
                    data: {
                        action: 'mre_generate_wc_api_key',
                        nonce: '<?php echo wp_create_nonce('mre_admin_nonce'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#mre-ck').val(response.data.consumer_key);
                            $('#mre-cs').val(response.data.consumer_secret);
                            $('#mre-auy-keys-section').hide();
                            $('#mre-auy-keys-result').show();
                        } else {
                            alert(response.data.message || 'Failed to generate keys');
                            $btn.prop('disabled', false).html('🔑 Generate API Keys for AUY Utility');
                        }
                    },
                    error: function() {
                        alert('Network error — could not generate keys');
                        $btn.prop('disabled', false).html('🔑 Generate API Keys for AUY Utility');
                    }
                });
            });
            
            // Copy buttons
            $('.mre-copy-btn').on('click', function() {
                var target = document.getElementById($(this).data('target'));
                target.select();
                document.execCommand('copy');
                $(this).text('✅ Copied!');
                var $b = $(this);
                setTimeout(function() { $b.text('📋 Copy'); }, 2000);
            });
        });
        </script>
        <?php
    }

    /**
     * Initialize Gateway Settings Form Fields
     */
    public function init_form_fields() {
        $this->form_fields = array(
            'enabled' => array(
                'title'       => __('Enable/Disable', 'ab2bc-red-envelope'),
                'type'        => 'checkbox',
                'label'       => __('Enable Red Envelope Payment', 'ab2bc-red-envelope'),
                'default'     => 'no',
            ),
            'title' => array(
                'title'       => __('Title', 'ab2bc-red-envelope'),
                'type'        => 'text',
                'description' => __('Payment method title shown at checkout.', 'ab2bc-red-envelope'),
                'default'     => __('Red Envelope Payment', 'ab2bc-red-envelope'),
                'desc_tip'    => true,
            ),
            'description' => array(
                'title'       => __('Description', 'ab2bc-red-envelope'),
                'type'        => 'textarea',
                'description' => __('Payment method description shown at checkout. Leave blank to use default.', 'ab2bc-red-envelope'),
                'default'     => '',
                'desc_tip'    => true,
            ),
            'merchant_wallet' => array(
                'title'       => __('Merchant Wallet Address', 'ab2bc-red-envelope'),
                'type'        => 'text',
                'description' => __('Your Red Envelope Wallet address for receiving USDC payments. Get this from your Red Envelope Wallet app.', 'ab2bc-red-envelope'),
                'default'     => '',
                'placeholder' => '0x...',
                'desc_tip'    => true,
            ),
            'reward_percent' => array(
                'title'       => __('Consumer Reward Share %', 'ab2bc-red-envelope'),
                'type'        => 'number',
                'description' => __('Consumer\'s share of the M2C commission AQY pool (from distribution config). Default 60%.', 'ab2bc-red-envelope'),
                'default'     => '60',
                'desc_tip'    => true,
                'custom_attributes' => array(
                    'min'  => '0',
                    'max'  => '100',
                    'step' => '1',
                ),
            ),
            'merchant_commission_pct' => array(
                'title'       => __('Merchant Commission % (KYM)', 'ab2bc-red-envelope'),
                'type'        => 'number',
                'description' => __('M2C Reward percentage from merchant\'s KYM (gratuity_percentage). This is deducted from the order total as commission.', 'ab2bc-red-envelope'),
                'default'     => '50',
                'desc_tip'    => true,
                'custom_attributes' => array(
                    'min'  => '0',
                    'max'  => '100',
                    'step' => '1',
                ),
            ),
            'aqy_base_price' => array(
                'title'       => __('AQY Base Price (USDC)', 'ab2bc-red-envelope'),
                'type'        => 'text',
                'description' => __('Price of 1 AQY token in USDC from oracle. E.g. 0.10 means 1 USDC = 10 AQY.', 'ab2bc-red-envelope'),
                'default'     => '0.10',
                'desc_tip'    => true,
            ),
            'api_endpoint' => array(
                'title'       => __('AB2BC API Endpoint', 'ab2bc-red-envelope'),
                'type'        => 'text',
                'description' => __('AB2BC backend API URL for payment processing.', 'ab2bc-red-envelope'),
                'default'     => 'https://m2c.ab2bc.com/api',
                'desc_tip'    => true,
            ),
            'rpc_endpoint' => array(
                'title'       => __('Blockchain RPC Endpoint', 'ab2bc-red-envelope'),
                'type'        => 'text',
                'description' => __('AQY Chain RPC endpoint for verifying transactions.', 'ab2bc-red-envelope'),
                'default'     => 'https://rpc.aqy.ab2bc.com',
                'desc_tip'    => true,
            ),
            'test_mode' => array(
                'title'       => __('Test Mode', 'ab2bc-red-envelope'),
                'type'        => 'select',
                'description' => __('<strong>Auto:</strong> Local IPs/devnet = test mode, public URLs = production.<br><strong>Yes:</strong> Force test mode (accepts wallet webhook notifications without blockchain verification).<br><strong>No:</strong> Force production (requires blockchain verification).', 'ab2bc-red-envelope'),
                'default'     => 'auto',
                'options'     => array(
                    'auto' => __('Auto-detect (recommended)', 'ab2bc-red-envelope'),
                    'yes'  => __('Yes - Force test mode', 'ab2bc-red-envelope'),
                    'no'   => __('No - Force production mode', 'ab2bc-red-envelope'),
                ),
            ),
            
            // AUY Utility Auto-Sync Settings
            'auy_sync_section' => array(
                'title'       => __('AUY Utility Auto-Sync', 'ab2bc-red-envelope'),
                'type'        => 'title',
                'description' => __('Automatically keep your WooCommerce store and AUY Utility portal in sync. Requires a valid WooCommerce API key connection in the AUY portal.', 'ab2bc-red-envelope'),
            ),
            'auto_sync_catalog' => array(
                'title'       => __('Auto-Sync Catalog / Products', 'ab2bc-red-envelope'),
                'type'        => 'checkbox',
                'label'       => __('Automatically sync categories and products between AUY portal and WooCommerce (every 15 minutes)', 'ab2bc-red-envelope'),
                'description' => __('When enabled, product changes in the AUY Utility portal are automatically pushed to WooCommerce, and WooCommerce product changes are pulled into AUY.', 'ab2bc-red-envelope'),
                'default'     => 'no',
                'desc_tip'    => true,
            ),
            'auto_sync_orders' => array(
                'title'       => __('Auto-Upload Orders to AUY', 'ab2bc-red-envelope'),
                'type'        => 'checkbox',
                'label'       => __('Automatically upload new WooCommerce orders to AUY Utility for unified order management', 'ab2bc-red-envelope'),
                'description' => __('When a new WooCommerce order is placed (any payment method), it is uploaded to the AUY portal so the merchant can manage all orders in one place.', 'ab2bc-red-envelope'),
                'default'     => 'no',
                'desc_tip'    => true,
            ),
            
            // QR Payment API Settings (Optional)
            'qr_api_section' => array(
                'title'       => __('QR Payment API (Optional)', 'ab2bc-red-envelope'),
                'type'        => 'title',
                'description' => __('Optional: Connect to external QR Payment API for centralized multi-site QR management. Leave empty to use built-in QR generation.', 'ab2bc-red-envelope'),
            ),
            'qr_api_endpoint' => array(
                'title'       => __('QR API URL', 'ab2bc-red-envelope'),
                'type'        => 'text',
                'description' => __('QR Payment API endpoint (e.g., https://qr-api.yourdomain.com). Leave empty to disable.', 'ab2bc-red-envelope'),
                'default'     => '',
                'placeholder' => 'https://qr-api.yourdomain.com',
                'desc_tip'    => true,
            ),
            'qr_api_key' => array(
                'title'       => __('QR API Key', 'ab2bc-red-envelope'),
                'type'        => 'text',
                'description' => __('Your merchant API key from QR Payment API.', 'ab2bc-red-envelope'),
                'default'     => '',
                'placeholder' => 're_live_xxxxxxxxxxxx',
                'desc_tip'    => true,
            ),
            'qr_api_secret' => array(
                'title'       => __('QR API Secret', 'ab2bc-red-envelope'),
                'type'        => 'password',
                'description' => __('Your merchant API secret for signing requests.', 'ab2bc-red-envelope'),
                'default'     => '',
                'desc_tip'    => true,
            ),
            'qr_api_webhook_secret' => array(
                'title'       => __('QR API Webhook Secret', 'ab2bc-red-envelope'),
                'type'        => 'password',
                'description' => __('Webhook secret for verifying callbacks from QR API.', 'ab2bc-red-envelope'),
                'default'     => '',
                'desc_tip'    => true,
            ),
        );
    }

    /**
     * Check if gateway is available at checkout.
     * Requires: enabled, wallet set, AND wallet verified as M2C member.
     */
    public function is_available() {
        if (empty($this->merchant_wallet)) {
            return false;
        }
        if (!$this->is_merchant_verified()) {
            return false;
        }
        return parent::is_available();
    }

    /**
     * Payment fields shown at checkout
     */
    public function payment_fields() {
        $reward_percent = $this->reward_percent ? $this->reward_percent : '60';
        
        // Custom description or default
        $description = $this->description;
        if (empty($description)) {
            $description = sprintf(
                __('Pay with USDC via Red Envelope Wallet on AQY Chain and receive %s%% of your purchase as AQY Coins rewards! Your reward will be sent to your Red Envelope Wallet instantly as a receipt, with full value released when your order ships.', 'ab2bc-red-envelope'),
                $reward_percent
            );
        }
        
        echo '<div class="mre-payment-box" style="background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); color: white; padding: 20px; border-radius: 8px;">';
        
        // Description
        echo '<p style="color: #e0e0e0; margin-bottom: 15px;">' . wp_kses_post($description) . '</p>';
        
        // Reward badge
        echo '<div style="display: inline-block; background: linear-gradient(135deg, #f39c12, #e74c3c); color: white; padding: 8px 20px; border-radius: 20px; font-weight: bold; margin-bottom: 15px;">';
        echo '🎁 ' . esc_html($reward_percent) . '% AQY Coins Reward!';
        echo '</div>';
        
        // Payment instructions
        echo '<div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 6px; margin-top: 10px;">';
        echo '<p style="color: #fff; margin: 0 0 10px 0;"><strong>' . __('How to pay:', 'ab2bc-red-envelope') . '</strong></p>';
        echo '<ol style="color: #e0e0e0; margin: 0; padding-left: 20px;">';
        echo '<li>' . __('Complete your order', 'ab2bc-red-envelope') . '</li>';
        echo '<li>' . __('Scan the QR code with your Red Envelope Wallet app', 'ab2bc-red-envelope') . '</li>';
        echo '<li>' . __('Confirm the USDC payment on AQY Chain', 'ab2bc-red-envelope') . '</li>';
        echo '<li>' . __('Receive your AQY Coins rewards instantly!', 'ab2bc-red-envelope') . '</li>';
        echo '</ol>';
        echo '</div>';
        
        echo '</div>';
    }

    /**
     * Validate payment fields — double-check verification at checkout.
     */
    public function validate_fields() {
        if (empty($this->merchant_wallet)) {
            wc_add_notice(__('Red Envelope Payment is not properly configured — merchant wallet is missing. Please contact the store.', 'ab2bc-red-envelope'), 'error');
            return false;
        }
        if (!$this->is_merchant_verified()) {
            wc_add_notice(__('Red Envelope Payment is temporarily unavailable — merchant account verification pending. Please choose another payment method or contact the store.', 'ab2bc-red-envelope'), 'error');
            return false;
        }
        return true;
    }

    /**
     * Process the payment
     * Strictly enforces merchant verification before accepting any payment.
     */
    public function process_payment($order_id) {
        $order = wc_get_order($order_id);

        if (!$order) {
            return array('result' => 'failure');
        }

        // ── STRICT ENFORCEMENT: Re-verify merchant at payment time ──
        // This is the last line of defense. Even if is_available() and
        // validate_fields() both passed, a cached verification could have
        // expired between page load and payment submission.
        if (empty($this->merchant_wallet)) {
            wc_add_notice(
                __('Red Envelope Payment cannot process this order — the merchant wallet is not configured. Please contact the store owner.', 'ab2bc-red-envelope'),
                'error'
            );
            $order->add_order_note('🚨 Payment BLOCKED: No merchant wallet configured.');
            return array('result' => 'failure');
        }

        if (!$this->is_merchant_verified()) {
            // Attempt a live re-verification in case transient just expired
            $live_check = $this->verify_m2c_account($this->merchant_wallet);
            $this->cache_wallet_verification($this->merchant_wallet, $live_check);

            if (empty($live_check['valid'])) {
                wc_add_notice(
                    __('Red Envelope Payment is temporarily unavailable — the merchant\'s M2C account could not be verified. Please choose another payment method or try again later.', 'ab2bc-red-envelope'),
                    'error'
                );
                $order->add_order_note(
                    '🚨 Payment BLOCKED: Merchant M2C verification failed at payment time. Reason: ' .
                    ($live_check['message'] ?? 'Unknown')
                );
                error_log('[M2C Red Envelope] Payment BLOCKED for order #' . $order_id . ': merchant verification failed.');

                // Auto-disable gateway to prevent further failed attempts
                $this->update_option('enabled', 'no');
                $this->enabled = 'no';

                // Send alert email
                $this->send_merchant_alert_email(
                    'critical',
                    '🚨 Payment Blocked — Merchant Verification Failed During Checkout',
                    $live_check
                );

                return array('result' => 'failure');
            }
        }
        // ── END verification enforcement ──

        // Store payment details
        $order->update_meta_data('_mre_merchant_wallet', $this->merchant_wallet);
        $order->update_meta_data('_mre_reward_percent', $this->reward_percent);
        $order->update_meta_data('_mre_payment_status', 'pending');
        $order->update_meta_data('_mre_merchant_verified_at', current_time('mysql'));

        // ── v4.1: Split order into bonus vs M2C portions ──
        $bonus_total = 0.0;
        $m2c_total   = 0.0;
        $bonus_items = array();

        foreach ($order->get_items() as $item) {
            $product_id  = $item->get_product_id();
            $is_bonus    = get_post_meta($product_id, '_m2c_bonus_enabled', true) === 'yes';
            $item_total  = floatval($item->get_total());

            if ($is_bonus) {
                $bonus_total += $item_total;
                $bonus_product_id = get_post_meta($product_id, '_m2c_bonus_product_id', true);
                $bonus_aqy        = floatval(get_post_meta($product_id, '_m2c_bonus_amount', true));
                $bonus_items[]    = array(
                    'product_id'   => $bonus_product_id ?: $product_id,
                    'product_name' => $item->get_name(),
                    'aqy_amount'   => $bonus_aqy,
                    'quantity'     => $item->get_quantity(),
                    'usdc_amount'  => $item_total,
                );
            } else {
                $m2c_total += $item_total;
            }
        }

        $order->update_meta_data('_mre_bonus_total', $bonus_total);
        $order->update_meta_data('_mre_m2c_total', $m2c_total);
        if (!empty($bonus_items)) {
            $order->update_meta_data('_mre_bonus_items', $bonus_items);
        }
        // ── END bonus/M2C split ──

        // Calculate reward amount:
        // - Bonus products: use product-defined AQY amount (_m2c_bonus_amount × qty)
        // - M2C products:   formula: (m2c_total × merchant_commission%) / aqy_price × consumer%
        //   e.g. ($199 × 50%) / $0.10 × 60% = 597 AQY
        $bonus_aqy_total = 0.0;
        foreach ($bonus_items as $bi) {
            $bonus_aqy_total += floatval($bi['aqy_amount']) * intval($bi['quantity']);
        }

        // M2C commission: merchant KYM defines what % of sale goes to commission
        // Then convert USDC commission to AQY via oracle price, then take consumer share
        $merchant_pct = floatval($this->merchant_commission_pct) ?: 50;
        $aqy_price    = floatval($this->aqy_base_price) ?: 0.10;
        $consumer_pct = floatval($this->reward_percent) ?: 60;

        $commission_usdc  = $m2c_total * ($merchant_pct / 100);         // e.g. $199 × 50% = $99.50
        $total_aqy_tokens = ($aqy_price > 0) ? ($commission_usdc / $aqy_price) : 0;  // $99.50 / $0.10 = 995 AQY
        $m2c_reward       = $total_aqy_tokens * ($consumer_pct / 100);  // 995 × 60% = 597 AQY

        $reward_amount = $bonus_aqy_total + $m2c_reward;
        $order->update_meta_data('_mre_reward_amount', $reward_amount);
        $order->update_meta_data('_mre_bonus_aqy_total', $bonus_aqy_total);
        $order->update_meta_data('_mre_m2c_reward', $m2c_reward);
        $order->update_meta_data('_mre_merchant_commission_pct', $merchant_pct);
        $order->update_meta_data('_mre_aqy_base_price', $aqy_price);
        $order->update_meta_data('_mre_consumer_pct', $consumer_pct);

        // Set order status to pending payment
        $order->update_status('pending', __('Awaiting Red Envelope USDC payment on AQY Chain.', 'ab2bc-red-envelope'));
        $order->save();

        // Reduce stock levels
        wc_reduce_stock_levels($order_id);

        // Empty cart
        WC()->cart->empty_cart();

        // Return success - redirect to thank you page with payment instructions
        return array(
            'result'   => 'success',
            'redirect' => $this->get_return_url($order),
        );
    }

    /**
     * Public hook for WooCommerce Admin's PaymentsProviders badge.
     * WC checks this method first (before reading the 'test_mode' option) when
     * deciding whether to render the yellow "Test mode" pill on the Payments
     * settings list. We always return false so the merchant-facing badge shows
     * "Active" \u2014 the internal `test_mode` setting (used for webhook acceptance
     * and blockchain-bypass logic) is governed by is_test_mode() below and is
     * independent of this admin badge.
     *
     * @return bool Always false (badge displays "Active", not "Test mode")
     */
    public function is_in_test_mode() {
        return false;
    }

    /**
     * Determine if test mode is enabled
     * Checks explicit setting first, then auto-detects based on RPC endpoint
     * 
     * @param string $rpc_endpoint The RPC endpoint URL
     * @return bool True if test mode, false for production
     */
    private function is_test_mode($rpc_endpoint) {
        // Check explicit test_mode setting first
        $test_mode_setting = $this->get_option('test_mode', 'auto');
        
        if ($test_mode_setting === 'yes') {
            return true; // Force test mode
        }
        if ($test_mode_setting === 'no') {
            return false; // Force production mode
        }
        
        // Auto-detect based on RPC endpoint
        $url = strtolower($rpc_endpoint);
        
        // Check for local IP patterns
        if (preg_match('/192\.168\.\d+\.\d+/', $url)) return true;
        if (preg_match('/10\.\d+\.\d+\.\d+/', $url)) return true;
        if (preg_match('/172\.(1[6-9]|2\d|3[01])\.\d+\.\d+/', $url)) return true;
        
        // Check for localhost patterns
        if (strpos($url, 'localhost') !== false) return true;
        if (strpos($url, '127.0.0.1') !== false) return true;
        if (strpos($url, '0.0.0.0') !== false) return true;
        
        // Check for devnet/testnet keywords
        if (strpos($url, 'devnet') !== false) return true;
        if (strpos($url, 'testnet') !== false) return true;
        if (strpos($url, 'local') !== false) return true;
        
        // Default: production mode
        return false;
    }

    /**
     * Generate QR code URL using QR Server API (free and reliable)
     */
    private function generate_qr_code_url($data, $size = 350) {
        $encoded = urlencode($data);
        // ecc=L = low error correction = less dense QR for easier scanning
        return "https://api.qrserver.com/v1/create-qr-code/?size={$size}x{$size}&data={$encoded}&format=png&margin=10&ecc=L";
    }

    /**
     * Thank you page with payment instructions and QR code
     */
    public function thankyou_page($order_id) {
        $order = wc_get_order($order_id);
        
        if (!$order || $order->get_payment_method() !== $this->id) {
            return;
        }

        $payment_status = $order->get_meta('_mre_payment_status');
        
        if ($payment_status === 'completed') {
            echo '<div class="woocommerce-message" style="background: #d4edda; border-color: #c3e6cb; color: #155724; padding: 15px; border-radius: 4px;">';
            echo '<p>✅ ' . __('Payment received! Your AQY Coins rewards have been sent to your wallet.', 'ab2bc-red-envelope') . '</p>';
            echo '</div>';
            return;
        }

        $amount = $order->get_total();
        $merchant_wallet = $order->get_meta('_mre_merchant_wallet');
        
        // Get store/seller info
        $store_name = get_bloginfo('name');
        $store_url = home_url();

        // Calculate reward: bonus products use product-defined AQY, M2C uses commission formula
        $bonus_aqy_total = floatval($order->get_meta('_mre_bonus_aqy_total'));
        $m2c_reward_stored = floatval($order->get_meta('_mre_m2c_reward'));
        if ($bonus_aqy_total > 0 || $m2c_reward_stored > 0) {
            // New-style calculation (post-fix) — already correct in meta
            $reward_amount = $bonus_aqy_total + $m2c_reward_stored;
        } else {
            // Recalculate from order items using correct M2C formula:
            // Bonus: _m2c_bonus_amount × qty
            // M2C:   (m2c_total × merchant_commission%) / aqy_price × consumer%
            $reward_amount = 0.0;
            $m2c_total_calc = 0.0;
            foreach ($order->get_items() as $item) {
                $product_id = $item->get_product_id();
                $is_bonus = get_post_meta($product_id, '_m2c_bonus_enabled', true) === 'yes';
                if ($is_bonus) {
                    $bonus_aqy = floatval(get_post_meta($product_id, '_m2c_bonus_amount', true));
                    $reward_amount += $bonus_aqy * intval($item->get_quantity());
                } else {
                    $m2c_total_calc += floatval($item->get_total());
                }
            }
            // M2C commission formula
            $merchant_pct = floatval($order->get_meta('_mre_merchant_commission_pct')) ?: (floatval($this->merchant_commission_pct) ?: 50);
            $aqy_price    = floatval($order->get_meta('_mre_aqy_base_price')) ?: (floatval($this->aqy_base_price) ?: 0.10);
            $consumer_pct = floatval($order->get_meta('_mre_consumer_pct')) ?: (floatval($this->reward_percent) ?: 60);
            $commission_usdc = $m2c_total_calc * ($merchant_pct / 100);
            $total_aqy = ($aqy_price > 0) ? ($commission_usdc / $aqy_price) : 0;
            $reward_amount += $total_aqy * ($consumer_pct / 100);
        }
        
        // Get product details (simplified for QR)
        $products = array();
        $product_names = array();
        foreach ($order->get_items() as $item) {
            $product = $item->get_product();
            $products[] = array(
                'name' => $item->get_name(),
                'qty' => $item->get_quantity(),
                'price' => floatval($item->get_total()),
            );
            $product_names[] = $item->get_name() . ' x' . $item->get_quantity();
        }
        
        // Auto-detect test mode based on RPC endpoint
        $rpc_endpoint = $this->get_option('rpc_endpoint', 'https://rpc.aqy.ab2bc.com');
        $test_mode = $this->is_test_mode($rpc_endpoint);
        
        // Get reward percentage from order meta or settings
        $reward_percent = $order->get_meta('_mre_reward_percent');
        if (empty($reward_percent)) {
            $reward_percent = $this->reward_percent ? $this->reward_percent : '60';
        }
        
        // Create SLIM payment data for QR code — payment-essential fields only
        // Display fields (seller, products, email, bonus details) are shown on the page, NOT in QR.
        // v2.1: Added bonus item data (bi, bt, mt) for correct M2C reward distribution.
        // v2.2: Added WooCommerce tax data (wt, sb) so wallet can avoid double taxation
        //       and fall back to M2C KYG regional tax rates when WC has no tax configured.
        $wc_tax_amount = floatval($order->get_total_tax());   // WC sales tax already collected (0 if WC tax not configured)
        $wc_subtotal   = floatval($order->get_subtotal());    // Pre-tax subtotal (before WC tax/shipping/discounts)
        $qr_data_array = array(
            'a' => 'pay',                           // action
            'v' => '2.2',                           // version (v2.2: slim QR + WC tax data)
            'c' => 'AQY',                           // chain
            't' => $merchant_wallet,                // to (wallet)
            'm' => floatval($amount),               // amount (money) — WC grand total (may include WC tax)
            'u' => 'USDC',                          // currency unit
            'o' => $order->get_order_number(),      // order ID
            'r' => round(floatval($reward_amount), 2), // reward amount (AQY)
            'n' => $test_mode ? 'test' : 'main',    // network mode
            'ts' => time(),                          // page-load timestamp (unique per render)
            'w' => rest_url('m2c/v1/payment-notify'),  // webhook URL for payment notification
            'wt' => round($wc_tax_amount, 2),       // WooCommerce tax collected (0 = WC tax not configured)
            'sb' => round($wc_subtotal, 2),         // WC subtotal before tax
        );

        // v2.1: Include bonus product data so M2C backend can split commission correctly.
        // Without this, M2C applies commission to the full order total instead of just M2C portion.
        $bonus_items_meta = $order->get_meta('_mre_bonus_items');
        if (!empty($bonus_items_meta) && is_array($bonus_items_meta)) {
            $qr_bonus = array();
            foreach ($bonus_items_meta as $bi) {
                $qr_bonus[] = array(
                    'pid' => $bi['product_id'],
                    'nm'  => $bi['product_name'],
                    'aqy' => floatval($bi['aqy_amount']),
                    'qty' => intval($bi['quantity']),
                );
            }
            $qr_data_array['bi'] = $qr_bonus;                                       // bonus items
            $qr_data_array['bt'] = floatval($order->get_meta('_mre_bonus_total'));   // bonus total USDC
            $qr_data_array['mt'] = floatval($order->get_meta('_mre_m2c_total'));     // M2C commission total USDC
        }

        // Inject merchant referral code (rc) from cached verification data
        $verification = $this->get_wallet_verification_status();
        if (!empty($verification['membership']['referralCode'])) {
            $qr_data_array['rc'] = $verification['membership']['referralCode'];
        }

        error_log('[RE Gateway] QR data fields: ' . count($qr_data_array) . ', order #' . $order->get_order_number());
        
        // Webhook URL (w) is now included directly in QR data for reliability
        
        $qr_url = $this->generate_qr_code_url(json_encode($qr_data_array));
        
        ?>
        <div class="mre-payment-instructions" style="background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); color: white; padding: 30px; border-radius: 12px; margin: 20px 0;">
            <h3 style="color: #f39c12; margin-top: 0;">📱 <?php _e('Complete Your Payment', 'ab2bc-red-envelope'); ?></h3>
            
            <div style="display: flex; gap: 20px; align-items: flex-start;">
                <!-- Left Column: QR Code + Manual Steps -->
                <div style="width: 320px; flex-shrink: 0;">
                    <div style="background: white; padding: 10px; border-radius: 8px; text-align: center;">
                        <img src="<?php echo esc_url($qr_url); ?>" alt="Payment QR Code" style="width: 300px; height: 300px;"/>
                        <p style="color: #333; margin: 8px 0 0 0; font-size: 12px;"><?php _e('Scan with Red Envelope Wallet', 'ab2bc-red-envelope'); ?></p>
                    </div>

                    <div style="margin-top: 15px;">
                        <h4 style="color: #e0e0e0; margin-top: 0; font-size: 13px;"><?php _e('Manual Payment Steps:', 'ab2bc-red-envelope'); ?></h4>
                        <ol style="color: #e0e0e0; margin: 0; padding-left: 20px; font-size: 12px; line-height: 1.6;">
                            <li><?php _e('Open your Red Envelope Wallet app', 'ab2bc-red-envelope'); ?></li>
                            <li><?php _e('Go to Send → USDC', 'ab2bc-red-envelope'); ?></li>
                            <li><?php printf(__('Enter amount: %s USDC', 'ab2bc-red-envelope'), esc_html($amount)); ?></li>
                            <li><?php _e('Paste the merchant wallet address above', 'ab2bc-red-envelope'); ?></li>
                            <li><?php printf(__('Add memo: Order #%s', 'ab2bc-red-envelope'), esc_html($order->get_order_number())); ?></li>
                            <li><?php _e('Confirm and send!', 'ab2bc-red-envelope'); ?></li>
                        </ol>
                    </div>
                </div>
                
                <!-- Right Column: Payment Details -->
                <div style="flex: 1; min-width: 250px;">
                    <!-- Order Summary -->
                    <div style="background: rgba(255,255,255,0.05); padding: 15px; border-radius: 8px; margin-bottom: 15px;">
                        <p style="margin: 0 0 10px 0; color: #f39c12; font-weight: bold;">🛒 <?php _e('Order Summary', 'ab2bc-red-envelope'); ?></p>
                        <?php foreach ($products as $product) : ?>
                        <div style="display: flex; justify-content: space-between; color: #e0e0e0; font-size: 14px; margin-bottom: 5px;">
                            <span><?php echo esc_html($product['name']); ?> × <?php echo esc_html($product['qty']); ?></span>
                            <span>$<?php echo esc_html(number_format($product['price'], 2)); ?></span>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Seller Info -->
                    <div style="background: rgba(255,255,255,0.05); padding: 15px; border-radius: 8px; margin-bottom: 15px;">
                        <p style="margin: 0 0 5px 0; color: #aaa; font-size: 12px;"><?php _e('Seller:', 'ab2bc-red-envelope'); ?></p>
                        <p style="margin: 0; color: #fff; font-weight: bold;"><?php echo esc_html($store_name); ?></p>
                    </div>

                    <div style="background: rgba(255,255,255,0.1); padding: 20px; border-radius: 8px; margin-bottom: 15px;">
                        <p style="margin: 0 0 5px 0; color: #aaa;"><?php _e('Amount to Pay:', 'ab2bc-red-envelope'); ?></p>
                        <p style="font-size: 28px; color: #4ecdc4; margin: 0; font-weight: bold;"><?php echo esc_html($amount); ?> USDC</p>
                    </div>

                    <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px; margin-bottom: 15px;">
                        <p style="margin: 0 0 5px 0; color: #aaa;"><?php _e('Send USDC to:', 'ab2bc-red-envelope'); ?></p>
                        <p style="font-family: monospace; background: rgba(0,0,0,0.3); padding: 10px; border-radius: 4px; word-break: break-all; margin: 0; font-size: 12px;">
                            <?php echo esc_html($merchant_wallet); ?>
                        </p>
                    </div>

                    <div style="background: linear-gradient(135deg, #f39c12, #e74c3c); padding: 15px; border-radius: 8px;">
                        <p style="margin: 0; font-weight: bold;">🎁 <?php _e('Your Reward:', 'ab2bc-red-envelope'); ?> 
                        <?php echo esc_html(number_format($reward_amount, 2)); ?> <?php _e('AQY Coins', 'ab2bc-red-envelope'); ?></p>
                    </div>
                </div>
            </div>

            <p style="color: #aaa; font-size: 12px; margin-top: 20px; margin-bottom: 0;">
                <?php _e('Payment is processed on the AQY Chain. Transaction confirmation typically takes 2-3 seconds.', 'ab2bc-red-envelope'); ?>
            </p>
            
            <!-- Payment Status Polling -->
            <div id="mre-payment-status" style="margin-top: 20px; padding: 15px; background: rgba(255,255,255,0.1); border-radius: 8px; text-align: center;">
                <div id="mre-status-pending">
                    <span class="mre-spinner" style="display: inline-block; width: 20px; height: 20px; border: 3px solid rgba(255,255,255,0.3); border-radius: 50%; border-top-color: #4ecdc4; animation: mre-spin 1s linear infinite;"></span>
                    <span style="margin-left: 10px;"><?php _e('Waiting for payment confirmation...', 'ab2bc-red-envelope'); ?></span>
                </div>
                <div id="mre-status-confirmed" style="display: none;">
                    <span style="font-size: 24px;">✅</span>
                    <span style="margin-left: 10px; color: #4ecdc4; font-weight: bold;"><?php _e('Payment Confirmed!', 'ab2bc-red-envelope'); ?></span>
                </div>
            </div>
        </div>
        
        <style>
            @keyframes mre-spin {
                to { transform: rotate(360deg); }
            }
        </style>
        
        <script type="text/javascript">
        (function() {
            var orderId = <?php echo absint($order_id); ?>;
            var orderKey = '<?php echo esc_js($order->get_order_key()); ?>';
            // Use REST API endpoint instead of admin-ajax.php (avoids Cloudflare blocks)
            var restUrl = '<?php echo esc_url(rest_url('m2c/v1/payment-status')); ?>';
            var ajaxUrl = '<?php echo esc_url(admin_url('admin-ajax.php')); ?>';
            var pollInterval = null;
            var pollCount = 0;
            var fastPolls = 300;  // First 10 min: every 2s (300 polls)
            var maxPolls = 660;   // Next 12 min: every 5s (144 polls) → total ~22 min
            var currentInterval = 2000;
            
            function checkPaymentStatus() {
                pollCount++;
                
                // Switch to slower polling after 10 minutes
                if (pollCount === fastPolls) {
                    clearInterval(pollInterval);
                    currentInterval = 5000;
                    pollInterval = setInterval(checkPaymentStatus, currentInterval);
                    // Show a subtle "still watching" message
                    var statusEl = document.getElementById('mre-status-pending');
                    if (statusEl) {
                        statusEl.innerHTML = '<span class="mre-spinner" style="display:inline-block;width:20px;height:20px;border:3px solid rgba(255,255,255,0.3);border-radius:50%;border-top-color:#4ecdc4;animation:mre-spin 1s linear infinite;"></span>' +
                            '<span style="margin-left:10px;"><?php _e('Still waiting for payment... (checking every 5s)', 'ab2bc-red-envelope'); ?></span>';
                    }
                }
                
                if (pollCount > maxPolls) {
                    clearInterval(pollInterval);
                    // Show refresh button instead of silently stopping
                    var statusEl = document.getElementById('mre-status-pending');
                    if (statusEl) {
                        statusEl.innerHTML = '<span style="color:#f39c12;">⏱ <?php _e('Polling paused.', 'ab2bc-red-envelope'); ?></span>' +
                            '<button onclick="window.location.reload()" style="margin-left:12px;background:#4ecdc4;color:#1a1a2e;border:none;padding:8px 20px;border-radius:6px;cursor:pointer;font-weight:bold;">' +
                            '🔄 <?php _e('Check Now', 'ab2bc-red-envelope'); ?></button>';
                    }
                    return;
                }
                
                // Try REST endpoint first (faster, avoids CF blocks), fall back to admin-ajax
                var url = restUrl + '?order_id=' + orderId + '&order_key=' + orderKey;
                var xhr = new XMLHttpRequest();
                xhr.open('GET', url, true);
                xhr.setRequestHeader('Cache-Control', 'no-cache');
                
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            try {
                                var response = JSON.parse(xhr.responseText);
                                var data = response.data || response;
                                if (data.status === 'completed') {
                                    clearInterval(pollInterval);
                                    document.getElementById('mre-status-pending').style.display = 'none';
                                    document.getElementById('mre-status-confirmed').style.display = 'block';
                                    setTimeout(function() { window.location.reload(); }, 2000);
                                }
                            } catch (e) {
                                console.error('Parse error:', e);
                            }
                        } else {
                            // REST failed — try admin-ajax fallback
                            var xhr2 = new XMLHttpRequest();
                            xhr2.open('POST', ajaxUrl, true);
                            xhr2.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                            xhr2.onreadystatechange = function() {
                                if (xhr2.readyState === 4 && xhr2.status === 200) {
                                    try {
                                        var r = JSON.parse(xhr2.responseText);
                                        if (r.success && r.data.status === 'completed') {
                                            clearInterval(pollInterval);
                                            document.getElementById('mre-status-pending').style.display = 'none';
                                            document.getElementById('mre-status-confirmed').style.display = 'block';
                                            setTimeout(function() { window.location.reload(); }, 2000);
                                        }
                                    } catch (e2) {}
                                }
                            };
                            xhr2.send('action=mre_check_payment&order_id=' + orderId + '&order_key=' + orderKey);
                        }
                    }
                };
                
                xhr.send();
            }
            
            // Start polling every 2 seconds
            pollInterval = setInterval(checkPaymentStatus, currentInterval);
            checkPaymentStatus();
            
            // Also listen for visibility changes — recheck when user returns to tab
            document.addEventListener('visibilitychange', function() {
                if (document.visibilityState === 'visible') {
                    checkPaymentStatus();
                }
            });
        })();
        </script>
        <?php
    }

    /**
     * Add payment instructions to emails
     */
    public function email_instructions($order, $sent_to_admin, $plain_text = false) {
        if ($order->get_payment_method() !== $this->id) {
            return;
        }

        if ($order->get_meta('_mre_payment_status') === 'completed') {
            return;
        }

        $amount = $order->get_total();
        $merchant_wallet = $order->get_meta('_mre_merchant_wallet');

        if ($plain_text) {
            echo "\n=== RED ENVELOPE PAYMENT INSTRUCTIONS ===\n\n";
            echo "Amount: " . $amount . " USDC\n";
            echo "Send to: " . $merchant_wallet . "\n";
            echo "Memo: Order #" . $order->get_order_number() . "\n";
            echo "Chain: AQY Chain\n\n";
        } else {
            echo '<div style="background: #f8f9fa; padding: 20px; margin: 15px 0; border-left: 4px solid #f39c12; border-radius: 4px;">';
            echo '<h3 style="margin-top: 0; color: #333;">' . __('Red Envelope Payment Instructions', 'ab2bc-red-envelope') . '</h3>';
            echo '<p><strong>' . __('Amount:', 'ab2bc-red-envelope') . '</strong> ' . esc_html($amount) . ' USDC</p>';
            echo '<p><strong>' . __('Send to:', 'ab2bc-red-envelope') . '</strong><br>';
            echo '<code style="background: #e9ecef; padding: 5px 10px; font-size: 12px; word-break: break-all;">' . esc_html($merchant_wallet) . '</code></p>';
            echo '<p><strong>' . __('Memo:', 'ab2bc-red-envelope') . '</strong> Order #' . esc_html($order->get_order_number()) . '</p>';
            echo '<p><strong>' . __('Chain:', 'ab2bc-red-envelope') . '</strong> AQY Chain</p>';
            echo '</div>';
        }
    }

    /**
     * Process refund
     */
    public function process_refund($order_id, $amount = null, $reason = '') {
        $order = wc_get_order($order_id);
        
        if (!$order) {
            return new WP_Error('error', __('Order not found.', 'ab2bc-red-envelope'));
        }

        // For now, refunds need to be processed manually
        $order->add_order_note(sprintf(
            __('Refund of %s USDC requested. Reason: %s. Please process manually via Red Envelope Wallet.', 'ab2bc-red-envelope'),
            $amount,
            $reason
        ));

        return true;
    }
    
    /**
     * AJAX: Check payment status
     */
    public function ajax_check_payment() {
        $order_id = isset($_POST['order_id']) ? absint($_POST['order_id']) : 0;
        $order_key = isset($_POST['order_key']) ? sanitize_text_field($_POST['order_key']) : '';
        
        if (!$order_id || !$order_key) {
            wp_send_json_error(array('message' => 'Invalid request'));
            return;
        }
        
        $order = wc_get_order($order_id);
        
        if (!$order || $order->get_order_key() !== $order_key) {
            wp_send_json_error(array('message' => 'Order not found'));
            return;
        }
        
        $payment_status = $order->get_meta('_mre_payment_status');
        $transaction_hash = $order->get_meta('_m2c_transaction_hash');
        $order_status = $order->get_status();
        
        // Diagnostic logging for payment polling
        error_log('[RE AJAX Poll] Order #' . $order_id . ' | meta_status=' . $payment_status . ' | order_status=' . $order_status . ' | tx=' . ($transaction_hash ?: 'none'));

        // Check if payment is complete
        if ($payment_status === 'completed' || in_array($order_status, array('processing', 'completed'))) {
            error_log('[RE AJAX Poll] ✓ COMPLETED detected for order #' . $order_id);
            wp_send_json_success(array(
                'status' => 'completed',
                'message' => __('Payment confirmed!', 'ab2bc-red-envelope'),
                'transaction_hash' => $transaction_hash,
                'order_status' => $order_status,
                'redirect_url' => $order->get_view_order_url()
            ));
            return;
        }
        
        // Still pending
        wp_send_json_success(array(
            'status' => 'pending',
            'message' => __('Awaiting payment...', 'ab2bc-red-envelope'),
            'order_status' => $order_status
        ));
    }
}
