<?php
require __DIR__ . '/_bootstrap.php';
try {
  $stmt = $pdo->query("SELECT id, full_name, email, created_at FROM admins ORDER BY id DESC");
  $rows = $stmt->fetchAll();
} catch (Throwable $e) {
  http_response_code(500);
  echo "<pre>DB Error: " . htmlspecialchars($e->getMessage()) . "</pre>";
  exit;
}
include __DIR__ . '/_header.php';
?>
<?php
if (empty($_SESSION['csrf_token']) && empty($_SESSION['csrf'])) {
  $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'] ?? $_SESSION['csrf'];
?>
<?php if (!empty($_GET['msg'])): ?>
  <div class="alert" style="margin-bottom:12px;">
    <?php echo htmlspecialchars($_GET['msg'], ENT_QUOTES, 'UTF-8'); ?>
  </div>
<?php endif; ?>


<div class="page-header">
  <h1>Admins</h1>
  <a class="btn btn-primary" href="<?php echo url_for('/admin/admin_add.php'); ?>">+ Add Admin</a>
</div>
<div class="card">
  <table class="data-table">
    <thead><tr><th>ID</th><th>Name</th><th>Email</th><th>Actions</th></tr></thead>
    <tbody>
      <?php foreach ($rows as $a): ?>
        <tr>
          <td><?php echo $a['id']; ?></td>
          <td><?php echo htmlspecialchars($a['full_name']); ?></td>
          <td><?php echo htmlspecialchars($a['email']); ?></td>
          
          <!--<td class="actions">-->
          <!--  <a href="<?php echo url_for('/admin/admin_view.php?id=' . $a['id']); ?>">View</a>-->
          <!--  <a href="<?php echo url_for('/admin/admin_edit.php?id=' . $a['id']); ?>">Edit</a>-->
          <!--</td>-->
          
<td class="actions-cell">
  <a class="chip chip-view" href="admin_view.php?id=<?php echo (int)$a['id']; ?>">View</a>
  <a class="chip chip-edit" href="admin_edit.php?id=<?php echo (int)$a['id']; ?>">Edit</a>
  <button type="button"
          class="chip chip-danger js-delete-admin"
          data-id="<?php echo (int)$a['id']; ?>"
          data-name="<?php echo htmlspecialchars($a['full_name']); ?>">
    Delete
  </button>
</td>



          
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

<div id="confirmModal" class="modal hidden">
  <div class="modal-content card">
    <h3 class="card-title">Confirm Deletion</h3>
    <p id="confirmText">Are you sure?</p>
    <form id="deleteForm" method="post"
          action="<?php echo url_for('/admin/admin_delete_handler.php'); ?>"
          class="actions-bar">
      <input type="hidden" name="id" id="deleteId">
      <input type="hidden" name="csrf" value="<?php echo htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8'); ?>">
      <button type="button" class="btn" id="cancelBtn">Cancel</button>
      <button type="submit" class="btn-primary" style="background:#dc2626;border-color:#dc2626">Delete</button>
    </form>
  </div>
</div>
<script src="/public/js/delete-modal.js" defer></script>


<?php include __DIR__ . '/_footer.php'; ?>
