<?php
$stats = $connectedMailboxStats ?? ['total_count' => 0, 'connected_count' => 0, 'renewal_due_count' => 0, 'error_count' => 0, 'last_synced_at' => null];
$mailboxes = $connectedMailboxes ?? [];
$subscriptions = $mailboxSubscriptions ?? [];
$queueJobs = $queueJobs ?? [];
?>
<section class="workspace-hero">
    <div>
        <h2>Connected Mailboxes</h2>
        <p>Connect Gmail and Microsoft 365 accounts, track OAuth readiness, record sync cursors, and queue mailbox refreshes from one place.</p>
    </div>
    <div class="workspace-actions">
        <a class="btn secondary small" href="index.php?route=messages/mailCenter">Mail Center</a>
        <a class="btn secondary small" href="index.php?route=messages/syncHealth">Sync Health</a>
    </div>
</section>

<section class="cards four compact-stats">
    <div class="card stat"><h3>Total mailboxes</h3><p><?= (int)($stats['total_count'] ?? 0) ?></p><span><?= (int)($stats['active_count'] ?? 0) ?> active</span></div>
    <div class="card stat alt"><h3>Connected</h3><p><?= (int)($stats['connected_count'] ?? 0) ?></p><span><?= (int)($stats['gmail_count'] ?? 0) ?> Gmail · <?= (int)($stats['microsoft_count'] ?? 0) ?> Microsoft 365</span></div>
    <div class="card stat alt"><h3>Renewals due</h3><p><?= (int)($stats['renewal_due_count'] ?? 0) ?></p><span>Watch / subscription renewals due in 48 hours</span></div>
    <div class="card stat alt"><h3>Errors</h3><p><?= (int)($stats['error_count'] ?? 0) ?></p><span>Last sync <?= e($stats['last_synced_at'] ?? 'never') ?></span></div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Add or update mailbox</h2><span class="badge">OAuth-ready</span></div>
        <form method="post" action="index.php?route=messages/saveConnectedMailbox" class="stacked-panel">
            <?= csrf_input() ?>
            <div class="form-grid two">
                <select name="provider">
                    <option value="gmail">Gmail / Google Workspace</option>
                    <option value="microsoft365">Microsoft 365 / Outlook</option>
                </select>
                <input name="name" placeholder="Mailbox name" required>
                <input name="email_address" placeholder="Mailbox email address" required>
                <input name="account_identifier" placeholder="External account / tenant id">
                <select name="oauth_status">
                    <option value="planned">Planned</option>
                    <option value="connected">Connected</option>
                    <option value="needs_renewal">Needs renewal</option>
                    <option value="error">Error</option>
                </select>
                <select name="sync_state">
                    <option value="idle">Idle</option>
                    <option value="queued">Queued</option>
                    <option value="syncing">Syncing</option>
                    <option value="error">Error</option>
                </select>
                <input name="token_expires_at" placeholder="Token expires at (YYYY-MM-DD HH:MM:SS)">
                <input name="subscription_expires_at" placeholder="Subscription expires at (YYYY-MM-DD HH:MM:SS)">
                <input name="watch_topic" placeholder="Gmail Pub/Sub topic or Graph resource">
                <input name="webhook_endpoint" placeholder="Webhook endpoint URL">
                <input name="subscription_id" placeholder="Watch / subscription id">
                <input name="history_cursor" placeholder="History cursor or delta token">
                <input name="scope_json" placeholder="mail.read,mail.send,mail.modify,contacts.read">
                <label class="mail-inline-check"><input type="checkbox" name="is_active" value="1" checked> Active mailbox</label>
            </div>
            <button class="btn primary">Save mailbox</button>
        </form>
        <div class="small muted mt-12">Store the mailbox record first, then queue sync or renewal jobs as credentials and webhook infrastructure are completed.</div>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Provider checklist</h2><span class="badge">Rollout guide</span></div>
        <div class="alert-list">
            <article class="alert-tile ok"><strong>Gmail</strong><div class="small muted">Use Google OAuth, store the watch topic, and renew mailbox watch state before expiration.</div></article>
            <article class="alert-tile ok"><strong>Microsoft 365</strong><div class="small muted">Store the tenant/account identifier, renewal window, delta link, and change subscription id.</div></article>
            <article class="alert-tile warn"><strong>Queue worker</strong><div class="small muted">Run the new mailbox sync job from cron so queued mailbox refreshes do not sit idle.</div></article>
            <article class="alert-tile warn"><strong>Webhook security</strong><div class="small muted">Pair mailbox connections with secured webhook endpoints and renewal checks in Sync Health.</div></article>
        </div>
    </div>
