{% import '_includes/forms' as forms %}
{% import 'formie/_macros' as formieMacros %}
{% import 'verbb-base/_macros' as macros %}

<h2>{{ 'Form Submission' | t('formie') }}</h2>

{% set submitMethod = form.settings.submitMethod ?? 'page-reload' %}
{% set submitAction = form.settings.submitAction ?? 'message' %}

{# Force Ajax if the form contains some payment fields, due to 3DS requirements #}
<div v-if="forcedAjax()">
    {{ forms.selectField({
        label: 'Submission Method' | t('formie'),
        instructions: 'Whether to reload the page when this form is submitted, or use Ajax to send this form without reloading the page.' | t('formie'),
        id: 'submitMethod',
        name: 'settings[submitMethod]',
        options: [{
            label: 'Ajax (Client-side)' | t('formie'),
            value: 'ajax',
        }],
        value: submitMethod,
        warning: 'You must use Ajax submissions when using some payment integrations in your form.' | t('formie'),
    }) }}

    {# Spacing fix #}
    <div class="field"></div>
</div>

<div v-else>
    {{ forms.selectField({
        label: 'Submission Method' | t('formie'),
        instructions: 'Whether to reload the page when this form is submitted, or use Ajax to send this form without reloading the page.' | t('formie'),
        id: 'submitMethod',
        name: 'settings[submitMethod]',
        options: [{
            label: 'Page Reload (Server-side)' | t('formie'),
            value: 'page-reload',
        },
        {
            label: 'Ajax (Client-side)' | t('formie'),
            value: 'ajax',
        }],
        value: submitMethod,
    }) }}

    {# Spacing fix #}
    <div class="field"></div>
</div>

<div class="fui-settings-wrap">
    {{ forms.selectField({
        label: 'Action on Submit' | t('formie'),
        instructions: 'When a user submits this form, I want to:' | t('formie'),
        id: 'submitAction',
        name: 'settings[submitAction]',
        value: submitAction,
        inputAttributes: {
            'data-value': submitAction,
            'data-target-prefix': 'submit-action-',
        },
    }) }}

    <hr>

    <div id="submit-action-message" class="{{ submitAction != 'message' ? 'hidden' }}">
        {{ forms.lightswitchField({
            label: 'Hide Form' | t('formie'),
            instructions: 'Whether to hide the form and only show the success message.' | t('formie'),
            id: 'submitActionFormHide',
            name: 'settings[submitActionFormHide]',
            on: form.settings.submitActionFormHide ?? false,
        }) }}

        <form-kit
            type="richText"
            label="{{ 'Submission Message' | t('formie') }}"
            help="{{ 'This text will be shown after submission, as a success message.' | t('formie') }}"
            name="settings[submitActionMessage]"
            v-model="form.settings.submitActionMessage"
            v-bind="{{ getRichTextConfig('forms.submitActionMessage') | json_encode }}"
            variables="plainTextVariables"
        ></form-kit>

        {{ forms.textField({
            label: 'Submission Message Timeout' | t('formie'),
            instructions: 'The number of seconds to automatically hide the message. Leave empty to disable hiding.' | t('formie'),
            id: 'submitActionMessageTimeout',
            name: 'settings[submitActionMessageTimeout]',
            type: 'number',
            size: 3,
            value: form.settings.submitActionMessageTimeout ?? null,
        }) }}

        {{ forms.selectField({
            label: 'Submission Message Position' | t('formie'),
            instructions: 'Where to position the success message in the form, when shown.' | t('formie'),
            name: 'settings[submitActionMessagePosition]',
            options: [
                { label: 'None' | t('formie'), value: '' },
                { label: 'Top of Form' | t('formie'), value: 'top-form' },
                { label: 'Bottom of Form' | t('formie'), value: 'bottom-form' },
            ],
            value: form.settings.submitActionMessagePosition ?? 'top-form',
        }) }}
    </div>

    <div id="submit-action-entry" class="{{ submitAction != 'entry' ? 'hidden' }}">
        {{ formieMacros.siteElementSelectField({
            label: 'Redirect Entry' | t('formie'),
            instructions: 'Select an entry for the user to be redirected to.' | t('formie'),
            id: 'submitActionEntryId',
            name: 'submitActionEntryId',
            limit: 1,
            elementType: 'craft\\elements\\Entry',
            elements: form.redirectEntry ? [ form.redirectEntry ] : [],
            showSiteMenu: true,
            jsClass: 'Craft.Formie.SiteElementSelect',
        }) }}

        {{ forms.selectField({
            label: 'Redirect Option' | t('formie'),
            instructions: 'How to redirect the user after submission, whether in the same tab, or a new tab.' | t('formie'),
            id: 'submitActionTab',
            name: 'settings[submitActionTab]',
            disabled: (submitAction == 'entry') ? false : true,
            disabled: (submitAction == 'entry' or submitAction == 'url') ? false : true,
            options: [{
                label: 'Redirect on the same tab' | t('formie'),
                value: 'same-tab',
            },
            {
                label: 'Redirect on a new tab' | t('formie'),
                value: 'new-tab',
            }],
            value: form.settings.submitActionTab ?? 'same-tab',
        }) }}
    </div>

    <div id="submit-action-url" class="{{ submitAction != 'url' ? 'hidden' }}">
        {{ forms.textField({
            label: 'Redirect URL' | t('formie'),
            instructions: 'The full URL that the user to be redirected to.' | t('formie'),
            id: 'submitActionUrl',
            name: 'settings[submitActionUrl]',
            value: form.settings.submitActionUrl ?? null,
        }) }}

        {{ forms.selectField({
            label: 'Redirect Option' | t('formie'),
            instructions: 'How to redirect the user after submission, whether in the same tab, or a new tab.' | t('formie'),
            id: 'submitActionTab',
            name: 'settings[submitActionTab]',
            disabled: (submitAction == 'url') ? false : true,
            disabled: (submitAction == 'entry' or submitAction == 'url') ? false : true,
            options: [{
                label: 'Redirect on the same tab' | t('formie'),
                value: 'same-tab',
            },
            {
                label: 'Redirect on a new tab' | t('formie'),
                value: 'new-tab',
            }],
            value: form.settings.submitActionTab ?? 'same-tab',
        }) }}
    </div>

    <div id="submit-action-reload" class="{{ submitAction != 'reload' ? 'hidden' }}">
        <div class="field">
            <div class="heading">
                <div class="instructions">
                    <p>{{ 'This will reload the page, clearing the form of values, and showing no success message.' | t('formie') }}</p>
                </div>
            </div>
        </div>
    </div>

    <div id="submit-action-reset" class="{{ submitAction != 'reset' ? 'hidden' }}">
        <div class="field">
            <div class="heading">
                <div class="instructions">
                    <p>{{ 'This will clear the form of values, and showing no success message.' | t('formie') }}</p>
                </div>
            </div>
        </div>
    </div>
</div>

{{ forms.selectField({
    label: 'Loading Indicator' | t('formie'),
    instructions: 'Whether to show a loading indicator when submitting the form. This will be shown on the submit button.' | t('formie'),
    id: 'loadingIndicator',
    name: 'settings[loadingIndicator]',
    options: [{
        label: 'None' | t('formie'),
        value: '',
    },
    {
        label: 'Spinner' | t('formie'),
        value: 'spinner',
    },
    {
        label: 'Text' | t('formie'),
        value: 'text',
    }],
    toggle: true,
    targetPrefix: 'loading-indicator-',
    value: form.settings.loadingIndicator ?? '',
}) }}

<div id="loading-indicator-text" class="hidden">
    {{ forms.textField({
        label: 'Loading Indicator Text' | t('formie'),
        instructions: 'Text shown over the submit button, when in the loading state.' | t('formie'),
        id: 'loadingIndicatorText',
        name: 'settings[loadingIndicatorText]',
        value: form.settings.loadingIndicatorText ?? null,
    }) }}
</div>

<hr>

<h2>{{ 'Validation' | t('formie') }}</h2>

{{ forms.lightswitchField({
    label: 'Validate Form on Submit' | t('formie'),
    instructions: 'Whether to validate the form client-side, when the user submits the form. This will show errors as soon as the submit button is pressed. Forms will also always be validated server-side.' | t('formie'),
    id: 'validationOnSubmit',
    name: 'settings[validationOnSubmit]',
    on: form.settings.validationOnSubmit ?? true,
}) }}

{{ forms.lightswitchField({
    label: 'Validate When Typing' | t('formie'),
    instructions: 'Whether to validate each field as the user types, so that errors will appear immediately.' | t('formie'),
    id: 'validationOnFocus',
    name: 'settings[validationOnFocus]',
    on: form.settings.validationOnFocus ?? false,
}) }}

<form-kit
    type="richText"
    label="{{ 'Error Message' | t('formie') }}"
    help="{{ 'This text will be shown when an error on the submission occurs.' | t('formie') }}"
    name="settings[errorMessage]"
    v-model="form.settings.errorMessage"
    v-bind="{{ getRichTextConfig('forms.errorMessage') | json_encode }}"
></form-kit>

{{ forms.selectField({
    label: 'Error Message Position' | t('formie'),
    instructions: 'Where to position the error message in the form, when shown.' | t('formie'),
    name: 'settings[errorMessagePosition]',
    options: [
        { label: 'None' | t('formie'), value: '' },
        { label: 'Top of Form' | t('formie'), value: 'top-form' },
        { label: 'Bottom of Form' | t('formie'), value: 'bottom-form' },
    ],
    value: form.settings.errorMessagePosition ?? 'top-form',
}) }}

<hr>

<h2>{{ 'Restrictions' | t('formie') }}</h2>

{{ forms.lightswitchField({
    label: 'Require Logged-in User' | t('formie'),
    instructions: 'Whether this form can be viewed only by logged-in users.' | t('formie'),
    id: 'requireUser',
    name: 'settings[requireUser]',
    toggle: '#require-user',
    on: form.settings.requireUser ?? false,
}) }}

<div id="require-user" class="hidden">
    <form-kit
        type="richText"
        label="{{ 'Message' | t('formie') }}"
        help="{{ 'The message displayed to users who are not logged in.' | t('formie') }}"
        name="settings[requireUserMessage]"
        v-model="form.settings.requireUserMessage"
        v-bind="{{ getRichTextConfig('forms.requireUserMessage') | json_encode }}"
    ></form-kit>
</div>

{{ forms.lightswitchField({
    label: 'Schedule Form' | t('formie'),
    instructions: 'Whether this form should only be available on a schedule.' | t('formie'),
    id: 'scheduleForm',
    name: 'settings[scheduleForm]',
    toggle: '#schedule-form',
    on: form.settings.scheduleForm ?? false,
}) }}

<div id="schedule-form" class="hidden">
    {{ forms.dateTimeField({
        label: 'Schedule Start Date' | t('formie'),
        instructions: 'Set when the form should be available from.' | t('formie'),
        id: 'scheduleFormStart',
        name: 'settings[scheduleFormStart]',
        value: form.settings.scheduleFormStart ?? null,
    }) }}

    {{ forms.dateTimeField({
        label: 'Schedule End Date' | t('formie'),
        instructions: 'Set when the form should be available until.' | t('formie'),
        id: 'scheduleFormEnd',
        name: 'settings[scheduleFormEnd]',
        value: form.settings.scheduleFormEnd ?? null,
    }) }}

    <form-kit
        type="richText"
        label="{{ 'Pending Message' | t('formie') }}"
        help="{{ 'The message displayed when the current time is before the scheduled start date.' | t('formie') }}"
        name="settings[scheduleFormPendingMessage]"
        v-model="form.settings.scheduleFormPendingMessage"
        v-bind="{{ getRichTextConfig('forms.scheduleFormPendingMessage') | json_encode }}"
    ></form-kit>

    <form-kit
        type="richText"
        label="{{ 'Expired Message' | t('formie') }}"
        help="{{ 'The message displayed when the current time is after the scheduled start date.' | t('formie') }}"
        name="settings[scheduleFormExpiredMessage]"
        v-model="form.settings.scheduleFormExpiredMessage"
        v-bind="{{ getRichTextConfig('forms.scheduleFormExpiredMessage') | json_encode }}"
    ></form-kit>
</div>

{{ forms.lightswitchField({
    label: 'Limit Submissions' | t('formie'),
    instructions: 'Whether submissions for this form should be limited to a number.' | t('formie'),
    id: 'limitSubmissions',
    name: 'settings[limitSubmissions]',
    toggle: '#limit-submissions',
    on: form.settings.limitSubmissions ?? false,
}) }}

<div id="limit-submissions" class="hidden">
    {% set limitInput %}
        <div class="flex">
            <div>
                {{ forms.text({
                    name: 'settings[limitSubmissionsNumber]',
                    value: form.settings.limitSubmissionsNumber ?? null,
                }) }}
            </div>

            <div class="flex-grow">
                {{ forms.select({
                    name: 'settings[limitSubmissionsType]',
                    options: [
                        {
                            label: 'total' | t('formie'),
                            value: 'total',
                        },
                        {
                            label: 'per day' | t('formie'),
                            value: 'day',
                        },
                        {
                            label: 'per week' | t('formie'),
                            value: 'week',
                        },
                        {
                            label: 'per month' | t('formie'),
                            value: 'month',
                        },
                        {
                            label: 'per year' | t('formie'),
                            value: 'year',
                        },
                    ],
                    value: form.settings.limitSubmissionsType ?? null,
                }) }}
            </div>
        </div>
    {% endset %}

    {{ forms.field({
        label: 'Number of Submissions' | t('formie'),
        instructions: 'The number of submissions to allow.' | t('formie'),
    }, limitInput) }}

    <form-kit
        type="richText"
        label="{{ 'Message' | t('formie') }}"
        help="{{ 'The message displayed to once the limit has been reached.' | t('formie') }}"
        name="settings[limitSubmissionsMessage]"
        v-model="form.settings.limitSubmissionsMessage"
        v-bind="{{ getRichTextConfig('forms.limitSubmissionsMessage') | json_encode }}"
    ></form-kit>
</div>

{% set actionOptions = {
    'page-reload': [
        {
            label: 'Display a message' | t('formie'),
            value: 'message',
        },
        {
            label: 'Redirect to an entry' | t('formie'),
            value: 'entry',
        },
        {
            label: 'Redirect to a URL' | t('formie'),
            value: 'url',
        },
        {
            label: 'Reload the page' | t('formie'),
            value: 'reload',
        },
    ],

    'ajax': [
        {
            label: 'Display a message' | t('formie'),
            value: 'message',
        },
        {
            label: 'Redirect to an entry' | t('formie'),
            value: 'entry',
        },
        {
            label: 'Redirect to a URL' | t('formie'),
            value: 'url',
        },
        {
            label: 'Reset form values' | t('formie'),
            value: 'reset',
        },
    ],
} %}

{% js %}

// "Action on Submit" has dynamic options, depending on the "Submission Method"
function updateSubmitActionOptions() {
    var $submitAction = $('[name="settings[submitAction]"]');
    var $submitMethod = $('[name="settings[submitMethod]"]');
    var allOptions = {{ actionOptions | json_encode | raw }};
    var options = allOptions[$submitMethod.val()];
    var selectedOption = $submitAction.val() || $submitAction.data('value');

    var output = [];

    $.each(options, function(index, option) {
        output.push('<option value="'+ option.value +'">'+ option.label +'</option>');
    });

    $submitAction.html(output.join(''));

    // Restore the original value
    $submitAction.val(selectedOption);

    // Manually find the toggle - Craft doesn't like it when set initially and values change dynamically
    $submitAction.fieldtoggle();
}

$('[name="settings[submitMethod]"]').on('change', function(e) {
    updateSubmitActionOptions();

    // Hide the panes that are unique to specific submit methods, as they'll stick around otherwise
    $('#submit-action-reload').addClass('hidden');
    $('#submit-action-reset').addClass('hidden');
});

updateSubmitActionOptions();

{% endjs %}
