{% extends '_layouts/cp.twig' %}

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

{% import '_includes/forms.twig' 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.getActionSegments() == ['users', 'save-user'] %}
    {% 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':  (isCurrentUser ? '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.twig', {user: user}, with_context = false)) }}
            {% endif %}

            {% if isNewUser %}
                <hr>

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

                {{ forms.checkboxField({
                    label: 'Send an activation email now'|t('app'),
                    name: 'sendActivationEmail',
                    checked: (user.hasErrors() and craft.app.request.getBodyParam('sendActivationEmail')),
                }) }}

            {% elseif isCurrentUser 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,
                    type: 'email',
                    autocomplete: isCurrentUser ? 'email' : false,
                    errors: user.getErrors('email')|merge(user.getErrors('unverifiedEmail')),
                    inputAttributes: {
                        data: {lpignore: 'true'},
                    },
                }) }}

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

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

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

            {% endif %}
        </div>

        {{ fieldsHtml|raw }}

        {% if showPermissionsTab %}
            <div id="perms" class="flex-fields hidden">

                {% if canAssignUserGroups %}
                    <fieldset>
                        <h2>{{ "User Groups"|t('app') }}</h2>

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

                        {% embed '_includes/forms/field.twig' 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 %}
                        {{ 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 {
                            subject: user.admin ? null : user,
                            permissions: craft.app.userPermissions.getAssignablePermissions(user),
                            groupPermissions: user.id ? craft.app.userPermissions.getGroupPermissionsByUserId(user.id) : []
                        } only %}
                    </div>
                {% endif %}

            </div>
        {% endif %}

        {% if isCurrentUser %}
            <div id="prefs" class="flex-fields hidden">
                <h2>{{ 'General'|t('app') }}</h2>

                {{ forms.selectizeField({
                    id: 'preferredLanguage',
                    name: 'preferredLanguage',
                    label: "Language"|t('app'),
                    instructions: 'The language that the control panel should use.'|t('app'),
                    options: languageOptions,
                    value: userLanguage,
                }) }}

                {{ forms.selectizeField({
                    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,
                    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)
                }) }}

                <h2>{{ 'Accessibility'|t('app') }}</h2>

                {% set a11yDefaults = craft.app.config.general.accessibilityDefaults %}
                {{ forms.checkboxGroupField({
                    label: 'Display Settings'|t('app'),
                    options: [
                        {
                            label: 'Always show focus rings'|t('app'),
                            name: 'alwaysShowFocusRings',
                            id: 'alwaysShowFocusRings',
                            checked: user.getPreference('alwaysShowFocusRings') ?? a11yDefaults['alwaysShowFocusRings'] ?? false,
                        },
                        {
                            label: 'Use shapes to represent statuses'|t('app'),
                            name: 'useShapes',
                            id: 'useShapes',
                            checked: user.getPreference('useShapes') ?? a11yDefaults['useShapes'] ?? false,
                        },
                        {
                            label: 'Underline links'|t('app'),
                            name: 'underlineLinks',
                            id: 'underlineLinks',
                            checked: user.getPreference('underlineLinks') ?? a11yDefaults['underlineLinks'] ?? false,
                        },
                    ],
                }) }}

                {{ forms.selectField({
                    label: 'Notification Duration'|t('app'),
                    instructions: 'How long notifications should be shown before they disappear automatically.'|t('app'),
                    name: 'notificationDuration',
                    id: 'notificationDuration',
                    options: [
                        {value: 2000, label: '{num, number} {num, plural, =1{second} other{seconds}}'|t('app', {num: 2})},
                        {value: 5000, label: '{num, number} {num, plural, =1{second} other{seconds}}'|t('app', {num: 5})},
                        {value: 10000, label: '{num, number} {num, plural, =1{second} other{seconds}}'|t('app', {num: 10})},
                        {value: 0, label: 'Show them indefinitely'|t('app')},
                    ],
                    value: user.getPreference('notificationDuration') ?? a11yDefaults['notificationDuration'] ?? 5000,
                }) }}

                {% if user.admin %}
                    <h2>{{ 'Development'|t('app') }}</h2>

                    {{ forms.checkboxGroupField({
                        label: 'Development Settings'|t('app'),
                        options: [
                            {
                                label: 'Show field handles in edit forms'|t('app'),
                                name: 'showFieldHandles',
                                id: 'showFieldHandles',
                                checked: user.getPreference('showFieldHandles')
                            },
                            {
                                label: 'Profile Twig templates when Dev Mode is disabled'|t('app'),
                                name: 'profileTemplates',
                                id: 'profileTemplates',
                                checked: user.getPreference('profileTemplates')
                            },
                            {
                                label: 'Show full exception views when Dev Mode is disabled'|t('app'),
                                name: 'showExceptionView',
                                id: 'showExceptionView',
                                checked: user.getPreference('showExceptionView')
                            },
                        ],
                    }) }}

                    {{ forms.checkboxGroupField({
                        label: 'Debug Toolbar'|t('app'),
                        options: [
                            {
                                label: "Show the debug toolbar on the front end"|t('app'),
                                name: 'enableDebugToolbarForSite',
                                id: 'enableDebugToolbarForSite',
                                checked: user.getPreference('enableDebugToolbarForSite')
                            },
                            {
                                label: "Show the debug toolbar in the control panel"|t('app'),
                                name: 'enableDebugToolbarForCp',
                                id: 'enableDebugToolbarForCp',
                                checked: user.getPreference('enableDebugToolbarForCp')
                            },
                        ],
                    }) }}
                {% 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>
                                {{ forms.button({
                                    class: 'menubtn',
                                    attributes: {
                                        id: 'action-menubtn',
                                        title: 'Actions'|t('app'),
                                        aria: {
                                            label: 'Actions'|t('app'),
                                        },
                                        data: {
                                            icon: 'settings',
                                        },
                                    },
                                    spinner: true,
                                }) }}
                                <div class="menu">
                                    {% for actionList in actions %}
                                        {% if not loop.first %}<hr>{% endif %}
                                        <ul>
                                            {% for actionItem in actionList %}
                                                <li>
                                                    {{ tag('a', {
                                                        id: actionItem.id ?? false,
                                                        class: [
                                                            (actionItem.action ?? false) ? 'formsubmit',
                                                            (actionItem.destructive ?? false) ? 'error',
                                                        ]|filter,
                                                        data: {
                                                            action: actionItem.action ?? false,
                                                            confirm: actionItem.confirm ?? false,
                                                        },
                                                        text: actionItem.label,
                                                    }) }}
                                                </li>
                                            {% endfor %}
                                        </ul>
                                    {% endfor %}
                                </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">{{ 'Created 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 isCurrentUser %}
        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 %}
