<?php
/**
 * Stablezact WP Admin Class
 * 
 * Handles admin interface, settings, and transaction management
 */

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

class Stablezact_Admin {
    
    /**
     * API instance
     */
    private $api;
    
    /**
     * Gateway settings
     */
    private $gateway_settings;
    
    /**
     * Constructor
     */
    public function __construct() {
        $this->gateway_settings = get_option('woocommerce_stablezact_settings', array());
        
        // Initialize API if credentials are available
        if (!empty($this->gateway_settings['public_key'])) {
            require_once STABLEZACT_PLUGIN_DIR . 'includes/class-stablezact-api.php';
            $testmode = isset($this->gateway_settings['testmode']) && $this->gateway_settings['testmode'] === 'yes';
            $debug = isset($this->gateway_settings['debug']) && $this->gateway_settings['debug'] === 'yes';
            $this->api = new Stablezact_API(
                $this->gateway_settings['public_key'],
                $testmode,
                $debug
            );
        }
        
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        add_action('wp_ajax_stablezact_fetch_transactions', array($this, 'ajax_fetch_transactions'));
        add_action('wp_ajax_stablezact_get_transaction_details', array($this, 'ajax_get_transaction_details'));
        add_action('wp_ajax_stablezact_fetch_dashboard_data', array($this, 'ajax_fetch_dashboard_data'));
        add_action('wp_ajax_stablezact_update_merchant_settings', array($this, 'ajax_update_merchant_settings'));
        add_action('wp_ajax_stablezact_test_connection', array($this, 'ajax_test_connection'));
        add_action('wp_ajax_stablezact_regenerate_webhook_secret', array($this, 'ajax_regenerate_webhook_secret'));
        add_action('wp_ajax_stablezact_save_network_settings', array($this, 'ajax_save_network_settings'));
        add_action('wp_ajax_stablezact_update_wallet_addresses', array($this, 'ajax_update_wallet_addresses'));
        add_action('wp_ajax_stablezact_check_credentials', array($this, 'ajax_check_credentials'));
        add_action('wp_ajax_stablezact_refresh_credentials', array($this, 'ajax_refresh_credentials'));
        add_action('wp_ajax_stablezact_clear_credentials', array($this, 'ajax_clear_credentials'));
        add_action('wp_ajax_stablezact_refresh_wallets', array($this, 'ajax_refresh_wallets'));
        add_action('wp_ajax_stablezact_fetch_wallets', array($this, 'ajax_fetch_wallets'));
        add_action('wp_ajax_stablezact_save_wallets', array($this, 'ajax_save_wallets'));

        // Add validation for settings update
        add_filter('pre_update_option_woocommerce_stablezact_settings', array($this, 'validate_settings_update'), 10, 2);
    }
    
    /**
     * Get menu icon for WordPress admin sidebar
     */
    private function get_menu_icon() {
        // Option 1: Custom SVG icon (currently active)
        $svg = '<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="10" cy="10" r="8" stroke="currentColor" stroke-width="1.5" fill="none"/>
            <path d="M7 8h6M7 10h6M7 12h4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
            <circle cx="10" cy="6" r="1.5" fill="currentColor"/>
        </svg>';
        
        return 'data:image/svg+xml;base64,' . base64_encode($svg);
        
        // Option 2: WordPress Dashicon (uncomment to use instead)
        // return 'dashicons-money-alt';
    }

    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        // Main menu page
        add_menu_page(
            __('Stablezact', 'stablezact-crypto-payments'),
            __('Stablezact', 'stablezact-crypto-payments'),
            'manage_options',
            'stablezact',
            array($this, 'dashboard_page'),
            $this->get_menu_icon(),
            56
        );
        
        // Dashboard submenu
        add_submenu_page(
            'stablezact',
            __('Dashboard', 'stablezact-crypto-payments'),
            __('Dashboard', 'stablezact-crypto-payments'),
            'manage_options',
            'stablezact',
            array($this, 'dashboard_page')
        );
        
        // Transactions submenu
        add_submenu_page(
            'stablezact',
            __('Transactions', 'stablezact-crypto-payments'),
            __('Transactions', 'stablezact-crypto-payments'),
            'manage_options',
            'stablezact-transactions',
            array($this, 'transactions_page')
        );

        // Wallet Settings submenu
        add_submenu_page(
            'stablezact',
            __('Wallet Settings', 'stablezact-crypto-payments'),
            __('Settings', 'stablezact-crypto-payments'),
            'manage_options',
            'stablezact-wallet-settings',
            array($this, 'wallet_settings_page')
        );
        
        /* 
        // Analytics submenu - REMOVED - Keep menu simple with just Dashboard and Transactions
        add_submenu_page(
            'stablezact',
            __('Analytics', 'stablezact-crypto-payments'),
            __('Analytics', 'stablezact-crypto-payments'),
            'manage_options',
            'stablezact-analytics',
            array($this, 'analytics_page')
        );
        */

