<?php
/* print_zpl.php
 * Libreria unica per stampa RAW ZPL
 */

function print_zpl($zpl, $copies = 1, $printerType = 'labels')
{
    $config_file = __DIR__ . '/../config/printer_settings.json';
    if (!file_exists($config_file)) return "Printer config missing.";

    $cfg = json_decode(file_get_contents($config_file), true);

    // scegli stampante in base al tipo
    $printers = [
        "labels"        => $cfg["labels_printer"]        ?? "",
        "group_labels"  => $cfg["group_labels_printer"]  ?? "",
        "orders"        => $cfg["orders_printer"]        ?? "",
        "reports"       => $cfg["reports_printer"]       ?? ""
    ];

    $printer = $printers[$printerType] ?? "";

    if (!$printer) return "No printer configured for $printerType";

    // prepara file RAW temp
    $tmp = tempnam(sys_get_temp_dir(), "zpl_");

    $payload = str_repeat($zpl, max(1, intval($copies)));
    file_put_contents($tmp, $payload);

    // stampa RAW tramite LPR
    $cmd = 'lpr -S localhost -P "' . $printer . '" "' . $tmp . '"';
    shell_exec($cmd);

    return "OK";
}
