<?php

/**
 * Hyva-compatible override of Meta_Conversion::pixel/add_payment_info.phtml
 *
 * BEST EFFORT / LIMITATION:
 * The original implementation hooks into Magento_Checkout's Knockout.js
 * "place-order-hooks" and "customer-data" modules, which are Luma-only
 * concepts. Hyva Checkout is a separate, self-contained checkout
 * implementation with its own JS architecture, so there is no universal
 * hook here.
 *
 * This override instead listens for a change on any input named
 * "payment[method]" (the standard Magento quote-API field name for the
 * selected payment method, which most checkout implementations still use
 * even with custom front-ends). Verify this fires correctly for your
 * specific checkout using Meta Events Manager's Test Events tool - if it
 * does not, you will need to dispatch this event from your checkout's own
 * JS/Alpine components instead, calling:
 *   window.MetaConversion.trackEvent(config)
 * with eventId set to null.
 *
 * @var \Meta\Conversion\Block\Pixel\AddPaymentInfo $block
 * @var \Magento\Framework\Escaper $escaper
 */

if (!function_exists('metaConversionJsonEncode')) {
    /**
     * metaConversionJsonEncode() hardened for direct interpolation into an inline <script> tag.
     */
    function metaConversionJsonEncode($value)
    {
        return json_encode($value, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
    }
}


$trackerUrl = $block->getTrackerUrl();
?>
<?php if ($block->getFacebookPixelID()): ?>
    <script>
        (function () {
            var config = {
                url: <?= /* @noEscape */ metaConversionJsonEncode($trackerUrl) ?>,
                payload: {
                    eventName: <?= /* @noEscape */ metaConversionJsonEncode($block->getEventToObserveName()) ?>
                },
                browserEventData: {
                    fbAgentVersion: <?= /* @noEscape */ metaConversionJsonEncode($block->getFacebookAgentVersion()) ?>,
                    fbPixelId: <?= /* @noEscape */ metaConversionJsonEncode($block->getFacebookPixelID()) ?>,
                    source: <?= /* @noEscape */ metaConversionJsonEncode($block->getSource()) ?>,
                    pluginVersion: <?= /* @noEscape */ metaConversionJsonEncode($block->getPluginVersion()) ?>,
                    track: 'track',
                    event: 'AddPaymentInfo',
                    payload: {
                        currency: <?= /* @noEscape */ metaConversionJsonEncode($block->getCurrency()) ?>
                    }
                }
            };

            function init() {
                window.MetaConversion.addPaymentInfo(config);
            }

            window.MetaConversion ? init() : document.addEventListener('DOMContentLoaded', init);
        })();
    </script>
<?php endif; ?>
