<?php

	require "inc/connect.php";

	require "inc/get_units.php";
	require "inc/cypherstuff.php"; //functions for converting dates to cyphers, and also expirys
	require "inc/texttonumber.php";
	require "inc/numbertotext.php";

	$title = "Report";
	require "inc/head.php";
	$menu = "reportip";
	require "inc/menu.php";

	if($debug) showdebug();

	if(isset($_REQUEST['datefrom']) && $_REQUEST['datefrom']!="" && $_REQUEST['datefrom']!=null) $datefrom = $_REQUEST['datefrom'];
	else $datefrom = date('Y-m-d',strtotime('1 month ago'));

	if(isset($_REQUEST['dateto']) && $_REQUEST['dateto']!="" && $_REQUEST['dateto']!=null) $dateto = $_REQUEST['dateto'];
	else $dateto = date('Y-m-d');
?>
<div id='topDIV'>
	<h1 class='text-center' ><?php echo $title;
		if(isset($_REQUEST['t'])){
			$sql="
				Select
					dw_test.testText
				From
					dw_test
				Where
					dw_test.testID = ?
			";
			if(!$test_query = mysqli_prepared_query($link, $sql, "i", array($_REQUEST['t']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			$row = $test_query[0];
			echo " for ".$row['testText'];
		}
	?></h1>
</div>
<div class='col-md-3' role='complementary' >
	<form method='get' >
		<div class='form-group'>
			<label for='datefrom'>Date from</label>
			<input type='date' class='form-control' name='datefrom' placeholder='Date from' value='<?php echo $datefrom; ?>'>
		</div>
		<div class='form-group'>
			<label for='dateto'>Date to</label>
			<input type='date' class='form-control' name='dateto' placeholder='Date to' value='<?php echo $dateto; ?>'>
		</div>

		<div class='form-group'>
			<label for='s'>Product(s)</label>
			<?php
				$sql="
					# Get products
					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(!$specquery = mysqli_prepared_query($link, $sql, "i", array($_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			?>
			<select name='s[]' id='s' class='form-control' multiple size='7'>
				<option value='0'>All products</option>
				<?php
					foreach($specquery as $specarray){
						echo "<option value='".$specarray['specID']."'";
						if(isset($_REQUEST['s']) && $_REQUEST['s']!="" && $_REQUEST['s']!=null && ($_REQUEST['s'] == $specarray['specID'] || (is_array($specarray['specID']) && in_array($_REQUEST['s'], $specarray['specID'])))) echo " selected";
						if($specarray['specText']==$specarray['specShortDesc']) echo ">".$specarray['specText'];
						else echo ">".$specarray['specText']." - ".$specarray['specShortDesc'];
						if($debug) echo " [".$specarray['specID']."]";
						echo "</option>";
					}
					?>
			</select>
		</div>

		<div class='form-group'>
			<label for='t'>Test</label>
			<?php
				if(isset($_GET['datefrom']) && isset($_GET['dateto'])){
					$sql="
						# get all tests within date range
						Select
							dw_group.groupText,
							dw_test.testID,
							dw_test.testText
						From
							dw_group Right Join
							dw_test
								On dw_test.testGroup = dw_group.groupID Right Join
							dw_result
								On dw_result.resultTest = dw_test.testID Left Join
							dw_unit
								On dw_result.resultUnit = dw_unit.unitID Left Join
							dw_cypher
								On dw_unit.unitCypher = dw_cypher.cypherID Left Join
							dw_spec
								On dw_cypher.cypherSpec = dw_spec.specID
						Where
							dw_test.testActive = 1 And
							dw_group.groupActive = 1 And
							dw_test.testSite = ? And
							dw_cypher.cypherManuDate >= ? And
							dw_cypher.cypherManuDate <= ? ";

					if(isset($_REQUEST['s']) && $_REQUEST['s']!=""){
						$where = "";
						if(isset($_REQUEST['s']) && $_REQUEST['s']!="" && $_REQUEST['s']!=null){
							$where .= " AND (";
							foreach($_REQUEST['s'] as $s){
								if($s!=0){
									$where .= "specID=".$s." OR ";
								}
							}
							if(substr($where,-6)!=" AND ("){
								$where=substr($where,0,strlen($where)-4); //take off the last " OR "
								$where .= ")";
							}else{
								$where=substr($where,0,strlen($where)-6); //take off " AND ("
							}
						}
						$sql.=$where;
					}

					$sql.="
						Group By
							dw_test.testID
						Order By
							dw_group.groupOrder,
							dw_test.testOrder
					";
					if(!$test_query = mysqli_prepared_query($link, $sql, "iss", array($_SESSION['userSite'], $_GET['datefrom'], $_GET['dateto']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
				}else{
					$sql="
						# get all tests, date not set
						Select
							dw_group.groupText,
							dw_test.testID,
							dw_test.testText
						From
							dw_group Right Join
							dw_test
								On dw_test.testGroup = dw_group.groupID
						Where
							dw_test.testActive = 1 And
							dw_group.groupActive = 1 And
							dw_test.testSite = ?
						Order By
							dw_group.groupOrder,
							dw_test.testOrder
					";
					if(!$test_query = mysqli_prepared_query($link, $sql, "i", array($_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
				}
			?>
			<select name='t' id='t' class='form-control' >
				<?php
					$group = array();
					foreach($test_query as $row){
						$group[$row['groupText']][] = $row;
					}
					foreach ($group as $key => $values) {
						echo "<optgroup label='".$key."'>";
						foreach ($values as $value) {
							echo "<option value='".$value['testID']."' ";
								if(isset($_REQUEST['t']) && $value['testID']==$_REQUEST['t']) echo "selected ";
								echo ">".$value['testText'];
								if($debug) echo " [".$value['testID']."]";
							echo "</option>";
						}
						echo "</optgroup>";
					}
				?>
			</select>
		</div>

		<button type='submit' class='btn btn-default btn-primary'>Refresh</button>
	</form>
</div>
<div class='col-md-9' id='loading'>
	<img src="images/loading-small.gif" alt="Please wait. Loading..." width="111" height="156" style="margin-top:150px;" class="center-block"><br>
	<div class="text-center"><img src='images/carregando.gif' width='16' height='16'>&nbsp;Please wait while loading...</div>
	<div id='percent'>
		<div class='progress'><div class='progress-bar progress-bar-striped active' role='progressbar' aria-valuenow='0' aria-valuemin='0' aria-valuemax='100' style='width: 0%;'>0%</div></div>
	</div>
</div>
<div class='col-md-9' role='main' id='main' style='display:none;'>
	<?php
		if(isset($_REQUEST['t'])){

			$_REQUEST['t'] = clean($_REQUEST['t']);
			$sql="
				Select
					dw_test.testFormat,
					dw_test.testUnits,
					dw_test.testRound
				From
					dw_test
				Where
					dw_test.testID = ?
			";
			if($testquery = mysqli_prepared_query($link, $sql, "i", array($_REQUEST['t']), __FILE__, __LINE__)){
				if(mysqli_prepared_num_rows($testquery)>0){
					$testarray = $testquery[0];
					$testFormat = $testarray['testFormat'];
					$testUnits = $testarray['testUnits'];
					$testRound = $testarray['testRound'];
				}else{
					$testFormat = 0;
					$testUnits = "";
					$testRound = 0;
				}
			}else{
				$testFormat = 0;
				$testUnits = "";
				$testRound = 0;
			}

			$where = "cypherManuDate>='".$datefrom."' AND cypherManuDate<='".$dateto."' AND cypherSite=".$_SESSION['userSite'];
			if(isset($_REQUEST['s']) && $_REQUEST['s']!="" && $_REQUEST['s']!=null){
				$where .= " AND (";
				foreach($_REQUEST['s'] as $s){
					if($s!=0){
						$where .= "specID=".clean($s)." OR ";
					}
				}
				if(substr($where,-6)!=" AND ("){
					$where=substr($where,0,strlen($where)-4); //take off the last " OR "
					$where .= ")";
				}else{
					$where=substr($where,0,strlen($where)-6); //take off " AND ("
				}
			}

			$cyphersql="
				Select
					dw_cypher.cypherID,
					dw_cypher.cypherManuDate,
					dw_cypher.cypherOrderID,
					dw_spec.specID,
					dw_spec.specText
				From
					dw_spec Right Join
					dw_cypher
						On dw_spec.specID = dw_cypher.cypherSpec
				Where
					dw_cypher.cypherID > ? And
					".$where."
				Order By
					dw_cypher.cypherManuDate Desc
			";
			$counter = 0;
			if(!$cypherquery = mysqli_prepared_query($link, $cyphersql, "i", array(0), __FILE__, __LINE__)) reporterror(get_error(), $cyphersql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			if(mysqli_prepared_num_rows($cypherquery)>0){

				echo "<table class='table table-striped table-bordered'>";

				$cypherarray = $cypherquery[0];
				$locationsql="
					Select
						dw_location.locationText,
						dw_location.locationID
					From
						dw_result Left Join
						dw_unit
							On dw_result.resultUnit = dw_unit.unitID Left Join
						dw_cypher
							On dw_unit.unitCypher = dw_cypher.cypherID Left Join
						dw_location
							On dw_unit.unitLocation = dw_location.locationID
					Where
						dw_result.resultModDate >= ? And
						dw_result.resultModDate <= ? And
						dw_result.resultTest = ? And
						dw_cypher.cypherSpec = ? And
						dw_location.locationActive = 1
					Group By
						dw_location.locationID
				";
				//for top row
				if(!$locationquery = mysqli_prepared_query($link, $locationsql, "ssii", array($datefrom, $dateto, $_REQUEST['t'], $cypherarray['specID']), __FILE__, __LINE__)) reporterror(get_error(), $locationsql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
				if(mysqli_prepared_num_rows($locationquery)>0){
					echo "<tr><td>&nbsp;</td>";
					foreach($locationquery as $locationarray){
						echo "<td>".$locationarray['locationText'];
						if($debug) echo " [".$locationarray['locationID']."]";
						echo "</td>";
					}
					echo "</tr>";
				}

				if(mysqli_prepared_num_rows($cypherquery)>0){
					foreach($cypherquery as $cypherarray){

						$cypherID       = $cypherarray['cypherID'];
						$cypherManuDate = $cypherarray['cypherManuDate'];
						$cypherOrderID  = $cypherarray['cypherOrderID'];
						$specID         = $cypherarray['specID'];
						$specText       = $cypherarray['specText'];

						if(mysqli_prepared_num_rows($locationquery)>0){
							echo "<tr><td><strong><a href='results.php?r=".$cypherID."'>".date('d/m/Y',strtotime($cypherManuDate))." ".$cypherOrderID." ".$specText."</a></strong></td>";
							foreach($locationquery as $locationarray){
								$locationID = $locationarray['locationID'];

								$sql="
									Select
										dw_result.resultFriendly,
										Max(dw_result.resultModDate) As resultModDate # for retests
									From
										dw_result Inner Join
										dw_unit On dw_result.resultUnit = dw_unit.unitID
									Where
										dw_unit.unitCypher   = ? And
										dw_unit.unitLocation = ? And
										dw_result.resultTest = ?
								";
								if(!$resultquery = mysqli_prepared_query($link, $sql, "iii", array($cypherID, $locationID, $_REQUEST['t']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
								//echo "<td>";
								//echo $sql." ";

								$sum = 0;
								$count = 0;
								if($debug) $result_soft_array = "{";
								foreach($resultquery as $resultarray){
									if($resultarray['resultFriendly']!=""){
										$result = texttonumber($resultarray['resultFriendly'], $testFormat);
										$sum += $result;
										$count++;
										if($debug) $result_soft_array .= $resultarray['resultFriendly'].",";
									}
								}
								if($debug) $result_soft_array = substr($result_soft_array,0,-1)."} ";

								$sql="
									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(!$limit_query = mysqli_prepared_query($link, $sql, "iiiss", array($_REQUEST['t'], $specID, $locationID, $cypherManuDate, $cypherManuDate), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
								$limitarray = $limit_query[0];

								if($count>0) $average = numbertotext(($sum/$count), $testFormat, $testRound);
								else $average = $sum;

								if($count==0){
									//no result
									echo "<td>";
								}else if(mysqli_prepared_num_rows($limit_query)==0){
									//no limits
									echo "<td style='background-color:DarkGray;' title='No limits found'>";
								}else if($average < $limitarray['limitLow'] || $average > $limitarray['limitHigh']){
									//oos
									echo "<td style='background-color:orange;' title='Out of spec'>";
								}else{
									//in spec
									echo "<td >";
								}

								if($debug){
									echo $result_soft_array." (".$limitarray['limitLow']."-".$limitarray['limitLow'].") ";
								}

								if($count>0) echo $average." ".$testUnits;
								//else echo "<small>-</small>";

								echo "</td>";
							}
							echo "</tr>";
						}
						echo "<script>
							var percentdiv = document.getElementById('percent');
							var percent = Math.ceil(".$counter/mysqli_prepared_num_rows($cypherquery)."*100);
							percentdiv.innerHTML = \"<div class='progress'><div class='progress-bar progress-bar-striped active' role='progressbar' aria-valuenow='\"+percent+\"' aria-valuemin='0' aria-valuemax='100' style='width: \"+percent+\"%;'>\"+percent+\"%</div></div>\";
						</script>";
						$counter++;
					}
					echo "</table><table class='table-bordered'><tr><td>In spec</td></tr><tr><td style='background-color:orange;'>Out of spec</td></tr><tr><td style='background-color:DarkGray;'>No limits</td></tr></table>";

				}else echo "<span class='glyphicon glyphicon-remove' aria-hidden='true'></span>&nbsp;There were no results found for the search criteria you supplied";
			}else echo "<span class='glyphicon glyphicon-remove' aria-hidden='true'></span>&nbsp;There were no results found for the search criteria you supplied";

		}
	?>
</div>
<script>
	dropdown("#s");
	dropdown("#t");
</script>
<?php require "inc/footer.php"; ?>
