<?php
/**
 * Shared Markup Injector
 *
 * Several captcha integrations need to inject widget HTML just before a form's
 * submit button. WPForms / Gravity / Elementor expose filters on the entire
 * form HTML; we locate a safe anchor (submit wrapper, first submit button,
 * closing </form>) and splice the widget before it.
 *
 * @package WP_PowerSuite\Captcha\Shared
 * @since 1.1.0
 */

namespace WP_PowerSuite\Captcha\Shared;

/**
 * Markup injection utility.
 */
final class MarkupInjector {

	/**
	 * Insert `$widget` into `$html` before the best-known submit anchor.
	 *
	 * Priority of anchors:
	 *   1. `<div class="…-submit…">` wrapper (WPForms / Gravity)
	 *   2. The first `<button type="submit"` or `<input type="submit"`
	 *   3. The closing `</form>` tag
	 *
	 * Returns the original HTML unchanged if nothing matches.
	 *
	 * @param string $html   Full form HTML.
	 * @param string $widget Widget HTML to inject.
	 */
	public static function beforeSubmit( string $html, string $widget ): string {
		if ( $html === '' || $widget === '' ) {
			return $html;
		}
		$patterns = [
			'/<div\\s[^>]*class="[^"]*(?:wpforms-submit-container|gform_footer|elementor-field-group-submit)[^"]*"[^>]*>/i',
			'/<button\\s[^>]*type=["\']submit["\'][^>]*>/i',
			'/<input\\s[^>]*type=["\']submit["\'][^>]*>/i',
			'/<\\/form>/i',
		];
		foreach ( $patterns as $pattern ) {
			if ( preg_match( $pattern, $html, $m, PREG_OFFSET_CAPTURE ) ) {
				$offset = (int) $m[0][1];
				return substr( $html, 0, $offset ) . $widget . substr( $html, $offset );
			}
		}
		return $html;
	}
}
