<?php
	/* (C) DairyWindow 2012-2017 */
	
	require "inc/connect.php";
	require "inc/fade.php";
	
	$title = "Sampling plan";
	require "inc/head.php";
	$menu = "insert";
	require "inc/menu.php";
	
	if($debug) showdebug();
	
	$counter = 0;
	
	if(isset($_GET['product']) && $_GET['product']!="") $spec = clean($_GET['product']);
	else $spec = 0;
	
	if(isset($_POST['newsample']) || isset($_POST['btnAdd'])){ //this allows blank unit numbers (for current time)
		if(
			isset($_POST['newlocation']) && 
			isset($_POST['newsample'  ]) && 
			isset($_GET[ 'product'    ]) && 
			$_POST['newlocation']!="" && 
			$_POST['newlocation']!=0  && 
			//$_POST['newsample'  ]!="" && 
			$_GET[ 'product'    ]!="" &&
			$_GET[ 'product'    ]!=0
		){
			$product  = clean($_GET[ 'product'    ]);
			$location = clean($_POST['newlocation']);
			$sample   = clean($_POST['newsample'  ]);
			
			$sql="
				# check for dups
				Select insertID
				From dw_insert
				Where
					insertSpec = ? and
					insertLocation = ? and
					insertUnit like ?
			";
			if(!$checkquery = mysqli_prepared_query($link, $sql, "iis", array($product, $location, $sample), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			if(mysqli_prepared_num_rows($checkquery)==0){
				$sql="
					Insert into dw_insert        (insertSpec, insertLocation, insertUnit, insertModUser, insertModDate)
					Values                       (      ?   ,       ?       ,       ?   ,       ?      ,     now()    )
				";
				if(!savesql($link, $sql, "iisi", array( $product ,      $location,   $sample , $_SESSION['userID']         ), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			}else{
				$message['type'] = "error";
				$message['text'] = "That already existed ";
				if($debug) $message['text'] .= $sql;
			}
		}
	}else{
		if(isset($_POST['del']) && $_POST['del']!=''){
			$sql="
				delete from dw_insert
				where insertID = ?
			";
			if(!savesql($link, $sql, "i", array($_POST['del']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		}
	}
?>

<div 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>

<h1 class='text-center'>Sampling plan</h1>

<div class='col-md-3' role='complementary' >
	<form class="form-horizontal" method="get" id='mainform' style='position:fixed;'>
		<div class="form-group">
			<label for="product" 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.specActive = 1 And
							dw_spec.specSite = ?
						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 id='product' name='product' class='form-control' onchange='submit();'>
					<option value='0' disabled selected >Choose a product</option>
					<?php
						foreach($specquery as $specarray){
							echo "<option value='".$specarray['specID']."'";
								if(isset($_GET['product']) && $_GET['product']==$specarray['specID']) echo " selected";
								echo ">".$specarray['specText']." (".$specarray['specShortDesc'].")";
								if($debug) echo " [".$specarray['specID']."]";
							echo "</option>";
						}
					?>
				</select>
			</div>
		</div>
		
		<div class="form-group">
			<div class="col-sm-offset-2 col-sm-10">
				<button type="submit" class="btn btn-primary">Refresh</button>
			</div>
		</div>
	</form>
</div>

<div id='main' class='container col-md-9' style='display:none;' role='main'>
	<h2 class='text-center'>These will be automatically inserted at time of cypher/batch creation</h2>

	<table class='table table-hover'>
		<thead>
			<tr>
				<th class='text-center'><!-- Number --></th>
				<th class='text-center'>Location</th>
				<th class='text-center'>Sample text</th>
				<th class='text-center'><!-- Button --></th>
			</tr>
		</thead>
		<tbody>
			<?php
				if(isset($_GET['product']) && $_GET['product']!='' && $_GET['product']!=0){
					$sql="
						Select
							dw_insert.insertID,
							dw_location.locationID,
							dw_location.locationText,
							dw_location.locationFriendly,
							dw_insert.insertUnit
						From
							dw_insert Inner Join
							dw_location
								On dw_insert.insertLocation = dw_location.locationID
						Where
							dw_insert.insertSpec = ?
						Order By
							dw_location.locationOrder,
							dw_location.locationText,
							Case dw_insert.insertUnit
								When 'F' Then 1
								When 'M' Then 2
								When 'L' Then 3
								Else 4
							End,
							Field(dw_insert.insertUnit, 'F', 'M', 'L', 'Comp1', 'Comp 1', 'Comp2', 'Comp 2'),
							LPad(dw_insert.insertUnit,5,0)
					";
					if(!$subquery = mysqli_prepared_query($link, $sql, "i", array($spec), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					if(mysqli_prepared_num_rows($subquery)>0){
						$counter = 0;
						foreach($subquery as $subarray){
							echo "<tr>
								<td class='text-center'>".$counter."</td>
								<td class='text-center'>".$subarray['locationText']; if($subarray['locationText']!=$subarray['locationFriendly'] && $subarray['locationFriendly']!='') echo ' ('.$subarray['locationFriendly'].')'; if($debug) echo " [".$subarray['locationID']."]"; echo "</td>
								<td class='text-center'>".(empty($subarray['insertUnit']) ? "&lt;Current time&gt;" : $subarray['insertUnit'])."</td>
								<td class='text-center'>
									<form method='post'>
										<button type='submit' class='btn btn-sm' name='del' value='".$subarray['insertID']."'>
											<span class='glyphicon glyphicon-trash' aria-hidden='true'></span>
											<span class='sr-only'>Remove</span>
											<span class='hidden-xs'> Remove</span>
											"; if($debug) echo $subarray['insertID']; echo "
										</button>
									</form>
								</td>
							</tr>";
							$counter++;
						}
					}
				}
				
				//insert new
			?>
			<tr>

				<td class='text-center'><?php echo $counter; ?></td>
				<td class='text-center'>
					<?php
						$sql="# Get all locations
							Select
								dw_locgroup.locGroupText,
								dw_location.locationID,
								dw_location.locationText,
								dw_location.locationFriendly
							From
								dw_location Left Join
								dw_locgroup On dw_location.locationGroup = dw_locgroup.locGroupID
							Where
								dw_location.locationActive = 1 And
								dw_location.locationSite = ?
							Order By
								dw_locgroup.locGroupOrder,
								dw_location.locationOrder,
								dw_location.locationText
						";
						if(!$location_query = mysqli_prepared_query($link, $sql, "i", array($_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					?>
					<select class='form-control' name='newlocation' id='newlocation'>
						<option value='0' disabled selected >Choose a location</option>
						<?php
							$group = array();
							foreach($location_query as $row){
								$group[$row['locGroupText']][] = $row;
							}
							foreach ($group as $key => $values) {
								echo "<optgroup label='".$key."'>\n";
								foreach ($values as $value) {
									echo "	<option value='".$value['locationID']."'";
										if(isset($_POST['newlocation']) && $_POST['newlocation']!="" && $_POST['newlocation']!=null && $_POST['newlocation']==$value['locationID']) echo " selected"; //set location to previously created sample
										echo ">".$value['locationText'];
										if($value['locationText']!=$value['locationFriendly'] && $value['locationFriendly']!='') echo ' ('.$value['locationFriendly'].')';
										if($debug) echo " [".$value['locationID']."]";
									echo "</option>\n";
								}
								echo "</optgroup>\n";
							}
						?>
					</select>
				</td>
				<td class='text-center'>
					<input type='text' name='newsample' class='form-control' id='newsample' placeholder='New sample text (leave blank for current time)' >
					<?php time_input('newsample'); ?>
				</td>
				<td class='text-center'>
					<button type='button' class='btn btn-default' name='btnAdd' id='btnAdd'>
						<span class='glyphicon glyphicon-plus' aria-hidden='true'></span>
						<span class='sr-only'>Add</span>
						<span class='hidden-xs'> Add </span>
					</button>
				</td>
				<form method='post' id='new'>
					<input type='hidden' name='newlocation' id='form-newlocation'>
					<input type='hidden' name='newsample'   id='form-newsample'  >
				</form>
				<script>
					$("#btnAdd").click(function(){
						//update fields
						$("#form-newlocation").val($("#newlocation").val());
						$("#form-newsample"  ).val($("#newsample"  ).val());
						//send form
						$("#new").submit();
					});
				</script>
			</tr>
		</tbody>
	</table>
</div>
<script>
	dropdown("#product");
	dropdown("#newlocation");
</script>
<?php require "inc/footer.php"; ?>
