<?php
$counts = $counts ?? ['all' => 0, 'sent' => 0, 'logged' => 0, 'failed' => 0, 'in' => 0, 'month' => 0];
$q = $q ?? '';
$status = $status ?? 'all';
$filterUrl = static function (string $st) use ($q): string {
    $qs = ['status' => $st];
    if ($q !== '') {
        $qs['q'] = $q;
    }
    return url('emails') . '?' . http_build_query($qs);
};
$filters = [
    ['all', 'All', (int) $counts['all']],
    ['sent', 'Sent', (int) $counts['sent']],
    ['logged', 'Logged', (int) $counts['logged']],
    ['in', 'Received', (int) $counts['in']],
    ['failed', 'Failed', (int) $counts['failed']],
];
$summaries = [
    ['This month', (int) $counts['month'], 'bi-calendar-event-fill', '#2563eb', '#eff6ff', 'all'],
    ['Sent', (int) $counts['sent'], 'bi-send-fill', '#16a34a', '#f0fdf4', 'sent'],
    ['Logged', (int) $counts['logged'], 'bi-journal-text', '#7c3aed', '#f3e8ff', 'logged'],
    ['Received', (int) $counts['in'], 'bi-inbox-fill', '#ea580c', '#fff7ed', 'in'],
];
$statusLabel = ['sent' => 'Sent', 'logged' => 'Logged', 'failed' => 'Failed'];
?>
<div class="email-page">
  <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-3">
    <div>
      <h1 class="page-title">Personal email</h1>
      <p class="page-sub mb-0"><?= (int) $total ?> in this view · one-to-one mail saved on customers and deals</p>
    </div>
    <form class="task-search" method="get">
      <input type="hidden" name="status" value="<?= e($status) ?>">
      <i class="bi bi-search"></i>
      <input class="form-control" name="q" value="<?= e($q) ?>" placeholder="Search subject, to, from">
    </form>
  </div>

  <div class="task-summary mb-3">
    <?php foreach ($summaries as $s): ?>
      <a class="task-summary-card <?= $status === $s[5] ? 'is-active' : '' ?>" href="<?= e($filterUrl($s[5])) ?>" style="--task-accent: <?= e($s[3]) ?>; --task-tint: <?= e($s[4]) ?>">
        <div class="task-summary-icon"><i class="bi <?= e($s[2]) ?>"></i></div>
        <div>
          <div class="task-summary-n"><?= (int) $s[1] ?></div>
          <div class="task-summary-l"><?= e($s[0]) ?></div>
        </div>
      </a>
    <?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 (!$rows): ?>
    <div class="card-soft task-empty">
      <div class="task-empty-icon"><i class="bi bi-envelope"></i></div>
      <h2>No emails here</h2>
      <p>Use <strong>Add New → Email</strong> to log a one-to-one message. Connect Outlook or Gmail in Settings.</p>
    </div>
  <?php else: ?>
    <?php foreach ($rows as $r):
      $st = (string) ($r['status'] ?? 'logged');
      $dir = (string) ($r['direction'] ?? 'out');
      $tone = $st === 'failed' ? 'failed' : ($dir === 'in' ? 'in' : $st);
      $owner = trim((string) ($r['owner_name'] ?? ''));
      $related = trim((string) ($r['related_name'] ?? ''));
      $relUrl = related_url($r['related_type'] ?? null, (int) ($r['related_id'] ?? 0));
      $provider = strtolower(trim((string) ($r['provider'] ?? '')));
      $rawBody = strip_tags((string) ($r['body'] ?? ''));
      $preview = trim((string) preg_replace('/\s+/', ' ', $rawBody));
      $who = $dir === 'in'
          ? ('From ' . ($r['from_email'] ?: $r['to_email'] ?: '—'))
          : ('To ' . ($r['to_email'] ?: '—'));
      $icon = $dir === 'in' ? 'bi-envelope-arrow-down' : ($st === 'sent' ? 'bi-send' : 'bi-envelope');
    ?>
      <div class="email-card email-tone-<?= e($tone) ?>">
        <div class="email-icon"><i class="bi <?= e($icon) ?>"></i></div>
        <div class="flex-grow-1 min-w-0">
          <div class="lead-name"><?= e($r['subject'] ?: '(No subject)') ?></div>
          <div class="lead-sub">
            <span><?= e($who) ?></span>
            <?php if ($related !== '' && $relUrl !== '#'): ?>
              <a href="<?= e($relUrl) ?>"><?= e($related) ?></a>
            <?php elseif ($related !== ''): ?>
              <span><?= e($related) ?></span>
            <?php endif; ?>
            <?php if ($provider !== ''): ?><span class="lead-source"><?= e(ucfirst($provider)) ?></span><?php endif; ?>
          </div>
          <?php if ($preview !== ''): ?>
            <div class="email-preview"><?= e(mb_substr($preview, 0, 140)) ?><?= mb_strlen($preview) > 140 ? '…' : '' ?></div>
          <?php endif; ?>
        </div>
        <div class="task-meta">
          <?php if ($owner !== ''): ?>
            <span class="task-owner-chip" title="<?= e($owner) ?>">
              <span class="task-avatar"><?= e(name_initials($owner)) ?></span>
              <span class="task-owner text-truncate"><?= e($owner) ?></span>
            </span>
          <?php endif; ?>
          <span class="lead-status email-status-<?= e($st) ?>"><?= e($statusLabel[$st] ?? $st) ?></span>
          <span class="lead-date"><?= e(dt_fmt($r['sent_at'], 'M j, g:i A')) ?></span>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>

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