{% extends "base.html" %}

{% block title %}Permisos de {{ application.name }} - Administración{% endblock %}
{% block header_title %}Gestión de Permisos{% endblock %}

{% block content %}
<div class="page-header">
    <div class="d-flex justify-content-between align-items-start">
        <div>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ url_for('admin_dashboard') }}">Administración</a></li>
                    <li class="breadcrumb-item"><a href="{{ url_for('admin_applications') }}">Aplicaciones</a></li>
                    <li class="breadcrumb-item active">Permisos</li>
                </ol>
            </nav>
            <h1 class="page-title">Permisos de {{ application.name }}</h1>
            <p class="page-subtitle">Gestiona quién puede ver y acceder a esta aplicación</p>
        </div>
        <div class="d-flex gap-2">
            <a href="{{ url_for('admin_edit_application', app_id=application.id) }}" class="btn btn-outline-primary">
                <i class="fas fa-edit me-2"></i>Editar App
            </a>
            <a href="{{ url_for('admin_applications') }}" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left me-2"></i>Volver
            </a>
        </div>
    </div>
</div>

<!-- Información de la aplicación -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <div class="d-flex align-items-center">
                            <div class="me-3">
                                {% if application.icon_filename %}
                                <img src="{{ application.icon_url }}" alt="{{ application.name }}"
                                     class="rounded" style="width: 48px; height: 48px; object-fit: cover;">
                                {% else %}
                                <div class="bg-primary text-white rounded d-flex align-items-center justify-content-center"
                                     style="width: 48px; height: 48px;">
                                    <i class="fas fa-server"></i>
                                </div>
                                {% endif %}
                            </div>
                            <div>
                                <h5 class="mb-1">{{ application.name }}</h5>
                                <p class="text-muted mb-1">{{ application.description or 'Sin descripción' }}</p>
                                <small class="text-muted">
                                    <i class="fas fa-globe me-1"></i>{{ application.full_url }}
                                </small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 text-md-end">
                        <div class="d-flex flex-column align-items-md-end gap-2">
                            <span class="badge bg-{{ 'warning' if application.is_private else 'success' }}">
                                <i class="fas fa-{{ 'lock' if application.is_private else 'globe' }} me-1"></i>
                                {{ 'Privada' if application.is_private else 'Pública' }}
                            </span>
                            {% if application.category %}
                            <span class="badge" style="background-color: {{ application.category.color }}20; color: {{ application.category.color }};">
                                <i class="{{ application.category.icon }} me-1"></i>{{ application.category.name }}
                            </span>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Configuración de privacidad -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-cog me-2"></i>Configuración de Privacidad
                </h5>
            </div>
            <div class="card-body">
                <form method="POST" action="{{ url_for('admin_update_application_privacy', app_id=application.id) }}">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-check form-switch mb-3">
                                <input class="form-check-input" type="checkbox" id="is_private" name="is_private"
                                       {% if application.is_private %}checked{% endif %}>
                                <label class="form-check-label" for="is_private">
                                    <strong>Aplicación Privada</strong>
                                </label>
                            </div>
                            <p class="text-muted small">
                                Las aplicaciones privadas solo son visibles para usuarios autorizados.
                            </p>
                        </div>

                        <div class="col-md-6" id="departmentsSection" style="display: {{ 'block' if application.is_private else 'none' }};">
                            <label for="allowed_departments" class="form-label">Departamentos Permitidos</label>
                            <input type="text" class="form-control" id="allowed_departments" name="allowed_departments"
                                   value="{{ application.allowed_departments or '' }}"
                                   placeholder="IT, Contabilidad, Gerencia">
                            <div class="form-text">Departamentos separados por comas</div>

                            {% if departments %}
                            <div class="mt-2">
                                <small class="text-muted">Disponibles:</small>
                                <div class="d-flex flex-wrap gap-1 mt-1">
                                    {% for dept in departments %}
                                    <span class="badge bg-light text-dark cursor-pointer" onclick="addDepartment('{{ dept }}')">
                                        {{ dept }}
                                    </span>
                                    {% endfor %}
                                </div>
                            </div>
                            {% endif %}
                        </div>
                    </div>

                    <div class="mt-3">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save me-2"></i>Guardar Configuración
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Permisos específicos de usuarios -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-users me-2"></i>Permisos Específicos de Usuarios
                </h5>
                <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addPermissionModal">
                    <i class="fas fa-plus me-1"></i>Agregar Usuario
                </button>
            </div>
            <div class="card-body">
                {% if permissions %}
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Usuario</th>
                                <th>Departamento</th>
                                <th>Acceso</th>
                                <th>Otorgado por</th>
                                <th>Fecha</th>
                                <th>Notas</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for permission, user in permissions %}
                            <tr>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="me-2">
                                            <div class="bg-secondary text-white rounded-circle d-flex align-items-center justify-content-center"
                                                 style="width: 32px; height: 32px;">
                                                {{ user.full_name[0].upper() }}
                                            </div>
                                        </div>
                                        <div>
                                            <strong>{{ user.full_name }}</strong>
                                            <br><small class="text-muted">{{ user.username }}</small>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span class="badge bg-light text-dark">{{ user.department or 'Sin departamento' }}</span>
                                </td>
                                <td>
                                    <span class="badge bg-{{ 'success' if permission.can_access else 'danger' }}">
                                        <i class="fas fa-{{ 'check' if permission.can_access else 'times' }} me-1"></i>
                                        {{ 'Permitido' if permission.can_access else 'Denegado' }}
                                    </span>
                                </td>
                                <td>
                                    {% if permission.granted_by %}
                                    <small class="text-muted">{{ permission.granted_by }}</small>
                                    {% else %}
                                    <small class="text-muted">Sistema</small>
                                    {% endif %}
                                </td>
                                <td>
                                    <small class="text-muted">{{ permission.granted_at.strftime('%d/%m/%Y') }}</small>
                                </td>
                                <td>
                                    <small class="text-muted">{{ permission.notes[:50] if permission.notes else '-' }}</small>
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <button class="btn btn-outline-warning" data-bs-toggle="modal"
                                                data-bs-target="#editPermissionModal"
                                                onclick="editPermission({{ permission.id }}, {{ user.id }}, '{{ user.full_name }}', {{ permission.can_access|tojson }}, '{{ permission.notes or '' }}')">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <form method="POST" action="{{ url_for('admin_delete_user_permission', app_id=application.id, permission_id=permission.id) }}"
                                              style="display: inline;" onsubmit="return confirm('¿Eliminar este permiso?')">
                                            <button type="submit" class="btn btn-outline-danger">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                {% else %}
                <div class="text-center py-5">
                    <i class="fas fa-users fa-3x text-muted mb-3"></i>
                    <h6>No hay permisos específicos configurados</h6>
                    <p class="text-muted">Los usuarios accederán según la configuración de departamentos o permisos generales.</p>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addPermissionModal">
                        <i class="fas fa-plus me-2"></i>Agregar Primer Usuario
                    </button>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- Modal para agregar permiso -->
