<?php
/**
 * Frontend Tracking Code Output
 *
 * Injects Google Analytics tracking code into wp_head.
 *
 * @package SEOvaultSEO
 */

namespace SEOvaultSEO\Frontend;

use SEOvaultSEO\Core\Options;

/**
 * Handles GA tracking code injection
 */
class TrackingCode {

	/**
	 * Initialize frontend tracking output
	 */
	public static function init() {
		if ( ! \SEOvaultSEO\Compatibility\Detector::should_output_seo() ) {
			return;
		}

		if ( ! Options::is_ga_tracking_enabled() ) {
			return;
		}

		add_action( 'wp_enqueue_scripts', array( __CLASS__, 'output_tracking_code' ), 99 );
	}

	/**
	 * Check whether tracking should be skipped for the current visitor.
	 *
	 * @return bool True if tracking should be skipped.
	 */
	public static function should_skip_tracking() {
		if ( ! Options::is_ga_track_logged_in() && is_user_logged_in() ) {
			return true;
		}
		return false;
	}

	/**
	 * Output tracking code in wp_head
	 */
	public static function output_tracking_code() {
		if ( ! Options::is_ga_tracking_enabled() ) {
			return;
		}

		if ( self::should_skip_tracking() ) {
			return;
		}

		// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound -- Hook name is the prefixed public API constant declared in ExtensionApi.
		$mode = apply_filters( \SEOvaultSEO\Extension\ExtensionApi::FILTER_ANALYTICS_OUTPUT_MODE, 'gtag' );
		if ( 'extension' === $mode ) {
			// Trusted extensions own their registered script handle and output.
			// Free never accepts or emits arbitrary script content.
			// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound -- Hook name is the prefixed public API constant declared in ExtensionApi.
			do_action( \SEOvaultSEO\Extension\ExtensionApi::ACTION_ANALYTICS_OUTPUT );
			return;
		}

		// Unknown filter values fall back to the programmatically generated gtag method.
		self::output_gtag();
	}

	/**
	 * Output gtag.js snippet
	 */
	private static function output_gtag() {
		$measurement_id = Options::get_ga_measurement_id();

		if ( '' === $measurement_id ) {
			return;
		}

		$anonymize = Options::is_ga_anonymize_ip();

		$script_url = add_query_arg( 'id', $measurement_id, 'https://www.googletagmanager.com/gtag/js' );
		wp_enqueue_script( 'seovaultseo-google-tag', esc_url_raw( $script_url ), array(), SEOVAULT_SEO_VERSION, false );
		wp_script_add_data( 'seovaultseo-google-tag', 'async', true );

		$config_args = array();
		if ( $anonymize ) {
			$config_args['anonymize_ip'] = true;
		}

		$inline  = "window.dataLayer = window.dataLayer || [];\n";
		$inline .= "function gtag(){dataLayer.push(arguments);}\n";
		$inline .= "gtag('js', new Date());\n";
		$inline .= 'gtag(\'config\', ' . wp_json_encode( $measurement_id );
		if ( ! empty( $config_args ) ) {
			$inline .= ', ' . wp_json_encode( $config_args );
		}
		$inline .= ');';
		wp_add_inline_script( 'seovaultseo-google-tag', $inline, 'after' );
	}
}
