<?php
/**
 *
 * Adyen Payment Module
 *
 * @extends Magento_Multishipping::checkout/billing.phtml
 * @var Adyen\Payment\Block\Checkout\Multishipping\Billing $block
 * @var Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer
 */
?>

<div id="checkout-loader" data-role="checkout-loader" class="loading-mask" data-mage-init='{"billingLoader": {}}'>
    <div class="loader">
        <img src="<?= $block->escapeUrl($block->getViewFileUrl('images/loader-1.gif')); ?>"
             alt="<?= $block->escapeHtml(__('Loading...')); ?>">
    </div>
</div>

<?php


$checkoutConfig = $block->getCheckoutData()->getSerializedCheckoutConfigs();
$scriptString = <<<script
    window.checkoutConfig = {$checkoutConfig};
    window.isCustomerLoggedIn = window.checkoutConfig.isCustomerLoggedIn;
    window.customerData = window.checkoutConfig.customerData;
script;

/* @noEscape */
echo $secureRenderer->renderTag('script', [], $scriptString, false);
?>

<div id="checkout" data-bind="scope:'checkoutMessages'">
    <!-- ko template: getTemplate() --><!-- /ko -->
    <script type="text/x-magento-init">
        {
            "#checkout": {
                "Magento_Ui/js/core/app": {
                   "components": {
                        "checkoutMessages": {
                            "component": "Magento_Ui/js/view/messages",
                            "displayArea": "messages"
                        }
                    }
                }
            }
        }
    </script>
</div>

<form action="<?= $block->escapeUrl($block->getPostActionUrl()); ?>"
      method="post"
      id="multishipping-billing-form"
      class="form multicheckout billing">

    <!-- Adyen plugin customization -->
    <input name="payment[cc_number]" id="stateData" type="hidden">
    <div id="cc_actionContainer">
        <div id="cc_actionModal">
            <div id="cc_actionModalContent"></div>
        </div>
    </div>
    <!-- End: Adyen plugin customization -->

    <div class="block block-billing">
        <div class="block-content">
            <div class="box box-billing-address">
                <strong class="box-title">
                    <span><?= $block->escapeHtml(__('Billing Address')); ?></span>
                    <a href="<?= $block->escapeUrl($block->getSelectAddressUrl()); ?>" class="action">
                        <span><?= $block->escapeHtml(__('Change')); ?></span>
                    </a>
                </strong>
                <div class="box-content">
                    <address>
                        <?= /* @noEscape */ $block->getCheckoutData()->getAddressHtml($block->getAddress()); ?>
                    </address>
                </div>
            </div>
            <div class="box box-billing-method">
                <fieldset class="fieldset">
                    <legend class="legend box-title">
                        <span><?= $block->escapeHtml(__('Payment Method')); ?></span>
                    </legend><br>
                    <div class="box-content">
                        <?= $block->getChildHtml('payment_methods_before') ?>
                        <dl class="checkout-payment-method" id="payment-methods">
                            <?php
                            $methods = $block->getMethods();
                            $methodsCount = count($methods);
                            $methodsForms = $block->hasFormTemplates() ? $block->getFormTemplates(): [];

                            foreach ($methods as $_method):
                                $code = $_method->getCode();
                                $checked = $block->getSelectedMethodCode() === $code;
                                if (isset($methodsForms[$code])) {
                                    $block->setMethodFormTemplate($code, $methodsForms[$code]);
                                }
                                ?>
                                <div data-bind="scope: 'payment_method_<?= $block->escapeHtml($code); ?>'">
                                    <dt class="item-title" data-bind="<?= str_starts_with($code, 'adyen_') ? 'visible: paymentMethodReady' : '' ?>">
                                        <?php if ($methodsCount > 1): ?>
                                            <input type="radio"
                                                   id="p_method_<?= $block->escapeHtml($code); ?>"
                                                   value="<?= $block->escapeHtml($code); ?>"
                                                   name="payment[method]"
                                                   title="<?= $block->escapeHtml($_method->getTitle()) ?>"
                                                   data-bind="
                                                       value: getCode(),
                                                       checked: isChecked,
                                                       visible: isRadioButtonVisible(),
                                                       click: selectPaymentMethod"
                                                   class="radio"/>
                                        <?php else: ?>
                                            <input type="radio"
                                                   id="p_method_<?= $block->escapeHtml($code); ?>"
                                                   value="<?= $block->escapeHtml($code); ?>"
                                                   name="payment[method]"
                                                   title="<?= $block->escapeHtml($_method->getTitle()) ?>"
                                                   data-bind="value: getCode(), afterRender: selectPaymentMethod"
                                                   checked="checked"
                                                   class="radio solo method" />
                                        <?php endif; ?>
                                        <label for="p_method_<?= $block->escapeHtml($code); ?>">
                                            <?= $block->escapeHtml($_method->getTitle()) ?>
                                        </label>
                                    </dt>
                                    <?php if ($html = $block->getChildHtml('payment.method.' . $code)): ?>
                                        <dd class="item-content <?= $checked ? '' : 'no-display'; ?>">
                                            <?= /* @noEscape */ $html; ?>
                                        </dd>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </dl>
                        <?= $block->getChildHtml('payment_methods_after') ?>
                        <?= $block->getChildHtml('checkout_billing_items') ?>
                    </div>
                </fieldset>
            </div>
        </div>
    </div>
    <div class="actions-toolbar">
        <div class="primary" id="parent-payment-continue">
            <button id="payment-continue"
                    type="button"
                    class="action primary continue">
                <span><?= $block->escapeHtml(__('Go to Review Your Order')); ?></span>
            </button>
        </div>
        <div class="secondary">
            <a href="<?= $block->escapeUrl($block->getBackUrl()); ?>" class="action back">
                <span><?= $block->escapeHtml(__('Back to Shipping Information')); ?></span>
            </a>
        </div>
    </div>
