<?php
include('db/cn.php');

$query = mysqli_query($connection, "SELECT product_id, product_name, retail_price FROM products");
if (!$query) {
    die("Query failed: " . mysqli_error($connection));
}
$products = [];
while ($row = mysqli_fetch_assoc($query)) {
    $products[] = $row;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Product Labels</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@400;600&display=swap" rel="stylesheet">
  <style>
    body { font-family: 'Quicksand', sans-serif; }
    .label-card {
        width: 250px;
        border: 1px dashed #333;
        padding: 15px;
        margin: 10px;
        text-align: center;
        font-weight:700;
    }
    svg {
        width: 100%;
        height: 60px;
    }
    h2, h6{
        font-weight:700;
        color:#000;
    }
    .btn{
        font-weight:700;
    }
  </style>
</head>
<body>
<div class="container mt-4">
  <div class="d-flex justify-content-between align-items-center mb-4">
    <h2>Product Labels</h2>
    <a href="addproducts.php" class="btn btn-secondary">&larr; Back</a>
  </div>
  <div class="row">
    <?php foreach($products as $p) { ?>
      <div class="col-md-3 col-sm-4 col-6">
        <div class="label-card">
          <svg id="barcode-<?php echo $p['product_id']; ?>"></svg>
          <h6><?php echo htmlspecialchars($p['product_name']); ?></h6>
          <p>Price: <?php echo number_format($p['retail_price'], 2); ?></p>
        </div>
      </div>
    <?php } ?>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.6/dist/JsBarcode.all.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(){
    <?php foreach($products as $p) { ?>
        JsBarcode("#barcode-<?php echo $p['product_id']; ?>", "<?php echo $p['product_id']; ?>", {
            format: "CODE128",
            lineColor: "#000",
            width: 2,
            height: 40,
            displayValue: true
        });
    <?php } ?>
});
</script>
</body>
</html>
