<?php
/**
 *
 * Adyen Payment Module
 *
 * Copyright (c) 2021 Adyen N.V.
 * This file is open source and available under the MIT license.
 * See the LICENSE file for more info.
 *
 * Author: Adyen <magento@adyen.com>
 */

/**
 * @var \Adyen\Payment\Block\Checkout\Multishipping\Success $block
 */
$paymentResponseEntities = $block->getPaymentResponseEntities();
?>
<form action="<?= $block->escapeUrl($block->getContinueUrl()); ?>" method="post">
    <div class="multicheckout success">
        <p><?= $block->escapeHtml(__('For successfully order items, you\'ll receive a confirmation email including ' .
                'order numbers, tracking information and more details.')) ?></p>
        <?php if ($orderIds = $block->getOrderIds()) : ?>
            <h3><?= $block->escapeHtml(__('Successfully ordered')) ?></h3>
            <div class="orders-succeed">
                <ul class="orders-list">
                    <?php foreach ($orderIds as $orderId => $incrementId) : ?>
                        <li class="shipping-list">
                            <div class="order-id"><a
                                        href="<?= $block->escapeUrl($block->getViewOrderUrl($orderId)); ?>">
                                    <?= $block->escapeHtml($incrementId); ?></a>
                            </div>
                            <?php $shippingAddress = $block->getCheckoutData()->getOrderShippingAddress($orderId); ?>
                            <div class="shipping-item">
                                <?php if ($shippingAddress) : ?>
                                    <span class="shipping-label"><?= $block->escapeHtml(__('Ship to:')); ?></span>
                                    <span class="shipping-address">
                            <?= $block->escapeHtml(
                                $block->getCheckoutData()->formatOrderShippingAddress($shippingAddress)
                            ); ?>
                        </span>
                                <?php else : ?>
                                    <span class="shipping-address">
                                <?= $block->escapeHtml(__('No shipping required.')); ?>
                            </span>
                                <?php endif; ?>

                                <?php if($block->isAdyenPayment() === true): ?>
                                    <!-- Adyen custom 'Complete Payment' button -->
                                    <span class="adyen-continue-payment">
                                            <button
                                                <?php if ($block->getIsPaymentCompleted($orderId)): ?>
                                                    disabled="disabled"
                                                    class="adyen-finish-payment adyen-payment-finished"
                                                <?php else: ?>
                                                    class="adyen-finish-payment adyen-payment-unfinished"
                                                    data-order-id="<?= $block->escapeHtml($orderId); ?>"
                                                    data-adyen-response="<?= $block->escapeHtml(
                                                        $paymentResponseEntities[array_search(
                                                            $incrementId,
                                                            array_column(
                                                                $paymentResponseEntities,
                                                                'merchant_reference'
                                                            )
                                                        )]['response']
                                                    ); ?>"
                                                <?php endif; ?>
                                            ><?= $block->escapeHtml($block->getPaymentButtonLabel($orderId)); ?></button>
                                    <div class="adyen-component"></div>
                                    </span>
                                    <!-- End of Adyen custom 'Complete Payment' button -->
                                <?php endif; ?>

                            </div>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>
        <?= $block->getChildHtml() ?>
        <div class="actions-toolbar" id="review-buttons-container">
            <div class="primary">
                <button type="submit"
                        class="action primary submit"><span><?= $block->escapeHtml(__('Continue Shopping')); ?></span>
                </button>
            </div>
        </div>
    </div>
