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

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

// Group subcategories by category - shows all categories with their subs
$cats = $conn->query("SELECT c.*, p.name pname FROM categories c JOIN projects p ON p.id=c.project_id ORDER BY p.name, c.name");

include __DIR__ . '/../includes/header.php';
?>
<div class="d-flex justify-content-between mb-3">
  <h2>Subcategories</h2>
  <a href="form.php" class="btn btn-primary"><i class="bi bi-plus-lg"></i> Add Subcategory</a>
</div>

<?php while ($cat = $cats->fetch_assoc()):
    $subs = $conn->query("SELECT s.*, (SELECT image_path FROM subcategory_images WHERE subcategory_id=s.id LIMIT 1) thumb FROM subcategories s WHERE s.category_id={$cat['id']} ORDER BY s.id DESC");
?>
<div class="card mb-3">
  <div class="card-header bg-light d-flex justify-content-between">
    <strong><?= e($cat['pname']) ?> &raquo; <?= e($cat['name']) ?></strong>
    <a href="form.php?category_id=<?= $cat['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-plus"></i> Add Subcategory</a>
  </div>
  <?php if ($subs->num_rows): ?>
  <table class="table table-sm mb-0">
    <thead class="table-light"><tr><th width="60">ID</th><th width="80">Image</th><th>Name</th><th>Description</th><th width="160">Actions</th></tr></thead>
    <tbody>
    <?php while ($s = $subs->fetch_assoc()): ?>
      <tr>
        <td><?= $s['id'] ?></td>
        <td><?= $s['thumb'] ? '<img src="'.UPLOAD_URL.'/'.e($s['thumb']).'" class="thumb">' : '-' ?></td>
        <td><?= e($s['name']) ?></td>
        <td><?= e(mb_strimwidth($s['description'] ?? '',0,80,'...')) ?></td>
        <td>
          <a href="form.php?id=<?= $s['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-pencil"></i></a>
          <a href="?delete=<?= $s['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this subcategory?')"><i class="bi bi-trash"></i></a>
        </td>
      </tr>
    <?php endwhile; ?>
    </tbody>
  </table>
  <?php else: ?>
  <div class="card-body text-muted small">No subcategories yet.</div>
  <?php endif; ?>
</div>
<?php endwhile; ?>

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