<?php
/**
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the GNU General Public License (GPL 3)
 * that is bundled with this package in the file LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Payone_Core to newer
 * versions in the future. If you wish to customize Payone_Core for your
 * needs please refer to http://www.payone.de for more information.
 *
 * @category        Payone
 * @package         design_frontend_base_default
 * @subpackage      template
 * @copyright       Copyright (c) 2020 <kontakt@fatchip.de> - www.fatchip.com
 * @author          Vincent Boulanger <vincent.boulanger@fatchip.de>
 * @license         <http://www.gnu.org/licenses/> GNU General Public License (GPL 3)
 * @link            http://www.fatchip.com
 */

/** @var $this Payone_Core_Block_Payment_Method_Form_KlarnaBase */
$code = $this->getMethodCode();
$quote = $this->getQuote();
$startSessionUrl = $this->getStartSessionUrl();
$availableMethods = $this->getKlarnaMethods($quote->getId());
$klarnaMethodNames = $this->getKlarnaMethodNames();
$klarnaMethodConfigIds = $this->getKlarnaMethodConfigId();

$customerDob = !empty($quote->getCustomerDob()) ? (new DateTime($quote->getCustomerDob()))->format('Y-m-d') : '';
$customerBillingPhone = $this->getCustomerBillingPhone();
$customerShippingPhone = $this->getCustomerShippingPhone();
$customerGender = $quote->getCustomerGender() == 2 ? 'female' : 'male';
$quoteLocale = str_replace('_', '-' , Mage::app()->getLocale()->getLocaleCode());
?>
<fieldset class="form-list">
    <ul id="payment_form_<?php echo $code ?>" style="display:none">
        <div id="payone_klarna_method_overlay" style="display: none"><img src="<?php echo Mage::getDesign()->getSkinUrl('images/payone/ajaxloader.gif') ?>"></div>

        <h2><?php echo $this->__('KLARNA_CHECKOUT_TITLE') ?></h2>

        <li class="fields">
            <div class="field">
                <input type="checkbox" id="payone_klarna_additional_fields_agreement_checkbox"
                       class="checkbox required-entry"/>
                <label for="payone_klarna_additional_fields_agreement_checkbox" class="required" style="float:none;">
                    <?php echo $this->__('KLARNA_CHECKOUT_DISCLAIMER') ?>
                    <em style="float:none; position:relative;">*</em>
                </label>
            </div>
        </li>

        <?php if ($this->isDobRequired()) { ?>
            <li class="fields">
                <div class="field">
                    <label for="payone_klarna_base_additional_fields_customer_dob_month"
                           class="required"><em>*</em><?php echo $this->__('Date of birth (DD MM YYYY)') ?>
                    </label>
                    <br class="clear"/>
                    <select id="payone_klarna_base_additional_fields_customer_dob_day" class="required-entry"
                            style="width: 60px;" onchange="payoneKlarnaCustomerDobInput('payone_klarna_base_additional_fields_customer_dob_full')">
                        <option value="">--</option>
                        <?php for ($x = 1; $x <= 31; $x++): ?>
                            <option value="<?php echo sprintf('%02d', $x); ?>">
                                <?php echo sprintf('%02d', $x); ?>
                            </option>
                        <?php endfor; ?>
                    </select>
                    <select id="payone_klarna_base_additional_fields_customer_dob_month" class="required-entry"
                            style="width: 60px;" onchange="payoneKlarnaCustomerDobInput('payone_klarna_base_additional_fields_customer_dob_full')">
                        <option value="">--</option>
                        <?php for ($x = 1; $x <= 12; $x++) : ?>
                            <option value="<?php echo sprintf('%02d', $x); ?>">
                                <?php echo sprintf('%02d', $x); ?>
                            </option>
                        <?php endfor; ?>
                    </select>
                    <select id="payone_klarna_base_additional_fields_customer_dob_year" class="required-entry"
                            style="width: 60px;" onchange="payoneKlarnaCustomerDobInput('payone_klarna_base_additional_fields_customer_dob_full')">
                        <option value="">----</option>
                        <?php for ($x = date('Y'); $x > (date('Y') - 100); $x--) : ?>
                            <option value="<?php echo $x; ?>">
                                <?php echo $x; ?>
                            </option>
                        <?php endfor; ?>
                    </select>
                </div>
            </li>
        <?php } ?>


        <?php if (empty($customerBillingPhone)) { ?>
            <li>
                <div class="field">
                    <label for="payone_klarna_base_additional_fields_customer_billing_telephone" class="required">
                        <em>*</em><?php echo $this->__('Telephone') ?> (<?php echo $this->__('Billing') ?>)
                    </label>
                    <br class="clear"/>
                    <input type="text" name="payment[payone_customer_billing_telephone]"
                           id="payone_klarna_base_additional_fields_customer_billing_telephone"
                           class="input-text required-entry"/>
                </div>
            </li>
        <?php } else {?>
            <input type="hidden" name="payment[payone_customer_billing_telephone]"
                   id="payone_klarna_base_additional_fields_customer_telephone"
                   value="<?php echo $customerBillingPhone; ?>"/>
        <?php } ?>

        <?php if (empty($customerShippingPhone)) { ?>
            <li>
                <div class="field">
                    <label for="payone_klarna_base_additional_fields_customer_shipping_telephone" class="required">
                        <em>*</em><?php echo $this->__('Telephone') ?> (<?php echo $this->__('Shipping') ?>)
                    </label>
                    <br class="clear"/>
                    <input type="text" name="payment[payone_customer_shipping_telephone]"
                           id="payone_klarna_base_additional_fields_customer_shipping_telephone"
                           class="input-text required-entry"/>
                </div>
            </li>
        <?php } else {?>
            <input type="hidden" name="payment[payone_customer_shipping_telephone]"
                   id="payone_klarna_base_additional_fields_customer_shipping_telephone"
                   value="<?php echo $customerShippingPhone; ?>"/>
        <?php } ?>

        <li class="fields">
            <div class="payone_klarna_methods">
                <?php foreach ($availableMethods as $methodType => $methodCode) { ?>
                    <div id="<?php echo $methodCode ?>_payment_selection" class="button payone_klarna_button">
                        <input type="hidden" id="<?php echo $methodCode ?>_payment_code" value="<?php echo $methodCode ?>" />
                        <span><?php echo isset($klarnaMethodNames[$methodType]) ? $this->__($klarnaMethodNames[$methodType]) : $methodCode ?></span>
                    </div>
                <?php } ?>
            </div>

            <h2 id="klarna_payment_title"></h2>
            <div id="klarna_payments_container"></div>
        </li>
        <li style="display:none;">
            <input type="hidden" id="klarna_config_id"  name="payment[payone_config_payment_method_id]"  value=""/>
            <input type="hidden" id="klarna_authorization_token" name="payment[authorization_token]" value=""/>
            <input type="hidden" id="payment_method_category_identifier" name="payment[payment_method_category_identifier]" value=""/>
            <input type="hidden" id="payone_klarna_base_additional_fields_customer_dob_full" name="payment[payone_customer_dob]" value="<?php echo $customerDob; ?>">
            <input type="hidden" id="payone_klarna_base_additional_fields_customer_billing_telephone" name="payment[payone_customer_billing_telephone]" value="<?php echo $customerBillingPhone; ?>">
            <input type="hidden" id="payone_klarna_base_additional_fields_customer_shipping_telephone" name="payment[payone_customer_shipping_telephone]" value="<?php echo $customerShippingPhone; ?>">
            <input type="hidden" id="quoteId" name="quoteId" value="<?php echo $quote->getId(); ?>" />
        </li>
    </ul>
