<?php
require_once "../../config/settings.inc.php";
require_once "../../include/database.inc.php";
require_once "../../include/network.php";
require_once "../../include/forms.php";
require_once "../../include/jpgraph/jpgraph.php";
require_once "../../include/jpgraph/jpgraph_line.php";
require_once "../../include/jpgraph/jpgraph_date.php";
$nt = new NetworkTable('IA_DCP');
$pgconn = iemdb("hads");

$station = get_str404('station', 'AESI4');
$varname = get_str404('var', 'tmpf');
$sday = strtotime(get_str404('sday', '2010-01-01'));
$eday = strtotime(get_str404('eday', '2010-01-02'));

$stname = iem_pg_prepare(
    $pgconn,
    "SELECT * from raw" . date("Y", $sday) .
        " WHERE station = $1 and valid BETWEEN $2 and $3 and key = $4 " .
        "ORDER by valid ASC"
);

$rs = pg_execute($pgconn, $stname, array(
    $station,
    date('Y-m-d', $sday),
    date('Y-m-d', $eday),
    $varname
));

$data = array();
$times = array();
while ($row = pg_fetch_assoc($rs)) {
    $times[] = strtotime($row["valid"]);
    $data[] = $row["value"];
}

$graph = new Graph(640, 480);
$graph->SetScale("datelin");

$graph->SetMarginColor('white');

$graph->img->SetMargin(40, 40, 45, 120);

$title = sprintf(
    "%s [%s] \nPlot of SHEF Variable [%s]",
    array_key_exists($station, $nt->table) ? $nt->table[$station]['name'] : "",
    $station,
    $varname
);
$graph->title->Set($title);

$graph->xaxis->scale->SetDateFormat("M d h A");

$graph->xaxis->SetTitle(sprintf(
    "Time Interval: %s - %s",
    date('d M Y', $sday),
    date('d M Y', $eday)
));

$graph->xaxis->SetTitleMargin(90);
$graph->xaxis->SetLabelAngle(90);

$lineplot = new LinePlot($data, $times);
$lineplot->SetColor("red");
$lineplot->SetWeight(2);
$graph->Add($lineplot);

$graph->Stroke();
