<?php
/**
 * ConvesioPay functions.
 *
 * @package PeachPay
 */

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

/**
 * ConvesioPay dashboard base URL (for "View Payment" links). Test mode uses dev.convesiopay.com.
 *
 * @return string Base URL (no trailing slash), e.g. https://convesiopay.com or https://dev.convesiopay.com
 */
function peachpay_convesiopay_dashboard_url() {
	return peachpay_is_test_mode() ? 'https://dev.convesiopay.com' : 'https://convesiopay.com';
}

/**
 * URL of the bundled Apple Pay domain association ZIP under core/payments/convesiopay/assets/certificates/.
 *
 * @param bool $is_orchestration True for Orchestration (OL): test-apple-pay-ol.zip or prod-apple-pay-ol.zip from PeachPay test mode. False for standard merchants: standard-apple-pay.zip.
 * @return string Full URL to the ZIP file.
 */
function peachpay_convesiopay_apple_pay_certificate_url( $is_orchestration ) {
	$base = plugin_dir_url( PEACHPAY_ABSPATH . '/.' ) . 'core/payments/convesiopay/assets/certificates/';

	if ( $is_orchestration ) {
		$filename = ( function_exists( 'peachpay_is_test_mode' ) && peachpay_is_test_mode() ) ? 'test-apple-pay-ol.zip' : 'prod-apple-pay-ol.zip';
	} else {
		$filename = 'standard-apple-pay.zip';
	}

	return $base . $filename;
}

/**
 * Check if ConvesioPay is connected.
 *
 * @return boolean
 */
function peachpay_convesiopay_connected() {
	// Use the integration class method for consistent logic
	if (class_exists('PeachPay_ConvesioPay_Integration')) {
		return PeachPay_ConvesioPay_Integration::connected();
	}
	
	// Fallback check if class not available
	$account = get_option( 'peachpay_connected_convesiopay_account', false );
	$config = get_option( 'peachpay_connected_convesiopay_config', array() );
	
	return !empty($account) && !empty($config) && 
	       isset($account['status']) && $account['status'] === 'connected';
}

/**
 * Get list of active payment methods
 * 
 * @return array Array of active payment method keys ('card', 'applepay', 'googlepay', 'crypto')
 */
function peachpay_convesiopay_get_active_payment_methods() {
	$active_methods = array();
	$gateways = WC()->payment_gateways->payment_gateways();
	
	// Check Card
	if ( PeachPay_ConvesioPay_Integration::is_capable( 'card' ) ) {
		$card_gateway = $gateways['peachpay_convesiopay_card'] ?? null;
		if ( $card_gateway ) {
			// Check both get_option and the enabled property
			$enabled_option = $card_gateway->get_option( 'enabled', 'no' );
			$enabled_property = $card_gateway->enabled ?? 'no';
			if ( $enabled_option === 'yes' || $enabled_property === 'yes' ) {
				$active_methods[] = 'card';
			}
		}
	}
	
	// Check ApplePay
	if ( PeachPay_ConvesioPay_Integration::is_capable( 'applepay' ) ) {
		$applepay_gateway = $gateways['peachpay_convesiopay_applepay'] ?? null;
		if ( $applepay_gateway ) {
			// Check both get_option and the enabled property
			$enabled_option = $applepay_gateway->get_option( 'enabled', 'no' );
			$enabled_property = $applepay_gateway->enabled ?? 'no';
			if ( $enabled_option === 'yes' || $enabled_property === 'yes' ) {
				$active_methods[] = 'applepay';
			}
		}
	}

	// Check Google Pay
	if ( PeachPay_ConvesioPay_Integration::is_capable( 'googlepay' ) ) {
		$googlepay_gateway = $gateways['peachpay_convesiopay_googlepay'] ?? null;
		if ( $googlepay_gateway ) {
			$enabled_option   = $googlepay_gateway->get_option( 'enabled', 'no' );
			$enabled_property = $googlepay_gateway->enabled ?? 'no';
			if ( $enabled_option === 'yes' || $enabled_property === 'yes' ) {
				$active_methods[] = 'googlepay';
			}
		}
	}
	
	// Check Crypto/BTCPay
	if ( PeachPay_ConvesioPay_Integration::is_capable( 'btcpay' ) ) {
		$btcpay_gateway = $gateways['peachpay_convesiopay_btcpay'] ?? null;
		if ( $btcpay_gateway ) {
			// Check both get_option and the enabled property
			$enabled_option = $btcpay_gateway->get_option( 'enabled', 'no' );
			$enabled_property = $btcpay_gateway->enabled ?? 'no';
			if ( $enabled_option === 'yes' || $enabled_property === 'yes' ) {
				$active_methods[] = 'crypto';
			}
		}
	}
	
	return $active_methods;
}

/**
 * Adds the feature flag for enabling ConvesioPay gateways.
 *
 * @param array $feature_list The list of features.
 */
