<?php
/**
 * Wrapper for WS Form Integration
 *
 * @link https://personalizewp.com/
 * @since 2.5.0
 *
 * @package PersonalizeWP
 * @subpackage PersonalizeWP/Integrations
 */

namespace PersonalizeWP\Integrations\WSForm;

use PersonalizeWP\Integrations\WSForm\WSForm;

/**
 * Register the WSForm integation, and setup various actions/filters.
 *
 * @param \PersonalizeWP\PersonalizeWP $personalizewp Instance of plugin
 *
 * @return void
 */
function register_integration( $personalizewp ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found

	// Use WP functions to check activeness.
	require_once ABSPATH . 'wp-admin/includes/plugin.php';

	// Check for either base or Pro plugin.
	if ( ! is_plugin_active( 'ws-form/ws-form.php' ) && ! is_plugin_active( 'ws-form-pro/ws-form.php' ) ) {
		return;
	}

	add_action(
		'wsf_plugins_loaded',
		function () {
			if ( ! version_compare( WS_FORM_VERSION, '1.9.208', '>=' ) ) {
				return;
			}
			$wsform = new WSForm();
		}
	);

	add_filter(
		'wsf_enqueue_scripts',
		function () {
			// Add JS to the footer when any WS Form is in use.
			add_action( 'wp_footer', __NAMESPACE__ . '\action_wp_footer' );
		}
	);
}
add_action( 'personalizewp_register_integrations', __NAMESPACE__ . '\register_integration' );

/**
 * Output inline JS that ensures initialisation of any injected WS Form.
 *
 * @return void
 */
function action_wp_footer() {
	?>
<script>
document.addEventListener('PWP:parsedPlaceholders', () => { if ( typeof wsf_form_init === "function" ) { wsf_form_init() } } );
</script>
	<?php
}
