<?php
// =====================================================
// LOAD PRINTER SETTINGS
// =====================================================
$printerFile = __DIR__ . '/../config/printer_settings.json';
$settings = file_exists($printerFile)
    ? json_decode(file_get_contents($printerFile), true)
    : [];

// Defaults
$mode = $settings['full_bins_mode'] ?? 'manual';
$previewEnabled = !empty($settings['full_bins_preview']);

$binId = intval($_GET["id"] ?? 0);
?>

<hr class="my-4">

<h4>🖨 Full Bin Label</h4>

<div class="d-flex gap-3 mt-3">

    <?php if ($previewEnabled): ?>
        <a href="/smproduce/print/preview_zpl.php?id=<?= $binId ?>" 
           class="btn btn-secondary" target="_blank">
           👁 Preview
        </a>
    <?php endif; ?>

    <?php if ($mode === "manual"): ?>
        <button class="btn btn-primary" onclick="printLabel()">🖨 Print Label</button>
    <?php elseif ($mode === "auto_confirm"): ?>
        <button class="btn btn-warning" onclick="autoConfirmPrint()">⚠ Stampa Automatica</button>
    <?php elseif ($mode === "auto_instant"): ?>
        <script>
            // stampa immediata all'apertura della pagina
            window.onload = function() {
                fetch('/smproduce/print/print_zpl.php?id=<?= $binId ?>')
                    .then(r => r.text())
                    .then(t => console.log("Printed:", t));
            };
        </script>
        <span class="badge bg-info p-2">Auto-stampa attiva</span>
    <?php elseif ($mode === "preview_only"): ?>
        <span class="badge bg-secondary p-2">Preview only mode</span>
    <?php endif; ?>

</div>

<script>
function printLabel() {
    window.open("/smproduce/print/print_zpl.php?id=<?= $binId ?>", "_blank");
}

function autoConfirmPrint() {
    if (confirm("Stampare l'etichetta del full bin?")) {
        window.open("/smproduce/print/print_zpl.php?id=<?= $binId ?>", "_blank");
    }
}
</script>
