<?php
$actionButton = function (string $route, string $label, int $campaignId, string $returnTo = 'report', 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());
};
$operatorState = (string)($campaign['operator_state'] ?? 'running');
$displayStatus = (string)($campaign['display_status'] ?? ($campaign['status'] ?? 'draft'));
$hasQueued = (int)($campaign['queued_recipients'] ?? 0) > 0;
$hasFailed = (int)($campaign['failed_recipients'] ?? 0) > 0;
$isPending = ($campaign['approval_status'] ?? 'not_required') === 'pending';
$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;
?>
<section class="cards four">
    <div class="card stat"><h3>Recipients</h3><p><?= (int)($campaign['total_recipients'] ?? 0) ?></p><span><?= e($campaign['name']) ?></span></div>
    <div class="card stat alt"><h3>Queued</h3><p><?= (int)($campaign['queued_recipients'] ?? 0) ?></p><span><?= e(ucfirst($operatorState)) ?> run control</span></div>
    <div class="card stat alt"><h3>Delivery Rate</h3><p><?= number_format((float)($campaignHealth['delivery_rate'] ?? 0), 1) ?>%</p><span><?= e(strtoupper($campaign['channel'] ?? '')) ?> launch health</span></div>
    <div class="card stat alt"><h3>Click Rate</h3><p><?= number_format((float)($campaignHealth['click_rate'] ?? 0), 1) ?>%</p><span>Unique clicks vs recipients</span></div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Campaign Report</h2><span class="badge">V16.0</span></div>
        <table>
            <tbody>
                <tr><th>Name</th><td><?= e($campaign['name']) ?></td></tr>
                <tr><th>Channel</th><td><?= e(strtoupper($campaign['channel'])) ?></td></tr>
                <tr><th>Template</th><td><?= e($campaign['template_name'] ?? 'None') ?></td></tr>
                <tr><th>Status</th><td><?= e($displayStatus) ?></td></tr>
                <tr><th>Run Control</th><td><?= e(ucfirst($operatorState)) ?></td></tr>
                <tr><th>Approval</th><td><?= e($campaign['approval_status'] ?? 'not_required') ?></td></tr>
                <tr><th>Scheduled</th><td><?= e($campaign['scheduled_at'] ?? 'Immediate') ?></td></tr>
                <tr><th>Audience</th><td><?= e($preflight['summary']['audience_source'] ?? ($campaign['segment_name'] ?: 'All reachable contacts')) ?></td></tr>
                <tr><th>Saved List</th><td><?= e($campaign['contact_list_name'] ?? 'None') ?></td></tr>
                <tr><th>Variants</th><td><?= (int)($preflight['summary']['variant_count'] ?? 1) ?> versions</td></tr>
                <tr><th>Builder Blocks</th><td><?= (int)($preflight['summary']['block_count'] ?? 0) ?></td></tr>
            </tbody>
        </table>
        <div class="stacked-badges mt-12">
            <a class="btn secondary small" href="index.php?route=messages/campaignReports">Back to Campaign Reports</a>
            <a class="btn secondary small" href="index.php?route=settings/providerStatus">Provider Status</a>
            <?php if ($isPending): ?>
                <a class="btn primary small" href="index.php?route=messages/approveCampaign&id=<?= (int)$campaign['id'] ?>">Approve Campaign</a>
            <?php endif; ?>
        </div>
        <div class="mt-12">
            <?php if (!$isPending): ?>
                <?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'], 'report', '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 is available before a campaign sends or enters active processing.</span>
            <?php endif; ?>
        </div>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Run Controls</h2><span class="badge">Queue recovery</span></div>
        <div class="health-grid">
            <div class="health-item"><div class="small muted">Queued Recipients</div><strong><?= (int)($campaign['queued_recipients'] ?? 0) ?></strong><span>ready to resume or force</span></div>
            <div class="health-item"><div class="small muted">Failed Recipients</div><strong><?= (int)($campaign['failed_recipients'] ?? 0) ?></strong><span>restart to recover</span></div>
            <div class="health-item"><div class="small muted">Queue Jobs</div><strong><?= (int)($queueStats['queued_jobs'] ?? 0) ?> queued</strong><span><?= (int)($queueStats['failed_jobs'] ?? 0) ?> failed jobs</span></div>
            <div class="health-item"><div class="small muted">Mail</div><strong><?= !empty($providerStatus['smtp']['configured']) ? 'Ready' : 'Missing' ?></strong><span><?= e(($providerStatus['smtp']['label'] ?? 'Mail') . ' · ' . ($providerStatus['smtp']['from'] ?? '')) ?></span></div>
        </div>
        <ul class="feature-list small" style="margin-top:16px;">
            <li><strong>Start</strong> resumes queued recipients while respecting the scheduled send time unless you use Force Queue.</li>
            <li><strong>Pause</strong> halts active processing and leaves unsent recipients in the queue.</li>
            <li><strong>Stop</strong> halts the run until an operator explicitly restarts or force-queues it.</li>
            <li><strong>Restart</strong> returns failed recipients to the queue and launches a fresh processing pass.</li>
            <li><strong>Force Queue</strong> pulls the campaign back into the queue immediately after provider or SMTP changes.</li>
            <li><strong>Delete</strong> removes campaigns created by mistake before they send, including queued recipients and pending queue jobs.</li>
        </ul>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Preflight Checklist</h2><span class="badge">Launch guardrails</span></div>
        <div class="preflight-list">
            <?php foreach (($preflight['checks'] ?? []) as $check): ?>
                <div class="preflight-row status-<?= e($check['status']) ?>">
                    <strong><?= e($check['label']) ?></strong>
                    <span><?= e($check['detail']) ?></span>
                </div>
            <?php endforeach; ?>
        </div>
        <?php if (!empty($preflight['warnings'])): ?>
            <div class="alert-list mt-12">
                <?php foreach ($preflight['warnings'] as $warning): ?>
                    <article class="alert-tile warn"><strong>Warning</strong><div class="small muted"><?= e($warning) ?></div></article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        <?php if (!empty($preflight['errors'])): ?>
            <div class="alert-list mt-12">
                <?php foreach ($preflight['errors'] as $error): ?>
                    <article class="alert-tile error"><strong>Blocking issue</strong><div class="small muted"><?= e($error) ?></div></article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Send Test</h2><span class="badge">Preview lane</span></div>
        <form method="post" action="index.php?route=messages/sendCampaignTest">
            <?= csrf_input() ?>
            <input type="hidden" name="campaign_id" value="<?= (int)$campaign['id'] ?>">
            <div class="form-grid">
                <input name="to_address" placeholder="<?= ($campaign['channel'] ?? 'email') === 'sms' ? 'Phone number' : 'Email address' ?>" required>
                <select name="variant">
                    <option value="default">Control content</option>
                    <?php if (!empty($campaign['variant_a_body']) || !empty($campaign['variant_a_subject'])): ?><option value="a">Variant A</option><?php endif; ?>
                    <?php if (!empty($campaign['variant_b_body']) || !empty($campaign['variant_b_subject'])): ?><option value="b">Variant B</option><?php endif; ?>
                </select>
            </div>
            <button class="btn primary">Send Test</button>
        </form>
        <div class="mini-chart mt-12" data-series='<?= e(json_encode($trend)) ?>' data-keys="delivered_count,unique_open_count,unique_click_count,bounced_count" data-names="Delivered|Unique Opens|Unique Clicks|Bounced" data-label-key="day"></div>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Variant Performance</h2><span class="badge">Control + A/B</span></div>
        <div class="mini-chart" data-series='<?= e(json_encode($variantPerformance)) ?>' data-keys="message_count,unique_open_count,unique_click_count,bounced_count" data-names="Messages|Unique Opens|Unique Clicks|Bounced" data-label-key="label"></div>
        <table style="margin-top:16px;">
            <thead><tr><th>Variant</th><th>Messages</th><th>Open Rate</th><th>Click Rate</th><th>Bounce Rate</th></tr></thead>
            <tbody>
            <?php foreach ($variantPerformance as $row): ?>
                <tr>
                    <td><?= e($row['label']) ?></td>
                    <td><?= (int)($row['message_count'] ?? 0) ?></td>
                    <td><?= number_format((float)($row['open_rate'] ?? 0), 1) ?>%</td>
                    <td><?= number_format((float)($row['click_rate'] ?? 0), 1) ?>%</td>
                    <td><?= number_format((float)($row['bounce_rate'] ?? 0), 1) ?>%</td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$variantPerformance): ?><tr><td colspan="5" class="muted">No variant data yet.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Comparison Snapshot</h2><span class="badge">Recent campaigns</span></div>
        <table>
            <thead><tr><th>Campaign</th><th>Sent</th><th>Opens</th><th>Clicks</th></tr></thead>
            <tbody>
            <?php foreach ($comparison 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; ?>
            </tbody>
        </table>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Recipient Breakdown</h2><span class="badge">Execution log</span></div>
        <table>
            <thead><tr><th>Recipient</th><th>Status</th><th>Message</th><th>Processed</th></tr></thead>
            <tbody>
            <?php foreach ($recipients as $row): ?>
                <tr>
                    <td><?= e(trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? '')) ?: ($row['address'] ?? '')) ?><br><span class="small muted"><?= e($row['address']) ?></span></td>
                    <td><?= e($row['status']) ?><?php if (!empty($row['error_message'])): ?><br><span class="small muted"><?= e($row['error_message']) ?></span><?php endif; ?></td>
                    <td><?= e($row['message_status'] ?? '-') ?></td>
                    <td><?= e($row['processed_at'] ?? '-') ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Template + Segment Performance</h2><span class="badge">Benchmarks</span></div>
        <div class="grid two" style="margin-bottom:0;">
            <div>
                <h3>Templates</h3>
                <table>
                    <thead><tr><th>Name</th><th>Messages</th><th>Opens</th></tr></thead>
                    <tbody>
                    <?php foreach ($templatePerformance as $row): ?>
                        <tr><td><?= e($row['name']) ?></td><td><?= (int)($row['message_count'] ?? 0) ?></td><td><?= (int)($row['unique_open_count'] ?? 0) ?></td></tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <div>
                <h3>Segments</h3>
                <table>
                    <thead><tr><th>Segment</th><th>Messages</th><th>Clicks</th></tr></thead>
                    <tbody>
                    <?php foreach ($segmentPerformance as $row): ?>
                        <tr><td><?= e($row['segment_name']) ?></td><td><?= (int)($row['message_count'] ?? 0) ?></td><td><?= (int)($row['unique_click_count'] ?? 0) ?></td></tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</section>
