<div class="d-flex justify-content-end mb-3">
  <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#abSourceModal">New Lead Source</button>
</div>

<div class="ab-table-card">
  <div class="table-responsive">
    <table class="table ab-table">
      <thead><tr><th>Name</th><th>Leads Generated</th><th>Status</th><th></th></tr></thead>
      <tbody>
      <?php foreach ($rows as $s): ?>
        <tr>
          <td class="ab-cell-primary"><?= e($s['name']) ?></td>
          <td><?= (int) $s['lead_count'] ?></td>
          <td><span class="ab-badge <?= $s['is_active'] ? 'bg-success-soft' : 'bg-danger-soft' ?>"><?= $s['is_active'] ? 'Active' : 'Inactive' ?></span></td>
          <td><button class="btn btn-icon btn-light-soft btn-sm ab-deactivate-source" data-id="<?= (int) $s['id'] ?>"><i class="bi bi-trash text-danger"></i></button></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<div class="modal fade" id="abSourceModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title">New Lead Source</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
  <div class="modal-body"><form id="abSourceForm"><label class="form-label ab-req">Name</label><input class="form-control" name="name" required></form></div>
  <div class="modal-footer"><button class="btn btn-light-soft" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary" id="abSourceSaveBtn">Create</button></div>
</div></div></div>

<script>
document.getElementById('abSourceSaveBtn').addEventListener('click', function () {
  var form = document.getElementById('abSourceForm');
  abFetch('<?= base_url('lead-sources') ?>', { method: 'POST', body: Object.fromEntries(new FormData(form).entries()) })
    .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 500); })
    .catch(function (err) { abShowFormErrors(form, err.errors); abToast(err.message, 'danger'); });
});
document.querySelectorAll('.ab-deactivate-source').forEach(function (btn) {
  btn.addEventListener('click', function () {
    if (!confirm('Deactivate this lead source?')) return;
    abFetch('<?= base_url('lead-sources') ?>/' + this.dataset.id, { method: 'DELETE' }).then(function () { window.location.reload(); });
  });
});
</script>
