{% extends "base.html" %}

{% block title %}Database Migrations - Admin{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- Header with Navigation -->
    <div class="row mb-4">
        <div class="col-12">
            <nav class="navbar navbar-expand-lg navbar-dark bg-primary rounded">
                <div class="container-fluid">
                    <a class="navbar-brand" href="{{ url_for('main.dashboard') }}">
                        <i class="fas fa-fist-raised me-2"></i>Fixture Manager
                    </a>
                    <div class="navbar-nav ms-auto">
                        <a class="nav-link" href="{{ url_for('main.dashboard') }}">
                            <i class="fas fa-tachometer-alt me-1"></i>Dashboard
                        </a>
                        <a class="nav-link" href="{{ url_for('main.admin_panel') }}">
                            <i class="fas fa-cog me-1"></i>Admin Panel
                        </a>
                        <a class="nav-link" href="{{ url_for('main.admin_users') }}">
                            <i class="fas fa-users me-1"></i>Users
                        </a>
                        <a class="nav-link active" href="{{ url_for('main.admin_database_migrations') }}">
                            <i class="fas fa-database me-1"></i>Migrations
                        </a>
                        <a class="nav-link" href="{{ url_for('auth.logout') }}">
                            <i class="fas fa-sign-out-alt me-1"></i>Logout
                        </a>
                    </div>
                </div>
            </nav>
        </div>
    </div>

    <!-- Page Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1 class="h3 mb-0">
                        <i class="fas fa-database text-primary me-2"></i>Database Migrations
                    </h1>
                    <p class="text-muted mb-0">Manage database schema versions and migrations</p>
                </div>
                <div>
                    <button type="button" class="btn btn-outline-primary me-2" onclick="refreshMigrationStatus()">
                        <i class="fas fa-sync-alt me-1"></i>Refresh Status
                    </button>
                    <button type="button" class="btn btn-primary" onclick="runMigrations()" id="runMigrationsBtn">
                        <i class="fas fa-play me-1"></i>Run Migrations
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Migration Status Overview -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card border-primary">
                <div class="card-body text-center">
                    <div class="display-6 text-primary mb-2">
                        <span id="currentVersion">{{ migration_status.get('current_version', 'Unknown') }}</span>
                    </div>
                    <h6 class="card-title text-muted mb-0">Current Version</h6>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-success">
                <div class="card-body text-center">
                    <div class="display-6 text-success mb-2">
                        <span id="appliedCount">{{ migration_status.get('applied_count', 0) }}</span>
                    </div>
                    <h6 class="card-title text-muted mb-0">Applied Migrations</h6>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-warning">
                <div class="card-body text-center">
                    <div class="display-6 text-warning mb-2">
                        <span id="pendingCount">{{ migration_status.get('pending_count', 0) }}</span>
                    </div>
                    <h6 class="card-title text-muted mb-0">Pending Migrations</h6>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-info">
                <div class="card-body text-center">
                    <div class="display-6 text-info mb-2">
                        <span id="totalCount">{{ migration_status.get('total_migrations', 0) }}</span>
                    </div>
                    <h6 class="card-title text-muted mb-0">Total Migrations</h6>
                </div>
            </div>
        </div>
    </div>

    <!-- Migration Details -->
    <div class="row">
        <div class="col-md-6">
            <!-- Applied Migrations -->
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h5 class="card-title mb-0">
                        <i class="fas fa-check-circle me-2"></i>Applied Migrations
                    </h5>
                </div>
                <div class="card-body">
                    <div id="appliedMigrations">
                        {% if migration_status.get('applied_versions') %}
                            {% for version in migration_status.applied_versions %}
                            <div class="d-flex align-items-center mb-2">
                                <span class="badge bg-success me-2">{{ version }}</span>
                                <span class="text-muted">Migration {{ version }}</span>
                            </div>
                            {% endfor %}
                        {% else %}
                            <p class="text-muted mb-0">No migrations have been applied yet.</p>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <!-- Pending Migrations -->
            <div class="card">
                <div class="card-header bg-warning text-dark">
                    <h5 class="card-title mb-0">
                        <i class="fas fa-clock me-2"></i>Pending Migrations
                    </h5>
                </div>
                <div class="card-body">
                    <div id="pendingMigrations">
                        {% if migration_status.get('pending_versions') %}
                            {% for version in migration_status.pending_versions %}
                            <div class="d-flex align-items-center mb-2">
                                <span class="badge bg-warning text-dark me-2">{{ version }}</span>
                                <span class="text-muted">Migration {{ version }}</span>
                            </div>
                            {% endfor %}
                        {% else %}
                            <p class="text-success mb-0">
                                <i class="fas fa-check me-1"></i>All migrations are up to date!
                            </p>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Migration Log -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="fas fa-list me-2"></i>Migration Log
                    </h5>
                </div>
                <div class="card-body">
                    <div id="migrationLog" class="bg-dark text-light p-3 rounded" style="height: 300px; overflow-y: auto; font-family: monospace;">
                        <div class="text-muted">Migration log will appear here...</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Migration Progress Modal -->
<div class="modal fade" id="migrationProgressModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-cog fa-spin me-2"></i>Running Migrations
                </h5>
            </div>
            <div class="modal-body text-center">
                <div class="spinner-border text-primary mb-3" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mb-0">Please wait while migrations are being applied...</p>
                <small class="text-muted">This may take a few moments.</small>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let migrationProgressModal;

document.addEventListener('DOMContentLoaded', function() {
    migrationProgressModal = new bootstrap.Modal(document.getElementById('migrationProgressModal'));
});

function addToLog(message, type = 'info') {
    const log = document.getElementById('migrationLog');
    const timestamp = new Date().toLocaleTimeString();
    const colorClass = {
        'info': 'text-info',
        'success': 'text-success',
        'warning': 'text-warning',
        'error': 'text-danger'
    }[type] || 'text-light';
    
    const logEntry = document.createElement('div');
    logEntry.innerHTML = `<span class="text-muted">[${timestamp}]</span> <span class="${colorClass}">${message}</span>`;
    log.appendChild(logEntry);
    log.scrollTop = log.scrollHeight;
}

function refreshMigrationStatus() {
    addToLog('Refreshing migration status...', 'info');
    
    fetch('{{ url_for("main.admin_migration_status") }}')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateMigrationStatus(data.status);
                addToLog('Migration status refreshed successfully', 'success');
            } else {
                addToLog(`Failed to refresh status: ${data.message}`, 'error');
            }
        })
        .catch(error => {
            addToLog(`Error refreshing status: ${error.message}`, 'error');
        });
}