        // Add onboarding page (hidden from menu)
        add_submenu_page(
            null, // No parent menu - hidden page
            __('Stablezact Onboarding', 'stablezact-crypto-payments'),
            __('Onboarding', 'stablezact-crypto-payments'),
            'manage_options',
            'stablezact-onboarding',
            array($this, 'onboarding_page')
        );
    }
    
    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_admin_scripts($hook) {
        // Load on our admin pages and WooCommerce settings pages
        $load_styles = false;
        
        // Load on Stablezact admin pages
        if (strpos($hook, 'stablezact') !== false) {
            $load_styles = true;
        }
        
        // Load on WooCommerce settings pages (for wallet configuration styling).
        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only check of which admin page is loading, to decide whether to enqueue styles; no state is changed.
        if (strpos($hook, 'woocommerce_page_wc-settings') !== false ||
            (isset($_GET['page']) && $_GET['page'] === 'wc-settings')) {
            $load_styles = true;
        }
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        
        if (!$load_styles) {
            return;
        }
        
        // Enqueue enhanced admin styles with cache busting
        wp_enqueue_style(
            'stablezact-admin-enhanced',
            STABLEZACT_PLUGIN_URL . 'assets/css/admin-enhanced.css',
            array(),
            STABLEZACT_VERSION . '-' . time()
        );
        
        // Add Bricolage Grotesque font
        wp_enqueue_style(
            'bricolage-grotesque-font',
            'https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,200..800&display=swap',
            array(),
            STABLEZACT_VERSION
        );
        
        // Enqueue admin JavaScript
        wp_enqueue_script(
            'stablezact-admin',
            STABLEZACT_PLUGIN_URL . 'assets/js/admin.js',
            array('jquery'),
            STABLEZACT_VERSION . '-' . time(),
            true
        );
        
        // Localize script with proper nonce and AJAX URL
        wp_localize_script('stablezact-admin', 'stablezact_admin', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('stablezact_admin_nonce'),
            'is_configured' => !empty($this->gateway_settings['public_key']),
            'strings' => array(
                'loading' => __('Loading...', 'stablezact-crypto-payments'),
                'saving' => __('Saving...', 'stablezact-crypto-payments'),
                'validating' => __('Validating...', 'stablezact-crypto-payments'),
                'refreshing' => __('Refreshing credentials...', 'stablezact-crypto-payments'),
                'error' => __('Error', 'stablezact-crypto-payments'),
                'success' => __('Success', 'stablezact-crypto-payments'),
                'confirm_delete' => __('Are you sure you want to delete this item?', 'stablezact-crypto-payments'),
                'connection_test_success' => __('API connection successful!', 'stablezact-crypto-payments'),
                'connection_test_failed' => __('API connection failed', 'stablezact-crypto-payments'),
                'settings_saved' => __('Settings saved successfully', 'stablezact-crypto-payments'),
                'settings_save_failed' => __('Failed to save settings', 'stablezact-crypto-payments'),
                'wallets_updated' => __('Wallet addresses updated successfully!', 'stablezact-crypto-payments'),
                'wallets_update_failed' => __('Failed to update wallet addresses', 'stablezact-crypto-payments'),
                'credential_warning' => __('API Credentials Need Refresh', 'stablezact-crypto-payments'),
                'credential_warning_desc' => __('Your API credentials may have expired. Click the button below to refresh them.', 'stablezact-crypto-payments'),
                'refresh_credentials' => __('Refresh Credentials', 'stablezact-crypto-payments'),
                'refresh_failed' => __('Failed to refresh credentials. Please try logging in again.', 'stablezact-crypto-payments')
            )
        ));
    }
    
    /**
     * Dashboard page
     */
    public function dashboard_page() {
        $merchant_data = $this->get_merchant_dashboard_data();
        $stats = $this->get_payment_stats();
        $recent_transactions = $this->get_recent_transactions(5);
        
        include STABLEZACT_PLUGIN_DIR . 'includes/admin/dashboard.php';
    }
    
    /**
     * Transactions page
     */
    public function transactions_page() {
        include STABLEZACT_PLUGIN_DIR . 'includes/admin/transactions.php';
    }

    /**
     * Wallet settings page
     */
    public function wallet_settings_page() {
        require_once STABLEZACT_PLUGIN_DIR . 'includes/admin/wallet-settings.php';
    }
    
    // Settings page - REMOVED - Use WooCommerce > Settings > Payments > Stablezact instead
    /*
    public function settings_page() {
        include STABLEZACT_PLUGIN_DIR . 'includes/admin/settings.php';
    }
    */
    
    // Analytics page - REMOVED - Keep menu simple with just Dashboard and Transactions
    /*
    public function analytics_page() {
        $stats = $this->get_payment_stats();
        include STABLEZACT_PLUGIN_DIR . 'includes/admin/analytics.php';
    }
    */
    
    /**
     * Onboarding page.
     */
    public function onboarding_page() {
        ?>
        <div class="wrap stablezact-onboarding">
            <!-- Enhanced Notification Container -->
            <div id="stablezact-notification-container"></div>
            
            <div class="stablezact-onboarding-container">
                <div class="stablezact-onboarding-header">
                    <img src="<?php echo esc_url(STABLEZACT_PLUGIN_URL . 'assets/images/stablezact-logo.png'); ?>" alt="Stablezact" class="stablezact-logo">
                    <h1><?php esc_html_e('Welcome to Stablezact!', 'stablezact-crypto-payments'); ?></h1>
                    <p><?php esc_html_e('Connect your Stablezact merchant account to start accepting cryptocurrency payments', 'stablezact-crypto-payments'); ?></p>
                </div>

                <div class="stablezact-onboarding-tabs">
                    <button class="tab-button active" data-tab="login"><?php esc_html_e('Log In', 'stablezact-crypto-payments'); ?></button>
                    <button class="tab-button" data-tab="register"><?php esc_html_e('Sign Up', 'stablezact-crypto-payments'); ?></button>
                </div>

                <div class="stablezact-onboarding-content">
                    <!-- Login Tab -->
                    <div id="login-tab" class="tab-content active">
                        <form id="stablezact-login-form" class="onboarding-form">
                            <h2><?php esc_html_e('Log In to Your Stablezact Account', 'stablezact-crypto-payments'); ?></h2>
                            <p><?php esc_html_e('Enter your existing Stablezact merchant credentials', 'stablezact-crypto-payments'); ?></p>
                            
                            <div class="form-group">
                                <label for="login-email"><?php esc_html_e('Email Address', 'stablezact-crypto-payments'); ?></label>
                                <input type="email" id="login-email" name="email" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="login-password"><?php esc_html_e('Password', 'stablezact-crypto-payments'); ?></label>
                                <input type="password" id="login-password" name="password" required>
                            </div>
                            
                            <div class="form-actions">
                                <button type="submit" class="button button-primary button-large">
                                    <span class="button-text"><?php esc_html_e('Connect Account', 'stablezact-crypto-payments'); ?></span>
                                    <span class="spinner"></span>
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- Register Tab -->
                    <div id="register-tab" class="tab-content">
                        <form id="stablezact-register-form" class="onboarding-form">
                            <h2><?php esc_html_e('Create a New Stablezact Account', 'stablezact-crypto-payments'); ?></h2>
                            <p><?php esc_html_e('Sign up for a new Stablezact merchant account to start accepting payments', 'stablezact-crypto-payments'); ?></p>
                            
                            <div class="form-group">
                                <label for="register-email"><?php esc_html_e('Email Address', 'stablezact-crypto-payments'); ?></label>
                                <input type="email" id="register-email" name="email" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="register-password"><?php esc_html_e('Password', 'stablezact-crypto-payments'); ?></label>
                                <input type="password" id="register-password" name="password" required minlength="8">
                                <small><?php esc_html_e('Minimum 8 characters', 'stablezact-crypto-payments'); ?></small>
                            </div>
                            
                            <div class="business-info">
                                <h3><?php esc_html_e('Business Information', 'stablezact-crypto-payments'); ?></h3>
                                <div class="form-group">
                                    <label><?php esc_html_e('Business Name', 'stablezact-crypto-payments'); ?></label>
                                    <input type="text" value="<?php echo esc_attr(get_bloginfo('name')); ?>" readonly>
                                    <small><?php esc_html_e('Automatically detected from your WordPress site', 'stablezact-crypto-payments'); ?></small>
                                </div>
                                
                                <div class="form-group">
                                    <label><?php esc_html_e('Website URL', 'stablezact-crypto-payments'); ?></label>
                                    <input type="url" value="<?php echo esc_attr(get_site_url()); ?>" readonly>
                                    <small><?php esc_html_e('Your WordPress site URL', 'stablezact-crypto-payments'); ?></small>
                                </div>
                            </div>
                            
                            <div class="form-actions">
                                <button type="submit" class="button button-primary button-large">
                                    <span class="button-text"><?php esc_html_e('Create Account & Connect', 'stablezact-crypto-payments'); ?></span>
                                    <span class="spinner"></span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="stablezact-onboarding-info">
                    <div class="info-card">
                        <h4>📧 <?php esc_html_e('Email Verification Required', 'stablezact-crypto-payments'); ?></h4>
                        <p><?php esc_html_e('After registration, you\'ll receive a verification email. You can continue with the setup, but some features may be limited until you verify your email address.', 'stablezact-crypto-payments'); ?></p>
                    </div>
                    <div class="info-card">
                        <h4>🔐 <?php esc_html_e('Secure API Integration', 'stablezact-crypto-payments'); ?></h4>
                        <p><?php esc_html_e('Your API credentials will be automatically configured in WooCommerce settings after successful authentication.', 'stablezact-crypto-payments'); ?></p>
                    </div>
                </div>

                <div class="stablezact-onboarding-benefits">
                    <h3><?php esc_html_e('Why Choose Stablezact?', 'stablezact-crypto-payments'); ?></h3>
                    <div class="benefits-grid">
                        <div class="benefit-item">
                            <span class="dashicons dashicons-money-alt"></span>
                            <h4><?php esc_html_e('Low Fees', 'stablezact-crypto-payments'); ?></h4>
                            <p><?php esc_html_e('Save up to 80% on transaction fees compared to traditional payment processors', 'stablezact-crypto-payments'); ?></p>
                        </div>
                        <div class="benefit-item">
                            <span class="dashicons dashicons-clock"></span>
                            <h4><?php esc_html_e('Instant Settlement', 'stablezact-crypto-payments'); ?></h4>
                            <p><?php esc_html_e('Receive payments instantly without waiting for bank processing', 'stablezact-crypto-payments'); ?></p>
                        </div>
                        <div class="benefit-item">
                            <span class="dashicons dashicons-shield"></span>
                            <h4><?php esc_html_e('No Chargebacks', 'stablezact-crypto-payments'); ?></h4>
                            <p><?php esc_html_e('Cryptocurrency payments are final and irreversible', 'stablezact-crypto-payments'); ?></p>
                        </div>
                        <div class="benefit-item">
                            <span class="dashicons dashicons-admin-site"></span>
                            <h4><?php esc_html_e('Global Reach', 'stablezact-crypto-payments'); ?></h4>
                            <p><?php esc_html_e('Accept payments from customers anywhere in the world', 'stablezact-crypto-payments'); ?></p>
                        </div>
                    </div>
                </div>

                <div class="stablezact-onboarding-footer">
                    <p><?php esc_html_e('Need help?', 'stablezact-crypto-payments'); ?> <a href="https://stablezact.com/contact-us" target="_blank"><?php esc_html_e('Contact Support', 'stablezact-crypto-payments'); ?></a></p>
                    <p><a href="<?php echo esc_url(admin_url('admin.php?page=wc-settings&tab=checkout&section=stablezact')); ?>"><?php esc_html_e('Skip and set up manually', 'stablezact-crypto-payments'); ?></a></p>
                </div>
            </div>
        </div>


        <?php
        // Emit the onboarding script as an inline script on the enqueued admin handle
        // (wp_enqueue policy) rather than a raw inline script; ob_start captures the
        // rendered JS (including translated strings) unchanged.
        ob_start();
        ?>
        jQuery(document).ready(function($) {
            // Enhanced notification system
            function showNotification(type, title, message, actions) {
                // Remove existing notifications
                $('#stablezact-notification-container').empty();
                
                var iconMap = {
                    'success': '✓',
                    'error': '⚠',
                    'warning': '!',
                    'info': 'ℹ'
                };
                
                var notification = $(`
                    <div class="stablezact-enhanced-notification ${type}">
                        <div class="stablezact-enhanced-notification-header">
                            <div class="stablezact-enhanced-notification-icon">${iconMap[type] || 'ℹ'}</div>
                            <div class="stablezact-enhanced-notification-content">
                                <div class="stablezact-enhanced-notification-title">${title}</div>
                                <div class="stablezact-enhanced-notification-message">${message}</div>
                            </div>
                        </div>
                        ${actions ? `<div class="stablezact-enhanced-notification-actions">${actions}</div>` : ''}
                        <button class="stablezact-enhanced-notification-close">&times;</button>
                    </div>
                `);
                
                $('#stablezact-notification-container').append(notification);
                
                // Add close button event handler
                notification.find('.stablezact-enhanced-notification-close').on('click', function() {
                    notification.addClass('slide-out').delay(300).queue(function(){
                        $(this).remove();
                    });
                });
                
                // Auto-dismiss after 8 seconds for non-error notifications
                if (type !== 'error') {
                    setTimeout(function() {
                        notification.addClass('slide-out').delay(300).queue(function(){
                            $(this).remove();
                        });
                    }, 8000);
                }
            }
            
            // Tab switching
            $('.tab-button').click(function() {
                var tab = $(this).data('tab');
                
                $('.tab-button').removeClass('active');
                $('.tab-content').removeClass('active');
                
                $(this).addClass('active');
                $('#' + tab + '-tab').addClass('active');
                
                // Clear any existing notifications when switching tabs
                $('#stablezact-notification-container').empty();
            });

            // Form submissions
            $('#stablezact-login-form').submit(function(e) {
                e.preventDefault();
                submitForm('login');
            });

            $('#stablezact-register-form').submit(function(e) {
                e.preventDefault();
                submitForm('register');
            });

            function submitForm(actionType) {
                var form = $('#stablezact-' + actionType + '-form');
                var button = form.find('button[type="submit"]');
                var email = form.find('input[name="email"]').val();
                var password = form.find('input[name="password"]').val();

                if (!email || !password) {
                    showNotification('warning', 
                        '<?php esc_html_e('Missing Information', 'stablezact-crypto-payments'); ?>', 
                        '<?php esc_html_e('Please fill in all required fields to continue.', 'stablezact-crypto-payments'); ?>'
                    );
                    return;
                }

                button.addClass('loading').prop('disabled', true);
                
                // Show loading notification
                showNotification('info', 
                    '<?php esc_html_e('Connecting...', 'stablezact-crypto-payments'); ?>', 
                    actionType === 'login' ? '<?php esc_html_e('Logging into your Stablezact account...', 'stablezact-crypto-payments'); ?>' : '<?php esc_html_e('Creating your Stablezact account...', 'stablezact-crypto-payments'); ?>'
                );

                $.post(ajaxurl, {
                    action: 'stablezact_complete_onboarding',
                    nonce: '<?php echo esc_js(wp_create_nonce('stablezact_onboarding')); ?>',
                    email: email,
                    password: password,
                    action_type: actionType
                }, function(response) {
                    if (response.success) {
                        if (response.data.requires_verification) {
                            // Registration successful but needs email verification
                            showNotification('warning', 
                                '<?php esc_html_e('Email Verification Required', 'stablezact-crypto-payments'); ?>', 
                                response.data.message + ' <?php esc_html_e('You can continue with the setup, but some features may be limited until you verify your email.', 'stablezact-crypto-payments'); ?>',
                                '<button class="stablezact-enhanced-notice-btn-primary" onclick="window.location.href=\'' + response.data.redirect + '\'"><?php esc_html_e('Continue Setup', 'stablezact-crypto-payments'); ?></button>'
                            );
                        } else {
                            // Login successful
                            showNotification('success', 
                                '<?php esc_html_e('Successfully Connected!', 'stablezact-crypto-payments'); ?>', 
                                response.data.message,
                                '<button class="stablezact-enhanced-notice-btn-primary" onclick="window.location.href=\'' + response.data.redirect + '\'"><?php esc_html_e('Continue to Settings', 'stablezact-crypto-payments'); ?></button>'
                            );
                        }
                        
                        // Redirect after a brief delay to show the notification
                        setTimeout(function() {
                            window.location.href = response.data.redirect;
                        }, 2000);
                    } else {
                        // Handle specific error cases
                        var errorMessage = response.data;
                        if (errorMessage.includes('not verified') || errorMessage.includes('verification')) {
                            showNotification('error', 
                                '<?php esc_html_e('Email Verification Required', 'stablezact-crypto-payments'); ?>', 
                                errorMessage + ' <?php esc_html_e('Please check your email and click the verification link, then try logging in again.', 'stablezact-crypto-payments'); ?>'
                            );
                        } else {
                            showNotification('error', 
                                '<?php esc_html_e('Connection Failed', 'stablezact-crypto-payments'); ?>', 
                                errorMessage
                            );
                        }
                        button.removeClass('loading').prop('disabled', false);
                    }
                }).fail(function() {
                    showNotification('error', 
                        '<?php esc_html_e('Connection Error', 'stablezact-crypto-payments'); ?>', 
                        '<?php esc_html_e('Unable to connect to Stablezact servers. Please check your internet connection and try again.', 'stablezact-crypto-payments'); ?>'
                    );
                    button.removeClass('loading').prop('disabled', false);
                });
            }
        });
        <?php
        wp_add_inline_script('stablezact-admin', ob_get_clean());
    }
    
    /**
     * Get merchant dashboard data
     */
    private function get_merchant_dashboard_data() {
        if (!$this->api) {
            return $this->get_mock_merchant_data();
        }
        
        try {
            $response = $this->api->get_comprehensive_merchant_data();
            
            if (is_wp_error($response)) {
                return $this->get_mock_merchant_data();
            }
            
            // Extract merchant data from the comprehensive response
            if (isset($response['merchant'])) {
                // Try to get wallet data from the API
                $merchant_wallets = array();
                
                // First try to get from the comprehensive response
                if (isset($response['merchantWallets'])) {
                    $merchant_wallets = $response['merchantWallets'];
                } else {
                    // Fallback: try to fetch wallets separately
                    $wallets_response = $this->api->get_merchant_wallets();
                    if (!is_wp_error($wallets_response) && isset($wallets_response['wallets'])) {
                        // Format API wallet response to match expected format
                        foreach ($wallets_response['wallets'] as $wallet) {
                            if (isset($wallet['networkShortName']) && isset($wallet['walletAddress'])) {
                                $merchant_wallets[$wallet['networkShortName']] = $wallet['walletAddress'];
                            }
                        }
                    }
                }
                
                return array(
                    'id' => $response['merchant']['id'] ?? 'N/A',
                    'name' => $response['merchant']['businessName'] ?? $response['merchant']['firstName'] . ' ' . $response['merchant']['lastName'] ?? 'Merchant',
                    'email' => $response['merchant']['email'] ?? '',
                    'status' => $response['merchant']['status'] ?? 'active',
                    'verified' => $response['merchant']['verified'] ?? false,
                    'customFeePercentage' => $response['merchant']['customFeePercentage'] ?? STABLEZACT_DEFAULT_FEE_PERCENTAGE,
                    'feeChargedTo' => $response['merchant']['feeChargedTo'] ?? 'customer',
                    'merchantWallets' => $merchant_wallets,
                    'networks' => $response['networks'] ?? array(),
                    'tokens' => $response['tokens'] ?? array()
                );
            }
            
            return $this->get_mock_merchant_data();
        } catch (Exception $e) {
            return $this->get_mock_merchant_data();
        }
    }
    
    /**
     * Get mock merchant data for fallback
     */
    private function get_mock_merchant_data() {
        return array(
            'id' => 'merchant_' . substr(md5($this->gateway_settings['public_key'] ?? 'demo'), 0, 8),
            'name' => 'Demo Merchant',
            'email' => 'demo@stablezact.com',
            'status' => 'active',
            'verified' => true,
            'customFeePercentage' => STABLEZACT_DEFAULT_FEE_PERCENTAGE,
            'feeChargedTo' => 'customer',
            'merchantWallets' => array(
                'ethereum' => '0x' . '1234567890123456789012345678901234567890',
                'bsc' => '0x' . '0987654321098765432109876543210987654321',
                'polygon' => '0x' . '1111111111111111111111111111111111111111',
                'solana' => 'Sol1234567890123456789012345678901234567890'
            ),
            'networks' => array(),
            'tokens' => array()
        );
    }

    /**
     * Get payment statistics for this merchant
     */
    private function get_payment_stats() {
        if (!$this->api) {
            return $this->get_mock_stats();
        }

        try {
            // Use merchant-specific stats endpoint: GET /api/payments/merchant/stats
            $response = $this->api->get_merchant_payment_stats();

            if (is_wp_error($response)) {
                return $this->get_mock_stats();
            }

            // API returns: { success: true, stats: { totalPayments, completedPayments, pendingPayments, failedPayments, totalAmount, totalFeeAmount, averageAmount } }
            // Note: All amounts are returned as strings for decimal precision
            if (isset($response['success']) && $response['success'] && isset($response['stats'])) {
                $stats = $response['stats'];

                // Convert string amounts to floats (API returns strings for precision)
                $totalAmount = floatval($stats['totalAmount'] ?? '0');
                $totalFeeAmount = floatval($stats['totalFeeAmount'] ?? '0');
                $averageAmount = floatval($stats['averageAmount'] ?? '0');

                return array(
                    'totalPayments' => intval($stats['totalPayments'] ?? 0),
                    'completedPayments' => intval($stats['completedPayments'] ?? 0),
                    'pendingPayments' => intval($stats['pendingPayments'] ?? 0),
                    'failedPayments' => intval($stats['failedPayments'] ?? 0),
                    'totalVolume' => $totalAmount,
                    'totalFees' => $totalFeeAmount,
                    'averagePayment' => $averageAmount,
                    'byNetwork' => array(), // Not provided by this endpoint
                    'byCurrency' => array(), // Not provided by this endpoint
                    'monthly' => array() // Not provided by this endpoint
                );
            }

            return $this->get_mock_stats();
        } catch (Exception $e) {
            return $this->get_mock_stats();
        }
    }
    
    /**
     * Helper methods for stats transformation
     */
    private function sum_stats_count($currency_stats) {
        return array_sum(array_column($currency_stats, 'count'));
    }
    
    private function get_status_count($status_stats, $status) {
        foreach ($status_stats as $stat) {
            if ($stat['status'] === $status) {
                return intval($stat['count']);
            }
        }
        return 0;
    }
    
    private function sum_stats_amount($currency_stats) {
        return array_sum(array_map('floatval', array_column($currency_stats, 'totalAmount')));
    }
    
    private function calculate_total_fees($currency_stats) {
        $total_fees = 0;
        foreach ($currency_stats as $stat) {
            $volume = floatval($stat['totalAmount'] ?? 0);
            $total_fees += $volume * STABLEZACT_DEFAULT_FEE_PERCENTAGE; // Assuming the default fee rate
        }
        return $total_fees;
    }
    
    private function transform_network_stats($network_stats) {
        $transformed = array();
        foreach ($network_stats as $stat) {
            $network_name = strtolower($stat['network'] ?? 'unknown');
            $transformed[$network_name] = array(
                'count' => intval($stat['count'] ?? 0),
                'volume' => floatval($stat['totalAmount'] ?? 0)
            );
        }
        return $transformed;
    }
    
    private function transform_currency_stats($currency_stats) {
        $transformed = array();
        foreach ($currency_stats as $stat) {
            $currency = $stat['currency'] ?? 'UNKNOWN';
            $transformed[$currency] = array(
                'count' => intval($stat['count'] ?? 0),
                'volume' => floatval($stat['totalAmount'] ?? 0)
            );
        }
        return $transformed;
    }

    /**
     * Get recent transactions
     */
    private function get_recent_transactions($limit = 5) {
        if (!$this->api) {
            return array(); // Return empty array instead of mock data
        }

        try {
            $response = $this->api->get_merchant_payments(array(
                'limit' => $limit,
                'page' => 1
            ));

            if (is_wp_error($response)) {
                return array(); // Return empty array instead of mock data
            }

            // API returns: { success: true, payments: [...], pagination: {...}, filters: {...} }
            if (isset($response['success']) && $response['success'] && isset($response['payments'])) {
                return $response['payments'];
            }

            return array(); // Return empty array instead of mock data
        } catch (Exception $e) {
            return array(); // Return empty array instead of mock data
        }
    }
    
    /**
     * Get transaction list with filters and pagination
     */
    private function get_transaction_list($args = array()) {
        if (!$this->api) {
            return $this->get_empty_transaction_list($args);
        }

        try {
            // Transform WordPress pagination to API format
            $api_args = array(
                'page' => isset($args['page']) ? intval($args['page']) : 1,
                'limit' => isset($args['limit']) ? intval($args['limit']) : 20
            );

            // Add filters
            if (!empty($args['status'])) {
                $api_args['status'] = $args['status'];
            }
            if (!empty($args['currency'])) {
                $api_args['currency'] = $args['currency'];
            }
            if (!empty($args['search'])) {
                $api_args['search'] = $args['search'];
            }
            if (!empty($args['start_date'])) {
                $api_args['startDate'] = $args['start_date'];
            }
            if (!empty($args['end_date'])) {
                $api_args['endDate'] = $args['end_date'];
            }

            $response = $this->api->get_merchant_payments($api_args);

            if (is_wp_error($response)) {
                return $this->get_empty_transaction_list($args);
            }

            // API returns: { success: true, payments: [...], pagination: {...}, filters: {...} }
            if (isset($response['success']) && $response['success']) {
                return array(
                    'payments' => $response['payments'] ?? array(),
                    'pagination' => array(
                        'total' => $response['pagination']['totalItems'] ?? 0,
                        'total_pages' => $response['pagination']['totalPages'] ?? 1,
                        'current_page' => $response['pagination']['currentPage'] ?? 1,
                        'limit' => $api_args['limit'],
                        'offset' => ($api_args['page'] - 1) * $api_args['limit']
                    ),
                    'filters' => $response['filters'] ?? array()
                );
            }

            return $this->get_empty_transaction_list($args);
        } catch (Exception $e) {
            return $this->get_empty_transaction_list($args);
        }
    }
    
    /**
     * Get empty transaction list (when no API or no data)
     */
    private function get_empty_transaction_list($args = array()) {
        $limit = $args['limit'] ?? 20;

        return array(
            'payments' => array(),
            'pagination' => array(
                'total' => 0,
                'total_pages' => 0,
                'current_page' => 1,
                'limit' => $limit,
                'offset' => 0
            ),
            'filters' => array(
                'currencies' => array('USDT', 'USDC', 'BNB', 'ETH', 'SOL'),
                'statuses' => array('pending', 'completed', 'failed')
            )
        );
    }

    /**
     * Get transaction details
     */
    private function get_transaction_details($payment_id) {
        if (!$this->api) {
            return array('error' => 'API not configured');
        }

        try {
            $response = $this->api->get_payment($payment_id);

            if (is_wp_error($response)) {
                $error_message = $response->get_error_message();
                $error_code = $response->get_error_code();

                return array(
                    'error' => true,
                    'error_code' => $error_code,
                    'error_message' => $error_message,
                    'details' => 'The Stablezact API returned an error. This may be a backend issue.'
                );
            }


            // API returns payment details directly, not wrapped in a 'payment' key
            if (isset($response['id'])) {
                return $response;
            }

            return array(
                'error' => true,
                'error_message' => 'Invalid API response format',
                'details' => 'The API response did not contain the expected payment data.'
            );
        } catch (Exception $e) {
            return array(
                'error' => true,
                'error_message' => 'Exception: ' . $e->getMessage()
            );
        }
    }
    
    /**
     * Get mock transaction details for fallback
     */
    private function get_mock_transaction_details($payment_id) {
        return array(
            'id' => $payment_id,
            'amount' => 100.00,
            'totalAmount' => 101.75,
            'feeAmount' => 1.75,
            'currency' => 'USDT',
            'status' => 'completed',
            'network' => 'Ethereum',
            'transactionHash' => '0x' . str_repeat('a', 64),
            'senderAddress' => '0x' . str_repeat('b', 40),
            'createdAt' => gmdate('c'),
            'processedAt' => gmdate('c'),
            'metadata' => array(
                'orderId' => 'ORDER_123',
                'customerEmail' => 'customer@example.com'
            )
        );
    }
    
    /**
     * AJAX: Fetch transactions
     */
    public function ajax_fetch_transactions() {
        // Check user capabilities
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        // Verify nonce
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'stablezact_admin_nonce')) {
            wp_send_json_error('Invalid security token');
            return;
        }

        // Build query args from request
        $args = array(
            'page' => isset($_POST['page']) ? intval($_POST['page']) : 1,
            'limit' => isset($_POST['limit']) ? intval($_POST['limit']) : 20
        );
        
        // Add filters
        if (!empty($_POST['status'])) {
            $args['status'] = sanitize_text_field(wp_unslash($_POST['status']));
        }
        if (!empty($_POST['currency'])) {
            $args['currency'] = sanitize_text_field(wp_unslash($_POST['currency']));
        }
        if (!empty($_POST['network'])) {
            $args['network'] = sanitize_text_field(wp_unslash($_POST['network']));
        }
        if (!empty($_POST['search'])) {
            $args['search'] = sanitize_text_field(wp_unslash($_POST['search']));
        }
        if (!empty($_POST['start_date'])) {
            $args['start_date'] = sanitize_text_field(wp_unslash($_POST['start_date']));
        }
        if (!empty($_POST['end_date'])) {
            $args['end_date'] = sanitize_text_field(wp_unslash($_POST['end_date']));
        }
        
        $result = $this->get_transaction_list($args);
        
        if ($result) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error('Failed to fetch transactions');
        }
    }
    
    /**
     * AJAX: Get transaction details
     */
    public function ajax_get_transaction_details() {
        // Check user capabilities
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }

        // Verify nonce
        if (!wp_verify_nonce(isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '', 'stablezact_admin_nonce')) {
            wp_send_json_error('Invalid security token');
            return;
        }

        $payment_id = isset($_POST['payment_id']) ? sanitize_text_field(wp_unslash($_POST['payment_id'])) : '';

        if (empty($payment_id)) {
            wp_send_json_error('Payment ID is required');
            return;
        }

        $transaction_details = $this->get_transaction_details($payment_id);

        // Check if there's an error in the response
        if (isset($transaction_details['error'])) {
            wp_send_json_error(array(
                'message' => $transaction_details['error_message'] ?? 'Failed to fetch transaction details',
                'details' => $transaction_details['details'] ?? 'Check server logs for more information',
                'error_code' => $transaction_details['error_code'] ?? 'unknown'
            ));
            return;
        }

        if ($transaction_details && isset($transaction_details['id'])) {
            wp_send_json_success($transaction_details);
        } else {
            wp_send_json_error('Failed to fetch transaction details. The payment may not exist or there may be a backend issue.');
        }
    }
    
    /**
     * AJAX: Fetch dashboard data
     */
    public function ajax_fetch_dashboard_data() {
        // Check user capabilities
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        // Verify nonce
        if (!wp_verify_nonce(isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '', 'stablezact_admin_nonce')) {
            wp_send_json_error('Invalid security token');
            return;
        }
        
        $merchant_data = $this->get_merchant_dashboard_data();
        $stats = $this->get_payment_stats();
        $recent_transactions = $this->get_recent_transactions(5);
        
        wp_send_json_success(array(
            'merchant' => $merchant_data,
            'stats' => $stats,
            'recent_transactions' => $recent_transactions
        ));
    }
    
    /**
     * AJAX: Update merchant settings
     */
    public function ajax_update_merchant_settings() {
        // Check user capabilities
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        // Verify nonce
        if (!wp_verify_nonce(isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '', 'stablezact_admin_nonce')) {
            wp_send_json_error('Invalid security token');
            return;
        }
        
        if (!$this->api) {
            wp_send_json_error('API not configured');
            return;
        }
        
        // Extract settings data
        $settings_data = array();
        $allowed_fields = array('businessName', 'firstName', 'lastName', 'businessType', 'phone', 'industry', 'position', 'state', 'country', 'postal', 'city', 'address', 'website', 'feeChargedTo');
        
        foreach ($allowed_fields as $field) {
            if (isset($_POST[$field])) {
                $settings_data[$field] = sanitize_text_field(wp_unslash($_POST[$field]));
            }
        }
        
        // Update wallets if provided
        if (isset($_POST['wallets']) && is_array($_POST['wallets'])) {
            $wallets = array();
            $posted_wallets = array_map('sanitize_text_field', wp_unslash($_POST['wallets']));
            foreach ($posted_wallets as $network => $address) {
                $wallets[sanitize_key($network)] = $address;
            }
            
            // Update wallets separately
            $wallet_response = $this->api->update_merchant_wallets($wallets);
            if (is_wp_error($wallet_response)) {
                wp_send_json_error('Failed to update wallet addresses: ' . $wallet_response->get_error_message());
                return;
            }
        }
        
        // Update profile
        if (!empty($settings_data)) {
            $response = $this->api->update_merchant_profile($settings_data);
            
            if (is_wp_error($response)) {
                wp_send_json_error('Failed to update merchant profile: ' . $response->get_error_message());
                return;
            }
        }
        
        wp_send_json_success('Settings updated successfully');
    }
    
    /**
     * AJAX: Test API connection
     */
    public function ajax_test_connection() {
        // Check user capabilities
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        // Verify nonce
        if (!wp_verify_nonce(isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '', 'stablezact_admin_nonce')) {
            wp_send_json_error('Invalid security token');
            return;
        }
        
        if (!$this->api) {
            wp_send_json_error('API not configured');
            return;
        }
        
        try {
            $response = $this->api->get_merchant_dashboard();
            
            if (is_wp_error($response)) {
                wp_send_json_error('Connection failed: ' . $response->get_error_message());
                return;
            }
            
            $merchant_name = 'Unknown';
            if (isset($response['merchant'])) {
                $merchant = $response['merchant'];
                $merchant_name = $merchant['businessName'] ?? $merchant['firstName'] . ' ' . $merchant['lastName'] ?? 'Merchant';
            }
            
            wp_send_json_success(array(
                /* translators: %s: merchant name */
                'message' => sprintf(__('Connection successful! Connected as: %s', 'stablezact-crypto-payments'), $merchant_name),
                'merchant_data' => $response['merchant'] ?? null
            ));
            
        } catch (Exception $e) {
            wp_send_json_error('Connection test failed: ' . $e->getMessage());
        }
    }
    
    /**
     * AJAX: Regenerate webhook secret
     */
    public function ajax_regenerate_webhook_secret() {
        // Check user capabilities
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        // Verify nonce
        if (!wp_verify_nonce(isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '', 'stablezact_admin_nonce')) {
            wp_send_json_error('Invalid security token');
            return;
        }
        
        // Generate new webhook secret
        $new_secret = wp_generate_password(32, false);
        
        // Update the gateway settings
        $gateway_settings = get_option('woocommerce_stablezact_settings', array());
        $gateway_settings['webhook_secret'] = $new_secret;
        update_option('woocommerce_stablezact_settings', $gateway_settings);
        
        wp_send_json_success(array(
            'secret' => $new_secret,
            'message' => __('Webhook secret regenerated successfully', 'stablezact-crypto-payments')
        ));
    }
    
    /**
     * AJAX: Save network settings
     */
    public function ajax_save_network_settings() {
        // Check user capabilities
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        // Verify nonce
        if (!wp_verify_nonce(isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '', 'stablezact_admin_nonce')) {
            wp_send_json_error('Invalid security token');
            return;
        }
        
        if (!isset($_POST['networks']) || !is_array($_POST['networks'])) {
            wp_send_json_error('Invalid network data');
            return;
        }

        // Sanitize network settings up front (keys via sanitize_key, values to bool).
        $sanitized_networks = array();
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- each element sanitized in the loop before any use
        foreach (wp_unslash($_POST['networks']) as $network => $enabled) {
            $sanitized_networks[sanitize_key($network)] = (bool) $enabled;
        }
        
        // Save to WordPress options
        update_option('stablezact_enabled_networks', $sanitized_networks);
        
        // If API is available, try to sync with Stablezact backend
        if ($this->api) {
            try {
                // This would be a custom endpoint to update network preferences
                // For now, we'll just save locally
            } catch (Exception $e) {
            }
        }
        
        wp_send_json_success(array(
            'message' => __('Network settings saved successfully', 'stablezact-crypto-payments'),
            'networks' => $sanitized_networks
        ));
    }
    
    /**
     * AJAX: Update wallet addresses
     */
    public function ajax_update_wallet_addresses() {
        // Check user capabilities
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        // Verify nonce
        if (!wp_verify_nonce(isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '', 'stablezact_admin_nonce')) {
            $this->log('Invalid nonce in wallet update request', 'error', array('force_log' => true));
            wp_send_json_error('Invalid security token');
            return;
        }
        
        if (!$this->api) {
            $this->log('API not configured for wallet update', 'error', array('force_log' => true));
            wp_send_json_error('API not configured. Please configure your API credentials first.');
            return;
        }
        
        // Get wallet data — sanitize keys (network) and values up front so nothing
        // raw is used or logged (e.g. via array_keys below) before sanitization.
        $wallets = array();
        if ( isset( $_POST['wallets'] ) && is_array( $_POST['wallets'] ) ) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- each element sanitized on the next line before any use
            foreach ( wp_unslash( $_POST['wallets'] ) as $network => $data ) {
                $wallets[ sanitize_key( $network ) ] = is_array( $data ) ? map_deep( $data, 'sanitize_text_field' ) : sanitize_text_field( $data );
            }
        }

        if (empty($wallets)) {
            $this->log('Empty wallet data received', 'error', array('force_log' => true));
            wp_send_json_error('No wallet addresses provided');
            return;
        }

        $this->log('Processing wallet update request', 'info', array(
            'wallet_count' => count($wallets),
            'networks' => array_keys($wallets),
            'force_log' => true
        ));

        // Sanitize and format wallet addresses
        $formatted_wallets = array();
        foreach ($wallets as $network => $data) {
            $network = sanitize_key($network);
            
            // Handle both simple addresses and complex wallet data
            if (is_array($data)) {
                $formatted_wallets[$network] = array(
                    'address' => sanitize_text_field($data['address']),
                    'supportedTokens' => isset($data['supportedTokens']) ? array_map('sanitize_text_field', $data['supportedTokens']) : array()
                );
            } else {
                $address = sanitize_text_field($data);
                if (!empty($address)) {
                    $formatted_wallets[$network] = $address;
                }
            }
        }

        // First check API credentials
        $this->log('Checking API credentials before wallet update', 'debug', array('force_log' => true));
        $check_response = $this->api->ensure_valid_credentials();
        if (is_wp_error($check_response)) {
            $this->log('API credential check failed', 'error', array(
                'error' => $check_response->get_error_message(),
                'code' => $check_response->get_error_code(),
                'force_log' => true
            ));
            wp_send_json_error('API credentials check failed: ' . $check_response->get_error_message());
            return;
        }

        // Update wallets
        $this->log('Sending wallet update request', 'info', array(
            'formatted_wallet_count' => count($formatted_wallets),
            'networks' => array_keys($formatted_wallets),
            'force_log' => true
        ));
        
        $response = $this->api->update_merchant_wallets($formatted_wallets);
        
        if (is_wp_error($response)) {
            $error_message = $response->get_error_message();
            $error_code = $response->get_error_code();
            
            $this->log('Wallet update failed', 'error', array(
                'error' => $error_message,
                'code' => $error_code,
                'force_log' => true
            ));
            
            if ($error_code === 'invalid_credentials') {
                // Try to refresh credentials automatically
                $this->log('Attempting credential refresh', 'info', array('force_log' => true));
                $refresh_response = $this->api->refresh_credentials();
                if ($refresh_response) {
                    // Retry wallet update with fresh credentials
                    $this->log('Retrying wallet update after credential refresh', 'info', array('force_log' => true));
                    $response = $this->api->update_merchant_wallets($formatted_wallets);
                    if (!is_wp_error($response)) {
                        $this->log('Wallet update successful after credential refresh', 'info', array('force_log' => true));
                        wp_send_json_success('Wallet addresses updated successfully after credential refresh');
                        return;
                    }
                }
                $this->log('Credential refresh failed', 'error', array('force_log' => true));
                wp_send_json_error('Failed to update wallet addresses. Please try logging in again.');
                return;
            }
            wp_send_json_error('Failed to update wallet addresses: ' . $error_message);
            return;
        }
        
        $this->log('Wallet update completed successfully', 'info', array('force_log' => true));
        wp_send_json_success('Wallet addresses updated successfully');
    }
    
    /**
     * AJAX: Check credentials
     */
    public function ajax_check_credentials() {
        // Check user capabilities
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        // Verify nonce
        if (!wp_verify_nonce(isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '', 'stablezact_admin_nonce')) {
            wp_send_json_error('Invalid security token');
            return;
        }

        if (!$this->api) {
            wp_send_json_error('API not configured');
            return;
        }

        try {
            // Get current wallet status
            $wallet_response = $this->api->get_merchant_wallets();
            
            if (is_wp_error($wallet_response)) {
                if ($wallet_response->get_error_code() === 'invalid_credentials') {
                    // Try to refresh credentials
                    $refresh_response = $this->api->refresh_credentials();
                    if ($refresh_response) {
                        // Retry wallet fetch with fresh credentials
                        $wallet_response = $this->api->get_merchant_wallets();
                        if (!is_wp_error($wallet_response)) {
                            wp_send_json_success($wallet_response);
                            return;
                        }
                    }
                }
                wp_send_json_error($wallet_response->get_error_message());
                return;
            }

            wp_send_json_success($wallet_response);
        } catch (Exception $e) {
            wp_send_json_error($e->getMessage());
        }
    }

    /**
     * AJAX: Refresh API credentials
     */
    public function ajax_refresh_credentials() {
        // Check user capabilities
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        check_ajax_referer('stablezact_admin_nonce', 'nonce');
        
        if (!$this->api) {
            wp_send_json_error('API not configured');
            return;
        }
        
        try {
            if ($this->api->refresh_credentials()) {
                wp_send_json_success();
            } else {
                wp_send_json_error('Failed to refresh credentials');
            }
        } catch (Exception $e) {
            wp_send_json_error($e->getMessage());
        }
    }
    
    /**
     * Clear stored API credentials
     */
    private function clear_stored_credentials() {
        $settings = get_option('woocommerce_stablezact_settings', array());
        $settings['public_key'] = '';
        update_option('woocommerce_stablezact_settings', $settings);
    }

    /**
     * AJAX: Clear credentials and force relogin
     */
    public function ajax_clear_credentials() {
        // Check user capabilities
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        // Verify nonce
        if (!wp_verify_nonce(isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '', 'stablezact_admin_nonce')) {
            wp_send_json_error('Invalid security token');
            return;
        }
        
        $this->clear_stored_credentials();
        wp_send_json_success('Credentials cleared. Please log in again.');
    }
    
    /**
     * Get mock statistics for demo purposes
     */
    private function get_mock_stats() {
        return array(
            'totalPayments' => 47,
            'completedPayments' => 43,
            'pendingPayments' => 3,
            'failedPayments' => 1,
            'totalVolume' => 15420.50,
            'totalFees' => 269.86,
            'byNetwork' => array(
                'ethereum' => array('count' => 25, 'volume' => 8500.00),
                'bsc' => array('count' => 15, 'volume' => 4200.50),
                'polygon' => array('count' => 7, 'volume' => 2720.00)
            ),
            'byCurrency' => array(
                'USDT' => array('count' => 28, 'volume' => 9800.00),
                'USDC' => array('count' => 12, 'volume' => 3620.50),
                'BNB' => array('count' => 7, 'volume' => 2000.00)
            ),
            'monthly' => array(
                array('month' => 'Jan 2024', 'count' => 15, 'totalAmount' => 1500.00),
                array('month' => 'Feb 2024', 'count' => 25, 'totalAmount' => 2800.00),
                array('month' => 'Mar 2024', 'count' => 32, 'totalAmount' => 3120.50)
            )
        );
    }
    
    /**
     * Get mock transactions for demo purposes
     */
    private function get_mock_transactions($limit = 10) {
        $currencies = array('USDT', 'USDC', 'BNB', 'ETH', 'SOL');
        $networks = array('ethereum', 'bsc', 'polygon', 'solana');
        $statuses = array('completed', 'pending', 'processing', 'failed');
        $amounts = array(50.00, 75.25, 89.99, 120.50, 150.00, 200.75, 250.00, 300.25, 450.00, 500.75, 750.00, 1000.00);
        
        $mock_transactions = array();
        
        for ($i = 1; $i <= $limit; $i++) {
            $currency = $currencies[array_rand($currencies)];
            $network = $networks[array_rand($networks)];
            $status = $statuses[array_rand($statuses)];
            $amount = $amounts[array_rand($amounts)];
            
            // Adjust network based on currency
            if ($currency === 'SOL') {
                $network = 'solana';
            } elseif ($currency === 'BNB') {
                $network = 'bsc';
            }
            
            $transaction = array(
                'id' => 'pay_' . substr(md5($i . time()), 0, 10),
                'amount' => $amount,
                'currency' => $currency,
                'network' => $network,
                'status' => $status,
                'createdAt' => gmdate('c', strtotime("-{$i} hours")),
                'totalAmount' => $amount + ($amount * STABLEZACT_DEFAULT_FEE_PERCENTAGE),
                'feeAmount' => $amount * STABLEZACT_DEFAULT_FEE_PERCENTAGE
            );
            
            // Add transaction hash for completed/processing transactions
            if (in_array($status, array('completed', 'processing'))) {
                $transaction['transactionHash'] = '0x' . substr(md5('tx' . $i . time()), 0, 64);
                if ($status === 'completed') {
                    $transaction['processedAt'] = gmdate('c', strtotime("-{$i} hours") + wp_rand(300, 3600));
                    $transaction['confirmations'] = wp_rand(12, 100);
                }
            }
            
            $mock_transactions[] = $transaction;
        }
        
        return $mock_transactions;
    }

    /**
     * Log admin interactions
     *
     * @param string $message The log message
     * @param string $level The log level (debug, info, error)
     * @param array $context Additional context
     */
    private function log($message, $level = 'debug', $context = array()) {
        // Format the log entry
        $log_entry = sprintf(
            "[%s] [%s] %s\nContext: %s\n",
            gmdate('Y-m-d H:i:s'),
            strtoupper($level),
            $message,
            wp_json_encode($context)
        );
        
        // Add basic context
        $context['source'] = 'stablezact_admin';
        $context['api_configured'] = !empty($this->api);
        
        if ($this->api) {
            $settings = get_option('woocommerce_stablezact_settings', array());
            $context['public_key_set'] = !empty($settings['public_key']);
            $context['test_mode'] = !empty($settings['testmode']);
        }
        
        // Log to WooCommerce logger only
        if (function_exists('wc_get_logger')) {
            $logger = wc_get_logger();

            switch ($level) {
                case 'error':
                    $logger->error($message, $context);
                    break;
                case 'info':
                    $logger->info($message, $context);
                    break;
                default:
                    $logger->debug($message, $context);
            }
        }
    }
    
    /**
     * AJAX: Refresh wallets from API
     */
    public function ajax_refresh_wallets() {
        // Check user permissions
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        // Verify nonce
        if (!wp_verify_nonce(isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '', 'stablezact_refresh_wallets')) {
            wp_send_json_error('Invalid security token');
            return;
        }
        
        // Get gateway instance
        $settings = get_option('woocommerce_stablezact_settings', array());
        $gateway = new Stablezact_Gateway();
        
        // Clear wallet cache
        delete_transient('stablezact_merchant_wallets');
        
        // Fetch fresh wallet data
        $wallets = $gateway->get_merchant_wallets();
        
        if (!empty($wallets)) {
            wp_send_json_success(array(
                'message' => 'Wallets refreshed successfully',
                'wallets' => $wallets
            ));
        } else {
            wp_send_json_error('Failed to refresh wallets. Please check your API credentials.');
        }
    }
    
    /**
     * Validate settings update to prevent tampering with sensitive fields
     * 
     * @param array $value New settings values
     * @param array $old_value Current settings values
     * @return array Validated settings
     */
    public function validate_settings_update($value, $old_value) {
        // Prevent manual tampering with webhook_secret field only
        $protected_fields = array('webhook_secret');

        foreach ($protected_fields as $field) {
            if (isset($old_value[$field]) && isset($value[$field])) {
                // If the field value has changed and we're not in authorized update context
                if ($value[$field] !== $old_value[$field]) {
                    // Check if this is an authorized update (webhook regeneration, etc.)
                    if (!$this->is_authorized_credential_update($field)) {
                        // Restore the original value
                        $value[$field] = $old_value[$field];

                        // Add admin notice
                        add_action('admin_notices', function() use ($field) {
                            echo '<div class="notice notice-error"><p>';
                            printf(
                                /* translators: %s: field name */
                                esc_html__('Security Notice: Direct modification of %s is not allowed.', 'stablezact-crypto-payments'),
                                esc_html($field)
                            );
                            echo '</p></div>';
                        });
                    }
                }
            }
        }

        return $value;
    }

    /**
     * Check if the current request is an authorized credential update
     *
     * @param string $field The field being updated
     * @return bool True if authorized, false otherwise
     */
    private function is_authorized_credential_update($field) {
        // Check if this is a webhook secret regeneration
        $action = isset($_POST['action']) ? sanitize_text_field(wp_unslash($_POST['action'])) : '';
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';

        if ($field === 'webhook_secret' && $action === 'stablezact_regenerate_webhook_secret') {
            return wp_verify_nonce($nonce, 'stablezact_admin_nonce');
        }

        return false;
    }

    /**
     * AJAX: Fetch wallet addresses from Stablezact API
     */
    public function ajax_fetch_wallets() {
        check_ajax_referer('stablezact_wallet_settings_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array(
                'message' => __('Insufficient permissions', 'stablezact-crypto-payments')
            ));
        }

        if (!$this->api) {
            wp_send_json_error(array(
                'message' => __('API not initialized. Please configure API credentials.', 'stablezact-crypto-payments')
            ));
        }

        // Use the same method as dashboard to get merchant data
        $merchant_data = $this->get_merchant_dashboard_data();

        // Extract wallet addresses
        $wallets = array();
        if (isset($merchant_data['merchantWallets']) && is_array($merchant_data['merchantWallets'])) {
            foreach ($merchant_data['merchantWallets'] as $network => $wallet_data) {
                if (is_array($wallet_data) && isset($wallet_data['address'])) {
                    $wallets[$network] = $wallet_data['address'];
                } elseif (is_array($wallet_data) && isset($wallet_data['walletAddress'])) {
                    $wallets[$network] = $wallet_data['walletAddress'];
                } elseif (is_string($wallet_data)) {
                    $wallets[$network] = $wallet_data;
                }
            }
        }

        wp_send_json_success(array(
            'wallets' => $wallets
        ));
    }

    /**
     * AJAX: Save wallet addresses to Stablezact API
     */
    public function ajax_save_wallets() {
        check_ajax_referer('stablezact_wallet_settings_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array(
                'message' => __('Insufficient permissions', 'stablezact-crypto-payments')
            ));
        }

        if (!$this->api) {
            wp_send_json_error(array(
                'message' => __('API not initialized. Please configure API credentials.', 'stablezact-crypto-payments')
            ));
        }

        // Sanitize wallet keys (network) + values (address) up front before any use.
        $wallets_data = array();
        if ( isset( $_POST['wallets'] ) && is_array( $_POST['wallets'] ) ) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- each element sanitized on the next line before any use
            foreach ( wp_unslash( $_POST['wallets'] ) as $network => $address ) {
                $wallets_data[ sanitize_key( $network ) ] = is_array( $address ) ? map_deep( $address, 'sanitize_text_field' ) : sanitize_text_field( $address );
            }
        }

        if (empty($wallets_data)) {
            wp_send_json_error(array(
                'message' => __('No wallet addresses provided', 'stablezact-crypto-payments')
            ));
        }

        // Supported tokens per network (only USDT and USDC)
        $network_tokens = array(
            'ethereum' => array('USDT', 'USDC'),
            'bsc' => array('USDT', 'USDC'),
            'polygon' => array('USDT', 'USDC'),
            'arbitrum' => array('USDT', 'USDC'),
            'optimism' => array('USDT', 'USDC'),
            'avalanche' => array('USDT', 'USDC'),
            'celo' => array('USDT', 'USDC'),
            'base' => array('USDT', 'USDC')
        );

        // Validate and format wallet addresses
        $validated_wallets = array();
        foreach ($wallets_data as $network => $address) {
            // Sanitize the array key: it is echoed in error messages and sent to the API
            // as networkShortName, so it must not carry unsanitized POST data.
            $network = sanitize_key($network);
            $address = sanitize_text_field($address);

            if (empty($address)) {
                continue; // Skip empty addresses
            }

            // Validate EVM address format
            if (!preg_match('/^0x[a-fA-F0-9]{40}$/', $address)) {
                wp_send_json_error(array(
                    /* translators: %s: network name */
                    'message' => sprintf(__('Invalid wallet address format for %s network', 'stablezact-crypto-payments'), $network)
                ));
            }

            $tokens = isset($network_tokens[$network]) ? $network_tokens[$network] : array('USDT', 'USDC');

            $validated_wallets[] = array(
                'networkShortName' => $network,
                'walletAddress' => $address,
                'supportedTokens' => $tokens
            );
        }

        if (empty($validated_wallets)) {
            wp_send_json_error(array(
                'message' => __('At least one wallet address is required', 'stablezact-crypto-payments')
            ));
        }

        // Use the update_merchant_wallets API method
        $response = $this->api->update_merchant_wallets(array(
            'wallets' => $validated_wallets
        ));

        if (is_wp_error($response)) {
            wp_send_json_error(array(
                'message' => __('Failed to save wallet addresses: ', 'stablezact-crypto-payments') . $response->get_error_message()
            ));
        }

        wp_send_json_success(array(
            'message' => __('Wallet addresses saved successfully!', 'stablezact-crypto-payments'),
            'wallets' => $response['wallets'] ?? array()
        ));
    }
} 