<?php
/**
 * Intent confirmation: after a magic link is clicked, present a small
 * "Continue to log in" page that requires a POST/click before the
 * token is actually consumed. Combined with ScannerDetector this prevents
 * email-security gateways from silently burning single-use tokens.
 *
 * @package KaizenCoders\MagicLink
 */

namespace KaizenCoders\MagicLink;

class IntentConfirmation {

	/**
	 * Settings key controlling whether intent confirmation is required.
	 *
	 * @return bool
	 */
	public static function is_enabled() {
		$settings = get_option( 'kc_ml_settings', array() );
		$value    = Helper::get_data( $settings, 'general|settings|require_intent_confirmation', 1 );

		// Default ON to protect against scanners; explicit "0" turns it off.
		return ! ( '0' === (string) $value || 0 === $value || false === $value );
	}

	/**
	 * Build the URL the confirmation form posts to. Preserves the original
	 * magic-link query string so the underlying handler can consume the token.
	 *
	 * @param  array $query Original query parameters.
	 *
	 * @return string
	 */
	public static function build_confirm_url( $query ) {
		$base = home_url( '/' );
		$args = array_merge( array( 'kc_ml_confirm' => 1 ), (array) $query );

		return add_query_arg( $args, $base );
	}

	/**
	 * Render the confirmation form. Output is captured; caller decides how to
	 * emit it (echo + exit, return as string, etc.).
	 *
	 * @param  array  $query Original query parameters to preserve.
	 * @param  string $label User-facing label, e.g. "Log in as jane@example.com".
	 *
	 * @return string
	 */
	public static function render( $query, $label = '' ) {
		$action  = esc_url( self::build_confirm_url( $query ) );
		$nonce   = function_exists( 'wp_create_nonce' ) ? wp_create_nonce( 'kc_ml_intent' ) : 'test-nonce';
		$button  = esc_html__( 'Continue to log in', 'magic-link' );
		$heading = esc_html__( 'Confirm sign-in', 'magic-link' );
		$label   = '' === $label ? esc_html__( 'Click to complete your sign-in.', 'magic-link' ) : esc_html( $label );

		ob_start();
		?>
<!doctype html>
<html>
<head>
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width,initial-scale=1" />
	<meta name="robots" content="noindex,nofollow" />
	<title><?php echo $heading; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></title>
	<style>
		body{font-family:-apple-system,Segoe UI,Roboto,sans-serif;background:#f6f7f7;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0}
		.kc-card{background:#fff;padding:32px;border-radius:8px;box-shadow:0 1px 3px rgba(0,0,0,.08);max-width:380px;width:100%;text-align:center}
		.kc-card h1{margin:0 0 12px;font-size:20px}
		.kc-card p{color:#50575e;margin:0 0 24px}
		.kc-card button{background:#2271b1;color:#fff;border:0;border-radius:4px;padding:12px 24px;font-size:15px;cursor:pointer;width:100%}
		.kc-card button:hover{background:#135e96}
	</style>
</head>
<body>
	<form method="post" action="<?php echo $action; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>" class="kc-card">
		<input type="hidden" name="_kc_ml_intent_nonce" value="<?php echo esc_attr( $nonce ); ?>" />
		<h1><?php echo $heading; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></h1>
		<p><?php echo $label; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></p>
		<button type="submit"><?php echo $button; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></button>
	</form>
</body>
</html>
		<?php
		return ob_get_clean();
	}

	/**
	 * True when the current request is the confirmation POST itself
	 * (i.e. the user just clicked "Continue").
	 *
	 * @return bool
	 */
	public static function is_confirmation_submitted() {
		if ( 'POST' !== ( isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( $_SERVER['REQUEST_METHOD'] ) : 'GET' ) ) {
			return false;
		}
		if ( ! isset( $_GET['kc_ml_confirm'] ) ) {
			return false;
		}
		$nonce = isset( $_POST['_kc_ml_intent_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['_kc_ml_intent_nonce'] ) ) : '';

		return function_exists( 'wp_verify_nonce' ) ? (bool) wp_verify_nonce( $nonce, 'kc_ml_intent' ) : ! empty( $nonce );
	}
}
