<div class="d-flex justify-content-end mb-3">
  <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#abNewKeyModal"><i class="bi bi-plus-lg me-1"></i>Generate API Key</button>
</div>

<div class="ab-table-card">
  <div class="table-responsive">
    <table class="table ab-table align-middle">
      <thead><tr><th>Name</th><th>Prefix</th><th>Scopes</th><th>Last Used</th><th>Created By</th><th>Status</th><th></th></tr></thead>
      <tbody>
      <?php foreach ($rows as $k): ?>
        <?php $scopes = json_decode($k['scopes'] ?? '[]', true) ?: []; ?>
        <tr>
          <td class="ab-cell-primary"><?= e($k['name']) ?></td>
          <td class="ab-mono small"><?= e($k['key_prefix']) ?>&hellip;</td>
          <td><?= $scopes === [] ? '<span class="ab-badge bg-secondary-soft">Full access</span>' : e(implode(', ', $scopes)) ?></td>
          <td class="ab-cell-sub"><?= $k['last_used_at'] ? e(date('M j, Y g:i A', strtotime($k['last_used_at']))) : 'Never' ?></td>
          <td class="ab-cell-sub"><?= e($k['created_by_name'] ?? '—') ?></td>
          <td><span class="ab-badge <?= $k['revoked_at'] ? 'bg-danger-soft' : 'bg-success-soft' ?>"><?= $k['revoked_at'] ? 'Revoked' : 'Active' ?></span></td>
          <td><?php if (!$k['revoked_at']): ?><button class="btn btn-icon btn-light-soft btn-sm ab-revoke-key" data-id="<?= (int) $k['id'] ?>"><i class="bi bi-x-circle text-danger"></i></button><?php endif; ?></td>
        </tr>
      <?php endforeach; ?>
      <?php if (empty($rows)): ?><tr><td colspan="7" class="text-center p-4 ab-text-muted">No API keys yet.</td></tr><?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<div class="modal fade" id="abNewKeyModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title">Generate API Key</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
  <div class="modal-body">
    <form id="abNewKeyForm">
      <div class="mb-3"><label class="form-label ab-req">Name</label><input class="form-control" name="name" placeholder="e.g. Zapier Integration" required></div>
      <div class="mb-0">
        <label class="form-label">Scopes (leave all unchecked for full access)</label>
        <div class="form-check"><input class="form-check-input" type="checkbox" name="scopes[]" value="leads.read" id="scopeLR"><label class="form-check-label" for="scopeLR">leads.read</label></div>
        <div class="form-check"><input class="form-check-input" type="checkbox" name="scopes[]" value="leads.write" id="scopeLW"><label class="form-check-label" for="scopeLW">leads.write</label></div>
        <div class="form-check"><input class="form-check-input" type="checkbox" name="scopes[]" value="customers.read" id="scopeCR"><label class="form-check-label" for="scopeCR">customers.read</label></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="abNewKeySaveBtn">Generate</button></div>
</div></div></div>

<div class="modal fade" id="abKeyRevealModal" tabindex="-1" data-bs-backdrop="static"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title">API Key Generated</h5></div>
  <div class="modal-body">
    <div class="alert alert-warning small"><i class="bi bi-exclamation-triangle me-1"></i>Copy this key now — it will not be shown again.</div>
    <div class="input-group">
      <input type="text" class="form-control ab-mono" id="abRevealedKey" readonly>
      <button class="btn btn-outline-primary" type="button" id="abCopyKeyBtn"><i class="bi bi-clipboard"></i></button>
    </div>
  </div>
  <div class="modal-footer"><button class="btn btn-primary" data-bs-dismiss="modal" onclick="window.location.reload()">Done</button></div>
</div></div></div>

<script>
document.getElementById('abNewKeySaveBtn').addEventListener('click', function () {
  var form = document.getElementById('abNewKeyForm');
  var fd = new FormData(form);
  var scopes = fd.getAll('scopes[]');

  abFetch('<?= base_url('api-keys') ?>', { method: 'POST', body: { name: fd.get('name'), scopes: scopes } })
    .then(function (res) {
      bootstrap.Modal.getInstance(document.getElementById('abNewKeyModal')).hide();
      document.getElementById('abRevealedKey').value = res.data.plaintext_key;
      new bootstrap.Modal(document.getElementById('abKeyRevealModal')).show();
    })
    .catch(function (err) { abShowFormErrors(form, err.errors); abToast(err.message || 'Save failed.', 'danger'); });
});

document.getElementById('abCopyKeyBtn').addEventListener('click', function () {
  var input = document.getElementById('abRevealedKey');
  input.select();
  navigator.clipboard.writeText(input.value).then(function () { abToast('Copied to clipboard.'); });
});

document.querySelectorAll('.ab-revoke-key').forEach(function (btn) {
  btn.addEventListener('click', function () {
    if (!confirm('Revoke this API key? Any integration using it will stop working immediately.')) return;
    abFetch('<?= base_url('api-keys') ?>/' + btn.dataset.id + '/revoke', { method: 'POST' })
      .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 600); })
      .catch(function (err) { abToast(err.message, 'danger'); });
  });
});
</script>
