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

// daemon_keyence.php
// Run from CLI: php daemon_keyence.php
set_time_limit(0);
date_default_timezone_set('UTC');

$LISTEN_PORT = 9004;
$PRODUCTION_LINE = "Apple Line";

echo "[".date('Y-m-d H:i:s')."] Starting Keyence listener on port $LISTEN_PORT...\n";

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!$sock) {
    die("socket_create failed: ".socket_strerror(socket_last_error())."\n");
}
if (!socket_bind($sock, "0.0.0.0", $LISTEN_PORT)) {
    die("socket_bind failed: ".socket_strerror(socket_last_error($sock))."\n");
}
if (!socket_listen($sock)) {
    die("socket_listen failed: ".socket_strerror(socket_last_error($sock))."\n");
}

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

$logDir = __DIR__ . "/logs";
if (!is_dir($logDir)) mkdir($logDir, 0777, true);
$logFile = $logDir . "/keyence.log";

function klog($msg) {
    global $logFile;
    $line = "[".date('Y-m-d H:i:s')."] ".$msg."\n";
    echo $line;
    file_put_contents($logFile, $line, FILE_APPEND);
}

klog("Keyence daemon started.");

while (true) {
    $client = @socket_accept($sock);
    if ($client === false) {
        usleep(100000);
        continue;
    }

    $data = trim(@socket_read($client, 2048));
    if ($data !== '') {
        $serial = $data;
        klog("BARCODE / SERIAL RECEIVED: $serial");

        global $mysqli;
        $serialEsc = $mysqli->real_escape_string($serial);
        $sql = "SELECT * FROM Serialformatted WHERE Serial = '$serialEsc' OR serial = '$serialEsc' LIMIT 1";
        $res = $mysqli->query($sql);

        $variety = null;
        $grower  = null;
        $lot     = null;
        $harvested_at = null;

        if ($res && $res->num_rows > 0) {
            $row = $res->fetch_assoc();
            $variety = $row['Variety']      ?? $row['variety']      ?? null;
            $grower  = $row['Grower']       ?? $row['grower']       ?? null;
            $lot     = $row['Lot']          ?? $row['lot']          ?? $row['Batch'] ?? null;
            $harvested_at = $row['HarvestedAt'] ?? $row['harvested_at'] ?? $row['HarvestDate'] ?? null;
            klog("Serialformatted found: variety=$variety, grower=$grower, lot=$lot, harvested_at=$harvested_at");
        } else {
            klog("Serialformatted NOT found for serial: $serial");
        }

        $serialDb = $mysqli->real_escape_string($serial);
        $varDb    = $mysqli->real_escape_string((string)$variety);
        $growDb   = $mysqli->real_escape_string((string)$grower);
        $lotDb    = $mysqli->real_escape_string((string)$lot);
        $harvDb   = $harvested_at ? "'".$mysqli->real_escape_string($harvested_at)."'" : "NULL";
        $lineDb   = $mysqli->real_escape_string($PRODUCTION_LINE);

        $sqlIns = "
            INSERT INTO boxes_produced (serial, variety, grower, lot, harvested_at, production_line, read_at)
            VALUES ('$serialDb', '$varDb', '$growDb', '$lotDb', $harvDb, '$lineDb', NOW())
        ";
        if (!$mysqli->query($sqlIns)) {
            klog("ERROR inserting into boxes_produced: ".$mysqli->error);
        } else {
            klog("Saved into boxes_produced.");
        }

        @socket_write($client, "OK\n");
    }

    @socket_close($client);
}

socket_close($sock);
