<?php

/**
 * NMI Blocks Support Class
 *
 * @package PeachPay
 */

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

/**
 * Add data-attributes to Collect.js script tag
 *
 * @param string $tag The script tag HTML
 * @param string $handle The script handle
 * @return string Modified script tag
 */
function nmi_add_collect_js_tokenization_key($tag, $handle)
{
	if ($handle === 'nmi-collect-js' && isset($GLOBALS['nmi_collect_js_tokenization_key'])) {
		$tokenization_key = trim($GLOBALS['nmi_collect_js_tokenization_key']);

		// Validate the key is not empty
		if (empty($tokenization_key)) {
			return $tag;
		}

		if (strpos($tag, '<script') !== false) {
			// Check if the attribute already exists
			if (strpos($tag, 'data-tokenization-key') === false) {
				$tag = str_replace(
					'<script ',
					'<script 
					data-tokenization-key="' . esc_attr($tokenization_key) . '" 
					data-variant="inline"
					data-field-ccnumber-placeholder="**** **** **** ****"
					data-field-ccexp-placeholder="MM / YY"
					data-field-cvv-placeholder="CVV"',
					$tag
				);
			}
		}
	}

	return $tag;
}

/**
 * NMI Blocks Support Class
 */
class NMI_Blocks_Support extends \Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType
{
	/**
	 * Payment method name
	 */
	protected $name = 'peachpay_nmi_card';

	/**
	 * Initialize the payment method type
	 */
	public function initialize()
	{
		$this->settings = get_option('woocommerce_peachpay_nmi_card_settings', []);
	}

	/**
	 * Check if this is a Blocks checkout
	 *
	 * @return bool
	 */
	private function is_blocks_checkout()
	{
		// Check if WooCommerce Blocks is active and we're in a blocks context
		return class_exists('Automattic\WooCommerce\Blocks\Package');
	}

	/**
	 * Check if public tokenization key exists
	 *
	 * @return bool
	 */
	private function has_public_tokenization_key()
	{
		$public_key = $this->settings['public_tokenization_key'] ?? '';
		return !empty($public_key);
	}

	/**
	 * Returns if this payment method should be active
	 */
	public function is_active()
	{
		// Check if gateway exists
		if (! function_exists('WC') || ! WC()->payment_gateways) {
			return false;
		}

		$all_gateways = WC()->payment_gateways()->payment_gateways();
		$gateway = $all_gateways['peachpay_nmi_card'] ?? null;

		if (! $gateway) {
			return false;
		}

		// Check if gateway is enabled
		$enabled_option = $gateway->get_option('enabled', 'no');
		$enabled_property = $gateway->enabled ?? 'no';

		if ($enabled_option !== 'yes' && $enabled_property !== 'yes') {
			return false;
		}

		// Support both Collect.js AND Direct Post for Blocks
		$active_api_tab = $gateway->get_option('active_api_tab', 'collectjs');
		$private_key = $gateway->get_option('private_key', '');
		$public_key = $gateway->get_option('public_tokenization_key', '');

		// For Direct Post, require private key
		if ($active_api_tab === 'directapi') {
			return ! empty($private_key);
		}

		// For Collect.js, require public tokenization key
		return ! empty($public_key);
	}

	/**
	 * Returns an array of scripts/handles to be registered for this payment method
	 */
	public function get_payment_method_script_handles()
	{
		$script_path = '/core/payments/nmi/assets/js/blocks.js';

		// Define dependencies for blocks.js
		$dependencies = array(
			'wc-blocks-registry',
			'wc-settings',
			'wp-element',
			'wp-html-entities',
			'wp-i18n',
		);

		// Get gateway for accurate settings (don't rely on cached $this->settings)
		$gateway = null;
		if (function_exists('WC') && WC()->payment_gateways()) {
			$all_gateways = WC()->payment_gateways()->payment_gateways();
			$gateway = $all_gateways['peachpay_nmi_card'] ?? null;
		}

		// Get active mode from gateway directly
		$active_api_tab = $gateway ? $gateway->get_option('active_api_tab', 'collectjs') : ($this->settings['active_api_tab'] ?? 'collectjs');
		$is_direct_post = ($active_api_tab === 'directapi');
		$public_tokenization_key = $gateway ? $gateway->get_option('public_tokenization_key', '') : '';

		// Only load Collect.js for Collect.js mode (NEVER for Direct Post)
		if (! $is_direct_post && ! empty($public_tokenization_key)) {
			$collect_js_url = PeachPay_NMI_Integration::get_collect_js_url();
			wp_register_script(
				'nmi-collect-js',
				$collect_js_url,
				array(),
				'1.0.0',
				true
			);

			$GLOBALS['nmi_collect_js_tokenization_key'] = trim($public_tokenization_key);

			// Add filter only once
			if (! has_filter('script_loader_tag', 'nmi_add_collect_js_tokenization_key')) {
				add_filter('script_loader_tag', 'nmi_add_collect_js_tokenization_key', 10, 2);
			}

			// Enqueue the script
			wp_enqueue_script('nmi-collect-js');

			// Add Collect.js as dependency
			$dependencies[] = 'nmi-collect-js';
		}

		// Register blocks.js script (works for both Collect.js AND Direct Post)
		wp_register_script(
			'wc-nmi-blocks-integration',
			plugins_url('peachpay-for-woocommerce' . $script_path),
			$dependencies,
			'1.1.9',
			true
		);

		return ['wc-nmi-blocks-integration'];
	}

	/**
	 * Returns an array of key=>value pairs of data made available to the payment methods script
	 */
	public function get_payment_method_data()
	{
		$gateway = WC()->payment_gateways()->get_available_payment_gateways()['peachpay_nmi_card'] ?? null;

		// Get NMI configuration
		$config = PeachPay_NMI_Integration::config();
		$public_tokenization_key = '';
		$active_api_tab = 'collectjs';

		if ($gateway) {
			$public_tokenization_key = $gateway->get_option('public_tokenization_key', '');
			$active_api_tab = $gateway->get_option('active_api_tab', 'collectjs');
		}

		// Determine if Direct Post mode
		$is_direct_post = ($active_api_tab === 'directapi');

		// Add AJAX configuration for transaction creation
		// Note: Private key is NOT exposed to frontend - only server-side use
		// IMPORTANT: Do NOT pass tokenization key if in Direct Post mode
		$ajax_config = array(
			'ajax_url'               => admin_url( 'admin-ajax.php' ),
			'create_transaction_url' => WC_AJAX::get_endpoint( 'pp-create-transaction' ),
			'nonce'                  => wp_create_nonce( 'peachpay_nmi_nonce' ),
			'publicTokenizationKey'  => $is_direct_post ? '' : $public_tokenization_key,
		);

		return [
			'title' => $gateway ? $gateway->get_option('title', $gateway->get_title()) : __('NMI Card', 'peachpay-for-woocommerce'),
			'description' => $gateway ? $gateway->get_option('description') : '',
			'supports' => $gateway ? array_filter($gateway->supports, [$gateway, 'supports']) : [],
			'is_blocks' => true,
			'isDirectPost' => $is_direct_post,
			'ajax_config' => $ajax_config,
			'publicTokenizationKey' => $is_direct_post ? '' : $public_tokenization_key,
		];
	}
}