<div class="modal fade" id="addPermissionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-user-plus me-2"></i>Agregar Permiso de Usuario
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="{{ url_for('admin_add_user_permission', app_id=application.id) }}">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="user_id" class="form-label">Usuario</label>
                        <select class="form-control" id="user_id" name="user_id" required>
                            <option value="">Seleccionar usuario...</option>
                            {% for user in all_users %}
                            <option value="{{ user.id }}" data-department="{{ user.department or '' }}">
                                {{ user.full_name }} ({{ user.username }})
                                {% if user.department %} - {{ user.department }}{% endif %}
                            </option>
                            {% endfor %}
                        </select>
                    </div>

                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="can_access" name="can_access" checked>
                            <label class="form-check-label" for="can_access">
                                Permitir acceso
                            </label>
                        </div>
                        <div class="form-text">Desmarcar para denegar explícitamente el acceso</div>
                    </div>

                    <div class="mb-3">
                        <label for="notes" class="form-label">Notas (opcional)</label>
                        <textarea class="form-control" id="notes" name="notes" rows="3"
                                  placeholder="Razón para otorgar/denegar el acceso..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>Guardar Permiso
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal para editar permiso -->
<div class="modal fade" id="editPermissionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-user-edit me-2"></i>Editar Permiso de Usuario
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="{{ url_for('admin_add_user_permission', app_id=application.id) }}" id="editPermissionForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Usuario</label>
                        <input type="hidden" id="edit_user_id" name="user_id">
                        <div class="p-2 bg-light rounded border">
                            <span id="edit_user_name"></span>
                        </div>
                    </div>

                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="edit_can_access" name="can_access">
                            <label class="form-check-label" for="edit_can_access">
                                Permitir acceso
                            </label>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="edit_notes" class="form-label">Notas</label>
                        <textarea class="form-control" id="edit_notes" name="notes" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>Actualizar Permiso
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const isPrivateCheckbox = document.getElementById('is_private');
    const departmentsSection = document.getElementById('departmentsSection');

    // Toggle sección de departamentos
    isPrivateCheckbox.addEventListener('change', function() {
        departmentsSection.style.display = this.checked ? 'block' : 'none';
    });
});

// Función para agregar departamento
function addDepartment(dept) {
    const input = document.getElementById('allowed_departments');
    const currentValue = input.value.trim();

    if (!currentValue) {
        input.value = dept;
    } else if (!currentValue.split(',').map(d => d.trim()).includes(dept)) {
        input.value = currentValue + ', ' + dept;
    }

    input.focus();
}

// Función para editar permiso
function editPermission(permissionId, userId, userName, canAccess, notes) {
    document.getElementById('edit_user_id').value = userId;
    document.getElementById('edit_user_name').textContent = userName;
    document.getElementById('edit_can_access').checked = canAccess;
    document.getElementById('edit_notes').value = notes;
}

// Filtro de usuarios en select
document.getElementById('user_id').addEventListener('input', function() {
    const searchTerm = this.value.toLowerCase();
    const options = this.querySelectorAll('option');

    options.forEach(option => {
        if (option.value === '') return;

        const text = option.textContent.toLowerCase();
        const match = text.includes(searchTerm);
        option.style.display = match ? 'block' : 'none';
    });
});
</script>
{% endblock %}
