<div class="row g-3 mb-4" id="abRoleCards">
  <?php foreach ($roles as $role): ?>
  <div class="col-md-3">
    <div class="ab-card text-center p-3">
      <div class="ab-stat-icon bg-primary-soft ab-badge mx-auto"><i class="bi bi-shield-fill-check text-primary"></i></div>
      <h3 class="fs-6 mt-2 mb-0"><?= e($role['name']) ?></h3><div class="ab-cell-sub"><?= (int) $role['user_count'] ?> users</div>
      <?php if (!$role['is_system']): ?>
      <div class="mt-2 d-flex gap-1 justify-content-center">
        <button class="btn btn-icon btn-light-soft btn-sm ab-edit-role" data-id="<?= (int) $role['id'] ?>" data-name="<?= e($role['name']) ?>" data-description="<?= e($role['description'] ?? '') ?>"><i class="bi bi-pencil"></i></button>
        <button class="btn btn-icon btn-light-soft btn-sm ab-delete-role" data-id="<?= (int) $role['id'] ?>"><i class="bi bi-trash text-danger"></i></button>
      </div>
      <?php endif; ?>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<div class="ab-card">
  <div class="ab-card-header"><h2>Permission Matrix</h2>
    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#abRoleModal" id="abNewRoleBtn"><i class="bi bi-plus-lg me-1"></i>New Role</button>
  </div>
  <div class="table-responsive">
    <table class="table ab-table align-middle" id="abMatrixTable">
      <thead><tr><th>Module</th></tr></thead>
      <tbody><tr><td class="text-center p-4 ab-text-muted">Loading matrix…</td></tr></tbody>
    </table>
  </div>
  <div class="ab-table-pagination justify-content-end">
    <button class="btn btn-primary btn-sm" id="abSaveMatrixBtn">Save Changes</button>
  </div>
</div>

<div class="modal fade" id="abRoleModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title" id="abRoleModalTitle">New Role</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <form id="abRoleForm">
          <input type="hidden" name="id">
          <div class="mb-3"><label class="form-label ab-req">Role Name</label><input class="form-control" name="name" required></div>
          <div class="mb-0"><label class="form-label">Description</label><textarea class="form-control" name="description" rows="2"></textarea></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="abRoleSaveBtn">Save Role</button></div>
    </div>
  </div>
</div>

<script>
(function () {
  var matrixData = null;

  function renderMatrix(matrix) {
    matrixData = matrix;
    var thead = document.querySelector('#abMatrixTable thead tr');
    thead.innerHTML = '<th>Module</th>' + matrix.roles.map(function (r) {
      return '<th class="text-center">' + r.name + '</th>';
    }).join('');

    var tbody = document.querySelector('#abMatrixTable tbody');
    tbody.innerHTML = '';

    Object.keys(matrix.modules).forEach(function (moduleSlug) {
      var mod = matrix.modules[moduleSlug];
      var manageSlug = moduleSlug + '.manage';
      var manageIdx = mod.slugs.indexOf(manageSlug);
      var managePermId = null; // resolved below via lookup table

      var row = document.createElement('tr');
      var label = moduleSlug.replace(/_/g, ' ').replace(/\b\w/g, function (c) { return c.toUpperCase(); });
      var cellsHtml = '<td class="ab-cell-primary">' + label + '</td>';

      matrix.roles.forEach(function (role) {
        var grants = matrix.grants[role.id] || {};
        var checked = grants[manageSlug] ? 'checked' : '';
        var disabled = role.slug === 'operations_admin' ? 'disabled' : ''; // Operations Admin always has full access
        cellsHtml += '<td class="text-center"><input type="checkbox" class="form-check-input ab-matrix-check" ' +
          'data-role-id="' + role.id + '" data-module="' + moduleSlug + '" ' + checked + ' ' + disabled + '></td>';
      });

      row.innerHTML = cellsHtml;
      tbody.appendChild(row);
    });
  }

  function loadMatrix() {
    abFetch('<?= base_url('api/v1/permissions/matrix') ?>').then(function (res) { renderMatrix(res.data); });
  }
  loadMatrix();

  document.getElementById('abSaveMatrixBtn').addEventListener('click', function () {
    if (!matrixData) return;

    // Build a permission-slug lookup: module -> all action slugs.
    var byRole = {};
    document.querySelectorAll('.ab-matrix-check').forEach(function (cb) {
      var roleId = cb.dataset.roleId;
      var moduleSlug = cb.dataset.module;
      byRole[roleId] = byRole[roleId] || {};
      byRole[roleId][moduleSlug] = cb.checked;
    });

    // For each role, compute a full permission slug list: checked module -> ALL actions in that module; unchecked -> none.
    // (Matches the frontend's single-checkbox-per-module-per-role UX from Phase 1.)
    var requests = Object.keys(byRole).map(function (roleId) {
      var permissionIds = [];
      Object.keys(byRole[roleId]).forEach(function (moduleSlug) {
        if (!byRole[roleId][moduleSlug]) return;
        var mod = matrixData.modules[moduleSlug];
        mod.slugs.forEach(function (slug, i) {
          var id = matrixData.permission_ids ? matrixData.permission_ids[slug] : null;
          if (id) permissionIds.push(id);
        });
      });
      return abFetch('<?= base_url('roles') ?>/' + roleId + '/permissions', { method: 'PUT', body: { permission_ids: permissionIds } });
    });

    Promise.all(requests).then(function () { abToast('Permissions saved.'); loadMatrix(); })
      .catch(function (err) { abToast(err.message || 'Save failed.', 'danger'); });
  });

  // ---- Role CRUD ----
  document.getElementById('abNewRoleBtn').addEventListener('click', function () {
    document.getElementById('abRoleForm').reset();
    document.getElementById('abRoleForm').id.value = '';
    document.getElementById('abRoleModalTitle').textContent = 'New Role';
  });

  document.querySelectorAll('.ab-edit-role').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var form = document.getElementById('abRoleForm');
      form.id.value = this.dataset.id;
      form.name.value = this.dataset.name;
      form.description.value = this.dataset.description;
      document.getElementById('abRoleModalTitle').textContent = 'Edit Role';
      new bootstrap.Modal(document.getElementById('abRoleModal')).show();
    });
  });

  document.getElementById('abRoleSaveBtn').addEventListener('click', function () {
    var form = document.getElementById('abRoleForm');
    var id = form.id.value;
    var data = { name: form.name.value, description: form.description.value };
    var url = id ? '<?= base_url('roles') ?>/' + id : '<?= base_url('roles') ?>';

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

  document.querySelectorAll('.ab-delete-role').forEach(function (btn) {
    btn.addEventListener('click', function () {
      if (!confirm('Delete this role? Only possible if no users hold it.')) return;
      abFetch('<?= base_url('roles') ?>/' + 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>