</section>

<section class="card">
    <div class="toolbar"><h2>Connected mailbox inventory</h2><span class="badge"><?= count($mailboxes) ?></span></div>
    <table>
        <thead>
        <tr><th>Provider</th><th>Mailbox</th><th>OAuth</th><th>Sync</th><th>Subscription expires</th><th>Last synced</th><th>Actions</th></tr>
        </thead>
        <tbody>
        <?php foreach ($mailboxes as $mailbox): ?>
            <tr>
                <td><?= e(ucfirst((string)($mailbox['provider'] ?? 'gmail'))) ?></td>
                <td>
                    <strong><?= e($mailbox['name'] ?? '') ?></strong><br>
                    <span class="small muted"><?= e($mailbox['email_address'] ?? '') ?></span>
                </td>
                <td><span class="badge <?= e($mailbox['oauth_status'] ?? 'planned') ?>"><?= e($mailbox['oauth_status'] ?? 'planned') ?></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><?= e($mailbox['subscription_expires_at'] ?? '—') ?></td>
                <td><?= e($mailbox['last_synced_at'] ?? 'never') ?></td>
                <td>
                    <div style="display:flex;gap:8px;flex-wrap:wrap;">
                        <form method="post" action="index.php?route=messages/queueMailboxSync">
                            <?= csrf_input() ?>
                            <input type="hidden" name="id" value="<?= (int)$mailbox['id'] ?>">
                            <button class="btn secondary small">Queue sync</button>
                        </form>
                        <form method="post" action="index.php?route=messages/renewMailboxSubscription">
                            <?= csrf_input() ?>
                            <input type="hidden" name="id" value="<?= (int)$mailbox['id'] ?>">
                            <button class="btn secondary small">Renew subscription</button>
                        </form>
                    </div>
                </td>
            </tr>
        <?php endforeach; ?>
        <?php if (!$mailboxes): ?>
            <tr><td colspan="7" class="muted">No connected mailboxes saved yet.</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Webhook subscriptions</h2><span class="badge"><?= count($subscriptions) ?></span></div>
        <table>
            <thead><tr><th>Mailbox</th><th>Scope</th><th>Subscription</th><th>Expires</th><th>Verification</th></tr></thead>
            <tbody>
            <?php foreach ($subscriptions as $subscription): ?>
                <tr>
                    <td><?= e(($subscription['mailbox_name'] ?? 'Mailbox') . ' · ' . ($subscription['email_address'] ?? '')) ?></td>
                    <td><?= e($subscription['resource_scope'] ?? 'messages') ?></td>
                    <td><code><?= e($subscription['subscription_id'] ?? 'pending') ?></code></td>
                    <td><?= e($subscription['expires_at'] ?? '—') ?></td>
                    <td><?= e($subscription['verification_state'] ?? 'planned') ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$subscriptions): ?><tr><td colspan="5" class="muted">No subscriptions recorded 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</th><th>Status</th><th>Available</th><th>Updated</th><th>Error</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 class="small" style="max-width:280px;"><?= e($job['last_error'] ?? '') ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$queueJobs): ?><tr><td colspan="5" class="muted">No mailbox sync jobs yet.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</section>
