<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
  <div class="d-flex gap-2">
    <div class="ab-search"><i class="bi bi-search"></i><input type="text" id="abUserSearch" placeholder="Search users..."></div>
    <select class="form-select form-select-sm" id="abFilterStatus" style="width:auto;">
      <option value="">All statuses</option>
      <option value="active">Active</option>
      <option value="invited">Invited</option>
      <option value="suspended">Suspended</option>
    </select>
  </div>
  <?php if (\App\Core\Rbac::can('user_management.create')): ?>
  <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#abUserModal" id="abNewUserBtn"><i class="bi bi-person-plus me-1"></i>Invite User</button>
  <?php endif; ?>
</div>

<div class="ab-table-card">
  <div class="table-responsive">
    <table class="table ab-table align-middle" id="abUsersTable">
      <thead><tr><th>User</th><th>Role</th><th>Department</th><th>Business Access</th><th>Status</th><th>Last Active</th><th></th></tr></thead>
      <tbody>
      <?php foreach ($rows as $row): ?>
        <tr data-id="<?= (int) $row['id'] ?>">
          <td><div class="d-flex align-items-center gap-2">
            <div class="ab-mini-avatar"><?= e(mb_strtoupper(mb_substr($row['first_name'],0,1).mb_substr($row['last_name'] ?? '',0,1))) ?></div>
            <div><div class="ab-cell-primary"><?= e($row['first_name'].' '.($row['last_name'] ?? '')) ?></div><div class="ab-cell-sub"><?= e($row['email']) ?></div></div>
          </div></td>
          <td><?= e($row['role_name'] ?? '—') ?></td>
          <td><?= e($row['department_name'] ?? '—') ?></td>
          <td><?= e($row['business_lines'] ?? '—') ?></td>
          <td><span class="ab-badge <?= $row['status']==='active'?'bg-success-soft':($row['status']==='invited'?'bg-secondary-soft':'bg-danger-soft') ?>"><span class="dot"></span><?= e(ucfirst($row['status'])) ?></span></td>
          <td class="ab-cell-sub"><?= $row['last_login_at'] ? e(date('M j, g:i A', strtotime($row['last_login_at']))) : 'Never' ?></td>
          <td>
            <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-user" href="#" data-id="<?= (int) $row['id'] ?>">Edit</a></li>
                <?php if ($row['status'] === 'active'): ?>
                <li><a class="dropdown-item ab-deactivate-user" href="#" data-id="<?= (int) $row['id'] ?>">Deactivate</a></li>
                <?php else: ?>
                <li><a class="dropdown-item ab-reactivate-user" href="#" data-id="<?= (int) $row['id'] ?>">Reactivate</a></li>
                <?php endif; ?>
                <li><a class="dropdown-item ab-reset-password" href="#" data-id="<?= (int) $row['id'] ?>">Reset Password</a></li>
                <li><hr class="dropdown-divider"></li>
                <li><a class="dropdown-item text-danger ab-delete-user" href="#" data-id="<?= (int) $row['id'] ?>">Delete</a></li>
              </ul>
            </div>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <div class="ab-table-pagination">
    <div>Showing <strong><?= (int) $meta['from'] ?>–<?= (int) $meta['to'] ?></strong> of <strong><?= (int) $meta['total'] ?></strong> users</div>
    <?php if ((int) $meta['total_pages'] > 1): ?>
    <nav aria-label="Users pagination">
      <ul class="pagination pagination-sm mb-0">
        <?php
          $currentPage = (int) $meta['page'];
          $lastPage = (int) $meta['total_pages'];
          $pageUrl = function (int $page) {
              $params = $_GET;
              $params['page'] = $page;
              return base_url('users') . '?' . http_build_query($params);
          };
          $pagesToShow = array_unique(array_filter(
              range(max(1, $currentPage - 2), min($lastPage, $currentPage + 2)) + [1, $lastPage],
              fn ($p) => $p >= 1 && $p <= $lastPage
          ));
          sort($pagesToShow);
        ?>
        <li class="page-item <?= !$meta['has_previous'] ? 'disabled' : '' ?>">
          <a class="page-link" href="<?= $meta['has_previous'] ? e($pageUrl($currentPage - 1)) : '#' ?>" aria-label="Previous">&laquo;</a>
        </li>
        <?php $previousPage = 0; foreach ($pagesToShow as $p): ?>
          <?php if ($p - $previousPage > 1): ?>
            <li class="page-item disabled"><span class="page-link">&hellip;</span></li>
          <?php endif; ?>
          <li class="page-item <?= $p === $currentPage ? 'active' : '' ?>">
            <a class="page-link" href="<?= e($pageUrl($p)) ?>"><?= $p ?></a>
          </li>
          <?php $previousPage = $p; ?>
        <?php endforeach; ?>
        <li class="page-item <?= !$meta['has_next'] ? 'disabled' : '' ?>">
          <a class="page-link" href="<?= $meta['has_next'] ? e($pageUrl($currentPage + 1)) : '#' ?>" aria-label="Next">&raquo;</a>
        </li>
      </ul>
    </nav>
    <?php endif; ?>
  </div>
</div>

