<?php
// pump_status.php - reads pump statuses from a text file updated by external system.
// Expected lines: "1, FUELLING" or "2, IDLE" etc.
// Returns JSON: { ok:true, source:"...", statuses:{ "1":"IDLE", "2":"FUELLING" ... } }

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

$paths = [
  'C:\\opscode\\fs3xp.txt',
  'C:\\opscode\\fss3xp.txt',
  'C:\\opscode\\fs3xp.TXT',
  'C:\\opscode\\fss3xp.TXT',
];

$path = null;
foreach ($paths as $p) {
  if (@file_exists($p)) { $path = $p; break; }
}
if ($path === null) {
  echo json_encode(['ok'=>false,'error'=>'status_file_not_found','paths'=>$paths]);
  exit;
}

// Open -> read -> close every request (avoid stale buffers / locking issues)
$fh = @fopen($path, 'rb');
if (!$fh) {
  echo json_encode(['ok'=>false,'error'=>'cannot_open_status_file','path'=>$path]);
  exit;
}
$txt = '';
while (!feof($fh)) { $txt .= fread($fh, 8192); }
fclose($fh);

$lines = preg_split("/\\r\\n|\\n|\\r/", $txt);
$statuses = [];
foreach ($lines as $line) {
  $line = trim($line);
  if ($line === '') continue;
  // Accept: "2, FUELLING" "2:FUELLING" "2=FUELLING" "2 FUELLING"
  if (!preg_match('/^\\s*(\\d+)\\s*[,=: ]\\s*([A-Za-z_]+)\\s*$/', $line, $m)) continue;
  $id = (string)intval($m[1]);
  $st = strtoupper(trim($m[2]));
  // normalize common variants
  if ($st === 'IDELL') $st = 'IDLE';
  if ($st === 'FUELING' || $st === 'FUEL') $st = 'FUELLING';
  $statuses[$id] = $st;
}

echo json_encode([
  'ok'=>true,
  'source'=>$path,
  'count'=>count($statuses),
  'statuses'=>$statuses,
  'ts'=>time()
]);
