<?php
require_once __DIR__ . '/../config.php';
requireAdmin();
$db     = getDB();
$action = $_GET['action'] ?? 'list';
$id     = (int)($_GET['id'] ?? 0);
$msg    = '';

if ($action === 'delete' && $id) {
    $db->prepare("DELETE FROM categories WHERE id=?")->execute([$id]);
    redirect(SITE_URL . '/admin/categories.php?msg=deleted');
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_cat'])) {
    $name = trim($_POST['name'] ?? '');
    $slug = slugify($name);
    $desc = trim($_POST['description'] ?? '');
    if ($id) {
        $db->prepare("UPDATE categories SET name=?,slug=?,description=? WHERE id=?")->execute([$name,$slug,$desc,$id]);
        $msg = 'Category updated.';
    } else {
        $db->prepare("INSERT INTO categories (name,slug,description) VALUES (?,?,?)")->execute([$name,$slug,$desc]);
        $msg = 'Category added.';
        $action = 'list';
    }
}
$cat  = $id ? $db->query("SELECT * FROM categories WHERE id=$id")->fetch() : [];
$cats = $db->query("SELECT c.*,(SELECT COUNT(*) FROM products WHERE category_id=c.id) AS pcount FROM categories c ORDER BY c.id DESC")->fetchAll();
$page_title = 'Categories';
include __DIR__ . '/header.php';
?>
<?php if ($msg): ?><div class="alert alert-success"><?= h($msg) ?></div><?php endif; ?>
<?php if (isset($_GET['msg'])): ?><div class="alert alert-success">Category deleted.</div><?php endif; ?>

<div style="display:grid;grid-template-columns:1fr 1.4fr;gap:24px;">
  <div class="card">
    <div class="card-header"><h2><?= $id ? 'Edit Category' : 'Add Category' ?></h2></div>
    <div class="card-body">
      <form method="POST">
        <input type="hidden" name="save_cat" value="1">
        <div class="form-group"><label>Category Name *</label><input type="text" name="name" value="<?= h($cat['name'] ?? '') ?>" required placeholder="e.g. Single Bowl Sinks"></div>
        <div class="form-group"><label>Description</label><textarea name="description"><?= h($cat['description'] ?? '') ?></textarea></div>
        <div style="display:flex;gap:10px;">
          <button type="submit" class="btn-primary">Save</button>
          <?php if ($id): ?><a href="categories.php" class="btn-secondary">Cancel</a><?php endif; ?>
        </div>
      </form>
    </div>
  </div>
  <div class="card">
    <div class="card-header"><h2>All Categories</h2></div>
    <div class="table-wrap">
      <table>
        <thead><tr><th>Name</th><th>Slug</th><th>Products</th><th>Actions</th></tr></thead>
        <tbody>
          <?php foreach ($cats as $c): ?>
          <tr>
            <td><strong><?= h($c['name']) ?></strong></td>
            <td><code style="font-size:.78rem;background:#f1f5f9;padding:2px 6px;border-radius:4px;"><?= h($c['slug']) ?></code></td>
            <td><?= $c['pcount'] ?></td>
            <td class="action-btns">
              <a href="?action=edit&id=<?= $c['id'] ?>" class="btn-action btn-edit">Edit</a>
              <a href="?action=delete&id=<?= $c['id'] ?>" class="btn-action btn-delete" onclick="return confirm('Delete this category?')">Delete</a>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php include __DIR__ . '/footer.php'; ?>
