<?php
include('global.php');
  
if(array_key_exists('Debug', $_GET)) $Debug = $_GET['Debug']; 
  else $Debug = 0;
  
$DefaultWidth = 750;
$DefaultHeight = 200;
$K = 0.9;   // Coeficient for decreasing graph height 
$FontFile = 'arial.ttf';
$FontSize = 10;

if(!array_key_exists('From',$_GET)) die('Musíte zadat čas počátku');
$StartTime = addslashes($_GET['From']);
if(!array_key_exists('To',$_GET)) die('Musíte zadat čas konce');
$EndTime = addslashes($_GET['To']);
if($EndTime < $StartTime) $EndTime = $StartTime + 60;
$TimeDifference = $EndTime - $StartTime;
if(!array_key_exists('Measure',$_GET)) die('Musíte zadat měřenou veličinu');
$MeasureId = addslashes($_GET['Measure']);
if(!array_key_exists('Width', $_GET)) $Width = $DefaultWidth; 
else $Width = addslashes($_GET['Width']);
if(!array_key_exists('Height', $_GET)) $Height = $DefaultHeight;
else $Height = addslashes($_GET['Height']);
$VerticalLinesCount = round($Height / ($FontSize + 4));

$StopWatchStart = GetMicrotime();

$Measure = GetMeasureById($MeasureId);

$Level = floor(log(($EndTime - $StartTime) / $DivisionCount / 60) / log($LevelReducing)) - 1;
if($Level < 0) $Level = 0;
if($Level > $MaxLevel) $Level = $MaxLevel;
//$Level = 0;


$Points = GetValues($Measure, $StartTime, $EndTime, $Level);

if($Debug) echo('Points count: '.count($Points).'<br>'); 
//if($Debug) foreach($Points as $Index => $Item) 
//  echo($Index.': '.$Item['min'].'<br>');

// Calculate total max, avg, min value
$MaxValue = -1000000000;
$AvgValue = 0;
$MinValue = 1000000000;
foreach($Points as $Index => $Item)
{
  $Points[$Index]['min'] =  $Points[$Index]['min'] / $Measure['display_divider'];
  $Points[$Index]['avg'] =  $Points[$Index]['avg'] / $Measure['display_divider'];
  $Points[$Index]['max'] =  $Points[$Index]['max'] / $Measure['display_divider'];
  if($Points[$Index]['avg'] > $MaxValue) $MaxValue = $Points[$Index]['avg'];
  if($Points[$Index]['avg'] < $MinValue) $MinValue = $Points[$Index]['avg'];
  if($Points[$Index]['max'] > $MaxValue) $MaxValue = $Points[$Index]['max'];
  if($Points[$Index]['min'] < $MinValue) $MinValue = $Points[$Index]['min'];
  $AvgValue = $AvgValue + $Points[$Index]['avg'];
}
$MinValue = round($MinValue * $Measure['display_divider']) / $Measure['display_divider'];
$MaxValue = round($MaxValue * $Measure['display_divider']) / $Measure['display_divider'];
$AvgValue = round($AvgValue / count($Points) * $Measure['display_divider']) / $Measure['display_divider'];

