<?php

namespace DigitalApps\PaymentsForAdyen;

defined('ABSPATH') || exit;

/** Merchant-hosted page that lets Adyen Web handle native and redirect actions. */
final class Adyen_Action_Page
{
	public function register_hooks()
	{
		add_action('template_redirect', [$this, 'maybe_render'], 0);
	}

	public function maybe_render()
	{
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only high-entropy continuation token.
		$session_key = isset($_GET['digitalapps_payments_for_adyen_action'])
			? sanitize_text_field(wp_unslash($_GET['digitalapps_payments_for_adyen_action']))
			: '';
		if ('' === $session_key) {
			return;
		}

		$manager = new Adyen_Session_Manager();
		$session = $manager->get_session($session_key);
		$order = $session ? wc_get_order($session['order_id']) : false;
		if (!$session || !$order || empty($session['action'])) {
			wp_die(
				esc_html__('This payment authentication link is invalid or has expired. Return to checkout and try again.', 'digital-apps-payments-for-adyen'),
				esc_html__('Payment authentication unavailable', 'digital-apps-payments-for-adyen'),
				['response' => 410]
			);
		}

		$settings = Settings_Store::get();
		$order_environment = (string) $order->get_meta('_digitalapps_payments_for_adyen_environment', true);
		$test_mode = in_array($order_environment, ['test', 'live'], true)
			? 'test' === $order_environment
			: !empty($settings['testMode']);
		$environment = Settings_Store::get_environment($test_mode, $settings);
		$config = [
			'environment' => !empty($environment['testMode']) ? 'test' : 'live',
			'clientKey' => (string) ($environment['clientKey'] ?? ''),
			'countryCode' => $order->get_billing_country() ?: 'US',
			'locale' => str_replace('_', '-', determine_locale()),
			'actionMode' => true,
			'action' => $session['action'],
			'sessionKey' => $session_key,
			'detailsUrl' => rest_url('digitalapps-payments-for-adyen/v1/submit-additional-details'),
			'restNonce' => wp_create_nonce('wp_rest'),
			'returnUrl' => $order->get_checkout_order_received_url(),
			'retryUrl' => $order->get_checkout_payment_url(),
			'messages' => [
				'loadFailed' => __('Payment authentication could not be loaded. Return to checkout and try again.', 'digital-apps-payments-for-adyen'),
				'failed' => __('Payment authentication was not completed. Return to checkout and try again.', 'digital-apps-payments-for-adyen'),
				'returnToCheckout' => __('Return to checkout', 'digital-apps-payments-for-adyen'),
			],
		];

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Value is relayed to the signed action details endpoint.
		if (isset($_GET['redirectResult']) && is_string($_GET['redirectResult'])) {
			$config['redirectResult'] = sanitize_text_field(wp_unslash($_GET['redirectResult']));
		}

		$handle = 'digitalapps-payments-for-adyen-card-init';
		wp_enqueue_script(
			$handle,
			DIGITALAPPS_PAYMENTS_FOR_ADYEN_URL . 'build/checkout/digitalapps-payments-for-adyen-card-init.js',
			['jquery'],
			DIGITALAPPS_PAYMENTS_FOR_ADYEN_VERSION,
			true
		);
		wp_localize_script($handle, 'digitalAppsPaymentsForAdyenConfig', $config);

		nocache_headers();
		header('X-Robots-Tag: noindex, nofollow', true);
		status_header(200);
		$this->render_document();
		exit;
	}

	private function render_document()
	{
		?><!doctype html>
		<html <?php language_attributes(); ?>>
		<head>
			<meta charset="<?php bloginfo('charset'); ?>">
			<meta name="viewport" content="width=device-width, initial-scale=1">
			<title><?php esc_html_e('Complete payment authentication', 'digital-apps-payments-for-adyen'); ?></title>
			<?php wp_head(); ?>
		</head>
		<body <?php body_class('digitalappsPaymentsForAdyenActionPage'); ?>>
			<?php wp_body_open(); ?>
			<main style="max-width: 680px; margin: 4rem auto; padding: 1.5rem;">
				<h1><?php esc_html_e('Complete payment authentication', 'digital-apps-payments-for-adyen'); ?></h1>
				<p><?php esc_html_e('Follow the secure instructions below to complete your card payment.', 'digital-apps-payments-for-adyen'); ?></p>
				<div id="digitalapps-payments-for-adyen-action-component" aria-live="polite"></div>
				<div id="digitalapps-payments-for-adyen-action-error" class="woocommerce-error" role="alert" hidden></div>
			</main>
			<?php wp_footer(); ?>
		</body>
		</html><?php
	}
}