</form>
<?php if ($block->renderAction()):
    $checkoutConfig = /* @noEscape */
        $block->getSerializedCheckoutConfig();
    $scriptString = __('window.checkoutConfig = %1;', $checkoutConfig);
    ?>
    <script type="text/javascript">
        <?= /* @noEscape */ $scriptString ?>

        require([
            'jquery',
            'Adyen_Payment/js/adyen',
            'Magento_Checkout/js/model/full-screen-loader',
            'Adyen_Payment/js/model/adyen-payment-service',
            'Magento_Checkout/js/model/error-processor',
            'Magento_Ui/js/model/messages',
            'Adyen_Payment/js/model/adyen-payment-modal'
        ], function ($, AdyenWeb, fullScreenLoader, adyenPaymentService, errorProcessor, Messages, adyenPaymentModal) {
        (async function () { // RequireJS does not support async callback
            let checkoutComponent = await window.AdyenWeb.AdyenCheckout({
                locale: '<?= $block->escapeHtml($block->getLocale()); ?>',
                countryCode: '<?= $block->escapeHtml($block->getBillingCountryCode()); ?>',
                environment: '<?= $block->escapeHtml($block->getEnvironment()); ?>',
                clientKey: '<?= $block->escapeHtml($block->getClientKey()); ?>',
                onAdditionalDetails: handleOnAdditionalDetails.bind(this),
            });

            let paymentSelected;
            let modalLabel = 'actionModal'
            let messageContainer = new Messages();

            function showModal() {
                let orderId = $(paymentSelected).data('order-id');

                /**
                 * Setting labels to payment failed on closing the modal
                 * // TODO: This function should be removed once multishipping
                 *  allows a modal to be closed without closing the order
                 */
                function setPaymentFailedLabel(paymentFailed) {
                    if (paymentFailed) {
                        let buttonLabel = "<?= $block->escapeHtml($block->getPaymentFailedLabel()) ?>";

                        $(paymentSelected).attr('disabled', true)
                            .addClass('adyen-payment-finished')
                            .removeClass('adyen-payment-unfinished')
                            .html(buttonLabel);
                    }
                }

                return adyenPaymentModal.showModal(adyenPaymentService, fullScreenLoader, messageContainer, orderId, modalLabel, setPaymentFailedLabel)
            }

            function closeModal(popupModal) {
                adyenPaymentModal.closeModal(popupModal, modalLabel)
            }

            function handleOnAdditionalDetails(result) {
                let self = this;
                let request = result.data;
                let orderId = $(paymentSelected).data('order-id');
                fullScreenLoader.stopLoader();
                let popupModal = showModal();
                adyenPaymentService.paymentDetails(request, orderId, true).done(function (responseJSON) {
                    handleAdyenResult(responseJSON, $(paymentSelected).data('order-id'));
                }).fail(function (response) {
                    errorProcessor.process(response, self.messageContainer);
                    let buttonLabel = "<?= $block->escapeHtml($block->getPaymentFailedLabel()) ?>";
                    $(paymentSelected).attr('disabled', true)
                        .addClass('adyen-payment-finished')
                        .removeClass('adyen-payment-unfinished')
                        .html(buttonLabel);
                });
                closeModal(popupModal);
                fullScreenLoader.stopLoader();
            }

            function handleAdyenResult(responseJSON, orderId) {
                var self = this;
                var response = JSON.parse(responseJSON);
                let buttonLabel;
                if (!!response.isFinal && response.resultCode === 'Authorised') {
                    buttonLabel = "<?= $block->escapeHtml($block->getPaymentCompletedLabel()) ?>";
                } else if (!!response.isFinal && response.resultCode === 'Refused') {
                    buttonLabel = "<?= $block->escapeHtml($block->getPaymentFailedLabel()) ?>";
                }

                $(paymentSelected).attr('disabled', true)
                    .addClass('adyen-payment-finished')
                    .removeClass('adyen-payment-unfinished')
                    .html(buttonLabel);

                if (!response.isFinal) {
                    self.handleAction(response.action, orderId);
                }
            }

            $('.adyen-finish-payment').on('click', function (e) {
                e.preventDefault();
                paymentSelected = this;
                try {
                    let response = $(this).data('adyen-response');

                    if (response.resultCode !== 'RedirectShopper') {
                        showModal();
                    }

                    checkoutComponent
                        .createFromAction(response.action)
                        .mount("#" + modalLabel + "Content");
                } catch (err) {
                    console.log(err);
                }
            });

        })();
        });
    </script>
    <div id="actionModalWrapper">
        <div id="actionModal">
            <div id="actionModalContent"></div>
        </div>
    </div>
<?php endif; ?>
