<section class="cards four">
    <div class="card stat"><h3>Total Contacts</h3><p><?= (int)($contactCounts['total'] ?? 0) ?></p><span>Full audience records</span></div>
    <div class="card stat"><h3>SMS Reachable</h3><p><?= (int)($contactCounts['sms_reachable'] ?? 0) ?></p><span>Not unsubscribed</span></div>
    <div class="card stat"><h3>Email Reachable</h3><p><?= (int)($contactCounts['email_reachable'] ?? 0) ?></p><span>Opted in contacts</span></div>
    <div class="card stat"><h3>Templates</h3><p><?= (int)$templateCount ?></p><span>Reusable brand content</span></div>
</section>

<section class="cards four">
    <div class="card stat alt"><h3>Campaign Queued</h3><p><?= (int)($campaignExecution['queued_total'] ?? 0) ?></p><span>Recipients waiting in campaign queues</span></div>
    <div class="card stat alt"><h3>Campaign Sent</h3><p><?= (int)($campaignExecution['sent_total'] ?? 0) ?></p><span>Recipients marked sent from campaigns</span></div>
    <div class="card stat alt"><h3>Campaign Failed</h3><p><?= (int)($campaignExecution['failed_total'] ?? 0) ?></p><span>Recipients that failed during campaign processing</span></div>
    <div class="card stat alt"><h3>Campaign Total</h3><p><?= (int)($campaignExecution['total_recipients'] ?? 0) ?></p><span>Queued + sent + failed + skipped campaign recipients</span></div>
</section>

