<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include '../../db.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Product List</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body {
      background-color: #f8f9fa;
    }
    .img-thumb {
      border-radius: 8px;
      object-fit: cover;
    }
  </style>
</head>
<body class="p-5 bg-light">
<div class="container bg-white p-4 rounded shadow">
  <h2 class="mb-4">📦 Product List</h2>

  <?php if (isset($_GET['msg'])): ?>
    <div class="alert alert-success"><?= htmlspecialchars($_GET['msg']) ?></div>
  <?php endif; ?>

  <a href="add.php" class="btn btn-primary mb-3">➕ Add New</a>

  <table class="table table-bordered table-striped align-middle">
    <thead class="table-dark">
      <tr>
        <th>#</th>
        <th>Image</th>
        <th>Name</th>
        <th>Price</th>
        <th>Category</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      <?php
      $result = $conn->query("
        SELECT products.*, product_categories.category_name 
        FROM products 
        JOIN product_categories ON products.category_id = product_categories.id 
        ORDER BY products.id DESC
      ");

      if ($result && $result->num_rows > 0):
        while ($row = $result->fetch_assoc()):
          $imagePath = "../" . $row['product_image']; // Relative path for dashboard display
          $price = $row['price'];
      ?>
      <tr>
        <td><?= $row['id'] ?></td>
        <td>
          <?php if (file_exists($imagePath)): ?>
            <img src="<?= $imagePath ?>" width="60" height="60" class="img-thumb">
          <?php else: ?>
            <span class="text-danger">Image missing</span>
          <?php endif; ?>
        </td>
        <td><?= htmlspecialchars($row['product_name']) ?></td>
        <td>
          <?= is_numeric($price) ? "₹" . number_format($price, 2) : "<span class='text-danger'>Invalid</span>" ?>
        </td>
        <td><?= htmlspecialchars($row['category_name']) ?></td>
        <td>
          <a href="edit.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-warning">Edit</a>
          <a href="delete.php?id=<?= $row['id'] ?>" onclick="return confirm('Delete this product?')" class="btn btn-sm btn-danger">Delete</a>
        </td>
      </tr>
      <?php
        endwhile;
      else:
      ?>
      <tr>
        <td colspan="6" class="text-center text-muted">No products found.</td>
      </tr>
      <?php endif; ?>
    </tbody>
  </table>
</div>
</body>
</html>
