<?php
$pendingApproval = count(array_filter($campaigns ?? [], fn($row) => ($row['approval_status'] ?? 'not_required') === 'pending'));
$sentTotal = array_sum(array_map(fn($row) => (int)($row['sent_recipients'] ?? 0), $campaigns ?? []));
$pausedTotal = count(array_filter($campaigns ?? [], fn($row) => ($row['operator_state'] ?? 'running') === 'paused'));
$stoppedTotal = count(array_filter($campaigns ?? [], fn($row) => ($row['operator_state'] ?? 'running') === 'stopped'));
$actionButton = function (string $route, string $label, int $campaignId, string $returnTo = 'reports', string $class = 'secondary'): string {
    ob_start();
    ?>
    <form method="post" action="index.php?route=<?= e($route) ?>" style="display:inline-block;margin:4px 6px 0 0;">
        <?= csrf_input() ?>
        <input type="hidden" name="campaign_id" value="<?= (int)$campaignId ?>">
        <input type="hidden" name="return_to" value="<?= e($returnTo) ?>">
        <button class="btn <?= e($class) ?> small" type="submit"><?= e($label) ?></button>
    </form>
    <?php
    return trim((string)ob_get_clean());
};
$deleteButton = function (int $campaignId, string $returnTo = 'reports', string $campaignName = 'this campaign'): string {
    ob_start();
    ?>
    <form method="post" action="index.php?route=messages/deleteCampaign" style="display:inline-block;margin:4px 6px 0 0;" onsubmit="return confirm('Delete <?= e(addslashes($campaignName)) ?>? This removes queued recipients, queued jobs, and unsent campaign history.');">
        <?= csrf_input() ?>
        <input type="hidden" name="campaign_id" value="<?= (int)$campaignId ?>">
        <input type="hidden" name="return_to" value="<?= e($returnTo) ?>">
        <button class="btn danger small" type="submit">Delete</button>
    </form>
    <?php
    return trim((string)ob_get_clean());
};
?>
<section class="workspace-hero">
    <div>
        <h2>Campaign Reports</h2>
        <p>Work the recovery queue, review campaign queue status, open detailed reports, and monitor approvals for commercial campaign operations.</p>
    </div>
    <div class="workspace-actions">
        <a class="btn secondary small" href="index.php?route=messages/campaignDashboard">Campaign Dashboard</a>
        <a class="btn secondary small" href="index.php?route=messages/campaignStudio">Campaign Studio</a>
    </div>
</section>

