<?php

/**
 * PeachPay NMI Connect
 *
 * @package PeachPay
 */

defined('PEACHPAY_ABSPATH') || exit;

// Get settings from database
$option_name = 'woocommerce_peachpay_nmi_card_settings';
$settings = get_option($option_name, array());

// Get gateway instance if available
if (function_exists('WC') && WC()->payment_gateways) {
	$gateways = WC()->payment_gateways->payment_gateways();
	$nmi_gateway = isset($gateways['peachpay_nmi_card']) ? $gateways['peachpay_nmi_card'] : null;

	// Merge with gateway settings if available
	if ($nmi_gateway && isset($nmi_gateway->settings) && is_array($nmi_gateway->settings)) {
		$settings = array_merge($settings, $nmi_gateway->settings);
	}
}

// Extract settings with defaults
$enabled = isset($settings['enabled']) ? $settings['enabled'] : 'no';
// Normalize enabled value - WooCommerce uses 'yes'/'no', but can also be 1/0
if ($enabled === '1' || $enabled === 1 || $enabled === true || $enabled === 'yes') {
	$enabled = 'yes';
} else {
	$enabled = 'no';
}
$is_enabled = $enabled === 'yes';
$title = isset($settings['title']) ? $settings['title'] : 'Credit card (NMI)';
$description = isset($settings['description']) ? $settings['description'] : 'Pay with your credit card via NMI.';
$test_mode = isset($settings['test_mode']) ? $settings['test_mode'] : 'no';
$gateway_domain = get_option('nmi_gateway_domain', '');
$gateway_domain_display = $gateway_domain ? $gateway_domain : PeachPay_NMI_Integration::CONVESIO_GATEWAY_DOMAIN;
$private_key = isset($settings['private_key']) ? $settings['private_key'] : '';
$public_tokenization_key = isset($settings['public_tokenization_key']) ? $settings['public_tokenization_key'] : '';
$capture_immediately = isset($settings['capture_immediately']) ? $settings['capture_immediately'] : 'yes';
$receipt = isset($settings['receipt']) ? $settings['receipt'] : 'no';
$active_api_tab = isset($settings['active_api_tab']) ? $settings['active_api_tab'] : 'collectjs';
$tutorial_url = 'https://www.notion.so/peachpay/Connecting-NMI-7285284292a5807483505512c0060832';
?>

