<?php

function printer_send($zpl) {

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

    $printer = $cfg["printer_fullbins"] ?? "";

    if (!$printer) {
        return "NO PRINTER SELECTED";
    }

    // --- NETWORK PRINTER MODE (IP: es. 192.168.1.50) ---
    if (str_contains($printer, ":")) {
        $ip = $printer;
        $fp = @fsockopen($ip, 9100, $e, $s, 2);
        if (!$fp) return "ERROR: cannot open printer socket ($ip:9100)";
        fwrite($fp, $zpl);
        fclose($fp);
        return "PRINT SENT TO $ip";
    }

    // --- WINDOWS SHARED PRINTER ---
    $tmp = tempnam(sys_get_temp_dir(), "zpl_");
    file_put_contents($tmp, $zpl);

    $cmd = "copy /B \"$tmp\" \"$printer\"";
    $out = shell_exec($cmd . " 2>&1");

    unlink($tmp);

    return $out ?: "OK";
}

/**
 * Zebra raw query on port 9100.
 * Sends a command (like ~HS, ^XA^HH^XZ, ~HQES) and reads the response.
 */
function zebra_raw_query($ip, $command, $timeout = 2.0) {
    $errno = 0;
    $errstr = '';
    $fp = @fsockopen($ip, 9100, $errno, $errstr, $timeout);
    if (!$fp) {
        return "ERROR: Cannot connect to $ip:9100 — $errstr ($errno)";
    }

    // some commands must be wrapped by ^XA^XZ, some no; 
    // assumiamo che venga passato già corretto.
    fwrite($fp, $command);

    stream_set_timeout($fp, $timeout);
    $response = '';
    while (!feof($fp)) {
        $chunk = fgets($fp, 1024);
        if ($chunk === false) break;
        $response .= $chunk;
    }
    fclose($fp);

    return trim($response) !== '' ? trim($response) : '(no response)';
}

/**
 * Zebra diagnostics high-level:
 *  - ping socket
 *  - ~HS (health status)
 *  - ^XA^HH^XZ (config)
 *  - ~HQES (error/status)
 */
function zebra_diagnostics($ip) {
    $diag = [
        'ip'         => $ip,
        'socket_ok'  => false,
        'hs'         => null,
        'config'     => null,
        'hqes'       => null,
        'error'      => null,
    ];

    $errno = 0; $errstr = '';
    $fp = @fsockopen($ip, 9100, $errno, $errstr, 1.0);
    if (!$fp) {
        $diag['error'] = "Cannot open socket: $errstr ($errno)";
        return $diag;
    }
    $diag['socket_ok'] = true;
    fclose($fp);

    // ~HS → health status
    $diag['hs'] = zebra_raw_query($ip, "~HS");

    // Config dump
    $diag['config'] = zebra_raw_query($ip, "^XA^HH^XZ");

    // Error / sensor status
    $diag['hqes'] = zebra_raw_query($ip, "~HQES");

    return $diag;
}