</form>

<?php
// JS for mage payment & validation
$quoteBaseGrandTotal = (float)$block->getQuoteBaseGrandTotal();
$scriptString = <<<script
    require(['jquery', 'mage/mage'], function(jQuery) {
        var addtocartForm = jQuery('#multishipping-billing-form');

        addtocartForm.mage('payment', {
            checkoutPrice: {$quoteBaseGrandTotal}
        });

        addtocartForm.mage('validation', {
            errorPlacement: function(error, element) {
                if (element.attr('data-validate') && element.attr('data-validate').indexOf('validate-cc-ukss') >= 0) {
                    element.parents('form').find('[data-validation-msg="validate-cc-ukss"]').html(error);
                } else {
                    element.after(error);
                }
            }
        });
    });
script;

/* @noEscape */
echo $secureRenderer->renderTag('script', [], $scriptString, false);

// JS to populate billing address in JS model
$address = $block->getAddress();
$addressData = json_encode($address->getStreet());
$scriptString = <<<script
    require(
        ['Magento_Checkout/js/model/quote', 'jquery', 'domReady!'],
        function(quote, \$) {
            quote.billingAddress({
                city: '{$block->escapeJs($address->getCity())}',
                company: '{$block->escapeJs($address->getCompany())}',
                countryId: '{$block->escapeJs($address->getCountryId())}',
                customerAddressId: '{$block->escapeJs($address->getCustomerAddressId())}',
                customerId: '{$block->escapeJs($address->getCustomerId())}',
                fax: '{$block->escapeJs($address->getFax())}',
                firstname: '{$block->escapeJs($address->getFirstname())}',
                lastname: '{$block->escapeJs($address->getLastname())}',
                postcode: '{$block->escapeJs($address->getPostcode())}',
                regionId: '{$block->escapeJs($address->getRegionId())}',
                regionCode: '{$block->escapeJs($address->getRegionCode())}',
                region: '{$block->escapeJs($address->getRegion())}',
                street: {$addressData},
                telephone: '{$block->escapeJs($address->getTelephone())}'
            });
        }
    );
script;

/* @noEscape */
echo $secureRenderer->renderTag('script', [], $scriptString, false);

$adyenMethodsJson = $block->escapeJs($block->getAdyenPaymentMethodsResponse());
$adyenScript = <<<script
    require([
        'Adyen_Payment/js/model/adyen-payment-service'
    ], function(adyenPaymentService) {
        let adyenPaymentMethods = '{$adyenMethodsJson}';
        let paymentMethods = JSON.parse(adyenPaymentMethods);
        adyenPaymentService.setPaymentMethods(paymentMethods);
    });
script;

/* @noEscape */
echo $secureRenderer->renderTag('script', [], $adyenScript, false);
?>
