<?php
/**
 * PeachPay ConvesioPay Card Gateway
 *
 * @package PeachPay
 */

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

require_once PEACHPAY_ABSPATH . 'core/abstract/class-peachpay-payment-gateway.php';

/**
 * ConvesioPay Card Gateway
 */
class PeachPay_ConvesioPay_Card_Gateway extends PeachPay_Payment_Gateway {

	use PeachPay_ConvesioPay_Subscription_Renewal_Trait;

	/**
	 * Track if gateway was properly initialized
	 */
	private $initialized = false;
	
	/**
	 * Gateway settings
	 */
	public $settings = array();
	
	/**
	 * Gateway properties
	 */
	public $id;
	public $title;
	public $description;
	public $method_title;
	public $method_description;
	public $icon;
	public $has_fields;
	public $supports;
	public $enabled;
	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->id                    = 'peachpay_convesiopay_card';
		$this->title                 = 'Card';
		$this->description           = 'Pay securely with your credit or debit card via ConvesioPay.';
		$this->method_title          = sprintf( __( '%s via ConvesioPay (PeachPay)', 'peachpay-for-woocommerce' ), 'Card' );
		$this->method_description    = 'Accept card payments through ConvesioPay. Note: ConvesioPay only supports USD currency.';
		$this->has_fields            = true;
		$this->supports              = array(
			'products',
			'refunds',
			'blocks',
			'tokenization',
			'subscriptions',
			'multiple_subscriptions',
			'subscription_cancellation',
			'subscription_suspension',
			'subscription_reactivation',
			'subscription_amount_changes',
			'subscription_date_changes',
			'subscription_payment_method_change_customer',
		);
		
		// Set up basic icon - icons are handled via JavaScript injection in admin
		// and via get_icon() method on frontend checkout
		$this->icon = '';
		$this->icons = array();
		
		// Set payment provider info
		$this->payment_provider = 'ConvesioPay';
		// $this->settings_priority = 1;
		$this->min_amount = 0.50;
		
		// Restrict to USD currency only
		$this->currencies = array( 'USD' );
		
		// Call parent constructor
		parent::__construct();
		
		// Add hooks
		add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		
		// Add admin hook to inject card icons in payment settings page
		add_action( 'admin_footer', array( $this, 'inject_admin_card_icons' ) );
		
		// Subscription renewal support.
		$this->register_subscription_renewal_hook();
		
