<?php // content="text/plain; charset=utf-8"

error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE & ~E_DEPRECATED);

include ('config_local.php');

require_once ('jpgraph/jpgraph.php');
require_once ('jpgraph/jpgraph_line.php');
require_once ('jpgraph/jpgraph_date.php');
require_once ('jpgraph/jpgraph_scatter.php');
require_once ('jpgraph/jpgraph_regstat.php');

if (! ($db = new PDO("mysql:host=$mysql_host;port=$mysql_port;dbname=$mysql_schema",$mysql_user,$mysql_pwd,array( PDO::ATTR_PERSISTENT => false)))) {

  die('Не могу подключиться к БД');

}  

$supported = imagetypes();
if( $supported & IMG_PNG )    $img_format="png";
elseif( $supported & IMG_GIF ) $img_format="gif";
elseif( $supported & IMG_JPG ) $img_format="jpeg";
elseif( $supported & IMG_WBMP ) $img_format="wbmp";
elseif( $supported & IMG_XPM ) $img_format="xpm";

$cachefilename = NULL;

$db -> exec('SET CHARACTER SET utf8');
  
$type = $_REQUEST['type'];
$sensor=$_REQUEST['sensor'];
$param=$_REQUEST['param'];

if ($type and $param) {
  
  $sensor = intval($sensor);
  $param = intval($param);

  $q = $db -> prepare(
    'select s_description from sensors where id='.$sensor
  );
  $q -> execute();

  while ($row = $q -> fetch(PDO::FETCH_ASSOC)) {
    $sensor_name = $row['s_description'];
  }                                                                

  $q = $db -> prepare(
    'select st.st_dot_color,st.st_line_color,st.st_description,u.id,u.unit_group from st_parameters st,units u where st.id='.$param.' and st.st_unit=u.id'
  );
  $q -> execute();

  while ($row = $q -> fetch(PDO::FETCH_ASSOC)) {
    $param_name = $row['st_description'];
    $from_unit = $row['id'];
    $unit_group = $row['unit_group'];
    $dot_color = $row['st_dot_color'];
    $line_color = $row['st_line_color'];
  }                                                                

  if (!empty($_COOKIE['unit_'.$unit_group])) {
    $to_unit=intval($_COOKIE['unit_'.$unit_group]);
  } else {
    $to_unit=$from_unit;
  }  

  $q = $db -> prepare(
    'select u.name_short,u.prec from units u where u.id='.$to_unit
  );
  $q -> execute();

  while ($row = $q -> fetch(PDO::FETCH_ASSOC)) {
    $param_unit = $row['name_short'];
    $precision = $row['prec'];
  }                                                                
  
  $xdata = array();
  $ydata = array();

  if ($type == 'last24') { 

    $q = $db -> prepare(
      'select unix_timestamp(timestamp) as x,unitconv(value,'.$from_unit.','.$to_unit.') as y from sensor_values where timestamp>adddate(now(), -1) and sensor_id='.$sensor.' and parameter_id='.$param.' order by timestamp'
    );

    $bottomheight = 130;
    $topheight = 40;
    $sizex = 1000;
    $sizey = 800;
    $scale = True;
    
  } elseif ($type == 'last24small') {

    $q = $db -> prepare(
      'select unix_timestamp(timestamp) as x,unitconv(value,'.$from_unit.','.$to_unit.') as y from sensor_values where timestamp>adddate(now(), -1) and sensor_id='.$sensor.' and parameter_id='.$param.' order by timestamp'
    );

    $bottomheight = 20;
    $topheight = 20;
    $sizex = 400;
    $sizey = 300;
    $scale = False;
    
  } elseif ($type == 'range') {

    $curr = intval(date('YmdHis'));

    $from = intval($_REQUEST['fromdate']);
    $to = intval($_REQUEST['todate']);

    if ($curr>$to) {
    
        $cachefilename='meteo.'.$sensor.'.'.$param.'.'.$to_unit.'.'.$from.'-'.$to.'.'.$img_format;
    
    }

    $q = $db -> prepare(
      'select unix_timestamp(timestamp) as x,unitconv(value,'.$from_unit.','.$to_unit.') as y from sensor_values where timestamp>=str_to_date("'.$from.'","%Y%m%d%H%i%s") and timestamp<=str_to_date("'.$to.'","%Y%m%d%H%i%s") and sensor_id='.$sensor.' and parameter_id='.$param.' order by timestamp'
    );
  
    $bottomheight = 60;
    $topheight = 40;
    $sizex = 1000;
    $sizey = 800;
    $scale = True;
  
  }

  $g = new Graph($sizex,$sizey);
  
  if ($cachefilename) {
      if ($g->cache->IsValid($cachefilename)) {
  
          $g->cache->StreamImgFile($g->img,$cachefilename);
          return;
  
      } else {
      
          $timeout = 8640000;
          $g->SetupCache($cachefilename,$timeout);
      
      }
  }

  $q -> execute();
    
  while ($row = $q -> fetch(PDO::FETCH_ASSOC)) {
    
    $xdata[] = $row['x'];
    $ydata[] = $row['y'];
    
  }                                                                


  for ($i = 0; $i < count($xdata); ++$i) {

    $total_weight=0;
    $sum=0;
    $maxdelta = 1800;
    
    for ($j = $i; $j < count($xdata); ++$j) {
    
      $delta = abs($xdata[$i]-$xdata[$j]);
      if ($delta > $maxdelta) { break; }
    
      $weight = 1-$delta/$maxdelta;
      $total_weight += $weight;
      $sum += $weight*$ydata[$j];
      
    }

    for ($j = $i-1; $j >=0 ; --$j) {
    
      $delta = abs($xdata[$i]-$xdata[$j]);
      if ($delta > $maxdelta) { break; }
    
      $weight = 1-$delta/$maxdelta;
      $total_weight += $weight;
      $sum += $weight*$ydata[$j];
      
    }
    
    $new_val = $sum/$total_weight;
    $f_ydata[$i] = $new_val; 
    
  }

  // Create the graph
  $g->graph_theme = null;

  $g->img->SetAntiAliasing();

  // We need a datlin scale since we provide both
  // x and y coordinates for the data points, but x is unix timestamp.
  $g->SetScale('datlin');
  if ($scale) {
    $g->xaxis->SetLabelAngle(90);
  } else {
    $g->xaxis->HideLabels(True);
  }
  $g->xaxis->SetPos("min");
  $g->yaxis->SetLabelFormat("%0.".$precision."f");
#  $g->xaxis->scale->SetTimeAlign( HOURADJ_1 );


  if ($type!="last24small") {

    // We use a scatterplot to illustrate the original
    // contro points.
    $splot = new ScatterPlot($ydata,$xdata);
    $g->Add($splot);

    // 
    $splot->mark->SetFillColor($dot_color);
    $splot->mark->SetColor($dot_color);
    $splot->mark->SetType(MARK_FILLEDCIRCLE);
    $splot->mark->SetSize(2);

  }

  $fplot = new LinePlot($f_ydata,$xdata);
  $g->Add($fplot);
  $fplot->SetColor($line_color);
  $fplot->SetWeight(2);

  $g->SetMargin(50,30,$topheight,$bottomheight);
  if ($scale) {
    $g->title->Set($sensor_name.'/'.$param_name.', '.$param_unit);
    $g->title->SetFont(FF_DV_SANSSERIF,FS_BOLD,12);
  }  
  $g->SetMarginColor('lightgray');

  $g->xgrid->Show();
  $g->xgrid->SetLineStyle('dotted');
  $g->ygrid->Show();
  $g->ygrid->SetLineStyle('dotted');

  // Add the plots to the graph and stroke
  $g->Stroke();
  
} else {

  header("Content-Type: text/html; charset=UTF-8");
  die('Сенсор не выбран!');

}  

?>