<div class="nmi-box flex-row payment-provider-header <?php echo esc_attr(peachpay_nmi_connected() ? 'is-connected' : ''); ?>">

	<form method="post" action="" id="nmi-gateway-settings-form" class="nmi-settings-form ">
		<div class="flex-row">
			<div class="flex-col gap-12 flex w-80">
				<div class="flex-row gap-12 ai-center provider-title h-fit">
					<img src="<?php echo esc_attr(peachpay_url('public/img/marks/nmi/nmi.png')); ?>" />
					<?php echo esc_html_e('NMI Account', 'peachpay-for-woocommerce'); ?>
				</div>

				<div class="flex-col provider-description nmi-provider-description <?php echo $is_enabled ? 'hidden' : ''; ?>">
					<p>
						<span><?php esc_html_e('Not sure if NMI is right for you?', 'peachpay-for-woocommerce'); ?></span>
						<span><?php esc_html_e('NMI is a great fit for online merchants who want a flexible gateway with broad integration options and risk controls.', 'peachpay-for-woocommerce'); ?></span>
						<span><?php esc_html_e('With NMI you can securely accept card payments through PeachPay.', 'peachpay-for-woocommerce'); ?></span>
					</p>
				</div>
			</div>

			<div class="flex-col gap-12 ai-center buttons-container w-20">
				<div class="pp-switch-section">
					<div>
						<label class="pp-switch">
							<input type="checkbox" name="nmi_enabled" id="nmi-enabled-toggle" value="1" <?php checked($is_enabled, true); ?>>
							<span class="pp-slider round"></span>
						</label>
					</div>
					<div>
						<label class="pp-setting-label" for="nmi-enabled-toggle">Enable NMI</label>
					</div>
				</div>
				<span class="nmi-tutorial-link <?php echo $is_enabled ? 'hidden' : ''; ?>">
					<?php echo peachpay_build_read_tutorial_section($tutorial_url); ?>
				</span>
			</div>
		</div>
		<div>
			<div class="nmi-gateway-settings" style="<?php echo $is_enabled ? '' : 'display: none;'; ?>">
				<h2>Gateway Settings</h2>

				<?php wp_nonce_field('nmi_gateway_settings', 'nmi_gateway_settings_nonce'); ?>
				<input type="hidden" id="nmi_active_api_tab" name="nmi_active_api_tab" value="<?php echo esc_attr($active_api_tab); ?>">

				<div class="nmi-form-field">
					<label for="nmi_title">Title</label>
					<input type="text" id="nmi_title" name="nmi_title" value="<?php echo esc_attr($title); ?>">
					<br>
					<small>This controls the title which the user sees during checkout.</small>
				</div>

				<!-- Description -->
				<div class="nmi-form-field">
					<label for="nmi_description">Description</label>
					<textarea id="nmi_description" name="nmi_description" rows="3" style="width: 100%;"><?php echo esc_textarea($description); ?></textarea>
					<small>This controls the description which the user sees during checkout.</small>
				</div>

				<!-- API Keys Section -->
				<h2>API Keys</h2>

				<div class="nmi-form-field">
					<label for="nmi_gateway_domain"><?php esc_html_e('NMI Gateway Domain', 'peachpay-for-woocommerce'); ?> <span style="color: #dc2626;">*</span></label>
					<input type="text" id="nmi_gateway_domain" name="nmi_gateway_domain" value="<?php echo esc_attr($gateway_domain_display); ?>" placeholder="<?php echo esc_attr(PeachPay_NMI_Integration::CONVESIO_GATEWAY_DOMAIN); ?>" autocomplete="off">
					<br>
					<small><?php esc_html_e('Enter your full NMI gateway domain (without https://). Example: convesio.transactiongateway.com', 'peachpay-for-woocommerce'); ?></small>
				</div>

				<!-- Private Key (Always Required) -->
				<div class="nmi-form-field">
					<label for="nmi_private_key">Private Key (Security Key) <span style="color: #dc2626;">*</span></label>
					<input type="password" id="nmi_private_key" name="nmi_private_key" value="<?php echo esc_attr($private_key); ?>">
					<br>
					<small>Required for BOTH Collect.js and Direct Post. Used for server-side API authentication. Make sure this key has "API" permission enabled in your NMI account.</small>
				</div>

				<!-- Integration Method Selection -->
				<h3 style="margin-top: 20px;">Integration Method</h3>
				<div class="nmi-api-tabs">
					<button type="button" class="nmi-tab-button <?php echo $active_api_tab === 'collectjs' ? 'active' : ''; ?>" data-tab="collectjs">Collect.js (Recommended)</button>
					<button type="button" class="nmi-tab-button <?php echo $active_api_tab === 'directapi' ? 'active' : ''; ?>" data-tab="directapi">Direct Post</button>
				</div>

				<!-- Tab Content -->
				<div class="nmi-tab-content">
					<!-- Collect.js Tab -->
					<div class="nmi-tab-panel <?php echo $active_api_tab === 'collectjs' ? 'active' : ''; ?>" id="collectjs-panel">
						<div class="nmi-form-field">
							<label for="nmi_public_tokenization_key">Public Tokenization Key <span style="color: #dc2626;">*</span></label>
							<input type="text" id="nmi_public_tokenization_key" name="nmi_public_tokenization_key" value="<?php echo esc_attr($public_tokenization_key); ?>">
							<br>
							<small>Required for Collect.js. Enables PCI-compliant card tokenization in the browser. This is the recommended method for secure payment processing.</small>
						</div>
					</div>

					<!-- Direct Post Tab -->
					<div class="nmi-tab-panel <?php echo $active_api_tab === 'directapi' ? 'active' : ''; ?>" id="directapi-panel">
						<p style="color: #666; font-style: italic;">
							<?php esc_html_e('Direct Post sends card data directly to NMI servers. Only the Private Key above is required for this method.', 'peachpay-for-woocommerce'); ?>
						</p>
					</div>
				</div>

			</div>

			<button type="submit" name="save_nmi_gateway_settings" class="button-primary-filled-medium" style="<?php echo $enabled === 'yes' || $is_enabled == true || $enabled == 1 || $enabled == '1' ? '' : 'display: none;'; ?>">Save Settings</button>
		</div>
	</form>
</div>