<section class="cards four">
    <div class="card stat alt"><h3>Email Delivered</h3><p><?= (int)($campaignRollup['delivered_total'] ?? ($delivery['delivered_count'] ?? 0)) ?></p><span>Provider-level delivery events from campaign mail</span></div>
    <div class="card stat alt"><h3>Unique Opens</h3><p><?= (int)($campaignRollup['unique_open_total'] ?? ($delivery['unique_open_count'] ?? 0)) ?></p><span>Campaign email recipients who opened at least once</span></div>
    <div class="card stat alt"><h3>Unique Clicks</h3><p><?= (int)($campaignRollup['unique_click_total'] ?? ($delivery['unique_click_count'] ?? 0)) ?></p><span>Campaign email recipients who clicked tracked links</span></div>
    <div class="card stat alt"><h3>Dead Letters</h3><p><?= (int)($queueStats['dead_letter_jobs'] ?? 0) ?></p><span>Queue items awaiting replay or recovery</span></div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Version + Schema</h2><span class="badge">V<?= e($appVersion) ?></span></div>
        <table>
            <tbody>
                <tr><th>Application Version</th><td><?= e($appVersion) ?> <span class="badge" style="margin-left:8px;">Source: <?= e($appVersionSource ?? 'unknown') ?></span></td></tr>
                <tr><th>Schema Version</th><td><?= e($schemaVersion) ?></td></tr>
                <tr><th>Status</th><td><?= $schemaMatches ? 'Aligned' : 'Mismatch detected' ?></td></tr>
                <tr><th>Worker Heartbeat</th><td><?= e($heartbeat['label']) ?><?= $heartbeat['at'] ? ' • ' . e($heartbeat['at']) : '' ?></td></tr>
            </tbody>
        </table>
        <?php if (!$schemaMatches): ?>
            <p class="alert error" style="margin-top:12px;">Code and database schema versions do not match. Run migrations from the installer or scripts/migrate.php.</p>
            <p style="margin-top:12px;display:flex;gap:10px;flex-wrap:wrap;">
                <a class="btn secondary" href="install.php?action=repair">Run Repair / Migrations</a>
                <a class="btn secondary" href="index.php?route=settings/diagnostics">Open Diagnostics</a>
            </p>
        <?php endif; ?>
    </div>
    <div class="card">
        <h2>Delivery + Engagement Trend</h2>
        <div class="mini-chart" data-series='<?= e(json_encode($analytics)) ?>'></div>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <h2>Queue Health</h2>
        <table>
            <tbody>
                <tr><th>Queued</th><td><?= (int)($queueStats['queued_jobs'] ?? 0) ?></td></tr>
                <tr><th>Processing</th><td><?= (int)($queueStats['processing_jobs'] ?? 0) ?></td></tr>
                <tr><th>Done</th><td><?= (int)($queueStats['done_jobs'] ?? 0) ?></td></tr>
                <tr><th>Failed</th><td><?= (int)($queueStats['failed_jobs'] ?? 0) ?></td></tr>
                <tr><th>Dead Letters</th><td><?= (int)($queueStats['dead_letter_jobs'] ?? 0) ?></td></tr>
            </tbody>
        </table>
    </div>
    <div class="card">
        <h2>Recent Queue Jobs</h2>
        <table>
            <thead><tr><th>ID</th><th>Type</th><th>Status</th><th>Attempts</th><th>Updated</th></tr></thead>
            <tbody>
            <?php foreach ($queueJobs as $job): ?>
                <tr>
                    <td>#<?= (int)$job['id'] ?></td>
                    <td><?= e($job['job_type']) ?></td>
                    <td><?= e($job['status']) ?></td>
                    <td><?= (int)$job['attempts'] ?></td>
                    <td><?= e($job['updated_at']) ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <h2>Latest Campaigns</h2>
        <table>
            <thead><tr><th>Name</th><th>Channel</th><th>Queued</th><th>Sent</th><th>Status</th></tr></thead>
            <tbody>
            <?php foreach ($campaigns as $campaign): ?>
                <tr>
                    <td><?= e($campaign['name']) ?></td>
                    <td><?= e(strtoupper($campaign['channel'])) ?></td>
                    <td><?= (int)($campaign['queued_recipients'] ?? 0) ?></td>
                    <td><?= (int)($campaign['sent_recipients'] ?? 0) ?></td>
                    <td><?= e($campaign['status']) ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <div class="card">
        <h2>Recent Audit Log</h2>
        <table>
            <thead><tr><th>When</th><th>User</th><th>Action</th><th>Entity</th></tr></thead>
            <tbody>
            <?php foreach ($auditLogs as $log): ?>
                <tr>
                    <td><?= e($log['created_at']) ?></td>
                    <td><?= e($log['user_name'] ?: 'System') ?></td>
                    <td><?= e($log['action']) ?></td>
                    <td><?= e($log['entity_type']) ?> #<?= (int)$log['entity_id'] ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <h2>Saved Segments</h2>
        <table>
            <thead><tr><th>Name</th><th>Channel</th><th>Members</th></tr></thead>
            <tbody>
            <?php foreach ($segments as $segment): ?>
                <tr>
                    <td><?= e($segment['name']) ?></td>
                    <td><?= e(strtoupper($segment['channel'])) ?></td>
                    <td><?= (int)($segment['member_count'] ?? 0) ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <div class="card">
        <h2>Recent Dead Letters</h2>
        <table>
            <thead><tr><th>ID</th><th>Type</th><th>Error</th><th></th></tr></thead>
            <tbody>
            <?php foreach ($deadLetters as $dead): ?>
                <tr>
                    <td>#<?= (int)$dead['id'] ?></td>
                    <td><?= e($dead['job_type']) ?></td>
                    <td><?= e(substr((string)$dead['last_error'], 0, 90)) ?></td>
                    <td><a class="btn secondary small" href="index.php?route=settings/replayDeadLetter&id=<?= (int)$dead['id'] ?>">Replay</a></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <h2>Workflow Automation</h2>
        <table>
            <tbody>
                <tr><th>Total workflows</th><td><?= (int)($workflowStats['total'] ?? 0) ?></td></tr>
                <tr><th>Active workflows</th><td><?= (int)($workflowStats['active_count'] ?? 0) ?></td></tr>
                <tr><th>Contact-created triggers</th><td><?= (int)($workflowStats['created_triggers'] ?? 0) ?></td></tr>
                <tr><th>Tag-added triggers</th><td><?= (int)($workflowStats['tag_triggers'] ?? 0) ?></td></tr>
            </tbody>
        </table>
    </div>
    <div class="card">
        <h2>Lifecycle Stages</h2>
        <table>
            <thead><tr><th>Stage</th><th>Contacts</th></tr></thead>
            <tbody>
            <?php foreach ($stageBreakdown as $row): ?>
                <tr><td><?= e(ucfirst($row['lifecycle_stage'])) ?></td><td><?= (int)$row['total'] ?></td></tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</section>

