<?php
/**
 * PeachPay ConvesioPay Payment extension.
 *
 * @package PeachPay
 */

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

require_once PEACHPAY_ABSPATH . 'core/traits/trait-peachpay-payment-integration.php';

/**
 * ConvesioPay Integration class.
 */
final class PeachPay_ConvesioPay_Integration {
	use PeachPay_Payment_Integration;

	/**
	 * Cached decrypted config for the current request (avoids repeated decryption during checkout).
	 *
	 * @var array|null
	 */
	private static $config_cache = null;

	/**
	 * Should the extension load?
	 */
	public static function should_load() {
		// Re-enabled for admin tab testing
		return true;
	}

	/**
	 * Is the integration enabled?
	 */
	public static function enabled() {
		return true;
	}

	/**
	 * Load required files and set up hooks.
	 *
	 * @param boolean $enabled If the extension is enabled.
	 */
	private function includes( $enabled ) {
		require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/hooks.php';
		require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/functions.php';
		require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/includes/peachpay-functions.php';

		// Include customer token store for card manager
		require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/includes/class-peachpay-convesiopay-customer-token-store.php';
		require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/includes/class-peachpay-convesiopay-subscription-migrator.php';

		// Include and initialize webhook handler (payment + paymentMethods)
		require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/routes/class-peachpay-convesiopay-webhook-payment-methods.php';
		require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/routes/class-peachpay-convesiopay-webhook.php';
		require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/routes/class-peachpay-convesiopay-accelerated-checkout.php';
		require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/includes/class-peachpay-convesiopay-accelerated-checkout-element.php';
		new PeachPay_ConvesioPay_Webhook();
		new PeachPay_ConvesioPay_Accelerated_Checkout();
		( new PeachPay_ConvesioPay_Accelerated_Checkout_Element() )->init();

		// Pending order reconciliation (background polling when webhook fails)
		require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/routes/class-peachpay-convesiopay-reconciliation.php';
		new PeachPay_ConvesioPay_Reconciliation();

		if ( is_admin() ) {
			require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/admin/class-peachpay-admin-convesiopay-integration.php';
			require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/admin/class-peachpay-convesiopay-manual-capture.php';
			require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/admin/class-peachpay-convesiopay-fetch-payment-status-manually.php';
		}
	}
	
	/**
	 * Initialize WooCommerce integration.
	 *
	 * @param boolean $enabled If the extension is enabled.
	 */
	private function woocommerce_init( $enabled ) {
		if ( ! $enabled ) {
			return;
		}

		// Load gateway files
		require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/gateways/trait-peachpay-convesiopay-subscription-renewal.php';
		require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/gateways/class-peachpay-convesiopay-unified-gateway.php';
		require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/gateways/class-peachpay-convesiopay-card-gateway.php';
		require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/gateways/class-peachpay-convesiopay-applepay-gateway.php';
		require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/gateways/class-peachpay-convesiopay-googlepay-gateway.php';
		require_once PEACHPAY_ABSPATH . 'core/payments/convesiopay/gateways/class-peachpay-convesiopay-btcpay-gateway.php';

		// Add unified gateway first, then individual gateways for backward compatibility
		$this->payment_gateways[] = 'PeachPay_ConvesioPay_Unified_Gateway';
		$this->payment_gateways[] = 'PeachPay_ConvesioPay_Card_Gateway';
		$this->payment_gateways[] = 'PeachPay_ConvesioPay_ApplePay_Gateway';
		$this->payment_gateways[] = 'PeachPay_ConvesioPay_GooglePay_Gateway';
		$this->payment_gateways[] = 'PeachPay_ConvesioPay_BTCPay_Gateway';
	}

