<?php
/**
 * File to track plain HTML form submissions.
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Concrete tracker for plain HTML forms.
 *
 * Inherits the REST handler from SimpleStats_Forms_Tracking and adds the
 * frontend script enqueue + config localization.
 */
class SimpleStats_Tracking_HtmlForms extends SimpleStats_Forms_Tracking {

	const SCRIPT_HANDLE = 'simplestats-forms-tracking';

	/**
	 * Default CSS selectors for forms that should NOT be tracked.
	 *
	 * Filterable via `simplestats_forms_exclusion_selectors`.
	 *
	 * @return string[]
	 */
	public static function default_exclusion_selectors() {
		return array(
			'form[role="search"]',
			'form[action*="?s="]',
			'#loginform',
			'#registerform',
			'#lostpasswordform',
			'#commentform',
			'[data-simplestats-skip]',
		);
	}

	/**
	 * Register hooks. Extends the parent's REST registration with the asset enqueue.
	 */
	protected function hooks() {
		parent::hooks();

		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );
	}

	/**
	 * Enqueue the frontend tracking script + localize its config.
	 */
	public function enqueue_assets() {
		if ( is_admin() ) {
			return;
		}

		if ( ! simplestats_is_connected() ) {
			return;
		}

		wp_enqueue_script(
			self::SCRIPT_HANDLE,
			SIMPLESTATS_PLUGIN_URL . 'assets/js/forms-tracking.js',
			array(),
			SIMPLESTATS_PLUGIN_VERSION,
			true
		);

		$exclude = apply_filters(
			'simplestats_forms_exclusion_selectors',
			self::default_exclusion_selectors()
		);

		wp_localize_script(
			self::SCRIPT_HANDLE,
			'simplestatsForms',
			array(
				'ajaxUrl' => esc_url_raw( admin_url( 'admin-ajax.php' ) ),
				'action'  => self::AJAX_ACTION,
				'nonce'   => wp_create_nonce( self::NONCE_ACTION ),
				// The 'exclude' key is localized JS config (CSS selectors to skip),
				// not a get_posts() query argument, so VIP's exclusionary-param
				// performance warning does not apply here.
				'exclude' => array_values( array_filter( (array) $exclude, 'is_string' ) ), // phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_exclude
			)
		);
	}
}
