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

// ✅ Validate inv_id from request
if (!isset($_GET['inv_id']) || trim($_GET['inv_id']) === "") {
    die("Invalid or missing Invoice ID.");
}
$inv_id = $_GET['inv_id'];

// ✅ Fetch records for this inv_id
$sql = "SELECT product_id, product_name 
        FROM purchase 
        WHERE inv_id = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("s", $inv_id); // alphanumeric, so bind as string
$stmt->execute();
$result = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Product Labels</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.label-card {
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 10px;
  margin: 10px;
  text-align: center;
  width: 220px;
  background: #f9f9f9;
}
.barcode-img {
  max-width: 200px;
}
@media print {
  #buttons { display: none; }
}
</style>
</head>
<body class="container mt-4">

<div id="buttons" class="mb-3">
  <button onclick="window.print()" class="btn btn-primary">Print</button>
  <a href="purchase_n.php" class="btn btn-secondary">Back</a>
</div>

<h5>Invoice ID: <?php echo htmlspecialchars($inv_id); ?></h5>
<hr>

<div class="row">
<?php if ($result->num_rows > 0): ?>
    <?php while ($row = $result->fetch_assoc()): ?>
      <div class="col-md-3">
        <div class="label-card">
          <h6><?php echo htmlspecialchars($row['product_id']); ?></h6>
          <p><?php echo htmlspecialchars($row['product_name']); ?></p>
          <img class="barcode-img" 
               src="https://barcodeapi.org/api/code128/<?php echo urlencode($row['product_id']); ?>" 
               alt="Barcode" />
        </div>
      </div>
    <?php endwhile; ?>
<?php else: ?>
    <p class="text-danger">No products found for this invoice.</p>
<?php endif; ?>
</div>

</body>
</html>

<?php
$stmt->close();
$connection->close();
?>
