<?php
date_default_timezone_set('America/New_York');

$FILE  = '/var/www/html/boiler.txt';
$HOURS = 48;
$now   = time();
$start = $now - ($HOURS * 3600);

$t = [];
$c0 = [];
$c1 = [];
$c2 = [];

if (is_readable($FILE)) {
  $fh = fopen($FILE, 'r');
  if ($fh) {
    while (($line = fgets($fh)) !== false) {
      $line = trim($line);
      if ($line === '') continue;

      $parts = explode(',', $line, 3);
      if (count($parts) < 3) continue;

      $epoch = intval($parts[0]);
      if ($epoch < $start || $epoch > ($now + 300)) continue;

      $qs = trim($parts[2]);

      // strip trailing " 64.30.91.207" etc if present
      $sp = strpos($qs, ' ');
      if ($sp !== false) $qs = substr($qs, 0, $sp);

      $params = [];
      parse_str($qs, $params);

      if (!isset($params['c0'], $params['c1'], $params['c2'])) continue;

      $t[]  = $epoch;
      $c0[] = floatval($params['c0']);
      $c1[] = floatval($params['c1']);
      $c2[] = floatval($params['c2']);
    }
    fclose($fh);
  }
}

if (count($t) < 2) {
  header('Content-Type: image/png');
  $im = imagecreatetruecolor(1000, 240);
  $white = imagecolorallocate($im, 255, 255, 255);
  $black = imagecolorallocate($im, 0, 0, 0);
  imagefilledrectangle($im, 0, 0, 999, 239, $white);
  imagestring($im, 5, 20, 30, "3temps.php: no data found in last {$HOURS} hours", $black);
  imagestring($im, 3, 20, 70, "File: $FILE", $black);
  imagepng($im);
  imagedestroy($im);
  exit;
}

$minT = min($t);
$maxT = max($t);

$all = array_merge($c0, $c1, $c2);
$minY = min($all);
$maxY = max($all);

$yr = max(0.01, $maxY - $minY);
$pad = $yr * 0.10;
$minY -= $pad;
$maxY += $pad;

// Image + generous margins
$W = 1400; $H = 800;
$ML = 110; // left
$MR = 60;  // right
$MT = 70;  // top
$MB = 150; // bottom

$PW = $W - $ML - $MR;
$PH = $H - $MT - $MB;

$im = imagecreatetruecolor($W, $H);
imageantialias($im, true);

$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
$grid  = imagecolorallocate($im, 220, 220, 220);
$axis  = imagecolorallocate($im, 40, 40, 40);

$col0  = imagecolorallocate($im, 30, 90, 200);
$col1  = imagecolorallocate($im, 200, 80, 40);
$col2  = imagecolorallocate($im, 20, 140, 80);

imagefilledrectangle($im, 0, 0, $W-1, $H-1, $white);

$X = function($tt) use ($minT, $maxT, $ML, $PW) {
  if ($maxT == $minT) return $ML;
  return $ML + intval(($tt - $minT) * $PW / ($maxT - $minT));
};
$Y = function($yy) use ($minY, $maxY, $MT, $PH) {
  if ($maxY == $minY) return $MT + intval($PH/2);
  return $MT + intval(($maxY - $yy) * $PH / ($maxY - $minY));
};

imagerectangle($im, $ML, $MT, $ML+$PW, $MT+$PH, $axis);

// Y grid + labels
$yTicks = 8;
for ($i=0; $i<=$yTicks; $i++) {
  $yy = $minY + (($maxY - $minY) * ($i / $yTicks));
  $py = $Y($yy);
  imageline($im, $ML, $py, $ML+$PW, $py, $grid);
  imagestring($im, 3, 15, $py-7, sprintf("%.1f", $yy), $black);
}

// X grid every 2 hours
$step = 2 * 3600;
$firstTick = intval(ceil($minT / $step) * $step);
for ($tt = $firstTick; $tt <= $maxT; $tt += $step) {
  $px = $X($tt);
  imageline($im, $px, $MT, $px, $MT+$PH, $grid);
  imagestring($im, 3, $px-30, $MT+$PH+18, date("m/d H:i", $tt), $black);
}

function plot_series($im, $t, $v, $X, $Y, $color) {
  $n = count($t);
  $prev = null;
  for ($i=0; $i<$n; $i++) {
    $px = $X($t[$i]);
    $py = $Y($v[$i]);
    if ($prev !== null) imageline($im, $prev[0], $prev[1], $px, $py, $color);
    $prev = [$px, $py];
  }
}

plot_series($im, $t, $c0, $X, $Y, $col0);
plot_series($im, $t, $c1, $X, $Y, $col1);
plot_series($im, $t, $c2, $X, $Y, $col2);

$title = "3 Temps (c0, c1, c2) — last {$HOURS}h  |  " . date("Y-m-d H:i:s T", $now);
imagestring($im, 5, $ML, 20, $title, $black);

// Legend
$lx = $ML + 10; $ly = $MT + 10; $lw = 320; $lh = 55;
imagerectangle($im, $lx, $ly, $lx+$lw, $ly+$lh, $grid);
imagestring($im, 4, $lx+10,  $ly+8, "c0", $col0);
imagestring($im, 4, $lx+80,  $ly+8, "c1", $col1);
imagestring($im, 4, $lx+150, $ly+8, "c2", $col2);
imagestring($im, 3, $lx+10, $ly+30, sprintf("Y range: %.1f .. %.1f", $minY, $maxY), $black);

imagestring($im, 4, $ML + intval($PW/2) - 120, $MT+$PH+60, "Time (tick ~ every 2 hours)", $black);
imagestring($im, 4, 10, $MT + intval($PH/2) - 10, "Temp", $black);

header('Content-Type: image/png');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

imagepng($im);
imagedestroy($im);
