<?php
$domainStats = $deliverabilityDomainStats ?? ['total_count' => 0, 'healthy_count' => 0, 'avg_daily_volume' => 0, 'last_checked_at' => null];
$domains = $deliverabilityDomains ?? [];
$dnsSummary = $dnsCheckSummary ?? [];
$dnsChecksByDomain = $dnsChecksByDomain ?? [];
$complianceSnapshot = $complianceSnapshot ?? ['score' => 0, 'passed' => 0, 'total' => 0, 'risk' => 'healthy'];
$reputationSummary = $reputationSummary ?? ['avg_inbox_rate' => 0, 'avg_spam_rate' => 0, 'avg_complaint_rate' => 0];
$eventWebhookSummary = $eventWebhookSummary ?? ['total_count' => 0, 'verified_count' => 0, 'last_event_at' => null];
$deliverabilitySettings = $deliverabilitySettings ?? [];
?>
<section class="workspace-hero">
    <div>
        <h2>Deliverability Control Tower</h2>
        <p>Manage sending domains, DNS records, unsubscribe posture, queue safety controls, reputation trends, and provider event observability in one screen.</p>
    </div>
    <div class="workspace-actions">
        <a class="btn secondary small" href="index.php?route=messages/commercialCampaign">Commercial Campaign</a>
        <a class="btn secondary small" href="index.php?route=settings/providerStatus">Provider Status</a>
    </div>
</section>

