{% extends "_layouts/cp" %}

{% if CraftEdition == CraftPro and currentUser.can('editUsers') %}
    {% set crumbs = [
        { label: "Users"|t('app'), url: url('users') },
    ] %}
{% endif %}

{% import "_includes/forms" as forms %}

{% do view.registerAssetBundle("craft\\web\\assets\\fileupload\\FileUploadAsset") %}
{% do view.setIsDeltaRegistrationActive(true) %}

{% set requireEmailVerification = craft.app.projectConfig.get('users.requireEmailVerification') ?? true %}
{% set canAdministrateUsers = currentUser.can('administrateUsers') %}

{% if craft.app.request.isPost %}
    {% set currentGroupIds = craft.app.request.getBodyParam('groups') ?: [] %}
{% else %}
    {% set currentGroupIds = user.getGroups()|column('id') %}
{% endif %}

{% set hiddenInputs %}
    {{ csrfInput() }}
    {% if not isNewUser -%}
        {{ hiddenInput('userId', user.id) }}
    {%- endif %}
{% endset %}

{% hook "cp.users.edit" %}

{% block actionButton %}
    {% if not currentUser.can('registerUsers') or CraftEdition != CraftPro %}
        <button type="button" class="btn submit formsubmit" data-form="userform">{{ 'Save'|t('app') }}</button>
    {% else %}
        <div class="btngroup">
            <button type="button" class="btn submit formsubmit" data-form="userform">{{ 'Save'|t('app') }}</button>
            <button type="button" class="btn submit menubtn" data-form="userform"></button>
            <div class="menu">
                <ul>
                    <li>
                        <a class="formsubmit" data-redirect="{{ (isNewUser ? 'users/{id}' : user.getCpEditUrl())|hash }}">
                            {{ forms.optionShortcutLabel('S') }}
                            {{ "Save and continue editing"|t('app') }}
                        </a>
                    </li>
                    <li><a class="formsubmit" data-redirect="{{ 'users/new#'|hash }}">{{ "Save and add another"|t('app') }}</a></li>
                </ul>
            </div>
        </div>
    {% endif %}
{% endblock %}