function updateMigrationStatus(status) {
    // Update overview cards
    document.getElementById('currentVersion').textContent = status.current_version || 'Unknown';
    document.getElementById('appliedCount').textContent = status.applied_count || 0;
    document.getElementById('pendingCount').textContent = status.pending_count || 0;
    document.getElementById('totalCount').textContent = status.total_migrations || 0;
    
    // Update applied migrations list
    const appliedDiv = document.getElementById('appliedMigrations');
    if (status.applied_versions && status.applied_versions.length > 0) {
        appliedDiv.innerHTML = status.applied_versions.map(version => `
            <div class="d-flex align-items-center mb-2">
                <span class="badge bg-success me-2">${version}</span>
                <span class="text-muted">Migration ${version}</span>
            </div>
        `).join('');
    } else {
        appliedDiv.innerHTML = '<p class="text-muted mb-0">No migrations have been applied yet.</p>';
    }
    
    // Update pending migrations list
    const pendingDiv = document.getElementById('pendingMigrations');
    if (status.pending_versions && status.pending_versions.length > 0) {
        pendingDiv.innerHTML = status.pending_versions.map(version => `
            <div class="d-flex align-items-center mb-2">
                <span class="badge bg-warning text-dark me-2">${version}</span>
                <span class="text-muted">Migration ${version}</span>
            </div>
        `).join('');
    } else {
        pendingDiv.innerHTML = '<p class="text-success mb-0"><i class="fas fa-check me-1"></i>All migrations are up to date!</p>';
    }
}

function runMigrations() {
    const btn = document.getElementById('runMigrationsBtn');
    const originalText = btn.innerHTML;
    
    // Show progress modal
    migrationProgressModal.show();
    
    // Disable button
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Running...';
    
    addToLog('Starting migration process...', 'info');
    
    fetch('{{ url_for("main.admin_run_migrations") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        migrationProgressModal.hide();
        
        if (data.success) {
            addToLog(`Migrations completed successfully: ${data.message}`, 'success');
            if (data.applied_count > 0) {
                addToLog(`Applied ${data.applied_count} migration(s)`, 'success');
            }
            // Refresh status after successful migration
            setTimeout(refreshMigrationStatus, 1000);
        } else {
            addToLog(`Migration failed: ${data.message}`, 'error');
            if (data.failed_migrations) {
                data.failed_migrations.forEach(migration => {
                    addToLog(`Failed migration: ${migration}`, 'error');
                });
            }
        }
    })
    .catch(error => {
        migrationProgressModal.hide();
        addToLog(`Error running migrations: ${error.message}`, 'error');
    })
    .finally(() => {
        // Re-enable button
        btn.disabled = false;
        btn.innerHTML = originalText;
    });
}

// Initialize log
addToLog('Migration management interface loaded', 'info');
</script>
{% endblock %}