<?php
$stats = $connectedMailboxStats ?? ['total_count' => 0, 'connected_count' => 0, 'renewal_due_count' => 0, 'error_count' => 0, 'last_synced_at' => null, 'imported_total' => 0, 'last_imported_at' => null];
$mailboxes = $connectedMailboxes ?? [];
$subscriptions = $mailboxSubscriptions ?? [];
$queueJobs = $queueJobs ?? [];
$presets = $mailboxProviderPresets ?? [];
?>
<section class="workspace-hero">
    <div>
        <h2>Connected Mailboxes</h2>
        <p>Finish the V16.11 mailbox phases with a real inbox bridge: connect Gmail or Microsoft 365 accounts, poll them over IMAP today, and keep the API foundation fields ready for later OAuth / webhook rollout.</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>
        <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>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>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>Bridge mode</h3><p><?= (int)($stats['imap_bridge_count'] ?? 0) ?></p><span><?= (int)($stats['api_foundation_count'] ?? 0) ?> API foundation</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 mailbox bridge</h2><span class="badge">Live import ready</span></div>
        <form method="post" action="index.php?route=messages/saveConnectedMailbox" class="stacked-panel" id="connected-mailbox-form" data-provider-presets='<?= e(json_encode($presets, JSON_UNESCAPED_SLASHES)) ?>'>
            <?= csrf_input() ?>
            <div class="form-grid two">
                <label>
                    <span class="small muted">Provider</span>
                    <select name="provider" data-mailbox-provider>
                        <option value="gmail">Gmail / Google Workspace</option>
                        <option value="microsoft365">Microsoft 365 / Outlook</option>
                    </select>
                </label>
                <label>
                    <span class="small muted">Sync mode</span>
                    <select name="sync_mode" data-mailbox-sync-mode>
                        <option value="imap_bridge">IMAP bridge (functional now)</option>
                        <option value="api_foundation">API foundation only</option>
                    </select>
                </label>
                <label>
                    <span class="small muted">Mailbox name</span>
                    <input name="name" placeholder="Mailbox name" required>
                </label>
                <label>
                    <span class="small muted">Mailbox email address</span>
                    <input name="email_address" placeholder="team@example.com" required>
                </label>
                <label>
                    <span class="small muted">IMAP host</span>
                    <input name="imap_host" data-mailbox-preset="imap_host" placeholder="imap.gmail.com">
                </label>
                <label>
                    <span class="small muted">IMAP port</span>
                    <input name="imap_port" data-mailbox-preset="imap_port" placeholder="993">
                </label>
                <label>
                    <span class="small muted">IMAP flags</span>
                    <input name="imap_flags" data-mailbox-preset="imap_flags" placeholder="/imap/ssl/novalidate-cert">
                </label>
                <label>
                    <span class="small muted">Mailbox folder</span>
                    <input name="imap_mailbox" data-mailbox-preset="imap_mailbox" placeholder="INBOX">
                </label>
                <label>
                    <span class="small muted">IMAP username</span>
                    <input name="imap_username" placeholder="Mailbox login">
                </label>
                <label>
                    <span class="small muted">IMAP password / app password</span>
                    <input type="password" name="imap_password" placeholder="Stored for worker sync">
                </label>
                <label>
                    <span class="small muted">External account / tenant id</span>
                    <input name="account_identifier" placeholder="Optional provider account id">
                </label>
                <label>
                    <span class="small muted">OAuth status</span>
                    <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>
                </label>
                <label>
                    <span class="small muted">Sync state</span>
                    <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>
                </label>
                <label>
                    <span class="small muted">Subscription expires at</span>
                    <input name="subscription_expires_at" placeholder="YYYY-MM-DD HH:MM:SS">
                </label>
                <label>
                    <span class="small muted">Watch topic / resource</span>
                    <input name="watch_topic" data-mailbox-preset="watch_topic" placeholder="Optional foundation field">
                </label>
                <label>
                    <span class="small muted">Webhook endpoint</span>
                    <input name="webhook_endpoint" data-mailbox-preset="webhook_endpoint" placeholder="Optional foundation field">
                </label>
                <label>
                    <span class="small muted">Scopes</span>
                    <input name="scope_json" placeholder="mail.read,mail.send,mail.modify,contacts.read">
                </label>
                <label class="mail-inline-check"><input type="checkbox" name="is_active" value="1" checked> Active mailbox</label>
            </div>
            <div class="alert info small">Use <strong>IMAP bridge</strong> for the functional V16.11 path. Gmail usually requires an app password if MFA is enabled; Microsoft 365 typically uses the mailbox password or app password for IMAP-enabled accounts.</div>
            <button class="btn primary">Save mailbox</button>
        </form>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Phase completion notes</h2><span class="badge">V16.11.1</span></div>
        <div class="alert-list">
            <article class="alert-tile ok"><strong>Mail Center ingestion</strong><div class="small muted">Mailbox sync jobs now import inbound email directly into the <code>messages</code> table so Mail Center can display connected mailbox mail.</div></article>
            <article class="alert-tile ok"><strong>Source-aware threads</strong><div class="small muted">Imported email stores source mailbox metadata, making it easier to filter Mail Center by connected mailbox.</div></article>
            <article class="alert-tile warn"><strong>API foundation still available</strong><div class="small muted">Google / Microsoft OAuth, webhooks, watch renewals, and delta cursors still need your provider credentials and infrastructure to go live.</div></article>
            <article class="alert-tile warn"><strong>Worker requirement</strong><div class="small muted">Run <code>scripts/sync_mailboxes.php</code> from cron every minute so queued mailbox imports do not sit idle.</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>Mode</th><th>IMAP</th><th>Imported</th><th>Last import</th><th>Sync</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((string)($mailbox['sync_mode'] ?? 'imap_bridge')) ?></span></td>
                <td>
                    <div class="small"><?= e($mailbox['imap_host'] ?? '—') ?><?= !empty($mailbox['imap_port']) ? ':' . (int)$mailbox['imap_port'] : '' ?></div>
                    <div class="small muted"><?= e($mailbox['imap_mailbox'] ?? 'INBOX') ?></div>
                </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>
                    <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>
                    <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>
                        <a class="btn secondary small" href="index.php?route=messages/mailCenter&connected_mailbox_id=<?= (int)$mailbox['id'] ?>">Open in Mail Center</a>
                        <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">Refresh health</button>
                        </form>
                    </div>
                </td>
            </tr>
        <?php endforeach; ?>
        <?php if (!$mailboxes): ?>
            <tr><td colspan="8" 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 / subscription records</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 subscription records 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 / 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 class="small" style="max-width:320px;"><?= 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>

