<?php
/**
 * PeachPay Authnet Connect template.
 *
 * @package PeachPay
 */

defined( 'PEACHPAY_ABSPATH' ) || exit;

$mode         = PeachPay_Authnet_Credentials::current_mode();
$is_connected = PeachPay_Authnet_Integration::connected();
$is_enabled   = (bool) get_option( 'peachpay_authnet_enabled', false );
$is_configured = PeachPay_Authnet_Credentials::is_configured( $mode );

$section_title = 'test' === $mode
	? __( 'Sandbox Credentials', 'peachpay-for-woocommerce' )
	: __( 'Live Credentials', 'peachpay-for-woocommerce' );

$tutorial_url = 'https://support.authorize.net/knowledgebase/Knowledgearticle/?code=000001482';

?>
<style>
	.authnet-box,
	.authnet-gateway-settings {
		font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
	}

	.authnet-box .provider-title,
	.authnet-box .provider-description,
	.authnet-box .pp-setting-label,
	.authnet-gateway-settings h2,
	.authnet-gateway-settings th,
	.authnet-gateway-settings td,
	.authnet-gateway-settings label,
	.authnet-gateway-settings input,
	.authnet-gateway-settings p,
	.authnet-gateway-settings .description,
	.authnet-gateway-settings .account-info {
		font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
	}

	.authnet-box .button-primary-filled-medium {
		font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
	}

	.pp-admin-content-wrapper.section-authnet .peachpay-stripe-upgrade-notice {
		display: none !important;
	}

	.authnet-mode-section {
		margin-bottom: 28px;
	}

	.authnet-gateway-settings .notice {
		display: none !important;
	}

	.authnet-mode-section .authnet-form-field {
		display: block !important;
		margin-bottom: 18px;
	}

	.authnet-mode-section .authnet-form-field label {
		display: block !important;
		width: 100%;
		margin-bottom: 8px;
		font-size: 14px;
		font-weight: 600;
		color: #0d2743;
	}

	.authnet-mode-section .authnet-form-field input {
		display: block !important;
		width: 100%;
		max-width: 100%;
	}

	.authnet-mode-section .authnet-form-field .description {
		display: block;
		margin-top: 8px;
	}

	.authnet-save-row {
		margin-top: 6px;
	}

