<div class="row justify-content-center">
  <div class="col-lg-7">
    <div class="ab-card">
      <div class="ab-card-header"><h2>Import Leads from CSV</h2><a href="<?= base_url('leads') ?>" class="small fw-semibold">Back to Leads</a></div>
      <div class="ab-card-body">
        <p class="ab-cell-sub">The file must include <code>first_name</code> and <code>email</code> columns. Optional columns: <code>last_name</code>, <code>phone</code>, <code>estimated_value</code>, <code>notes</code>. Rows matching an existing lead's email or phone are skipped automatically.</p>

        <form id="abImportForm">
          <div class="mb-3">
            <label class="form-label ab-req">Business Line</label>
            <select class="form-select" name="business_line_id" required>
              <?php foreach ($lookups['business_lines'] as $bl): ?><option value="<?= (int) $bl['id'] ?>"><?= e($bl['name']) ?></option><?php endforeach; ?>
            </select>
          </div>
          <div class="mb-3">
            <label class="form-label ab-req">CSV File</label>
            <input type="file" class="form-control" name="file" accept=".csv" required>
          </div>
          <button type="submit" class="btn btn-primary" id="abImportBtn"><i class="bi bi-upload me-1"></i>Import</button>
        </form>

        <div id="abImportResult" class="mt-4 d-none">
          <div class="alert alert-success" id="abImportSummary"></div>
          <div id="abImportErrors"></div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
document.getElementById('abImportForm').addEventListener('submit', function (e) {
  e.preventDefault();
  var btn = document.getElementById('abImportBtn');
  btn.disabled = true; btn.textContent = 'Importing…';

  var fd = new FormData(e.target);
  abFetch('<?= base_url('leads/import') ?>', { method: 'POST', body: fd }).then(function (res) {
    var box = document.getElementById('abImportResult');
    box.classList.remove('d-none');
    document.getElementById('abImportSummary').textContent = res.message;

    if (res.data.errors && res.data.errors.length) {
      document.getElementById('abImportErrors').innerHTML = '<div class="ab-table-card"><table class="table ab-table"><thead><tr><th>Row</th><th>Issue</th></tr></thead><tbody>' +
        res.data.errors.map(function (er) { return '<tr><td>' + er.row + '</td><td>' + er.message + '</td></tr>'; }).join('') +
        '</tbody></table></div>';
    }
  }).catch(function (err) {
    abToast(err.message || 'Import failed.', 'danger');
  }).finally(function () {
    btn.disabled = false; btn.innerHTML = '<i class="bi bi-upload me-1"></i>Import';
  });
});
</script>
