{% extends 'admin/base.html.twig' %}

{% block title %}Migraciones{% endblock %}
{% block page_title %}Migraciones de base de datos{% endblock %}

{% block body %}

<div class="admin-toolbar">
    <span class="admin-count">
        {{ total_ejecutadas }} / {{ total }} ejecutadas
    </span>
    {% if total_pendientes > 0 %}
        <span class="admin-badge admin-badge--warning">{{ total_pendientes }} pendiente{{ total_pendientes != 1 ? 's' }}</span>
    {% else %}
        <span class="admin-badge admin-badge--success">Al día</span>
    {% endif %}
    <a href="{{ path('app_admin_mantenimiento_index') }}" class="admin-btn admin-btn--secondary admin-btn--sm">
        ← Mantenimiento
    </a>
</div>

<div class="admin-table-wrap">
    <table class="admin-table" style="table-layout: fixed;">
        <colgroup>
            <col style="width: 2.5rem">
            <col style="width: 10rem">
            <col>
            <col style="width: 8rem">
            <col style="width: 9rem">
            <col style="width: 22rem">
        </colgroup>
        <thead>
            <tr>
                <th>#</th>
                <th>Versión</th>
                <th>Descripción</th>
                <th>Estado</th>
                <th>Ejecutada el</th>
                <th>Acciones</th>
            </tr>
        </thead>
        <tbody>
        {% for info in migraciones %}
            <tr>
                <td class="text-muted">{{ loop.index }}</td>

                <td>
                    <code style="font-size: .75rem; white-space: nowrap;">{{ info.fechaFormateada }}</code>
                </td>

                <td>
                    <span style="font-size: .85rem;">{{ info.descripcion ?: '—' }}</span>
                    {% if info.compleja %}
                        <br><small class="text-muted" title="Contiene lógica PHP que no se puede ejecutar desde la interfaz">⚠ Compleja</small>
                    {% endif %}
                </td>

                <td>
                    {% if info.ejecutada %}
                        <span class="admin-badge admin-badge--success">Ejecutada</span>
                    {% else %}
                        <span class="admin-badge admin-badge--warning">Pendiente</span>
                    {% endif %}
                </td>

                <td class="text-muted" style="font-size: .8rem;">
                    {{ info.ejecutadaEn ? info.ejecutadaEn|date('d/m/Y H:i') : '—' }}
                </td>

                <td>
                    <div style="display: flex; flex-wrap: wrap; gap: .3rem; align-items: flex-start;">

                        {# Ejecutar UP — siempre disponible para migraciones no complejas #}
                        {% if not info.compleja %}
                            <form method="post"
                                  action="{{ path('app_admin_migraciones_ejecutar_up', {version: info.version}) }}"
                                  onsubmit="return confirm('¿Ejecutar UP de {{ info.version }}?{% if info.ejecutada %} (ya consta como ejecutada){% endif %}')">
                                <input type="hidden" name="_csrf_token"
                                       value="{{ csrf_token('migrar_up_' ~ info.version) }}">
                                <button type="submit" class="admin-btn admin-btn--success admin-btn--sm"
                                        title="Ejecutar sentencias UP">
                                    ▶ UP
                                </button>
                            </form>
                        {% endif %}

                        {# Ejecutar DOWN — solo si ejecutada, no compleja y tiene sentencias DOWN #}
                        {% if info.ejecutada and not info.compleja and info.sqlDown is not empty %}
                            <form method="post"
                                  action="{{ path('app_admin_migraciones_ejecutar_down', {version: info.version}) }}"
                                  onsubmit="return confirm('ATENCIÓN: ¿Ejecutar DOWN de {{ info.version }}?\nEsto puede eliminar tablas o columnas de la base de datos.')">
                                <input type="hidden" name="_csrf_token"
                                       value="{{ csrf_token('migrar_down_' ~ info.version) }}">
                                <button type="submit" class="admin-btn admin-btn--danger admin-btn--sm"
                                        title="Ejecutar sentencias DOWN (reversión)">
                                    ▼ DOWN
                                </button>
                            </form>
                        {% endif %}

                        {# Marcar / Desmarcar — sincroniza doctrine_migration_versions sin tocar el esquema #}
                        {% if info.ejecutada %}
                            <form method="post"
                                  action="{{ path('app_admin_migraciones_desmarcar', {version: info.version}) }}"
                                  onsubmit="return confirm('¿Desmarcar {{ info.version }} como ejecutada?\nNo se revertirá ningún cambio en la base de datos.')">
                                <input type="hidden" name="_csrf_token"
                                       value="{{ csrf_token('migrar_desmarcar_' ~ info.version) }}">
                                <button type="submit" class="admin-btn admin-btn--secondary admin-btn--sm"
                                        title="Quitar de doctrine_migration_versions sin revertir esquema">
                                    Desmarcar
                                </button>
                            </form>
                        {% else %}
                            <form method="post"
                                  action="{{ path('app_admin_migraciones_marcar', {version: info.version}) }}"
                                  onsubmit="return confirm('¿Marcar {{ info.version }} como ejecutada sin correr el SQL?')">
                                <input type="hidden" name="_csrf_token"
                                       value="{{ csrf_token('migrar_marcar_' ~ info.version) }}">
                                <button type="submit" class="admin-btn admin-btn--secondary admin-btn--sm"
                                        title="Registrar en doctrine_migration_versions sin ejecutar SQL">
                                    Marcar
                                </button>
                            </form>
                        {% endif %}

                    </div>

                    {# Ver SQL — siempre visible #}
                    <details style="margin-top: .5rem;">
                        <summary style="cursor: pointer; font-size: .8rem; color: var(--color-muted, #888);">
                            Ver SQL
                            {% if not info.compleja %}
                                ({{ info.sqlUp|length }} UP / {{ info.sqlDown|length }} DOWN)
                            {% else %}
                                (código complejo)
                            {% endif %}
                        </summary>

                        <div style="margin-top: .5rem;">
                            {% if info.compleja %}
                                <p style="font-size:.8rem; color: #e6a817;">
                                    ⚠ Esta migración contiene lógica PHP que no puede ejecutarse desde la interfaz.
                                    Aplícala con <code>php bin/console doctrine:migrations:migrate</code>.
                                </p>
                                <p style="font-size:.75rem; font-weight:bold; margin:.4rem 0 .2rem;">Código up():</p>
                                <pre style="font-size:.7rem; overflow-x:auto; background:#1e1e1e; color:#d4d4d4; padding:.6rem; border-radius:4px; white-space:pre-wrap; word-break:break-word;"><code>{{ info.fuenteUp|e }}</code></pre>
                            {% else %}
                                {% if info.sqlUp is not empty %}
                                    <p style="font-size:.75rem; font-weight:bold; margin:.4rem 0 .2rem;">UP:</p>
                                    {% for i, sql in info.sqlUp %}
                                        <p style="font-size:.7rem; color:#888; margin:.15rem 0;">#{{ i + 1 }}</p>
                                        <pre style="font-size:.7rem; overflow-x:auto; background:#1e1e1e; color:#d4d4d4; padding:.6rem; border-radius:4px; white-space:pre-wrap; word-break:break-word; margin-bottom:.4rem;"><code>{{ sql|e }}</code></pre>
                                    {% endfor %}
                                {% endif %}

                                {% if info.sqlDown is not empty %}
                                    <p style="font-size:.75rem; font-weight:bold; margin:.6rem 0 .2rem;">DOWN:</p>
                                    {% for i, sql in info.sqlDown %}
                                        <p style="font-size:.7rem; color:#888; margin:.15rem 0;">#{{ i + 1 }}</p>
                                        <pre style="font-size:.7rem; overflow-x:auto; background:#1e1e1e; color:#d4d4d4; padding:.6rem; border-radius:4px; white-space:pre-wrap; word-break:break-word; margin-bottom:.4rem;"><code>{{ sql|e }}</code></pre>
                                    {% endfor %}
                                {% else %}
                                    <p style="font-size:.8rem; color:#888;">Sin sentencias DOWN.</p>
                                {% endif %}
                            {% endif %}
                        </div>
                    </details>
                </td>
            </tr>
        {% else %}
            <tr>
                <td colspan="6" class="text-center text-muted">No se encontraron ficheros de migración.</td>
            </tr>
        {% endfor %}
        </tbody>
    </table>
</div>

{% endblock %}
