<?php
/**
 * php_tcp_listener.php
 *
 * Listener TCP per il Keyence.
 * Riceve i barcode, li salva nel database e aggiorna il timestamp
 * della lettura più recente (per l’auto-report).
 */

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

$address = "0.0.0.0";
$port    = 12000;

$socket = stream_socket_server("tcp://{$address}:{$port}", $errno, $errstr);

if (!$socket) {
    error_log("TCP Listener ERROR: $errstr ($errno)");
    exit(1);
}

error_log("TCP Listener avviato su {$address}:{$port}");

while ($conn = @stream_socket_accept($socket, -1)) {

    $barcode = trim(@fgets($conn));
    if ($barcode === "") {
        fclose($conn);
        continue;
    }

    $barcodeSafe = $mysqli->real_escape_string($barcode);
    $now         = date('Y-m-d H:i:s');

    // FIX: source_code = KEYENCE
    $sql = "
        INSERT INTO barcode_readings (code, source_code, read_time)
        VALUES ('{$barcodeSafe}', 'KEYENCE', '{$now}')
    ";

    if (!$mysqli->query($sql)) {
        error_log("TCP INSERT ERROR: " . $mysqli->error);
    }

    // timestamp per auto-report
    @file_put_contents(__DIR__ . '/../last_barcode_timestamp.txt', time());

    fwrite($conn, "OK\n");
    fclose($conn);
}

fclose($socket);
?>
