<?php
$d = $data;
$s = $d['summary'] ?? [];
$hour = (int) date('G');
$hi = $hour < 12 ? 'Good morning' : ($hour < 17 ? 'Good afternoon' : 'Good evening');
$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);
$summaries = [
    [(string) (int) ($s['campaigns_sent'] ?? 0), 'Sent this month', 'bi-send-fill', '#2563eb', '#eff6ff', url('campaigns')],
    [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')],
];
$jumps = [
    ['Campaigns', (int) (($d['counts']['all'] ?? 0)), 'bi-megaphone-fill', url('campaigns'), '#2563eb', '#eff6ff'],
    ['Lists', (int) ($d['lists'] ?? 0), 'bi-collection-fill', url('lists'), '#0f766e', '#f0fdfa'],
    ['Templates', (int) ($d['templates'] ?? 0), 'bi-file-earmark-text-fill', url('templates'), '#7c3aed', '#f3e8ff'],
    ['Reports', (int) (($d['counts']['sent'] ?? 0)), 'bi-graph-up-arrow', url('campaigns/reports'), '#ea580c', '#fff7ed'],
];
?>
<div class="mkt-page">
  <div class="d-flex justify-content-between align-items-start dash-head">
    <div>
      <h1 class="page-title"><?= e($hi) ?>, <?= e(current_user()['first_name']) ?></h1>
      <p class="page-sub mb-0">Build a list, send a campaign, and see opens on the customer.</p>
    </div>
    <div class="d-flex flex-wrap align-items-center gap-2">
      <?php \App\Core\View::partial('smart_tips_jump', ['tips' => $tips ?? []]); ?>
      <div class="dash-date"><i class="bi bi-calendar3"></i> <?= date('M j, Y') ?></div>
      <a class="btn btn-primary" href="<?= e(url('campaigns')) ?>">New campaign</a>
    </div>
  </div>

  <?php if (dash_on('kpis')): ?>
  <div class="task-summary mb-3">
    <?php foreach ($summaries 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>
  <?php endif; ?>

  <?php if (dash_on('jumps')): ?>
  <div class="mkt-jumps mb-3">
    <?php foreach ($jumps as $j): ?>
      <a class="mkt-jump" href="<?= e($j[3]) ?>" style="--task-accent: <?= e($j[4]) ?>; --task-tint: <?= e($j[5]) ?>">
        <span class="task-summary-icon"><i class="bi <?= e($j[2]) ?>"></i></span>
        <span class="min-w-0">
          <span class="mkt-jump-n"><?= e((string) $j[1]) ?></span>
          <span class="mkt-jump-l"><?= e($j[0]) ?></span>
        </span>
        <i class="bi bi-chevron-right mkt-jump-go"></i>
      </a>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>

  <?php
    $campaigns = $d['campaigns'] ?? [];
    $sentN = (int) (($d['counts']['sent'] ?? 0));
    $draftN = (int) (($d['counts']['draft'] ?? 0));
    $campN = count($campaigns);
    $campSub = $campN
        ? $campN . ' latest · ' . $sentN . ' sent · ' . $draftN . ' draft'
        : 'Create a draft, pick a live list, and send';
  ?>
  <div class="card-soft rc-card">
    <div class="rc-head">
      <div class="rc-head-icon"><i class="bi bi-megaphone-fill"></i></div>
      <div class="min-w-0 flex-grow-1">
        <h2>Recent campaigns</h2>
        <p><?= e($campSub) ?></p>
      </div>
      <a href="<?= e(url('campaigns')) ?>">View all</a>
    </div>
    <?php if ($campaigns): ?>
      <div class="rc-pills">
        <?php if ($sentN): ?>
          <span class="rc-pill is-sent"><i class="bi bi-send-check"></i> <?= $sentN ?> sent</span>
        <?php endif; ?>
        <?php if ($draftN): ?>
          <span class="rc-pill is-draft"><i class="bi bi-pencil-square"></i> <?= $draftN ?> draft</span>
        <?php endif; ?>
      </div>
      <div class="rc-list">
        <?php foreach ($campaigns 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');
            $isSent = $campStatus === 'sent';
            $when = $isSent && !empty($r['sent_at'])
                ? dt_fmt($r['sent_at'], 'M j')
                : relative_when($r['created_at'] ?? null);
            $subject = trim((string) merge_readable((string) ($r['subject'] ?? '')));
            $listName = trim((string) ($r['list_name'] ?? ''));
        ?>
          <a class="rc-item is-<?= e($campStatus) ?>" href="<?= e(url('campaigns/' . (int) $r['id'])) ?>">
            <div class="rc-item-top">
              <span class="rc-mark"><i class="bi <?= $isSent ? 'bi-send-fill' : 'bi-file-earmark-text' ?>"></i></span>
              <span class="min-w-0 flex-grow-1">
                <span class="rc-name"><?= e($r['name'] ?: 'Untitled') ?></span>
                <span class="rc-meta">
                  <?php if ($listName !== ''): ?><span class="rc-list-name text-truncate"><?= e($listName) ?></span><?php endif; ?>
                  <?php if ($subject !== ''): ?><span class="rc-subj text-truncate"><?= e($subject) ?></span><?php endif; ?>
                </span>
              </span>
              <span class="rc-side">
                <span class="rc-status is-<?= e($campStatus) ?>"><?= $isSent ? 'Sent' : 'Draft' ?></span>
                <?php if ($when !== ''): ?><span class="rc-when"><?= e($when) ?></span><?php endif; ?>
              </span>
            </div>
            <?php if ($isSent): ?>
              <div class="rc-stats">
                <div class="rc-stat">
                  <div class="rc-stat-n"><?= number_format($del) ?></div>
                  <div class="rc-stat-l">Delivered</div>
                </div>
                <div class="rc-stat">
                  <div class="rc-stat-n"><?= $op ?>%</div>
                  <div class="rc-stat-l">Opened · <?= number_format($opn) ?></div>
                  <div class="rc-bar"><span style="width:<?= $op ?>%;background:#7c3aed"></span></div>
                </div>
                <div class="rc-stat">
                  <div class="rc-stat-n"><?= $cp ?>%</div>
                  <div class="rc-stat-l">Clicked · <?= number_format($clk) ?></div>
                  <div class="rc-bar"><span style="width:<?= $cp ?>%;background:#ea580c"></span></div>
                </div>
                <?php if ($bnc > 0 || $uns > 0): ?>
                  <div class="rc-stat rc-stat-warn">
                    <div class="rc-stat-n"><?= $bnc + $uns ?></div>
                    <div class="rc-stat-l"><?= $bnc ?> bounce · <?= $uns ?> unsub</div>
                  </div>
                <?php endif; ?>
              </div>
            <?php endif; ?>
          </a>
        <?php endforeach; ?>
      </div>
    <?php else: ?>
      <div class="rc-empty">
        <i class="bi bi-megaphone"></i>
        <strong>No campaigns yet</strong>
        <span>Create a draft under Campaigns, pick a live list, and send.</span>
        <a class="btn btn-primary mt-3" href="<?= e(url('campaigns')) ?>">Create campaign</a>
      </div>
    <?php endif; ?>
  </div>
  <?php \App\Core\View::partial('smart_tips', ['tips' => $tips ?? [], 'kind' => 'marketing']); ?>
</div>