<script>
(function () {
    const form = document.getElementById('connected-mailbox-form');
    if (!form) return;
    let presets = {};
    try {
        presets = JSON.parse(form.dataset.providerPresets || '{}');
    } catch (err) {
        presets = {};
    }
    const providerSelect = form.querySelector('[data-mailbox-provider]');
    const syncModeSelect = form.querySelector('[data-mailbox-sync-mode]');
    const applyPreset = () => {
        const provider = providerSelect ? providerSelect.value : 'gmail';
        const preset = presets[provider] || {};
        Object.keys(preset).forEach((key) => {
            const field = form.querySelector('[name="' + key + '"]');
            if (!field) return;
            if (field.value && field.dataset.userEdited === '1') return;
            field.value = preset[key];
        });
        if (syncModeSelect && !syncModeSelect.dataset.userEdited && preset.sync_mode) {
            syncModeSelect.value = preset.sync_mode;
        }
    };
    form.querySelectorAll('input, select').forEach((field) => {
        field.addEventListener('input', () => {
            field.dataset.userEdited = '1';
        });
        field.addEventListener('change', () => {
            field.dataset.userEdited = '1';
        });
    });
    if (providerSelect) {
        providerSelect.addEventListener('change', () => {
            const fields = ['imap_host', 'imap_port', 'imap_flags', 'imap_mailbox', 'watch_topic', 'webhook_endpoint'];
            fields.forEach((name) => {
                const field = form.querySelector('[name="' + name + '"]');
                if (field) {
                    field.dataset.userEdited = '';
                }
            });
            if (syncModeSelect) {
                syncModeSelect.dataset.userEdited = '';
            }
            applyPreset();
        });
    }
    applyPreset();
})();
</script>
