<?php
$s = $summary ?? [];
$counts = $counts ?? ['sent' => 0, 'draft' => 0, 'all' => 0];
$status = $status ?? 'all';
$rows = $rows ?? [];
$lists = $lists ?? [];
$templates = $templates ?? [];
$delivered = (int) ($s['delivered'] ?? 0);
$opened = (int) ($s['opened'] ?? 0);
$clicked = (int) ($s['clicked'] ?? 0);
$pct = static function (int $n, int $den): int {
    return $den < 1 ? 0 : (int) round(100 * $n / $den);
};
$openPct = $pct($opened, $delivered);
$clickPct = $pct($clicked, $delivered);
$filterUrl = static function (string $st): string {
    return url('campaigns') . ($st === 'all' ? '' : '?' . http_build_query(['status' => $st]));
};
$filters = [
    ['all', 'All', (int) $counts['all']],
    ['draft', 'Draft', (int) $counts['draft']],
    ['sent', 'Sent', (int) $counts['sent']],
];
$kpis = [
    [(string) (int) ($s['campaigns_sent'] ?? 0), 'Sent this month', 'bi-send-fill', '#2563eb', '#eff6ff', url('campaigns') . '?status=sent'],
    [number_format($delivered), 'Delivered', 'bi-envelope-check-fill', '#16a34a', '#f0fdf4', url('campaigns/reports')],
    [$openPct . '%', 'Open rate', 'bi-eye-fill', '#7c3aed', '#f3e8ff', url('campaigns/reports')],
    [$clickPct . '%', 'Click rate', 'bi-cursor-fill', '#ea580c', '#fff7ed', url('campaigns/reports')],
];
$canReports = can_see('campaign_reports');
?>
<div class="camp-page">
  <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-3">
    <div>
      <h1 class="page-title">Campaigns</h1>
      <p class="page-sub mb-0">Plan a group email, send it from a live list, and see how it did. Personal one-to-one mail stays in Email.</p>
    </div>
    <?php if ($canReports): ?>
      <a class="btn btn-outline-primary" href="<?= e(url('campaigns/reports')) ?>"><i class="bi bi-graph-up"></i> Reports</a>
    <?php endif; ?>
  </div>

  <div class="task-summary mb-3">
    <?php foreach ($kpis as $k): ?>
      <a class="task-summary-card" href="<?= e($k[5]) ?>" 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[0]) ?></div>
          <div class="task-summary-l"><?= e($k[1]) ?></div>
        </div>
      </a>
    <?php endforeach; ?>
  </div>

  <form class="camp-compose ajax-form mb-3" action="<?= e(url('campaigns')) ?>" method="post">
    <?= csrf_field() ?>
    <div class="camp-compose-head">
      <div class="task-summary-icon" style="--task-accent:#2563eb;--task-tint:#eff6ff"><i class="bi bi-megaphone-fill"></i></div>
      <div class="min-w-0">
        <div class="camp-compose-title">New campaign</div>
        <p class="camp-compose-sub mb-0">Pick a live list, optional template, then save a draft. Send from the campaign page.</p>
      </div>
    </div>
    <?php if (!$lists): ?>
      <div class="camp-compose-note">
        Save a list under <a href="<?= e(url('lists')) ?>">Lists</a> first — a campaign needs someone to mail.
      </div>
    <?php endif; ?>
    <div class="camp-compose-grid">
      <div>
        <label class="form-label" for="campName">Name</label>
        <input class="form-control" id="campName" name="name" placeholder="Spring catalog" required>
      </div>
      <div>
        <label class="form-label" for="campList">List</label>
        <select class="form-select" id="campList" name="list_id" required <?= $lists ? '' : 'disabled' ?>>
          <option value=""><?= $lists ? 'Choose a list' : 'No lists yet' ?></option>
          <?php foreach ($lists as $l): ?>
            <option value="<?= (int) $l['id'] ?>"><?= e($l['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label class="form-label" for="tplPick">Template</label>
        <select class="form-select" name="template_id" id="tplPick">
          <option value="">None — write it here</option>
          <?php foreach ($templates as $t): ?>
            <option value="<?= (int) $t['id'] ?>" data-subject="<?= e($t['subject']) ?>" data-body="<?= e($t['body']) ?>"><?= e($t['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label class="form-label" for="campSubject">Subject</label>
        <input class="form-control" name="subject" id="campSubject" placeholder="A note for {{first_name}}" required>
      </div>
      <div class="camp-compose-body">
        <label class="form-label" for="campBody">Message</label>
        <textarea class="form-control" name="body" id="campBody" rows="4" placeholder="Hello {{first_name}} at {{company}}" required></textarea>
      </div>
    </div>
    <button class="btn btn-primary" type="submit" <?= $lists ? '' : 'disabled' ?>>Save draft</button>
  </form>

  <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 (!$rows): ?>
    <div class="card-soft task-empty">
      <div class="task-empty-icon"><i class="bi bi-megaphone"></i></div>
      <h2><?= $status === 'all' ? 'No campaigns yet' : 'Nothing in this view' ?></h2>
      <p><?= $status === 'draft' ? 'Saved drafts will show here until you send them.' : ($status === 'sent' ? 'Sent campaigns will show here with opens and clicks.' : 'Save a draft above, pick a live list, then send from the campaign page.') ?></p>
    </div>
  <?php else: ?>
    <?php foreach ($rows 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');
    ?>
      <a class="rpt-card" href="<?= e(url('campaigns/' . $r['id'])) ?>">
        <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>
        <?php if ($campStatus === 'sent'): ?>
          <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>
        <?php endif; ?>
      </a>
    <?php endforeach; ?>
  <?php endif; ?>

  <?php \App\Core\View::partial('pager', compact('page', 'pages')); ?>
</div>
<script>
document.getElementById('tplPick')?.addEventListener('change', function () {
  const opt = this.options[this.selectedIndex];
  if (!opt || !opt.value) return;
  document.getElementById('campSubject').value = opt.getAttribute('data-subject') || '';
  document.getElementById('campBody').value = opt.getAttribute('data-body') || '';
});
</script>