// Generate polygon and recalculate y values to fit graph height 
$PointsMin = array(0, $Height-1);
$PointsAvg = array(0, $Height-1);
$PointsMax = array(0, $Height-1);
if(($MaxValue - $MinValue) == 0) $MaxValue = $MinValue + 1;
{ 
  foreach($Points as $Index => $Item)
  {
    $PointsMin[] = $Index*$Width/$DivisionCount;
    $PointsMin[] = $Height - 1 - ($Points[$Index]['min'] - $MinValue) / ($MaxValue - $MinValue) * $Height * $K;
    $PointsAvg[] = $Index*$Width/$DivisionCount;
    $PointsAvg[] = $Height - 1 - ($Points[$Index]['avg'] - $MinValue) / ($MaxValue - $MinValue) * $Height * $K;
    $PointsMax[] = $Index*$Width/$DivisionCount;
    $PointsMax[] = $Height - 1 - ($Points[$Index]['max'] - $MinValue) / ($MaxValue - $MinValue) * $Height * $K;
    //echo($Index.' - '.$Item.' '.$Points[$Index].'<br>');
  }
}
$PointsMin[] = $Width-1;
$PointsMin[] = $Height-1;
$PointsAvg[] = $Width-1;
$PointsAvg[] = $Height-1;
$PointsMax[] = $Width-1;
$PointsMax[] = $Height-1;
$PointsMin[] = $Width-1;
$PointsMin[] = $Height-1;
$PointsAvg[] = $Width-1;
$PointsAvg[] = $Height-1;
$PointsMax[] = $Width-1;
$PointsMax[] = $Height-1;


array_unshift($Points, $Height - 1);
array_unshift($Points, 0);
$Points[] = $Width - 1;
$Points[] = $Height - 1;

