<link rel="stylesheet" type="text/css" href="calendar-win2k-cold-1.css"/>

<!--[if IE]><script type="text/javascript" src="js/excanvas.js"></script><![endif]-->
<script type="text/javascript" src="js/prototype-1.6.0.2.js"></script>
<script type="text/javascript" src="js/flotr-0.1.0alpha.js"></script>

<script type="text/javascript" src="js/calendar/calendar.js"></script>
<script type="text/javascript" src="js/calendar/lang/calendar-en.js"></script>
<script type="text/javascript" src="js/calendar/calendar-setup.js"></script>

<?php

	$db_host = 'localhost';
        $db_user = 'xxxx';
        $db_pwd = 'xxxx';
        $database = 'electricity';
        $table = 'consumption';
        $maxResults = 800;

	$correctionFactor = 30; //Bodge to rempove static virtual power due to X10 modules (unit measures VA only)
	//$correctionFactor = 0;

$now = date("H:i:s d/m/Y");
$thisMorning = date("00:00:00 d/m/Y");

$thisHour = date("H:00:00 d/m/Y");
$startLastHour = date("H:00:00 d/m/Y",strtotime(date("d-m-Y H:00:00")."- 1 hour"));
$endLastHour = date("H:59:59 d/m/Y",strtotime(date("d-m-Y H:00:00")."- 1 hour"));

$yesterdayMorning = date("00:00:00 d/m/Y", strtotime("-1 day", strtotime(date("d-m-Y 00:00:00"))));
$yesterdayEvening =date("H:i:s d/m/Y", strtotime("-1 day", strtotime(date("d-m-Y 23:59:59"))));

$startWeek = date("00:00:00 d/m/Y", mktime(1, 0, 0, date("m"), date("d")-date("w"), date("Y")));
$startMonth = date("01/m/Y 00:00:00");

$startLastMonth =date("00:00:00 01/m/Y", strtotime(date('d-m-Y')."- 1 month") ); 
$endLastMonth=date("23:59:59 d/m/Y", strtotime("-1 day", strtotime(date("m/01/Y"))));

$startLastWeek=date("00:00:00 d/m/Y",strtotime($date." - 1 week"));
$endLastWeek= date('d/m/Y 23:59:59',strtotime(date('d-m-Y 23:59:59', mktime(1, 0, 0, date('m'), date('d')-date('w'), date('Y')))."- 1 day"));


function secs($hours, $mins, $secs){

return (($hours*3600)+($mins*60)+$secs);
}

	
	$datapow = Array();
	$datatemp = Array();
	$datatime = Array();

        if( isset($_GET['to']))
                $to = $_GET['to'];

        else{
                $to = $now;
	}	
	if( isset($_GET['from']))
                $from = $_GET['from'];

        else{
                $from = $thisMorning;
	}

