<?php

/**
 * Developer Console — Synchronization History Log (DX002B)
 *
 * Displays all sync log entries newest first.
 * Provides a Clear Log button.
 *
 * Variables:
 *   $logs — list<array> from SynchronizationService::getLogs(100)
 *
 * @package Inveetaire
 * @ref     DX002B
 */

/** @var array $logs */
$logs       = $logs ?? [];
$clearUrl   = url('/app/developer/sync/log/clear');

?>

<!-- Page Header -->
<div style="margin-bottom: 2rem;">
    <div style="font-family: var(--mono); font-size: 0.6875rem; color: var(--dev-text-muted); margin-bottom: 0.5rem;">
        <a href="<?= url('/app/developer') ?>" style="color:var(--dev-accent); text-decoration:none;">developer</a>
        <span style="color:#444c56;"> / </span>
        <a href="<?= url('/app/developer/sync') ?>" style="color:var(--dev-accent); text-decoration:none;">sync</a>
        <span style="color:#444c56;"> / </span>
        <span>log</span>
    </div>
    <div style="display:flex; align-items:flex-start; justify-content:space-between; flex-wrap:wrap; gap:1rem;">
        <div>
            <h1 style="font-size: 1.5rem; font-weight: 800; color: var(--dev-text); margin-bottom: 0.25rem;">
                Synchronization Log
            </h1>
            <p style="font-size: 0.8125rem; color: var(--dev-text-muted);">
                History of all schema comparison and push operations. Newest first.
                <?= count($logs) ?> entries.
            </p>
        </div>
        <?php if (!empty($logs)): ?>
        <button id="btn-clear-log" onclick="clearLog()"
                style="display:inline-flex; align-items:center; gap:0.5rem; padding:0.5rem 1rem; background:rgba(248,81,73,0.08); border:1px solid rgba(248,81,73,0.2); border-radius:6px; font-family:var(--mono); font-size:0.75rem; color:var(--dev-danger); cursor:pointer;">
            <i class="fa-solid fa-trash-can"></i> Clear Log
        </button>
        <?php endif; ?>
    </div>
</div>

<!-- Stats Row -->
<?php
$totalDryRuns = count(array_filter($logs, static fn($l) => $l['is_dry_run'] ?? false));
$totalPushes  = count(array_filter($logs, static fn($l) => !($l['is_dry_run'] ?? false)));
$successCount = count(array_filter($logs, static fn($l) => ($l['result'] ?? '') === 'success'));
$errorCount   = count(array_filter($logs, static fn($l) => ($l['result'] ?? '') === 'error'));
$avgDuration  = !empty($logs) ? round(array_sum(array_column($logs, 'duration_ms')) / count($logs)) : 0;
?>
<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 1rem; margin-bottom: 2rem;">
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">Total Entries</div>
        <div class="dev-stat-value"><?= count($logs) ?></div>
    </div>
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">Push Operations</div>
        <div class="dev-stat-value" style="color:#3ecf8e;"><?= $totalPushes ?></div>
    </div>
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">Dry Runs</div>
        <div class="dev-stat-value" style="color:var(--dev-warn);"><?= $totalDryRuns ?></div>
    </div>
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">Successful</div>
        <div class="dev-stat-value" style="color:var(--dev-accent2);"><?= $successCount ?></div>
    </div>
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">Errors</div>
        <div class="dev-stat-value" style="color:var(--dev-danger);"><?= $errorCount ?></div>
    </div>
    <div class="dev-card" style="padding:1.25rem;">
        <div class="dev-stat-label">Avg Duration</div>
        <div class="dev-stat-value" style="font-size:1rem;"><?= number_format($avgDuration) ?> ms</div>
    </div>
</div>

