<?php
/**
 * PeachPay ConvesioPay payment integration admin settings.
 *
 * @package PeachPay
 */

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

/**
 * ConvesioPay Admin Integration class.
 */
final class PeachPay_Admin_ConvesioPay_Integration {
	
	/**
	 * Encryption key for sensitive data
	 */
	private function get_encryption_key() {
		// Use WordPress secret keys for encryption base
		$key = defined('AUTH_KEY') ? AUTH_KEY : 'fallback-key';
		$salt = defined('SECURE_AUTH_KEY') ? SECURE_AUTH_KEY : 'fallback-salt';
		
		// Create a consistent 32-byte key for AES-256
		return substr(hash('sha256', $key . $salt . 'convesiopay'), 0, 32);
	}
	
	/**
	 * Encrypt sensitive data
	 */
	private function encrypt_data($data) {
		if (empty($data)) {
			return $data;
		}
		
		$key = $this->get_encryption_key();
		$iv = openssl_random_pseudo_bytes(16);
		$encrypted = openssl_encrypt($data, 'AES-256-CBC', $key, 0, $iv);
		
		// Return base64 encoded IV + encrypted data
		return base64_encode($iv . $encrypted);
	}
	
	/**
	 * Decrypt sensitive data
	 */
	private function decrypt_data($encrypted_data) {
		if (empty($encrypted_data)) {
			return $encrypted_data;
		}
		
		$data = base64_decode($encrypted_data);
		if ($data === false) {
			return $encrypted_data; // Return original if not base64
		}
		
		$key = $this->get_encryption_key();
		$iv = substr($data, 0, 16);
		$encrypted = substr($data, 16);
		
		$decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $key, 0, $iv);
		return $decrypted !== false ? $decrypted : $encrypted_data;
	}
	
	/**
	 * Get decrypted ConvesioPay configuration
	 * 
	 * @return array Decrypted configuration array
	 */
	public static function get_decrypted_config() {
		$instance = self::instance();
		$config = get_option('peachpay_connected_convesiopay_config', array());
		
		if (empty($config)) {
			return array();
		}
		
		// Check if config is encrypted
		if (isset($config['encrypted']) && $config['encrypted'] === true) {
			// Decrypt sensitive fields
			$config['api_key'] = $instance->decrypt_data($config['api_key'] ?? '');
			$config['secret_key'] = $instance->decrypt_data($config['secret_key'] ?? '');
			$config['client_key'] = $instance->decrypt_data($config['client_key'] ?? '');
			
			// Decrypt webhook signature key
			if (isset($config['webhook_data']['signature_key'])) {
				$config['webhook_data']['signature_key'] = $instance->decrypt_data($config['webhook_data']['signature_key']);
			}
		}
		
		return $config;
	}
	
	/**
	 * Get instance
	 */
	public static function instance() {
		static $instance = null;
		
		if ( null === $instance ) {
			$instance = new static();
			$instance->init();
		}
		
		return $instance;
	}

	/**
	 * Initialize admin hooks
	 */
	private function init() {
		// Add admin menu
		add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
		
		// Add AJAX handlers for ConvesioPay connection
		add_action( 'wp_ajax_peachpay_convesiopay_connect', array( $this, 'handle_convesiopay_connect' ) );
		add_action( 'wp_ajax_peachpay_convesiopay_disconnect', array( $this, 'handle_convesiopay_disconnect' ) );
		add_action( 'wp_ajax_test_convesiopay_gateway_class', array( $this, 'handle_test_gateway_class' ) );

		// Add AJAX handler for ConvesioPay payment method sync with high priority
		// Try multiple possible WooCommerce gateway toggle action names
		add_action( 'wp_ajax_woocommerce_toggle_gateway_enabled', array( $this, 'handle_gateway_toggle_and_sync' ), 5 );
		add_action( 'wp_ajax_woocommerce_toggle_payment_gateway_enabled', array( $this, 'handle_gateway_toggle_and_sync' ), 5 );

		// Add manual sync trigger for testing
		add_action( 'wp_ajax_convesiopay_manual_sync', array( $this, 'handle_manual_sync' ) );

		// Alternative approach: Hook into admin page loads for ConvesioPay settings
		add_action( 'admin_init', array( $this, 'maybe_sync_on_admin_load' ) );

		// Hook into option updates to sync when gateway settings change
		add_action( 'update_option_woocommerce_peachpay_convesiopay_card_settings', array( $this, 'on_gateway_setting_updated' ), 10, 2 );
		add_action( 'update_option_woocommerce_peachpay_convesiopay_btcpay_settings', array( $this, 'on_gateway_setting_updated' ), 10, 2 );
		add_action( 'update_option_woocommerce_peachpay_convesiopay_applepay_settings', array( $this, 'on_gateway_setting_updated' ), 10, 2 );
		add_action( 'update_option_woocommerce_peachpay_convesiopay_googlepay_settings', array( $this, 'on_gateway_setting_updated' ), 10, 2 );
		add_action( 'update_option_woocommerce_peachpay_convesiopay_unified_settings', array( $this, 'on_gateway_setting_updated' ), 10, 2 );

		// Add admin scripts
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
	}

	/**
	 * Add admin menu
	 */
	public function add_admin_menu() {
		// Add submenu to PeachPay admin
		add_submenu_page(
			'peachpay',
			__( 'ConvesioPay', 'peachpay-for-woocommerce' ),
			__( 'ConvesioPay', 'peachpay-for-woocommerce' ),
			'manage_options',
			'admin.php?page=peachpay&tab=payment#convesiopay',
			array( $this, 'do_admin_page' )
		);
	}

	/**
	 * Enqueue admin scripts
	 */
	public function enqueue_admin_scripts( $hook ) {
		if ( 'peachpay_page_peachpay-convesiopay' !== $hook ) {
			return;
		}
		
		wp_enqueue_script( 'jquery' );
		wp_localize_script( 'jquery', 'peachpay_convesiopay_admin', array(
			'ajax_url' => admin_url( 'admin-ajax.php' ),
			'nonce' => wp_create_nonce( 'peachpay_admin_nonce' ),
		) );
	}

	/**
	 * Display the admin page content.
	 */
	public static function do_admin_page( $args ) {
		?>
		<div id="convesiopay" class="peachpay-setting-section">
			<?php
				// ConvesioPay connect option.
				require PeachPay::get_plugin_path() . '/core/payments/convesiopay/admin/views/html-convesiopay-connect.php';
			?>
			<?php if ( peachpay_convesiopay_connected() ) : ?>
				<div>
					<?php
						// Safety check: ensure WooCommerce is fully loaded
						if ( ! class_exists( 'WC_Payment_Gateway' ) || ! function_exists( 'WC' ) ) {
							echo '<div style="background: #f8d7da; padding: 10px; margin: 10px 0; border: 1px solid #f5c6cb; color: #721c24;">';
							echo '<strong>WooCommerce Not Ready:</strong> WooCommerce is not fully loaded yet. Please refresh the page.';
							echo '</div>';
						} else {
							// Get available payment methods from ConvesioPay API
							$available_methods = self::get_available_payment_methods();
							$gateway_list = self::filter_gateways_by_api_methods( $available_methods );
							
							// Only show gateways if we have valid instances
							if ( ! empty( $gateway_list ) && is_array( $gateway_list ) ) {
								require PeachPay::get_plugin_path() . '/core/admin/views/html-gateways.php';
							} else {
								echo '<div style="background: #fff3cd; padding: 10px; margin: 10px 0; border: 1px solid #ffeaa7; color: #856404;">';
								echo '<strong>Payment Methods:</strong> ';
								if ( is_array( $available_methods ) && ! empty( $available_methods ) ) {
									echo 'Available methods from ConvesioPay API: <code>' . implode( ', ', $available_methods ) . '</code><br>';
									echo 'No matching PeachPay gateways found for these methods.';
								} else {
									echo 'Unable to fetch payment methods from ConvesioPay API. Please check your integration configuration.';
								}
								echo '</div>';
							}
						}
					?>
				</div>
								
			<?php else : ?>
				<div style="background: #fff3cd; padding: 10px; margin: 10px 0; border: 1px solid #ffeaa7;">
					<strong>Not Connected:</strong> ConvesioPay is not connected yet. Please connect your account above.
				</div>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Handle ConvesioPay connection AJAX request using official connect endpoint.
	 */
	public function handle_convesiopay_connect() {
		if (!current_user_can('manage_woocommerce')) {
			wp_send_json_error('Insufficient permissions');
			return;
		}
		
		// Verify nonce for security
		if (!wp_verify_nonce($_POST['nonce'] ?? '', 'peachpay_convesiopay_connect')) {
			wp_send_json_error('Security check failed');
			return;
		}
		
		$email = sanitize_text_field($_POST['email'] ?? '');
		$password = sanitize_text_field($_POST['password'] ?? '');
		$admin_client_key = sanitize_text_field($_POST['admin_client_key'] ?? '');
		$merchant_api_key = sanitize_text_field($_POST['merchant_api_key'] ?? '');
		
		// Support both password and adminClientKey authentication methods
		if (empty($email) || (empty($password) && empty($admin_client_key))) {
			wp_send_json_error('Email and either Password or Admin Client Key are required');
			return;
		}
		
		// Use adminClientKey if provided, otherwise use password
		$auth_credential = !empty($admin_client_key) ? $admin_client_key : $password;
		
		// Auto-generate integration parameters
		$site_url = get_site_url();
		$domain = $site_url;
		// $integration_name = sanitize_title(get_bloginfo('name')) . '_' . substr(md5($site_url), 0, 8);
		$integration_name = 'PeachPay_'. substr(md5($site_url), 0, 8);
		$webhook_notification_url = rest_url('peachpay/v1/convesiopay/webhook');
		
		$api_url = peachpay_is_test_mode() ? 'https://api-qa.convesiopay.com/v1' : 'https://api.convesiopay.com/v1';
		
		// Use official ConvesioPay integrations/connect endpoint with Basic Auth
		// Updated according to new documentation structure
		$connect_data = array(
			'integrationName' => $integration_name,
			'domain' => $domain,
			'webhooks' => array(
				array(
					'url' => $webhook_notification_url,
					'eventTypes' => array('payment')
				)
				),
				'integrationPartnerId' => peachpay_is_test_mode() ? '69cd60fd9fe6e5cce89f40fa' : '69cd60c62165d18a0271dd47'
		);

		if (!empty($merchant_api_key)) {
			$connect_data['merchantApiKey'] = $merchant_api_key;
		}
		
		// Create Basic Authentication header (email:password or email:adminClientKey base64 encoded)
		$auth_string = base64_encode($email . ':' . $auth_credential);
		
		$response = wp_remote_post($api_url . '/integrations/connect', array(
			'headers' => array(
				'Authorization' => 'Basic ' . $auth_string,
				'Content-Type' => 'application/json',
			),
			'body' => json_encode($connect_data),
			'timeout' => 30,
		));
		
		if (is_wp_error($response)) {
			wp_send_json_error('Connection failed: ' . $response->get_error_message());
			return;
		}
		
		$status_code = wp_remote_retrieve_response_code($response);
		$response_body = wp_remote_retrieve_body($response);
		$response_data = json_decode($response_body, true);
		
		
		if ($status_code !== 200) {
			$error_message = 'API connection failed. Status: ' . $status_code;
			if (isset($response_data['message'])) {
				$error_message .= ' - ' . $response_data['message'];
			}
			if (isset($response_data['body']['message'])) {
				$error_message .= ' - ' . $response_data['body']['message'];
			}
			wp_send_json_error($error_message);
			return;
		}
		
		// Extract response data according to the updated API format
		$api_key = '';
		$secret_key = '';
		$client_key = '';
		$webhook_data = array();
		
		if (is_array($response_data)) {
			$api_key = sanitize_text_field($response_data['apiKey'] ?? '');
			$secret_key = sanitize_text_field($response_data['secretKey'] ?? '');
			$client_key = sanitize_text_field($response_data['clientKey'] ?? '');
			$integration_name = sanitize_text_field($response_data['integrationName'] ?? '');
			
			// Extract webhook information from new webhooks array format
			if (isset($response_data['webhooks']) && is_array($response_data['webhooks']) && !empty($response_data['webhooks'])) {
				// Get the first webhook configuration
				$webhook = $response_data['webhooks'][0];
				$webhook_data = array(
					'name' => sanitize_text_field($webhook['name'] ?? ''),
					'signature_key' => sanitize_text_field($webhook['signatureKey'] ?? ''),
					'notification_url' => sanitize_text_field($webhook['notificationUrl'] ?? ''),
					'event_types' => $webhook['eventTypes'] ?? array('payment', 'paymentMethods')
				);
			}
		}

		// Store the response keys and configuration with encryption for sensitive data
		$config = array(
			'integration_name' => $integration_name,
			'api_key' => $this->encrypt_data($api_key), // Encrypt API key
			'secret_key' => $this->encrypt_data($secret_key), // Encrypt secret key
			'client_key' => $this->encrypt_data($client_key), // Encrypt client key
			'domain' => $domain,
			'webhook_notification_url' => $webhook_notification_url,
			'webhook_data' => array(
				'name' => $webhook_data['name'] ?? '',
				'signature_key' => $this->encrypt_data($webhook_data['signature_key'] ?? ''), // Encrypt signature key
				'notification_url' => $webhook_data['notification_url'] ?? '',
				'event_types' => $webhook_data['event_types'] ?? array('payment', 'paymentMethods'),
			),
			'api_url' => $api_url,
			'connected_at' => current_time('mysql'),
			'connection_method' => 'integrations_connect_api',
			'email' => $email, // Email is not sensitive, store as plain text
			'encrypted' => true, // Flag to indicate this config uses encryption
		);
		
		
		
		update_option('peachpay_connected_convesiopay_config', $config);
		update_option('peachpay_connected_convesiopay_account', array(
			'connected_at' => current_time('mysql'),
			'status' => 'connected',
			'connection_method' => 'official_api',
			'integration_id' => $config['integration_id'] ?? null,
		));

		// Auto-enable ConvesioPay gateways after successful connection
		$this->auto_enable_convesiopay_gateways();

		wp_send_json_success('ConvesioPay connected successfully using official API');
	}

	/**
	 * Auto-enable ConvesioPay gateways after successful connection
	 */
	private function auto_enable_convesiopay_gateways() {
		// List of ConvesioPay gateway IDs to enable
		$convesiopay_gateways = array(
			'peachpay_convesiopay_unified' => 'yes', // Enable unified gateway
			'peachpay_convesiopay_card' => 'yes',    // Enable card gateway
			'peachpay_convesiopay_btcpay' => 'yes',  // Enable BTCPay gateway
			'peachpay_convesiopay_applepay' => 'yes', // Enable Apple Pay gateway
			'peachpay_convesiopay_googlepay' => 'yes', // Enable Google Pay gateway
		);

		foreach ($convesiopay_gateways as $gateway_id => $enabled_status) {
			// Update the gateway enabled setting
			$option_name = 'woocommerce_' . $gateway_id . '_settings';
			$gateway_settings = get_option($option_name, array());

			// Set enabled to 'yes' if not already set
			$gateway_settings['enabled'] = $enabled_status;

			// Update the option
			update_option($option_name, $gateway_settings);
		}

		// Trigger synchronization with ConvesioPay API after enabling gateways
		$this->sync_payment_methods_with_convesiopay();
	}

	/**
	 * Handle ConvesioPay disconnection AJAX request using official disconnect endpoint.
	 */
	public function handle_convesiopay_disconnect() {
		if (!current_user_can('manage_woocommerce')) {
			wp_send_json_error('Insufficient permissions');
			return;
		}
		
		// Verify nonce
		if ( ! wp_verify_nonce( $_POST['nonce'], 'peachpay_convesiopay_disconnect' ) ) {
			wp_send_json_error( 'Security check failed' );
			return;
		}

		// Get current configuration to retrieve integration details (decrypted)
		$config = self::get_decrypted_config();
		if (empty($config)) {
			// Still try to clean up local data
			delete_option( 'peachpay_connected_convesiopay_config' );
			delete_option( 'peachpay_connected_convesiopay_account' );
			wp_send_json_success( 'ConvesioPay account disconnected locally!' );
			return;
		}

		$api_url = peachpay_is_test_mode() ? 'https://api-qa.convesiopay.com/v1' : 'https://api.convesiopay.com/v1';
		
		// Use official ConvesioPay integrations/disconnect endpoint
		// This endpoint requires the secret key for authorization (no body data needed)

		$response = wp_remote_post($api_url . '/integrations/disconnect', array(
			'headers' => array(
				'Authorization' => $config['secret_key'] ?? '',
			),
			'timeout' => 30,
		));

		$api_success = true;
		$api_error_message = '';

		if (is_wp_error($response)) {
			$api_success = false;
			$api_error_message = $response->get_error_message();
		} else {
			$status_code = wp_remote_retrieve_response_code($response);
			$response_body = wp_remote_retrieve_body($response);
			$response_data = json_decode($response_body, true);


			if ($status_code !== 200) {
				$api_success = false;
				$api_error_message = 'API disconnection failed. Status: ' . $status_code;
				if (isset($response_data['message'])) {
					$api_error_message .= ' - ' . $response_data['message'];
				}
			}
		}

		// Always clean up local configuration regardless of API response
		$local_cleanup_result = delete_option( 'peachpay_connected_convesiopay_config' );
		$account_cleanup_result = delete_option( 'peachpay_connected_convesiopay_account' );

		// Unschedule reconciliation cron when ConvesioPay is disconnected.
		if ( function_exists( 'peachpay_unschedule_convesiopay_reconcile_cron' ) ) {
			peachpay_unschedule_convesiopay_reconcile_cron();
		}

		// Auto-disable ConvesioPay gateways after disconnection
		$this->auto_disable_convesiopay_gateways();


		if ($api_success) {
			wp_send_json_success( 'ConvesioPay account disconnected successfully from both local and remote!' );
		} elseif ($local_cleanup_result && $account_cleanup_result) {
			wp_send_json_success( 'ConvesioPay account disconnected locally. Remote disconnection failed: ' . $api_error_message );
		} else {
			wp_send_json_error( 'Failed to disconnect ConvesioPay account. API Error: ' . $api_error_message );
		}
	}

	/**
	 * Auto-disable ConvesioPay gateways after disconnection
	 */
	private function auto_disable_convesiopay_gateways() {
		// List of ConvesioPay gateway IDs to disable
		$convesiopay_gateways = array(
			'peachpay_convesiopay_unified',
			'peachpay_convesiopay_card',
			'peachpay_convesiopay_btcpay',
			'peachpay_convesiopay_applepay',
			'peachpay_convesiopay_googlepay'
		);

		foreach ($convesiopay_gateways as $gateway_id) {
			// Update the gateway enabled setting
			$option_name = 'woocommerce_' . $gateway_id . '_settings';
			$gateway_settings = get_option($option_name, array());

			// Set enabled to 'no'
			$gateway_settings['enabled'] = 'no';

			// Update the option
			update_option($option_name, $gateway_settings);
		}
	}

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'wp_ajax_test_convesiopay_gateway_class', array( $this, 'handle_test_gateway_class' ) );
	}
	
	/**
	 * Handle gateway class testing
	 */
	public function handle_test_gateway_class() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'Insufficient permissions' );
		}
		
		if ( ! wp_verify_nonce( $_POST['nonce'], 'test_gateway_class' ) ) {
			wp_send_json_error( 'Security check failed' );
		}
		
		ob_start();
		
		echo "=== GATEWAY CLASS DEBUG ===\n";
		
		// Check if WooCommerce is loaded
		if ( ! class_exists( 'WC_Payment_Gateway' ) ) {
			echo "❌ WC_Payment_Gateway class not found\n";
			wp_send_json_success( ob_get_clean() );
		}
		echo "✅ WC_Payment_Gateway class found\n";
		
		// Check if our integration class exists
		if ( ! class_exists( 'PeachPay_Convesiopay_Integration' ) ) {
			echo "❌ PeachPay_Convesiopay_Integration class not found\n";
			wp_send_json_success( ob_get_clean() );
		}
		echo "✅ PeachPay_ConvesioPay_Integration class found\n";
		
		// Check if connected
		if ( ! method_exists( 'PeachPay_ConvesioPay_Integration', 'connected' ) ) {
			echo "❌ connected() method not found\n";
			wp_send_json_success( ob_get_clean() );
		}
		
		$connected = PeachPay_ConvesioPay_Integration::connected();
		echo "✅ Connected status: " . ($connected ? 'YES' : 'NO') . "\n";
		
		// Try to load the gateway file
		$gateway_file = ABSPATH . 'wp-content/plugins/peachpay-for-woocommerce/core/payments/convesiopay/gateways/class-peachpay-convesiopay-card-gateway.php';
		
		if ( ! file_exists( $gateway_file ) ) {
			echo "❌ Gateway file not found: " . $gateway_file . "\n";
			wp_send_json_success( ob_get_clean() );
		}
		echo "✅ Gateway file found\n";
		
		// Check file contents for syntax errors
		$file_contents = file_get_contents( $gateway_file );
		if ( $file_contents === false ) {
			echo "❌ Could not read gateway file\n";
			wp_send_json_success( ob_get_clean() );
		}
		
		// Check for basic PHP syntax
		$tokens = token_get_all( $file_contents );
		$has_class = false;
		$class_name = '';
		
		foreach ( $tokens as $token ) {
			if ( is_array( $token ) && $token[0] === T_CLASS ) {
				$has_class = true;
				// Get the next token which should be the class name
				$next_token = next( $tokens );
				if ( is_array( $next_token ) ) {
					$class_name = $next_token[1];
				}
				break;
			}
		}
		
		if ( ! $has_class ) {
			echo "❌ No class definition found in gateway file\n";
			wp_send_json_success( ob_get_clean() );
		}
		echo "✅ Class definition found: " . $class_name . "\n";
		
		// Try to include the file
		echo "🔄 Including gateway file...\n";
		ob_clean();

		try {
			// The card gateway declares `use PeachPay_ConvesioPay_Subscription_Renewal_Trait`
			// and extends PeachPay_Payment_Gateway.  When this diagnostic handler loads the
			// gateway file directly (bypassing the integration loader that normally requires
			// these dependencies), PHP fatals with "Trait not found" / "Class not found".
			// Ensure both dependencies are loaded first.
			require_once ABSPATH . 'wp-content/plugins/peachpay-for-woocommerce/core/abstract/class-peachpay-payment-gateway.php';
			require_once ABSPATH . 'wp-content/plugins/peachpay-for-woocommerce/core/payments/convesiopay/gateways/trait-peachpay-convesiopay-subscription-renewal.php';
			include_once $gateway_file;
			
			// Check if class exists after including
			if ( class_exists( 'PeachPay_ConvesioPay_Card_Gateway' ) ) {
				echo "✅ Gateway class successfully loaded\n";
				
				// Try to instantiate
				try {
					$gateway = new PeachPay_ConvesioPay_Card_Gateway();
					echo "✅ Gateway instance created successfully\n";
					
					// Check if initialized
					if ( method_exists( $gateway, 'is_initialized' ) ) {
						$initialized = $gateway->is_initialized();
						echo "✅ Gateway initialized: " . ($initialized ? 'YES' : 'NO') . "\n";
					}
					
				} catch ( Exception $e ) {
					echo "❌ Error creating gateway instance: " . $e->getMessage() . "\n";
				}
				
			} else {
				echo "❌ Gateway class still not found after including file\n";
				
				// Check for any PHP errors
				$errors = error_get_last();
				if ( $errors ) {
					echo "⚠️ PHP errors: " . print_r( $errors, true ) . "\n";
				}
			}
			
		} catch ( Exception $e ) {
			echo "❌ Exception when including file: " . $e->getMessage() . "\n";
		}
		
		echo "=== END DEBUG ===\n";
		
		wp_send_json_success( ob_get_clean() );
	}
	
	/**
	 * Get available payment methods from ConvesioPay API
	 * 
	 * @return array|false Array of available payment method names, or false on error
	 */
	private static function get_available_payment_methods() {
		// Get DECRYPTED ConvesioPay configuration
		$config = self::get_decrypted_config();

		if ( empty( $config['secret_key'] ) || empty( $config['integration_name'] ) ) {
			return false;
		}

		$secret_key = $config['secret_key'];
		$integration_name = $config['integration_name'];
		
		// Determine API URL based on mode
		$api_url = peachpay_is_test_mode() ? 'https://api-qa.convesiopay.com' : 'https://api.convesiopay.com';
		$payment_methods_url = $api_url . '/v1/payment-methods?integration=' . urlencode( $integration_name );
		
		
		// Make API request
		$response = wp_remote_post( $payment_methods_url, array(
			'timeout' => 30,
			'headers' => array(
				'Authorization' => $secret_key,
				'Content-Type' => 'application/json'
			)
		) );
		
		if ( is_wp_error( $response ) ) {
			return false;
		}
		
		$response_code = wp_remote_retrieve_response_code( $response );
		$response_body = wp_remote_retrieve_body( $response );
		
		
		// $parsed_response = json_decode( $response_body, true );
		// if ( $parsed_response ) {
		// }
		
		if ( $response_code !== 200 ) {
			return false;
		}
		$api_response = json_decode( $response_body, true );
		
		if ( ! is_array( $api_response ) ) {
			return false;
		}
		
		$method_names = array();
		
		// Parse paymentMethods array
		if ( isset( $api_response['paymentMethods'] ) && is_array( $api_response['paymentMethods'] ) ) {
			foreach ( $api_response['paymentMethods'] as $method ) {
				if ( is_array( $method ) && isset( $method['name'] ) ) {
					// Temporarily ignore ACH Direct Debit method
					if ( $method['name'] !== 'ACH Direct Debit' ) {
						$method_names[] = $method['name'];
						// $method_names[] = 'Apple Pay';
						// $method_names[] = 'Credit Card';
					}
				}
			}
		}
		
		// Parse integrations object
		if ( isset( $api_response['integrations'] ) && is_array( $api_response['integrations'] ) ) {
			// Check if BTCPay is enabled
			if ( $api_response['integrations']['btcpay']['enabled'] == true ) {
				$method_names[] = 'BTC Pay';
			}
			
			// Check if Google Pay has merchantId (indicates availability)
			if ( isset( $api_response['integrations']['gpay']['merchantId'] ) && 
				 ! empty( $api_response['integrations']['gpay']['merchantId'] ) ) {
				$method_names[] = 'Google Pay';
			}
		}

		// Auto-sync payment methods with API response
		self::sync_payment_methods_from_api_response($method_names);

		return $method_names;
	}

	/**
	 * Sync payment methods based on API response
	 * Enables/disables gateways based on what's available in ConvesioPay
	 *
	 * @param array $available_methods Array of available payment method names from API
	 */
	private static function sync_payment_methods_from_api_response($available_methods) {
		if (!is_array($available_methods)) {
			return;
		}

		// Mapping between ConvesioPay API method names and gateway IDs
		$method_to_gateway_mapping = array(
			'Credit Card' => 'peachpay_convesiopay_card',
			'Apple Pay' => 'peachpay_convesiopay_applepay',
			'Google Pay' => 'peachpay_convesiopay_googlepay',
			'BTC Pay' => 'peachpay_convesiopay_btcpay',
		);

		// Get all gateways
		$gateways = WC()->payment_gateways->payment_gateways();

		// Loop through our ConvesioPay gateways and enable/disable based on API response
		foreach ($method_to_gateway_mapping as $api_method => $gateway_id) {
			// Check if this payment method is available in the API response
			$should_enable = in_array($api_method, $available_methods, true);

			// Get the gateway
			if (isset($gateways[$gateway_id])) {
				$gateway = $gateways[$gateway_id];
				$current_enabled = $gateway->get_option('enabled', 'no');
				$new_enabled = $should_enable ? 'yes' : 'no';

				// Only update if the state changed
				if ($current_enabled !== $new_enabled) {
					$gateway->update_option('enabled', $new_enabled);
					// error_log("ConvesioPay: Auto-synced {$gateway_id} to {$new_enabled} based on API response");
				}
			}
		}
	}
	
	/**
	 * Filter PeachPay gateways based on ConvesioPay API available methods
	 *
	 * @param array|false $available_methods Array of available payment method names from API
	 * @return array Filtered gateway list
	 */
	private static function filter_gateways_by_api_methods( $available_methods ) {
		// Get all ConvesioPay gateways
		$all_gateways = PeachPay_ConvesioPay_Integration::get_payment_gateways();

		if ( empty( $all_gateways ) ) {
			return array();
		}

		// Define the EXPLICIT order we want payment methods to appear
		// This ensures consistent ordering across all environments.
		$target_payment_methods = array( 'Card', 'Apple Pay', 'Google Pay', 'Crypto' );
		$filtered_gateways = array();

		// Iterate through target methods IN ORDER (not through all_gateways)
		// This guarantees the display order matches our defined order
		foreach ( $target_payment_methods as $target_title ) {
			foreach ( $all_gateways as $gateway ) {
				if ( $gateway->title === $target_title ) {
					$filtered_gateways[] = $gateway;
					break; // Found this method, move to next target
				}
			}
		}

		return $filtered_gateways;

		/*
		// COMMENTED OUT - Original API-based filtering method
		// Uncomment this section if you want to filter based on ConvesioPay API response

		// If API call failed, return empty array (show nothing)
		if ( ! is_array( $available_methods ) ) {
			return array();
		}

		// Mapping between ConvesioPay API method names and PeachPay gateway titles
		$method_to_gateway_mapping = array(
			'Credit Card' => array( 'Card' ), // Maps to Card gateway (API returns "Credit Card")
			'Apple Pay' => array( 'Apple Pay' ), // Maps to Apple Pay gateway
			'BTC Pay' => array( 'Crypto' ), // Maps to BTCPay/Crypto gateway (from integrations.btcpay.enabled)
			'Google Pay' => array( 'Google Pay' ), // Maps to Google Pay gateway (from integrations.gpay.merchantId)
		);

		$filtered_gateways = array();

		foreach ( $all_gateways as $gateway ) {
			$gateway_title = $gateway->title;
			$should_include = false;

			// Check if this gateway matches any available API method
			foreach ( $available_methods as $api_method ) {
				if ( isset( $method_to_gateway_mapping[ $api_method ] ) ) {
					$mapped_titles = $method_to_gateway_mapping[ $api_method ];
					if ( in_array( $gateway_title, $mapped_titles, true ) ) {
						$should_include = true;
						break;
					}
				}
			}

			if ( $should_include ) {
				$filtered_gateways[] = $gateway;
			}
		}

		return $filtered_gateways;
		*/
	}

	/**
	 * Handle gateway toggle and sync with ConvesioPay API
	 * This intercepts the standard WooCommerce gateway toggle AJAX request
	 */
	public function handle_gateway_toggle_and_sync() {
		// Check if this is a ConvesioPay gateway
		$gateway_id = sanitize_text_field($_POST['gateway_id'] ?? '');

		// Check permissions
		if (!current_user_can('manage_woocommerce')) {
			wp_send_json_error('Insufficient permissions');
			return;
		}

		// Verify nonce - try multiple possible nonce names
		$security = $_POST['security'] ?? '';
		$nonce_valid = false;

		// Try different possible nonce names
		$possible_nonces = array(
			'woocommerce-toggle-payment-gateway-enabled',
			'gateway_toggle',
			'peachpay_admin_nonce',
			'_wpnonce'
		);

		foreach ($possible_nonces as $nonce_name) {
			if (wp_verify_nonce($security, $nonce_name)) {
				$nonce_valid = true;
				break;
			}
		}

		if (!$nonce_valid) {
			wp_send_json_error('Security check failed');
			return;
		}

		if (empty($gateway_id)) {
			wp_send_json_error('Gateway ID is required');
			return;
		}

		// Get all payment gateways (including disabled/hidden ones)
		$gateways = WC()->payment_gateways->payment_gateways();

		if (!isset($gateways[$gateway_id])) {
			wp_send_json_error('Gateway not found');
			return;
		}

		$gateway = $gateways[$gateway_id];

		// Toggle the enabled status
		$current_setting = $gateway->get_option('enabled', 'no');
		$new_setting = ($current_setting === 'yes') ? 'no' : 'yes';

		// Update the setting
		$gateway->update_option('enabled', $new_setting);

		// If this is a ConvesioPay gateway, sync with API BEFORE sending response
		if ($this->is_convesiopay_gateway($gateway_id)) {
			$this->sync_payment_methods_with_convesiopay();
		}

		// Return success with the new state
		wp_send_json_success($new_setting === 'yes');
	}

	/**
	 * Check if a gateway ID belongs to ConvesioPay
	 */
	private function is_convesiopay_gateway($gateway_id) {
		$convesiopay_gateways = array(
			'peachpay_convesiopay_card',
			'peachpay_convesiopay_btcpay',
			'peachpay_convesiopay_applepay',
			'peachpay_convesiopay_googlepay',
			'peachpay_convesiopay_unified'
		);

		return in_array($gateway_id, $convesiopay_gateways, true);
	}

	/**
	 * Sync payment method status with ConvesioPay API
	 */
	private function sync_payment_methods_with_convesiopay() {
		// Check if ConvesioPay is connected
		if (!PeachPay_ConvesioPay_Integration::connected()) {
			return;
		}

		// Get configuration
		$config = self::get_decrypted_config();
		if (empty($config['secret_key']) || empty($config['integration_name'])) {
			return;
		}

		// Get current gateway states
		$gateway_states = $this->get_convesiopay_gateway_states();

		// Prepare API payload according to official ConvesioPay documentation
		// Use the exact field names from the Update Integration Payment Methods API
		$api_payload = array(
			'card' => $gateway_states['card'],
			'applePay' => $gateway_states['apple_pay'],
			'googlePay' => $gateway_states['google_pay'],
			'btcPay' => $gateway_states['btc_pay']
		);

		// Use the correct Update Integration Payment Methods endpoint
		// According to ConvesioPay API docs: PATCH /v1/payment-methods (no integration parameter needed)
		$api_url = peachpay_is_test_mode() ? 'https://api-qa.convesiopay.com' : 'https://api.convesiopay.com';
		$endpoint = $api_url . '/v1/payment-methods';

		// Make API request using PATCH method as specified in documentation
		$response = wp_remote_request($endpoint, array(
			'method' => 'PATCH',
			'timeout' => 30,
			'headers' => array(
				'Authorization' => $config['secret_key'],
				'Content-Type' => 'application/json',
			),
			'body' => wp_json_encode($api_payload)
		));

		// Handle response
		if (is_wp_error($response)) {
			return;
		}

		$response_code = wp_remote_retrieve_response_code($response);

		if ($response_code === 200) {
			// Store last sync time
			update_option('peachpay_convesiopay_last_payment_method_sync', current_time('mysql'));
		}
	}

	/**
	 * Get current state of ConvesioPay gateways
	 */
	private function get_convesiopay_gateway_states() {
		$gateway_states = array(
			'card' => false,
			'apple_pay' => false,
			'google_pay' => false,
			'btc_pay' => false
		);

		// Get all gateways
		$gateways = WC()->payment_gateways->payment_gateways();

		// Check individual gateways with fallback to 'no' if not set
		if (isset($gateways['peachpay_convesiopay_card'])) {
			$enabled_option = $gateways['peachpay_convesiopay_card']->get_option('enabled', 'no');
			$gateway_states['card'] = $enabled_option === 'yes';
		}

		if (isset($gateways['peachpay_convesiopay_applepay'])) {
			$enabled_option = $gateways['peachpay_convesiopay_applepay']->get_option('enabled', 'no');
			$gateway_states['apple_pay'] = $enabled_option === 'yes';
		}

		if (isset($gateways['peachpay_convesiopay_googlepay'])) {
			$enabled_option = $gateways['peachpay_convesiopay_googlepay']->get_option('enabled', 'no');
			$gateway_states['google_pay'] = $enabled_option === 'yes';
		}

		if (isset($gateways['peachpay_convesiopay_btcpay'])) {
			$enabled_option = $gateways['peachpay_convesiopay_btcpay']->get_option('enabled', 'no');
			$gateway_states['btc_pay'] = $enabled_option === 'yes';
		}

		return $gateway_states;
	}

	/**
	 * Handle gateway setting updates via option hooks
	 */
	public function on_gateway_setting_updated($old_value, $new_value) {
		// Check if the 'enabled' setting changed
		$old_enabled = $old_value['enabled'] ?? 'no';
		$new_enabled = $new_value['enabled'] ?? 'no';

		if ($old_enabled !== $new_enabled) {
			$this->sync_payment_methods_with_convesiopay();
		}
	}

	/**
	 * Handle manual sync for testing purposes
	 */
	public function handle_manual_sync() {
		if (!current_user_can('manage_woocommerce')) {
			wp_send_json_error('Insufficient permissions');
			return;
		}

		$this->sync_payment_methods_with_convesiopay();
		wp_send_json_success('Sync completed');
	}

	/**
	 * Maybe sync payment methods when viewing ConvesioPay admin pages
	 */
	public function maybe_sync_on_admin_load() {
		// Only run on admin and if user has proper permissions
		if (!is_admin() || !current_user_can('manage_woocommerce')) {
			return;
		}

		// Check if we're on a ConvesioPay-related page
		$current_page = $_GET['page'] ?? '';
		$current_tab = $_GET['tab'] ?? '';
		$current_section = $_GET['section'] ?? '';

		$is_convesiopay_page = false;

		// Check for PeachPay ConvesioPay page
		if ($current_page === 'peachpay' && $current_tab === 'payment' && strpos($_SERVER['REQUEST_URI'] ?? '', '#convesiopay') !== false) {
			$is_convesiopay_page = true;
		}

		// Check for WooCommerce payment settings page with ConvesioPay gateways
		if ($current_page === 'wc-settings' && $current_tab === 'checkout' &&
			(strpos($current_section, 'peachpay_convesiopay') !== false || $current_section === '')) {
			$is_convesiopay_page = true;
		}

		if ($is_convesiopay_page) {
			// Check if we've synced recently to avoid excessive API calls
			$last_sync = get_option('peachpay_convesiopay_last_payment_method_sync', '');
			$should_sync = true;

			if ($last_sync) {
				$last_sync_time = strtotime($last_sync);
				$current_time = current_time('timestamp');
				// Don't sync if last sync was less than 5 minutes ago
				if (($current_time - $last_sync_time) < 300) {
					$should_sync = false;
				}
			}

			if ($should_sync) {
				$this->sync_payment_methods_with_convesiopay();
			}
		}
	}
}

PeachPay_Admin_ConvesioPay_Integration::instance(); 