<?php
include("../../../DTM/scripts/ReadMe_v2.php");

//Commented out below on the 4th jan 2023
/* 

chdir("../databases");

if(!$_GET["SiteName"]) {
	echo "SiteName not placed in GET<br>";
	echo "to use this file, you need to add ?SiteName=yourfilename.csv&Key=ParameterYouNeed<br>";
	echo "Key is not required - last line will be returned<br>";
	echo "if key is inserted, this function looks for the last time !empty data was recorded<br>";
	exit;
}
$filename = $_GET["SiteName"];

if($_GET["Key"]) {
	$key_me = $_GET["Key"];
}else{
	echo readlastlineoffile($filename);
	exit;
}

//GET HEADER OF FILE
$header_of_file = readlineoffile($filename,0);
$headerarray_file = explode(",",$header_of_file);
$headerarray_file = array_map('trim', $headerarray_file);

//FIND POSITION IN HEADER
$i = 0;
$position = 0;
foreach($headerarray_file as $headerarray_file_temp){
	if($headerarray_file_temp == $key_me){
		$position = $i;	
	}
	$i = $i+1;
}

if($position == 0){
	echo "error - Key not found";
	exit;
}

//GET LAST LINE OF DATA WHEN KEY WAS NOT BLANK
$cur_line = '';
$data = file($filename);
$lines = count($data);
$last_data_line_when_key_logged = "";
$i=0;
for($i = 0; $i<1000; $i++){	
	$cur_line = $data[$lines -1 - $i];
	$cur_line = explode(",",$cur_line);
	if(trim($cur_line[$position]) != ""){
		$last_data_line_when_key_logged = $cur_line[$position];
		$i=2000;
	}
}
echo $last_data_line_when_key_logged;



function readlineoffile($Fname,$LineNo){
		$line = '';
		$data = file($Fname);
		$line = $data[$LineNo];
		return $line;	
}

function writelineoffile($Fname,$LineNo,$newlineinfo){
	$data = file($Fname);
	$data[$LineNo] = $newlineinfo;
	file_put_contents($Fname, $data);
}

function readlastlineoffile($Fname){
	$line = '';
	$data = file($Fname);
	$line = $data[count($data)-1];
	return $line;	
}

 */
?>