<!-- User modal (create + edit) -->
<div class="modal fade" id="abUserModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title" id="abUserModalTitle">Invite User</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <form id="abUserForm">
          <input type="hidden" name="id">
          <div class="row g-3">
            <div class="col-md-6"><label class="form-label ab-req">First Name</label><input class="form-control" name="first_name" required></div>
            <div class="col-md-6"><label class="form-label">Last Name</label><input class="form-control" name="last_name"></div>
            <div class="col-md-6"><label class="form-label ab-req">Email</label><input type="email" class="form-control" name="email" required></div>
            <div class="col-md-6"><label class="form-label">Phone</label><input class="form-control" name="phone"></div>
            <div class="col-md-6"><label class="form-label ab-req">Role</label>
              <select class="form-select" name="role_id" required>
                <?php foreach ($roles as $r): ?><option value="<?= (int) $r['id'] ?>"><?= e($r['name']) ?></option><?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6"><label class="form-label">Department</label>
              <select class="form-select" name="department_id">
                <option value="">—</option>
                <?php foreach ($departments as $d): ?><option value="<?= (int) $d['id'] ?>"><?= e($d['name']) ?></option><?php endforeach; ?>
              </select>
            </div>
            <div class="col-12"><label class="form-label">Business Access</label><div class="d-flex gap-2 flex-wrap">
              <?php foreach ($businessLines as $bl): ?>
              <label class="ab-chip"><input type="checkbox" class="form-check-input me-1 abBusinessLineCheck" value="<?= (int) $bl['id'] ?>"><?= e($bl['name']) ?></label>
              <?php endforeach; ?>
            </div></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="abUserSaveBtn">Send Invitation</button>
      </div>
    </div>
  </div>
</div>

<script>
(function () {
  var currentPage = 1;

  function reload(page) {
    page = page || 1;
    currentPage = page;
    var params = new URLSearchParams({
      page: page,
      search: document.getElementById('abUserSearch').value,
      status: document.getElementById('abFilterStatus').value
    });
    window.location.href = '<?= base_url('users') ?>?' + params.toString();
  }

  document.getElementById('abUserSearch').addEventListener('keydown', function (e) { if (e.key === 'Enter') reload(1); });
  document.getElementById('abFilterStatus').addEventListener('change', function () { reload(1); });

  document.getElementById('abNewUserBtn')?.addEventListener('click', function () {
    document.getElementById('abUserForm').reset();
    document.getElementById('abUserForm').id.value = '';
    document.getElementById('abUserModalTitle').textContent = 'Invite User';
    document.getElementById('abUserSaveBtn').textContent = 'Send Invitation';
  });

  document.querySelectorAll('.ab-edit-user').forEach(function (link) {
    link.addEventListener('click', function (e) {
      e.preventDefault();
      var id = this.dataset.id;
      abFetch('<?= base_url('users') ?>/' + id).then(function (res) {
        var u = res.data;
        var form = document.getElementById('abUserForm');
        form.id.value = u.id;
        form.first_name.value = u.first_name;
        form.last_name.value = u.last_name || '';
        form.email.value = u.email;
        form.phone.value = u.phone || '';
        form.role_id.value = u.role_id || '';
        form.department_id.value = u.department_id || '';
        document.querySelectorAll('.abBusinessLineCheck').forEach(function (cb) {
          cb.checked = u.business_line_ids.includes(parseInt(cb.value));
        });
        document.getElementById('abUserModalTitle').textContent = 'Edit User';
        document.getElementById('abUserSaveBtn').textContent = 'Save Changes';
        new bootstrap.Modal(document.getElementById('abUserModal')).show();
      });
    });
  });

  document.getElementById('abUserSaveBtn').addEventListener('click', function () {
    var form = document.getElementById('abUserForm');
    var id = form.id.value;
    var businessLineIds = Array.from(document.querySelectorAll('.abBusinessLineCheck:checked')).map(function (cb) { return parseInt(cb.value); });
    var data = {
      first_name: form.first_name.value, last_name: form.last_name.value, email: form.email.value,
      phone: form.phone.value, role_id: form.role_id.value, department_id: form.department_id.value || null,
      business_line_ids: businessLineIds
    };

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

  document.querySelectorAll('.ab-deactivate-user').forEach(function (link) {
    link.addEventListener('click', function (e) {
      e.preventDefault();
      if (!confirm('Deactivate this user? They will be signed out everywhere immediately.')) return;
      abFetch('<?= base_url('users') ?>/' + this.dataset.id + '/deactivate', { method: 'POST' })
        .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 600); })
        .catch(function (err) { abToast(err.message, 'danger'); });
    });
  });

  document.querySelectorAll('.ab-reactivate-user').forEach(function (link) {
    link.addEventListener('click', function (e) {
      e.preventDefault();
      abFetch('<?= base_url('users') ?>/' + this.dataset.id + '/reactivate', { method: 'POST' })
        .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 600); })
        .catch(function (err) { abToast(err.message, 'danger'); });
    });
  });

  document.querySelectorAll('.ab-reset-password').forEach(function (link) {
    link.addEventListener('click', function (e) {
      e.preventDefault();
      if (!confirm('Send a password reset link to this user?')) return;
      abFetch('<?= base_url('users') ?>/' + this.dataset.id + '/reset-password', { method: 'POST' })
        .then(function (res) { abToast(res.message); })
        .catch(function (err) { abToast(err.message, 'danger'); });
    });
  });

  document.querySelectorAll('.ab-delete-user').forEach(function (link) {
    link.addEventListener('click', function (e) {
      e.preventDefault();
      if (!confirm('Permanently delete this user? This cannot be undone.')) return;
      abFetch('<?= base_url('users') ?>/' + 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>
