<?php
require 'vendor/autoload.php';
include 'db.php';

use Picqer\Barcode\BarcodeGeneratorPNG;

$itemCode = $_GET['code'] ?? '';
$copies = intval($_GET['copies'] ?? 1);

if (!$itemCode || $copies < 1) {
    die('Invalid request.');
}

// Get item info including price
$stmt = $conn->prepare("SELECT name, retail_price FROM items WHERE item_code = ?");
$stmt->bind_param('s', $itemCode);
$stmt->execute();
$item = $stmt->get_result()->fetch_assoc();

if (!$item) {
    die('Item not found.');
}

// Get branch info
$branch = $conn->query("SELECT branch_name FROM branch_info LIMIT 1")->fetch_assoc();
$branchName = $branch['branch_name'] ?? 'Branch';

$generator = new BarcodeGeneratorPNG();

?>
<!DOCTYPE html>
<html>
<head>
    <title>Barcode - <?= htmlspecialchars($item['name']) ?></title>
    <style>
        body { font-family: Arial, sans-serif; }
        .barcode-label {
            text-align: center;
            margin: 10px;
            display: inline-block;
            width: 220px;
            border: 1px solid #000;
            padding: 10px;
        }
        .barcode-label img {
            max-width: 100%;
        }
        .barcode-text {
            font-size: 14px;
        }
        .price {
            font-size: 16px;
            font-weight: bold;
        }
    </style>
</head>
<body onload="window.print()">
<?php for ($i = 0; $i < $copies; $i++): ?>
    <div class="barcode-label">
        <div class="barcode-text"><?= htmlspecialchars($branchName) ?></div>
        <div class="barcode-text"><?= htmlspecialchars($item['name']) ?></div>
        <img src="data:image/png;base64,<?= base64_encode($generator->getBarcode($itemCode, $generator::TYPE_CODE_128)) ?>" alt="Barcode">
        <div class="barcode-text"><?= htmlspecialchars($itemCode) ?></div>
        <div class="price">Rs <?= number_format($item['retail_price'], 2) ?></div>
    </div>
<?php endfor; ?>
</body>
</html>