<section class="cards four compact-stats">
    <div class="card stat"><h3>Recovery Queue</h3><p><?= (int)($queueStats['failed_jobs'] ?? 0) ?></p><span>failed jobs waiting for action</span></div>
    <div class="card stat alt"><h3>Campaign Queue</h3><p><?= (int)($queueStats['queued_jobs'] ?? 0) ?></p><span>queued jobs pending processing</span></div>
    <div class="card stat alt"><h3>Paused / Stopped</h3><p><?= (int)$pausedTotal ?> / <?= (int)$stoppedTotal ?></p><span>operator-controlled runs</span></div>
    <div class="card stat alt"><h3>Total Sent</h3><p><?= (int)$sentTotal ?></p><span>recipients sent across listed campaigns</span></div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Recovery Queue</h2><span class="badge">Jobs</span></div>
        <table>
            <thead><tr><th>ID</th><th>Type</th><th>Error</th><th>Updated</th></tr></thead>
            <tbody>
            <?php foreach (($failedQueueJobs ?? []) as $job): ?>
                <tr>
                    <td>#<?= (int)$job['id'] ?></td>
                    <td><?= e($job['job_type']) ?></td>
                    <td><?= e(mb_strimwidth((string)$job['last_error'], 0, 90, '...')) ?></td>
                    <td><?= e($job['updated_at'] ?? $job['created_at'] ?? '') ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($failedQueueJobs)): ?><tr><td colspan="4" class="muted">No failed queue jobs.</td></tr><?php endif; ?>
            </tbody>
        </table>
        <div class="stacked-badges mt-12">
            <a class="btn secondary small" href="index.php?route=settings/diagnostics">Open Diagnostics</a>
            <a class="btn secondary small" href="index.php?route=settings/providerStatus">Provider Status</a>
        </div>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Campaign Queue + Reports</h2><span class="badge">Commercial campaigns</span></div>
        <table>
            <thead><tr><th>Name</th><th>Channel</th><th>Queued</th><th>Sent</th><th>Failed</th><th>State</th><th>Approval</th><th></th></tr></thead>
            <tbody>
            <?php foreach (($campaigns ?? []) as $campaign): ?>
                <?php
                $operatorState = (string)($campaign['operator_state'] ?? 'running');
                $displayStatus = (string)($campaign['display_status'] ?? ($campaign['status'] ?? 'draft'));
                $isPending = ($campaign['approval_status'] ?? 'not_required') === 'pending';
                $hasQueued = (int)($campaign['queued_recipients'] ?? 0) > 0;
                $hasFailed = (int)($campaign['failed_recipients'] ?? 0) > 0;
                $isActive = in_array((string)($campaign['status'] ?? ''), ['queued', 'processing'], true) && $operatorState === 'running';
                $canDelete = !in_array((string)($campaign['status'] ?? ''), ['processing'], true)
                    && (int)($campaign['sent_recipients'] ?? 0) <= 0
                    && (int)($campaign['delivered_count'] ?? 0) <= 0;
                ?>
                <tr>
                    <td><?= e($campaign['name']) ?><br><span class="small muted"><?= e($displayStatus) ?></span></td>
                    <td><?= e(strtoupper($campaign['channel'])) ?></td>
                    <td><?= (int)($campaign['queued_recipients'] ?? 0) ?> / <?= (int)($campaign['total_recipients'] ?? 0) ?></td>
                    <td><?= (int)($campaign['sent_recipients'] ?? 0) ?></td>
                    <td><?= (int)($campaign['failed_recipients'] ?? 0) ?></td>
                    <td><?= e(ucfirst($operatorState)) ?></td>
                    <td><?= e($campaign['approval_status'] ?? 'not_required') ?></td>
                    <td class="actions-cell">
                        <a class="btn secondary small" href="index.php?route=messages/report&id=<?= (int)$campaign['id'] ?>">Report</a>
                        <?php if ($isPending): ?>
                            <a class="btn primary small" href="index.php?route=messages/approveCampaign&id=<?= (int)$campaign['id'] ?>">Approve</a>
                        <?php else: ?>
                            <?php if ($hasQueued): ?>
                                <?= $actionButton('messages/startCampaign', 'Start', (int)$campaign['id']) ?>
                            <?php endif; ?>
                            <?php if ($isActive): ?>
                                <?= $actionButton('messages/pauseCampaign', 'Pause', (int)$campaign['id']) ?>
                                <?= $actionButton('messages/stopCampaign', 'Stop', (int)$campaign['id']) ?>
                            <?php endif; ?>
                            <?php if ($hasFailed || $operatorState === 'stopped'): ?>
                                <?= $actionButton('messages/restartCampaign', 'Restart', (int)$campaign['id']) ?>
                            <?php endif; ?>
                            <?php if ($hasQueued || $hasFailed): ?>
                                <?= $actionButton('messages/forceQueueCampaign', 'Force Queue', (int)$campaign['id'], 'reports', 'primary') ?>
                            <?php endif; ?>
                        <?php endif; ?>
                        <?php if ($canDelete): ?>
                            <?= $deleteButton((int)$campaign['id'], 'reports', (string)($campaign['name'] ?? 'this campaign')) ?>
                        <?php else: ?>
                            <span class="small muted">Delete locks after send or while processing.</span>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($campaigns)): ?><tr><td colspan="8" class="muted">No campaigns queued yet.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Comparison Snapshot</h2><span class="badge">Recent reports</span></div>
        <table>
            <thead><tr><th>Campaign</th><th>Sent</th><th>Opens</th><th>Clicks</th></tr></thead>
            <tbody>
            <?php foreach (($campaignComparison ?? []) as $row): ?>
                <tr>
                    <td><a href="index.php?route=messages/report&id=<?= (int)$row['id'] ?>"><?= e($row['name']) ?></a></td>
                    <td><?= (int)($row['sent_recipients'] ?? 0) ?></td>
                    <td><?= (int)($row['unique_open_count'] ?? 0) ?></td>
                    <td><?= (int)($row['unique_click_count'] ?? 0) ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($campaignComparison)): ?><tr><td colspan="4" class="muted">No campaign comparison data yet.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="card spaced-card">
        <div class="toolbar"><h2>Report Operations</h2><span class="badge">Workflow</span></div>
        <ul class="feature-list small">
            <li>Pause or stop active runs when provider, SMTP, or audience settings need to be changed.</li>
            <li>Use Restart to recover failed recipients without rebuilding the campaign audience from scratch.</li>
            <li>Use Force Queue to pull the campaign back into the processing queue immediately after a mail-provider fix.</li>
            <li>Use Delete for campaigns created by mistake before any send activity starts.</li>
        </ul>
    </div>
</section>
