<?php
require_once __DIR__ . '/../config/user_functions.php';

session_start();
if (!isset($_SESSION['user'])) { header('Location: /smproduce/auth/login.php'); exit; }
$role = $_SESSION['user']['role'] ?? 'viewer';
if (!in_array($role, ['admin','warehouse'])) { http_response_code(403); die('Forbidden'); }

require_once __DIR__ . '/../config/db_remote.php';

// Load printer settings JSON (if present)
$printerFile = __DIR__ . '/../config/printer_settings.json';
$printerConfig = [
    "selected_printer" => "",
    "labels_printer" => "",
    "print_after_generation" => false,
    "label_width_in" => 4,
    "label_height_in" => 2,
];
if (file_exists($printerFile)) {
    $data = json_decode(file_get_contents($printerFile), true);
    if (is_array($data)) {
        $printerConfig = array_merge($printerConfig, $data);
    }
}

$source = $_GET['source'] ?? 'bins_ingresso';
$id     = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$count  = isset($_GET['count']) ? (int)$_GET['count'] : 0;

if ($source !== 'bins_ingresso' || $id <= 0) {
    http_response_code(400);
    echo "Invalid label request.";
    exit;
}

// Fetch row from bins_ingresso
$stmt = $mysqli->prepare("SELECT id, grower, date, variety, lot, quantity FROM bins_ingresso WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();

if (!$row) {
    http_response_code(404);
    echo "Bin record not found.";
    exit;
}

$grower   = $row['grower'];
$variety  = $row['variety'];
$date_rec = $row['date'];
$lot      = $row['lot'] ?? '';
$qty_row  = (int)$row['quantity'];

// Number of labels to print = quantity of bins for that record
$label_count = $count > 0 ? $count : $qty_row;
if ($label_count <= 0) $label_count = 1;

// Compute label size in dots for 203 dpi printers (Zebra default)
$dpmm = 8; // 203 dpi ~ 8 dots per mm
$width_in  = (float)($printerConfig['label_width_in'] ?? 4);
$height_in = (float)($printerConfig['label_height_in'] ?? 2);
$width_dots  = (int)round($width_in * 203);
$height_dots = (int)round($height_in * 203);

// Prepare QR payload (smartphone readable)
$qr_text = sprintf(
    "BIN|%d|%s|%s|%s|%s|%d",
    $row['id'],
    $grower,
    $variety,
    $date_rec,
    $lot,
    $qty_row
);

// Escape ^ and ~ that might break ZPL (basic replace)
$qr_text_zpl = str_replace(['^', '~'], [' ', ' '], $qr_text);

// Build ZPL for all labels
$zpl = "";
for ($i = 0; $i < $label_count; $i++) {
    $zpl .= "^XA
";
    $zpl .= "^PW" . $width_dots . "
";
    $zpl .= "^LL" . $height_dots . "
";
    $zpl .= "^FO40,40^A0N,40,40^FDGROWER: " . strtoupper($grower) . "^FS
";
    $zpl .= "^FO40,90^A0N,40,40^FDVARIETY: " . strtoupper($variety) . "^FS
";
    $zpl .= "^FO40,140^A0N,35,35^FDRECEIVED: " . $date_rec . "^FS
";
    $zpl .= "^FO40,190^A0N,35,35^FDBINS IN LOT: " . $qty_row . "^FS
";
    if ($lot !== '') {
        $zpl .= "^FO40,240^A0N,35,35^FDLOT: " . strtoupper($lot) . "^FS
";
    }
    // QR code on the right side
    $zpl .= "^FO" . ($width_dots - 260) . ",40^BQN,2,6
";
    $zpl .= "^FDLA," . $qr_text_zpl . "^FS
";
    $zpl .= "^XZ
";

}

// Direct print to labels_printer if configured
$labelsPrinter = $printerConfig['labels_printer'] ?? '';
if ($labelsPrinter) {
    // RAW 9100 (network Zebra)
    @file_put_contents("tcp://".$labelsPrinter.":9100", $zpl);

    // Windows Spooler (USB/local printer)
    $tmpLbl = tempnam(sys_get_temp_dir(), "zpl");
    file_put_contents($tmpLbl, $zpl);
    $psFileLbl = str_replace("'", "''", $tmpLbl);
    $printerNameLbl = str_replace("'", "''", $labelsPrinter);
    $cmdLbl = 'powershell -command "Get-Content -Path '''.$psFileLbl."'' | Out-Printer -Name '''.$printerNameLbl."''"';
    shell_exec($cmdLbl);
}

// If requested as raw (e.g. for direct print), respond as text/plain
// If requested as raw (e.g. for direct print), respond as text/plain
if (isset($_GET['raw']) && $_GET['raw'] === '1') {
    header('Content-Type: text/plain');
    echo $zpl;
    exit;
}
?>
<?php include('../includes/header.php'); ?>
<?php include('../includes/sidebar.php'); ?>

<div class="container py-4">
  <h3 class="mb-3">Print Bin Labels</h3>

  <div class="alert alert-info">
    <div><strong>Grower:</strong> <?= htmlspecialchars($grower) ?></div>
    <div><strong>Variety:</strong> <?= htmlspecialchars($variety) ?></div>
    <div><strong>Date received:</strong> <?= htmlspecialchars($date_rec) ?></div>
    <div><strong>Bins in lot (this record):</strong> <?= $qty_row ?></div>
    <?php if ($lot !== ''): ?>
      <div><strong>Lot:</strong> <?= htmlspecialchars($lot) ?></div>
    <?php endif; ?>
    <div class="mt-2"><strong>Labels to print:</strong> <?= $label_count ?></div>
  </div>

  <p class="mb-2">
    This page generates ZPL for your Zebra label printer (4x2").  
    You can:
  </p>
  <ul>
    <li>Download the ZPL file and send it to the printer.</li>
    <li>Or open the <code>?raw=1</code> version and print via your print spooler.</li>
  </ul>

  <div class="mb-3">
    <a class="btn btn-primary" href="?source=bins_ingresso&id=<?= $row['id'] ?>&count=<?= $label_count ?>&raw=1" target="_blank">
      Open Raw ZPL (for direct printing)
    </a>
  </div>

  <div class="mb-3">
    <label class="form-label">ZPL Preview</label>
    <textarea class="form-control" rows="12" readonly><?= htmlspecialchars($zpl) ?></textarea>
  </div>

  <a href="/smproduce/pages/bins_ingresso.php" class="btn btn-secondary">Back to Bins Ingress</a>
</div>

<?php include('../includes/footer.php'); ?>
