<?php
require_once __DIR__ . '/../includes/auth.php';

$id = (int)($_GET['id'] ?? 0);
$row = ['id'=>0,'keyword_category_id'=>0,'keyword'=>''];

if ($id) {
    $row = $conn->query("SELECT * FROM keywords WHERE id=$id")->fetch_assoc() ?: $row;
}
$pageTitle = $id ? 'Edit Keyword' : 'Add Keyword';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $kc_id = (int)$_POST['keyword_category_id'];
    // Allow multiple comma-separated keywords for quick entry on add
    $keywords_input = trim($_POST['keyword']);

    if ($id) {
        $stmt = $conn->prepare("UPDATE keywords SET keyword_category_id=?, keyword=? WHERE id=?");
        $stmt->bind_param('isi', $kc_id, $keywords_input, $id);
        $stmt->execute();
        flash('success','Keyword updated');
    } else {
        $list = array_filter(array_map('trim', explode(',', $keywords_input)));
        foreach ($list as $kw) {
            $stmt = $conn->prepare("INSERT INTO keywords (keyword_category_id, keyword) VALUES (?,?)");
            $stmt->bind_param('is', $kc_id, $kw);
            $stmt->execute();
        }
        flash('success', count($list) . ' keyword(s) added');
    }
    redirect('index.php');
}

$kcats = $conn->query("SELECT id, name FROM keyword_categories ORDER BY name");
include __DIR__ . '/../includes/header.php';
?>
<h2 class="mb-3"><?= $pageTitle ?></h2>
<div class="card"><div class="card-body">
<form method="post">
  <div class="mb-3">
    <label class="form-label">Keyword Category *</label>
    <select name="keyword_category_id" class="form-select" required>
      <option value="">-- Select --</option>
      <?php while ($k = $kcats->fetch_assoc()): ?>
      <option value="<?= $k['id'] ?>" <?= $row['keyword_category_id']==$k['id']?'selected':'' ?>><?= e($k['name']) ?></option>
      <?php endwhile; ?>
    </select>
  </div>
  <div class="mb-3">
    <label class="form-label">Keyword *</label>
    <input type="text" name="keyword" class="form-control" value="<?= e($row['keyword']) ?>" required>
    <?php if (!$id): ?><div class="form-text">You can enter multiple keywords separated by commas.</div><?php endif; ?>
  </div>
  <button class="btn btn-primary"><i class="bi bi-save"></i> Save</button>
  <a href="index.php" class="btn btn-secondary">Cancel</a>
</form>
</div></div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