<section class="cards four compact-stats">
    <div class="card stat"><h3>Domains</h3><p><?= (int)($domainStats['total_count'] ?? 0) ?></p><span><?= (int)($domainStats['healthy_count'] ?? 0) ?> healthy / connected</span></div>
    <div class="card stat alt"><h3>Compliance score</h3><p><?= number_format((float)($complianceSnapshot['score'] ?? 0), 1) ?>%</p><span><?= (int)($complianceSnapshot['passed'] ?? 0) ?>/<?= (int)($complianceSnapshot['total'] ?? 0) ?> checks passing</span></div>
    <div class="card stat alt"><h3>Inbox rate</h3><p><?= number_format((float)($reputationSummary['avg_inbox_rate'] ?? 0), 1) ?>%</p><span>Spam <?= number_format((float)($reputationSummary['avg_spam_rate'] ?? 0), 2) ?>% · complaint <?= number_format((float)($reputationSummary['avg_complaint_rate'] ?? 0), 2) ?>%</span></div>
    <div class="card stat alt"><h3>Webhook events</h3><p><?= (int)($eventWebhookSummary['total_count'] ?? 0) ?></p><span><?= (int)($eventWebhookSummary['verified_count'] ?? 0) ?> verified · <?= e($eventWebhookSummary['last_event_at'] ?? 'never') ?></span></div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Add sending domain</h2><span class="badge">DNS planner</span></div>
        <form method="post" action="index.php?route=messages/saveDeliverabilityDomain" class="stacked-panel">
            <?= csrf_input() ?>
            <div class="form-grid two">
                <input name="domain_name" placeholder="example.com" required>
                <select name="provider_hint">
                    <option value="sendgrid">SendGrid</option>
                    <option value="smtp">SMTP relay</option>
                    <option value="microsoft365">Microsoft 365</option>
                    <option value="gmail">Google Workspace</option>
                </select>
                <select name="postmaster_status">
                    <option value="planned">Planned</option>
                    <option value="connected">Connected</option>
                    <option value="healthy">Healthy</option>
                    <option value="warning">Warning</option>
                </select>
                <input name="dkim_selector" placeholder="DKIM selector" value="s1">
                <input name="spf_include" placeholder="include:sendgrid.net" value="include:sendgrid.net">
                <select name="dmarc_policy">
                    <option value="none">none</option>
                    <option value="quarantine" selected>quarantine</option>
                    <option value="reject">reject</option>
                </select>
                <input name="return_path_domain" placeholder="bounce.example.com">
                <input name="tracking_domain" placeholder="click.example.com">
                <input name="bimi_svg_url" placeholder="https://example.com/brand.svg">
                <input name="warmup_profile" placeholder="Warm-up profile">
                <input name="complaint_threshold" type="number" step="0.001" value="0.1">
                <input name="bounce_threshold" type="number" step="0.1" value="3.0">
                <input name="daily_volume_target" type="number" step="100" value="5000">
                <label class="mail-inline-check"><input type="checkbox" name="one_click_unsubscribe_enabled" value="1" checked> One-click unsubscribe enabled</label>
                <label class="mail-inline-check"><input type="checkbox" name="is_active" value="1" checked> Active domain</label>
            </div>
            <button class="btn primary">Save domain</button>
        </form>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Guardrails and failover</h2><span class="badge">Safety controls</span></div>
        <form method="post" action="index.php?route=messages/saveCommercialCampaignSettings" class="stacked-panel">
            <?= csrf_input() ?>
            <input type="hidden" name="return_route" value="messages/deliverabilityControlTower">
            <div class="form-grid two">
                <input name="campaign_safe_launch_batch_size" type="number" min="10" step="10" value="<?= e($deliverabilitySettings['safe_launch_batch_size'] ?? '50') ?>" placeholder="Safe launch batch size">
                <input name="campaign_holdback_percent" type="number" min="0" max="50" step="1" value="<?= e($deliverabilitySettings['holdback_percent'] ?? '5') ?>" placeholder="Holdback %">
                <input name="campaign_seed_list_json" value="<?= e($deliverabilitySettings['seed_list_json'] ?? '') ?>" placeholder='["seed@example.com"]'>
                <input name="campaign_domain_throttle_json" value="<?= e($deliverabilitySettings['domain_throttle_json'] ?? '') ?>" placeholder='{"gmail.com":50}'>
                <select name="campaign_provider_failover_transport">
                    <option value="sendgrid_api" <?= ($deliverabilitySettings['provider_failover_transport'] ?? 'sendgrid_api') === 'sendgrid_api' ? 'selected' : '' ?>>SendGrid API</option>
                    <option value="smtp" <?= ($deliverabilitySettings['provider_failover_transport'] ?? '') === 'smtp' ? 'selected' : '' ?>>SMTP</option>
                    <option value="php_mail" <?= ($deliverabilitySettings['provider_failover_transport'] ?? '') === 'php_mail' ? 'selected' : '' ?>>PHP mail()</option>
                </select>
                <select name="deliverability_alerts_enabled">
                    <option value="1" <?= ($deliverabilitySettings['alerts_enabled'] ?? '1') === '1' ? 'selected' : '' ?>>Alerts enabled</option>
                    <option value="0" <?= ($deliverabilitySettings['alerts_enabled'] ?? '') === '0' ? 'selected' : '' ?>>Alerts disabled</option>
                </select>
                <select name="deliverability_one_click_unsubscribe">
                    <option value="1" <?= ($deliverabilitySettings['one_click_unsubscribe'] ?? '1') === '1' ? 'selected' : '' ?>>One-click unsubscribe enabled</option>
                    <option value="0" <?= ($deliverabilitySettings['one_click_unsubscribe'] ?? '') === '0' ? 'selected' : '' ?>>One-click unsubscribe disabled</option>
                </select>
            </div>
            <button class="btn secondary">Save guardrails</button>
        </form>
    </div>
</section>

