<?php if ( !defined( 'ABSPATH' ) ) exit;//PHPの宣言と直接アクセスの拒否

/***** GA4タグの出力 *****/
function haup_ga4_tag_footer_insert(){
//変数
	//アクセス解析タグの入力値
	$ga = esc_html( GetOP01_ana_ad()['ga4-tag-id'] );

	//ログインユーザーへ出力しない
	$logged = absint( GetOP01_ana_ad()['login-user-not-output-analytics_tag'] );

	//タグの出力をする
	$output = absint( GetOP01_ana_ad()['insert-ga-tag'] );

if(!empty($output)){
//GA4のIDがあり、かつログインユーザー除外が有効の場合
if(!empty($ga) && $logged == '1'){
	if(!is_user_logged_in()){
		
		echo "\n";
		// phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript
		echo '<script async src="https://www.googletagmanager.com/gtag/js?id='.esc_html( $ga ).'"></script>';
		echo "\n";
		echo '<script>';
		echo "\n";
		echo 'window.dataLayer = window.dataLayer || [];';
		echo "\n";
		echo 'function gtag(){dataLayer.push(arguments);}';
		echo "\n";
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo "gtag('js', new Date());";
		echo "\n";
		echo "gtag('config','" .esc_html($ga)."', {";
		echo "\n";
		echo "  cookie_flags: 'max-age=7200;secure;samesite=none'";
		echo "\n";
		echo '});';
		echo "\n";
		echo '</script>';
		echo "\n";
	}
}


//GA4のIDがあり、かつログインユーザー除外が無効の場合
if(!empty($ga) && empty($logged)){
	
	echo "\n";
	// phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript
	echo '<script async src="https://www.googletagmanager.com/gtag/js?id='.esc_html( $ga ).'"></script>';
	echo "\n";
	echo '<script>';
	echo "\n";
	echo 'window.dataLayer = window.dataLayer || [];';
	echo "\n";
	echo 'function gtag(){dataLayer.push(arguments);}';
	echo "\n";
	// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	echo "gtag('js', new Date());";
	echo "\n";
	echo "gtag('config','" .esc_html($ga)."', {";
	echo "\n";
	echo "  cookie_flags: 'max-age=7200;secure;samesite=none'";
	echo "\n";
	echo '});';
	echo "\n";
	echo '</script>';
	echo "\n";
}
}
}
add_action('wp_footer','haup_ga4_tag_footer_insert');