// Generate image
if(!$Debug) 
{
  header("Content-type: image/png");
  header("Cache-Control: no-cache");	// Dynamic graph - no cache 
  $Image = @imagecreate($Width, $Height + 14);
  $BackgroundColor = imagecolorallocate($Image, 255, 255, 255);
  $Black = imagecolorallocate($Image, 0, 0, 0);
  $White = imagecolorallocate($Image, 255, 255, 255);
  $Gray = imagecolorallocate($Image, 200, 200, 200);
  $DarkGray = imagecolorallocate($Image, 100, 100, 100);
  $LightBlue = imagecolorallocate($Image, 150, 150, 255);
  $Blue = imagecolorallocate($Image, 0, 0, 255);
  $LightRed = imagecolorallocate($Image, 255, 150, 150);
  $Red = imagecolorallocate($Image, 255, 0, 0);
  $Green = imagecolorallocate($Image, 0, 200, 0);
  $LightGreen = imagecolorallocate($Image, 150, 255, 150);

  imagefilledpolygon($Image, $PointsMax, count($PointsMax) / 2, $LightRed);
  imagefilledpolygon($Image, $PointsAvg, count($PointsAvg) / 2, $LightGreen);
  imagefilledpolygon($Image, $PointsMin, count($PointsMin) / 2, $LightBlue);
  
  $TimeMarks = array(1, 60, 60*60, 60*60*24, 60*60*24*7, 60*60*24*30, 60*60*24*365, 60*60*24*365*10);
  
  $TimeRange = $EndTime - $StartTime;
  $TimeMarksIndex = 0;
  while(($TimeRange / $TimeMarks[$TimeMarksIndex]) > 1) $TimeMarksIndex += 1;
  if($TimeMarksIndex < 2) $TimeMarksIndex = 2;
  $MajorTimeMarks = $TimeMarks[$TimeMarksIndex - 1];
  $MinorTimeMarks = $TimeMarks[$TimeMarksIndex - 2];  
   
  $TimeShift = AlignTime($StartTime, $MajorTimeMarks) - $StartTime; 
  //imagestring($Image, 10, 40, 50, $TimeShift, $Black);
  
  // Zobraz měřítko Y
  $VerticalLinesDistance = $Height / $VerticalLinesCount;
  for($I=1; $I<=$VerticalLinesCount; $I++)
  {
    $Y = $Height - 1 - ($VerticalLinesDistance * $I);
    for($X=1; $X < $Width; $X = $X + 3) imagesetpixel($Image, $X, $Y, $Gray);
    //imageline($Image, 30, $Y, $Width-1, $Y, IMG_COLOR_STYLED);
  } 

  $TimeShift = AlignTime($StartTime, $MinorTimeMarks) - $StartTime; 

  /*
  if(($MinorTimeMarks / $TimeRange * $Width) > 3)
  for($Time = $StartTime; $Time < $EndTime; $Time += $MinorTimeMarks)
  {
    $X = round(($Time - $StartTime + $TimeShift) / $TimeRange * $Width) % $Width; 
    for($Y=0; $Y < $Height; $Y = $Y + 3) imagesetpixel($Image, $X, $Y, $Gray);
    //imageline($Image, 30, $Y, $Width-1, $Y, IMG_COLOR_STYLED);
    //imagestring($Image, 2, 2, $Y - 6, round(($I * $VerticalLinesDistance + $MinValue)*$Measure['divider']) / $Measure['divider'], $Black);
  } 
  */
  
  // Zobraz měřítko X
  $LastTextEnd = 0;
  for($Time = $StartTime; $Time < $EndTime; $Time += $MajorTimeMarks)
  {
    $X = round(($Time - $StartTime + $TimeShift) / $TimeRange * $Width) % $Width; 
    //imageline($Image, 30, $Y, $Width-1, $Y, IMG_COLOR_STYLED);
    if(($MajorTimeMarks > 60*60*24)) $Text = date('j.n.Y', $Time + $TimeShift);
      else $Text = date('j.n.Y G:i', $Time + $TimeShift);
    $BoundBox = imagettfbbox($FontSize, 0, $FontFile, $Text);
    if($LastTextEnd < ($X - ($BoundBox[2] - $BoundBox[0] + 20) / 2))
    {
      for($Y=0; $Y < $Height; $Y = $Y + 1) imagesetpixel($Image, $X, $Y, $Gray);
      imagettftext($Image, $FontSize, 0, $X - ($BoundBox[2] - $BoundBox[0]) / 2,  $Height - 2, $Black, $FontFile, $Text);
      $LastTextEnd = $X + ($BoundBox[2] - $BoundBox[0]) / 2;
    }
    else for($Y=0; $Y < $Height; $Y = $Y + 3) imagesetpixel($Image, $X, $Y, $Gray);
  } 
  
  // Popisky osy Y
  for($I=1; $I<=$VerticalLinesCount; $I++)
  {
    $Y = $Height - 1 - ($VerticalLinesDistance * $I);
    //$Y = $Height - 1 - ($VerticalLinesDistance * $I / ($MaxValue - $MinValue) * $K * $Height);
    $Text = round(($I * $VerticalLinesDistance / $Height / $K * ($MaxValue - $MinValue) + $MinValue));
    $BoundBox = imagettfbbox($FontSize, 0, $FontFile, $Text);
    if(($Y - ($BoundBox[5] - $BoundBox[1]) / 2) > 10)
      imagettftext($Image, $FontSize, 0, 2,  $Y - ($BoundBox[5] - $BoundBox[1]) / 2, $Black, $FontFile, $Text);
  } 
  $GenerationTime = floor((GetMicrotime() - $StopWatchStart) * 1000  ) / 1000;

  imagettftext($Image, $FontSize, 0, $Width-94, 14, $Red, $FontFile, "Max. ".$MaxValue.' '.$Measure['unit']);
  imagettftext($Image, $FontSize, 0, $Width-194, 14, $Green, $FontFile, "Avg.  ".$AvgValue.' '.$Measure['unit']);
  imagettftext($Image, $FontSize, 0, $Width-294, 14, $Blue, $FontFile, "Min.  ".$MinValue.' '.$Measure['unit']);
  imagestring($Image, 2, 50, 20, 'Vygenerováno za '.$GenerationTime.' sekund', $Black);
  //imagestring($Image, 2, 50, 30, 'Level: '.$Level, $Black);

  imagettftext($Image, $FontSize, 0, 50, 14, $Black, $FontFile, to_utf8($Measure['description']));
  imagerectangle($Image, 0, 0, $Width - 1, $Height - 1, $Black);   // Frame border
  imagepng($Image);
  imagedestroy($Image);
}

?>
