<?php
if ( ! function_exists( 'nishiki_pro_analytics_customizer' ) ) {
	add_action( 'customize_register', 'nishiki_pro_analytics_customizer' );
	/**
	 * カスタマイザーの設定
	 *
	 * @param instance $wp_customize インスタンス
	 * @return void
	 */
	function nishiki_pro_analytics_customizer( $wp_customize ) {

		// セクション追加
		$wp_customize->add_section(
			'section_' . NISHIKI_PRO_PREFIX_ANALYTICS,
			array(
				'title'    => __( 'アクセス解析', 'nishiki_pro' ),
				'priority' => 500,
				'panel'    => 'panel_' . NISHIKI_PRO_PREFIX,
			)
		);

		// Header
		$wp_customize->add_setting(
			'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_header',
			array(
				'sanitize_callback' => 'nishiki_pro_sanitize_text',
			)
		);

		$wp_customize->add_control(
			new Nishiki_WP_Customize_Content(
				$wp_customize,
				'ctrl_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_header',
				array(
					'label'    => '<p class="nishiki-pro-customizer-heading">Google タグマネージャー（GTM）</p>',
					'description' => __( 'GTM から発行されたコンテナ ID を入れてください。', 'nishiki_pro' ),
					'section'  => 'section_' . NISHIKI_PRO_PREFIX_ANALYTICS,
					'settings' => 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_header',
				)
			)
		);

		// Header
		$wp_customize->add_setting(
			'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtag_header',
			array(
				'sanitize_callback' => 'nishiki_pro_sanitize_text',
			)
		);

		// アナリティクスID（GTM）
		$wp_customize->add_setting(
			'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtm_id',
			array(
				'default'           => '',
				'sanitize_callback' => 'nishiki_pro_sanitize_textarea',
			)
		);

		$wp_customize->add_control(
			'ctrl_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtm_id',
			array(
				'label'       => __( 'Google タグマネージャーコンテナ ID', 'nishiki_pro' ),
				'description' => __( 'GTM-XXXXXXX の形式で入れてください。', 'nishiki_pro' ),
				'type'        => 'text',
				'section'     => 'section_' . NISHIKI_PRO_PREFIX_ANALYTICS,
				'settings'    => 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtm_id',
			)
		);

		$wp_customize->add_control(
			new Nishiki_WP_Customize_Content(
				$wp_customize,
				'ctrl_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtag_header',
				array(
					'label'    => '<p class="nishiki-pro-customizer-heading">Google アナリティクス測定 ID</p>',
					'description' => __( 'Google タグマネージャーをすでに設定している場合は空欄のままにしてください。', 'nishiki_pro' ),
					'section'  => 'section_' . NISHIKI_PRO_PREFIX_ANALYTICS,
					'settings' => 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtag_header',
				)
			)
		);

		// アナリティクスID（GA4）
		$wp_customize->add_setting(
			'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtag_id',
			array(
				'default'           => '',
				'sanitize_callback' => 'nishiki_pro_sanitize_textarea',
			)
		);

		$wp_customize->add_control(
			'ctrl_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtag_id',
			array(
				'label'       => __( 'GA4 測定 ID', 'nishiki_pro' ),
				'description' => __( 'G-XXXXXXXXXX の形式で入れてください。', 'nishiki_pro' ),
				'type'        => 'text',
				'section'     => 'section_' . NISHIKI_PRO_PREFIX_ANALYTICS,
				'settings'    => 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtag_id',
			)
		);

		// Header
		$wp_customize->add_setting(
			'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_range_header',
			array(
				'sanitize_callback' => 'nishiki_pro_sanitize_text',
			)
		);

		$wp_customize->add_control(
			new Nishiki_WP_Customize_Content(
				$wp_customize,
				'ctrl_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_range_header',
				array(
					'label'    => '<p class="nishiki-pro-customizer-heading">計測範囲</p>',
					'description' => __( '', 'nishiki_pro' ),
					'section'  => 'section_' . NISHIKI_PRO_PREFIX_ANALYTICS,
					'settings' => 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_range_header',
				)
			)
		);

		// Range
		$wp_customize->add_setting(
			'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_range',
			array(
				'default'           => false,
				'sanitize_callback' => 'nishiki_pro_sanitize_checkbox',
			)
		);

		$wp_customize->add_control(
			'ctrl_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_range',
			array(
				'label'    => __( 'Include logged-in users in the measurement range', 'nishiki-pro' ),
				'type'     => 'checkbox',
				'section'  => 'section_' . NISHIKI_PRO_PREFIX_ANALYTICS,
				'settings' => 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_range',
			)
		);
	}
}


