<?php
/**
 *
 * Adyen Payment module (https://www.adyen.com/)
 *
 * Copyright (c) 2022 Adyen N.V. (https://www.adyen.com/)
 * See LICENSE.txt for license details.
 *
 * Author: Adyen <magento@adyen.com>
 */

// @codingStandardsIgnoreFile
/**
 * @var \Adyen\Payment\Block\Form\Moto $block
 */
$ccType = $block->getInfoData('cc_type');
$ccExpMonth = $block->getInfoData('cc_exp_month');
$ccExpYear = $block->getInfoData('cc_exp_year');
$motoMerchantAccounts = $block->getMotoMerchantAccounts();

?>

<fieldset class="admin__fieldset payment-method"
          id="payment_form_adyen_moto"
          style="display:none">

    <input name="payment[stateData]" id="adyen_moto-statedata" type="hidden">
    <input name="payment[motoMerchantAccount]" id="adyen_moto-merchant-account" type="hidden">

    <label for="adyen_moto_merchant_accounts" class="admin__field-label">
       <span>
           <?= $escaper->escapeHtml(__('MOTO Merchant Account')) ?>
       </span>
    </label>
    <?php if ($motoMerchantAccounts): ?>
    <div class="admin__field-control">
        <select id="adyen_moto_merchant_accounts" class="required-entry admin__control-select">
            <option value=""><?= $escaper->escapeHtml(__('Please select...')) ?></option>
            <?php foreach ($motoMerchantAccounts as $key => $value): ?>
                <option value="<?= $escaper->escapeHtmlAttr($key) ?>" data-adyen-client-key="<?= $escaper->escapeHtmlAttr($value['clientkey']) ?>"><?= $escaper->escapeHtml($key) ?></option>
            <?php endforeach; ?>
        </select>
    </div>
    <?php else: ?>
        <p class="admin__field-error">
            <?= $escaper->escapeHtml(__('No Adyen MOTO merchant account found. Please configure MOTO merchant accounts in the plugin configuration page.')) ?>
        </p>
    <?php endif ?>
    <div id="cardContainer-adyen_moto" style=""></div>

    <?php
    $availableCcTypesByAlt = json_encode($block->getCcAvailableTypesByAlt());
    $countryCode = $block->getCountryId();
    $environment = $block->getCheckoutEnvironment();
    $locale = $block->getLocale();
    $amount = $block->getAmount();
    $formattedInstallments = $block->getFormattedInstallments();

    $scriptString = <<<script
        define(
            'renderCheckoutComponent',
            [
                'jquery',
                'Adyen_Payment/js/adyen'
            ],
            function($, AdyenWeb) {
                let card = null;
                return {
                    status: function () {
                        return card;
                    },
                    init: function (clientKey, amount, installmentAmounts) {
                        (async function () {
                            let ccTypes = $availableCcTypesByAlt;
                            let cardNode = document.getElementById("cardContainer-adyen_moto");

                            let checkoutComponent = await window.AdyenWeb.AdyenCheckout({
                                clientKey: clientKey,
                                countryCode: "$countryCode",
                                environment: "$environment",
                                locale: "$locale",
                                risk: {
                                    enabled: false
                                },
                            });

                            let cardComponentConfiguration = {
                                brands: Object.keys(ccTypes),
                                hideCVC: true,
                                enableStoreDetails: false,
                                hasHolderName: true,
                                installmentOptions: installmentAmounts,
                                showInstallmentAmounts: true,
                                showPayButton: false,
                                amount: amount,
                                onChange: function (state) {
                                    if (state.isValid) {
                                        $('#adyen_moto-statedata').val(JSON.stringify(state.data));
                                    }
                                }
                            };

                            try {
                                card = window.AdyenWeb.createComponent(
                                    'card',
                                    checkoutComponent,
                                    cardComponentConfiguration
                                );

                                card.mount(cardNode);
                            } catch (e) {
                                console.log(e);
                            }
                        })();
                    },

                    unmount: function () {
                        card.unmount();
                    }
                }
            }
        );

        require(
            [
                'jquery',
                'renderCheckoutComponent',
            ],
            function ($, renderCheckoutComponent) {
                $("#adyen_moto_merchant_accounts").on("change", function () {
                    if (renderCheckoutComponent.status() !== null) {
                        renderCheckoutComponent.unmount();
                    }

                    let amount = $amount;
                    let installmentAmounts = $formattedInstallments;

                    let clientKey = $(this).find("option:selected").attr('data-adyen-client-key');
                    let merchantAccount = $(this).find("option:selected").val();

                    if (merchantAccount === "") {
                        return;
                    }

                    $("#adyen_moto-merchant-account").val(merchantAccount);
                    renderCheckoutComponent.init(clientKey, amount, installmentAmounts);
                });
            }
        );
    script;
    ?>

    <?= /* @noEscape */ $secureRenderer->renderTag('script', [], $scriptString, false) ?>
</fieldset>
