<?php
/**
 * PeachPay ConvesioPay Apple Pay Gateway
 *
 * @package PeachPay
 */

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

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

/**
 * ConvesioPay Apple Pay Gateway
 */
class PeachPay_ConvesioPay_ApplePay_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_applepay';
		$this->title                 = 'Apple Pay';
		$this->description           = sprintf( __( 'After selecting %s a prompt will appear to complete your payment.', 'peachpay-for-woocommerce' ), 'Apple Pay' );
		$this->method_title          = sprintf( __( '%s via ConvesioPay (PeachPay)', 'peachpay-for-woocommerce' ), 'Apple Pay' );
		$this->method_description    = 'Accept Apple Pay payments through ConvesioPay';
		$this->has_fields            = true;
		$this->supports              = array(
			'products',
			'refunds',
			'blocks',
			'subscriptions',
			'multiple_subscriptions',
			'subscription_cancellation',
			'subscription_suspension',
			'subscription_reactivation',
			'subscription_amount_changes',
			'subscription_date_changes',
			'subscription_payment_method_change_customer',
		);
		
		// Set up Apple Pay icons
		$this->icon = '';
		$this->icons = array(
			'full'  => array(
				'white' => PeachPay::get_asset_url( 'img/marks/applepay-full.svg' ),
			),
			'small' => array(
				'white' => PeachPay::get_asset_url( 'img/marks/applepay-small-white.svg' ),
				'color' => PeachPay::get_asset_url( 'img/marks/applepay-small-color.svg' ),
			),
		);
		
		// Set payment provider info
		$this->payment_provider = 'ConvesioPay';
		$this->payment_method_family = __( 'Digital wallet', 'peachpay-for-woocommerce' );
		
		// Restrict to USD currency only
		$this->currencies = array( 'USD' );
		
		// Override max_amount to prevent JSON encoding issues
		// $this->max_amount = INF; // Commented out to show "Not restricted"
		// $this->custom_max_amount = INF;
		$this->min_amount = 0.50;
		
		// Call parent constructor
		parent::__construct();
		
		// Enable gateway by default if not set
		if (!isset($this->settings['enabled'])) {
			$this->enabled = 'yes';
		}
		
		// 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 information block after settings
		add_action( 'woocommerce_settings_' . $this->id, array( $this, 'add_information_block' ) );

		// Subscription renewal support.
		$this->register_subscription_renewal_hook();

		// Initialize form fields
		$this->init_form_fields();
		
		// Mark as initialized
		$this->initialized = true;

	}

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

		// Add ApplePay-specific fields at the top
		$applepay_fields = array(
			'applepay_info' => array(
				'title'       => 'Configuration',
				'type'        => 'title',
				'description' => '<div style="background: #f8f9fa; border-left: 4px solid #0073aa; padding: 15px; margin: 10px 0; border-radius: 4px;">
					<p style="margin: 0 0 8px 0;"><strong>Step 1:</strong> Download and unzip the <a href="https://dev.convesiopay.com/assets/apple-developer-merchantid-domain-association-2024.zip">ConvesioPay\'s Apple Pay certificate</a></p>
					<p style="margin: 0 0 8px 0;"><strong>Step 2:</strong> Host the certificate file with the name <code>apple-developer-merchantid-domain-association</code> on each domain you want to use, including subdomains, under the following path:</p>
					<p style="margin: 0 0 8px 0; background: #fff; padding: 8px; border-radius: 3px; font-family: monospace; border: 1px solid #ddd;">/.well-known/apple-developer-merchantid-domain-association</p>
					<p style="margin: 0 0 8px 0;"><strong>The file must:</strong></p>
					<ul style="margin: 0 0 8px 0; padding-left: 20px;">
						<li>Be externally accessible</li>
						<li>Not be password protected</li>
						<li>Not be behind a proxy or redirect</li>
					</ul>
					<p "><a href="https://eu.adyen.link/.well-known/apple-developer-merchantid-domain-association" style="color: #0073aa; text-decoration: underline;">See an example of a working certificate file</a></p>
					<ul><li style="margin: 0 0 8px 0;"><a href="https://convesiopay.com/integrations/woo-commerce" style="color: #0073aa;">Add ApplePay domains in the ConvesioPay Dashboard WooCommerce Integration Settings.</a> You must register all top-level domains and subdomains you want to take ApplePay payments for with this extension.</li></ul>
					<hr style="margin: 15px 0; border: none; border-top: 1px solid #ddd;">
					<p style="margin: 0; font-size: 13px; color: #666;"><em>💡 If you need assistance setting this up, please reach out to <a href="mailto:pay@convesio.com"><strong>ConvesioPay Support</strong></a></em></p>
				</div>',
			),
		);

		// Merge ApplePay-specific fields at the beginning (before parent fields)
		$this->form_fields = array_merge( $applepay_fields, $this->form_fields );
		// Modify the active_locations field after parent initialization
		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' );
		}
	}

	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, '.', '' );
	}

	/**
	 * Gets the maximum charge - return INF to show "Not restricted"
	 *
	 * @return float
	 */
	public function get_maximum_charge() {
		return INF;
	}

	/**
	 * Check if the gateway is available for use.
	 *
	 * @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;
		}

		// Admin context - always show for settings
		if ( is_admin() && ! wp_doing_ajax() ) {
			return true;
		}
		
		// 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;
		}
		
		// Apple Pay availability checking is handled in JavaScript on the frontend
		// The gateway itself should be available so the JS can determine browser support
		
		return parent::is_available( $skip_cart_check );
	}

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

	/**
	 * Process the payment (NEW TOKEN-BASED FLOW).
	 * Creates payment using token after order exists (no more TEMP- order numbers).
	 *
	 * @param int $order_id Order ID.
	 * @return array
	 */
	public function process_payment( $order_id ) {
		$order = wc_get_order( $order_id );

		if ( ! $order ) {
			return array(
				'result'   => 'failure',
				'message'  => __( 'Order not found.', 'peachpay-for-woocommerce' ),
			);
		}

		// NEW FLOW: Get payment token from request (not payment ID)
		$payment_token = $this->get_payment_token_from_request();

		if ( empty( $payment_token ) ) {
			throw new Exception( __( 'Apple Pay payment token is missing. Please try again.', 'peachpay-for-woocommerce' ) );
		}

		// Use parent's PeachPay transaction system for processing
		$result = parent::process_payment( $order_id );

		// NEW FLOW: Create payment using token and secret key (after order exists)
		try {
			// Get ConvesioPay configuration
			$config = $this->get_convesiopay_config();

			if ( empty( $config ) || empty( $config['secret_key'] ) ) {
				throw new Exception( __( 'ConvesioPay is not properly configured.', 'peachpay-for-woocommerce' ) );
			}

			// Get order amount and convert using explicit rounding (not truncation).
			$order_amount       = $order->get_total();
			$order_amount_cents = (int) round( (float) $order_amount * 100 );

			// 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()
			);
			

			$line_items = $this->get_line_items( $order );
			$line_items_sum_cents = 0;
			foreach ( $line_items as $line_item ) {
				$line_items_sum_cents += isset( $line_item['amountIncludingTax'] ) ? (int) $line_item['amountIncludingTax'] : 0;
			}

			$frontend_applepay_amount = isset( $_POST['applepay_amount'] ) ? sanitize_text_field( wp_unslash( $_POST['applepay_amount'] ) ) : '';
			$frontend_applepay_amount_cents = $this->parse_amount_to_cents( $frontend_applepay_amount );
			$selected_method_session = ( WC()->session ) ? WC()->session->get( 'convesiopay_selected_method' ) : '';

			// Server-authoritative: always use order total for the payment request amount.
			// Use frontend applepay_amount only for validation and logging (avoids tampering/stale client data).
			$request_amount_cents = $order_amount_cents;
			if ( null !== $frontend_applepay_amount_cents && $frontend_applepay_amount_cents > 0 ) {
				$amount_diff_cents = abs( $frontend_applepay_amount_cents - $order_amount_cents );
				if ( $amount_diff_cents > 1 ) {
					peachpay_log(
						'warning',
						'Payments: Apple Pay process payment warning.',
						array(
							'event'     => 'payments.convesiopay_gateway.applepay.payment.warning',
							'component' => 'payments',
							'feature'   => 'convesiopay_gateway',
							'operation' => 'applepay.payment',
							'outcome'   => 'warning',
							'method'    => __METHOD__,
							'line'      => __LINE__,
							'data'      => array(
								'details' => 'ConvesioPay: Apple Pay frontend amount differs from order total for order ' . $order->get_order_number() . ' (order_cents: ' . $order_amount_cents . ', frontend_cents: ' . $frontend_applepay_amount_cents . '). Rejecting so user re-authorizes.'
							)
						)
					);
					throw new Exception( __( 'Order total has changed. Please confirm the payment amount and try again.', 'peachpay-for-woocommerce' ) );
				}
			}

			// Ensure line item sum equals request amount for strict API validation.
			$line_items_diff_cents = $request_amount_cents - $line_items_sum_cents;
			if ( 0 !== $line_items_diff_cents ) {
				if ( $line_items_diff_cents > 0 ) {
					$line_items[] = array(
						'description'        => __( 'Tax/rounding adjustment', 'peachpay-for-woocommerce' ),
						'quantity'           => 1,
						'amountIncludingTax' => $line_items_diff_cents,
					);
					$line_items_sum_cents += $line_items_diff_cents;
				} elseif ( ! empty( $line_items ) && isset( $line_items[0]['amountIncludingTax'] ) && ( (int) $line_items[0]['amountIncludingTax'] + $line_items_diff_cents ) > 0 ) {
					$line_items[0]['amountIncludingTax'] = (int) $line_items[0]['amountIncludingTax'] + $line_items_diff_cents;
					$line_items_sum_cents += $line_items_diff_cents;
				}
			}

			// Prepare payment data in ConvesioPay format (same as card gateway)
			$payment_data = array(
				'integration'        => $config['integration_name'] ?? 'PeachPay',
				'returnUrl'          => $this->get_return_url( $order ),
				'paymentToken'       => $payment_token,
				'orderNumber'        => $order->get_order_number(),
				'amount'             => $request_amount_cents,
				'currency'           => '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'          => $line_items,
			);

			// 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 with secret key
			// Use EXACT same format as card gateway: $config['api_url'] . '/payments'
			// According to ConvesioPay API docs: https://api.convesiopay.com/v1/payments
			$api_url = $config['api_url'] . '/payments';
			
			// Validate secret key exists and is not empty
			if ( empty( $config['secret_key'] ) || trim( $config['secret_key'] ) === '' ) {
				throw new Exception( __( 'ConvesioPay secret key is not configured. Please check your settings.', 'peachpay-for-woocommerce' ) );
			}

			// Prepare request body - encode array to JSON string
			$request_body = wp_json_encode( $payment_data );
			peachpay_log(
				'debug',
				'Payments: Apple Pay process payment api request debug.',
				array(
					'event'     => 'payments.convesiopay_gateway.applepay.payment.debug',
					'component' => 'payments',
					'feature'   => 'convesiopay_gateway',
					'operation' => 'applepay.payment',
					'outcome'   => 'debug',
					'method'    => __METHOD__,
					'line'      => __LINE__,
					'data'      => array(
						'details' => $payment_data
					)
				)
			);
			if ( $line_items_sum_cents !== $request_amount_cents ) {
				peachpay_log(
					'warning',
					'Payments: Apple Pay process payment warning.',
					array(
						'event'     => 'payments.convesiopay_gateway.applepay.payment.warning',
						'component' => 'payments',
						'feature'   => 'convesiopay_gateway',
						'operation' => 'applepay.payment',
						'outcome'   => 'warning',
						'method'    => __METHOD__,
						'line'      => __LINE__,
						'data'      => array(
							'details' => 'ConvesioPay: Apple Pay request amount differs from line item sum for order ' . $order->get_order_number() . ' (request_cents: ' . $request_amount_cents . ', line_items_sum_cents: ' . $line_items_sum_cents . ')'
						)
					)
				);
			}

			// Make API call - EXACT same format as card gateway
			$response = wp_remote_post(
				$api_url,
				array(
					'headers' => array(
						'Authorization' => $config['secret_key'], // Direct from config, same as card gateway
						'Content-Type'  => 'application/json',
					),
					'body'    => $request_body,
					'timeout' => 30,
				)
			);

			if ( is_wp_error( $response ) ) {
				throw new Exception( 'ConvesioPay: Apple Pay payment network error - ' . $response->get_error_message() . ' (order ' . $order->get_order_number() . ')' );
			}

			$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 ) {
				// Extract error message from response
				$error_message = 'ConvesioPay API error (HTTP ' . $response_code . ')';
				if ( is_array( $response_data ) ) {
					if ( isset( $response_data['message'] ) ) {
						$error_message .= ': ' . $response_data['message'];
					} elseif ( isset( $response_data['body']['message'] ) ) {
						$error_message .= ': ' . $response_data['body']['message'];
					}
				}
				throw new Exception( $error_message );
			}

			// Check ConvesioPay response status
			$status     = $response_data['status'] ?? '';
			$payment_id = $response_data['id'] ?? '';

			if ( empty( $status ) || empty( $payment_id ) ) {
				throw new Exception( 'Invalid response from ConvesioPay status: ' . $status . ', payment_id: ' . $payment_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 payment ID and capture mode
			$order->update_meta_data( '_convesiopay_payment_id', $payment_id );
			$order->update_meta_data( '_convesiopay_original_payment_id', $payment_id );
			$order->update_meta_data( '_convesiopay_manual_capture_mode', $manual_capture_mode ? 'yes' : 'no' );
			$order->set_transaction_id( $payment_id );

			// Add order note with payment ID
			$payment_url = peachpay_convesiopay_dashboard_url() . '/payments/' . $payment_id;

			// Handle payment status
			if ( in_array( $status, array( 'Succeeded', 'Pending', 'Refused', 'Blocked' ), true ) ) {
				if ( $status === 'Succeeded' ) {
					$order->add_order_note(
						sprintf(
							__( 'Apple Pay payment succeeded via ConvesioPay. Payment ID: %s | <a href="%s" target="_blank">View Payment</a>', 'peachpay-for-woocommerce' ),
							$payment_id,
							$payment_url
						)
					);
					$order->update_meta_data( '_convesiopay_payment_status', 'captured' );
					$order->payment_complete( $payment_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(
								__( 'Apple Pay payment authorized and ready for manual capture. Payment ID: %s | <a href="%s" target="_blank">View Payment</a>', 'peachpay-for-woocommerce' ),
								$payment_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(
								__( 'Apple Pay payment authorized and awaiting confirmation. Payment ID: %s | <a href="%s" target="_blank">View Payment</a>', 'peachpay-for-woocommerce' ),
								$payment_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(
							__( 'Apple Pay payment refused/blocked. Payment ID: %s | <a href="%s" target="_blank">View Payment</a>', 'peachpay-for-woocommerce' ),
							$payment_id,
							$payment_url
						)
					);
					$order->update_status( 'failed', __( 'Apple Pay payment refused or blocked.', 'peachpay-for-woocommerce' ) );
				}

				// Set PeachPay order details - following Stripe pattern
				$this->set_peachpay_order_details( $order );

				$order->save();

				$peachpay_log_type = "info";
				$peachpay_log_message = 'ConvesioPay ConvesioPay Apple Pay process payment success for order id - ' . $order_id;
				if ( $status === 'Refused' || $status === 'Blocked' ) {
					$peachpay_log_type = "error";
					$peachpay_log_message = 'ConvesioPay ConvesioPay Apple Pay process payment ' . strtolower($status) . ' for order id - ' . $order_id;
				}
				peachpay_log(
					$peachpay_log_type,
					$peachpay_log_message,
					array(
						'event'     => 'payments.convesiopay_gateway.applepay.payment.' . strtolower($status),
						'component' => 'payments',
						'feature'   => 'convesiopay_gateway',
						'operation' => 'applepay.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 {
				throw new Exception( 'Payment failed with status: ' . $status );
			}
		} catch ( Exception $e ) {
			peachpay_log(
				'error',
				'Payments: Apple Pay process payment failed.',
				array(
					'event'     => 'payments.convesiopay_gateway.applepay.payment.failed',
					'component' => 'payments',
					'feature'   => 'convesiopay_gateway',
					'operation' => 'applepay.payment',
					'outcome'   => 'failed',
					'method'    => __METHOD__,
					'line'      => __LINE__,
					'data'      => array(
						'details' => 'ConvesioPay: Apple Pay payment exception - ' . $e->getMessage() . ' (order ' . $order->get_order_number() . ')'
					)
				)
			);
			$order->add_order_note(
				sprintf(
					__( 'Apple Pay payment failed: %s', 'peachpay-for-woocommerce' ),
					$e->getMessage()
				)
			);
			wc_add_notice( __( 'Apple Pay payment failed: ', 'peachpay-for-woocommerce' ) . $e->getMessage(), 'error' );

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

	/**
	 * Get payment token from request (NEW TOKEN-BASED FLOW)
	 * Extracts the Apple Pay payment token sent from frontend
	 * Supports: Classic checkout, Blocks checkout, Express checkout
	 */
	private function get_payment_token_from_request() {
		$payment_token = '';

		// Method 1: Classic checkout - check POST data directly
		if ( isset( $_POST['convesiopay_payment_token'] ) && ! empty( $_POST['convesiopay_payment_token'] ) ) {
			$payment_token_raw = $_POST['convesiopay_payment_token'];
			
			// Validate token format BEFORE sanitizing - Apple Pay tokens should be long strings without spaces
			if ( strpos( $payment_token_raw, ' ' ) !== false ) {
				// Token contains spaces - this is likely the wrong field (order number, customer name, etc.)
				// Don't return this invalid token - continue to other extraction methods
			} elseif ( strlen( trim( $payment_token_raw ) ) < 20 ) {
				// Token too short - likely wrong field
				// Don't return this invalid token - continue to other extraction methods
			} else {
				// Token looks valid - sanitize and return
				$payment_token = sanitize_text_field( $payment_token_raw );
				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 ) ) {
					$checkout_schema = $container->get( \Automattic\WooCommerce\StoreApi\Schemas\CheckoutSchema::class );
					$request_data = $checkout_schema->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 ) {
				// Store API error - continue to other extraction methods
			}
		}

		// Method 3: WooCommerce Blocks - check payment_method_data
		if ( empty( $payment_token ) && isset( $_POST['payment_method'] ) && $_POST['payment_method'] === 'peachpay_convesiopay_applepay' ) {
			// Check payment_method_data (JSON string or array)
			if ( isset( $_POST['payment_method_data'] ) ) {
				$payment_method_data = $_POST['payment_method_data'];
				
				if ( is_string( $payment_method_data ) ) {
					$decoded = json_decode( stripslashes( $payment_method_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['paymentToken'] ) ) {
						$payment_token = sanitize_text_field( $decoded['paymentToken'] );
						return $payment_token;
					}
				} elseif ( is_array( $payment_method_data ) ) {
					if ( isset( $payment_method_data['convesiopay_payment_token'] ) ) {
						$payment_token = sanitize_text_field( $payment_method_data['convesiopay_payment_token'] );
						return $payment_token;
					} elseif ( isset( $payment_method_data['paymentToken'] ) ) {
						$payment_token = sanitize_text_field( $payment_method_data['paymentToken'] );
						return $payment_token;
					}
				}
			}

			// Method 4: Check other possible locations for Blocks
			$possible_locations = array(
				'convesiopay_payment_token',
				'applepay_payment_token',
				'payment_token',
				'paymentToken',
			);

			foreach ( $possible_locations as $location ) {
				if ( isset( $_POST[ $location ] ) ) {
					$data = $_POST[ $location ];

					if ( is_string( $data ) && ! empty( $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['paymentToken'] ) ) {
							$payment_token = sanitize_text_field( $decoded['paymentToken'] );
							return $payment_token;
						} elseif ( $location === 'convesiopay_payment_token' ) {
							// Direct token value
							$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['paymentToken'] ) ) {
							$payment_token = sanitize_text_field( $data['paymentToken'] );
							return $payment_token;
						}
					}
				}
			}
		}

		// Method 5: Check payment_data array format (Blocks specific)
		if ( empty( $payment_token ) && 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;
					}
				}
			}
		}

		return $payment_token;
	}

	/**
	 * Get payment ID from request (DEPRECATED - for backwards compatibility only)
	 */
	private function get_payment_id_from_request() {
		$payment_id = '';

		// Method 1: Check POST data for WooCommerce Blocks
		if ( isset( $_POST['payment_method'] ) && $_POST['payment_method'] === 'peachpay_convesiopay_applepay' ) {
			// Check all possible locations where blocks might send the payment ID
			$possible_locations = array(
				'convesiopay_payment_id',
				'applepay_payment_id',
				'payment_id',
				'paymentId',
				'payment_method_data',
			);

			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['paymentId'] ) ) {
							$payment_id = sanitize_text_field( $decoded['paymentId'] );
							return $payment_id;
						} elseif ( strpos( $data, 'applepay_' ) === 0 || strpos( $data, 'pm_' ) === 0 || strpos( $data, 'pi_' ) === 0 ) {
							// Looks like a payment ID
							$payment_id = sanitize_text_field( $data );
							return $payment_id;
						}
					} elseif ( is_array( $data ) ) {
						if ( isset( $data['paymentId'] ) ) {
							$payment_id = sanitize_text_field( $data['paymentId'] );
							return $payment_id;
						}
					}
				}
			}
		}

		return $payment_id;
	}

	/**
	 * 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 '';
	}

	/**
	 * Enqueue gateway scripts.
	 */
	public function enqueue_scripts() {
		if ( ! $this->is_available() ) {
			return;
		}

		// Enqueue Apple Pay specific scripts
		wp_enqueue_script(
			'peachpay-convesiopay-applepay',
			plugins_url( 'assets/js/applepay.js', dirname( __FILE__ ) ),
			array( 'jquery', 'peachpay-convesiopay-checkout' ),
			'1.1.0',
			true
		);

		// Add Apple Pay configuration
		$config = $this->get_convesiopay_config();
		
		wp_localize_script(
			'peachpay-convesiopay-applepay',
			'peachpayConvesioPayApplePay',
			array(
				'gateway_id'    => $this->id,
				'is_available'  => $this->is_available(),
				'client_key'    => $config['client_key'] ?? '',
				'api_url'       => peachpay_is_test_mode() ? 'https://api-qa.convesiopay.com' : 'https://api.convesiopay.com',
				'ajax_url'      => admin_url( 'admin-ajax.php' ),
				'nonce'         => wp_create_nonce( 'peachpay_convesiopay_nonce' ),
			)
		);
	}

	/**
	 * Get gateway icon with size and style options.
	 *
	 * @param boolean $flex Whether to use flex display.
	 * @param string $size Icon size (full/small).
	 * @param string $background Icon style (color/white).
	 * @return string
	 */
	public function get_icon( $flex = false, $size = 'full', $background = 'color' ) {
		if ( isset( $this->icons[ $size ][ $background ] ) ) {
			return '<img src="' . esc_url( $this->icons[ $size ][ $background ] ) . '" alt="' . esc_attr( $this->get_title() ) . '" class="peachpay-payment-method-icon peachpay-payment-method-icon-' . esc_attr( $size ) . '">';
		}
		
		// Fallback to first available icon
		foreach ( $this->icons as $size_key => $styles ) {
			foreach ( $styles as $style_key => $url ) {
				return '<img src="' . esc_url( $url ) . '" alt="' . esc_attr( $this->get_title() ) . '" class="peachpay-payment-method-icon peachpay-payment-method-icon-' . esc_attr( $size_key ) . '">';
			}
		}
		
		return '';
	}



	/**
	 * Add information block after the settings form.
	 */
	public function add_information_block() {
		echo '<div style="background: #f8f9fa; border-left: 4px solid #0073aa; padding: 15px; margin: 20px 0; border-radius: 4px;">
			<h4 style="margin: 0 0 10px 0; color: #0073aa;">🚀 Apple Pay Integration Details</h4>
			<p style="margin: 0 0 8px 0;"><strong>Payment Method:</strong> Apple Pay via ConvesioPay</p>
			<p style="margin: 0 0 8px 0;"><strong>Supported Devices:</strong> iPhone, iPad, Mac with Touch ID/Face ID</p>
			<p style="margin: 0 0 8px 0;"><strong>Browser Support:</strong> Safari on iOS/macOS</p>
			<p style="margin: 0 0 8px 0;"><strong>Requirements:</strong> Valid Apple Developer Account & Apple Pay Certificate</p>
			<p style="margin: 0 0 8px 0;"><strong>Transaction Security:</strong> End-to-end encryption with Apple Pay</p>
			<hr style="margin: 15px 0; border: none; border-top: 1px solid #ddd;">
			<p style="margin: 0; font-size: 13px; color: #666;"><em>💡 Tip: Apple Pay will automatically appear for supported devices and browsers. No additional configuration needed.</em></p>
		</div>';
	}

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

	/**
	 * 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;
	}

	/**
	 * Parse posted amount into integer cents.
	 *
	 * Accepts either minor-units integer strings (e.g. "101") or decimal
	 * major-units strings (e.g. "1.01") and returns cents.
	 *
	 * @param string $amount_raw Raw posted amount.
	 * @return int|null Amount in cents, or null when invalid.
	 */
	private function parse_amount_to_cents( $amount_raw ) {
		if ( null === $amount_raw || '' === trim( (string) $amount_raw ) ) {
			return null;
		}

		$normalized = preg_replace( '/[^\d\.]/', '', (string) $amount_raw );
		if ( '' === $normalized ) {
			return null;
		}

		// If it is a plain integer without a decimal point, assume minor units.
		if ( preg_match( '/^\d+$/', $normalized ) ) {
			return (int) $normalized;
		}

		if ( is_numeric( $normalized ) ) {
			return (int) round( (float) $normalized * 100 );
		}

		return null;
	}

	/**
	 * Set PeachPay order details - following Stripe pattern
	 *
	 * @param WC_Order $order The order object.
	 */
	private function set_peachpay_order_details( $order ) {
		// Store PeachPay details on the order - similar to Stripe pattern
		$peachpay_details = array(
			'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 );
		}
	}
}