{% block content %}
    {% set formAttributes = {
        id: 'userform',
        method: 'post',
        'accept-charset': 'UTF-8',
        data: {
            saveshortcut: true,
            'saveshortcut-redirect':  (user.getIsCurrent() ? 'myaccount' : (CraftEdition == CraftPro and currentUser.can('editUsers') ? 'users/{id}' : 'dashboard'))|hash,
            'saveshortcut-scroll': true,
            'confirm-unload': true,
            delta: true,
        },
    } %}
    <form {{ attr(formAttributes) }}>
        {{ actionInput('users/save-user') }}
        {{ redirectInput(CraftEdition == CraftPro and currentUser.can('editUsers') ? 'users' : 'dashboard') }}
        {{ hiddenInputs }}

        <div id="account" class="flex-fields">
            {% include "users/_accountfields" %}

            {% if not isNewUser and showPhotoField %}
                {{ forms.field({
                    label: "Photo"|t('app'),
                    id: 'photo'
                }, include('users/_photo', {user: user}, with_context = false)) }}
            {% endif %}

            {% if isNewUser %}
                <hr>

                {{ forms.textField({
                    label: "Email"|t('app'),
                    id: 'email',
                    name: 'email',
                    value: user.email,
                    required: true,
                    type: 'email',
                    errors: user.getErrors('email')|merge(user.getErrors('unverifiedEmail')),
                    inputAttributes: {
                        data: {lpignore: 'true'},
                    },
                }) }}

                {{ forms.checkboxField({
                    label: 'Send an activation email now'|t('app'),
                    name: 'sendActivationEmail',
                    checked: true
                }) }}

            {% elseif user.getIsCurrent() or canAdministrateUsers %}
                <hr>

                {{ forms.textField({
                    label: "Email"|t('app'),
                    warning: requireEmailVerification and not canAdministrateUsers
                        ? 'New email addresses must be verified before taking effect.'|t('app'),
                    id: 'email',
                    name: 'email',
                    value: user.email,
                    required: true,
                    type: 'email',
                    errors: user.getErrors('email')|merge(user.getErrors('unverifiedEmail')),
                    inputAttributes: {
                        data: {lpignore: 'true'},
                    },
                }) }}

                {% if user.getIsCurrent() %}
                    {{ forms.passwordField({
                        label: "New Password"|t('app'),
                        id: 'newPassword',
                        name: 'newPassword',
                        autocomplete: 'new-password',
                        errors: user.getErrors('newPassword'),
                        inputAttributes: {
                            data: {
                                lpignore: user.getIsCurrent() ? false : 'true',
                            }|filter,
                        },
                    }) }}

                    {% js %}
                        new Craft.PasswordInput('#newPassword');
                    {% endjs %}
                {% endif %}

                {% if canAdministrateUsers %}
                    {{ forms.checkboxField({
                        label: "Require a password reset on next login"|t('app'),
                        name: 'passwordResetRequired',
                        checked: user.passwordResetRequired
                    }) }}
                {% endif %}

            {% endif %}
        </div>

        {{ fieldsHtml|raw }}

        {% if CraftEdition == CraftPro and (currentUser.can('assignUserGroups') or currentUser.can('assignUserPermissions')) %}
            <div id="perms" class="flex-fields hidden">

                {% if CraftEdition == CraftPro and currentUser.can('assignUserGroups') %}
                    <fieldset>
                        <h2>{{ "User Groups"|t('app') }}</h2>

                        {% do view.registerDeltaName('groups') %}
                        {% set assignableGroups = craft.app.userGroups.getAssignableGroups(user) %}

                        {% embed '_includes/forms/field' with {
                            fieldId: 'user-groups',
                        } %}
                            {% block input %}
                                {% from '_includes/forms' import checkboxField %}
                                {{ hiddenInput('groups', '') }}
                                {% if assignableGroups %}
                                    {% for group in assignableGroups %}
                                        {{ checkboxField({
                                            label: group.name|t('site'),
                                            instructions: group.description ? group.description|t('site')|e,
                                            name: 'groups[]',
                                            value: group.id,
                                            checked: (group.id in currentGroupIds)
                                        }) }}
                                    {% endfor %}
                                {% else %}
                                    <p>{{ "No user groups exist yet."|t('app') }}</p>
                                {% endif %}
                            {% endblock %}
                        {% endembed %}
                    </fieldset>
                {% endif %}

                {% if currentUser.can('assignUserPermissions') %}
                    <h2>{{ "Permissions"|t('app') }}</h2>

                    {% if currentUser.admin and CraftEdition == CraftPro %}
                        {{ forms.checkboxField({
                            label: raw("<b>#{'Admin'|t('app')}</b>"),
                            name: 'admin',
                            id: 'admin',
                            checked: user.admin,
                            reverseToggle: 'permissions'
                        }) }}
                    {% endif %}

                    {% do view.registerDeltaName('permissions') %}
                    {{ hiddenInput('permissions', '') }}

                    <div id="permissions" class="field{% if user.admin %} hidden{% endif %}">
                        {% include "_includes/permissions" with {
                            userOrGroup: (user.admin ? null : user),
                            groupPermissions: user.id ? craft.app.userPermissions.getGroupPermissionsByUserId(user.id) : []
                        } only %}
                    </div>
                {% endif %}

            </div>
        {% endif %}

        {% if user.getIsCurrent() %}
            <div id="prefs" class="flex-fields hidden">
                {{ forms.selectField({
                    id: 'preferredLanguage',
                    name: 'preferredLanguage',
                    label: "Language"|t('app'),
                    instructions: 'The language that the control panel should use.'|t('app'),
                    options: localeOptions,
                    value: userLanguage,
                }) }}

                {{ forms.selectField({
                    id: 'preferredLocale',
                    name: 'preferredLocale',
                    label: "Formatting Locale"|t('app'),
                    instructions: 'The locale that should be used for date and number formatting.'|t('app'),
                    options: localeOptions|unshift({label: 'Same as language'|t('app'), value: ''}),
                    value: userLocale,
                }) }}

                {{ forms.selectField({
                    label: "Week Start Day"|t('app'),
                    id: 'weekStartDay',
                    name: 'weekStartDay',
                    options: craft.app.locale.getWeekDayNames(),
                    value: user.getPreference('weekStartDay', craft.app.config.general.defaultWeekStartDay)
                }) }}

                <hr>

                <fieldset>
                    {% embed '_includes/forms/field' with {
                        label: 'Accessibility'|t('app'),
                    } %}
                        {% set a11yDefaults = craft.app.config.general.accessibilityDefaults %}
                        {% block input %}
                            {% from '_includes/forms' import checkboxField %}
                            {{ checkboxField({
                                label: 'Always show focus rings'|t('app'),
                                name: 'alwaysShowFocusRings',
                                id: 'alwaysShowFocusRings',
                                checked: user.getPreference('alwaysShowFocusRings') ?? a11yDefaults['alwaysShowFocusRings'] ?? false,
                            }) }}
                            {{ checkboxField({
                                label: 'Use shapes to represent statuses'|t('app'),
                                name: 'useShapes',
                                id: 'useShapes',
                                checked: user.getPreference('useShapes') ?? a11yDefaults['useShapes'] ?? false,
                            }) }}
                            {{ checkboxField({
                                label: 'Underline links'|t('app'),
                                name: 'underlineLinks',
                                id: 'underlineLinks',
                                checked: user.getPreference('underlineLinks') ?? a11yDefaults['underlineLinks'] ?? false,
                            }) }}
                        {% endblock %}
                    {% endembed %}
                </fieldset>

                {% if user.admin %}
                    <fieldset>
                        {% embed '_includes/forms/field' with {
                            label: 'Development'|t('app'),
                        } %}
                            {% block input %}
                                {% from '_includes/forms' import checkboxField %}
                                {{ checkboxField({
                                    label: 'Show field handles in edit forms'|t('app'),
                                    name: 'showFieldHandles',
                                    id: 'showFieldHandles',
                                    checked: user.getPreference('showFieldHandles')
                                }) }}
                                {{ checkboxField({
                                    label: "Show the debug toolbar on the front end"|t('app'),
                                    name: 'enableDebugToolbarForSite',
                                    id: 'enableDebugToolbarForSite',
                                    checked: user.getPreference('enableDebugToolbarForSite')
                                }) }}
                                {{ checkboxField({
                                    label: "Show the debug toolbar in the control panel"|t('app'),
                                    name: 'enableDebugToolbarForCp',
                                    id: 'enableDebugToolbarForCp',
                                    checked: user.getPreference('enableDebugToolbarForCp')
                                }) }}
                                {{ checkboxField({
                                    label: 'Profile Twig templates when Dev Mode is disabled'|t('app'),
                                    name: 'profileTemplates',
                                    id: 'profileTemplates',
                                    checked: user.getPreference('profileTemplates')
                                }) }}
                                {{ checkboxField({
                                    label: 'Show full exception views when Dev Mode is disabled'|t('app'),
                                    name: 'showExceptionView',
                                    id: 'showExceptionView',
                                    checked: user.getPreference('showExceptionView')
                                }) }}
                            {% endblock %}
                        {% endembed %}
                    </fieldset>
                {% endif %}

                {% hook 'cp.users.edit.prefs' %}
            </div>
        {% endif %}

        {# Give plugins a chance to add other things here #}
        {% hook "cp.users.edit.content" %}

        <input type="submit" class="hidden">
    </form>
{% endblock %}

{% block details %}
    {% if not isNewUser %}
        {% if CraftEdition == CraftPro %}
            <form class="meta read-only" method="post" accept-charset="UTF-8">
                {{ hiddenInputs }}
                <div class="data first">
                    <h5 class="heading">{{ "Status"|t('app') }}</h5>
                    <div class="value flex">
                        <div class="flex-grow"><span class="status {{ user.getStatus() }}"></span> {{ statusLabel }}</div>

                        {% if actions|length %}
                            <div>
                                <button type="button" id="action-menubtn" class="btn menubtn" data-icon="settings" title="{{ 'Actions'|t('app') }}" aria-label="{{ 'Actions'|t('app') }}"></button>
                                <div class="menu">
                                    {% for actionList in actions %}
                                        {% if not loop.first %}<hr>{% endif %}
                                        <ul>
                                            {% for actionItem in actionList %}
                                                <li><a
                                                        {%- if actionItem.id is defined %} id="{{ actionItem.id }}"{% if actionItem.id == 'delete-btn' %} class="error"{% endif %}{% endif %}
                                                        {%- if actionItem.action is defined %} class="formsubmit" data-action="{{ actionItem.action }}"{% endif -%}
                                                    >{{ actionItem.label }}</a>
                                                </li>
                                            {% endfor %}
                                        </ul>
                                    {% endfor %}
                                </div>
                                <div id="action-spinner" class="spinner hidden"></div>
                            </div>
                        {% endif %}
                    </div>
                </div>

                {% if user.locked and craft.app.config.general.cooldownDuration and user.remainingCooldownTime %}
                    <div class="data">
                        <h5 class="heading">{{ "Cooldown Time Remaining"|t('app') }}</h5>
                        <p class="value">{{ user.remainingCooldownTime|duration }}</p>
                    </div>
                {% endif %}

                <div class="data">
                    <h5 class="heading">{{ "Registered at"|t('app') }}</h5>
                    <p class="value">{{ user.dateCreated|datetime('short') }}</p>
                </div>

                {% if user.getStatus() != 'pending' %}
                    <div class="data">
                        <h5 class="heading">{{ "Last login"|t('app') }}</h5>
                        <p class="value">{% if user.lastLoginDate %}{{ user.lastLoginDate|datetime('short') }}{% else %}{{ "Never"|t('app') }}{% endif %}</p>
                    </div>

                    {% if user.getStatus() == 'locked' %}
                        <div class="data">
                            <h5 class="heading">{{ "Last login fail"|t('app') }}</h5>
                            <p class="value">{% if user.lastInvalidLoginDate %}{{ user.lastInvalidLoginDate|datetime('short') }}{% endif %}</p>
                        </div>

                        <div class="data">
                            <h5 class="heading">{{ "Login fail count"|t('app') }}</h5>
                            <p class="value">{{ user.invalidLoginCount }}</p>
                        </div>
                    {% endif %}
                {% endif %}
            </form>
        {% endif %}
    {% endif %}

    {# Give plugins a chance to add other stuff here #}
    {% hook "cp.users.edit.details" %}
{% endblock %}

{% js %}
    {% if user.getIsCurrent() %}
        var changeSidebarPicture = true;
    {% else %}
        var changeSidebarPicture = false;
    {% endif %}

    new Craft.ElevatedSessionForm('#userform', [
        {% if not isNewUser %}
        '#email',
        '#newPassword',
        {% endif %}
        '#admin:not(:checked)',
        '#user-groups input[type="checkbox"]:not(:checked)',
        '#permissions input[type="checkbox"]:not(:checked)'
    ]);
{% endjs %}
