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

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $desc = trim($_POST['description']);

    if ($id) {
        $stmt = $conn->prepare("UPDATE keyword_categories SET name=?, description=? WHERE id=?");
        $stmt->bind_param('ssi', $name, $desc, $id);
    } else {
        $stmt = $conn->prepare("INSERT INTO keyword_categories (name, description) VALUES (?,?)");
        $stmt->bind_param('ss', $name, $desc);
    }
    $stmt->execute();
    flash('success', $id ? 'Updated' : 'Added');
    redirect('index.php');
}

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">Name *</label>
    <input type="text" name="name" class="form-control" value="<?= e($row['name']) ?>" required>
  </div>
  <div class="mb-3">
    <label class="form-label">Description</label>
    <textarea name="description" class="form-control" rows="3"><?= e($row['description']) ?></textarea>
  </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'; ?>
