<?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 ?? [];
$subscriptionsDue = $mailboxSubscriptionsDue ?? [];
$queueJobs = $queueJobs ?? [];
?>
<section class="workspace-hero">
    <div>
        <h2>Sync Health</h2>
        <p>Monitor mailbox imports, renewal windows, and worker activity so V16.11 unified mail sync keeps feeding Mail Center without 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>Queue backlog</h3><p><?= (int)($queueStats['queued_jobs'] ?? 0) ?></p><span><?= (int)($queueStats['processing_jobs'] ?? 0) ?> processing · <?= (int)($queueStats['failed_jobs'] ?? 0) ?> failed</span></div>
    <div class="card stat alt"><h3>Heartbeat</h3><p><?= e($mailboxSyncLastHeartbeat ?: 'never') ?></p><span>Worker heartbeat <?= e($workerLastHeartbeat ?: 'never') ?></span></div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Mailbox sync status</h2><span class="badge"><?= count($mailboxes) ?></span></div>
        <table>
            <thead><tr><th>Mailbox</th><th>Mode</th><th>Sync</th><th>Imported</th><th>Last import</th><th>Action</th></tr></thead>
            <tbody>
            <?php foreach ($mailboxes 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['sync_state'] ?? 'idle') ?>"><?= e($mailbox['sync_state'] ?? 'idle') ?></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><?= (int)($mailbox['imported_message_count'] ?? 0) ?><br><span class="small muted">UID <?= (int)($mailbox['last_message_uid'] ?? 0) ?></span></td>
                    <td><?= e($mailbox['last_imported_at'] ?? 'never') ?></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 (!$mailboxes): ?><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="card">
    <div class="toolbar"><h2>Recent mailbox sync 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>
</section>
