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

if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $imgs = $conn->query("SELECT image_path FROM category_images WHERE category_id=$id");
    while ($r = $imgs->fetch_assoc()) delete_image_file($r['image_path']);
    $conn->query("DELETE FROM categories WHERE id=$id");
    flash('success','Category deleted');
    redirect('index.php');
}

$filter = (int)($_GET['project_id'] ?? 0);
$where = $filter ? "WHERE c.project_id=$filter" : '';
$rows = $conn->query("SELECT c.*, p.name pname, (SELECT image_path FROM category_images WHERE category_id=c.id LIMIT 1) thumb FROM categories c JOIN projects p ON p.id=c.project_id $where ORDER BY c.id DESC");
$projects = $conn->query("SELECT id, name FROM projects ORDER BY name");
include __DIR__ . '/../includes/header.php';
?>
<div class="d-flex justify-content-between mb-3">
  <h2>Categories</h2>
  <a href="form.php" class="btn btn-primary"><i class="bi bi-plus-lg"></i> Add Category</a>
</div>
<form class="mb-3"><div class="row g-2">
  <div class="col-md-4"><select name="project_id" class="form-select" onchange="this.form.submit()">
    <option value="">All Projects</option>
    <?php while ($p = $projects->fetch_assoc()): ?>
    <option value="<?= $p['id'] ?>" <?= $filter==$p['id']?'selected':'' ?>><?= e($p['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 width="80">Image</th><th>Name</th><th>Project</th><th>Description</th><th width="160">Actions</th></tr></thead>
  <tbody>
  <?php while ($r = $rows->fetch_assoc()): ?>
    <tr>
      <td><?= $r['id'] ?></td>
      <td><?= $r['thumb'] ? '<img src="'.UPLOAD_URL.'/'.e($r['thumb']).'" class="thumb">' : '-' ?></td>
      <td><?= e($r['name']) ?></td>
      <td><span class="badge bg-primary"><?= e($r['pname']) ?></span></td>
      <td><?= e(mb_strimwidth($r['description'] ?? '',0,80,'...')) ?></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 this category and all its subcategories/products?')"><i class="bi bi-trash"></i></a>
      </td>
    </tr>
  <?php endwhile; ?>
  </tbody>
</table>
</div></div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