function peachpay_convesiopay_register_feature( $feature_list ) {
	$config = PeachPay_ConvesioPay_Integration::config();
	$active_methods = peachpay_convesiopay_get_active_payment_methods();

	// Get fee configuration for each payment method
	$gateways = WC()->payment_gateways ? WC()->payment_gateways->payment_gateways() : array();
	$card_gateway = $gateways['peachpay_convesiopay_card'] ?? null;
	$applepay_gateway = $gateways['peachpay_convesiopay_applepay'] ?? null;
	$googlepay_gateway = $gateways['peachpay_convesiopay_googlepay'] ?? null;
	$btcpay_gateway = $gateways['peachpay_convesiopay_btcpay'] ?? null;

	$fee_config = array(
		'card' => array(
			'enabled' => $card_gateway ? $card_gateway->get_option( 'fees_enabled' ) === 'yes' : false,
			'type' => $card_gateway ? $card_gateway->get_option( 'fee_type' ) : 'fixed',
			'amount' => $card_gateway ? floatval( $card_gateway->get_option( 'fee_amount' ) ) : 0,
			'label' => $card_gateway ? $card_gateway->get_option( 'fee_reason' ) : '',
		),
		'applepay' => array(
			'enabled' => $applepay_gateway ? $applepay_gateway->get_option( 'fees_enabled' ) === 'yes' : false,
			'type' => $applepay_gateway ? $applepay_gateway->get_option( 'fee_type' ) : 'fixed',
			'amount' => $applepay_gateway ? floatval( $applepay_gateway->get_option( 'fee_amount' ) ) : 0,
			'label' => $applepay_gateway ? $applepay_gateway->get_option( 'fee_reason' ) : '',
		),
		'googlepay' => array(
			'enabled' => $googlepay_gateway ? $googlepay_gateway->get_option( 'fees_enabled' ) === 'yes' : false,
			'type' => $googlepay_gateway ? $googlepay_gateway->get_option( 'fee_type' ) : 'fixed',
			'amount' => $googlepay_gateway ? floatval( $googlepay_gateway->get_option( 'fee_amount' ) ) : 0,
			'label' => $googlepay_gateway ? $googlepay_gateway->get_option( 'fee_reason' ) : '',
		),
		'btcpay' => array(
			'enabled' => $btcpay_gateway ? $btcpay_gateway->get_option( 'fees_enabled' ) === 'yes' : false,
			'type' => $btcpay_gateway ? $btcpay_gateway->get_option( 'fee_type' ) : 'fixed',
			'amount' => $btcpay_gateway ? floatval( $btcpay_gateway->get_option( 'fee_amount' ) ) : 0,
			'label' => $btcpay_gateway ? $btcpay_gateway->get_option( 'fee_reason' ) : '',
		),
	);

	// Get cart total for fee calculations (subtotal - discount to include coupon discounts)
	$cart_total = WC()->cart ? WC()->cart->get_subtotal() - WC()->cart->get_discount_total() : 0;
	
	$feature_list['peachpay_convesiopay_gateways'] = array(
		'enabled'  => (bool) PeachPay_ConvesioPay_Integration::connected(),
		'metadata' => array(
			'api_key'   => $config['api_key'] ?? '',
			'client_key' => $config['client_key'] ?? '',
			'api_url'   => $config['api_url'] ?? 'https://api.convesiopay.com',
			'environment' => peachpay_is_test_mode() ? 'test' : 'live',
			'nonce' => wp_create_nonce('peachpay_convesiopay_nonce'),
			'integration_name' => $config['integration_name'] ?? '',
			'active_methods' => $active_methods,
			'fee_config' => $fee_config,
			'cart_total' => floatval( $cart_total ),
		),
	);

	$feature_list['peachpay_convesiopay_card_gateway'] = array(
		'enabled'  => (bool) PeachPay_ConvesioPay_Integration::is_capable( 'card' ),
		'metadata' => array(
			'title' => __( 'Card', 'peachpay-for-woocommerce' ),
		),
	);

	$feature_list['peachpay_convesiopay_applepay_gateway'] = array(
		'enabled'  => (bool) PeachPay_ConvesioPay_Integration::is_capable( 'applepay' ),
		'metadata' => array(
			'title' => __( 'Apple Pay', 'peachpay-for-woocommerce' ),
		),
	);

	$feature_list['peachpay_convesiopay_googlepay_gateway'] = array(
		'enabled'  => (bool) PeachPay_ConvesioPay_Integration::is_capable( 'googlepay' ),
		'metadata' => array(
			'title' => __( 'Google Pay', 'peachpay-for-woocommerce' ),
		),
	);

	$feature_list['peachpay_convesiopay_btcpay_gateway'] = array(
		'enabled'  => (bool) PeachPay_ConvesioPay_Integration::is_capable( 'btcpay' ),
		'metadata' => array(
			'title' => __( 'Crypto', 'peachpay-for-woocommerce' ),
		),
	);

	return $feature_list;
}

/**
 * Get ConvesioPay feature flags for frontend.
 *
 * @return array
 */