<div class="nmi-provider-description">
	<span>
		<span><?php esc_html_e('Learn more about', 'peachpay-for-woocommerce'); ?> </span>
		<a href="https://www.nmi.com/products/nmi-payments/" target="_blank"><?php esc_html_e('payment methods', 'peachpay-for-woocommerce'); ?></a>
		<span> <?php esc_html_e('powered by NMI', 'peachpay-for-woocommerce'); ?> </span>
	</span>
</div>

<script>
	// Localize nonce for AJAX requests
	var peachpay_nmi_admin = {
		ajax_url: '<?php echo esc_js(admin_url('admin-ajax.php')); ?>',
		nonce: '<?php echo esc_js(wp_create_nonce('peachpay_admin_nonce')); ?>'
	};

	jQuery(document).ready(function($) {
		// Toggle enabled state - only show/hide settings, save happens on form submit
		$('#nmi-enabled-toggle').on('change', function() {
			var isEnabled = $(this).is(':checked');
			var $settingsContainer = $('.nmi-gateway-settings');
			var $submitButton = $('button[name="save_nmi_gateway_settings"]');
			var $providerDescription = $('.nmi-provider-description');
			var $tutorialLink = $('.nmi-tutorial-link');

			// Show/hide settings container and submit button with animation
			if (isEnabled) {
				$settingsContainer.slideDown(300);
				$submitButton.css('margin-top', '0px');
				$providerDescription.addClass('hidden');
				$tutorialLink.addClass('hidden');
			} else {
				$settingsContainer.slideUp(300);
				$submitButton.css('margin-top', '20px');
				$providerDescription.removeClass('hidden');
				$tutorialLink.removeClass('hidden');
			}

			if (isEnabled || <?php echo esc_js($enabled === 'yes') ? 'true' : 'false'; ?>) {
				$submitButton.show();
			} else {
				$submitButton.hide();
			}

		});

		// Tab switching functionality
		$('.nmi-tab-button').on('click', function() {
			var tab = $(this).data('tab');

			// Remove active class from all tabs and panels
			$('.nmi-tab-button').removeClass('active');
			$('.nmi-tab-panel').removeClass('active');

			// Add active class to clicked tab and corresponding panel
			$(this).addClass('active');
			$('#' + tab + '-panel').addClass('active');

			// Update hidden field with active tab
			$('#nmi_active_api_tab').val(tab);
		});

		$('#nmi-gateway-settings-form').on('submit', function(e) {
			e.preventDefault();

			// Build form data manually to ensure all fields are included
			var formData = new FormData(this);
			formData.append('action', 'save_nmi_gateway_settings');

			// Add enabled toggle value (checkbox won't be in FormData if unchecked)
			var isEnabled = $('#nmi-enabled-toggle').is(':checked');
			formData.set('nmi_enabled', isEnabled ? 1 : 0);

			// Show loading state
			var submitBtn = $(this).find('button[type="submit"]');
			var originalText = submitBtn.text();
			submitBtn.prop('disabled', true).text('<?php echo esc_js(__('Saving...', 'peachpay-for-woocommerce')); ?>');
			window.PeachPayAdminNotices?.show('info', 'saving-changes', '<?php echo esc_js(__('Saving NMI settings...', 'peachpay-for-woocommerce')); ?>');

			// Use FormData for better handling of all input types
			$.ajax({
				url: ajaxurl,
				type: 'POST',
				data: formData,
				processData: false,
				contentType: false,
				success: function(response) {
					if (response.success) {
						window.PeachPayAdminNotices?.show('success', 'saved-changes', response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('NMI settings saved successfully!', 'peachpay-for-woocommerce')); ?>');

						// Reload page after 1 second to reflect changes
						setTimeout(function() {
							window.location.reload();
						}, 1000);
					} else {
						submitBtn.prop('disabled', false).text(originalText);
						console.error('NMI Settings Save Error:', response);
						window.PeachPayAdminNotices?.show('error', 'error', response && response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('Unable to save NMI settings. Please review the form and try again.', 'peachpay-for-woocommerce')); ?>', true);
					}
				},
				error: function(xhr, status, error) {
					submitBtn.prop('disabled', false).text(originalText);
					console.error('NMI Settings Save Error:', status, error, xhr.responseText);
					window.PeachPayAdminNotices?.show('error', 'error', xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message ? xhr.responseJSON.data.message : '<?php echo esc_js(__('Unable to save NMI settings right now. Please try again.', 'peachpay-for-woocommerce')); ?>', true);
				}
			});
		});
	});
</script>