<?php
/**
 * Inquiry (Gravity Forms form 2) "Thank You" personalization.
 *
 * Mirrors the live site's inquiries/personalized.blade.php: after the Contact
 * Information form is submitted, the visitor is redirected to the dedicated
 * Thank-You page and that page echoes back the data they submitted (name,
 * email, target grade/year).
 *
 * How the data travels — securely:
 *   On submit we redirect to the Thank-You page with the ENTRY ID plus a
 *   short HMAC token: ?eid=123&t=<hmac>. The page's shortcodes load the real
 *   entry from Gravity Forms server-side (GFAPI::get_entry) ONLY when the token
 *   matches. Because the token is an HMAC keyed on a WordPress salt, entry ids
 *   cannot be guessed/enumerated to read someone else's submission, and no
 *   personal data is ever trusted from the URL itself — the URL only carries an
 *   id + signature. All output is escaped.
 *
 * Shortcodes to place on the Thank-You page (build the layout however you like):
 *   [bw_inquiry field="name"]      – the inquirer's name  (parent OR student)
 *   [bw_inquiry field="email"]     – the inquirer's email
 *   [bw_inquiry field="grade"]     – starting grade number, e.g. "8"
 *   [bw_inquiry field="year"]      – starting year, formatted "2026/27"
 *   [bw_inquiry field="year_raw"]  – starting year, raw "2026/2027"
 *   [bw_inquiry field="question"]  – the "Ask A Question" text
 *   [bw_inquiry_intro]             – the whole live paragraph, only rendered
 *                                    when grade AND year are present:
 *     "Thank you for taking the time to contact us regarding a Grade 8
 *      student starting in 2026/27."
 *
 * Optional attribute: [bw_inquiry field="name" fallback="there"] – shown when
 * there is no valid submission (e.g. the page is opened directly).
 *
 * @package Kadence-Child
 */

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

/** Gravity Forms id of the Contact Information form. */
if ( ! defined( 'BW_INQUIRY_FORM_ID' ) ) {
	define( 'BW_INQUIRY_FORM_ID', 2 );
}

/** Slug/path of the Thank-You page the form redirects to. */
if ( ! defined( 'BW_INQUIRY_THANKYOU_PATH' ) ) {
	define( 'BW_INQUIRY_THANKYOU_PATH', '/thank-you-contact-information/' );
}

/**
 * Signature for an entry id. Keyed on a WordPress secret salt so it cannot be
 * forged without server access. Truncated — 20 hex chars is ample here.
 *
 * @param int $eid Entry id.
 * @return string
 */
function bw_inquiry_token( $eid ) {
	return substr( hash_hmac( 'sha256', 'bw-inq-' . (int) $eid, wp_salt( 'auth' ) ), 0, 20 );
}

/**
 * After a valid submission of form 2, redirect to the Thank-You page carrying
 * the signed entry id. Works with the form's AJAX setting (GF turns an
 * array( 'redirect' => ... ) confirmation into a client-side redirect).
 */
add_filter(
	'gform_confirmation',
	function ( $confirmation, $form, $entry, $ajax ) {
		if ( (int) rgar( $form, 'id' ) !== (int) BW_INQUIRY_FORM_ID ) {
			return $confirmation;
		}
		$eid = (int) rgar( $entry, 'id' );
		if ( ! $eid ) {
			return $confirmation; // Entry not stored — leave default confirmation.
		}
		$url = add_query_arg(
			array(
				'eid' => $eid,
				't'   => bw_inquiry_token( $eid ),
			),
			home_url( BW_INQUIRY_THANKYOU_PATH )
		);
		return array( 'redirect' => $url );
	},
	10,
	4
);

/**
 * Load & validate the submitted entry referenced by the current request's
 * ?eid=&t= parameters. Returns the GF entry array, or null if missing/invalid.
 * Result is memoised for the request.
 *
 * @return array|null
 */
