<?php
/** @var Oney\ThreeByFour\Block\Catalog\Product $this */
$i = 0;
$simulations = $this->getInstalments();
$cc = $this->addCountryCodeTranslation();
$merchantGuid = $this->getMerchantGuid();
$frWidgetOptions = $this->getFranceWidgetOptions();
$simulationAmont = 0;
$businessTransactionCodes = [];

if (!empty($simulations)) :
?>
    <div class="oney-threebyfour-product-view-container" <?php if ($this->getIsConfigurable()): ?>style="display: none"<?php endif; ?>>
        
        <p><?= __('Or pay in'.$cc) ?></p>
        <?php foreach($simulations as $simulation) : ?>
            <?php
                $simulationAmont = $simulation['payment_amount'];
                $businessTransactionCodes[] = $simulation['business_transaction_details']['business_transaction_code'];
            ?>
            <?php if (++$i === count($simulations) && count($simulations) > 1) : ?>
                <p><?= __("Or".$cc) ?></p>
            <?php endif; ?>
            <span class="bubble small-bubble">
                <span><?= (count($simulation['instalments']) + 1) ?></span>
                <span>x</span>
            </span>
        <?php endforeach; ?>
        <p><?= __('with your credit card'.$cc) ?></p>
        <span class="title simulate-button open-simulation" onClick="threebyfourOneyProductPageWidget();">
            <?= __('Simulate'.$cc) ?>
        </span>
        <div id="threebyfourOneyProductSimulationContainer"></div>
    </div>

    <script>
        function threebyfourOneyProductPageWidget() {
            let options = {
                country: "<?= $this->escapeHtml($this->getCountryCode() ?: 'FR') ?>",
                language: "<?= $this->escapeHtml($this->getLanguageCode()) ?>",
                merchant_guid: "<?= $merchantGuid ?>",
                payment_amount: <?= number_format($simulationAmont, 2, '.', '') ?>,
                filter_by: "business_transaction_codes",
                business_transaction_codes: <?= json_encode($businessTransactionCodes) ?>,
                short_simulation_placeholder: "#threebyfourOneyProductSimulationContainer"
            };
            const frWidgetOptions = <?= json_encode($frWidgetOptions) ?>;
            if (Object.keys(frWidgetOptions).length) {
                options = Object.assign(options, frWidgetOptions);
            }

            loadOneyWidget(function () {
                oneyMerchantApp.loadSimulationPopin({ options });
            });
        }
    </script>

<?php endif; ?>