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

<div class="row g-3" id="abDeptCards">
  <?php foreach ($departments as $d): ?>
  <div class="col-md-4">
    <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($d['name']) ?></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-dept" href="#" data-id="<?= (int) $d['id'] ?>" data-name="<?= e($d['name']) ?>" data-description="<?= e($d['description'] ?? '') ?>" data-bl="<?= (int) ($d['business_line_id'] ?? 0) ?>">Edit</a></li>
              <li><a class="dropdown-item text-danger ab-delete-dept" href="#" data-id="<?= (int) $d['id'] ?>">Delete</a></li>
            </ul>
          </div>
        </div>
        <p class="ab-cell-sub"><?= e($d['description'] ?? 'No description') ?></p>
        <div class="d-flex gap-3 small ab-text-muted">
          <span><i class="bi bi-people me-1"></i><?= (int) $d['user_count'] ?> people</span>
          <span><i class="bi bi-diagram-2 me-1"></i><?= (int) $d['team_count'] ?> teams</span>
        </div>
        <?php if ($d['business_line_name']): ?><span class="ab-badge bg-primary-soft mt-2"><?= e($d['business_line_name']) ?></span><?php endif; ?>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
  <?php if (empty($departments)): ?>
  <div class="col-12"><div class="ab-empty"><i class="bi bi-diagram-3"></i><h3>No departments yet</h3></div></div>
  <?php endif; ?>
</div>

<div class="modal fade" id="abDeptModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title" id="abDeptModalTitle">New Department</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <form id="abDeptForm">
          <input type="hidden" name="id">
          <div class="mb-3"><label class="form-label ab-req">Name</label><input class="form-control" name="name" required></div>
          <div class="mb-3"><label class="form-label">Description</label><textarea class="form-control" name="description" rows="2"></textarea></div>
          <div class="mb-0"><label class="form-label">Business Line</label>
            <select class="form-select" name="business_line_id"><option value="">Spans both brands</option></select>
          </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="abDeptSaveBtn">Save</button></div>
    </div>
  </div>
</div>

<script>
(function () {
  document.getElementById('abNewDeptBtn').addEventListener('click', function () {
    var form = document.getElementById('abDeptForm');
    form.reset(); form.id.value = '';
    document.getElementById('abDeptModalTitle').textContent = 'New Department';
  });

  document.querySelectorAll('.ab-edit-dept').forEach(function (link) {
    link.addEventListener('click', function (e) {
      e.preventDefault();
      var form = document.getElementById('abDeptForm');
      form.id.value = this.dataset.id;
      form.name.value = this.dataset.name;
      form.description.value = this.dataset.description;
      form.business_line_id.value = this.dataset.bl || '';
      document.getElementById('abDeptModalTitle').textContent = 'Edit Department';
      new bootstrap.Modal(document.getElementById('abDeptModal')).show();
    });
  });

  document.getElementById('abDeptSaveBtn').addEventListener('click', function () {
    var form = document.getElementById('abDeptForm');
    var id = form.id.value;
    var data = { name: form.name.value, description: form.description.value, business_line_id: form.business_line_id.value || null };
    var url = id ? '<?= base_url('departments') ?>/' + id : '<?= base_url('departments') ?>';

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

  document.querySelectorAll('.ab-delete-dept').forEach(function (link) {
    link.addEventListener('click', function (e) {
      e.preventDefault();
      if (!confirm('Delete this department?')) return;
      abFetch('<?= base_url('departments') ?>/' + 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>