print "<title>From ".$from." to".$to."</title>";
print "<h1>".$from."...to...".$to."</h1>";
if (!mysql_connect($db_host, $db_user, $db_pwd))    die("Can't connect 
to database");
if (!mysql_select_db($database))    die("Can't select database");

$query = "SELECT AVG(power), AVG(temp), SUM(joules) FROM consumption WHERE time <='".toMySQL($to)."'
AND time >='".toMySQL($from)."' AND joules > 0";
//print $query;
$result = mysql_query($query);

while($row = mysql_fetch_array($result)) {
        $avgPow = $row['AVG(power)'];
	$avgTemp = $row['AVG(temp)'];
	$joules = $row['SUM(joules)'];
	$joules = $joules - ($correctionFactor*6);
}
//print $joules;

$query = "SELECT * FROM 
consumption 
WHERE time 
<='".toMySQL($to)."' AND time >= '".toMySQL($from)."'";

$result = mysql_query($query);

$records = mysql_num_rows($result);
$skip = ceil($records / $maxResults);

if($skip == 0)
	$skip =1;

$counter = 0;
$maxY = 0;
$index=0;

while ($row = mysql_fetch_array($result)) {
	$corrected = $row[power]-$correctionFactor;
        if($corrected > $maxY){
                        $maxY = $corrected;
                        $maxYTime=strtotime($row[time]);
                }
	if($counter % $skip ==0){
		 
		$flotr[$index][0]= strtotime($row[time]);
		$flotr[$index][1]= floatval($corrected);
		
		$temp = $row[temp];
		$time = $row[time];
		$power = $corrected;
		$datatime[] = strtotime($row[time]);
	$index++;
	}
	$counter++;
}

$query = "SELECT power, temp FROM consumption ORDER BY id DESC LIMIT 1";
$result = mysql_query($query);
$row = mysql_fetch_array($result);

$temp = $row[temp];
$corrected = $row[power]-$correctionFactor;


function toMySQL($date){
//Take our UK date string and parse it into a MySQL date YY-MM-DD HH:MM:SS
$day =  substr($date,9,2);
$month = substr($date,12,2);
$year = substr($date,15,4); 

$hour = substr($date,0,2); 
$min = substr($date,3,2);
$sec = substr($date,6,2); 

$retVal = $year."-".$month."-".$day." ".$hour.":".$min.":".$sec;
 //print $retVal."<br>";
return $retVal;
}

?>
<table><tr>
<td><a href='<?=$_SERVER["php_self"]?>?from=<?print $thisHour;?>&to=<?print $now;?>'>This Hour</a>|</td>
<td><a href='<?=$_SERVER["php_self"]?>?from=<?print $startLastHour;?>&to=<?print $endLastHour;?>'>Last Hour</a>|</td>

<td><a href='<?=$_SERVER["php_self"]?>?from=<?print $thisMorning;?>&to=<?print $now;?>'>Today</a>|</td>
<td><a href='<?=$_SERVER["php_self"]?>?from=<?print $yesterdayMorning;?>&to=<?print $yesterdayEvening;?>'>Yesterday</a>|</td>

<td><a href='<?=$_SERVER["php_self"]?>?from=<?print $startWeek;?>&to=<?print $now;?>'>This Week</a>|</td>
<td><a href='<?=$_SERVER["php_self"]?>?from=<?print $startLastWeek;?>&to=<?print $endLastWeek;?>'>Last Week</a>|</td>

<td><a href='<?=$_SERVER["php_self"]?>?from=<?print 
$startMonth;?>&to=<?print $now;?>'>This Month</a>|</td>
<td><a href='<?=$_SERVER["php_self"]?>?from=<?print $startLastMonth;?>&to=<?print $endLastMonth;?>'>Last Month</a>|</td>

</table>
<div id="container" style="width:800px;height:400px;"></div>
<br>
<form action="" method="GET">
  <button id="from">From</button>
  <input type="text" id="fromTxt" name="from" value="foo" />
  <button id="to">To</button>
  <input type="text" id="toTxt" name="to" value = "bar"/>
  
<br><br> 
 <input type="Submit" id="Go" name="Go" Value="Go" />
</form>

<?
	
	print"<table border=1>";
	print "<tr>";
	print "<td><b>Current Power:</b><td>".$corrected."<b>W</b></td></tr><tr>";
	print "<td><b>Current Temp:</b><td>".$temp."<b>C</b></td></tr></table>";
	
	print "<br><table border=1><tr>";
	print "<td><b>Readings From:</b><td>".date('H:i:s d/m/Y ',reset($datatime))."</td></tr><tr>";
	print "<td><b>To:</b><td>".date('H:i:s d/m/Y ',end($datatime))."</td></tr><tr>";
	print "<td><b>Avg Power:</b><td>".round($avgPow,1)."<b>W</b></td></tr><tr>";
        print "<td><b>Avg Temp:</b><td>".round($avgTemp,1)."<b>C</b></td></tr><tr>";
	print "<td><b>kWh:</b><td>".round(($joules/3600000),3)."<b>kWh</b></td></tr><tr>";
	print "<td><b>Cost:</b><td>#".round( ($joules/360000000)*14.62,2)."</td></tr><tr>";

	if($maxY < 1000)
		print "<td><b>Max Power:</b><td>".$maxY."<b>W</b></td></tr><tr>";

	else
		print "<td><b>Max Power:</b><td>".($maxY/1000)."<b>kW</b></td></tr><tr>";

	print "<td><b>@:</b><td>".date('H:i:s d/m/Y',$maxYTime)."</td></tr><tr>";
	

	print"<script>var d1 = ".json_encode($flotr).";</script>";
	print"<script>document.getElementById('fromTxt').value ='".$from."';</script>";
	print"<script>document.getElementById('toTxt').value ='".$to."';</script>";

?>
                <script type="text/javascript">

		function timestampHMTickFormatter(inputTimeStamp) {
			mydate = new Date(inputTimeStamp*1000);
			//mydate.setTime(inputTimeStamp);
			hours = mydate.getHours();
			minutes = mydate.getMinutes();
			secs = mydate.getSeconds();

			day = mydate.getDate();
			month = mydate.getMonth() +1;
			year = mydate.getFullYear();

			if (minutes<10) { // adding zero in front of one cipher
				minutes = "0"+minutes;
			}
		//output = hours +":"+minutes+" "+day+"/"+month+"/"+year+"";
		output = hours +":"+minutes+":"+secs;

		return output;
}


			  
var f = Flotr.draw($('container'),[
	{
	data: d1
	}
	],
	
	{
	lines:
		{
		fill: true
		},
	xaxis:
		{
		tickFormatter: timestampHMTickFormatter,
		noTicks: 8
		}

        }
	
);
          

  Calendar.setup(
    {
      inputField : "fromTxt",
      showsTime : true,
      ifFormat    : "%H:%M:%S %d/%m/%Y",
      button      : "from",
      singleClick : false
    }
  );

   Calendar.setup(
    {
      inputField : "toTxt",
      showsTime : true,
      ifFormat    : "%H:%M:%S %d/%m/%Y",
      button      : "to",
      singleClick : false
    }
  );


                </script>
</body></html>
















