<?php
require_once __DIR__ . '/../includes/auth.php';
$pageTitle = 'Keyword Categories';

if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $conn->query("DELETE FROM keyword_categories WHERE id=$id");
    flash('success','Keyword category deleted');
    redirect('index.php');
}

$rows = $conn->query("SELECT kc.*, (SELECT COUNT(*) FROM keywords WHERE keyword_category_id=kc.id) kw_count FROM keyword_categories kc ORDER BY kc.id DESC");
include __DIR__ . '/../includes/header.php';
?>
<div class="d-flex justify-content-between mb-3">
  <h2>Keyword Categories</h2>
  <a href="form.php" class="btn btn-primary"><i class="bi bi-plus-lg"></i> Add Keyword Category</a>
</div>
<div class="card"><div class="card-body p-0">
<table class="table table-hover mb-0">
  <thead class="table-light"><tr><th width="60">ID</th><th>Name</th><th>Description</th><th width="100">Keywords</th><th width="160">Actions</th></tr></thead>
  <tbody>
  <?php while ($r = $rows->fetch_assoc()): ?>
    <tr>
      <td><?= $r['id'] ?></td>
      <td><?= e($r['name']) ?></td>
      <td><?= e(mb_strimwidth($r['description'] ?? '',0,80,'...')) ?></td>
      <td><span class="badge bg-info"><?= $r['kw_count'] ?></span></td>
      <td>
        <a href="form.php?id=<?= $r['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-pencil"></i></a>
        <a href="?delete=<?= $r['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this keyword category and all its keywords?')"><i class="bi bi-trash"></i></a>
      </td>
    </tr>
  <?php endwhile; ?>
  </tbody>
</table>
</div></div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