<section class="card">
    <div class="toolbar"><h2>Domain inventory</h2><span class="badge"><?= count($domains) ?></span></div>
    <table>
        <thead><tr><th>Domain</th><th>Provider</th><th>Postmaster</th><th>DNS</th><th>One-click</th><th>Warm-up</th><th>Daily target</th></tr></thead>
        <tbody>
        <?php foreach ($domains as $domain): ?>
            <?php $summary = $dnsSummary[(int)$domain['id']] ?? ['pass_count' => 0, 'total_count' => 0, 'planned_count' => 0]; ?>
            <tr>
                <td><strong><?= e($domain['domain_name'] ?? '') ?></strong></td>
                <td><?= e($domain['provider_hint'] ?? '') ?></td>
                <td><span class="badge <?= e($domain['postmaster_status'] ?? 'planned') ?>"><?= e($domain['postmaster_status'] ?? 'planned') ?></span></td>
                <td><?= (int)($summary['pass_count'] ?? 0) ?>/<?= (int)($summary['total_count'] ?? 0) ?> passing · <?= (int)($summary['planned_count'] ?? 0) ?> planned</td>
                <td><?= !empty($domain['one_click_unsubscribe_enabled']) ? 'Yes' : 'No' ?></td>
                <td><?= e($domain['warmup_profile'] ?? '—') ?></td>
                <td><?= number_format((int)($domain['daily_volume_target'] ?? 0)) ?></td>
            </tr>
        <?php endforeach; ?>
        <?php if (!$domains): ?><tr><td colspan="7" class="muted">No deliverability domains saved yet.</td></tr><?php endif; ?>
        </tbody>
    </table>
</section>

<?php foreach ($domains as $domain): ?>
    <?php $checks = $dnsChecksByDomain[(int)$domain['id']] ?? []; ?>
    <section class="card spaced-card">
        <div class="toolbar"><h2><?= e($domain['domain_name'] ?? 'Domain') ?> DNS checklist</h2><span class="badge"><?= count($checks) ?> records</span></div>
        <table>
            <thead><tr><th>Type</th><th>Host</th><th>Expected</th><th>Status</th></tr></thead>
            <tbody>
            <?php foreach ($checks as $check): ?>
                <tr>
                    <td><?= e($check['record_type'] ?? '') ?></td>
                    <td><code><?= e($check['host_name'] ?? '') ?></code></td>
                    <td><code><?= e($check['expected_value'] ?? '') ?></code></td>
                    <td><?= e($check['status'] ?? 'planned') ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$checks): ?><tr><td colspan="4" class="muted">No DNS planner rows saved yet.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </section>
<?php endforeach; ?>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Recent reputation snapshots</h2><span class="badge"><?= count($reputationSnapshots ?? []) ?></span></div>
        <table>
            <thead><tr><th>Domain</th><th>Inbox %</th><th>Spam %</th><th>Complaint %</th><th>Observed</th></tr></thead>
            <tbody>
            <?php foreach (($reputationSnapshots ?? []) as $row): ?>
                <tr>
                    <td><?= e($row['domain_name'] ?? '') ?></td>
                    <td><?= number_format((float)($row['inbox_rate'] ?? 0), 1) ?></td>
                    <td><?= number_format((float)($row['spam_rate'] ?? 0), 2) ?></td>
                    <td><?= number_format((float)($row['complaint_rate'] ?? 0), 2) ?></td>
                    <td><?= e($row['observed_on'] ?? '') ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($reputationSnapshots)): ?><tr><td colspan="5" class="muted">No snapshots saved yet.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Event observability</h2><span class="badge"><?= count($eventWebhookLogs ?? []) ?></span></div>
        <table>
            <thead><tr><th>Provider</th><th>Event</th><th>Signature</th><th>Replay</th><th>Created</th></tr></thead>
            <tbody>
            <?php foreach (($eventWebhookLogs ?? []) as $row): ?>
                <tr>
                    <td><?= e($row['provider'] ?? '') ?></td>
                    <td><?= e($row['event_type'] ?? '') ?></td>
                    <td><?= e($row['signature_status'] ?? '') ?></td>
                    <td><?= e($row['replay_status'] ?? '') ?></td>
                    <td><?= e($row['created_at'] ?? '') ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($eventWebhookLogs)): ?><tr><td colspan="5" class="muted">No webhook events logged yet.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</section>
