<?php
	/* (C) DairyWindow 2012-2017 */

	require "inc/connect.php";
	require "inc/texttonumber.php";
	//require "inc/numbertotext.php";

	$title = "Result trends";
	require "inc/head.php";
	$menu = "trends";
	require "inc/menu.php";

	if($debug) showdebug();

	if(isset($_GET['from'])) $datefrom = date('Y-m-d',strtotime($_GET['from']));
	else $datefrom = date('Y-m-d',strtotime('last week'));

	if(isset($_GET['to'])) $dateto = date('Y-m-d',strtotime($_GET['to']));
	else $dateto = date('Y-m-d',strtotime('yesterday'));

	if($datefrom > $dateto) $datefrom = $dateto;

	$lineColors = array("#0b62a4", "#7A92A3", "#4da74d", "#afd8f8", "#edc240", "#cb4b4b", "#9440ed",
											"#62a40b", "#92A37A", "#a74d4d", "#d8f8af", "#c240ed", "#4b4bcb", "#40ed94",
											"#a40b62", "#A37A92", "#4d4da7", "#f8afd8", "#40edc2", "#4bcb4b", "#ed9440"); // copied from morris.js

?>

	<div id="topDIV" class="page-header">
		<h1 class="text-center"><?php echo $title; ?></h1>
	</div>

	<div id="main" >
		<div id="form" class="col-md-3 hidden-print" role='complementary'>
			<form class="form-horizontal" method="get" id="tform" >
				<div class="form-group">
					<label for="spec" class="col-sm-2 control-label">Product</label>
					<div class="col-sm-10">
						<?php
							$sql="
								Select
									dw_spec.specID,
									dw_spec.specText,
									dw_spec.specShortDesc
								From
									dw_spec
								Where
									dw_spec.specSite = ? And
									dw_spec.specActive = 1
								Order By
									dw_spec.specStyle,
									dw_spec.specOrder,
									dw_spec.specText
							";
							if(!$qrytest = mysqli_prepared_query($link, $sql, "i", array($_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
						?>
						<select name="p" id="spec" class="form-control" >
							<option value="0" >All products</option>
							<?php
								foreach($qrytest as $row){
									echo "<option value='".$row['specID']."' ";
									if(isset($_GET['p']) && $_GET['p']==$row['specID']) echo "selected ";
									echo ">";
									if($row['specText']==$row['specShortDesc']) echo $row['specText'];
									else echo $row['specText']." - ".$row['specShortDesc'];
									if($debug) echo " [".$row['specID']."]";
									echo "</option>";
								}
							?>
						</select>
					</div>
				</div>
				<div class="form-group">
					<label for="location" class="col-sm-2 control-label">Location</label>
					<div class="col-sm-10">
						<?php
							$sql="
								Select
									dw_location.locationID,
									dw_locgroup.locGroupText,
									dw_location.locationText
								From
									dw_locgroup Left Join
									dw_location
										On dw_location.locationGroup = dw_locgroup.locGroupID
								Where
									dw_location.locationSite = ? And
									dw_location.locationActive = 1
								Order By
									dw_locgroup.locGroupOrder,
									dw_location.locationOrder,
									dw_location.locationText
							";
							if(!$qrylocation = mysqli_prepared_query($link, $sql, "i", array($_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
						?>
						<select name="l" id="location" class="form-control" >
							<option value='0' >All locations</option>
							<?php
								$group = array();
								foreach($qrylocation as $row){
									$group[$row['locGroupText']][] = $row;
								}
								unset($row);
								foreach ($group as $key => $values) {
									echo "<optgroup label='".$key."'>";
									foreach ($values as $value) {
										echo "<option value='".$value['locationID']."' ";
										if(isset($_GET['l']) && $_GET['l']==$value['locationID']) echo "selected ";
										echo ">".$value['locationText'];
										if($debug) echo " [".$value['locationID']."]";
										echo "</option>";
									}
									unset($value);
									echo "</optgroup>";
								}
								unset($values);
								unset($group);
							?>
						</select>
					</div>
				</div>
				<div class="form-group">
					<label for="group" class="col-sm-2 control-label">Group</label>
					<div class="col-sm-10">
						<?php
							$sql="
								Select
									dw_group.groupID,
									dw_group.groupText
								From
									dw_group
								Where
									dw_group.groupSite = ? And
									dw_group.groupActive = 1
								Order By
									dw_group.groupOrder,
									dw_group.groupText
							";
							if(!$qrygroup = mysqli_prepared_query($link, $sql, "i", array($_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
						?>
						<select name="g" id="group" class="form-control" onchange="update_tests();" >
							<option value='0' >All groups</option>
							<?php
								foreach($qrygroup as $array){
									echo "<option value='".$array['groupID']."' ";
									if(isset($_GET['g']) && $_GET['g']==$array['groupID']) echo "selected ";
									echo ">".$array['groupText'];
									if($debug) echo " [".$array['groupID']."]";
									echo "</option>";
								}
							?>
						</select>
					</div>
				</div>
				<div class="form-group">
					<label for="test" class="col-sm-2 control-label">Test</label>
					<div class="col-sm-10">
						<?php
							if(isset($_GET['g']) && $_GET['g']!=""){
								$sql="
									Select
										dw_test.testID,
										dw_test.testText
									From
										dw_test Left Join
										dw_group
										On dw_test.testGroup = dw_group.groupID
									Where (testSite = ?) AND (testActive = 1) AND (testGroup = ?)
									Order by groupOrder, testOrder, testText
								";
								if(!$qrytest = mysqli_prepared_query($link, $sql, "ii", array($_SESSION['userSite'], $_GET['g']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							}else{
								$sql="
									Select
										dw_group.groupText,
										dw_test.testID,
										dw_test.testText
									From
										dw_test Left Join
										dw_group
										On dw_test.testGroup = dw_group.groupID
									Where (testSite = ?) AND (testActive = 1)
									Order by groupOrder, testOrder, testText
								";
								if(!$qrytest = mysqli_prepared_query($link, $sql, "i", array($_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							}

						?>
						<select name='t' id='tests' class='form-control' >
							<option value='0' >All tests</option>
							<?php
								if(isset($_GET['g']) && $_GET['g']!=""){
									foreach($qrytest as $row){
										echo "<option value='".$row['testID']."' ";
										if(isset($_GET['t']) && $_GET['t']==$row['testID']) echo "selected ";
										echo ">".$row['testText'];
										if($debug) echo " [".$row['testID']."]";
										echo "</option>";
									}
									unset($row);
								}else{
									$group = array();
									foreach($qrytest as $row){
										$group[$row['groupText']][] = $row;
										//var_dump($row);
									}
									unset($row);
									foreach ($group as $key => $values) {
										//var_dump($values);
										echo "<optgroup label='".$key."'>";
										foreach ($values as $value) {
											//var_dump($value);
											echo "<option value='".$value['testID']."'";
											if(isset($_POST['test']) && $_POST['test']==$value['testID']) echo " selected";
											echo ">";
											echo str_replace('&','&amp;', $value['testText']);
											if($debug) echo " [".$value['testID']."]";
											echo "</option>";
										}
										unset($value);
										echo "</optgroup>";
									}
									unset($key);
									unset($values);
									unset($group);
								}
							?>
						</select>
					</div>
				</div>
				<div class="form-group">
					<label for="from" class="col-sm-2 control-label">From</label>
					<div class="col-sm-10">
						<input type="date" class="form-control" name="from" id="from" value="<?php echo $datefrom; ?>" >
					</div>
				</div>
				<div class="form-group">
					<label for="to" class="col-sm-2 control-label">To</label>
					<div class="col-sm-10">
						<input type="date" class="form-control" name="to" id="to" value="<?php echo $dateto; ?>" >
					</div>
				</div>
				<div class="form-group">
					<div class="col-sm-offset-2 col-sm-10">
						<button type="button" class="btn btn-default btn-primary" onclick="submitform();" >Generate</button>
						<a class="btn btn-default" href="#" role="button" onclick="window.print();"><span class='glyphicon glyphicon-print' aria-hidden='true'></span>&nbsp;Print</a>
						<?php if(isset($_GET['t'])) echo "<a class='btn btn-default' href='file.csv' role='button'><img src='images/csv.png'>&nbsp;Download CSV</a>"; ?>
					</div>
				</div>
			</form>
		</div>
		<div id="trend" class="col-md-9" style="height:380px;" role='main'></div>
	</div>

	<script src="js/trends.js?v=2.1">/* Trend JS */</script>
	<script src="js/raphael-min.js?v=2.1">/* HTML5 canvas drawing API */</script>
	<script src="js/morris.min.js?v=2.1">/* Chart API http://morrisjs.github.io/morris.js/ */</script>
	<script>
		var monthNames = [ "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" ];
		<?php
			$script = "";
			$table = "";

			$types = "ssi";
			$params = array($datefrom, $dateto, $_SESSION['userSite']);
			$cyphersql="
				# get dates
				Select
					dw_cypher.cypherID,
					dw_cypher.cypherManuDate,
					dw_cypher.cypherText,
					dw_cypher.cypherOrderID,
					dw_spec.specText
				From
					dw_cypher Left Join
					dw_spec
						On dw_cypher.cypherSpec = dw_spec.specID Right Join
					dw_unit
						On dw_unit.unitCypher = dw_cypher.cypherID Right Join
					dw_result
						On dw_result.resultUnit = dw_unit.unitID Left Join
					dw_test
						On dw_result.resultTest = dw_test.testID
				Where
					dw_cypher.cypherManuDate >= ? And
					dw_cypher.cypherManuDate <= ? And
					dw_cypher.cypherSite = ?
			";
			if(isset($_GET['p']) && $_GET['p']!=0 && $_GET['p']!='0'){
				$cyphersql .= " And dw_cypher.cypherSpec = ? ";
				$types .= "i";
				$params[] = $_GET['p'];
			}
			if(isset($_GET['t']) && $_GET['t']!=0 && $_GET['t']!='0'){
				$cyphersql .= " And dw_test.testID = ? ";
				$types .= "i";
				$params[] = $_GET['t'];
			}
			if(isset($_GET['l']) && $_GET['l']!=0 && $_GET['l']!='0'){
				$cyphersql .= " And dw_unit.unitLocation = ? ";
				$types .= "i";
				$params[] = $_GET['l'];
			}
			$cyphersql .= "
				Group By
					dw_cypher.cypherID
				Order By
					dw_cypher.cypherManuDate
			";
			if($debug) echo "\n/* cyphersql:".@sprintf(str_replace('?', '%s', str_replace('	',' ', $cyphersql)), ...$params)." ";
			if(!$qrycypher = mysqli_prepared_query($link, $cyphersql, $types, $params, __FILE__, __LINE__)) reporterror(get_error(), $cyphersql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__, $params);
			if($debug) echo "*/\n";
			if(mysqli_prepared_num_rows($qrycypher)<1){
				echo "
					//error no results found
					var trend = document.getElementById('trend');
					trend.innerHTML = \"<img src='images/500.png' width='35' height='35' alt='sad cow'>&nbsp;<strong>No results found.</strong> Try modifying your search criteria\";
				";
			}else{
				if(isset($_GET['t'])){
					$ymin = PHP_INT_MAX;
					$ymax = 0;
				?>

				new Morris.Line({
					// ID of the element in which to draw the chart.
					element: 'trend',
					// Chart data records -- each entry in this array corresponds to a point on the chart.
					data: [<?php
						//2d array
						//$ymin = 1000000;
						$table .= "<tr><th></th>";
						$testindex = 0;

						$types = "i";
						$params = array($_SESSION['userSite']);
						$testsql="
							# get test info
							Select
								dw_test.testID,
								dw_test.testText,
								dw_test.testFormat,
								dw_test.testRound
							From
								dw_test Left Join
								dw_group
								On dw_test.testGroup = dw_group.groupID
							Where
								dw_test.testActive = 1 And
								dw_test.testSite = ?
						";
						if(isset($_GET['g']) && $_GET['g']!=0){
							$testsql .= " And dw_group.groupID = ?";
							$types .= "i";
							$params[] = $_GET['g'];
						}
						if(isset($_GET['t']) && $_GET['t']!=0){
							$testsql .= " And dw_test.testID = ?";
							$types .= "i";
							$params[] = $_GET['t'];
						}
						$testsql .= "
							Group By
								testID
							Order By
								groupOrder, testOrder, testText
						";
						if($debug) echo "\n/* testsql:".@sprintf(str_replace('?', '%s', str_replace('	',' ', $testsql)), ...$params)." ";
						if(!$qrytest = mysqli_prepared_query($link, $testsql, $types, $params, __FILE__, __LINE__)) reporterror(get_error(), $testsql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__, $params);
						if($debug) echo "*/\n";
						$csv = "Date,";
						foreach($qrytest as $test_array){
							$table .= "<th style='color:".$lineColors[$testindex].";'><img src='images/legend.php?color=".substr($lineColors[$testindex],1)."'> ".$test_array['testText']."</th>";
							$csv .= "\"".$test_array['testText']."\",";
							$testindex++;
							if($testindex>=count($lineColors)) $testindex = 0;
						}
						$table .= "</tr>";
						$csv .= "\r\n";

						foreach($qrycypher as $cypher_array){
							echo "{date: '".$cypher_array['cypherManuDate']."'";

							$cyphertext = date('d/m/y',strtotime($cypher_array['cypherManuDate']))." ".$cypher_array['cypherText']." ".$cypher_array['cypherOrderID']." ".$cypher_array['specText'];
							if($debug) $cyphertext .= " [".$cypher_array['cypherID']."] ";

							$table .= "<tr><td><span class='hidden-print'><a href='results.php?r=".$cypher_array['cypherID']."'>".$cyphertext."</a></span><span class='visible-print-inline'>".$cyphertext."</span></td>";
							$csv .= "\"".$cyphertext."\",";

							$testindex = 0;
							//if(!$qrytest = mysqli_prepared_query($link, $testsql, "i", array(0), __FILE__, __LINE__)) reporterror(get_error(), $testsql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							foreach($qrytest as $test_array){
								//get average of results
								$resultsql="
									# get average of results
									Select
										dw_result.resultFriendly,
										max(dw_result.resultModDate) # this is to get rid of retests
									From
										dw_result Left Join
										dw_unit
										On dw_result.resultUnit = dw_unit.unitID Left Join
										dw_test
										On dw_result.resultTest = dw_test.testID Left Join
										dw_cypher
										On dw_unit.unitCypher = dw_cypher.cypherID Left Join
										dw_spec
										On dw_cypher.cypherSpec = dw_spec.specID
									Where
										dw_cypher.cypherID = ? And
										dw_unit.unitActive = 1 And
										dw_test.testID = ?
								";
								$types = "ii";
								$params = array($cypher_array['cypherID'], $test_array['testID']);
								if(isset($_GET['l']) && $_GET['l']!=0 && $_GET['l']!='0'){
									$resultsql .= " And dw_unit.unitLocation = ?";
									$types .= "i";
									$params[] = $_GET['l'];
								}
								$resultsql .= " Group by dw_unit.unitID, dw_result.resultFriendly";
								//$script.="<script>alert('".$resultsql."');</script>";
								if($debug) echo "\n/* resultsql:".@sprintf(str_replace('?', '%s', str_replace('	',' ', $resultsql)), ...$params)." ";
								if(!$qryresult = mysqli_prepared_query($link, $resultsql, $types, $params, __FILE__, __LINE__)) reporterror(get_error(), $resultsql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__, $params);
								if($debug) echo "*/\n";
								$sum = 0;
								$count = 0;

								foreach($qryresult as $result_array){
									$sum += texttonumber($result_array['resultFriendly'], $test_array['testFormat']);
									$count++;
									$testText = $test_array['testText'];
								}

								//if($count!=0 && $sum!=0){
								//https://krud.no-ip.org/prodbase/trends.php?p=0&l=0&g=47&t=1067&from=2016-01-01&to=2017-07-25
								if($count > 0){
									$average = $sum / $count;
									if($debug) echo "\n/* ".$sum."/".$count."=".$average." */\n";
									if($average >= 0){ //dont want -1
										echo ", '".$test_array['testID']."':".number_format($average, $test_array['testRound'],'.',''); //dont want commas
										$table .= "<td><span class='hidden-print'><a href='results.php?r=".$cypher_array['cypherID']."'>".number_format($average, $test_array['testRound'])."</a></span><span class='visible-print-inline'>".number_format($average, $test_array['testRound'])."</span></td>";
										$csv .= number_format($average, $test_array['testRound']).",";
										//if($average < $ymin) $ymin = $average;
									}else{
										//echo ", '".$test_array['testID']."':0";
										$table .= "<td><span class='hidden-print'><a href='results.php?r=".$cypher_array['cypherID']."'>-</a></span><span class='visible-print-inline'>-</span></td>";
										$csv .= "-,";
									}

									if($average < $ymin) $ymin = $average;
									if($average > $ymax) $ymax = $average;

								}else{
									//echo "\n/* count is zero */\n";
									$table .= "<td></td>";
								}
							}
							$table .= "</tr>";
							$csv .= "\r\n";
							echo "},";
						}
						//write csv
						if($csv_file = fopen("file.csv", "w")){
							fwrite($csv_file, $csv);
							fclose($csv_file);
						}
					?>],
					// The name of the data record attribute that contains x-values.
					xkey: 'date',
					smooth: false,
					// A list of names of data record attributes that contain y-values.
					ykeys: [<?php
						$tests = "";
						//if(!$qrytest = mysqli_query($link, $testsql)) reporterror(get_error(), $testsql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
						foreach($qrytest as $test_array){
							$tests .= "'".$test_array['testID']."',";
						}
						echo substr($tests,0,strlen($tests)-1);
					?>],
					xlabels: 'day',
					// Labels for the ykeys -- will be displayed when you hover over the chart.
					labels: [<?php
						$tests = "";
						//if(!$qrytest = mysqli_query($link, $testsql)) reporterror(get_error(), $testsql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
						foreach($qrytest as $test_array){
							$tests .= "'".$test_array['testText']."',";
						}
						echo substr($tests,0,strlen($tests)-1);
					?>],
					<?php
						//if there is 1 of test, spec and location show limit
						if(isset($_GET['t']) && $_GET['t']!=0 && $_GET['t']!='0' &&
						   isset($_GET['p']) && $_GET['p']!=0 && $_GET['p']!='0' &&
						   isset($_GET['l']) && $_GET['l']!=0 && $_GET['l']!='0' &&
							 isset($_GET['from']) && isset($_GET['to'])
						){
							$limitsql="
								# get limits
								Select
									dw_limit.limitLow,
									dw_limit.limitHigh
								From
									dw_limit
								Where
									dw_limit.limitTest      = ? And
									dw_limit.limitSpec      = ? And
									dw_limit.limitLocation  = ? And
									dw_limit.limitDateFrom <= ? And
									dw_limit.limitDateTo   >= ?
							";
							if($debug) echo "\n/* limitsql:".@sprintf(str_replace('?', '%s', str_replace('	',' ', $limitsql)), ...$params)." ";
							if(!$qrylimit = mysqli_prepared_query($link, $limitsql, "iiiss", array(clean($_GET['t']), clean($_GET['p']), clean($_GET['l']), clean($_GET['from']), clean($_GET['to'])), __FILE__, __LINE__)) reporterror(get_error(), $limitsql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							if($debug) echo "*/\n";
							if(mysqli_prepared_num_rows($qrylimit)>0){
								$limit_array = $qrylimit[0];
								echo "goals: [".$limit_array['limitLow'].",".$limit_array['limitHigh']."], goalLineColors: ['#FF7F00', '#FF0000'],";
								//if($limit_array['limitLow'] < $ymin) $ymin = $limit_array['limitLow'];
							}
						}
						if($ymin < 1) $ymin = 0; //this is to stop silly rounding errors. some points were 12.99999999999999999
						//if($ymin != 1000000) echo "ymin: ".floor($ymin).",";
					?>
					ymin: <?php echo floor($ymin); ?>,
					ymax: <?php echo ceil($ymax); ?>,
					xLabelFormat: function(day){
						var d = new Date(day);
						return d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear();
					},
					hideHover: 'auto'
				});
			<?php
				}
			}
		?>
	</script>

	<div class='container'><table class='table table-striped'><?php echo $table; ?></table></div>
	<?php require "inc/footer.php"; ?>
