<div class="d-flex justify-content-end mb-3">
  <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#abKbModal" id="abNewKbBtn"><i class="bi bi-plus-lg me-1"></i>New Article</button>
</div>

<div class="row g-3">
  <?php foreach ($rows as $a): ?>
  <div class="col-md-6">
    <div class="ab-card h-100">
      <div class="ab-card-body">
        <div class="d-flex justify-content-between align-items-start">
          <h3 class="fs-6"><?= e($a['question']) ?></h3>
          <div class="dropdown">
            <button class="btn btn-icon btn-light-soft btn-sm" data-bs-toggle="dropdown"><i class="bi bi-three-dots"></i></button>
            <ul class="dropdown-menu dropdown-menu-end">
              <li><a class="dropdown-item ab-edit-kb" href="#" data-id="<?= (int) $a['id'] ?>">Edit</a></li>
              <li><a class="dropdown-item text-danger ab-delete-kb" href="#" data-id="<?= (int) $a['id'] ?>">Delete</a></li>
            </ul>
          </div>
        </div>
        <?php if ($a['category']): ?><span class="ab-badge bg-secondary-soft mb-2"><?= e($a['category']) ?></span><?php endif; ?>
        <p class="small mb-1"><?= e($a['answer']) ?></p>
        <div class="ab-cell-sub"><?= (int) $a['view_count'] ?> views</div>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
  <?php if (empty($rows)): ?><div class="col-12"><div class="ab-empty"><i class="bi bi-book"></i><h3>No articles yet</h3></div></div><?php endif; ?>
</div>

<div class="modal fade" id="abKbModal" tabindex="-1"><div class="modal-dialog modal-lg modal-dialog-centered"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title" id="abKbModalTitle">New Article</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
  <div class="modal-body">
    <form id="abKbForm">
      <input type="hidden" name="id">
      <div class="row g-3">
        <div class="col-md-8"><label class="form-label ab-req">Question</label><input class="form-control" name="question" required></div>
        <div class="col-md-4"><label class="form-label">Category</label><input class="form-control" name="category" placeholder="billing, scheduling..."></div>
        <div class="col-md-6"><label class="form-label">Business Line</label><select class="form-select" name="business_line_id"><option value="">Both brands</option><?php foreach ($businessLines as $bl): ?><option value="<?= (int) $bl['id'] ?>"><?= e($bl['name']) ?></option><?php endforeach; ?></select></div>
        <div class="col-12"><label class="form-label ab-req">Answer</label><textarea class="form-control" name="answer" rows="4" required></textarea></div>
      </div>
    </form>
  </div>
  <div class="modal-footer"><button class="btn btn-light-soft" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary" id="abKbSaveBtn">Save</button></div>
</div></div></div>

<script>
document.getElementById('abNewKbBtn').addEventListener('click', function () {
  var form = document.getElementById('abKbForm');
  form.reset(); form.id.value = '';
  document.getElementById('abKbModalTitle').textContent = 'New Article';
});

var kbData = <?= json_encode($rows) ?>;
document.querySelectorAll('.ab-edit-kb').forEach(function (link) {
  link.addEventListener('click', function (e) {
    e.preventDefault();
    var linkId = link.dataset.id;
    var article = kbData.find(function (a) { return String(a.id) === linkId; });
    var form = document.getElementById('abKbForm');
    form.id.value = article.id; form.question.value = article.question; form.category.value = article.category || '';
    form.answer.value = article.answer; form.business_line_id.value = article.business_line_id || '';
    document.getElementById('abKbModalTitle').textContent = 'Edit Article';
    new bootstrap.Modal(document.getElementById('abKbModal')).show();
  });
});

document.getElementById('abKbSaveBtn').addEventListener('click', function () {
  var form = document.getElementById('abKbForm');
  var id = form.id.value;
  var data = Object.fromEntries(new FormData(form).entries());
  var url = id ? '<?= base_url('knowledge-base') ?>/' + id : '<?= base_url('knowledge-base') ?>';

  abFetch(url, { method: id ? 'PATCH' : 'POST', body: data }).then(function (res) {
    abToast(res.message);
    bootstrap.Modal.getInstance(document.getElementById('abKbModal')).hide();
    setTimeout(function () { window.location.reload(); }, 600);
  }).catch(function (err) {
    abShowFormErrors(form, err.errors);
    abToast(err.message || 'Save failed.', 'danger');
  });
});

document.querySelectorAll('.ab-delete-kb').forEach(function (link) {
  link.addEventListener('click', function (e) {
    e.preventDefault();
    if (!confirm('Delete this article?')) return;
    abFetch('<?= base_url('knowledge-base') ?>/' + this.dataset.id, { method: 'DELETE' })
      .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 600); })
      .catch(function (err) { abToast(err.message, 'danger'); });
  });
});
</script>
