<?php
/**
 * Site Kit by Google Track Comments plugin file.
 *
 * @package   Google\Site_Kit_Track_Comments
 * @author    Felix Arntz, Google
 * @license   GPL-2.0-or-later
 * @copyright 2019 Google Inc.
 *
 * @wordpress-plugin
 * Plugin Name: Site Kit by Google Track Comments
 * Description: Tracks WordPress comment form submissions via Google Analytics.
 * Plugin URI:  https://gist.github.com/felixarntz//c7e0aea5c0a17c116b09a25f872d1da0
 * Version:     0.1.0
 * Author:      Felix Arntz, Google
 * Author URI:  https://felix-arntz.me
 * License:     GNU General Public License v2 (or later)
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

namespace Google\Site_Kit_Track_Comments;

/*
 * In AMP, we need to simply filter the amp-analytics options and add the required event trigger.
 */
add_filter(
	'googlesitekit_amp_gtag_opt',
	function( array $options ) {
		if ( ! isset( $options['triggers'] ) ) {
			$options['triggers'] = array();
		}
		// See https://developers.google.com/analytics/devguides/collection/amp-analytics/#measure_events
		// and https://amp.dev/documentation/components/amp-analytics/#triggers.
		$options['triggers']['comment_submission'] = array(
			'selector' => '#commentform input[type="submit"]',
			'on'       => 'click',
			'vars'     => array(
				'event_name'     => 'submit_comment',
				'event_category' => 'engagement',
			),
		);
		return $options;
	}
);

/*
 * In non-AMP, we need to add a custom script to listen to the DOM event and fire the gtag event.
 */
add_action(
	'wp_enqueue_scripts',
	function() {
		if ( ! wp_script_is( 'google_gtagjs' ) ) {
			return;
		}

		// See https://developers.google.com/analytics/devguides/collection/gtagjs/events#send_events.
		ob_start();
		?>
		<script>
	document.addEventListener( 'DOMContentLoaded', function() {
		var submitButton = document.querySelector( '#commentform input[type="submit"]' );
		if ( submitButton ) {
			submitButton.addEventListener( 'click', function() {
				gtag( 'event', 'submit_comment', { 'event_category': 'engagement' } );
			} );
		}
	} );
</script>
		<?php
		$script = substr( trim( ob_get_clean() ), strlen( '<script>' ), - strlen( '</script>' ) );

		wp_add_inline_script( 'google_gtagjs', $script );
	},
	99
);