// Add GTM(head)
if ( ! function_exists( 'nishiki_pro_google_tag_manager_head_script2' ) ) {
	add_action( 'wp_head', 'nishiki_pro_google_tag_manager_head_script2', 100 );

	/**
	 * Add GTM(head)
	 *
	 * @return void
	 */
	function nishiki_pro_google_tag_manager_head_script2() {
		if( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_range' ) == false || get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_range' == '' ) ){
			if( is_user_logged_in() ){
				return false;
			}
		}

		if ( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtm_id' ) !== '' ) {
			$code = esc_html( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtm_id', '' ) );

			$output = <<< EOM
			<!-- Google Tag Manager -->
			<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
			new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
			j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
			'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
			})(window,document,'script','dataLayer','{$code}');</script>
			<!-- End Google Tag Manager -->
			EOM;

			echo $output . "\n";
		}
	}
}

// Add GTM(body)
if ( ! function_exists( 'nishiki_pro_google_tag_manager_body_script2' ) ) {

	//add_action( 'wp_body_open', 'nishiki_pro_google_tag_manager_body_script2', 100 );

	/**
	 * Add GTM(body)
	 *
	 * @return void
	 */
	function nishiki_pro_google_tag_manager_body_script2() {
		if( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_range' ) == false || get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_range' == '' ) ){
			if( is_user_logged_in() ){
				return false;
			}
		}

		if ( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtm_id' ) !== '' ) {
			$code = esc_html( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtm_id', '' ) );

			$output = <<< EOM
			<!-- Google Tag Manager (noscript) -->
			<noscript><iframe src="https://www.googletagmanager.com/ns.html?id='{$code}'" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
			<!-- End Google Tag Manager (noscript) -->
			EOM;

			echo $output . "\n";
		}
	}

}

if ( ! function_exists( 'nishiki_pro_google_tag_manager_head_script' ) ) {
//	add_action( 'wp_head', 'nishiki_pro_google_tag_manager_head_script', 100 );
	/**
	 * Add GTM(head)
	 *
	 * @return void
	 */
	function nishiki_pro_google_tag_manager_head_script() {
		if( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_range' ) == false || get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_range' == '' ) ){
			if( is_user_logged_in() ){
				return false;
			}
		}

		if ( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtm_head_script' ) !== '' ) {
			$code = get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtm_head_script', '' );
			$code = str_replace( '&amp;', '&', $code );
			echo $code . "\n";
		}
	}
}

// Add GTM(body)
if ( ! function_exists( 'nishiki_pro_google_tag_manager_body_script' ) ) {

//	add_action( 'wp_body_open', 'nishiki_pro_google_tag_manager_body_script', 100 );

	/**
	 * Add GTM(body)
	 *
	 * @return void
	 */
	function nishiki_pro_google_tag_manager_body_script() {
		if( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_range' ) == false || get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_range' == '' ) ){
			if( is_user_logged_in() ){
				return false;
			}
		}

		if ( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtm_body_script' ) !== '' ) {
			$code = get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtm_body_script', '' );
			$code = str_replace( '&amp;', '&', $code );
			echo $code . "\n";
		}
	}

}

// Add Google Analytics ID（gtag）
if ( ! function_exists( 'nishiki_pro_google_analytics_gtag_id' ) ) {

	add_action( 'wp_head', 'nishiki_pro_google_analytics_gtag_id', 100 );

	/**
	 * Google アナリティクス ID（gtag）
	 *
	 * @return void
	 */
	function nishiki_pro_google_analytics_gtag_id() {
		if( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_range' ) == false || get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_range' == '' ) ){
			if( is_user_logged_in() ){
				return false;
			}
		}

		if ( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtag_id' ) !== false && get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtag_id' ) !== '' ) {
			$code   = get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_ANALYTICS . '_gtag_id', false );
			$output = <<< EOM
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', '{$code}');
EOM;
			echo '<!-- Global site tag (gtag.js) - Google Analytics -->';
			echo '<script async src="https://www.googletagmanager.com/gtag/js?id=' . esc_attr( $code ) . '"></script>' . "\n";
			echo '<script>' . wp_kses_post( $output ) . '</script>' . "\n";
		}
	}

}
