<?php
$counts = $counts ?? ['all' => 0, 'primary' => 0, 'email' => 0, 'bounced' => 0];
$q = $q ?? '';
$type = $type ?? 'all';
$accounts = $accounts ?? [];
$summaries = [
    ['People', (int) $counts['all'], 'bi-people-fill', '#2563eb', '#eff6ff'],
    ['Primary', (int) $counts['primary'], 'bi-star-fill', '#f59e0b', '#fffbeb'],
    ['Has email', (int) $counts['email'], 'bi-envelope-fill', '#16a34a', '#f0fdf4'],
    ['Bounced', (int) $counts['bounced'], 'bi-exclamation-triangle-fill', '#dc2626', '#fef2f2'],
];
$types = [
    'all' => 'All',
    'primary' => 'Primary',
    'email' => 'As email',
    'bounced' => 'Bounced',
];
?>
<div class="contact-page">
  <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-3">
    <div>
      <h1 class="page-title"><?= e(noun('contacts', 'Contacts')) ?></h1>
      <p class="page-sub mb-0"><?= (int) $total ?> in this view · open a card for the person and account</p>
    </div>
    <?php if (can_edit('contacts')): ?>
      <button class="btn btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#contactAddModal">
        <i class="bi bi-plus-lg"></i> Add
      </button>
    <?php endif; ?>
  </div>

  <div class="task-summary mb-3">
    <?php foreach ($summaries as $s): ?>
      <div class="task-summary-card" 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>
      </div>
    <?php endforeach; ?>
  </div>

  <form class="task-filters is-compact card-soft p-3 mb-3" method="get">
    <div class="task-filter-search">
      <label class="form-label" for="contact-q">Search</label>
      <input class="form-control" id="contact-q" name="q" value="<?= e($q) ?>" placeholder="Search name, email, account" autocomplete="off">
    </div>
    <div>
      <label class="form-label" for="contact-type">Type</label>
      <select class="form-select" id="contact-type" name="type">
        <?php foreach ($types as $k => $lab): ?>
          <option value="<?= e($k) ?>" <?= $type === $k ? 'selected' : '' ?>><?= e($lab) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="task-filter-go">
      <button class="btn btn-primary" type="submit"><i class="bi bi-search"></i> Search</button>
    </div>
  </form>

  <?php if (can_edit('contacts')): ?>
  <div class="modal fade" id="contactAddModal" tabindex="-1" aria-labelledby="contactAddTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered qa-dialog">
      <div class="modal-content qa-modal">
        <div class="qa-head">
          <div class="qa-head-icon"><i class="bi bi-person-plus"></i></div>
          <div class="min-w-0 flex-grow-1">
            <h5 class="modal-title" id="contactAddTitle">Add a contact</h5>
            <p class="qa-head-sub mb-0">A person at an account.</p>
          </div>
          <button class="btn-close btn-close-white" type="button" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body qa-body">
          <form class="ajax-form" action="<?= e(url('contacts')) ?>" method="post">
            <?= csrf_field() ?>
            <div class="qa-fields">
              <div class="qa-field">
                <label class="form-label" for="contact-add-first">First name *</label>
                <input class="form-control" id="contact-add-first" name="first_name" required maxlength="80" placeholder="First" autofocus>
              </div>
              <div class="qa-field">
                <label class="form-label" for="contact-add-last">Last name *</label>
                <input class="form-control" id="contact-add-last" name="last_name" required maxlength="80" placeholder="Last">
              </div>
              <div class="qa-field">
                <label class="form-label" for="contact-add-account">Account *</label>
                <select class="form-select" id="contact-add-account" name="account_id" required>
                  <option value="">Select</option>
                  <?php foreach ($accounts as $a): ?>
                    <option value="<?= (int) $a['id'] ?>"><?= e($a['name']) ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="qa-field">
                <label class="form-label" for="contact-add-email">Email</label>
                <input class="form-control" id="contact-add-email" name="email" type="email" placeholder="name@company.com">
              </div>
              <div class="qa-field">
                <label class="form-label" for="contact-add-phone">Phone</label>
                <input class="form-control" id="contact-add-phone" name="phone" placeholder="555-0000">
              </div>
            </div>
            <button class="btn btn-primary qa-submit" type="submit"><i class="bi bi-person-plus"></i> Create contact</button>
          </form>
        </div>
      </div>
    </div>
  </div>
  <?php endif; ?>

  <?php if (!$rows): ?>
    <div class="card-soft task-empty">
      <div class="task-empty-icon"><i class="bi bi-people"></i></div>
      <h2>No contacts here</h2>
      <p>Click <strong>Add</strong> to create a person, or open this page after you add an account.</p>
    </div>
  <?php else: ?>
    <?php foreach ($rows as $r):
      $name = trim($r['first_name'] . ' ' . $r['last_name']);
      $owner = trim((string) ($r['owner_name'] ?? ''));
      $role = trim((string) ($r['role_label'] ?: $r['title'] ?: ''));
      $primary = (int) ($r['is_primary'] ?? 0) === 1;
      $bounced = ($r['email_status'] ?? 'ok') === 'bounced';
      $tone = $bounced ? 'bounced' : ($primary ? 'primary' : 'ok');
    ?>
      <a class="contact-card contact-tone-<?= e($tone) ?>" href="<?= e(url('contacts/' . $r['id'])) ?>">
        <div class="contact-avatar"><?= e(name_initials($name)) ?></div>
        <div class="flex-grow-1 min-w-0">
          <div class="lead-name">
            <?= e($name !== '' ? $name : 'Untitled') ?>
            <?php if ($primary): ?><span class="contact-primary">Primary</span><?php endif; ?>
          </div>
          <div class="lead-sub">
            <?php if (!empty($r['account_name'])): ?><span><?= e($r['account_name']) ?></span><?php endif; ?>
            <?php if ($role !== ''): ?><span class="lead-source"><?= e($role) ?></span><?php endif; ?>
          </div>
          <div class="lead-contact">
            <?php if (!empty($r['email'])): ?><span><i class="bi bi-envelope"></i> <?= e($r['email']) ?></span><?php endif; ?>
            <?php if (!empty($r['phone'])): ?><span><i class="bi bi-telephone"></i> <?= e($r['phone']) ?></span><?php endif; ?>
          </div>
        </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; ?>
          <?php if ($bounced): ?>
            <span class="lead-status contact-status-bounced">Bounced</span>
          <?php elseif (!empty($r['email'])): ?>
            <span class="lead-status contact-status-ok">Email OK</span>
          <?php else: ?>
            <span class="lead-status contact-status-none">No email</span>
          <?php endif; ?>
        </div>
      </a>
    <?php endforeach; ?>
  <?php endif; ?>

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