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

$product_id = (int)($_GET['product_id'] ?? 0);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = (int)$_POST['product_id'];
    $selected = $_POST['keywords'] ?? [];
    $conn->query("DELETE FROM product_keywords WHERE product_id=$product_id");
    foreach ($selected as $kid) {
        $kid = (int)$kid;
        $stmt = $conn->prepare("INSERT IGNORE INTO product_keywords (product_id, keyword_id) VALUES (?,?)");
        $stmt->bind_param('ii', $product_id, $kid);
        $stmt->execute();
    }
    flash('success','Keywords saved');
    redirect("index.php?product_id=$product_id");
}

$products = $conn->query("SELECT id, name FROM products ORDER BY name");
$assigned = [];
if ($product_id) {
    $res = $conn->query("SELECT keyword_id FROM product_keywords WHERE product_id=$product_id");
    while ($r = $res->fetch_assoc()) $assigned[] = (int)$r['keyword_id'];
}

include __DIR__ . '/../includes/header.php';
?>
<h2 class="mb-3">Assign Keywords to Products</h2>

<div class="card mb-3"><div class="card-body">
<form method="get" class="row g-2 align-items-end">
  <div class="col-md-6"><label class="form-label">Select Product</label>
    <select name="product_id" class="form-select" onchange="this.form.submit()">
      <option value="">-- Select Product --</option>
      <?php while ($p = $products->fetch_assoc()): ?>
      <option value="<?= $p['id'] ?>" <?= $product_id==$p['id']?'selected':'' ?>><?= e($p['name']) ?></option>
      <?php endwhile; ?>
    </select>
  </div>
</form>
</div></div>

<?php if ($product_id):
    $kcats = $conn->query("SELECT * FROM keyword_categories ORDER BY name");
?>
<form method="post">
<input type="hidden" name="product_id" value="<?= $product_id ?>">
<div class="row g-3">
<?php while ($kc = $kcats->fetch_assoc()):
    $kws = $conn->query("SELECT * FROM keywords WHERE keyword_category_id={$kc['id']} ORDER BY keyword");
?>
  <div class="col-md-6">
    <div class="card">
      <div class="card-header bg-light"><strong><?= e($kc['name']) ?></strong></div>
      <div class="card-body">
        <?php if ($kws->num_rows): ?>
        <?php while ($k = $kws->fetch_assoc()):
            $checked = in_array((int)$k['id'], $assigned) ? 'checked' : '';
        ?>
          <div class="form-check form-check-inline">
            <input class="form-check-input" type="checkbox" name="keywords[]" value="<?= $k['id'] ?>" id="kw_<?= $k['id'] ?>" <?= $checked ?>>
            <label class="form-check-label" for="kw_<?= $k['id'] ?>"><?= e($k['keyword']) ?></label>
          </div>
        <?php endwhile; ?>
        <?php else: ?>
        <p class="text-muted small mb-0">No keywords yet.</p>
        <?php endif; ?>
      </div>
    </div>
  </div>
<?php endwhile; ?>
</div>
<div class="mt-3">
  <button class="btn btn-primary"><i class="bi bi-save"></i> Save Keywords</button>
</div>
</form>
<?php endif; ?>

<?php include __DIR__ . '/../includes/footer.php'; ?>
