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

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

$filter = (int)($_GET['kc'] ?? 0);
$where = $filter ? "WHERE k.keyword_category_id=$filter" : '';
$rows = $conn->query("SELECT k.*, kc.name kc_name FROM keywords k JOIN keyword_categories kc ON kc.id=k.keyword_category_id $where ORDER BY k.id DESC");
$kcats = $conn->query("SELECT id, name FROM keyword_categories ORDER BY name");

include __DIR__ . '/../includes/header.php';
?>
<div class="d-flex justify-content-between mb-3">
  <h2>Keywords</h2>
  <a href="form.php" class="btn btn-primary"><i class="bi bi-plus-lg"></i> Add Keyword</a>
</div>

<form class="mb-3"><div class="row g-2">
  <div class="col-md-4"><select name="kc" class="form-select" onchange="this.form.submit()">
    <option value="">All Keyword Categories</option>
    <?php while ($k = $kcats->fetch_assoc()): ?>
    <option value="<?= $k['id'] ?>" <?= $filter==$k['id']?'selected':'' ?>><?= e($k['name']) ?></option>
    <?php endwhile; ?>
  </select></div>
</div></form>

<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>Keyword</th><th>Category</th><th width="160">Actions</th></tr></thead>
  <tbody>
  <?php while ($r = $rows->fetch_assoc()): ?>
    <tr>
      <td><?= $r['id'] ?></td>
      <td><?= e($r['keyword']) ?></td>
      <td><span class="badge bg-secondary"><?= e($r['kc_name']) ?></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?')"><i class="bi bi-trash"></i></a>
      </td>
    </tr>
  <?php endwhile; ?>
  </tbody>
</table>
</div></div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
