<?php
$migrationStatus = is_array($status ?? null) ? $status : [];
$pending = (int) ($migrationStatus['pending'] ?? 0);
$total = (int) ($migrationStatus['total'] ?? 0);
$applied = (int) ($migrationStatus['applied'] ?? 0);
$pendingFiles = (array) ($migrationStatus['pending_files'] ?? []);
$logs = is_array($runLogs ?? null) ? $runLogs : [];
?>

<h4 class="fw-bold mb-4">Baza danych &mdash; Migracje</h4>

<div class="row g-3 mb-4">
    <div class="col-md-4">
        <div class="card text-center">
            <div class="card-body">
                <div class="text-muted small text-uppercase fw-bold">Wszystkie</div>
                <div class="fs-3 fw-bold text-dark"><?= $total ?></div>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card text-center">
            <div class="card-body">
                <div class="text-muted small text-uppercase fw-bold">Wykonane</div>
                <div class="fs-3 fw-bold text-success"><?= $applied ?></div>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card text-center">
            <div class="card-body">
                <div class="text-muted small text-uppercase fw-bold">Oczekujace</div>
                <div class="fs-3 fw-bold <?= $pending > 0 ? 'text-warning' : 'text-muted' ?>"><?= $pending ?></div>
            </div>
        </div>
    </div>
</div>

<?php if ($pending > 0): ?>
    <div class="alert alert-warning d-flex align-items-center justify-content-between">
        <span><strong><?= $pending ?></strong> migracji oczekuje na wykonanie.</span>
        <form action="/settings/database/migrate" method="post" class="d-inline">
            <button type="submit" class="btn btn-primary btn-sm">Uruchom migracje</button>
        </form>
    </div>
<?php else: ?>
    <div class="alert alert-success mb-4">Baza danych jest aktualna.</div>
<?php endif; ?>

<div class="card mb-4">
    <div class="card-header">Oczekujace pliki migracji</div>
    <div class="card-body p-0">
        <table class="table table-sm mb-0">
            <thead>
                <tr><th>Plik</th></tr>
            </thead>
            <tbody>
            <?php if (empty($pendingFiles)): ?>
                <tr><td class="text-muted">Brak oczekujacych migracji.</td></tr>
            <?php else: ?>
                <?php foreach ($pendingFiles as $filename): ?>
                    <tr><td><code><?= htmlspecialchars((string) $filename) ?></code></td></tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php if (!empty($logs)): ?>
<div class="card">
    <div class="card-header">Logi ostatniego uruchomienia</div>
    <div class="card-body">
        <pre class="mb-0 small" style="white-space: pre-wrap;"><?php foreach ($logs as $line): ?><?= htmlspecialchars((string) $line) . "\n" ?><?php endforeach; ?></pre>
    </div>
</div>
<?php endif; ?>
