<?php
defined( 'ABSPATH' ) || exit;

/**
 * Gravity Forms merge tags.
 *
 * Client-side JS populates hidden fields whose default value references a merge tag like
 * {bw:source}. The capture script reads the tag, resolves it from storage, and writes the
 * result before submit. Server-side we only need to register the tags so GF doesn't strip
 * them from the UI.
 */
class BW_Lead_AI_Merge_Tags {

	const TAGS = array(
		'source', 'medium', 'source_medium', 'channel', 'campaign', 'term',
		'content', 'adgroup', 'first_page', 'last_page', 'submit_page',
		'first_source', 'first_medium', 'first_channel', 'visits', 'pages',
		'tagged_visits', 'summary', 'summary_detailed',
	);

	private static $instance = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	public function register() {
		if ( ! $this->gf_active() ) {
			return;
		}
		add_filter( 'gform_custom_merge_tags', array( $this, 'register_tags' ), 10, 4 );
		// Server-side replacement: leave value empty so the JS front-end replaces it in the
		// hidden input before submission. (We cannot resolve storage values on the server.)
		add_filter( 'gform_replace_merge_tags', array( $this, 'passthrough' ), 10, 7 );
	}

	private function gf_active() {
		return class_exists( 'GFForms' );
	}

	public function register_tags( $merge_tags, $form_id, $fields, $element_id ) {
		foreach ( self::TAGS as $tag ) {
			$merge_tags[] = array(
				'label' => 'BW: ' . $tag,
				'tag'   => '{bw:' . $tag . '}',
			);
		}
		// Also register any custom dimensions defined in Parameter Aliases so they
		// appear in the Gravity Forms merge-tag dropdown alongside the built-ins.
		$settings = BW_Lead_AI_Settings::get();
		$aliases  = BW_Lead_AI_Settings::parse_parameter_aliases( $settings['parameter_aliases'] );
		foreach ( array_keys( $aliases['custom'] ) as $custom_key ) {
			$merge_tags[] = array(
				'label' => 'BW: ' . $custom_key,
				'tag'   => '{bw:' . $custom_key . '}',
			);
		}
		return $merge_tags;
	}

	/**
	 * Passthrough: leave {bw:*} tags untouched on the server so the capture script can
	 * replace them in hidden field defaults before submission.
	 */
	public function passthrough( $text, $form, $entry, $url_encode, $esc_html, $nl2br, $format ) {
		return $text;
	}
}
