<?php
$counts = $counts ?? ['new' => 0, 'qualified' => 0, 'unqualified' => 0, 'converted' => 0, 'all' => 0];
$q = $q ?? '';
$status = $status ?? 'new';
$source = $source ?? '';
$sources = $sources ?? [];
$created = $created ?? 'all';
$territoryId = (int) ($territoryId ?? 0);
$territories = $territories ?? [];
$assigned = (int) ($assigned ?? 0);
$showAssigned = (bool) ($showAssigned ?? false);
$owners = $owners ?? [];
$statusLabel = \App\Models\Lead::statusLabels();
$summaries = [
    ['New', (int) $counts['new'], 'bi-sparkles', '#2563eb', '#eff6ff'],
    ['Qualified', (int) $counts['qualified'], 'bi-star-fill', '#16a34a', '#f0fdf4'],
    ['Not a fit', (int) $counts['unqualified'], 'bi-x-circle-fill', '#dc2626', '#fef2f2'],
    ['Converted', (int) $counts['converted'], 'bi-arrow-left-right', '#0f766e', '#f0fdfa'],
];
?>
<div class="lead-page">
  <div class="mb-3">
    <h1 class="page-title"><?= e(noun('leads', 'Leads')) ?></h1>
    <p class="page-sub mb-0"><?= (int) $total ?> in this view · open a card to qualify or convert</p>
  </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 opp-filters card-soft p-3 mb-3" method="get">
    <div class="task-filter-search">
      <label class="form-label" for="lead-q">Search</label>
      <input class="form-control" id="lead-q" name="q" value="<?= e($q) ?>" placeholder="Search name, company, email" autocomplete="off">
    </div>
    <?php if ($showAssigned): ?>
    <div>
      <label class="form-label" for="lead-assigned">Assigned to</label>
      <select class="form-select" id="lead-assigned" name="assigned">
        <option value="0" <?= $assigned === 0 ? 'selected' : '' ?>>All</option>
        <option value="-1" <?= $assigned === -1 ? 'selected' : '' ?>>Unassigned</option>
        <?php foreach ($owners as $o): ?>
          <option value="<?= (int) $o['id'] ?>" <?= $assigned === (int) $o['id'] ? 'selected' : '' ?>><?= e(trim($o['first_name'] . ' ' . $o['last_name'])) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <?php endif; ?>
    <div>
      <label class="form-label" for="lead-territory">Territory</label>
      <select class="form-select" id="lead-territory" name="territory">
        <option value="0" <?= $territoryId === 0 ? 'selected' : '' ?>>All</option>
        <?php foreach ($territories as $t): ?>
          <option value="<?= (int) $t['id'] ?>" <?= $territoryId === (int) $t['id'] ? 'selected' : '' ?>><?= e($t['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div>
      <label class="form-label" for="lead-source">Source</label>
      <select class="form-select" id="lead-source" name="source">
        <option value="" <?= $source === '' ? 'selected' : '' ?>>All</option>
        <?php foreach ($sources as $src): ?>
          <option value="<?= e($src) ?>" <?= $source === $src ? 'selected' : '' ?>><?= e($src) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div>
      <label class="form-label" for="lead-created">Created</label>
      <select class="form-select" id="lead-created" name="created">
        <option value="all" <?= $created === 'all' ? 'selected' : '' ?>>All</option>
        <option value="today" <?= $created === 'today' ? 'selected' : '' ?>>Today</option>
        <option value="week" <?= $created === 'week' ? 'selected' : '' ?>>This week</option>
        <option value="month" <?= $created === 'month' ? 'selected' : '' ?>>This month</option>
        <option value="last_week" <?= $created === 'last_week' ? 'selected' : '' ?>>Last week</option>
        <option value="last_month" <?= $created === 'last_month' ? 'selected' : '' ?>>Last month</option>
      </select>
    </div>
    <div>
      <label class="form-label" for="lead-status">Status</label>
      <select class="form-select" id="lead-status" name="status">
        <option value="all" <?= $status === 'all' ? 'selected' : '' ?>>All</option>
        <?php foreach ($statusLabel as $k => $lab): ?>
          <option value="<?= e($k) ?>" <?= $status === $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 (!$rows): ?>
    <div class="card-soft task-empty">
      <div class="task-empty-icon"><i class="bi bi-person-plus"></i></div>
      <h2>No leads here</h2>
      <p>Use <strong>Add New → Lead</strong> to create one in under a minute.</p>
    </div>
  <?php else: ?>
    <?php foreach ($rows as $r):
      $st = (string) ($r['status'] ?? 'new');
      $name = trim($r['first_name'] . ' ' . $r['last_name']);
      $owner = trim((string) ($r['owner_name'] ?? ''));
      $company = trim((string) ($r['company'] ?? ''));
      $leadSource = trim((string) ($r['source'] ?? ''));
      $territory = trim((string) ($r['territory_name'] ?? ''));
    ?>
      <a class="lead-card lead-tone-<?= e($st) ?>" href="<?= e(url('leads/' . $r['id'])) ?>">
        <div class="lead-avatar"><?= e(name_initials($name)) ?></div>
        <div class="flex-grow-1 min-w-0">
          <div class="lead-name"><?= e($name !== '' ? $name : 'Untitled lead') ?></div>
          <div class="lead-sub">
            <?php if ($company !== ''): ?><span><?= e($company) ?></span><?php endif; ?>
            <?php if ($leadSource !== ''): ?><span class="lead-source"><?= e($leadSource) ?></span><?php endif; ?>
            <?php if ($territory !== ''): ?><span><?= e($territory) ?></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 else: ?>
            <span class="task-owner text-truncate">Unassigned</span>
          <?php endif; ?>
          <span class="lead-status lead-status-<?= e($st) ?>"><?= e($statusLabel[$st] ?? $st) ?></span>
          <span class="lead-date"><?= e(dt_fmt($r['created_at'], 'M j')) ?></span>
        </div>
      </a>
    <?php endforeach; ?>
  <?php endif; ?>

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