<?php
/**
 * /nxt-form/{id} — the Blackbaud web-form page carried over from the old site.
 *
 * The previous Laravel site served this route (routes/web.php: `Route::get(
 * '/nxt-form/{id}', [PagesController::class, 'nxtForm'])`), rendering a small
 * standalone page whose only job is to host a Blackbaud BBOX form:
 *
 *     window.bboxInit = function () { bbox.showForm('<id>'); };
 *
 * It did not come across in the migration, so every one of those links 404'd
 * after the cutover — and they are not ours to rewrite: only one lives in
 * WordPress content, the rest arrive from the calendar feed. The 404 log showed
 * eight distinct form ids and around a hundred hits in the first days, which is
 * families trying to register for school events and being turned away.
 *
 * So the URL has to keep working. This reproduces the route rather than
 * redirecting, because a Blackbaud form has no other address — it exists only
 * as an id handed to their script.
 *
 * One deliberate difference from the original: the id is validated as a UUID
 * before it reaches the page. The Laravel view interpolated it straight into a
 * <script> block with Blade's `{{ }}`, which escapes for HTML but not for
 * JavaScript — so a crafted id could break out of the string. Anything that is
 * not a UUID now 404s.
 *
 * @package Kadence-Child
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

const BW_NXT_FORM_REWRITE_VERSION = 1;

add_action(
	'init',
	function () {
		add_rewrite_rule( '^nxt-form/([^/]+)/?$', 'index.php?bw_nxt_form=$matches[1]', 'top' );

		// Flush once per rule change rather than on every load — flushing is
		// expensive and doing it unconditionally on init is a well-known way to
		// make every request slow.
		if ( (int) get_option( 'bw_nxt_form_rewrites' ) !== BW_NXT_FORM_REWRITE_VERSION ) {
			flush_rewrite_rules( false );
			update_option( 'bw_nxt_form_rewrites', BW_NXT_FORM_REWRITE_VERSION, false );
		}
	}
);

add_filter(
	'query_vars',
	function ( $vars ) {
		$vars[] = 'bw_nxt_form';
		return $vars;
	}
);

/**
 * Serve the URL as it was linked, without the trailing-slash bounce.
 *
 * The links in the calendar feed have no trailing slash, and WordPress's
 * canonical redirect would 301 every one of them. Harmless in a browser, but it
 * is an extra round trip on a page whose whole job is to load a third-party
 * form quickly — and a redirect on a route that did not have one before is the
 * sort of difference that turns up later as "it used to work".
 */
add_filter(
	'redirect_canonical',
	function ( $redirect ) {
		return get_query_var( 'bw_nxt_form' ) ? false : $redirect;
	}
);

add_action(
	'template_redirect',
	function () {
		$id = get_query_var( 'bw_nxt_form' );
		if ( '' === $id || null === $id ) {
			return;
		}

		// Strictly a UUID. Everything else is a 404, including the empty string.
		if ( ! preg_match( '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $id ) ) {
			global $wp_query;
			$wp_query->set_404();
			status_header( 404 );
			nocache_headers();
			include get_query_template( '404' );
			exit;
		}

		$logo_id  = (int) get_theme_mod( 'custom_logo' );
		$logo_url = $logo_id ? wp_get_attachment_image_url( $logo_id, 'medium' ) : '';

		status_header( 200 );
		nocache_headers();
		header( 'Content-Type: text/html; charset=utf-8' );
		?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex,nofollow">
<title><?php echo esc_html( get_bloginfo( 'name' ) ); ?></title>
<script>
window.bboxInit = function () {
	bbox.showForm( <?php echo wp_json_encode( $id ); ?> );
};
( function () {
	var e = document.createElement( 'script' );
	e.async = true;
	e.src = 'https://bbox.blackbaudhosting.com/webforms/bbox-min.js';
	document.getElementsByTagName( 'head' )[0].appendChild( e );
}() );
</script>
<style>
	body { margin: 0; padding: 2rem 1rem; background: #e5e7eb; font-family: "Open Sans", system-ui, sans-serif; }
	.bw-nxt { max-width: 820px; margin: 0 auto; background: #fff; border-radius: 8px;
		box-shadow: 0 2px 10px rgba(0,0,0,.08); padding: 1.5rem 1rem 2rem; }
	.bw-nxt__logo { display: block; margin: 0 auto 1.5rem; max-width: 254px; height: auto; }
	.bw-nxt__back { display: block; text-align: center; margin-top: 1.5rem; font-size: .9rem; }
	.bw-nxt__back a { color: #c8272c; }
</style>
</head>
<body>
	<div class="bw-nxt">
		<?php if ( $logo_url ) : ?>
			<img class="bw-nxt__logo" src="<?php echo esc_url( $logo_url ); ?>"
				alt="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>">
		<?php endif; ?>
		<div id="bbox-root"></div>
	</div>
	<p class="bw-nxt__back">
		<a href="<?php echo esc_url( home_url( '/' ) ); ?>">&larr; <?php echo esc_html( get_bloginfo( 'name' ) ); ?></a>
	</p>
</body>
</html>
		<?php
		exit;
	}
);
