<?php

/**
 * PeachPay NMI Payment extension.
 *
 * @package PeachPay
 */

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

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

/**
 * NMI Integration class.
 */
final class PeachPay_NMI_Integration
{
	use PeachPay_Payment_Integration;

	/**
	 * 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/nmi/hooks.php';
		require_once PEACHPAY_ABSPATH . 'core/payments/nmi/functions.php';
		require_once PEACHPAY_ABSPATH . 'core/payments/nmi/includes/peachpay-functions.php';
		require_once PEACHPAY_ABSPATH . 'core/payments/nmi/includes/class-peachpay-nmi-direct-post.php';

		// Include and initialize webhook handler
		// require_once PEACHPAY_ABSPATH . 'core/payments/nmi/routes/class-peachpay-nmi-webhook.php';
		// new PeachPay_NMI_Webhook();

		if (is_admin()) {
			require_once PEACHPAY_ABSPATH . 'core/payments/nmi/admin/class-peachpay-admin-nmi-integration.php';
			//require_once PEACHPAY_ABSPATH . 'core/payments/nmi/admin/class-peachpay-nmi-manual-capture.php';

			// Initialize admin integration to register AJAX handlers
			PeachPay_Admin_NMI_Integration::instance();

			wp_enqueue_style(
				'peachpay-nmi-admin-style',
				peachpay_url('core/payments/nmi/admin/assets/css/admin.css'),
				[],
				'1.1.9'
			);
		}
	}

	/**
	 * 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/nmi/gateways/class-peachpay-nmi-card-gateway.php';

		// Add NMI gateways
		$this->payment_gateways[] = 'PeachPay_NMI_Card_Gateway';
	}

	/**
	 * Check if a gateway ID belongs to NMI.
	 *
	 * @param string $gateway_id The gateway ID to check.
	 * @return boolean
	 */
	public static function is_payment_gateway($gateway_id)
	{
		$nmi_gateways = array('peachpay_nmi_card');
		return in_array($gateway_id, $nmi_gateways, true) || strpos($gateway_id, 'peachpay_nmi_') === 0;
	}

	/**
	 * Ensure the NMI card gateway is always enabled when connected.
	 */
	private static function ensure_unified_gateway_enabled()
	{
		$option_name = 'woocommerce_peachpay_nmi_card_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 NMI configuration.
	 *
	 * @return array
	 */
	public static function config()
	{
		return get_option('peachpay_connected_nmi_config', array());
	}

	/**
	 * Get NMI Private Key (Security Key).
	 *
	 * @return string
	 */
	public static function private_key()
	{
		$config = self::config();
		return $config['private_key'] ?? '';
	}

	/**
	 * Get NMI Public Tokenization Key (for Collect.js).
	 *
	 * @return string
	 */
	public static function public_tokenization_key()
	{
		$config = self::config();
		return $config['public_tokenization_key'] ?? '';
	}

	/**
	 * Convesio default gateway domain (used as default for Collect.js when nmi_gateway_domain is empty).
	 */
	const CONVESIO_GATEWAY_DOMAIN = 'convesio.transactiongateway.com';

	/**
	 * Secure gateway domain used for Direct Post transactions.
	 */
	const SECURE_GATEWAY_DOMAIN = 'secure.transactiongateway.com';

	/**
	 * Get NMI Gateway Domain for Collect.js only.
	 * Uses nmi_gateway_domain when set; otherwise defaults to Convesio.
	 *
	 * @return string Domain without https://
	 */
	public static function gateway_domain()
	{
		$domain = get_option( 'nmi_gateway_domain', '' );
		$domain = trim( sanitize_text_field( $domain ) );
		if ( '' !== $domain ) {
			return self::sanitize_gateway_domain( $domain );
		}
		return self::CONVESIO_GATEWAY_DOMAIN;
	}

	/**
	 * Sanitize gateway domain: remove protocol, trailing slashes, path.
	 *
	 * @param string $domain Raw domain input.
	 * @return string Sanitized domain.
	 */
	public static function sanitize_gateway_domain( $domain )
	{
		$domain = preg_replace( '#^https?://#i', '', $domain );
		$domain = preg_replace( '#/.*$#', '', $domain );
		return trim( $domain, " \t\n\r\0\x0B/" );
	}

	/**
	 * Get Collect.js URL. Uses nmi_gateway_domain (default: Convesio).
	 * Only used when Collect.js mode is active.
	 *
	 * @return string
	 */
	public static function get_collect_js_url()
	{
		$domain = self::gateway_domain();
		return "https://{$domain}/token/Collect.js";
	}

	/**
	 * Get NMI API transact endpoint URL.
	 *
	 * @param bool $for_direct_post If true, use Secure gateway. If false, use nmi_gateway_domain (Collect.js).
	 * @return string
	 */
	public static function get_api_endpoint()
	{
		$domain = self::gateway_domain();
		return "https://{$domain}/api/transact.php";
	}

	/**
	 * Check if NMI is capable of a specific payment method.
	 *
	 * @param string $payment_key The payment method key.
	 * @return boolean
	 */
	public static function is_capable($payment_key)
	{
		$capabilities = array(
			'card' => true,
		);

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

	/**
	 * Check if a specific NMI WooCommerce gateway is enabled.
	 *
	 * @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);
	}

	/**
	 * Get NMI mode (test or live).
	 *
	 * @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 NMI 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 NMI admin settings section.
	 */
	public function add_payment_setting_section()
	{
		add_settings_field(
			'peachpay_nmi_setting',
			null,
			array('PeachPay_Admin_NMI_Integration', 'do_admin_page'),
			'peachpay',
			'peachpay_payment_settings_section',
			array('class' => 'pp-header pp-sub-nav-nmi no-border-bottom')
		);
	}

	/**
	 * Callback for registering PeachPay NMI payment method support for WooCommerce blocks.
	 */
	protected function woocommerce_blocks_loaded()
	{
		// Register blocks support for BOTH Collect.js AND Direct Post modes
		$card_blocks_support_file = PEACHPAY_ABSPATH . 'core/payments/nmi/includes/class-nmi-blocks-support.php';

		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 NMI_Blocks_Support());
				}
			);
		}
	}
}

PeachPay_NMI_Integration::instance();