	/**
	 * Check if a gateway ID belongs to ConvesioPay.
	 *
	 * @param string $gateway_id The gateway ID to check.
	 * @return boolean
	 */
	public static function is_payment_gateway( $gateway_id ) {
		$convesiopay_gateways = array(
			'peachpay_convesiopay_unified',
			'peachpay_convesiopay_card',
			'peachpay_convesiopay_applepay',
			'peachpay_convesiopay_googlepay',
			'peachpay_convesiopay_btcpay'
		);
		
		return in_array( $gateway_id, $convesiopay_gateways, true ) || strpos( $gateway_id, 'peachpay_convesiopay_' ) === 0;
	}

	/**
	 * Check if ConvesioPay is connected.
	 *
	 * @return boolean
	 */
	public static function connected() {
		// Check if ConvesioPay account is connected
		$account = get_option( 'peachpay_connected_convesiopay_account', false );
		$config = get_option( 'peachpay_connected_convesiopay_config', array() );

		// Both account and config must exist and not be empty
		$is_connected = !empty($account) && !empty($config) &&
		                isset($account['status']) && $account['status'] === 'connected';

		// If connected, ensure unified gateway is always enabled
		if ( $is_connected ) {
			self::ensure_unified_gateway_enabled();
		}

		return $is_connected;
	}

	/**
	 * Ensure the unified ConvesioPay gateway is always enabled when connected.
	 */
	private static function ensure_unified_gateway_enabled() {
		$option_name = 'woocommerce_peachpay_convesiopay_unified_settings';
		$gateway_settings = get_option( $option_name, array() );
		// Only update if not already enabled to avoid unnecessary database writes
		if ( ! isset( $gateway_settings['enabled'] ) || $gateway_settings['enabled'] !== 'yes' ) {
			$gateway_settings['enabled'] = 'yes';
			update_option( $option_name, $gateway_settings );
		}
	}

	/**
	 * Get ConvesioPay configuration.
	 * Cached per request to avoid repeated decryption during checkout (update_order_review).
	 *
	 * @return array
	 */
	public static function config() {
		if ( self::$config_cache !== null ) {
			return self::$config_cache;
		}

		// Use decrypted configuration from admin integration class if available
		if ( class_exists( 'PeachPay_Admin_ConvesioPay_Integration' ) ) {
			$config = PeachPay_Admin_ConvesioPay_Integration::get_decrypted_config();
		} else {
			// Fallback: decrypt manually when admin class not available (e.g., during checkout)
			$config = get_option( 'peachpay_connected_convesiopay_config', array() );

			// If config is encrypted, decrypt it manually
			if ( ! empty( $config ) && isset( $config['encrypted'] ) && $config['encrypted'] === true ) {
				$config = self::decrypt_config_fallback( $config );
			}
		}

		self::$config_cache = $config;
		return $config;
	}

	/**
	 * Get the merchant email from the connected ConvesioPay config.
	 *
	 * @return string
	 */
	public static function merchant_email() {
		$is_connected = self::connected();

		if ( ! $is_connected ) {
			return '';
		}

		$config = self::config();

		return $config['email'] ?? '';
	}

	/**
	 * Fallback method to decrypt config when admin class is not available
	 *
	 * @param array $config Encrypted configuration
	 * @return array Decrypted configuration
	 */
	private static function decrypt_config_fallback($config) {
		// Use the same encryption key logic as admin class
		$key = defined('AUTH_KEY') ? AUTH_KEY : 'fallback-key';
		$salt = defined('SECURE_AUTH_KEY') ? SECURE_AUTH_KEY : 'fallback-salt';
		$encryption_key = substr(hash('sha256', $key . $salt . 'convesiopay'), 0, 32);
		
		// Decrypt sensitive fields
		$decrypted_config = $config;
		
		if (isset($config['api_key'])) {
			$decrypted_config['api_key'] = self::decrypt_data_fallback($config['api_key'], $encryption_key);
		}
		
		if (isset($config['secret_key'])) {
			$decrypted_config['secret_key'] = self::decrypt_data_fallback($config['secret_key'], $encryption_key);
		}
		
		if (isset($config['client_key'])) {
			$decrypted_config['client_key'] = self::decrypt_data_fallback($config['client_key'], $encryption_key);
		}
		
		// Decrypt webhook signature key
		if (isset($config['webhook_data']['signature_key'])) {
			$decrypted_config['webhook_data']['signature_key'] = self::decrypt_data_fallback($config['webhook_data']['signature_key'], $encryption_key);
		}
		
		return $decrypted_config;
	}
	
