<?php
/**
 * Copyright © Simplyin. All rights reserved.
 *
 * CSRF form_key injection for SimplyIN Hyva Checkout.
 * Patches window.fetch to automatically include Magento's form_key
 * in all POST requests to simplyin/* endpoints.
 *
 * This ensures compatibility with Magento's native CsrfValidator
 * which requires form_key in all non-GET requests.
 */
declare(strict_types=1);

use Magento\Framework\Escaper;
use Magento\Framework\View\Element\Template;

/** @var Template $block */
/** @var Escaper $escaper */

// Get form_key from the session
$formKey = $block->getFormKey();
?>
<script>
(function() {
    'use strict';

    var FORM_KEY = '<?= $escaper->escapeJs($formKey) ?>';

    // Store original fetch
    var originalFetch = window.fetch;

    // Override fetch to inject form_key for SimplyIN API calls
    window.fetch = function(url, options) {
        // Only apply to SimplyIN API endpoints with POST method
        if (url && typeof url === 'string' && url.indexOf('simplyin/') !== -1) {
            options = options || {};
            var method = (options.method || 'GET').toUpperCase();

            if (method === 'POST' && options.body) {
                try {
                    var body = JSON.parse(options.body);
                    if (typeof body === 'object' && body !== null && !body.form_key) {
                        body.form_key = FORM_KEY;
                        options.body = JSON.stringify(body);
                    }
                } catch (e) {
                    // Not JSON body — skip
                }
            }
        }

        return originalFetch.apply(this, arguments);
    };
})();
</script>
