<?php
require_once 'db/config.php';

$product_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($product_id === 0) {
    die("ID de producto no válido.");
}

$pdo = db();
$stmt = $pdo->prepare("SELECT * FROM productos WHERE id = ?");
$stmt->execute([$product_id]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$product) {
    die("Producto no encontrado.");
}

$barcodeValue = $product['codigo_barras'] ? $product['codigo_barras'] : $product['sku'];
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Imprimir Código de Barras - <?php echo htmlspecialchars($product['nombre']); ?></title>
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            padding: 20px;
        }
        .barcode-container {
            border: 1px solid #ccc;
            padding: 10px;
            display: inline-block;
            margin: 10px;
        }
        .product-name {
            font-size: 14px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        @media print {
            .no-print {
                display: none;
            }
            body {
                padding: 0;
                margin: 0;
            }
            .barcode-container {
                border: none;
            }
        }
    </style>
</head>
<body>

    <div class="no-print">
        <button onclick="window.print()">Imprimir</button>
        <button onclick="window.close()">Cerrar</button>
        <hr>
    </div>

    <div class="barcode-container">
        <div class="product-name"><?php echo htmlspecialchars($product['nombre']); ?></div>
        <svg id="barcode"></svg>
    </div>

    <script>
        JsBarcode("#barcode", "<?php echo htmlspecialchars($barcodeValue); ?>", {
            format: "CODE128",
            lineColor: "#000",
            width: 2,
            height: 40,
            displayValue: true
        });
    </script>
</body>
</html>
