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

/**
 * Returns Google Analytics tracking code.
 */
function wpex_google_analytics_tag() {
	$property_id = get_theme_mod( 'google_property_id' );

	/**
	 * Filters the Google Analytics Property ID.
	 *
	 * @param string|array $property_id
	 */
	$property_id = apply_filters( 'wpex_google_property_id', $property_id );

	if ( empty( $property_id ) ) {
		return;
	}

	$properties = array();

	if ( is_string( $property_id ) ) {
		$properties = explode( ',', $property_id );
		$properties = array_filter( $properties );
		$properties = array_map( 'trim', $properties );
	}

	foreach ( $properties as $property ) {

		// Old Ga format.
		if ( 0 === strpos( $property, 'UA-' ) ) {
			$validate_id = (bool) preg_match( '/^ua-\d{4,9}-\d{1,4}$/i', strval( $property ) );
			if ( $validate_id ) {
				echo "<!-- Google Analytics Universal -->";
				echo "<script>";
					echo "window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;";
					echo "ga('create', '" . wp_strip_all_tags( $property ) . "', 'auto');";
					echo "ga('send', 'pageview');";
					echo "ga('set', 'anonymizeIp', true);";
				echo "</script>";
				echo "<script async src='https://www.google-analytics.com/analytics.js'></script>";
			}
		}

		// Newer ga4 format.
		elseif ( 0 === strpos( $property, 'G-' ) ) {
			echo "<!-- Google Analytics G4 Site Tag -->";
			echo "<script async src=\"https://www.googletagmanager.com/gtag/js?id=" . wp_strip_all_tags( $property ) . "\"></script>";
			echo "<script>";
				echo "window.dataLayer = window.dataLayer || [];";
				echo "function gtag(){dataLayer.push(arguments);}";
				echo "gtag('js', new Date());";

				echo "gtag('config', '" . wp_strip_all_tags( $property ) . "', { 'anonymize_ip': true });";
			echo "</script>";
		}

	}
}