<!-- Log Table -->
<div class="dev-card">
    <?php if (empty($logs)): ?>
    <div class="dev-card-body" style="text-align:center; padding:3rem;">
        <div style="font-size:3rem; color:#444c56; margin-bottom:1rem;"><i class="fa-solid fa-clock-rotate-left"></i></div>
        <p style="font-size:0.875rem; color:var(--dev-text-muted);">No synchronization history yet.</p>
        <a href="<?= url('/app/developer/sync') ?>" style="font-size:0.75rem; color:var(--dev-accent); text-decoration:none; font-family:var(--mono);">
            Go to Synchronization →
        </a>
    </div>
    <?php else: ?>
    <div style="overflow-x: auto;">
        <table class="dev-table">
            <thead>
                <tr>
                    <th>Timestamp</th>
                    <th>User</th>
                    <th>Type</th>
                    <th>Direction</th>
                    <th>Tables</th>
                    <th>Columns</th>
                    <th>Statements</th>
                    <th>Result</th>
                    <th>Duration</th>
                    <th>Mode</th>
                    <th>Error</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($logs as $log): ?>
                <?php $res = $log['result'] ?? '—'; ?>
                <tr style="<?= $res === 'error' ? 'background:rgba(248,81,73,0.04);' : '' ?>">
                    <td class="mono" style="font-size:0.6875rem; white-space:nowrap;">
                        <?= escape_html($log['timestamp'] ?? '—') ?>
                    </td>
                    <td class="mono" style="font-size:0.6875rem;">
                        <?= escape_html($log['user'] ?? '—') ?>
                    </td>
                    <td>
                        <?php if ($log['is_dry_run'] ?? false): ?>
                            <span class="badge-warn">Dry Run</span>
                        <?php else: ?>
                            <span style="font-family:var(--mono); font-size:0.5625rem; font-weight:700; padding:0.2rem 0.5rem; border-radius:4px; background:rgba(62,207,142,0.1); border:1px solid rgba(62,207,142,0.3); color:#3ecf8e;">Push</span>
                        <?php endif; ?>
                    </td>
                    <td class="mono" style="font-size:0.6875rem; color:var(--dev-text-muted);">
                        <?= escape_html($log['direction'] ?? '—') ?>
                    </td>
                    <td style="text-align:center;"><?= (int)($log['tables_affected']  ?? 0) ?></td>
                    <td style="text-align:center;"><?= (int)($log['columns_affected'] ?? 0) ?></td>
                    <td style="text-align:center;"><?= (int)($log['sql_statements']   ?? 0) ?></td>
                    <td>
                        <span style="font-family:var(--mono); font-size:0.6875rem; color:<?=
                            $res === 'success' || $res === 'dry_run_complete' ? 'var(--dev-accent2)' :
                            ($res === 'error' ? 'var(--dev-danger)' : 'var(--dev-warn)')
                        ?>;"><?= escape_html($res) ?></span>
                    </td>
                    <td class="muted" style="white-space:nowrap;">
                        <?= number_format((int)($log['duration_ms'] ?? 0)) ?> ms
                    </td>
                    <td class="mono muted" style="font-size:0.5625rem;">
                        <?= escape_html($log['execution_mode'] ?? '—') ?>
                    </td>
                    <td style="max-width:200px;">
                        <?php if ($log['error_message']): ?>
                            <span style="font-size:0.6875rem; color:var(--dev-danger); font-family:var(--mono);" title="<?= escape_html($log['error_message']) ?>">
                                <?= escape_html(substr($log['error_message'], 0, 40)) ?><?= strlen($log['error_message']) > 40 ? '…' : '' ?>
                            </span>
                        <?php else: ?>
                            <span class="muted">—</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<script>
function clearLog() {
    if (!confirm('Clear all synchronization history? This cannot be undone.')) return;

    const btn = document.getElementById('btn-clear-log');
    if (btn) { btn.disabled = true; btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Clearing…'; }

    fetch('<?= escape_javascript($clearUrl) ?>', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            window.location.reload();
        } else {
            alert('Failed to clear log.');
            if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fa-solid fa-trash-can"></i> Clear Log'; }
        }
    })
    .catch(() => alert('Network error.'));
}
</script>
