<?php
/**
 * send_order.php
 * Envia solicitudes (RAW) al Fusion/Spirit por PuertoOrden (default 60608).
 * Soporta TCP y UDP. Puede usarse por CLI o via navegador (form).
 *
 * CLI ejemplos:
 *   php send_order.php --host=172.17.125.102 --port=60608 --proto=tcp --data="REQ_PUMP_STATUS_ID_001"
 *   php send_order.php --host=172.17.125.102 --port=60608 --proto=tcp --file=payload.txt
 *
 * Web:
 *   Subir a un servidor con PHP y abrir en navegador.
 */
declare(strict_types=1);

function send_data(string $host, int $port, string $proto, string $data, float $timeout=5.0, ?string $delim="\n"): array {
    $proto = strtolower($proto);
    if (!in_array($proto, ['tcp','udp'], true)) $proto = 'tcp';
    $scheme = $proto.'://'.$host.':'.$port;
    $ctx = stream_context_create();
    $fp = @stream_socket_client($scheme, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $ctx);
    if (!$fp) return ['ok'=>false, 'error'=>"Conexión fallida: $errstr ($errno)", 'sent'=>0, 'recv'=>''];
    stream_set_timeout($fp, (int)ceil($timeout));
    $payload = $data;
    if ($delim !== null && $delim !== '') $payload .= $delim;
    $sent = @fwrite($fp, $payload);
    // intentar leer respuesta (si existe)
    $response = '';
    $start = microtime(true);
    while ((microtime(true)-$start) < $timeout) {
        $chunk = @fread($fp, 8192);
        if ($chunk === false || $chunk === '') { usleep(50000); continue; }
        $response .= $chunk;
        // si no esperamos más, romper; si se quiere leer todo, quitar break
        if (strlen($chunk) < 8192) break;
    }
    @fclose($fp);
    return ['ok'=>true, 'error'=>'', 'sent'=>$sent, 'recv'=>$response];
}

function is_cli(): bool {
    return php_sapi_name() === 'cli' || PHP_SAPI === 'cli';
}

if (is_cli()) {
    // CLI
    $args = getopt('', ['host:', 'port::', 'proto::', 'data::', 'file::', 'timeout::', 'delim::']);
    $host = $args['host'] ?? '127.0.0.1';
    $port = isset($args['port']) ? (int)$args['port'] : 60608;
    $proto = $args['proto'] ?? 'tcp';
    $timeout = isset($args['timeout']) ? (float)$args['timeout'] : 5.0;
    $delim = array_key_exists('delim',$args) ? (string)$args['delim'] : "\n";
    $data = $args['data'] ?? '';
    if ($data === '' && isset($args['file'])) {
        $data = @file_get_contents((string)$args['file']) ?: '';
    }
    if ($data === '') {
        fwrite(STDERR, "Uso: php send_order.php --host=IP --port=60608 --proto=tcp --data=\"MENSAJE\"\n");
        exit(2);
    }
    $res = send_data($host, $port, $proto, $data, $timeout, $delim);
    echo "OK: ".($res['ok']?'true':'false')."\n";
    if ($res['error']) echo "ERROR: ".$res['error']."\n";
    echo "BYTES_ENVIADOS: ".(int)$res['sent']."\n";
    echo "RESPUESTA:\n".$res['recv']."\n";
    exit($res['ok']?0:1);
}

// WEB FORM
$host = $_POST['host'] ?? ($_GET['host'] ?? '127.0.0.1');
$port = isset($_POST['port']) ? (int)$_POST['port'] : (isset($_GET['port']) ? (int)$_GET['port'] : 60608);
$proto = $_POST['proto'] ?? ($_GET['proto'] ?? 'tcp');
$data = $_POST['data'] ?? ($_GET['data'] ?? '');
$delim = $_POST['delim'] ?? ($_GET['delim'] ?? "\n");
$timeout = isset($_POST['timeout']) ? (float)$_POST['timeout'] : (isset($_GET['timeout']) ? (float)$_GET['timeout'] : 5.0);
$res = null;
if (isset($_POST['send'])) {
    $res = send_data($host,$port,$proto,$data,$timeout,$delim);
}
?>
<!doctype html><meta charset="utf-8"><title>Send Order (PuertoOrden)</title>
<style>body{font-family:system-ui;background:#0b1022;color:#e5e7eb} .card{max-width:900px;margin:20px auto;background:#111827;border:1px solid #1f2937;border-radius:14px;padding:16px} input,textarea,select{width:100%;padding:8px;margin:6px 0;background:#0b1022;border:1px solid #1f2937;color:#e5e7eb;border-radius:10px} button{padding:10px 16px;border-radius:10px;border:1px solid #1f2937;background:#0b1022;color:#e5e7eb;cursor:pointer} .row{display:grid;grid-template-columns:1fr 1fr;gap:12px} .pre{white-space:pre-wrap;background:#0b1022;border:1px solid #1f2937;border-radius:10px;padding:10px;min-height:100px}</style>
<div class="card">
<h1>Enviar solicitud a PuertoOrden (default 60608)</h1>
<form method="post">
<div class="row">
  <label>Host/IP<input name="host" value="<?=htmlspecialchars($host,ENT_QUOTES)?>"></label>
  <label>Puerto<input name="port" value="<?=htmlspecialchars((string)$port,ENT_QUOTES)?>"></label>
</div>
<div class="row">
  <label>Protocolo
    <select name="proto">
      <option value="tcp" <?= $proto==='tcp'?'selected':''?>>TCP</option>
      <option value="udp" <?= $proto==='udp'?'selected':''?>>UDP</option>
    </select>
  </label>
  <label>Delimitador (ej. \n, vacío para ninguno)<input name="delim" value="<?=htmlspecialchars($delim,ENT_QUOTES)?>"></label>
</div>
<label>Data/Mensaje (RAW a enviar)<textarea name="data" rows="6" placeholder="Ej: REQ_PUMP_STATUS_ID_001"><?=htmlspecialchars($data,ENT_QUOTES)?></textarea></label>
<div class="row">
  <label>Timeout (segundos)<input name="timeout" value="<?=htmlspecialchars((string)$timeout,ENT_QUOTES)?>"></label>
  <div><br><button name="send" value="1">Enviar</button></div>
</div>
</form>
<?php if ($res!==null): ?>
<h2>Resultado</h2>
<p><b>OK:</b> <?= $res['ok']?'true':'false' ?></p>
<?php if(!$res['ok']): ?><p><b>Error:</b> <?= htmlspecialchars((string)$res['error'],ENT_QUOTES) ?></p><?php endif; ?>
<p><b>Bytes enviados:</b> <?= (int)$res['sent'] ?></p>
<div class="pre"><?= htmlspecialchars((string)$res['recv'],ENT_QUOTES) ?></div>
<?php endif; ?>
</div>
