{% 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.registerTranslations('app', [
    "Are you sure you want to delete this photo?",
]) %}

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

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

{% 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 -%}
        <input type="hidden" name="userId" value="{{ user.id }}">
    {%- endif %}
{% endset %}

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

{% block actionButton %}
    {% if not currentUser.can('registerUsers') or CraftEdition != CraftPro %}
        <div class="btn submit formsubmit" data-form="userform">{{ 'Save'|t('app') }}</div>
    {% else %}
        <div class="btngroup">
            <div class="btn submit formsubmit" data-form="userform">{{ 'Save'|t('app') }}</div>
            <div class="btn submit menubtn" data-form="userform"></div>
            <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 %}
    <form id="userform" method="post" accept-charset="UTF-8" data-saveshortcut data-saveshortcut-redirect="{{ (user.getIsCurrent() ? 'myaccount' : (CraftEdition == CraftPro and currentUser.can('editUsers') ? 'users/{id}' : 'dashboard'))|hash }}" data-confirm-unload>
        <input type="hidden" name="action" value="users/save-user">
        {{ redirectInput(CraftEdition == CraftPro and currentUser.can('editUsers') ? 'users' : 'dashboard') }}
        {{ hiddenInputs }}

        <div id="account">
            {% include "users/_accountfields" %}

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

            <hr>

            {% if isNewUser %}

                {{ forms.textField({
                    label: "Email"|t('app'),
                    instructions: (requireEmailVerification and not currentUser.admin ? 'A verification email will be sent automatically.'|t('app')),
                    id: 'email',
                    name: 'email',
                    value: user.email,
                    required: true,
                    type: 'email',
                    errors: user.getErrors('email')|merge(user.getErrors('unverifiedEmail'))
                }) }}

                {% if requireEmailVerification and currentUser.admin %}
                    {{ forms.checkboxField({
                        label: "Send an activation email now?"|t('app'),
                        name: 'sendVerificationEmail',
                        checked: true
                    }) }}
                {% endif %}

            {% elseif user.getIsCurrent() or currentUser.admin or currentUser.can('administrateUsers') %}

                {{ forms.textField({
                    label: "Email"|t('app'),
                    instructions: (requireEmailVerification and not currentUser.admin ? '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'))
                }) }}

                {% if user.getIsCurrent() %}
                    {{ forms.textField({
                        label: "New Password"|t('app'),
                        id: 'newPassword',
                        name: 'newPassword',
                        type: 'password',
                        autocomplete: 'new-password',
                        errors: user.getErrors('newPassword')
                    }) }}

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

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

            {% endif %}
        </div>

        {% for tab in user.getFieldLayout().getTabs() %}
            <div id="profile-{{ tab.getHtmlId() }}" class="hidden">
                {% include "_includes/fields" with {
                    fields:  tab.getFields(),
                    element: user
                } only %}
            </div>
        {% endfor %}

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

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

                    {% set assignableGroups = craft.app.userGroups.getAssignableGroups(user) %}

                    {% set userGroupsInput %}
                        <input type="hidden" name="groups" value="">

                        {% if assignableGroups %}
                            <ul>
                                {% for group in assignableGroups %}
                                    <li>
                                        {{ forms.checkbox({
                                            label: group.name|t('site')|e,
                                            name: 'groups[]',
                                            value: group.id,
                                            checked: (group.id in currentGroupIds)
                                        }) }}
                                    </li>
                                {% endfor %}
                            </ul>

                        {% else %}
                            <p>{{ "No user groups exist yet."|t('app') }}</p>
                        {% endif %}
                    {% endset %}

                    {{ forms.field({
                        fieldId: 'user-groups'
                    }, userGroupsInput) }}

                    <hr>
                {% endif %}

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

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

                    <input type="hidden" name="permissions" value="">

                    <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="hidden">
                {% set languageInput %}
                    <div class="select">
                        <select id="language" name="preferredLanguage">
                            {% set allAppLocales = craft.app.i18n.getAppLocales()|multisort('displayName')|index('id') %}
                            {% set userLanguage = user.getPreferredLanguage() ?: craft.app.language %}

                            {% if allAppLocales[userLanguage] is not defined %}
                                {% set userLanguage = userLanguage|replace('/-.*/', '') %}
                                {% if allAppLocales[userLanguage] is not defined %}
                                    {% set userLanguage = 'en' %}
                                {% endif %}
                            {% endif %}

                            {% for locale in allAppLocales %}
                                <option value="{{ locale.id }}" {% if locale.id == userLanguage %}selected{% endif %}>{{ locale.getDisplayName() }}</option>
                            {% endfor %}
                        </select>
                    </div>
                {% endset %}

                {{ forms.field({
                    id: 'language',
                    label: "Language"|t('app')
                }, languageInput) }}

                {{ 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)
                }) }}

                {% if user.admin %}
                    <hr>

                    {{ forms.checkboxField({
                        label: "Show the debug toolbar on the front end"|t('app'),
                        name: 'enableDebugToolbarForSite',
                        id: 'enableDebugToolbarForSite',
                        checked: user.getPreference('enableDebugToolbarForSite')
                    }) }}

                    {{ forms.checkboxField({
                        label: "Show the debug toolbar on the Control Panel"|t('app'),
                        name: 'enableDebugToolbarForCp',
                        id: 'enableDebugToolbarForCp',
                        checked: user.getPreference('enableDebugToolbarForCp')
                    }) }}
                {% endif %}
            </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>
                                <div id="action-menubtn" class="btn menubtn" data-icon="settings" title="{{ 'Actions'|t('app') }}"></div>
                                <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.getStatus() == '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 %}
