<?php
/* * * * * * * * * * * * * * * * * * * *
 *  ██████╗ █████╗  ██████╗ ███████╗
 * ██╔════╝██╔══██╗██╔═══██╗██╔════╝
 * ██║     ███████║██║   ██║███████╗
 * ██║     ██╔══██║██║   ██║╚════██║
 * ╚██████╗██║  ██║╚██████╔╝███████║
 *  ╚═════╝╚═╝  ╚═╝ ╚═════╝ ╚══════╝
 *
 * @author   : Daan van den Bergh
 * @url      : https://ffw.press/wordpress/caos/
 * @copyright: (c) 2021 Daan van den Bergh
 * @license  : GPL2v2 or later
 * * * * * * * * * * * * * * * * * * * */

$createConfig = apply_filters('caos_analytics_ga_create_config', array(
    'cookieName'    => 'caosLocalGa',
    'cookieDomain'  => home_url(),
    'cookieExpires' => CAOS_COOKIE_EXPIRY_SECONDS,
    'cookieFlags'   => 'samesite=none;secure'
));
?>

<script>
    window.ga = window.ga || function() {
        (ga.q = ga.q || []).push(arguments);
    };
    ga.l = +new Date;

    <?php if (apply_filters('caos_analytics_use_local_storage', false)) : ?>
        if (window.localStorage) {
            ga('create', '<?= CAOS_OPT_TRACKING_ID; ?>', <?= str_replace('"localStorage.getItem(\'GA_CLIENT_ID_HASHED\')"', 'localStorage.getItem(\'GA_CLIENT_ID_HASHED\')', json_encode($createConfig)); ?>);
        } else {
            <?php $createConfig['clientId'] = ''; ?>
            ga('create', '<?= CAOS_OPT_TRACKING_ID; ?>', <?= str_replace('"localStorage.getItem(\'GA_CLIENT_ID_HASHED\')"', 'localStorage.getItem(\'GA_CLIENT_ID_HASHED\')', json_encode($createConfig)); ?>)
        }
    <?php else : ?>
        ga('create', '<?= CAOS_OPT_TRACKING_ID; ?>', <?= json_encode($createConfig); ?>);
    <?php endif; ?>

    <?php
    /**
     * Allow WP DEVs to easily modify CAOS' analytics.js configuration with a plugin.
     *
     * Example: add_filter('caos_analytics_before_send', 'your_filter_function_name');
     */
    ?>
    <?= implode("\n", apply_filters('caos_analytics_before_send', array(), CAOS_OPT_TRACKING_ID)); ?>
    ga('send', '<?= apply_filters('caos_analytics_hit_type', 'pageview'); ?>');
    <?php
    /**
     * Allow WP DEVs to easily modify CAOS' analytics.js configuration with a plugin.
     *
     * Example: add_filter('caos_analytics_after_send', 'your_filter_function_name');
     */
    ?>
    <?= implode("\n", apply_filters('caos_analytics_after_send', array(), CAOS_OPT_TRACKING_ID)); ?>
    <?php if (CAOS_OPT_ADJUSTED_BOUNCE_RATE) : ?>
        setTimeout("ga('send', 'event', 'Adjusted Bounce Rate', '<?= CAOS_OPT_ADJUSTED_BOUNCE_RATE . ' seconds'; ?>')", <?= CAOS_OPT_ADJUSTED_BOUNCE_RATE * 1000; ?>);
    <?php endif; ?>
    <?php if (CAOS_OPT_EXT_TRACK_AD_BLOCKERS) : ?>
        var event = new Event('caos_track_ad_blockers');
        document.dispatchEvent(event);
    <?php endif; ?>
</script>