<?php
/**
 * CleverReach WooCommerce Integration - Usersnap widget partial.
 *
 * @package CleverReach
 */

use CleverReach\WooCommerce\Controllers\Clever_Reach_Usersnap_Controller;

$usersnap = Clever_Reach_Usersnap_Controller::get_usersnap_data();

// If Usersnap is not configured, do nothing.
if (empty($usersnap) || empty($usersnap['key'])) {
	return;
}
?>

<script>
    window.onUsersnapLoad = function (api) {
        var payload = {
            user: <?php echo wp_json_encode($usersnap['meta']); ?>,
            custom: <?php echo wp_json_encode($usersnap['meta']); ?>
        };

        payload.user.pageContextUrl = window.location.href;
        payload.custom.pageContextUrl = window.location.href;

        api.init(payload);
    };

    var script = document.createElement('script');
    script.defer = 1;

    var usersnapKey = <?php echo wp_json_encode($usersnap['key']); ?>;
    script.src =
        'https://widget.usersnap.com/global/load/' +
        usersnapKey +
        '?onload=onUsersnapLoad';

    document.head.appendChild(script);

</script>
