<?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">
    <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>
        <div>Available card types:</div>
        <div>
            <?php foreach ($block->getCcAvailableTypes() as $typeCode => $typeName): ?>
                <span class="cc-type-<?php echo $block->escapeHtml($typeCode); ?>">
                    <?php echo $block->escapeHtml($typeName); ?>
                </span>
            <?php endforeach ?>
        </div>
        <p class="helper-text" id="cc-type-helper-text"><?php echo $block->escapeHtml(__('(Please provide a card with the type from the list above)')); ?></p>
    </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]">

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

                //<![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 heklper text when necessary
                 */
                var secureFieldsInitialize = function () {

                    var cardNode = document.getElementById("cardContainer-<?php /* @noEscape */ echo $code; ?>");

                    var checkout = new AdyenCheckout({
                        locale: "<?php echo $block->getLocale(); ?>"
                    });

                    var card = checkout.create('card', {
                        originKey: "<?php echo $block->getCheckoutOriginKeys(); ?>",
                        loadingContext: "<?php echo $block->getCheckoutContextUrl(); ?>",
                        type: 'card',
                        groupTypes: ccTypes,

                        onChange: function(state) {

                            if (state.isCardValid) {
                                jQuery("#cc-type-helper-text").hide();
                            } else {
                                jQuery("#cc-type-helper-text").show();
                            }

                            // 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.encryptedCardNumber);
                                jQuery("#<?php /* @noEscape */ echo $code; ?>-expiryMonth").val(state.data.encryptedExpiryMonth);
                                jQuery("#<?php /* @noEscape */ echo $code; ?>-expiryYear").val(state.data.encryptedExpiryYear);
                                jQuery("#<?php /* @noEscape */ echo $code; ?>-cvc").val(state.data.encryptedSecurityCode);
                                jQuery("#<?php /* @noEscape */ echo $code; ?>-cc_type").val(getCcCodeByAltCode(state.brand));
                            }
                        },
                        onError: function() {}
                    });

                    card.mount(cardNode);
                    
                    /*order.submit = order.submit.wrap(function (originalSaveMethod) {
                        attachSecureFieldsData.call(this);
                        originalSaveMethod();
                    });*/
                }

                // 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();
                    };
                }

                //]]>
            });

        // TODO Oneclick
        // cvc is not required so cvchide: true or hidecvc

    </script>
</fieldset>
