<?php
/**
 * Tracking Component
 *
 * @package Nisje
 */

namespace Nisje\Tracking;

/**
 * Registers scripts and styles
 */
function register_scripts_and_styles() {
	wp_enqueue_script( 'nisje-track' );
}
add_action( 'wp_enqueue_scripts', __NAMESPACE__ . '\\register_scripts_and_styles', 20 );

/**
 * Add GTM to head
 */
function add_tag_manager() {
	if ( ! defined( 'WP_ENV' ) || 'production' !== WP_ENV ) {
		return;
	}

	$tracking_id = \nisje_get_setting( 'tracking_id', 'general' );
	?>
	<script async src="https://www.googletagmanager.com/gtag/js?id=UA-161616392-1"></script> <?php // phpcs:ignore ?>
	<script>
		window.dataLayer = window.dataLayer || [];
		function gtag() { dataLayer.push( arguments ); }
		gtag( 'js', new Date() );
		gtag( 'config', 'UA-161501573-1' );
		<?php
		// Add customer tracking code.
		if ( ! empty( $tracking_id ) ) {
			printf( 'gtag( \'config\', \'%s\' );', esc_js( $tracking_id ) );
		}
		?>
	</script>
	<?php
}
add_action( 'wp_head', __NAMESPACE__ . '\\add_tag_manager', 1 );
