<?php

/*
Template to generate a csv file with first column as timestamp
for later addition to an EnTrak variable
*/

require '../Common/preferences.php';
date_default_timezone_set($TimeZone);
$Time = strtotime($_POST[StartTime]); // convert to unix time stamp
$StopTime = strtotime($_POST[StopTime]);
$TimeStep = $_POST[TimeStep];
$Period = $_POST[Period];

if($Time == NULL || $Time == ""){
	echo ("Start date not provided");
	exit;
}
if($StopTime == NULL || $Time == ""){
	echo ("Stop date not provided");
	exit;
}
if($TimeStep == NULL || $Time == ""){
	echo ("Time step not provided");
	exit;
}




//$Time = strtotime("2015-01-01");
//$StopTime = strtotime("2015-01-02");

$StartMonth = date('m', $Time); // 1-12
$StartDay = date('d', $Time); // 1-31
$StartYear = date('Y', $Time);
$StopMonth = date('m', $StopTime); // 1-12
$StopDay = date('d', $StopTime); // 1-31
$StopYear = date('Y',  $StopTime);
if(!checkdate($StartMonth,$StartDay,$StartYear)){
	echo ("Start date is invalid");
	exit;
}
if(!checkdate($StopMonth,$StopDay,$StopYear)){
	echo ("Stop date is invalid");
	exit;
}

/*
$Time = strtotime("2015-01-01");
echo ("Input string {$Time} <br/>");

$II = date($Time);
echo ("Date(Time) {$II} <br/>");

$unixtimestamp = strtotime($Time);
echo ("strtotime(Time) {$unixtimestamp} <br/>");

$IJ = date('Y-m-d H:i:s',$unixtimestamp);
echo ("converted back  {$IJ} <br/>");

$IK = $unixtimestamp + 60;
$IL = date('Y-m-d H:i:s',$IK);
echo ("incremented {$IL} <br/>");

exit;
echo ("Date(Time) {$II} <br/>");
*/


if($TimeStep == NULL || $TimeStep == "" || $TimeStep == "0"){
	$TimeStep = 60; // Default of 1 minute
	echo ("Invalid time step, resetting to 1 minute");
}else{
	if($Period == "Minute"){
		$TimeStep = 60 / $TimeStep; // Get Time step in seconds
	}elseif($Period == "Hour"){
		$TimeStep = 60*60 / $TimeStep; // Get Time step in seconds
	}
}

// Open file name to be saved (downloaded) to client side
$filename = "template.csv";
$file = fopen($filename, "w") or die("Unable to open file!");

$i = 0;
while($Time < $StopTime && $i < 100000){ // More than 100000 lines cannot be created
	$Str = date('Y-m-d H:i:s',$Time);
	fwrite($file,"\t" . $Str . ",\n");
	$Time = $Time + $TimeStep;
	$i++;
}
if($i > 99999)echo("Warning: GenManualTemplate.php cannot generate more than 100000 lines \n");

fclose($file);


if (file_exists($filename)) {
	header('Content-Description: File Transfer');
	header('Content-Type: application/octet-stream');
	header('Content-Disposition: attachment; filename='.basename($filename));
	header('Content-Transfer-Encoding: binary');
	header('Expires: 0');
	header('Cache-Control: must-revalidate');
	header('Pragma: public');
	header('Content-Length: ' . filesize($filename));
	ob_clean();
	flush();
	readfile($filename);
	unlink($filename);	//remove file from server
	exit;
}



?>