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

$customAttributes = apply_filters('caos_analytics_script_element_attributes', '');
?>
<script <?= $customAttributes; ?>>
    <?php if (CAOS_OPT_SNIPPET_TYPE == 'async'): ?>
    window.ga = window.ga || function () {(ga.q = ga.q || []).push(arguments);};
    ga.l = +new Date;
    <?php else: ?>
    (function (i, s, o, g, r, a, m) {
        i['GoogleAnalyticsObject'] = r;
        i[r] = i[r] || function () {
            (i[r].q = i[r].q || []).push(arguments);
        }, i[r].l = 1 * new Date();
        a = s.createElement(o),
            m = s.getElementsByTagName(o)[0];
        a.async = 1;
        a.src = g;
        m.parentNode.insertBefore(a, m);
    })(window, document, 'script', '<?= CAOS_LOCAL_FILE_URL; ?>', 'ga');
    <?php endif; ?>
</script>

<?php
$template = new CAOS_Frontend_Tracking();
$template->get_tracking_code_template('ga-disable');

$createConfig = apply_filters('caos_analytics_ga_create_config', array(
    'cookieName' => 'caosLocalGa',
    'cookieDomain' => $_SERVER['SERVER_NAME'],
    'cookieExpires' => CAOS_COOKIE_EXPIRY_DAYS
));
?>

<script <?= $customAttributes; ?>>
    ga('create', '<?= CAOS_OPT_TRACKING_ID; ?>', <?= json_encode($createConfig); ?>);

    <?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', '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; ?>
</script>
