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

error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);

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'];
$year=$_REQUEST['year'];
$month=$_REQUEST['month'];

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_fill_color_top,st.st_fill_color_bottom,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'];
    $fill_color_top=$row['st_fill_color_top'];
    $fill_color_bottom=$row['st_fill_color_bottom'];
  }                                                                

  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 from units u where u.id='.$to_unit
  );
  $q -> execute();

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

  if ($type == 'month') { 

    $next_year = $year;
    $next_month = $month+1;

    if ($month==13) {
    
      $next_year++;
      $next_month=1;
    
    }

    $curr = date("Ym");
    
    if ($curr>$next_year.$next_month) {
    
      $cachefilename='meteo.month.'.$sensor.'.'.$param.'.'.$to_unit.'.'.$year.'-'.$month.'.'.$img_format;
    
    }

    $q = $db -> prepare(
      '
        select 
          x,
          unitconv(min(min),'.$from_unit.','.$to_unit.') min_value,
          unitconv(max(max),'.$from_unit.','.$to_unit.') max_value
        from  (
          select 
            unix_timestamp(day) x,
            min,
            max
          from 
            sensors_ranges 
          where 
            day>=str_to_date(\''.$year.$month.'\',\'%Y%m\')
            and day<str_to_date(\''.$next_year.$next_month.'\',\'%Y%m\')
            and sensor='.$sensor.'
            and parameter='.$param.'
          ) t group by x
        order by x'
    );
    
  } elseif ($type == "year") {

    $next_year = $year+1;

    $curr = date("Y");
        
    if ($curr>$next_year) {
                
        $cachefilename='meteo.year.'.$sensor.'.'.$param.'.'.$year.'.'.$img_format;
                          
    }

    $q = $db -> prepare(
      '
        select 
          x,
          unitconv(min(min),'.$from_unit.','.$to_unit.') min_value,
          unitconv(max(max),'.$from_unit.','.$to_unit.') max_value
        from  (
          select 
            unix_timestamp(
              DATE_SUB(day, INTERVAL DAYOFWEEK(day)-1 DAY)
              ) x,
            min,
            max
          from 
            sensors_ranges
          where 
            day>=str_to_date(\''.$year.'\',\'%Y\')
            and day<str_to_date(\''.$next_year.'\',\'%Y\')
            and sensor='.$sensor.'
            and parameter='.$param.'
          ) t group by x
        order by x'
    );
  
  }

  $g = new Graph(640,480);

  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'];
    $mindata[] = $row['min_value'];
    $maxdata[] = $row['max_value'];
    
  }                                                                


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

  //$g->img->SetAntiAliasing();

  // We need a linlin scale since we provide both
  // x and y coordinates for the data points.
  $g->SetScale('datlin');
  $g->xaxis->SetLabelAngle(90);
  $g->xaxis->SetPos("min");
  $g->xaxis->scale->SetTimeAlign( MINADJ_1 );

  // We use a scatterplot to illustrate the original
  // contro points.

  $bplot = new LinePlot($maxdata,$xdata);
  $g->Add($bplot);
  $bplot->SetColor($fill_color_top);
  $bplot->SetFillGradient($fill_color_top.'@0.2',$fill_color_bottom.'@0.9',100,TRUE);
  $bplot->SetFillFromYMin(TRUE);	
  $bplot->SetWeight(4);

  $aplot = new LinePlot($mindata,$xdata);
  $g->Add($aplot);
  $aplot->SetColor($fill_color_bottom);
  $aplot->SetFillGradient($fill_color_bottom.'@0.2','white@0.9',100,TRUE);
  $aplot->SetFillFromYMin(TRUE);	
  $aplot->SetWeight(4);

  $g->SetMargin(60,60,60,130);
  $g->title->Set($sensor_name.'/'.$param_name.', '.$param_unit);
  $g->title->SetFont(FF_DV_SANSSERIF,FS_BOLD,12);
  $g->subtitle->Set('(минимальные и максимальные значения за период)');
  $g->subtitle->SetColor('darkred');
  $g->SetMarginColor('silver');

  $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('Сенсор не выбран!');

}  

?>