function bw_inquiry_entry() {
	static $resolved = false;
	static $entry    = null;

	if ( $resolved ) {
		return $entry;
	}
	$resolved = true;

	$eid = isset( $_GET['eid'] ) ? absint( $_GET['eid'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$tok = isset( $_GET['t'] ) ? sanitize_text_field( wp_unslash( $_GET['t'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

	if ( ! $eid || ! $tok || ! hash_equals( bw_inquiry_token( $eid ), $tok ) ) {
		return $entry; // null — no valid signature.
	}
	if ( ! class_exists( 'GFAPI' ) ) {
		return $entry;
	}
	$loaded = GFAPI::get_entry( $eid );
	if ( is_wp_error( $loaded ) ) {
		return $entry;
	}
	if ( (int) rgar( $loaded, 'form_id' ) !== (int) BW_INQUIRY_FORM_ID ) {
		return $entry; // Token/id mismatch to a different form — ignore.
	}

	$entry = $loaded;
	return $entry;
}

/**
 * Pull a single logical value out of the submitted entry.
 *
 * Handles the parent-vs-student branch: whoever is inquiring is the "user"
 * whose name/email we greet (matching $inquiry->user on the live site).
 *
 * @param string $field One of: name, email, grade, year, year_raw, question.
 * @return string Unescaped value ('' when unavailable).
 */
function bw_inquiry_value( $field ) {
	$e = bw_inquiry_entry();
	if ( ! $e ) {
		return '';
	}

	$is_student = ( 'Student' === rgar( $e, '1' ) );

	switch ( $field ) {
		case 'name':
			// Parent path → field 3; Student path → field 7. Fall back to the
			// other if the expected one is somehow empty.
			$primary = $is_student ? rgar( $e, '7' ) : rgar( $e, '3' );
			$other   = $is_student ? rgar( $e, '3' ) : rgar( $e, '7' );
			return '' !== $primary ? $primary : $other;

		case 'email':
			// Parent path → field 14; Student path → field 13.
			$primary = $is_student ? rgar( $e, '13' ) : rgar( $e, '14' );
			$other   = $is_student ? rgar( $e, '14' ) : rgar( $e, '13' );
			return '' !== $primary ? $primary : $other;

		case 'grade':
			// "Grade 8" → "8".
			if ( preg_match( '/\d+/', (string) rgar( $e, '11' ), $m ) ) {
				return $m[0];
			}
			return '';

		case 'year':
			// "2026/2027" → "2026/27" (matches live: year . '/' . (year-1999)).
			if ( preg_match( '/(\d{4})/', (string) rgar( $e, '12' ), $m ) ) {
				$y = (int) $m[1];
				return $y . '/' . ( $y - 1999 );
			}
			return '';

		case 'year_raw':
			return (string) rgar( $e, '12' );

		case 'question':
			return (string) rgar( $e, '17' );
	}

	return '';
}

/**
 * [bw_inquiry field="name"] — echo one submitted value (escaped).
 */
add_shortcode(
	'bw_inquiry',
	function ( $atts ) {
		$atts = shortcode_atts(
			array(
				'field'    => 'name',
				'fallback' => '',
			),
			$atts,
			'bw_inquiry'
		);

		$value = bw_inquiry_value( $atts['field'] );
		if ( '' === $value ) {
			return esc_html( $atts['fallback'] );
		}
		return esc_html( $value );
	}
);

/**
 * [bw_inquiry_intro] — the live "Thank you for taking the time…" paragraph.
 * Rendered only when both grade and year are known (mirrors the live @if).
 */
add_shortcode(
	'bw_inquiry_intro',
	function () {
		$grade = bw_inquiry_value( 'grade' );
		$year  = bw_inquiry_value( 'year' );
		if ( '' === $grade || '' === $year ) {
			return '';
		}
		return '<p class="bw-inquiry-intro">Thank you for taking the time to contact us regarding a '
			. '<strong>Grade ' . esc_html( $grade ) . ' student</strong> starting in '
			. '<strong>' . esc_html( $year ) . '</strong>.</p>';
	}
);