	/**
	 * Fallback decrypt data method
	 *
	 * @param string $encrypted_data Base64 encoded encrypted data
	 * @param string $key Encryption key
	 * @return string Decrypted data or original if decryption fails
	 */
	private static function decrypt_data_fallback($encrypted_data, $key) {
		if (empty($encrypted_data)) {
			return $encrypted_data;
		}
		
		$data = base64_decode($encrypted_data);
		if ($data === false) {
			return $encrypted_data; // Return original if not base64
		}
		
		$iv = substr($data, 0, 16);
		$encrypted = substr($data, 16);
		
		$decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $key, 0, $iv);
		return $decrypted !== false ? $decrypted : $encrypted_data;
	}

	/**
	 * Get ConvesioPay connect ID.
	 *
	 * @return string
	 */
	public static function connect_id() {
		$config = self::config();
		return $config['client_id'] ?? '';
	}

	/**
	 * Get ConvesioPay public key.
	 *
	 * @return string
	 */
	public static function client_key() {
		$config = self::config();
		return $config['client_key'] ?? '';
	}

	/**
	 * Get ConvesioPay connect country.
	 *
	 * @return string
	 */
	public static function connect_country() {
		$config = self::config();
		return $config['country'] ?? 'US';
	}

	/**
	 * Check if ConvesioPay is capable of a specific payment method.
	 *
	 * @param string $payment_key The payment method key.
	 * @return boolean
	 */
	public static function is_capable( $payment_key ) {
		if ( ! self::connected() ) {
			return false;
		}

		$capabilities = array(
			'card'     => true,
			'applepay' => true,
			'googlepay' => true,
			'btcpay'   => true,
		);

		return isset( $capabilities[ $payment_key ] ) && $capabilities[ $payment_key ];
	}

	/**
	 * Check if a specific ConvesioPay WooCommerce gateway is enabled.
	 *
	 * This is used as the server-side source of truth for whether a
	 * payment method such as BTCPay should be allowed to process orders
	 * or create sessions/intents.
	 *
	 * @param string $gateway_id WooCommerce gateway ID.
	 * @return boolean
	 */
	public static function is_gateway_enabled( $gateway_id ) {
		if ( ! function_exists( 'WC' ) || ! WC()->payment_gateways ) {
			return false;
		}

		$gateways       = WC()->payment_gateways->payment_gateways();
		$target_gateway = $gateways[ $gateway_id ] ?? null;

		if ( ! $target_gateway ) {
			return false;
		}

		$enabled_option   = method_exists( $target_gateway, 'get_option' ) ? $target_gateway->get_option( 'enabled', 'no' ) : 'no';
		$enabled_property = isset( $target_gateway->enabled ) ? $target_gateway->enabled : 'no';

		return ( 'yes' === $enabled_option || 'yes' === $enabled_property );
	}

	/**
	 * Convenience wrapper: is BTCPay gateway enabled in WooCommerce.
	 *
	 * @return boolean
	 */
	public static function is_btcpay_enabled() {
		return self::is_gateway_enabled( 'peachpay_convesiopay_btcpay' );
	}

	/**
	 * Get ConvesioPay signup URL.
	 *
	 * @return string
	 */
	public static function signup_url() {
		return 'https://convesiopay.com/signup';
	}

	/**
	 * Get ConvesioPay mode.
	 *
	 * @param string $mode The mode to detect.
	 * @return string
	 */
	public static function mode( $mode = 'detect' ) {
		if ( 'detect' === $mode ) {
			return ( peachpay_is_test_mode() || peachpay_is_local_development_site() || peachpay_is_staging_site() ) ? 'test' : 'live';
		}

		return $mode;
	}

	/**
	 * Get available ConvesioPay payment gateways.
	 *
	 * @return array
	 */
	public static function get_payment_gateways() {
		$gateways = array();

		foreach ( WC()->payment_gateways->payment_gateways() as $gateway ) {
			if ( self::is_payment_gateway( $gateway->id ) ) {
				$gateways[] = $gateway;
			}
		}

		return $gateways;
	}

	/**
	 * Initialize REST API.
	 *
	 * @param boolean $enabled If the extension is enabled.
	 */
	private function rest_api_init( $enabled ) {
		if ( ! $enabled ) {
			return;
		}

		// Webhook class is now initialized in includes() method
	}

	/**
	 * Initialize plugins loaded hook.
	 *
	 * @param boolean $enabled If the extension is enabled.
	 */
	private function plugins_loaded( $enabled ) {
		if ( ! $enabled ) {
			return;
		}

		if ( is_admin() ) {
			add_action( 'peachpay_admin_add_payment_setting_section', array( $this, 'add_payment_setting_section' ) );
		}
	}

	/**
	 * Add ConvesioPay admin settings section.
	 */
	public function add_payment_setting_section() {
		add_settings_field(
			'peachpay_convesiopay_setting',
			null,
			array( 'PeachPay_Admin_ConvesioPay_Integration', 'do_admin_page' ),
			'peachpay',
			'peachpay_payment_settings_section',
			array( 'class' => 'pp-header pp-sub-nav-convesiopay no-border-bottom' )
		);
	}

	/**
	 * Callback for registering PeachPay ConvesioPay payment method support for WooCommerce blocks.
	 */
	protected function woocommerce_blocks_loaded() {
		
		// Check if blocks support class files exist
		$unified_blocks_support_file = PEACHPAY_ABSPATH . 'core/payments/convesiopay/includes/class-convesiopay-unified-blocks-support.php';
		$card_blocks_support_file = PEACHPAY_ABSPATH . 'core/payments/convesiopay/includes/class-convesiopay-blocks-support.php';
		$applepay_blocks_support_file = PEACHPAY_ABSPATH . 'core/payments/convesiopay/includes/class-convesiopay-applepay-blocks-support.php';
		$btcpay_blocks_support_file = PEACHPAY_ABSPATH . 'core/payments/convesiopay/includes/class-convesiopay-btcpay-blocks-support.php';
		
		// Register unified blocks support first
		if ( file_exists( $unified_blocks_support_file ) ) {
			require_once $unified_blocks_support_file;
			
			add_action(
				'woocommerce_blocks_payment_method_type_registration',
				function ( Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry ) {
					$payment_method_registry->register( new ConvesioPay_Unified_Blocks_Support() );
				}
			);
		}
		
		// Register individual blocks support for backward compatibility
		if ( file_exists( $card_blocks_support_file ) ) {
			require_once $card_blocks_support_file;
			
			add_action(
				'woocommerce_blocks_payment_method_type_registration',
				function ( Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry ) {
					$payment_method_registry->register( new ConvesioPay_Blocks_Support() );
				}
			);
		}
		
		if ( file_exists( $applepay_blocks_support_file ) ) {
			require_once $applepay_blocks_support_file;
			
			add_action(
				'woocommerce_blocks_payment_method_type_registration',
				function ( Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry ) {
					$payment_method_registry->register( new ConvesioPay_ApplePay_Blocks_Support() );
				}
			);
		}
		
		if ( file_exists( $btcpay_blocks_support_file ) ) {
			require_once $btcpay_blocks_support_file;
			
			add_action(
				'woocommerce_blocks_payment_method_type_registration',
				function ( Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry ) {
					$payment_method_registry->register( new ConvesioPay_BTCPay_Blocks_Support() );
				}
			);
		}
	}
}

PeachPay_ConvesioPay_Integration::instance();

 