<section class="grid three">
    <div class="card"><div class="toolbar"><h2>Provider Status</h2><span class="badge">Ops</span></div><div class="small muted">Twilio</div><strong><?= $providerStatus['twilio']['configured'] ? 'Configured' : 'Missing' ?></strong><div class="small muted">Mail</div><strong><?= $providerStatus['smtp']['configured'] ? 'Configured' : 'Missing' ?></strong><div class="small muted" style="margin-top:10px;">Latest test</div><strong><?= !empty($providerTestResults['twilio']['message']) ? e($providerTestResults['twilio']['message']) : 'Not run yet' ?></strong><div style="margin-top:8px;"><a class="btn secondary small" href="index.php?route=settings/providerStatus">Open Provider Detail</a></div></div>
    <div class="card"><div class="toolbar"><h2>Quiet Hours</h2><span class="badge">Compliance</span></div><div class="small muted">Enabled</div><strong><?= !empty($quietHours['enabled']) ? 'Yes' : 'No' ?></strong><div class="small muted">Window</div><strong><?= e($quietHours['start']) ?> - <?= e($quietHours['end']) ?></strong></div>
    <div class="card"><div class="toolbar"><h2>Upcoming Reminders</h2><span class="badge">CRM</span></div><?php foreach ($reminders as $reminder): ?><div class="small"><?= e($reminder['title']) ?> · <?= e($reminder['remind_at']) ?></div><?php endforeach; ?></div>
</section>

<section class="grid two">
    <div class="card">
        <h2>Pipeline Breakdown</h2>
        <table>
            <thead><tr><th>Pipeline</th><th>Contacts</th></tr></thead>
            <tbody><?php foreach ($pipelineBreakdown as $row): ?><tr><td><?= e($row['pipeline_name']) ?></td><td><?= (int)$row['total'] ?></td></tr><?php endforeach; ?></tbody>
        </table>
    </div>
    <div class="card">
        <h2>Pipeline Stage Reporting</h2>
        <table>
            <thead><tr><th>Pipeline</th><th>Stage</th><th>Total</th><th>Avg Score</th></tr></thead>
            <tbody><?php foreach ($pipelineStageReport as $row): ?><tr><td><?= e($row['pipeline_name']) ?></td><td><?= e(ucfirst($row['lifecycle_stage'])) ?></td><td><?= (int)$row['total'] ?></td><td><?= (int)round($row['avg_score']) ?></td></tr><?php endforeach; ?></tbody>
        </table>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <h2>Pipeline Conversion Matrix</h2>
        <table>
            <thead><tr><th>Pipeline</th><th>Total</th><th>Qualified</th><th>Proposal</th><th>Customers</th><th>Customer %</th></tr></thead>
            <tbody><?php foreach ($pipelineStageMatrix as $row): ?><tr><td><?= e($row['pipeline_name']) ?></td><td><?= (int)$row['total_contacts'] ?></td><td><?= (int)$row['qualified_count'] ?></td><td><?= (int)$row['proposal_count'] ?></td><td><?= (int)$row['customer_count'] ?></td><td><?= e(number_format((float)($row['customer_rate'] ?? 0), 1)) ?>%</td></tr><?php endforeach; ?></tbody>
        </table>
    </div>
    <div class="card">
        <h2>Pipeline Ownership</h2>
        <table>
            <thead><tr><th>Pipeline</th><th>Owner</th><th>Contacts</th><th>Avg Score</th></tr></thead>
            <tbody><?php foreach ($pipelineOwnerReport as $row): ?><tr><td><?= e($row['pipeline_name']) ?></td><td><?= e($row['owner_name']) ?></td><td><?= (int)$row['total_contacts'] ?></td><td><?= e(number_format((float)($row['avg_score'] ?? 0), 1)) ?></td></tr><?php endforeach; ?></tbody>
        </table>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <h2>Login History</h2>
        <table><thead><tr><th>When</th><th>User</th><th>Status</th><th>IP</th></tr></thead><tbody><?php foreach ($loginHistory as $row): ?><tr><td><?= e($row['created_at']) ?></td><td><?= e($row['user_name'] ?: $row['email']) ?></td><td><?= e($row['status']) ?></td><td><?= e($row['ip_address']) ?></td></tr><?php endforeach; ?></tbody></table>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Quick Actions</h2><span class="badge">V13</span></div>
        <p><a class="btn secondary" href="index.php?route=search/index">Open Global Search</a></p>
        <p><a class="btn secondary" href="index.php?route=settings/diagnostics">Open Health Center</a></p>
        <p><a class="btn secondary" href="index.php?route=settings/providerStatus">Provider Status</a></p>
    </div>
</section>
