Adding a script & php to functions.php

First you should include this code in your footer.php – or similar.
Second:

if ( is_product() ) { //you are already in php
    function add_klaviyo_script() {
        echo '<?php // dont need to echo php
              $ItemId = $product->id;  // and variables

The solution(footer.php):

<footer>
   ...things
</footer>
<?php
if ( is_product() ) {
                $ImageUrl = wp_get_attachment_image_src( get_post_thumbnail_id( $loop->post->ID ), \'single-post-thumbnail\' )[0];
                $ItemId = $product->id;
                $Title = $product-> get_title();
                $ProductUrl = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
                $CurrencySymbol = get_woocommerce_currency_symbol();
                $Currency = get_woocommerce_currency();
                $Price = $product->get_price();
                $RegularPrice = $product->get_regular_price();
                $DiscountAmount = $RegularPrice - $Price;
                $terms = get_terms( \'product_tag\' );
                ?>

                <script>
                var Title = "<?php echo $Title; ?>";
                var ItemId = "<?php echo $ItemId; ?>";
                var ImageUrl = "<?php echo $ImageUrl; ?>";
                var ProductUrl = "<?php echo $ProductUrl; ?>";
                var CurrencySymbol = "<?php echo $CurrencySymbol; ?>";
                var Currency = "<?php echo $Currency; ?>";
                var Price = "<?php echo $Price; ?>";
                var DiscountAmount = "<?php echo $DiscountAmount; ?>";
                var RegularPrice = "<?php echo $RegularPrice; ?>";
                var _learnq = _learnq || [];

                    _learnq.push([\'track\', \'Viewed Product\', {
                    Title: Title,
                    ItemId: ItemId,
                    ImageUrl: ImageUrl,
                    Url: ProductUrl,
                    Metadata: {
                        Currency: Currency,
                        CurrencySymbol: CurrencySymbol,
                        Price: Price,
                        DiscountAmount: DiscountAmount,
                        RegularPrice: RegularPrice
                    }
                }]);
                </script><?php
    }
}

tech