<?php
$stats = $connectedMailboxStats ?? ['total_count' => 0, 'renewal_due_count' => 0, 'error_count' => 0, 'last_synced_at' => null, 'imported_total' => 0, 'last_imported_at' => null];
$queueStats = $queueStats ?? ['queued_jobs' => 0, 'processing_jobs' => 0, 'failed_jobs' => 0];
$mailboxes = $connectedMailboxes ?? [];
$healthRows = $mailboxHealthRows ?? [];
$subscriptionsDue = $mailboxSubscriptionsDue ?? [];
$queueJobs = $queueJobs ?? [];
$mailboxSyncEvents = $mailboxSyncEvents ?? [];
?>
<section class="workspace-hero">
    <div>
        <h2>Sync Health</h2>
        <p>Watch mailbox imports, lag, renewal windows, and worker activity so Mail Center stays fed without hidden drift.</p>
    </div>
    <div class="workspace-actions">
        <a class="btn secondary small" href="index.php?route=messages/connectedMailboxes">Connected Mailboxes</a>
        <a class="btn secondary small" href="index.php?route=settings/diagnostics">Diagnostics</a>
        <form method="post" action="index.php?route=messages/queueAllMailboxSync" style="display:inline-flex;">
            <?= csrf_input() ?>
            <button class="btn primary small">Queue all imports</button>
        </form>
    </div>
</section>

<section class="cards four compact-stats">
    <div class="card stat"><h3>Mailboxes</h3><p><?= (int)($stats['total_count'] ?? 0) ?></p><span><?= (int)($stats['connected_count'] ?? 0) ?> connected</span></div>
    <div class="card stat alt"><h3>Imported emails</h3><p><?= (int)($stats['imported_total'] ?? 0) ?></p><span>Last import <?= e($stats['last_imported_at'] ?? 'never') ?></span></div>
    <div class="card stat alt"><h3>Renewals due</h3><p><?= count($subscriptionsDue) ?></p><span><?= (int)($stats['error_count'] ?? 0) ?> mailboxes currently in error</span></div>
    <div class="card stat alt"><h3>Heartbeat</h3><p><?= e($mailboxSyncLastHeartbeat ?: 'never') ?></p><span>Worker <?= e($workerLastHeartbeat ?: 'never') ?></span></div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Mailbox lag and health</h2><span class="badge"><?= count($healthRows) ?></span></div>
        <table>
            <thead><tr><th>Mailbox</th><th>Mode</th><th>Health</th><th>Lag</th><th>Imported</th><th>Action</th></tr></thead>
            <tbody>
            <?php foreach ($healthRows as $mailbox): ?>
                <tr>
                    <td><strong><?= e($mailbox['name'] ?? '') ?></strong><br><span class="small muted"><?= e($mailbox['email_address'] ?? '') ?></span></td>
                    <td><span class="badge"><?= e($mailbox['sync_mode'] ?? 'imap_bridge') ?></span></td>
                    <td>
                        <span class="badge <?= e($mailbox['health_state'] ?? 'healthy') ?>"><?= e($mailbox['health_state'] ?? 'healthy') ?></span>
                        <?php if (!empty($mailbox['last_error'])): ?><div class="small" style="color:#b91c1c;max-width:260px;"><?= e($mailbox['last_error']) ?></div><?php endif; ?>
                    </td>
                    <td>
                        <?php if (($mailbox['sync_lag_minutes'] ?? null) !== null): ?>
                            <?= (int)$mailbox['sync_lag_minutes'] ?> min
                        <?php else: ?>
                            never
                        <?php endif; ?>
                    </td>
                    <td><?= (int)($mailbox['imported_message_count'] ?? 0) ?><br><span class="small muted">Last <?= e($mailbox['last_imported_at'] ?? 'never') ?></span></td>
                    <td>
                        <div style="display:flex;gap:8px;flex-wrap:wrap;">
                            <form method="post" action="index.php?route=messages/queueMailboxSync" style="display:inline-flex;gap:8px;">
                                <?= csrf_input() ?>
                                <input type="hidden" name="id" value="<?= (int)$mailbox['id'] ?>">
                                <button class="btn secondary small">Queue sync</button>
                            </form>
                            <a class="btn secondary small" href="index.php?route=messages/mailCenter&connected_mailbox_id=<?= (int)$mailbox['id'] ?>">View mail</a>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$healthRows): ?><tr><td colspan="6" class="muted">No mailbox records yet.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Renewals due now</h2><span class="badge"><?= count($subscriptionsDue) ?></span></div>
        <table>
            <thead><tr><th>Mailbox</th><th>Provider</th><th>Expires</th><th>Verification</th><th>Action</th></tr></thead>
            <tbody>
            <?php foreach ($subscriptionsDue as $subscription): ?>
                <tr>
                    <td><?= e(($subscription['mailbox_name'] ?? 'Mailbox') . ' · ' . ($subscription['email_address'] ?? '')) ?></td>
                    <td><?= e($subscription['provider'] ?? '') ?></td>
                    <td><?= e($subscription['expires_at'] ?? '') ?></td>
                    <td><?= e($subscription['verification_state'] ?? '') ?></td>
                    <td>
                        <form method="post" action="index.php?route=messages/renewMailboxSubscription">
                            <?= csrf_input() ?>
                            <input type="hidden" name="id" value="<?= (int)($subscription['connected_mailbox_id'] ?? 0) ?>">
                            <button class="btn secondary small">Refresh</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$subscriptionsDue): ?><tr><td colspan="5" class="muted">No renewals due yet.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Recent mailbox sync events</h2><span class="badge"><?= count($mailboxSyncEvents) ?></span></div>
        <table>
            <thead><tr><th>Time</th><th>Mailbox</th><th>Type</th><th>Status</th><th>Summary</th></tr></thead>
            <tbody>
            <?php foreach ($mailboxSyncEvents as $event): ?>
                <tr>
                    <td><?= e($event['created_at'] ?? '') ?></td>
                    <td><?= e(($event['mailbox_name'] ?? 'Mailbox') . ' · ' . ($event['email_address'] ?? '')) ?></td>
                    <td><?= e($event['event_type'] ?? '') ?></td>
                    <td><?= e($event['status'] ?? '') ?></td>
                    <td class="small"><?= e($event['summary'] ?? '') ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$mailboxSyncEvents): ?><tr><td colspan="5" class="muted">No sync events logged yet.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Recent mailbox queue jobs</h2><span class="badge"><?= count($queueJobs) ?></span></div>
        <table>
            <thead><tr><th>Job type</th><th>Status</th><th>Available</th><th>Updated</th><th>Attempts</th><th>Last error / note</th></tr></thead>
            <tbody>
            <?php foreach ($queueJobs as $job): ?>
                <tr>
                    <td><?= e($job['job_type'] ?? '') ?></td>
                    <td><?= e($job['status'] ?? '') ?></td>
                    <td><?= e($job['available_at'] ?? '') ?></td>
                    <td><?= e($job['updated_at'] ?? '') ?></td>
                    <td><?= (int)($job['attempts'] ?? 0) ?></td>
                    <td class="small" style="max-width:320px;"><?= e($job['last_error'] ?? '') ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$queueJobs): ?><tr><td colspan="6" class="muted">No mailbox sync jobs found.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</section>