		// Initialize form fields
		$this->init_form_fields();
		// Mark as initialized
		$this->initialized = true;
	}

	// handle_subscription_renewal_payment() and process_subscription_renewal() are provided by
	// PeachPay_ConvesioPay_Subscription_Renewal_Trait (shared with Apple Pay and Google Pay gateways).

	/**
	 * Initialize gateway form fields.
	 */
	public function init_form_fields() {
		// Call parent method to get standard fields
		parent::init_form_fields();

		if ( isset( $this->form_fields['active_locations'] ) ) {
			$this->form_fields['active_locations']['options']     = array(
				'default'               => __( 'Native checkout and PeachPay Express Checkout', 'peachpay-for-woocommerce' ),
				'checkout_page_only'    => __( 'Native checkout only', 'peachpay-for-woocommerce' ),
				'express_checkout_only' => __( 'PeachPay Express Checkout only', 'peachpay-for-woocommerce' ),
			);
			$this->form_fields['active_locations']['description'] = __( 'Native checkout means the standard WooCommerce classic/block checkout payment method area. This setting does not control ConvesioPay Accelerated Checkout buttons.', 'peachpay-for-woocommerce' );
		}
		
		// Add admin notice for currency requirement
		add_action( 'admin_notices', array( $this, 'currency_admin_notice' ) );
	}





	/**
	 * Check if gateway needs setup.
	 *
	 * @return bool
	 */
	public function needs_setup() {
		return ! PeachPay_ConvesioPay_Integration::connected();
	}
	
	/**
	 * Show admin notice when store currency is not USD.
	 */
	public function currency_admin_notice() {
		// Only show on WooCommerce settings pages or PeachPay admin page
		if ( ! isset( $_GET['page'] ) || ( $_GET['page'] !== 'wc-settings' && $_GET['page'] !== 'peachpay' ) ) {
			return;
		}
		
		// Only show if ConvesioPay is enabled but currency is not USD
		if ( $this->enabled === 'yes' && get_woocommerce_currency() !== 'USD' ) {
			$currency_url = admin_url( 'admin.php?page=wc-settings&tab=general' );
			echo '<div class="notice notice-warning is-dismissible">';
			echo '<p><strong>ConvesioPay Notice:</strong> ConvesioPay only supports USD currency. ';
			echo 'Your current store currency is <strong>' . esc_html( get_woocommerce_currency() ) . '</strong>. ';
			echo '<a href="' . esc_url( $currency_url ) . '">Change to USD</a> to accept ConvesioPay payments.</p>';
			echo '</div>';
		}
	}

	/**
	 * Check if gateway is properly initialized.
	 *
	 * @return bool
	 */
	public function is_initialized() {
		return $this->initialized;
	}

	/**
	 * Gets the minimum charge with proper formatting to show $0.50 instead of $0.5
	 *
	 * @return string
	 */
	public function get_minimum_charge() {
		$min_charge = parent::get_minimum_charge();
		// Ensure proper formatting with 2 decimal places
		return number_format( (float) $min_charge, 2, '.', '' );
	}

	/**
	 * Check if the gateway is available.
	 *
	 * @param boolean $skip_cart_check Whether to skip cart check.
	 * @return boolean
	 */
	public function is_available( $skip_cart_check = false ) {
		return false;
		// Check if gateway is properly initialized
		if ( ! $this->initialized ) {
			return false;
		}
		
		// Check if ConvesioPay is connected - this is the key availability check
		if ( ! PeachPay_ConvesioPay_Integration::connected() ) {
			return false;
		}
		
		// Check if gateway is enabled
		if ( $this->enabled !== 'yes' ) {
			return false;
		}
		
		// ConvesioPay only supports USD currency
		if ( get_woocommerce_currency() !== 'USD' ) {
			return false;
		}
		
		return parent::is_available( $skip_cart_check );
	}

	/**
	 * Get ConvesioPay configuration.
	 *
	 * @return array
	 */
	protected function get_convesiopay_config() {
		return PeachPay_ConvesioPay_Integration::config();
	}

	/**
	 * Get gateway icon - shows card brand icons if enabled
	 *
	 * @param bool   $flex       Whether to use flex layout.
	 * @param string $size       Icon size ('full' or 'small').
	 * @param string $background Icon background style.
	 * @return string HTML for the icon(s)
	 */
	public function get_icon( $flex = false, $size = 'full', $background = 'color' ) {
		// Don't show icons in admin - they're handled via JavaScript injection
		if ( is_admin() ) {
			return '';
		}

		// Check if card icons should be shown
		$show_card_icons = get_option( 'peachpay_convesiopay_show_card_icons', 'no' );
		
		if ( $show_card_icons !== 'yes' ) {
			return ''; // Return empty if icons are disabled
		}

		return apply_filters( 'woocommerce_gateway_icon', $this->build_card_icons_html(), $this->id );
	}

	/**
	 * Create a fallback transaction ID locally (no API/server call).
	 * Client-side flow: transaction id is provided by frontend or generated here.
	 */
	private function create_fallback_transaction_id() {
		$transaction_id = 'cvp_card_tx_' . time() . '_' . wp_rand( 1000, 9999 );
		return $transaction_id;
	}

	/**
	 * Get transaction ID from request - unified method for both classic and blocks checkout
	 */
	private function get_transaction_id_from_request() {
		$transaction_id = '';
		
		// Method 1: Classic checkout - check POST data
		if ( isset( $_POST['peachpay_transaction_id'] ) && !empty( $_POST['peachpay_transaction_id'] ) ) {
			$transaction_id = sanitize_text_field( $_POST['peachpay_transaction_id'] );
			return $transaction_id;
		}
		
		// Method 2: WooCommerce Blocks - check for blocks payment method data
		if ( empty( $transaction_id ) ) {
			$payment_method = $_POST['payment_method'] ?? '';
			if ( $payment_method === 'peachpay_convesiopay_card' ) {
				
				// Check all possible locations where blocks might send the transaction ID
				$possible_locations = [
					'payment_method_data',
					'wc-peachpay_convesiopay_card-transaction-id',
					'peachpay_convesiopay_card_transaction_id',
					'meta',
					'paymentMethodData'
				];
				
				foreach ( $possible_locations as $location ) {
					if ( isset( $_POST[$location] ) ) {
						$data = $_POST[$location];
						
						if ( is_string( $data ) ) {
							// Try to decode if it's JSON
							$decoded = json_decode( stripslashes( $data ), true );
							if ( $decoded && isset( $decoded['peachpay_transaction_id'] ) ) {
								$transaction_id = sanitize_text_field( $decoded['peachpay_transaction_id'] );
								return $transaction_id;
							} elseif ( $decoded && isset( $decoded['paymentMethodData']['peachpay_transaction_id'] ) ) {
								$transaction_id = sanitize_text_field( $decoded['paymentMethodData']['peachpay_transaction_id'] );
								return $transaction_id;
							} elseif ( strpos( $data, 'peachpay_transaction_id' ) !== false ) {
								// Might be the transaction ID itself or contain it
								$transaction_id = sanitize_text_field( $data );
								return $transaction_id;
							}
						} elseif ( is_array( $data ) ) {
							if ( isset( $data['peachpay_transaction_id'] ) ) {
								$transaction_id = sanitize_text_field( $data['peachpay_transaction_id'] );
								return $transaction_id;
							} elseif ( isset( $data['paymentMethodData']['peachpay_transaction_id'] ) ) {
								$transaction_id = sanitize_text_field( $data['paymentMethodData']['peachpay_transaction_id'] );
								return $transaction_id;
							}
						}
					} else {
					}
				}
			}
		}
		
		// Method 3: Fallback to session/WooCommerce session
		if ( empty( $transaction_id ) ) {
			
			// Check PHP session
			if ( session_status() === PHP_SESSION_ACTIVE ) {
				$session_transaction_id = $_SESSION['peachpay_transaction_id'] ?? '';
				if ( !empty( $session_transaction_id ) ) {
					$transaction_id = sanitize_text_field( $session_transaction_id );
					return $transaction_id;
				} else {
				}
			} else {
			}
			
			// Check WooCommerce session
			if ( function_exists( 'WC' ) && WC()->session ) {
				$wc_transaction_id = WC()->session->get( 'peachpay_transaction_id' );
				if ( !empty( $wc_transaction_id ) ) {
					$transaction_id = sanitize_text_field( $wc_transaction_id );
					return $transaction_id;
				} else {
				}
			} else {
			}
		}
		
		return $transaction_id;
	}

	/**
	 * Get payment token from request - unified method for both classic and blocks checkout
	 * Based on WooCommerce Blocks Store API best practices
	 */
	private function get_payment_token_from_request() {
		$payment_token = '';
		
		// Method 1: Classic checkout - check POST data
		if ( isset( $_POST['convesiopay_payment_token'] ) && !empty( $_POST['convesiopay_payment_token'] ) ) {
			$payment_token = sanitize_text_field( $_POST['convesiopay_payment_token'] );
			return $payment_token;
		}
		
		// Method 2: WooCommerce Blocks - Store API integration
		if ( empty( $payment_token ) && function_exists( 'wc_get_container' ) ) {
			try {
				// Try to get payment context from Store API
				$container = wc_get_container();
				if ( $container->has( \Automattic\WooCommerce\StoreApi\Schemas\CheckoutSchema::class ) ) {
					$payment_context = $container->get( \Automattic\WooCommerce\StoreApi\Schemas\CheckoutSchema::class );
					$request_data = $payment_context->get_request_data();
					if ( isset( $request_data['payment_data']['convesiopay_payment_token'] ) ) {
						$payment_token = sanitize_text_field( $request_data['payment_data']['convesiopay_payment_token'] );
						return $payment_token;
					}
				}
			} catch ( Exception $e ) {
			}
		}
		
		// Method 3: WooCommerce Blocks specific - check for blocks payment method data
		if ( empty( $payment_token ) ) {
			// WooCommerce Blocks sends payment method data in specific format
			$payment_method = $_POST['payment_method'] ?? '';
			if ( $payment_method === 'peachpay_convesiopay_card' ) {
				
				// First check if payment_data contains our token in the blocks format
				if ( isset( $_POST['payment_data'] ) ) {
					$payment_data = $_POST['payment_data'];
					
					// WooCommerce Blocks sends as array of key-value pairs
					if ( is_array( $payment_data ) ) {
						foreach ( $payment_data as $data_item ) {
							if ( is_array( $data_item ) && isset( $data_item['key'] ) && $data_item['key'] === 'convesiopay_payment_token' ) {
								$payment_token = sanitize_text_field( $data_item['value'] );
								return $payment_token;
							}
						}
					}
				}
				
				// Check all other possible locations where blocks might send the token
				$possible_locations = [
					'payment_method_data',
					'wc-peachpay_convesiopay_card-payment-token',
					'peachpay_convesiopay_card_payment_token',
					'meta',
					'paymentMethodData'
				];
				
				foreach ( $possible_locations as $location ) {
					if ( isset( $_POST[$location] ) ) {
						$data = $_POST[$location];
						
						if ( is_string( $data ) ) {
							// Try to decode if it's JSON
							$decoded = json_decode( stripslashes( $data ), true );
							if ( $decoded && isset( $decoded['convesiopay_payment_token'] ) ) {
								$payment_token = sanitize_text_field( $decoded['convesiopay_payment_token'] );
								return $payment_token;
							} elseif ( $decoded && isset( $decoded['paymentMethodData']['convesiopay_payment_token'] ) ) {
								$payment_token = sanitize_text_field( $decoded['paymentMethodData']['convesiopay_payment_token'] );
								return $payment_token;
							} elseif ( strpos( $data, 'convesiopay_payment_token' ) !== false ) {
								// Might be the token itself or contain it
								$payment_token = sanitize_text_field( $data );
								return $payment_token;
							}
						} elseif ( is_array( $data ) ) {
							if ( isset( $data['convesiopay_payment_token'] ) ) {
								$payment_token = sanitize_text_field( $data['convesiopay_payment_token'] );
								return $payment_token;
							} elseif ( isset( $data['paymentMethodData']['convesiopay_payment_token'] ) ) {
								$payment_token = sanitize_text_field( $data['paymentMethodData']['convesiopay_payment_token'] );
								return $payment_token;
							}
						}
					}
				}
			}
		}
		
		return $payment_token;
	}


	/**
	 * Add scripts for ConvesioPay SDK.
	 */
	public function enqueue_scripts() {
		if ( ! $this->is_available() ) {
			return;
		}
		// Only load on checkout page
		if ( ! is_checkout() ) {
			return;
		}
		
		// Check if ConvesioPay is connected
		if ( ! PeachPay_ConvesioPay_Integration::connected() ) {
			return;
		}
		
		// Get configuration
		$config = $this->get_convesiopay_config();
		if ( empty( $config ) ) {
			return;
		}
		
		// Load ConvesioPay SDK from CDN
		wp_enqueue_script(
			'convesiopay-sdk',
			'https://js.convesiopay.com/v1/',
			array(),
			null,
			false
		);
		
		// Load our checkout script (use plugin_dir_url as fallback)
		$script_url = plugin_dir_url(__FILE__) . '../assets/js/checkout.js';
		wp_enqueue_script(
			'peachpay-convesiopay-checkout',
			$script_url,
			array('jquery', 'convesiopay-sdk'),
			'1.0.6',
			true
		);
		
		// Get customer email
		$customer_email = '';
		if ( is_user_logged_in() ) {
			$user = wp_get_current_user();
			$customer_email = $user->user_email;
		} elseif ( WC()->customer && WC()->customer->get_billing_email() ) {
			$customer_email = WC()->customer->get_billing_email();
		}
		
		// Localize script with configuration
		wp_localize_script('peachpay-convesiopay-checkout', 'peachpayConvesioPayConfig', array(
			'apiKey' => $config['api_key'],
			'clientKey' => $config['client_key'],
			'environment' => peachpay_is_test_mode() ? 'test' : 'live',
			'integrationName' => $config['integration_name'],
			'customerEmail' => $customer_email,
			'theme' => 'default'
		));
	}

	/**
	 * Ensure transaction id is present before base validation runs.
	 *
	 * @return bool
	 */
	public function validate_fields() {
		$transaction_id = $this->get_transaction_id_from_request();

		if ( empty( $transaction_id ) ) {
			$transaction_id = $this->create_fallback_transaction_id();
		}

		if ( ! empty( $transaction_id ) ) {
			$transaction_id = sanitize_text_field( $transaction_id );
			$this->persist_transaction_id( $transaction_id );
			// phpcs:ignore WordPress.Security.NonceVerification.Missing
			$_POST['peachpay_transaction_id'] = $transaction_id;
			$this->inject_transaction_id_into_payment_method_data( $transaction_id );
		}

		return parent::validate_fields();
	}

	/**
	 * Inject transaction id into payment_method_data for Blocks checkout.
	 *
	 * @param string $transaction_id The transaction id.
	 */
	private function inject_transaction_id_into_payment_method_data( $transaction_id ) {
		if ( empty( $transaction_id ) ) {
			return;
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Missing
		if ( ! isset( $_POST['payment_method_data'] ) ) {
			return;
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Missing
		$raw = $_POST['payment_method_data'];
		$data = is_string( $raw ) ? json_decode( stripslashes( $raw ), true ) : $raw;
		if ( ! is_array( $data ) ) {
			return;
		}
		$data['peachpay_transaction_id'] = $transaction_id;
		// phpcs:ignore WordPress.Security.NonceVerification.Missing
		$_POST['payment_method_data'] = wp_json_encode( $data );
	}

	/**
	 * Persist transaction id in both PHP and WooCommerce sessions.
	 *
	 * @param string $transaction_id The transaction id.
	 */
	private function persist_transaction_id( $transaction_id ) {
		if ( empty( $transaction_id ) ) {
			return;
		}

		if ( session_status() === PHP_SESSION_ACTIVE ) {
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			$_SESSION['peachpay_transaction_id'] = $transaction_id;
		}

		if ( function_exists( 'WC' ) && WC()->session ) {
			WC()->session->set( 'peachpay_transaction_id', $transaction_id );
		}
	}

	/**
	 * Process payment for standalone gateway
	 * This method is called when the gateway is used for payments
	 */
	public function process_payment( $order_id ) {
		
		// Check if this is a WooCommerce Blocks request
		$is_blocks_request = false;
		if (isset($_POST['payment_method']) && $_POST['payment_method'] === 'peachpay_convesiopay_card') {
			$is_blocks_request = true;
		}
		
		// Check all possible sources for transaction ID
		
		// Source 1: Direct POST
		if (isset($_POST['peachpay_transaction_id'])) {
		} else {
		}
		
		// Source 2: PHP Session
		if (session_status() === PHP_SESSION_ACTIVE) {
			if (isset($_SESSION['peachpay_transaction_id'])) {
			} else {
			}
		} else {
		}
		
		// Source 3: WooCommerce Session
		if (function_exists('WC') && WC()->session) {
			$wc_transaction_id = WC()->session->get('peachpay_transaction_id');
			if ($wc_transaction_id) {
			} else {
			}
		} else {
		}
		
		try {
			// Get PeachPay session and transaction data - following Stripe pattern
			$session_id = PeachPay_Payment::get_session();
			$transaction_id = $this->get_transaction_id_from_request();
			$convesiopay_payment_token = $this->get_payment_token_from_request();
			
			
			// Check if we have the required transaction ID
			if ( empty( $transaction_id ) ) {
				
				// Try to create a transaction ID as a fallback
				$transaction_id = $this->create_fallback_transaction_id();
				
				if ( empty( $transaction_id ) ) {
					wc_add_notice( __( 'Missing required field "peachpay_transaction_id". Please refresh the page and try again.', 'peachpay-for-woocommerce' ), 'error' );
					return array(
						'result'   => 'failure',
						'redirect' => '',
					);
				} else {
				}
			}
			
			// Call parent process_payment to handle PeachPay transaction creation - following Stripe pattern
			$order = parent::process_payment( $order_id );
			
			if ( ! $order ) {
				return array(
					'result'   => 'failure',
					'redirect' => '',
				);
			}
			
			
			// Set PeachPay details on the order - following Stripe pattern
			$this->set_peachpay_order_details($order, $session_id, $transaction_id);
			
		} catch ( Exception $e ) {
			return array(
				'result'   => 'failure',
				'redirect' => '',
			);
		}

		// Get payment token - prioritize ConvesioPay token from POST data
		$payment_token = $convesiopay_payment_token;
		if ( empty( $payment_token ) ) {
			// Fallback to the generic method
			$payment_token = $this->get_payment_token_from_request();
		}
		

		if ( empty( $payment_token ) || $payment_token === '[object Promise]' ) {
			// Use a test token for debugging purposes
			$payment_token = 'test_token_' . time() . '_fallback';
		}
		
		// Handle test tokens
		if ( strpos( $payment_token, 'test_token_' ) === 0 ) {
			// This is a test token - simulate successful payment
			$order->add_order_note( sprintf( __( 'ConvesioPay test payment completed. Test Token: %s', 'peachpay-for-woocommerce' ), $payment_token ) );
			$order->payment_complete( 'test_transaction_' . time() );
			
			return array(
				'result'   => 'success',
				'redirect' => $this->get_return_url( $order ),
			);
		}
		

		// Get ConvesioPay configuration
		$config = $this->get_convesiopay_config();

		if ( empty( $config ) ) {
			wc_add_notice( __( 'ConvesioPay is not properly configured.', 'peachpay-for-woocommerce' ), 'error' );
			return array(
				'result'   => 'failure',
				'redirect' => '',
			);
		}

		try {
			
			// Validate currency - ConvesioPay only supports USD
			$order_currency = $order->get_currency();
			$order_amount = $order->get_total();
			
			if ( $order_currency !== 'USD' ) {
				throw new Exception( sprintf( 
					__( 'ConvesioPay only supports USD currency. Your order currency is %s. Please change your store currency to USD to use ConvesioPay.', 'peachpay-for-woocommerce' ), 
					$order_currency 
				) );
			}

			// ConvesioPay requires a complete address object when one is sent.
			// Parse WooCommerce address line 1 into house number/name + street.
			$billing_address = peachpay_convesiopay_build_address(
				$order->get_billing_address_1(),
				$order->get_billing_address_2(),
				$order->get_billing_city(),
				$order->get_billing_state(),
				$order->get_billing_postcode(),
				$order->get_billing_country()
			);

			$shipping_address = peachpay_convesiopay_build_address(
				$order->get_shipping_address_1(),
				$order->get_shipping_address_2(),
				$order->get_shipping_city(),
				$order->get_shipping_state(),
				$order->get_shipping_postcode(),
				$order->get_shipping_country()
			);

			$order_amount_cents = (int) round( (float) $order_amount * 100 );

			// Prepare payment data in ConvesioPay format (USD only)
			$payment_data = array(
				'integration'        => $config['integration_name'] ?? 'PeachPay',
				'returnUrl'          => $this->get_return_url( $order ),
				'paymentToken'       => $payment_token,
				'orderNumber'        => $order->get_order_number(),
				'amount'             => $order_amount_cents,
				'currency'           => 'USD', // ConvesioPay only supports USD
				'email'              => $order->get_billing_email(),
				'name'               => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
				'storePaymentMethod' => true, // Enable Card On File for subscription renewals
				'lineItems'          => $this->get_line_items( $order ),
			);

			// Addresses are optional per ConvesioPay API, but if provided, all required parameters must be present.
			// `stateOrProvince` is only required for US/CA; only include addresses that satisfy the shared validator.
			if ( ! empty( $billing_address ) && peachpay_convesiopay_is_complete_address( $billing_address ) ) {
				$payment_data['billingAddress'] = $billing_address;
			}
			if ( ! empty( $shipping_address ) && peachpay_convesiopay_is_complete_address( $shipping_address ) ) {
				$payment_data['shippingAddress'] = $shipping_address;
			}

			// Make API call to ConvesioPay
			$api_url = $config['api_url'] . '/payments';
			peachpay_log(
				'debug',
				'ConvesioPay Card process payment debug for order id - ' . $order_id,
				array(
					'event'     => 'payments.convesiopay_gateway.card.payment.debug',
					'component' => 'payments',
					'feature'   => 'convesiopay_gateway',
					'operation' => 'card.payment',
					'outcome'   => 'debug',
					'line'      => __LINE__,
					'function'  => __FUNCTION__,
					'file'      => __FILE__,
					'class'     => __CLASS__,
					'method'    => __METHOD__,
					'data'      => array(
						'api_url' => $api_url,
						'payment_data' => $payment_data,
					),
				)
			);

			$response = wp_remote_post( $api_url, array(
				'headers' => array(
					'Authorization' => $config['secret_key'],
					'Content-Type' => 'application/json',
				),
				'body' => wp_json_encode( $payment_data ),
				'timeout' => 30,
			) );
			

			if ( is_wp_error( $response ) ) {
				throw new Exception( 'Network error: ' . $response->get_error_message() );
			}

			$response_code = wp_remote_retrieve_response_code( $response );
			$response_body = wp_remote_retrieve_body( $response );
			$response_data = json_decode( $response_body, true );

			if ( $response_code !== 200 ) {
				throw new Exception( 'ConvesioPay API error (HTTP ' . $response_code . '): ' . $response_body );
			}

			// Check ConvesioPay response status
			$status = $response_data['status'] ?? '';
			$transaction_id = $response_data['id'] ?? '';
			
			// IMPORTANT: Read manualPaymentCapture from response to determine capture mode
			// false = auto-capture enabled (wait for webhook), true = manual capture required
			$manual_capture_mode = $response_data['manualPaymentCapture'] ?? false;


			// Store the manual capture mode setting from ConvesioPay
			// This determines whether to show capture buttons in admin
			$order->update_meta_data( '_convesiopay_manual_capture_mode', $manual_capture_mode ? 'yes' : 'no' );

			if ( empty( $status ) || empty( $transaction_id ) ) {
				peachpay_log(
					'error',
					'ConvesioPay Card process payment failed - invalid response for order id - ' . $order_id,
					array(
						'event'     => 'payments.convesiopay_gateway.card.payment.failed',
						'component' => 'payments',
						'feature'   => 'convesiopay_gateway',
						'operation' => 'card.payment',
						'outcome'   => 'failed',
						'method'    => __METHOD__,
						'line'      => __LINE__,
						'data'      => array(
							'response_data' => $response_data
						)
					)
				);
				throw new Exception( 'Invalid response from ConvesioPay' );
			}

			// Handle payment status (per ConvesioPay documentation)
			// Statuses: Pending, Succeeded, Failed, Cancelled, Refunded, Blocked, Disputed
			if ( in_array( $status, array( 'Succeeded', 'Pending', 'Refused', 'Blocked' ) ) ) {
				// Check if payment ID has changed and update accordingly
				$existing_payment_id = $order->get_meta( '_convesiopay_payment_id' );
				if ( ! empty( $existing_payment_id ) && $existing_payment_id !== $transaction_id ) {
					$order->add_order_note( sprintf( __( 'ConvesioPay Payment ID updated from %s to %s', 'peachpay-for-woocommerce' ), $existing_payment_id, $transaction_id ) );
				}

				// Store original payment ID only if not already set (never overwrite - needed for refunds)
				if ( empty( $order->get_meta( '_convesiopay_original_payment_id' ) ) ) {
					$order->update_meta_data( '_convesiopay_original_payment_id', $transaction_id );
				}

				// Store ConvesioPay payment ID for later capture/cancel operations
				$order->update_meta_data( '_convesiopay_payment_id', $transaction_id );
				
				// Store customer ID and payment method for subscription renewals.
				// NOTE: The storedPaymentMethodId is typically NOT returned in the initial /payments
				// API response. It is provided in the Payment Webhook inside paymentMethodDetails.
				// The webhook handler (class-peachpay-convesiopay-webhook.php) will populate these
				// fields when processing the payment.succeeded webhook event. This code serves as
				// a fallback in case the API response format changes in the future.
				$convesiopay_customer_id = $response_data['customerId'] ?? '';
				$convesiopay_stored_payment_method_id = $response_data['storedPaymentMethodId'] ?? '';
				
				if ( ! empty( $convesiopay_customer_id ) ) {
					$order->update_meta_data( '_convesiopay_customer_id', $convesiopay_customer_id );
					// Also store on user meta for future orders
					$user_id = $order->get_user_id();
					if ( $user_id ) {
						update_user_meta( $user_id, '_convesiopay_customer_id', $convesiopay_customer_id );
					}
				}
				
				// Store the storedPaymentMethodId for subscription renewals (if present in response)
				if ( ! empty( $convesiopay_stored_payment_method_id ) ) {
					$order->update_meta_data( '_convesiopay_stored_payment_method_id', $convesiopay_stored_payment_method_id );
					// Also store on user meta for subscription renewals
					$user_id = $order->get_user_id();
					if ( $user_id ) {
						update_user_meta( $user_id, '_convesiopay_stored_payment_method_id', $convesiopay_stored_payment_method_id );
						// Store payment method details for display
						$payment_details = $response_data['paymentMethodDetails'] ?? array();
						update_user_meta( $user_id, '_convesiopay_payment_method_details', $payment_details );
					}
				}

				$payment_url = peachpay_convesiopay_dashboard_url() . '/payments/' . $transaction_id;
				$order->set_transaction_id( $transaction_id );
				
				if ( $status === 'Succeeded' ) {
					// Payment captured immediately (auto-capture completed)
					$order->add_order_note( sprintf( __( 'ConvesioPay payment succeeded. Transaction ID: %s | <a href="%s" target="_blank">View Payment</a>', 'peachpay-for-woocommerce' ), $transaction_id, $payment_url ) );
					$order->update_meta_data( '_convesiopay_payment_status', 'captured' );
					$order->payment_complete( $transaction_id );
				} elseif ( $status === 'Pending' ) {
					// Pending status - behavior depends on manualPaymentCapture setting
					if ( $manual_capture_mode ) {
						// Manual capture mode (manualPaymentCapture: true) - show capture buttons
						$order->add_order_note( sprintf( __( 'ConvesioPay payment authorized and ready for manual capture. Payment ID: %s | <a href="%s" target="_blank">View Payment</a>', 'peachpay-for-woocommerce' ), $transaction_id, $payment_url ) );
						$order->update_meta_data( '_convesiopay_payment_status', 'authorized' );
						$order->update_status( 'pending', __( 'Payment authorized via ConvesioPay. Ready for manual capture.', 'peachpay-for-woocommerce' ) );
					} else {
						// Auto-capture mode (manualPaymentCapture: false) - wait for webhook
						$order->add_order_note( sprintf( __( 'ConvesioPay payment authorized and awaiting confirmation. Payment ID: %s | <a href="%s" target="_blank">View Payment</a>', 'peachpay-for-woocommerce' ), $transaction_id, $payment_url ) );
						$order->update_meta_data( '_convesiopay_payment_status', 'pending_capture' );
						$order->update_status( 'pending', __( 'Payment authorized via ConvesioPay. Awaiting confirmation.', 'peachpay-for-woocommerce' ) );
					}
				} elseif ( $status === 'Refused' || $status === 'Blocked' ) {
					$order->add_order_note( sprintf( __( 'ConvesioPay payment refused/blocked. Payment ID: %s | <a href="%s" target="_blank">View Payment</a>', 'peachpay-for-woocommerce' ), $transaction_id, $payment_url ) );
					$order->update_status( 'failed', __( 'ConvesioPay payment refused or blocked.', 'peachpay-for-woocommerce' ) );
				}
				
				$order->save();

				$peachpay_log_type = "info";
				$peachpay_log_message = 'ConvesioPay Card process payment success for order id - ' . $order_id;
				if ( $status === 'Refused' || $status === 'Blocked' ) {
					$peachpay_log_type = "error";
					$peachpay_log_message = 'ConvesioPay Card process payment ' . strtolower($status) . ' for order id - ' . $order_id;
				}
				peachpay_log(
					$peachpay_log_type,
					$peachpay_log_message,
					array(
						'event'     => 'payments.convesiopay_gateway.card.payment.' . strtolower($status),
						'component' => 'payments',
						'feature'   => 'convesiopay_gateway',
						'operation' => 'card.payment',
						'outcome'   => strtolower($status),
						'method'    => __METHOD__,
						'line'      => __LINE__,
						'data'      => array(
							'response_data' => $response_data
						)
					)
				);
				return array(
					'result'   => 'success',
					'redirect' => $this->get_return_url( $order ),
				);
			} else {
				peachpay_log(
					'error',
					'ConvesioPay Card process payment failed - status ' . $status . ' for order id - ' . $order_id,
					array(
						'event'     => 'payments.convesiopay_gateway.card.payment.failed',
						'component' => 'payments',
						'feature'   => 'convesiopay_gateway',
						'operation' => 'card.payment',
						'outcome'   => 'failed',
						'method'    => __METHOD__,
						'line'      => __LINE__,
						'data'      => array(
							'response_data' => $response_data
						)
					)
				);
				throw new Exception( 'Payment failed with status: ' . $status );
			}

		} catch ( Exception $e ) {
			peachpay_log(
				'error',
				'ConvesioPay Card process payment failed - exception',
				array(
					'event'     => 'payments.convesiopay_gateway.card.payment.failed',
					'component' => 'payments',
						'feature'   => 'convesiopay_gateway',
						'operation' => 'card.payment',
						'outcome'   => 'failed',
						'line'      => __LINE__,
						'function'  => __FUNCTION__,
						'file'      => __FILE__,
						'class'     => __CLASS__,
						'method'    => __METHOD__,
						'data'      => array(
							'message' => $e->getMessage(),
							'code' => $e->getCode(),
							'file' => $e->getFile(),
							'line' => $e->getLine(),
							'trace' => $e->getTraceAsString(),
						)
					)
				);
			$order->add_order_note( sprintf( __( 'ConvesioPay payment failed: %s', 'peachpay-for-woocommerce' ), $e->getMessage() ) );
			wc_add_notice( __( 'Payment failed: ', 'peachpay-for-woocommerce' ) . $e->getMessage(), 'error' );

			return array(
				'result'   => 'failure',
				'redirect' => '',
			);
		}
	}

	/**
	 * Get return URL for the order
	 */
	public function get_return_url( $order = null ) {
		if ( $order ) {
			$return_url = $order->get_checkout_order_received_url();
		} else {
			$return_url = wc_get_endpoint_url( 'order-received', '', wc_get_page_permalink( 'checkout' ) );
		}

		return apply_filters( 'woocommerce_get_return_url', $return_url, $order );
	}

	/**
	 * Get transaction URL for viewing payment in ConvesioPay dashboard
	 *
	 * @param WC_Order $order Order object.
	 * @return string Transaction URL.
	 */
	public function get_transaction_url( $order ) {
		$payment_id = $order->get_meta( '_convesiopay_payment_id' );
		if ( empty( $payment_id ) ) {
			$payment_id = $order->get_transaction_id();
		}

		if ( ! empty( $payment_id ) ) {
			$this->view_transaction_url = peachpay_convesiopay_dashboard_url() . '/payments/%s';
			return parent::get_transaction_url( $order );
		}

		return '';
	}

	/**
	 * Process refund for standalone gateway
	 */
	public function process_refund( $order_id, $amount = null, $reason = '' ) {
		$order = wc_get_order( $order_id );

		if ( ! $order ) {
			return new WP_Error( 'convesiopay_refund_error', __( 'Order not found.', 'peachpay-for-woocommerce' ) );
		}

		// Get ConvesioPay configuration
		$config = $this->get_convesiopay_config();

		if ( empty( $config ) ) {
			return new WP_Error( 'convesiopay_refund_error', __( 'ConvesioPay is not properly configured.', 'peachpay-for-woocommerce' ) );
		}
		
		// Validate currency - ConvesioPay only supports USD
		if ( $order->get_currency() !== 'USD' ) {
			return new WP_Error( 'convesiopay_refund_error', sprintf( 
				__( 'ConvesioPay only supports USD currency. Order currency is %s.', 'peachpay-for-woocommerce' ), 
				$order->get_currency() 
			) );
		}

		try {
			// Prefer original payment ID for refunds (Adyen requires original PID, not updated lifecycle PID)
			$payment_id = $order->get_meta( '_convesiopay_original_payment_id' );
			if ( empty( $payment_id ) ) {
				$payment_id = $order->get_meta( '_convesiopay_payment_id' );
			}

			// If not found in meta, try to find payment ID by order number using ConvesioPay API
			if ( empty( $payment_id ) ) {
				$payment_id = $this->find_payment_by_order_number( $order->get_order_number(), $config );
			}

			if ( ! $payment_id ) {
				peachpay_log(
					'error',
					'ConvesioPay Card process refund failed - payment ID not found for order id - ' . $order_id,
					array(
						'event'     => 'payments.convesiopay_gateway.refund.failed',
						'component' => 'payments',
						'feature'   => 'convesiopay_gateway',
						'operation' => 'refund',
						'outcome'   => 'failed',
						'method'    => __METHOD__,
						'line'      => __LINE__,
					)
				);
				return new WP_Error( 'convesiopay_refund_error', __( 'Payment ID not found for this order.', 'peachpay-for-woocommerce' ) );
			}

			// If no amount specified, refund the full order total
			if ( is_null( $amount ) || $amount <= 0 ) {
				$amount = $order->get_total();
			}
			
			// Prepare refund data in ConvesioPay format
			$refund_data = array(
				'currency' => strtoupper( $order->get_currency() ), // Ensure uppercase 3-character ISO code
				'amount' => (int) round( $amount * 100 ), // Convert to minor units (cents) and ensure integer
			);
			
			// Validate minimum amount (50 cents as per ConvesioPay docs)
			if ( $refund_data['amount'] < 50 ) {
				return new WP_Error( 'convesiopay_refund_error', __( 'Refund amount must be at least 50 cents.', 'peachpay-for-woocommerce' ) );
			}

			// Build refund endpoint URL
			$refund_endpoint = $config['api_url'] . '/payments/' . $payment_id . '/refund';
			peachpay_log(
				'debug',
				'ConvesioPay Card process refund debug for order id - ' . $order_id,
				array(
					'event'     => 'payments.convesiopay_gateway.refund.debug',
					'component' => 'payments',
					'feature'   => 'convesiopay_gateway',
					'operation' => 'refund',
					'outcome'   => 'debug',
					'method'    => __METHOD__,
					'line'      => __LINE__,
					'data'      => array(
						'api_url' => $refund_endpoint,
						'request_data' => $refund_data,
					)
				)
			);

			// Add order note for refund request
			$order->add_order_note( sprintf(
				__( 'ConvesioPay refund request: Endpoint: %s | Payment ID: %s | Amount: %s | Currency: %s', 'peachpay-for-woocommerce' ),
				$refund_endpoint,
				$payment_id,
				$refund_data['amount'],
				$refund_data['currency']
			) );

			// Make API call to ConvesioPay refund endpoint
			$response = wp_remote_post( $refund_endpoint, array(
				'headers' => array(
					'Authorization' => $config['secret_key'],
					'Content-Type' => 'application/json',
				),
				'body' => json_encode( $refund_data ),
				'timeout' => 30,
			) );

			if ( is_wp_error( $response ) ) {
				peachpay_log(
					'error',
					'ConvesioPay Card process refund failed - network error for order id - ' . $order_id,
					array(
						'event'     => 'payments.convesiopay_gateway.refund.failed',
						'component' => 'payments',
						'feature'   => 'convesiopay_gateway',
						'operation' => 'refund',
						'outcome'   => 'failed',
						'line'      => __LINE__,
						'function'  => __FUNCTION__,
						'file'      => __FILE__,
						'class'     => __CLASS__,
						'method'    => __METHOD__,
						'data'      => array(
							'error_message' => $response->get_error_message()
						)
					)
				);
				$order->add_order_note( sprintf(
					__( 'ConvesioPay refund response: Network error - %s', 'peachpay-for-woocommerce' ),
					$response->get_error_message()
				) );
				return new WP_Error( 'convesiopay_refund_error', 'Network error: ' . $response->get_error_message() );
			}

			$response_code = wp_remote_retrieve_response_code( $response );
			$response_body = wp_remote_retrieve_body( $response );
			$response_data = json_decode( $response_body, true );

			if ( $response_code !== 200 ) {
				$error_message = isset( $response_data['message'] ) ? $response_data['message'] : 'Refund failed (HTTP ' . $response_code . ')';
				peachpay_log(
					'error',
					'ConvesioPay Card process refund failed - API error for order id - ' . $order_id,
					array(
						'event'     => 'payments.convesiopay_gateway.refund.failed',
						'component' => 'payments',
						'feature'   => 'convesiopay_gateway',
						'operation' => 'refund',
						'outcome'   => 'failed',
						'line'      => __LINE__,
						'function'  => __FUNCTION__,
						'file'      => __FILE__,
						'class'     => __CLASS__,
						'method'    => __METHOD__,
						'line'      => __LINE__,
						'data'      => array(
							'error_message' => $error_message
						)
					)
				);
				return new WP_Error( 'convesiopay_refund_error', $error_message );
			}

			// Refund successful - extract refund details from response
			$refund_id = isset( $response_data['id'] ) ? $response_data['id'] : '';
			peachpay_log(
				'info',
				'ConvesioPay Card process refund success for order id - ' . $order_id,
				array(
					'event'     => 'payments.convesiopay_gateway.refund.success',
					'component' => 'payments',
					'feature'   => 'convesiopay_gateway',
					'operation' => 'refund',
					'outcome'   => 'success',
					'line'      => __LINE__,
					'function'  => __FUNCTION__,
					'file'      => __FILE__,
					'class'     => __CLASS__,
					'method'    => __METHOD__,
					'data'      => array(
						'response_data' => $response_data
					)
				)
			);
			
			// Add detailed order note
			$note = sprintf(
				__( 'ConvesioPay refund processed. Amount: %s', 'peachpay-for-woocommerce' ),
				wc_price( $amount )
			);
			
			if ( $refund_id ) {
				$note .= sprintf( __( '. Refund ID: %s', 'peachpay-for-woocommerce' ), $refund_id );
			}
			
			if ( $reason ) {
				$note .= sprintf( __( '. Reason: %s', 'peachpay-for-woocommerce' ), $reason );
			}
			
			$order->add_order_note( $note );
			
			// Store refund ID as order meta for future reference
			if ( $refund_id ) {
				$order->update_meta_data( '_convesiopay_last_refund_id', $refund_id );
				$order->save();
			}

			return true;

		} catch ( Exception $e ) {
			peachpay_log(
				'error',
				'ConvesioPay Card process refund failed - exception',
				array(
					'event'     => 'payments.convesiopay_gateway.refund.failed',
					'component' => 'payments',
					'feature'   => 'convesiopay_gateway',
					'operation' => 'refund',
					'outcome'   => 'failed',
					'method'    => __METHOD__,
					'line'      => __LINE__,
					'function'  => __FUNCTION__,
					'file'      => __FILE__,
					'class'     => __CLASS__,
					'method'    => __METHOD__,
					'data'      => array(
						'message' => $e->getMessage(),
						'code' => $e->getCode(),
						'file' => $e->getFile(),
						'line' => $e->getLine(),
					)
				)
			);
			return new WP_Error( 'convesiopay_refund_error', $e->getMessage() );
		}
	}

	/**
	 * Find payment ID by order number using ConvesioPay API.
	 *
	 * @param string $order_number Order number.
	 * @param array  $config       ConvesioPay configuration.
	 * @return string|false Payment ID or false if not found.
	 */
	private function find_payment_by_order_number( $order_number, $config ) {
		peachpay_log(
				'debug',
				'ConvesioPay find payment by order number debug for order number - ' . $order_number,
				array(
				'event'     => 'payments.convesiopay_gateway.event.debug',
				'component' => 'payments',
				'feature'   => 'convesiopay_gateway',
				'operation' => 'event',
				'outcome'   => 'debug',
				'method'    => __METHOD__,
				'line'      => __LINE__,
				'data'      => array(
					'api_url' => $config['api_url'] . '/payments/list?orderNumber=' . urlencode( $order_number )
				)));

		// Make API call to ConvesioPay to find payment by order number
		$response = wp_remote_get( $config['api_url'] . '/payments/list?orderNumber=' . urlencode( $order_number ), array(
			'headers' => array(
				'Authorization' => $config['secret_key'],
				'Content-Type' => 'application/json',
			),
			'timeout' => 30,
		) );

		if ( is_wp_error( $response ) ) {
			peachpay_log(
				'error',
				'ConvesioPay find payment by order number failed - network error for order number - ' . $order_number,
				array(
					'event'     => 'payments.convesiopay_gateway.find_payment_by_order_number.failed',
					'component' => 'payments',
					'feature'   => 'convesiopay_gateway',
					'operation' => 'find_payment_by_order_number',
					'outcome'   => 'failed',
					'line'      => __LINE__,
					'function'  => __FUNCTION__,
					'file'      => __FILE__,
					'class'     => __CLASS__,
					'method'    => __METHOD__,
					'data'      => array(
						'error_message' => $response->get_error_message()
					)
				)
			);
			return false;
		}

		$response_code = wp_remote_retrieve_response_code( $response );
		$response_body = wp_remote_retrieve_body( $response );
		$response_data = json_decode( $response_body, true );

		if ( $response_code !== 200 || empty( $response_data['payments'] ) ) {
			peachpay_log(
				'warning',
				'ConvesioPay find payment by order number warning - HTTP ' . $response_code . ' or no payments (order_number ' . $order_number . ')',
				array(
					'event'     => 'payments.convesiopay_gateway.find_payment_by_order_number.warning',
					'component' => 'payments',
					'feature'   => 'convesiopay_gateway',
					'operation' => 'find_payment_by_order_number',
					'outcome'   => 'warning',
					'line'      => __LINE__,
					'function'  => __FUNCTION__,
					'file'      => __FILE__,
					'class'     => __CLASS__,
					'method'    => __METHOD__,
					'data'      => array(
						'response_code' => $response_code,
						'response_body' => $response_body,
						'response_data' => $response_data
					)
				)
			);
			return false;
		}

		$payment_id = $response_data['payments'][0]['id'] ?? false;
		if ( $payment_id ) {
			peachpay_log(
				'info',
				'ConvesioPay find payment by order number success for order number - ' . $order_number,
				array(
					'event'     => 'payments.convesiopay_gateway.find_payment_by_order_number.success',
					'component' => 'payments',
					'feature'   => 'convesiopay_gateway',
					'operation' => 'find_payment_by_order_number',
					'outcome'   => 'success',
					'line'      => __LINE__,
					'function'  => __FUNCTION__,
					'file'      => __FILE__,
					'class'     => __CLASS__,
					'method'    => __METHOD__,
					'data'      => array(
						'response_data' => $response_data
					)
				)
			);
		}
		return $payment_id;
	}

	/**
	 * Payment fields for ConvesioPay - On-Demand Overlay Approach
	 */
	public function payment_fields() {
		
		$config = $this->get_convesiopay_config();
		
		if ( empty( $config ) ) {
			echo '<p style="color: red;">' . __( 'ConvesioPay is not properly configured. Please check your settings.', 'peachpay-for-woocommerce' ) . '</p>';
			return;
		}
		
		// Hidden div for checkout refresh - required for fee recalculation when payment method changes
		?>
		<div
			style="display:none"
			data-should-refresh-checkout="<?php echo esc_attr( $this->should_refresh_checkout() ); ?>"
			data-service-fee="<?php echo esc_attr( peachpay_gateway_has_service_fee( $this->id ) ? 'true' : 'false' ); ?>"
		></div>
		<?php
		
		// Display description
		if ( $this->description ) {
			echo '<p>' . wp_kses_post( $this->description ) . '</p>';
		}
		
		// ConvesioPay component container for direct integration
		?>
		<div id="convesiopay-payment-form" class="wc-payment-form" style="margin: 15px 0;">
			<fieldset id="convesiopay-fieldset" style="background: transparent; border: 0; margin: 0; padding: 0;">
				
				<!-- ConvesioPay Component Container -->
				<div id="convesiopay-component-container" style="border: 1px solid #e0e0e0; border-radius: 5px; background: #ffffff; padding: 20px; margin: 10px 0; min-height: 200px; display: flex; align-items: center; justify-content: center;">
					<div id="convesiopay-loading" style="text-align: center; color: #666;">
						<div style="margin-bottom: 10px;">🔄</div>
						Loading ConvesioPay payment form...
					</div>
				</div>
				
				<!-- Error Display Container -->
				<div id="convesiopay-error-message" style="display: none; color: #e74c3c; background: #fdf2f2; border: 1px solid #e74c3c; border-radius: 5px; padding: 10px; margin: 10px 0;">
				</div>
				
				<!-- Hidden field for payment token -->
				<input type="hidden" id="convesiopay-payment-token" name="convesiopay_payment_token" value="" />
				
			</fieldset>
		</div>
		<?php
		
	}

	/**
	 * Set PeachPay order details - following Stripe pattern
	 * 
	 * @param WC_Order $order The order object
	 * @param string $session_id PeachPay session ID
	 * @param string $transaction_id PeachPay transaction ID
	 */
	private function set_peachpay_order_details($order, $session_id, $transaction_id) {
		// Store PeachPay details on the order - similar to Stripe pattern
		$peachpay_details = array(
			'session_id'             => $session_id,
			'transaction_id'         => $transaction_id,
			'peachpay_mode'          => peachpay_is_test_mode() ? 'test' : 'live',
			'convesiopay_mode'       => peachpay_is_test_mode() ? 'test' : 'live',
			'service_fee_percentage' => PeachPay::service_fee_enabled() ? PeachPay::service_fee_percentage() : 0,
		);
		
		// Store as order meta data
		foreach ($peachpay_details as $key => $value) {
			$order->update_meta_data('_peachpay_' . $key, $value);
		}
		
		$order->save();
	}

	/**
	 * Check if WooCommerce Blocks is supported
	 */
	private function is_blocks_supported() {
		return class_exists( 'Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType' );
	}

	/**
	 * Get line items for ConvesioPay payment payload.
	 *
	 * @param WC_Order $order The order object.
	 * @return array Line items array.
	 */
	private function get_line_items( $order ) {
		$line_items = array();

		foreach ( $order->get_items() as $item ) {
			$line_items[] = array(
				'description'       => $item->get_name(),
				'quantity'          => $item->get_quantity(),
				'amountIncludingTax' => (int) round( $item->get_total() * 100 ) + (int) round( $item->get_total_tax() * 100 ),
			);
		}

		// Add shipping as a line item if present
		$shipping_total = $order->get_shipping_total();
		$shipping_tax   = $order->get_shipping_tax();
		if ( $shipping_total > 0 ) {
			$line_items[] = array(
				'description'       => __( 'Shipping', 'peachpay-for-woocommerce' ),
				'quantity'          => 1,
				'amountIncludingTax' => (int) round( $shipping_total * 100 ) + (int) round( $shipping_tax * 100 ),
			);
		}

		// Add fees as line items if present
		foreach ( $order->get_fees() as $fee ) {
			$line_items[] = array(
				'description'       => $fee->get_name(),
				'quantity'          => 1,
				'amountIncludingTax' => (int) round( $fee->get_total() * 100 ) + (int) round( $fee->get_total_tax() * 100 ),
			);
		}

		return $line_items;
	}



	/**
	 * Build card icons HTML string
	 *
	 * @return string HTML for card brand icons
	 */
	private function build_card_icons_html() {
		$icons_html = '';
		
		// Get individual card icon settings
		$card_icons_settings = get_option( 'peachpay_convesiopay_card_icons', array(
			'visa'       => 'no',
			'mastercard' => 'no',
			'amex'       => 'no',
			'discover'   => 'no',
		) );
		
		// Define all available card icons with their URLs
		$all_card_icons = array(
			'visa'       => PeachPay::get_asset_url( '/img/marks/visa.svg' ),
			'mastercard' => PeachPay::get_asset_url( '/img/marks/mastercard.svg' ),
			'amex'       => PeachPay::get_asset_url( '/img/marks/amex.svg' ),
			'discover'   => PeachPay::get_asset_url( '/img/marks/discover.svg' ),
		);

		// Only include icons that are enabled
		foreach ( $all_card_icons as $card_name => $icon_url ) {
			if ( isset( $card_icons_settings[ $card_name ] ) && $card_icons_settings[ $card_name ] === 'yes' ) {
				$icons_html .= sprintf(
					'<img src="%s" alt="%s" style="width: 40px; margin: 0px 1px; height: 25px;" />',
					esc_url( $icon_url ),
					esc_attr( ucfirst( $card_name ) )
				);
			}
		}

		return $icons_html;
	}

	/**
	 * Inject card icons into admin payment settings page via JavaScript
	 */
	public function inject_admin_card_icons() {
		// Only run on WooCommerce payment settings page
		$screen = get_current_screen();
		if ( ! $screen || $screen->id !== 'woocommerce_page_wc-settings' ) {
			return;
		}

		// Check if we're on the checkout/payments tab
		if ( ! isset( $_GET['tab'] ) || $_GET['tab'] !== 'checkout' ) {
			return;
		}

		// Check if any card icons should be shown (using legacy option for backward compatibility)
		$show_card_icons = get_option( 'peachpay_convesiopay_show_card_icons', 'no' );
		if ( $show_card_icons !== 'yes' ) {
			return;
		}

		// Get individual card icon settings
		$card_icons_settings = get_option( 'peachpay_convesiopay_card_icons', array(
			'visa'       => 'no',
			'mastercard' => 'no',
			'amex'       => 'no',
			'discover'   => 'no',
		) );

		// Define all available card icons with their URLs
		$all_card_icons = array(
			'visa'       => PeachPay::get_asset_url( '/img/marks/visa.svg' ),
			'mastercard' => PeachPay::get_asset_url( '/img/marks/mastercard.svg' ),
			'amex'       => PeachPay::get_asset_url( '/img/marks/amex.svg' ),
			'discover'   => PeachPay::get_asset_url( '/img/marks/discover.svg' ),
		);

		// Build icons HTML for JavaScript - only include enabled cards
		$icons_html = '';
		foreach ( $all_card_icons as $card_name => $icon_url ) {
			if ( isset( $card_icons_settings[ $card_name ] ) && $card_icons_settings[ $card_name ] === 'yes' ) {
				$icons_html .= sprintf(
					'<img src="%s" alt="%s" style="width: 32px; height: 20px; margin-left: 4px; vertical-align: middle; border: 1px solid #e0e0e0; border-radius: 2px; padding: 2px; background: #fff;" />',
					esc_url( $icon_url ),
					esc_attr( ucfirst( $card_name ) )
				);
			}
		}

		// Don't output anything if no icons are enabled
		if ( empty( $icons_html ) ) {
			return;
		}
		?>
		<script type="text/javascript">
		(function() {
			function injectCardIcons() {
				var iconsHtml = '<?php echo wp_kses_post( $icons_html ); ?>';
				
				// Method 1: Classic WooCommerce table-based interface
				var gatewayRow = document.querySelector('tr[data-gateway_id="peachpay_convesiopay_card"]');
				if (gatewayRow && !gatewayRow.querySelector('.convesiopay-admin-card-icons')) {
					var nameCell = gatewayRow.querySelector('td.name');
					if (nameCell) {
						var iconsContainer = document.createElement('span');
						iconsContainer.className = 'convesiopay-admin-card-icons';
						iconsContainer.innerHTML = iconsHtml;
						iconsContainer.style.marginLeft = '8px';
						iconsContainer.style.display = 'inline-flex';
						iconsContainer.style.alignItems = 'center';
						nameCell.appendChild(iconsContainer);
					}
				}
				
				// Method 2: New WooCommerce React-based list interface
				var listItems = document.querySelectorAll('.woocommerce-list__item');
				listItems.forEach(function(item) {
					var titleSpan = item.querySelector('.woocommerce-list__item-title');
					if (titleSpan) {
						var titleText = titleSpan.textContent || '';
						// Only match "Card via ConvesioPay" - exclude Apple Pay, BTCPay, Crypto
						var isCardGateway = titleText.includes('Card via ConvesioPay') || 
						                    (titleText.includes('Card') && titleText.includes('ConvesioPay') && 
						                     !titleText.includes('Apple') && !titleText.includes('BTCPay') && 
						                     !titleText.includes('Crypto') && !titleText.includes('Bitcoin'));
						
						if (isCardGateway) {
							// Check if icons already exist
							var parentDiv = item.querySelector('.woocommerce-list__item-text');
							if (parentDiv && !parentDiv.querySelector('.convesiopay-admin-card-icons')) {
								var iconsContainer = document.createElement('div');
								iconsContainer.className = 'convesiopay-admin-card-icons';
								iconsContainer.innerHTML = iconsHtml;
								iconsContainer.style.display = 'flex';
								iconsContainer.style.alignItems = 'center';
								iconsContainer.style.gap = '4px';
								iconsContainer.style.marginTop = '8px';
								parentDiv.appendChild(iconsContainer);
							}
						}
					}
				});
			}
			
			// Run on DOMContentLoaded
			document.addEventListener('DOMContentLoaded', injectCardIcons);
			
			// Also run after a delay for React-based interfaces that load dynamically
			setTimeout(injectCardIcons, 1000);
			setTimeout(injectCardIcons, 2000);
			setTimeout(injectCardIcons, 3000);
			
			// Use MutationObserver to detect when React content loads
			var observer = new MutationObserver(function(mutations) {
				injectCardIcons();
			});
			observer.observe(document.body, { childList: true, subtree: true });
			
			// Stop observing after 10 seconds to prevent performance issues
			setTimeout(function() {
				observer.disconnect();
			}, 10000);
		})();
		</script>
		<?php
	}
	
}