</style>
<div class="authnet-box payment-provider-header <?php echo esc_attr( $is_connected ? 'is-connected' : '' ); ?>">
	<div class="peachpay-notices-container"></div>

	<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/authnet/short.svg' ) ); ?>" />
				<?php esc_html_e( 'Authorize.net Account', 'peachpay-for-woocommerce' ); ?>
			</div>

			<div class="flex-col provider-description authnet-provider-description <?php echo $is_enabled ? 'hidden' : ''; ?>">
				<p><?php esc_html_e( 'Authorize.net is a credit card processor. Not sure if this one is right for you, or looking to switch? Authorize.net offers competitive transaction rates for stores selling more than $500K USD per year.', 'peachpay-for-woocommerce' ); ?></p>
				<div class="method-icons">
					<?php
					foreach ( PeachPay_Authnet_Integration::get_payment_gateways() as $gateway ) {
						$icon = $gateway->get_icon_url( 'small', 'color' );
						?>
						<span class="flex-row">
							<img src="<?php echo esc_attr( $icon ); ?>" alt="<?php echo esc_attr( $gateway->title ); ?>"/>
							<span class="gateway-title">
								<span><?php echo esc_html( $gateway->title ); ?></span>
								<span>,</span>
							</span>
						</span>
						<?php
					}
					?>
				</div>
			</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="authnet_enabled" id="authnet-enabled-toggle" value="1" <?php checked( $is_enabled, true ); ?>>
						<span class="pp-slider round"></span>
					</label>
				</div>
				<div>
					<label class="pp-setting-label" for="authnet-enabled-toggle"><?php esc_html_e( 'Enable Authorize.net', 'peachpay-for-woocommerce' ); ?></label>
				</div>
			</div>
			<span class="authnet-tutorial-link <?php echo $is_enabled ? 'hidden' : ''; ?>">
				<?php echo peachpay_build_read_tutorial_section( $tutorial_url ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			</span>
		</div>
	</div>

	<!-- Single credentials section for the active mode -->
	<div class="authnet-gateway-settings" style="<?php echo $is_enabled ? '' : 'display: none;'; ?>">

		<div class="authnet-mode-section">
			<h2><?php echo esc_html( $section_title ); ?></h2>

			<?php if ( $is_configured ) : ?>
				<div class="flex-col gap-12 connected-info">
					<div class="flex-row gap-8 ai-center connected-success">
						<?php
						if ( 'test' === $mode ) {
							esc_html_e( 'Your Authorize.net sandbox account is connected!', 'peachpay-for-woocommerce' );
						} else {
							esc_html_e( 'Your Authorize.net live account is connected!', 'peachpay-for-woocommerce' );
						}
						?>
						<img src="<?php echo esc_attr( peachpay_url( 'public/img/checkmark-green.svg' ) ); ?>"/>
					</div>
					<div class="flex-col gap-4">
						<?php if ( 'test' === $mode ) : ?>
							<span class="account-info">
								<?php esc_html_e( 'Make test payments following', 'peachpay-for-woocommerce' ); ?>
								<a href="https://developer.authorize.net/hello_world/testing_guide.html" target="_blank"><?php esc_html_e( 'these instructions', 'peachpay-for-woocommerce' ); ?></a>.
							</span>
						<?php endif; ?>
						<span class="account-info">
							<?php esc_html_e( 'Login Id:', 'peachpay-for-woocommerce' ); ?> <?php echo esc_html( PeachPay_Authnet_Credentials::get_login_id( $mode ) ); ?>
						</span>
						<span class="account-info">
							<?php esc_html_e( 'Public Client Key:', 'peachpay-for-woocommerce' ); ?> <?php echo esc_html( PeachPay_Authnet_Credentials::get_public_client_key( $mode ) ); ?>
						</span>
					</div>
					<div>
						<a class="unlink-payment-button button-error-outlined-medium pp-authnet-delete-btn"
							href="#"
							data-mode="<?php echo esc_attr( $mode ); ?>"
							onclick="return confirm('<?php echo 'test' === $mode ? esc_attr__( 'Remove Authorize.net sandbox credentials? You will need to re-enter them to accept test payments.', 'peachpay-for-woocommerce' ) : esc_attr__( 'Remove Authorize.net live credentials? You will need to re-enter them to accept payments.', 'peachpay-for-woocommerce' ); ?>')">
							<?php
							if ( 'test' === $mode ) {
								esc_html_e( 'Unlink Authorize.net (sandbox)', 'peachpay-for-woocommerce' );
							} else {
								esc_html_e( 'Unlink Authorize.net', 'peachpay-for-woocommerce' );
							}
							?>
						</a>
					</div>
				</div>
			<?php else : ?>
				<div class="pp-authnet-connect-section" data-mode="<?php echo esc_attr( $mode ); ?>">
					<div class="authnet-form-field">
						<label for="authnet_login_id"><?php esc_html_e( 'API Login ID', 'peachpay-for-woocommerce' ); ?></label>
						<input id="authnet_login_id" type="text" class="pp-authnet-login-id regular-text" placeholder="<?php esc_attr_e( 'API Login ID', 'peachpay-for-woocommerce' ); ?>">
					</div>
					<div class="authnet-form-field">
						<label for="authnet_transaction_key"><?php esc_html_e( 'Transaction Key', 'peachpay-for-woocommerce' ); ?></label>
						<input id="authnet_transaction_key" type="password" class="pp-authnet-transaction-key regular-text" placeholder="<?php esc_attr_e( 'Transaction Key', 'peachpay-for-woocommerce' ); ?>">
					</div>
					<div class="authnet-form-field">
						<label for="authnet_public_client_key"><?php esc_html_e( 'Public Client Key', 'peachpay-for-woocommerce' ); ?></label>
						<input id="authnet_public_client_key" type="text" class="pp-authnet-public-client-key regular-text" placeholder="<?php esc_attr_e( 'Public Client Key', 'peachpay-for-woocommerce' ); ?>">
					</div>
					<div class="authnet-form-field">
						<label for="authnet_webhook_sig_key">
							<?php esc_html_e( 'Webhook Signature Key', 'peachpay-for-woocommerce' ); ?>
							<span class="pp-optional"><?php esc_html_e( '(optional)', 'peachpay-for-woocommerce' ); ?></span>
						</label>
						<input id="authnet_webhook_sig_key" type="password" class="pp-authnet-webhook-sig-key regular-text" placeholder="<?php esc_attr_e( 'Webhook Signature Key', 'peachpay-for-woocommerce' ); ?>">
						<p class="description"><?php esc_html_e( 'Required to verify webhook events from Authorize.net. Found in your Authorize.net merchant portal under Account > Settings > Security Settings > Webhooks.', 'peachpay-for-woocommerce' ); ?></p>
					</div>
					<p class="authnet-save-row">
						<button type="button" class="button-primary-filled-medium pp-authnet-save-credentials-mode" data-mode="<?php echo esc_attr( $mode ); ?>">
							<?php esc_html_e( 'Save credentials', 'peachpay-for-woocommerce' ); ?>
						</button>
						<span class="pp-authnet-status-message" style="margin-left:10px;"></span>
					</p>
				</div>
			<?php endif; ?>
		</div>

		<!-- Webhook endpoint reference -->
		<div class="flex-col gap-4" style="margin-top: 24px;">
			<strong><?php esc_html_e( 'Webhook Endpoint', 'peachpay-for-woocommerce' ); ?></strong>
			<p class="description"><?php esc_html_e( 'Configure this URL in your Authorize.net merchant portal under Account > Settings > Security Settings > Webhooks:', 'peachpay-for-woocommerce' ); ?></p>
			<code><?php echo esc_url( rest_url( 'peachpay/v1/authnet/webhook' ) ); ?></code>
		</div>

		<?php if ( $is_connected ) : ?>
			<div style="margin-top: 16px;">
				<a class="update-payment-button button-primary-filled-medium" href="<?php echo esc_url( PeachPay_Authnet_Advanced::get_url() ); ?>">
					<?php esc_html_e( 'Advanced settings', 'peachpay-for-woocommerce' ); ?>
				</a>
			</div>
		<?php endif; ?>


	</div><!-- .authnet-gateway-settings -->

	<div class="provider-info">
		<div class="info-icon icon-18"></div>
		<span>
			<span><?php esc_html_e( "For more information about Authorize.net's services and pricing, visit", 'peachpay-for-woocommerce' ); ?> </span>
			<a href="https://www.authorize.net/sign-up/pricing.html" target="_blank"><?php esc_html_e( 'Authorize.net', 'peachpay-for-woocommerce' ); ?></a>
		</span>
	</div>
</div>

<script>
jQuery(document).ready(function($) {
	var peachpay_authnet_nonce = '<?php echo esc_js( wp_create_nonce( 'peachpay_authnet_credentials' ) ); ?>';

	// -------------------------------------------------------------------------
	// Banner helpers (same pattern as NMI)
	// -------------------------------------------------------------------------
	function addBanner(type, message) {
		var banner = document.createElement('div');
		banner.className = 'notice notice-' + type + ' addition';
		var p = document.createElement('p');
		var strong = document.createElement('strong');
		strong.textContent = message;
		p.appendChild(strong);
		banner.appendChild(p);
		var container = document.querySelector('.authnet-box .peachpay-notices-container');
		if (container) {
			container.insertBefore(banner, container.firstChild);
			setTimeout(function() {
				banner.classList.add('removal');
				setTimeout(function() { banner.remove(); }, 2000);
			}, 3000);
		}
	}

	// -------------------------------------------------------------------------
	// Enable toggle — show/hide credentials form (same pattern as NMI)
	// -------------------------------------------------------------------------
	$('#authnet-enabled-toggle').on('change', function() {
		var isEnabled = $(this).is(':checked');
		var $settingsContainer = $('.authnet-gateway-settings');
		var $description       = $('.authnet-provider-description');
		var $tutorialLink      = $('.authnet-tutorial-link');

		$.ajax({
			url: ajaxurl,
			type: 'POST',
			data: {
				action: 'peachpay_authnet_set_enabled',
				nonce:   peachpay_authnet_nonce,
				enabled: isEnabled ? 1 : 0,
			},
		});

		if (isEnabled) {
			$settingsContainer.slideDown(300);
			$description.addClass('hidden');
			$tutorialLink.addClass('hidden');
		} else {
			$settingsContainer.slideUp(300);
			$description.removeClass('hidden');
			$tutorialLink.removeClass('hidden');
		}
	});

	// -------------------------------------------------------------------------
	// Save credentials for the active mode
	// -------------------------------------------------------------------------
	$(document).on('click', '.pp-authnet-save-credentials-mode', function() {
		var $btn     = $(this);
		var $section = $btn.closest('.pp-authnet-connect-section');
		var mode     = $btn.data('mode');
		var $msg     = $section.find('.pp-authnet-status-message');

		$btn.prop('disabled', true).text('<?php echo esc_js( __( 'Connecting...', 'peachpay-for-woocommerce' ) ); ?>');
		$msg.text('').css('color', '');

		$.ajax({
			url: ajaxurl,
			method: 'POST',
			data: {
				action:            'peachpay_authnet_save_credentials',
				nonce:             peachpay_authnet_nonce,
				mode:              mode,
				login_id:          $section.find('.pp-authnet-login-id').val(),
				transaction_key:   $section.find('.pp-authnet-transaction-key').val(),
				public_client_key: $section.find('.pp-authnet-public-client-key').val(),
				webhook_sig_key:   $section.find('.pp-authnet-webhook-sig-key').val(),
			},
			success: function(response) {
				if (response.success) {
					$msg.css('color', 'green').text(response.data.message);
					setTimeout(function() { window.location.reload(); }, 1000);
				} else {
					$msg.css('color', 'red').text(response.data.message);
					$btn.prop('disabled', false).text('<?php echo esc_js( __( 'Save credentials', 'peachpay-for-woocommerce' ) ); ?>');
				}
			},
			error: function() {
				$msg.css('color', 'red').text('<?php echo esc_js( __( 'Connection error. Please try again.', 'peachpay-for-woocommerce' ) ); ?>');
				$btn.prop('disabled', false).text('<?php echo esc_js( __( 'Save credentials', 'peachpay-for-woocommerce' ) ); ?>');
			},
		});
	});

	// -------------------------------------------------------------------------
	// Delete credentials for the active mode
	// -------------------------------------------------------------------------
	$(document).on('click', '.pp-authnet-delete-btn', function(e) {
		e.preventDefault();
		var $btn = $(this);
		var mode = $btn.data('mode');

		$.ajax({
			url: ajaxurl,
			method: 'POST',
			data: {
				action: 'peachpay_authnet_delete_credentials',
				nonce:  peachpay_authnet_nonce,
				mode:   mode,
			},
			success: function(response) {
				if (response.success) {
					window.location.reload();
				} else {
					addBanner('error', response.data.message || '<?php echo esc_js( __( 'Failed to remove credentials.', 'peachpay-for-woocommerce' ) ); ?>');
				}
			},
			error: function() {
				addBanner('error', '<?php echo esc_js( __( 'Connection error. Please try again.', 'peachpay-for-woocommerce' ) ); ?>');
			},
		});
	});
});
</script>
