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

// @codingStandardsIgnoreFile
/**
 * @var \Magento\Payment\Block\Adminhtml\Transparent\Form $block
 */
$code = $block->escapeHtml($block->getMethodCode());
$ccType = $block->getInfoData('cc_type');
$ccExpMonth = $block->getInfoData('cc_exp_month');
$ccExpYear = $block->getInfoData('cc_exp_year');
?>

<fieldset class="admin__fieldset payment-method" id="payment_form_<?php /* @noEscape */
echo $code; ?>" style="display:none">
    <span id="noApiKey" class="message message-error error" style="visibility: hidden"><?php echo $block->escapeHtml(__('Please configure an API Key and a live endpoint prefix(if in Production Mode) in your Adyen Required Settings'));?></span>
    <div class="field admin__field">
        <label for="<?php /* @noEscape */
        echo $code; ?>_cc_owner">
            <span><?php echo $block->escapeHtml(__('Name on Card')); ?></span>
        </label>
        <div>
            <input type="text" id="<?php /* @noEscape */
            echo $code; ?>_cc_owner" name="payment[holderName]"
                   title="<?php echo $block->escapeHtml(__('Name on Card')); ?>" class="admin__control-text"
                   value="<?php /* @noEscape */
                   echo $block->getInfoData('cc_owner'); ?>"
                   placeholder="<?php echo $block->escapeHtml(__('Name on Card')); ?>"/>
        </div>
    </div>

    <div id="cardContainer-<?php /* @noEscape */
    echo $code; ?>"></div>
    <input id="<?php /* @noEscape */
    echo $code; ?>-number" type="hidden" name="payment[number]">
    <input id="<?php /* @noEscape */
    echo $code; ?>-cvc" type="hidden" name="payment[cvc]">
    <input id="<?php /* @noEscape */
    echo $code; ?>-expiryMonth" type="hidden" name="payment[expiryMonth]">
    <input id="<?php /* @noEscape */
    echo $code; ?>-expiryYear" type="hidden" name="payment[expiryYear]">
    <input id="<?php /* @noEscape */
    echo $code; ?>-cc_type" type="hidden" name="payment[cc_type]">
    <input id="<?php /* @noEscape */
    echo $code; ?>-store_cc" type="hidden" name="payment[store_cc]">

    <?php if ($block->isVaultEnabled()): ?>
        <div class="field choice">
            <input type="checkbox"
                   id="<?php /* @noEscape */
                   echo $code; ?>_vault"
                   name="payment[is_active_payment_token_enabler]"
                   class="checkbox"/>
            <label class="label" for="<?php /* @noEscape */
            echo $code; ?>_vault">
                <span><?php echo $block->escapeHtml('Save for later use.'); ?></span>
            </label>
        </div>
    <?php endif; ?>


    <script>
        require(
            [
                'jquery',
                'Magento_Sales/order/create/scripts',
                "Magento_Sales/order/create/form"
            ],
            function () {
                var ccTypes = <?php echo json_encode($block->getCardAvailableTypes()); ?>;

                //<![CDATA[

                // Append checkout card components script
                var scriptTag = document.createElement('script');
                scriptTag.src = "<?php echo $block->getCheckoutCardComponentJs(); ?>";
                scriptTag.type = "text/javascript";
                document.body.appendChild(scriptTag);

                // Get cc type by adyen cc type
                var getCcCodeByAltCode = function (altCode) {

                    if (ccTypes.hasOwnProperty(altCode)) {
                        return ccTypes[altCode];
                    }

                    return "";
                }

                /*
                 * Initialize secure fields and set up the onChange callback to
                 *  - fill the input fields with the encrypted data
                 *  - show the helper text when necessary
                 */
                var secureFieldsInitialize = function () {

                    if (!"<?php echo $block->getCheckoutOriginKeys(); ?>") {
                        document.getElementById('noApiKey').style="visibility: visible; display:inline-block";
                        return;
                    }
                    var cardNode = document.getElementById("cardContainer-<?php /* @noEscape */ echo $code; ?>");

                    var checkout = new AdyenCheckout({
                        locale: "<?php echo $block->getLocale(); ?>",
                        risk: {
                            enabled: false
                        }
                    });
                    var hideCVC = "<?php echo !$block->hasVerification(); ?>";

                    var card = checkout.create('card', {
                        originKey: "<?php echo $block->getCheckoutOriginKeys(); ?>",
                        environment: "<?php echo $block->getCheckoutEnvironment(); ?>",
                        type: 'card',
                        groupTypes: ccTypes,
                        hideCVC: hideCVC,
                        enableStoreDetails: "<?php echo $block->allowRecurring() && !$block->isVaultEnabled();?>",

                        onChange: function (state) {
                            // When the state is valid update the input fields
                            if (state.isValid) {
                                // Here we enable the button if the component is now valid
                                jQuery("#<?php /* @noEscape */ echo $code; ?>-number").val(state.data.paymentMethod.encryptedCardNumber);
                                jQuery("#<?php /* @noEscape */ echo $code; ?>-expiryMonth").val(state.data.paymentMethod.encryptedExpiryMonth);
                                jQuery("#<?php /* @noEscape */ echo $code; ?>-expiryYear").val(state.data.paymentMethod.encryptedExpiryYear);
                                jQuery("#<?php /* @noEscape */ echo $code; ?>-cvc").val(state.data.paymentMethod.encryptedSecurityCode);
                                jQuery("#<?php /* @noEscape */ echo $code; ?>-store_cc").val(state.data.storePaymentMethod);
                            }
                        },
                        onBrand: function (state) {
                            if (state.isValid) {
                                jQuery("#<?php /* @noEscape */ echo $code; ?>-cc_type").val(getCcCodeByAltCode(state.brand));
                            }
                        },
                        onError: function () {
                        }
                    });
                    card.mount(cardNode);
                }

                // Load card components and force wait until the external script is loaded
                if (scriptTag.readyState) {
                    scriptTag.onreadystatechange = function () {
                        if (script.readyState == "loaded" ||
                            script.readyState == "complete") {
                            script.onreadystatechange = null;
                            secureFieldsInitialize();
                        }
                    };
                }
                else {
                    scriptTag.onload = function () {
                        secureFieldsInitialize();
                    };
                }
                //]]>
            });
    </script>
</fieldset>
