<?php
if ( ! defined( 'ABSPATH' ) ) { exit; } // Exit if accessed directly

/**
 * Adds the GTM or gtag.js script tag in the head.
 */
add_action( 'wp_head', 'rivax_add_gtm_script' );
function rivax_add_gtm_script() {

    $gtm_id  = rivax_get_option( 'gtm-id' );
    $gtag_id = rivax_get_option( 'gtag-id' );

    if ( ! empty( $gtm_id ) ) : ?>
        <!-- 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','<?php echo esc_attr( $gtm_id ); ?>');</script>
        <!-- End Google Tag Manager -->
    <?php elseif ( ! empty( $gtag_id ) ) : ?>
        <!-- Google tag (gtag.js) -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo esc_attr( $gtag_id ); ?>"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '<?php echo esc_attr( $gtag_id ); ?>');
        </script>
    <?php endif;
}


/**
 * Adds the GTM noscript tag in the body.
 */
add_action( 'wp_body_open', 'rivax_add_gtm_noscript', 1 );
function rivax_add_gtm_noscript() {

    $gtm_id  = rivax_get_option( 'gtm-id' );

    if ( ! empty( $gtm_id ) ) :
    ?>
    <!-- Google Tag Manager (noscript) -->
    <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=<?php echo esc_attr( $gtm_id ); ?>" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <!-- End Google Tag Manager (noscript) -->
    <?php endif;
}


/**
 * Adds AMP-specific GTM or gtag.js tracking.
 */
add_action( 'amp_post_template_body_open', 'rivax_add_gtm_script_amp' );
function rivax_add_gtm_script_amp() {

    $gtm_id  = rivax_get_option( 'gtm-id' );
    $gtag_id = rivax_get_option( 'gtag-id' );

    if ( ! empty( $gtm_id ) ) : ?>
        <!-- Google Tag Manager -->
        <amp-analytics config="https://www.googletagmanager.com/amp.json?id=<?php echo esc_attr( $gtm_id ); ?>" data-credentials="include"></amp-analytics>
    <?php elseif ( ! empty( $gtag_id ) ) : ?>
        <!-- Google tag (gtag.js) -->
        <amp-analytics type="gtag" data-credentials="include">
            <script type="application/json">
						{
							"vars" : {
								"gtag_id": "<?php echo esc_attr( $gtag_id ); ?>",
								"config" : {
									"<?php echo esc_attr( $gtag_id ); ?>": { "groups": "default" }
								}
							}
						}
					</script>
        </amp-analytics>
    <?php endif;
}