<?php
require_once __DIR__ . '/../config/db_remote.php';
require_once __DIR__ . '/zpl_renderer.php';
require_once __DIR__ . '/printer_manager.php';

$id = intval($_GET["id"] ?? 0);
if ($id <= 0) die("Invalid ID");

// ---- LOAD SETTINGS ----
$settingsFile = __DIR__ . '/../config/printer_settings.json';
$cfg = file_exists($settingsFile) ? json_decode(file_get_contents($settingsFile), true) : [];

$fields  = $cfg['label_fields']   ?? [];
$layout  = $cfg['full_bins_layout'] ?? 'layout_a';
$dpi     = intval($cfg['full_bins_dpi'] ?? 203);

// ---- LOAD BIN DATA ----
$res = $mysqli->query("SELECT * FROM bins_ingresso WHERE id=$id");
$row = $res->fetch_assoc();
if (!$row) die("Bin not found");

$payload = [
    "id"        => $id,
    "grower"    => $row["grower"],
    "variety"   => $row["variety"],
    "date"      => $row["date"],
    "bins_total"=> $row["bins_total"],
    "lot"       => $row["lot"],
    "barcode"   => "FBIN-" . str_pad($id, 6, "0", STR_PAD_LEFT)
];

// ---- RENDER ZPL ----
$zpl = renderBinLabel($layout, $payload, $fields, $dpi);

// ---- SEND TO PRINTER ----
$result = printer_send($zpl);

echo "<pre>PRINT SENT\n\n$result\n\n$zpl</pre>";
