<?php /** @var \Adyen\Payment\Model\Config\Adminhtml\ConfigurationWizard $block */ ?>
<?php echo $block->getNextButtonHtml() ?>
<span class="adyen-required-settings-config-admin" id="progress" style="display: none">
    <img class="processing" hidden="hidden" alt="Configuring" style="margin:0 5px" src="<?= $block->escapeUrl($block->getViewFileUrl('images/process_spinner.gif')) ?>"/>
    <img class="configured" hidden="hidden" alt="Configured" style="margin:-3px 5px" src="<?= $block->escapeUrl($block->getViewFileUrl('images/rule_component_apply.gif')) ?>"/>
<script>
    require(['jquery'], function ($) {
        $(window).on('load', function () {
            const configMode = $("select[name*='configuration_mode']");
            const demoModeSelector = "div.adyen_required_config_settings select[name*='demo_mode']";
            const testApiKeySelector = "div.adyen_required_config_settings input[name*='api_key_test']";
            const liveApiKeySelector = "div.adyen_required_config_settings input[name*='api_key_live']";
            const merchantAccountSelector = "div.adyen_required_config_settings select[name*='merchant_account_auto']";
            const livePrefixUrlSelector = "div.adyen_required_config_settings input[name*='live_endpoint_url_prefix']";
            const testClientKeySelector = "div.adyen_required_config_settings input[name*='client_key_test']";
            const liveClientKeySelector = "div.adyen_required_config_settings input[name*='client_key_live']";
            const webhookUsernameSelector = "div.adyen_required_config_settings input[name*='notification_username']";
            const webhookPasswordSelector = "div.adyen_required_config_settings input[name*='notification_password']";
            const createNewWebhookSelector = "div.adyen_required_config_settings input[name*='create_new_webhook']";
            const hasPlatformIntegrator = "div.adyen_required_config_settings select[name*='has_platform_integrator']";
            const platformIntegrator = "div.adyen_required_config_settings input[name*='platform_integrator']";
            const actionButton = $("#adyen_configuration_action");
            const resetButton = $("#adyen_configuration_action_reset");

            let merchantAccounts = [];
            let configured;

            $(document).ready(function() {
                resetButton.hide();

                if (parseInt($(demoModeSelector).val())) {
                    configured = <?=$block->testConfigured() ? 'true' : 'false';?>;
                } else {
                    configured = <?=$block->liveConfigured() ? 'true' : 'false';?>;
                }
                resetButton.on('click', function () {
                    if (window.confirm("Are you sure you want to reconfigure Required Settings?")) {
                        resetAutoConfiguration();
                        renderAutoConfiguration();
                    }
                });

                configMode.on('change', renderAutoConfiguration.bind(configMode));

                renderAutoConfiguration();
            });

            function renderAutoConfiguration() {
                if (configMode[0].value === 'manual') {
                    return;
                }
                if (configured) {
                    let demoMode = $(demoModeSelector).val();

                    if (parseInt(demoMode)) {
                        showConfigField($(testClientKeySelector), false);
                    } else {
                        showConfigField($(liveClientKeySelector), false);
                        showConfigField($(livePrefixUrlSelector), false);
                    }
                    showConfigField($(merchantAccountSelector), false);
                    showConfigField($(webhookUsernameSelector), false);
                    showConfigField($(webhookPasswordSelector), false);
                    showConfigField($(hasPlatformIntegrator));

                    actionButton.hide();
                    resetButton.show();
                } else {
                    actionButton.on('click', loadMerchantAccountsAndClientKey);
                }
            }

            function resetAutoConfiguration() {
                let demoMode = $(demoModeSelector).val();
                if (parseInt(demoMode)) {
                    hideConfigField($(testClientKeySelector));
                } else {
                    hideConfigField($(liveClientKeySelector));
                    hideConfigField($(livePrefixUrlSelector));
                }
                hideConfigField($(merchantAccountSelector));
                hideConfigField($(webhookUsernameSelector));
                hideConfigField($(webhookPasswordSelector));
                hideConfigField($(hasPlatformIntegrator));
                hideConfigField($(platformIntegrator));
                configured = false;

                actionButton.show();
                resetButton.hide();
            }

            function loadMerchantAccountsAndClientKey() {
                progressUpdate('start');
                let demoMode = $(demoModeSelector).val();
                let apiKey = parseInt(demoMode)
                    ? $(testApiKeySelector).val()
                    : $(liveApiKeySelector).val();
                $.ajax('<?= $block->escapeJs($block->getMerchantAccountsUrl()) ?>', {
                    data: {apiKey, demoMode},
                    method: "POST"
                }).done(function (response) {
                    let clientKey = response.clientKey;
                    if (parseInt(demoMode)) {
                        let clientKeyTest = $(testClientKeySelector);
                        clientKeyTest.val(clientKey);
                        showConfigField(clientKeyTest);
                    } else {
                        let clientKeyLive = $(liveClientKeySelector);
                        clientKeyLive.val(clientKey);
                        showConfigField(clientKeyLive);
                    }
                    let merchantAccountSelect = document.querySelector(merchantAccountSelector);
                    // remove previous merchant accounts from dropdown
                    for (let i = merchantAccountSelect.options.length - 1; i >= 0; i--) {
                        merchantAccountSelect.remove(i);
                    }
                    // save merchant accounts mapping with liveprefix urls to global constant
                    merchantAccounts = response.merchantAccounts;
                    // add merchant accounts to dropdown
                    for (i = 0; i < merchantAccounts.length; i++) {
                        merchantAccountSelect.add(new Option(merchantAccounts[i].name, merchantAccounts[i].id));
                    }
                    if (response.currentMerchantAccount) {
                        merchantAccountSelect.value = response.currentMerchantAccount;
                    }
                    showConfigField($(merchantAccountSelector));
                    $(merchantAccountSelector).change({merchantAccounts}, prefillLivePrefix);

                    prefillLivePrefix({data: {merchantAccounts, value: merchantAccountSelect.value}});

                    // update action button listener to perform next action
                    actionButton.off();
                    actionButton.on('click', consentNewWebhookCreation);
                    progressUpdate('success', 'Click Next to generate notification username and password.');
                }).fail(function(response) {
                    progressUpdate('error', 'Unable to load merchant accounts: ' + response.responseJSON.error);
                });
            }

            /**
             * Prefill livePrefixUrl based on mapping in merchantAccounts variable
             */
            function prefillLivePrefix(event) {
                let merchantAccounts = event.data.merchantAccounts;
                let value = event.data.value;
                if (value === undefined) {
                    value = this.value;
                }
                if (parseInt($(demoModeSelector).val())) {
                    return;
                }

                let livePrefixUrlField = $(livePrefixUrlSelector);
                let livePrefixUrl;

                for (let i = 0; i < merchantAccounts.length; i++) {
                    if (merchantAccounts[i].id === value) {
                        livePrefixUrl = merchantAccounts[i].liveEndpointPrefix
                    }
                }

                if (livePrefixUrl !== undefined) {
                    livePrefixUrlField.val(livePrefixUrl);
                }

                showConfigField(livePrefixUrlField);
            }

            function consentNewWebhookCreation() {
                showConfigField($(createNewWebhookSelector));
                showConfigField($(webhookUsernameSelector));
                showConfigField($(webhookPasswordSelector));
                showConfigField($(hasPlatformIntegrator));
                if ($(hasPlatformIntegrator).val() === '1') {
                    showConfigField($(platformIntegrator));
                }

                $('*[id*=create_new_webhook0]').prop('checked', true);

                convertActionButtonToFinished();

                progressUpdate('success', 'You completed the configuration. Now, you can click "<?= $block->escapeJs(__('Save Config')) ?>" to save it');

                $(createNewWebhookSelector).on('change', function () {
                    let createNewWebhook = parseInt(this.value);

                    if (createNewWebhook) {
                        generateWebhookCredentials();
                    } else {
                        $(webhookUsernameSelector).val('');
                        $(webhookPasswordSelector).val('');
                    }
                });
            }

            function generateWebhookCredentials() {
                let username = 'webhookuser';
                let password = generateRandomPassword();

                $(webhookUsernameSelector).val(username);
                $(webhookPasswordSelector).val(password);
            }

            function progressUpdate(action, message='') {
                const progress = $('#progress');
                const notification = $('#adyen_payments_configured_message');
                notification.html('');
                switch (action) {
                    case 'start':
                        progress.show();
                        progress.find('.processing').show();
                        progress.find('.configured').hide();
                        progress.find('#adyen_payments_configuration_errors').hide();
                        notification.text('').show();
                        break;
                    case 'success':
                        progress.find('.processing').hide();
                        progress.find('.configured').show();
                        progress.find('#adyen_payments_configuration_errors').hide();
                        notification.text(message).show();
                        break;
                    case 'error':
                        progress.find('.processing').hide();
                        progress.find('.configured').hide();
                        progress.find('#adyen_payments_configuration_errors').show();
                        progress.find('#adyen_payments_configuration_errors').find('.message').text(message);
                        break;
                }
            }

            function showConfigField(field, enable=true) {
                field.parents('tr').show();
                field.show();
                if (enable) {
                    field.prop('disabled', false);
                }
            }

            function hideConfigField(field) {
                field.parents('tr')[0].hide();
                field.prop('disabled', true);
                field.hide();
            }

            function generateRandomPassword() {
                var pass = '';
                var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';

                for (let i = 1; i <= 10; i++) {
                    var char = Math.floor(Math.random()
                        * str.length + 1);

                    pass += str.charAt(char)
                }

                return pass;
            }

            function convertActionButtonToFinished() {
                actionButton.off();
                actionButton.html('<span>Complete</span>');
                actionButton.removeClass('primary');
                actionButton.addClass('disabled ui-button');
                actionButton.attr('disabled', 'disabled');
                actionButton.hide();
            }
        });
    });
</script>
<span id="adyen_payments_configured_message"></span>
    <div id="adyen_payments_configuration_errors" class="message-system-inner">
        <div class="message message-warning"></div>
    </div>
</span>
<?php echo $block->getResetButtonHtml() ?>
