<?php
// api_pump_status.php
// Reads pump status file produced by external process. Returns per-pump status + icon filename.
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

$paths = [
  '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','checked'=>$paths]);
  exit;
}

clearstatcache(true, $path);

function read_file_fresh($path) {
  // Prefer fopen to ensure handle is short-lived.
  $fh = @fopen($path, 'rb');
  if ($fh) {
    $data = '';
    while (!feof($fh)) { $data .= fread($fh, 8192); }
    fclose($fh);
    return $data;
  }
  // Fallback
  $data = @file_get_contents($path);
  if ($data !== false) return $data;

  // Windows fallback via type (if allowed)
  $cmd = 'type "'.str_replace('"','\"',$path).'"';
  $out = @shell_exec($cmd);
  if ($out !== null) return $out;
  return false;
}

$raw = read_file_fresh($path);
if ($raw === false) {
  echo json_encode(['ok'=>false,'error'=>'cannot_read_status_file','path'=>$path]);
  exit;
}

$lines = preg_split("/\\r\\n|\\n|\\r/", $raw);
$statuses = [];
foreach ($lines as $line) {
  $line = trim($line);
  if ($line === '') continue;
  // Format: "2, FUELLING" or "2: FUELLING" or "2=FUELLING"
  if (preg_match('/^\\s*(\\d+)\\s*[,=:]\\s*([A-Za-z_]+)\\s*$/', $line, $m)) {
    $id = (string)intval($m[1]);
    $st = strtoupper(trim($m[2]));
    $statuses[$id] = $st;
  }
}

$map = [
  'IDLE'     => 'surtidor_300x300.jpg',
  'IDELL'    => 'surtidor_300x300.jpg',
  'IDLEL'    => 'surtidor_300x300.jpg',
  'CALLING'  => 'surtidor_naranja.jpg',
  'STARTING' => 'surtidor_naranja.jpg',
  'FUELLING' => 'surtidor_azul.jpg',
  'FUELING'  => 'surtidor_azul.jpg',
  'FUEL'     => 'surtidor_azul.jpg',
  'CLOSED'   => 'surtidor_rojo.jpg',
];

$icons = [];
foreach ($statuses as $id=>$st) {
  $icons[$id] = $map[$st] ?? 'surtidor_300x300.jpg';
}

echo json_encode([
  'ok'=>true,
  'path'=>$path,
  'mtime'=>@filemtime($path) ?: null,
  'statuses'=>$statuses,
  'icons'=>$icons
]);