function peachpay_convesiopay_feature_flags() {
	return array(
		'peachpay_convesiopay_gateways' => PeachPay_ConvesioPay_Integration::connected(),
		'peachpay_convesiopay_card_gateway' => PeachPay_ConvesioPay_Integration::is_capable( 'card' ),
		'peachpay_convesiopay_applepay_gateway' => PeachPay_ConvesioPay_Integration::is_capable( 'applepay' ),
		'peachpay_convesiopay_googlepay_gateway' => PeachPay_ConvesioPay_Integration::is_capable( 'googlepay' ),
		'peachpay_convesiopay_btcpay_gateway' => PeachPay_ConvesioPay_Integration::is_capable( 'btcpay' ),
	);
}

/**
 * Handle ConvesioPay admin actions.
 *
 * @param string $action The action to handle.
 */
function peachpay_convesiopay_handle_admin_actions( $action ) {
	// Handle ConvesioPay-specific admin actions
	if ( strpos( $action, 'convesiopay' ) !== false ) {
		// Add any ConvesioPay-specific admin action handling here
		return;
	}
}

/**
 * Whether the address has all required ConvesioPay parameters populated.
 *
 * Addresses are optional in the API, but when included, all required
 * parameters must be populated. `stateOrProvince` is only required for
 * countries where downstream PSP routing requires it today (US and CA).
 *
 * @param array<string, string>|null $address Address in ConvesioPay format.
 * @return bool True if all required fields are non-empty; false otherwise.
 */
function peachpay_convesiopay_is_complete_address( $address ) {
	if ( ! is_array( $address ) ) {
		return false;
	}

	$required = array( 'houseNumberOrName', 'street', 'city', 'postalCode', 'country' );
	$country  = strtoupper( trim( (string) ( $address['country'] ?? '' ) ) );
	if ( in_array( $country, array( 'US', 'CA' ), true ) ) {
		$required[] = 'stateOrProvince';
	}

	foreach ( $required as $key ) {
		if ( ! isset( $address[ $key ] ) || trim( (string) $address[ $key ] ) === '' ) {
			return false;
		}
	}

	return true;
}

/**
 * Parse WooCommerce address line 1 into ConvesioPay street fields.
 *
 * If a token contains digits, use the first such token as houseNumberOrName.
 * Otherwise, use the first token. The remaining tokens become the street name.
 *
 * @param string $address_line_1 WooCommerce address line 1.
 * @return array<string, string>
 */
function peachpay_convesiopay_parse_address_line_1( $address_line_1 ) {
	$normalized_address = trim( preg_replace( '/\s+/', ' ', (string) $address_line_1 ) );
	if ( '' === $normalized_address ) {
		return array(
			'houseNumberOrName' => '',
			'street'            => '',
		);
	}

	$tokens = preg_split( '/\s+/', $normalized_address );
	if ( empty( $tokens ) ) {
		return array(
			'houseNumberOrName' => '',
			'street'            => '',
		);
	}

	$house_number_index = 0;
	foreach ( $tokens as $index => $token ) {
		if ( preg_match( '/\d/', $token ) ) {
			$house_number_index = $index;
			break;
		}
	}

	$house_number_or_name = $tokens[ $house_number_index ];
	unset( $tokens[ $house_number_index ] );

	return array(
		'houseNumberOrName' => $house_number_or_name,
		'street'            => trim( implode( ' ', $tokens ) ),
	);
}

/**
 * Build a ConvesioPay address from WooCommerce address fields.
 *
 * WooCommerce commonly stores house number and street together in address line 1,
 * while address line 2 is usually apartment/suite data. ConvesioPay expects line 1
 * to be split into houseNumberOrName and street.
 *
 * @param string $address_line_1 WooCommerce address line 1.
 * @param string $address_line_2 WooCommerce address line 2.
 * @param string $city Billing/shipping city.
 * @param string $state Billing/shipping state or province.
 * @param string $postal_code Billing/shipping postal code.
 * @param string $country Billing/shipping ISO country code.
 * @return array<string, string>|null
 */
function peachpay_convesiopay_build_address( $address_line_1, $address_line_2, $city, $state, $postal_code, $country ) {
	$parsed_address = peachpay_convesiopay_parse_address_line_1( $address_line_1 );
	$normalized_address_line_1 = trim( preg_replace( '/\s+/', ' ', (string) $address_line_1 ) );
	$normalized_address_line_2 = trim( preg_replace( '/\s+/', ' ', (string) $address_line_2 ) );

	if ( '' !== $normalized_address_line_2 ) {
		$parsed_address['houseNumberOrName'] = $normalized_address_line_2;
		$parsed_address['street']            = $normalized_address_line_1;
	}

	$address = array(
		'houseNumberOrName' => $parsed_address['houseNumberOrName'],
		'street'            => $parsed_address['street'],
		'city'              => $city,
		'stateOrProvince'   => $state,
		'postalCode'        => $postal_code,
		'country'           => $country,
	);

	if ( ! peachpay_convesiopay_is_complete_address( $address ) ) {
		return null;
	}

	return $address;
}