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

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

$rows = $conn->query("SELECT pr.*, p.name pname, c.name cname, s.name sname,
  (SELECT image_path FROM product_images WHERE product_id=pr.id LIMIT 1) thumb,
  (SELECT COUNT(*) FROM product_titles WHERE product_id=pr.id) titles_count
  FROM products pr
  JOIN projects p ON p.id=pr.project_id
  JOIN categories c ON c.id=pr.category_id
  JOIN subcategories s ON s.id=pr.subcategory_id
  ORDER BY pr.id DESC");

include __DIR__ . '/../includes/header.php';
?>
<div class="d-flex justify-content-between mb-3">
  <h2>Products</h2>
  <a href="form.php" class="btn btn-primary"><i class="bi bi-plus-lg"></i> Add Product</a>
</div>
<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>Hierarchy</th><th width="100">Price</th><th width="80">Titles</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><strong><?= e($r['name']) ?></strong>
        <?php if ($r['url']): ?><br><a href="<?= e($r['url']) ?>" target="_blank" class="small"><i class="bi bi-link-45deg"></i> Link</a><?php endif; ?>
      </td>
      <td class="small"><?= e($r['pname']) ?> &raquo; <?= e($r['cname']) ?> &raquo; <?= e($r['sname']) ?></td>
      <td><?= number_format($r['price'],2) ?></td>
      <td><span class="badge bg-info"><?= $r['titles_count'] ?></span></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 product?')"><i class="bi bi-trash"></i></a>
      </td>
    </tr>
  <?php endwhile; ?>
  </tbody>
</table>
</div></div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
