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

// Delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $imgs = $conn->query("SELECT image_path FROM project_images WHERE project_id=$id");
    while ($r = $imgs->fetch_assoc()) delete_image_file($r['image_path']);
    $conn->query("DELETE FROM projects WHERE id=$id");
    flash('success','Project deleted');
    redirect('index.php');
}

$rows = $conn->query("SELECT p.*, (SELECT image_path FROM project_images WHERE project_id=p.id LIMIT 1) thumb FROM projects p ORDER BY p.id DESC");
include __DIR__ . '/../includes/header.php';
?>
<div class="d-flex justify-content-between mb-3">
  <h2>Projects</h2>
  <a href="form.php" class="btn btn-primary"><i class="bi bi-plus-lg"></i> Add Project</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>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><?= 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 project? All categories, products and images will be removed.')"><i class="bi bi-trash"></i></a>
      </td>
    </tr>
  <?php endwhile; ?>
  </tbody>
</table>
</div></div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