</fieldset>
<script type="text/javascript">
    var klarnaBaseCode = '<?php echo Payone_Core_Model_System_Config_PaymentMethodCode::KLARNABASE ?>';
    var klarnaInvoicingCode = '<?php echo Payone_Core_Model_System_Config_PaymentMethodCode::KLARNAINVOICING ?>';
    var klarnaInstallmentCode = '<?php echo Payone_Core_Model_System_Config_PaymentMethodCode::KLARNAINSTALLMENT ?>';
    var klarnaDirectDebitCode = '<?php echo Payone_Core_Model_System_Config_PaymentMethodCode::KLARNADIRECTDEBIT ?>';

    var klarnaInvoicingMethodId = '<?php echo isset($klarnaMethodConfigIds[Payone_Core_Model_System_Config_PaymentMethodType::KLARNAINVOICING]) ? $klarnaMethodConfigIds[Payone_Core_Model_System_Config_PaymentMethodType::KLARNAINVOICING] : '' ?>';
    var klarnaInstallmentMethodId = '<?php echo isset($klarnaMethodConfigIds[Payone_Core_Model_System_Config_PaymentMethodType::KLARNAINSTALLMENT]) ? $klarnaMethodConfigIds[Payone_Core_Model_System_Config_PaymentMethodType::KLARNAINSTALLMENT] : '' ?>';
    var klarnaDirectDebitMethodId = '<?php echo isset($klarnaMethodConfigIds[Payone_Core_Model_System_Config_PaymentMethodType::KLARNADIRECTDEBIT]) ? $klarnaMethodConfigIds[Payone_Core_Model_System_Config_PaymentMethodType::KLARNADIRECTDEBIT] : '' ?>';

    var startSessionUrl = '<?php echo $startSessionUrl ?>';

    var klarnaButtons = [].slice.call(document.getElementsByClassName("payone_klarna_button"));
    klarnaButtons.forEach(function(element) {
        element.onclick = function(event) {
            var validator = new Validation(payment.form);
            if (validator.validate()) {
                payoneKlarnaSwitchOverlay(true);
                var target = event.currentTarget;
                var children = $(target).select('input');

                var methodCode = children[0].value;

                var response = payoneKlarnaStartSession(startSessionUrl, methodCode);

                var status = response.status;
                if (status == 'OK') {
                    var paymentTitle = $('klarna_payment_title');
                    paymentTitle.innerHTML = '<img style="display: inline" src="' + response.payment_method_category_asset_url_descriptive + '" />'
                        + ' <span>' + response.payment_method_category_name + '</span>';

                    var formKlarnaPaymentMethodField= $('p_method_payone_klarna_base');
                    formKlarnaPaymentMethodField.value = methodCode;

                    var klarnaConfigIdField = $('klarna_config_id');
                    if (methodCode == klarnaDirectDebitCode) {
                        klarnaConfigIdField.value = klarnaDirectDebitMethodId;
                    } else if (methodCode == klarnaInstallmentCode) {
                        klarnaConfigIdField.value = klarnaInstallmentMethodId;
                    } else if (methodCode == klarnaInvoicingCode) {
                        klarnaConfigIdField.value = klarnaInvoicingMethodId;
                    } else {
                        klarnaConfigIdField.value = '';
                        formKlarnaPaymentMethodField.value = klarnaBaseCode;
                    }

                    $('klarna_payments_container').update();
                    window.klarnaAsyncCallback(response);
                } else {
                    alert(response.customer_message);
                }
                payoneKlarnaSwitchOverlay(false);
            }
        }
    });

    window.klarnaAsyncCallback = function (sessionData) {
        Klarna.Payments.init({
            client_token: sessionData.client_token
        });

        Klarna.Payments.load({
            container: '#klarna_payments_container',
            payment_method_category: sessionData.payment_method_category_identifier
        }, function (res) {
            if (!res.show_form) {
                handlePaymentBan();
            }
        });

        var paymentMethodCategoryIdentifier = $('payment_method_category_identifier');
        paymentMethodCategoryIdentifier.value = sessionData.payment_method_category_identifier;
    };

    payment.save = payment.save.wrap(
        function (origMethod) {
            var paymentMethodCategoryIdentifier = $('payment_method_category_identifier').value;
            var formKlarnaPaymentMethod = $('p_method_payone_klarna_base');
            var customerDoB = $('payone_klarna_base_additional_fields_customer_dob_full').value;
            var customerBillingPhone = $('payone_klarna_base_additional_fields_customer_billing_telephone').value;
            var customerShippingPhone = $('payone_klarna_base_additional_fields_customer_shipping_telephone').value;

            if (!formKlarnaPaymentMethod.checked || formKlarnaPaymentMethod.value == klarnaBaseCode || paymentMethodCategoryIdentifier == '') {
                return payone.exec(origMethod);
            }

            var quoteLocale = "<?php echo $quoteLocale ?>";
            Klarna.Payments.authorize(
                {
                    payment_method_category: paymentMethodCategoryIdentifier
                },
                {
                    purchase_country: "<?php echo $this->getQuote()->getBillingAddress()->getCountry() ?>",
                    purchase_currency: "<?php echo $this->getQuote()->getQuoteCurrencyCode() ?>",
                    locale: quoteLocale,
                    billing_address: {
                        given_name: "<?php echo $this->getQuote()->getBillingAddress()->getFirstname() ?>",
                        family_name: "<?php echo $this->getQuote()->getBillingAddress()->getLastname() ?>",
                        email: "<?php echo $this->getQuote()->getBillingAddress()->getEmail() ?>",
                        street_address: "<?php echo $this->getQuote()->getBillingAddress()->getStreet1() ?>",
                        street_address2: "<?php echo $this->getQuote()->getBillingAddress()->getStreet2() ?>",
                        postal_code: "<?php echo $this->getQuote()->getBillingAddress()->getPostcode() ?>",
                        city: "<?php echo $this->getQuote()->getBillingAddress()->getCity() ?>",
                        region: "",
                        phone: customerBillingPhone,
                        country: "<?php echo $this->getQuote()->getBillingAddress()->getCountry() ?>"
                    },
                    shipping_address: {
                        given_name: "<?php echo $this->getQuote()->getShippingAddress()->getFirstname() ?>",
                        family_name: "<?php echo $this->getQuote()->getShippingAddress()->getLastname() ?>",
                        email: "<?php echo $this->getQuote()->getShippingAddress()->getEmail() ?>",
                        street_address: "<?php echo $this->getQuote()->getShippingAddress()->getStreet1() ?>",
                        street_address2: "<?php echo $this->getQuote()->getShippingAddress()->getStreet2() ?>",
                        postal_code: "<?php echo $this->getQuote()->getShippingAddress()->getPostcode() ?>",
                        city: "<?php echo $this->getQuote()->getShippingAddress()->getCity() ?>",
                        region: "",
                        phone: customerShippingPhone,
                        country: "<?php echo $this->getQuote()->getShippingAddress()->getCountry() ?>"
                    },
                    customer: {
                        date_of_birth: customerDoB,
                        gender: "<?php echo $customerGender ?>",
                    }
                },
                function(res) {
                    var status = res.approved;
                    if (status) {
                        var token = res.authorization_token;
                        var tokenField = $('klarna_authorization_token');
                        tokenField.value = token;
                        payone.exec(origMethod);
                    } else {
                        if (!res.show_form) {
                            handlePaymentBan();
                        }
                        console.debug(res.error);
                    }
                }
            );
        }
    );

    function handlePaymentBan() {
        var paymentMethodCategoryIdentifier = $('payment_method_category_identifier');
        paymentMethodCategoryIdentifier.value = '';

        var formKlarnaPaymentMethod = $('p_method_payone_klarna_base');
        formKlarnaPaymentMethod.value = klarnaBaseCode;
        console.debug(formKlarnaPaymentMethod);

        var formKlarnaPaymentMethodSelector = $('dt_method_payone_klarna_base');
        var formKlarnaPaymentMethodContainer = $('dd_method_payone_klarna_base');
        formKlarnaPaymentMethodSelector.hide();
        formKlarnaPaymentMethodContainer.hide();
    }
</script>
<script src="https://x.klarnacdn.net/kp/lib/v1/api.js" async></script>