{% extends "base.html" %}

{% block title %}Editar Esquema: {{ schema.nombre }}{% endblock %}

{% block content %}
<div class="container mt-4">
    <h2>Editar Esquema</h2>
    
    <form method="POST">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        
        <div class="mb-3">
            <label for="nombre" class="form-label">Nombre</label>
            <input type="text" class="form-control" id="nombre" name="nombre" value="{{ schema.nombre }}" required>
        </div>
        
        <div class="mb-3">
            <label for="descripcion" class="form-label">Descripción</label>
            <textarea class="form-control" id="descripcion" name="descripcion" rows="3">{{ schema.descripcion }}</textarea>
        </div>
        
        <h4 class="mt-4">Tipos de Documentos</h4>
        <div id="documents-container">
            {% for doc in schema.documentos %}
            <div class="card mb-3 document-card">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3">
                            <label class="form-label">Tipo</label>
                            <select class="form-select" name="doc_tipo_{{ loop.index0 }}" required>
                                {% for extension, filetype in filetypes.items() %}
                                <option value="{{ extension }}" {% if doc.tipo == extension %}selected{% endif %}>
                                    {{ filetype.descripcion }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Nombre</label>
                            <input type="text" class="form-control" name="doc_nombre_{{ loop.index0 }}" 
                                   value="{{ doc.nombre }}" required>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Nivel Ver</label>
                            <input type="number" class="form-control" name="doc_nivel_ver_{{ loop.index0 }}" 
                                   value="{{ doc.nivel_ver }}" min="0" max="9999">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Nivel Editar</label>
                            <input type="number" class="form-control" name="doc_nivel_editar_{{ loop.index0 }}" 
                                   value="{{ doc.nivel_editar }}" min="0" max="9999">
                        </div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-danger btn-sm mt-4 remove-document">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
        
        <input type="hidden" id="document_count" name="document_count" value="{{ schema.documentos|length }}">
        
        <button type="button" id="add-document" class="btn btn-secondary mb-3">
            <i class="fas fa-plus"></i> Añadir Tipo de Documento
        </button>

        <h4 class="mt-4">Campos</h4>
        <div id="fields-container">
            {% for field in schema.fields %}
            <div class="card mb-3 field-card">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4">
                            <label class="form-label">Nombre</label>
                            <input type="text" class="form-control" name="field_name_{{ loop.index0 }}" value="{{ field.name }}" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Tipo</label>
                            <select class="form-select" name="field_type_{{ loop.index0 }}">
                                <option value="text" {% if field.type == 'text' %}selected{% endif %}>Texto</option>
                                <option value="textarea" {% if field.type == 'textarea' %}selected{% endif %}>Área de texto</option>
                                <option value="richtext" {% if field.type == 'richtext' %}selected{% endif %}>Texto enriquecido</option>
                                <option value="number" {% if field.type == 'number' %}selected{% endif %}>Número</option>
                                <option value="date" {% if field.type == 'date' %}selected{% endif %}>Fecha</option>
                                <option value="tags" {% if field.type == 'tags' %}selected{% endif %}>Etiquetas</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Requerido</label>
                            <div class="form-check mt-2">
                                <input class="form-check-input" type="checkbox" name="field_required_{{ loop.index0 }}" {% if field.required %}checked{% endif %}>
                                <label class="form-check-label">Es requerido</label>
                            </div>
                        </div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-danger btn-sm mt-4 remove-field">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
        
        <input type="hidden" id="field_count" name="field_count" value="{{ schema.fields|length }}">
        
        <button type="button" id="add-field" class="btn btn-secondary mb-3">
            <i class="fas fa-plus"></i> Añadir Campo
        </button>
        
        <div class="mt-4">
            <button type="submit" class="btn btn-primary">Guardar Cambios</button>
            <a href="{{ url_for('schemas.list') }}" class="btn btn-secondary">Cancelar</a>
        </div>
    </form>
</div>

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        let fieldCount = {{ schema.fields|length }};
        
        // Add new field
        document.getElementById('add-field').addEventListener('click', function() {
            const fieldsContainer = document.getElementById('fields-container');
            const newField = document.createElement('div');
            newField.className = 'card mb-3 field-card';
            newField.innerHTML = `
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4">
                            <label class="form-label">Nombre</label>
                            <input type="text" class="form-control" name="field_name_${fieldCount}" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Tipo</label>
                            <select class="form-select" name="field_type_${fieldCount}">
                                <option value="text">Texto</option>
                                <option value="textarea">Área de texto</option>
                                <option value="richtext">Texto enriquecido</option>
                                <option value="number">Número</option>
                                <option value="date">Fecha</option>
                                <option value="tags">Etiquetas</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Requerido</label>
                            <div class="form-check mt-2">
                                <input class="form-check-input" type="checkbox" name="field_required_${fieldCount}">
                                <label class="form-check-label">Es requerido</label>
                            </div>
                        </div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-danger btn-sm mt-4 remove-field">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            `;
            fieldsContainer.appendChild(newField);
            fieldCount++;
            document.getElementById('field_count').value = fieldCount;
            
            // Add event listener to new remove button
            newField.querySelector('.remove-field').addEventListener('click', removeField);
        });
        
        // Remove field functionality
        function removeField() {
            this.closest('.field-card').remove();
            fieldCount--;
            document.getElementById('field_count').value = fieldCount;
            // Renumber fields to keep proper sequence
            updateFieldNumbers();
        }
        
        // Add event listeners to existing remove buttons
        document.querySelectorAll('.remove-field').forEach(button => {
            button.addEventListener('click', removeField);
        });
        
        // Update field numbering when fields are removed
        function updateFieldNumbers() {
            const fieldCards = document.querySelectorAll('.field-card');
            fieldCards.forEach((card, index) => {
                const fieldNameInput = card.querySelector('input[name^="field_name_"]');
                const fieldTypeSelect = card.querySelector('select[name^="field_type_"]');
                const fieldRequiredCheck = card.querySelector('input[name^="field_required_"]');
                
                fieldNameInput.name = `field_name_${index}`;
                fieldTypeSelect.name = `field_type_${index}`;
                fieldRequiredCheck.name = `field_required_${index}`;
            });
        }

        // Document types functionality
        let documentCount = {{ schema.documentos|length }};
        
        document.getElementById('add-document').addEventListener('click', function() {
            const documentsContainer = document.getElementById('documents-container');
            const newDocument = document.createElement('div');
            newDocument.className = 'card mb-3 document-card';
            newDocument.innerHTML = `
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3">
                            <label class="form-label">Tipo</label>
                            <select class="form-select" name="doc_tipo_${documentCount}" required>
                                {% for extension, filetype in filetypes.items() %}
                                <option value="{{ extension }}">{{ filetype.descripcion }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Nombre</label>
                            <input type="text" class="form-control" name="doc_nombre_${documentCount}" required>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Nivel Ver</label>
                            <input type="number" class="form-control" name="doc_nivel_ver_${documentCount}" 
                                   value="0" min="0" max="9999">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Nivel Editar</label>
                            <input type="number" class="form-control" name="doc_nivel_editar_${documentCount}" 
                                   value="5000" min="0" max="9999">
                        </div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-danger btn-sm mt-4 remove-document">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            `;
            documentsContainer.appendChild(newDocument);
            documentCount++;
            document.getElementById('document_count').value = documentCount;
            
            newDocument.querySelector('.remove-document').addEventListener('click', removeDocument);
        });
        
        function removeDocument() {
            this.closest('.document-card').remove();
            documentCount--;
            document.getElementById('document_count').value = documentCount;
            updateDocumentNumbers();
        }
        
        document.querySelectorAll('.remove-document').forEach(button => {
            button.addEventListener('click', removeDocument);
        });
        
        function updateDocumentNumbers() {
            const documentCards = document.querySelectorAll('.document-card');
            documentCards.forEach((card, index) => {
                const tipoSelect = card.querySelector('select[name^="doc_tipo_"]');
                const nombreInput = card.querySelector('input[name^="doc_nombre_"]');
                const nivelVerInput = card.querySelector('input[name^="doc_nivel_ver_"]');
                const nivelEditarInput = card.querySelector('input[name^="doc_nivel_editar_"]');
                
                tipoSelect.name = `doc_tipo_${index}`;
                nombreInput.name = `doc_nombre_${index}`;
                nivelVerInput.name = `doc_nivel_ver_${index}`;
                nivelEditarInput.name = `doc_nivel_editar_${index}`;
            });
        }
    });
</script>
{% endblock %}
{% endblock %}
