<?php
$s = $summary ?? [];
$counts = $counts ?? ['sent' => 0, 'draft' => 0, 'all' => 0];
$status = $status ?? 'sent';
$delivered = (int) ($s['delivered'] ?? 0);
$opened = (int) ($s['opened'] ?? 0);
$clicked = (int) ($s['clicked'] ?? 0);
$bouncedN = (int) ($s['bounced'] ?? 0);
$unsub = (int) ($s['unsubscribed'] ?? 0);
$pct = static function (int $n, int $d): int {
    return $d < 1 ? 0 : (int) round(100 * $n / $d);
};
$openPct = $pct($opened, $delivered);
$clickPct = $pct($clicked, $delivered);
$bouncePct = $pct($bouncedN, $delivered);
$filterUrl = static function (string $st): string {
    return url('campaigns/reports') . '?' . http_build_query(['status' => $st]);
};
$filters = [
    ['sent', 'Sent', (int) $counts['sent']],
    ['draft', 'Draft', (int) $counts['draft']],
    ['all', 'All', (int) $counts['all']],
];
$kpis = [
    ['Sent this month', (string) (int) ($s['campaigns_sent'] ?? 0), 'bi-send-fill', '#2563eb', '#eff6ff'],
    ['Delivered', number_format($delivered), 'bi-envelope-check-fill', '#16a34a', '#f0fdf4'],
    ['Open rate', $openPct . '%', 'bi-eye-fill', '#7c3aed', '#f3e8ff'],
    ['Click rate', $clickPct . '%', 'bi-cursor-fill', '#ea580c', '#fff7ed'],
    ['Bounces', number_format($bouncedN) . ($delivered ? ' · ' . $bouncePct . '%' : ''), 'bi-exclamation-triangle-fill', '#dc2626', '#fef2f2'],
    ['Unsubscribes', number_format($unsub), 'bi-person-dash-fill', '#db2777', '#fce7f3'],
];
$canOpen = can_see('campaigns');
?>
<div class="rpt-page">
  <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-3">
    <div>
      <h1 class="page-title">Campaign reports</h1>
      <p class="page-sub mb-0">This month’s sends, opens, clicks, and problem addresses</p>
    </div>
  </div>

  <div class="rpt-kpis mb-3">
    <?php foreach ($kpis as $k): ?>
      <div class="task-summary-card" style="--task-accent: <?= e($k[3]) ?>; --task-tint: <?= e($k[4]) ?>">
        <div class="task-summary-icon"><i class="bi <?= e($k[2]) ?>"></i></div>
        <div>
          <div class="task-summary-n"><?= e($k[1]) ?></div>
          <div class="task-summary-l"><?= e($k[0]) ?></div>
        </div>
      </div>
    <?php endforeach; ?>
  </div>

  <div class="task-toolbar mb-3">
    <div class="task-chips">
      <?php foreach ($filters as $f): ?>
        <a class="task-chip <?= $status === $f[0] ? 'active' : '' ?>" href="<?= e($filterUrl($f[0])) ?>">
          <?= e($f[1]) ?>
          <span><?= (int) $f[2] ?></span>
        </a>
      <?php endforeach; ?>
    </div>
  </div>

  <?php if (!$stats): ?>
    <div class="card-soft task-empty mb-3">
      <div class="task-empty-icon"><i class="bi bi-graph-up"></i></div>
      <h2>No campaigns in this view</h2>
      <p><?php if ($canOpen): ?>Create a campaign under <strong>Campaigns</strong>, then send it to a list.<?php else: ?>Sent campaigns will show here once marketing has mailed a list.<?php endif; ?></p>
    </div>
  <?php else: ?>
    <?php foreach ($stats as $r):
      $st = $r['stats'] ?? [];
      $del = (int) ($st['delivered'] ?? 0);
      $opn = (int) ($st['opened'] ?? 0);
      $clk = (int) ($st['clicked'] ?? 0);
      $bnc = (int) ($st['bounced'] ?? 0);
      $uns = (int) ($st['unsubscribed'] ?? 0);
      $op = $pct($opn, $del);
      $cp = $pct($clk, $del);
      $campStatus = (string) ($r['status'] ?? 'draft');
    ?>
      <<?= $canOpen ? 'a' : 'div' ?> class="rpt-card" <?php if ($canOpen): ?>href="<?= e(url('campaigns/' . $r['id'])) ?>"<?php endif; ?>>
        <div class="rpt-card-top">
          <div class="rpt-icon"><i class="bi bi-megaphone"></i></div>
          <div class="flex-grow-1 min-w-0">
            <div class="lead-name"><?= e($r['name']) ?></div>
            <div class="lead-sub">
              <?php if (!empty($r['list_name'])): ?><span><?= e($r['list_name']) ?></span><?php endif; ?>
              <?php if (!empty($r['subject'])): ?><span class="text-truncate"><?= e(merge_readable($r['subject'])) ?></span><?php endif; ?>
            </div>
          </div>
          <span class="lead-status rpt-status-<?= e($campStatus) ?>"><?= e($campStatus === 'sent' ? 'Sent' : 'Draft') ?></span>
          <?php if (!empty($r['sent_at'])): ?>
            <span class="lead-date"><?= e(dt_fmt($r['sent_at'], 'M j')) ?></span>
          <?php endif; ?>
        </div>
        <div class="rpt-metrics">
          <div>
            <div class="rpt-metric-n"><?= $del ?></div>
            <div class="rpt-metric-l">Delivered</div>
          </div>
          <div>
            <div class="rpt-metric-n"><?= $op ?>%</div>
            <div class="rpt-metric-l">Opened · <?= $opn ?></div>
            <div class="rpt-bar"><span style="width:<?= $op ?>%;background:#7c3aed"></span></div>
          </div>
          <div>
            <div class="rpt-metric-n"><?= $cp ?>%</div>
            <div class="rpt-metric-l">Clicked · <?= $clk ?></div>
            <div class="rpt-bar"><span style="width:<?= $cp ?>%;background:#ea580c"></span></div>
          </div>
          <div>
            <div class="rpt-metric-n"><?= $bnc ?></div>
            <div class="rpt-metric-l">Bounced</div>
          </div>
          <div>
            <div class="rpt-metric-n"><?= $uns ?></div>
            <div class="rpt-metric-l">Unsub</div>
          </div>
        </div>
      </<?= $canOpen ? 'a' : 'div' ?>>
    <?php endforeach; ?>
  <?php endif; ?>

  <?php \App\Core\View::partial('pager', compact('page', 'pages')); ?>

  <h2 class="h6 mt-4 mb-2">Bounces</h2>
  <p class="page-sub">Bad addresses are marked so we stop sending to them.</p>
  <?php if (!$bounces): ?>
    <div class="card-soft p-4 text-muted">No bounces recorded.</div>
  <?php else: ?>
    <?php foreach ($bounces as $b): ?>
      <div class="rpt-bounce">
        <div class="rpt-bounce-icon"><i class="bi bi-exclamation-triangle-fill"></i></div>
        <div class="flex-grow-1 min-w-0">
          <div class="fw-bold text-truncate"><?= e($b['email']) ?></div>
          <div class="small text-muted"><?= e($b['campaign_name'] ?? '') ?></div>
        </div>
        <span class="lead-date"><?= e(dt_fmt($b['bounced_at'])) ?></span>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</div>
