{% extends 'mainapp/base.html' %}
{% load permission_tags %}

{% block title %}Права пользователя {{ custom_user.user.username }}{% endblock %}

{% block content %}
<div class="container-fluid px-3">
    <div class="row mb-3">
        <div class="col-12">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{% url 'mainapp:user_permissions_list' %}">Управление правами</a></li>
                    <li class="breadcrumb-item active">{{ custom_user.user.username }}</li>
                </ol>
            </nav>
            <h2>
                <i class="bi bi-person-gear"></i> 
                Права пользователя: {{ custom_user.user.username }}
                {% if custom_user.user.first_name or custom_user.user.last_name %}
                <small class="text-muted">({{ custom_user.user.first_name }} {{ custom_user.user.last_name }})</small>
                {% endif %}
            </h2>
        </div>
    </div>

    <form method="post">
        {% csrf_token %}
        
        <div class="card mb-3">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <span>Настройки прав</span>
                    <span class="badge {% if custom_user.role == 'admin' %}bg-danger{% elif custom_user.role == 'moderator' %}bg-warning text-dark{% else %}bg-secondary{% endif %}">
                        {{ custom_user.get_role_display }}
                    </span>
                </div>
            </div>
            <div class="card-body">
                <div class="form-check form-switch mb-3">
                    <input class="form-check-input" type="checkbox" id="use_custom_permissions" 
                           name="use_custom_permissions" {% if custom_user.use_custom_permissions %}checked{% endif %}
                           onchange="toggleCustomPermissions()">
                    <label class="form-check-label" for="use_custom_permissions">
                        <strong>Использовать индивидуальные разрешения</strong>
                    </label>
                    <div class="form-text">
                        Если выключено, будут использоваться права по умолчанию для роли "{{ custom_user.get_role_display }}"
                    </div>
                </div>
            </div>
        </div>

        <div id="permissions-container" {% if not custom_user.use_custom_permissions %}style="opacity: 0.5; pointer-events: none;"{% endif %}>
            {% for group_name, perms in permission_groups.items %}
            {% if perms %}
            <div class="card mb-3">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <span><i class="bi bi-folder"></i> {{ group_name }}</span>
                        <div>
                            <button type="button" class="btn btn-outline-success btn-sm" 
                                    onclick="selectAllInGroup('{{ group_name }}')">
                                Выбрать все
                            </button>
                            <button type="button" class="btn btn-outline-secondary btn-sm" 
                                    onclick="deselectAllInGroup('{{ group_name }}')">
                                Снять все
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="row">
                        {% for perm in perms %}
                        <div class="col-md-6 col-lg-4 mb-2">
                            <div class="form-check">
                                <input class="form-check-input perm-checkbox" type="checkbox" 
                                       name="permissions" value="{{ perm.code }}" 
                                       id="perm_{{ perm.code }}"
                                       data-group="{{ group_name }}"
                                       {% if perm.has_permission %}checked{% endif %}>
                                <label class="form-check-label" for="perm_{{ perm.code }}">
                                    <strong>{{ perm.name }}</strong>
                                    <br>
                                    <small class="text-muted">{{ perm.description }}</small>
                                </label>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
            {% endif %}
            {% endfor %}
        </div>

        <div class="d-flex gap-2 mb-4">
            <button type="submit" class="btn btn-primary">
                <i class="bi bi-check-lg"></i> Сохранить
            </button>
            <a href="{% url 'mainapp:user_permissions_list' %}" class="btn btn-secondary">
                <i class="bi bi-x-lg"></i> Отмена
            </a>
            <button type="button" class="btn btn-outline-warning" onclick="resetToDefaults()">
                <i class="bi bi-arrow-counterclockwise"></i> Сбросить к правам роли
            </button>
        </div>
    </form>
</div>

<script>
function toggleCustomPermissions() {
    const checkbox = document.getElementById('use_custom_permissions');
    const container = document.getElementById('permissions-container');
    
    if (checkbox.checked) {
        container.style.opacity = '1';
        container.style.pointerEvents = 'auto';
    } else {
        container.style.opacity = '0.5';
        container.style.pointerEvents = 'none';
    }
}

function selectAllInGroup(groupName) {
    document.querySelectorAll(`.perm-checkbox[data-group="${groupName}"]`).forEach(cb => {
        cb.checked = true;
    });
}

function deselectAllInGroup(groupName) {
    document.querySelectorAll(`.perm-checkbox[data-group="${groupName}"]`).forEach(cb => {
        cb.checked = false;
    });
}

function resetToDefaults() {
    // Снимаем все галочки
    document.querySelectorAll('.perm-checkbox').forEach(cb => {
        cb.checked = false;
    });
    
    // Устанавливаем галочки для прав по умолчанию
    const defaultPerms = [{% for perm in default_perms %}'{{ perm }}'{% if not forloop.last %}, {% endif %}{% endfor %}];
    defaultPerms.forEach(perm => {
        const checkbox = document.getElementById('perm_' + perm);
        if (checkbox) {
            checkbox.checked = true;
        }
    });
}
</script>
{% endblock %}
