<?php
/**
 * Copyright (C) DairyWindow 2018
 * admin@dairywindow.nz
 */

	/* (C) DairyWindow 2012-2017 */

	require "inc/connect.php";
	if($_SESSION['userLevel'] <= $_SESSION['admin_cypher_edit']) $allow_edit = 1;
	else $allow_edit = 0;

	require "inc/get_units.php";
	require "inc/cypherstuff.php"; //functions for converting dates to cyphers, and also expirys

	$cyphers_per_page = 100; //consider moving this to dw_settings

	/* * * * * * *\
	|* 0 Cypher  *|
	|* 1 Batch   *|
	|* 2 Both    *|
	\* * * * * * */

	if($_SESSION['cypherorbatch']==1 || $_SESSION['cypherorbatch']=='1') $cypherorbatchtext = "Batch";
	else $cypherorbatchtext = "Cypher";

	if(isset($_POST['hiding'])){
		if(isset($_POST['hideip'])) $_SESSION['hideip'] = 1;
		else $_SESSION['hideip'] = 0;
	}

	if(isset($_POST['add_date']) && isset($_POST['add_spec']) && !isset($_POST['confirm']) && $allow_edit){
		//create new cypher
		if($_POST['add_date']!="" && $_POST['add_date']!=null && $_POST['add_spec']!="" && $_POST['add_spec']!=null){ //these two things are required, regardless of 'cypher or batch'
			$add_date     = clean($_POST['add_date']);
			$add_spec     = clean($_POST['add_spec']);
			$add_batch    = clean($_POST['add_batch']);
			$add_comments = clean($_POST['add_comments']);

			//get cypher code
			if($debug) echo "add_date: ".$add_date."<br>";
			$cyphertext = date2cypher($add_date);
			if($debug) echo "cyphertext: ".$cyphertext."<br>";

			//see if cypher/spec already exists
			if($_SESSION['cypherorbatch']==1 || $_SESSION['cypherorbatch']=='1'){
				$sql="
					Select
						dw_cypher.cypherID,
						dw_spec.specText
					From
						dw_spec Right Join
						dw_cypher
							On dw_spec.specID = dw_cypher.cypherSpec
					Where
						dw_cypher.cypherManuDate = ? And
						dw_cypher.cypherOrderID = ? And
						dw_cypher.cypherSpec = ?
				";
				if(!$cypher_query = mysqli_prepared_query($link, $sql, "sii", array($add_date, $add_batch, $add_spec), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			}else{
				$sql="
					Select
						dw_cypher.cypherID,
						dw_spec.specText
					From
						dw_spec Right Join
						dw_cypher
							On dw_spec.specID = dw_cypher.cypherSpec
					Where
						dw_cypher.cypherManuDate = ? And
						dw_cypher.cypherText = ? And
						dw_cypher.cypherSpec = ?
				";
				if(!$cypher_query = mysqli_prepared_query($link, $sql, "ssi", array($add_date, $cyphertext, $add_spec), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			}
			$cypher_row = $cypher_query[0];
			if(mysqli_prepared_num_rows($cypher_query)>0 && !isset($_POST['confirm_cypher'])){

				$message['type'] = "warning";
				$message['text'] = "<span class='glyphicon glyphicon-warning-sign' aria-hidden='true'></span> The cypher or batch you are trying to create <strong>already exists!</strong> Are you sure you want to create a <strong>duplicate</strong> of ";
				switch($_SESSION['cypherorbatch']){
					case 0: //cyphers
						$message['text'] .= $cyphertext;
						break;
					case 1: //batches
						$message['text'] .= $add_batch;
						break;
					case 2: //both
						$message['text'] .= $cyphertext." ".$add_batch;
						break;
				}
				$message['text'] .= " ".$cypher_row['specText']."? You can just add samples and results to the existing one instead.
					<input type='hidden' name='cypherID'     value='".$cypher_row['cypherID']."'>
					<input type='hidden' name='add_date'     value='".$add_date."'>
					<input type='hidden' name='add_spec'     value='".$add_spec."'>
					<input type='hidden' name='spectext'     value='".$cypher_row['specText']."'>
					<input type='hidden' name='add_batch'    value='".$add_batch."'>
					<input type='hidden' name='add_cypher'   value='".$cyphertext."'>
					<input type='hidden' name='add_comments' value='".$add_comments."'>
				";
				if(isset($_POST['sample1' ]) && $_POST['sample1' ]!="" && isset($_POST['location1' ])) echo "<input type='hidden' name='sample1'  value='".$_POST['sample1' ]."'><input type='hidden' name='location1'  value='".$_POST['location1' ]."'>";
				if(isset($_POST['sample2' ]) && $_POST['sample2' ]!="" && isset($_POST['location2' ])) echo "<input type='hidden' name='sample2'  value='".$_POST['sample2' ]."'><input type='hidden' name='location2'  value='".$_POST['location2' ]."'>";
				if(isset($_POST['sample3' ]) && $_POST['sample3' ]!="" && isset($_POST['location3' ])) echo "<input type='hidden' name='sample3'  value='".$_POST['sample3' ]."'><input type='hidden' name='location3'  value='".$_POST['location3' ]."'>";
				if(isset($_POST['sample4' ]) && $_POST['sample4' ]!="" && isset($_POST['location4' ])) echo "<input type='hidden' name='sample4'  value='".$_POST['sample4' ]."'><input type='hidden' name='location4'  value='".$_POST['location4' ]."'>";
				if(isset($_POST['sample5' ]) && $_POST['sample5' ]!="" && isset($_POST['location5' ])) echo "<input type='hidden' name='sample5'  value='".$_POST['sample5' ]."'><input type='hidden' name='location5'  value='".$_POST['location5' ]."'>";
				if(isset($_POST['sample6' ]) && $_POST['sample6' ]!="" && isset($_POST['location6' ])) echo "<input type='hidden' name='sample6'  value='".$_POST['sample6' ]."'><input type='hidden' name='location6'  value='".$_POST['location6' ]."'>";
				if(isset($_POST['sample7' ]) && $_POST['sample7' ]!="" && isset($_POST['location7' ])) echo "<input type='hidden' name='sample7'  value='".$_POST['sample7' ]."'><input type='hidden' name='location7'  value='".$_POST['location7' ]."'>";
				if(isset($_POST['sample8' ]) && $_POST['sample8' ]!="" && isset($_POST['location8' ])) echo "<input type='hidden' name='sample8'  value='".$_POST['sample8' ]."'><input type='hidden' name='location8'  value='".$_POST['location8' ]."'>";
				if(isset($_POST['sample9' ]) && $_POST['sample9' ]!="" && isset($_POST['location9' ])) echo "<input type='hidden' name='sample9'  value='".$_POST['sample9' ]."'><input type='hidden' name='location9'  value='".$_POST['location9' ]."'>";
				if(isset($_POST['sample10']) && $_POST['sample10']!="" && isset($_POST['location10'])) echo "<input type='hidden' name='sample10' value='".$_POST['sample10']."'><input type='hidden' name='location10' value='".$_POST['location10']."'>";
			}else{
				//echo $cypherorbatchtext." doesnt exist<br>";

				//get expiry date
				$expiry = getexpiry($add_date, $add_spec);

				$sql="
					# get spectext
					Select
						dw_spec.specText
					From
						dw_spec
					Where
						dw_spec.specID = ?
				";
				if(!$spec_query = mysqli_prepared_query($link, $sql, "i", array($add_spec), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
				$spec_row = $spec_query[0];

				$add_batch = str_replace('/','-', $add_batch); //replace slashes with dashes. When submitting to lab it thinks the date is a directory (Could not open subforms/4/pre-reg-ODL-EA08-06/07/2017-LAC-Lactose-04.csv for writing, check path exists)

				$sql="
					INSERT INTO dw_cypher            ( cypherText, cypherOrderID, cypherSpec, cypherManuDate, cypherExpiryDate, cypherNotesFP,      cypherSite     ,   cypherModUser  , cypherModDate)
					VALUES                           (       ?   ,       ?      ,       ?   ,       ?       ,       ?         ,       ?      ,            ?        ,         ?        ,     now()    )
				";
				if(!savesql($link, $sql, "ssisssii", array($cyphertext,  $add_batch  , $add_spec ,   $add_date   ,     $expiry     , $add_comments, $_SESSION['userSite'], $_SESSION['userID']              ), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);

				$sql="
					# get newly created cypher id for sampling plan
					Select cypherID
					From dw_cypher
					Where cypherID > ?
					Order by cypherID
					Desc Limit 1
				";
				if(!$get_query = mysqli_prepared_query($link, $sql, "i", array(0), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
				$get_row = $get_query[0];
				$new_cypherID = $get_row['cypherID'];

				if(!empty($_SESSION) && $_SESSION['userLevel'] <= $_SESSION['admin_unit_add']){
					$sql = "# sampling plan - auto add samples
						Select
							dw_insert.insertUnit,
							dw_insert.insertLocation
						From
							dw_insert
						Where
							dw_insert.insertSpec = ?";
					if(!$insert_query = mysqli_prepared_query($link, $sql, "i", array($add_spec), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					if(mysqli_prepared_num_rows($insert_query) > 0){
						foreach($insert_query as $insert_row){
							if(isset($insert_row['insertUnit']) && $insert_row['insertUnit']!="" && $insert_row['insertUnit']!=null) $unitText = clean(ucfirst(strtolower($insert_row['insertUnit'])));else $unitText = date('H:i'); //current time, 24 hour, leading 0 (23:59)
							$sql = "
							insert into dw_unit          (  unitCypher ,  unitText,                unitLocation  , unitActive, unitModUser, unitModDate)
							values                       (      ?      ,      ?   ,                    ?         ,     1     ,     ?      ,    now()   )
						";
							if(!savesql($link, $sql, "isii", array($new_cypherID, $unitText, $insert_row['insertLocation'], $_SESSION['userID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
						}
					}


					$sql = "
					insert into dw_unit (unitCypher, unitText, unitLocation, unitActive, unitModUser, unitModDate)
					values              (    ?     ,     ?   ,     ?       ,     1     ,     ?      ,    now()   )
				";

					if(isset($_POST['sample1']) && $_POST['sample1']!="" && $_POST['location1']!=""){
						if(!savesql($link, $sql, "isii", array($new_cypherID, $_POST['sample1'], $_POST['location1'], $_SESSION['userID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					}
					if(isset($_POST['sample2']) && $_POST['sample2']!="" && $_POST['location2']!=""){
						if(!savesql($link, $sql, "isii", array($new_cypherID, $_POST['sample2'], $_POST['location2'], $_SESSION['userID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					}
					if(isset($_POST['sample3']) && $_POST['sample3']!="" && $_POST['location3']!=""){
						if(!savesql($link, $sql, "isii", array($new_cypherID, $_POST['sample3'], $_POST['location3'], $_SESSION['userID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					}
					if(isset($_POST['sample4']) && $_POST['sample4']!="" && $_POST['location4']!=""){
						if(!savesql($link, $sql, "isii", array($new_cypherID, $_POST['sample4'], $_POST['location4'], $_SESSION['userID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					}
					if(isset($_POST['sample5']) && $_POST['sample5']!="" && $_POST['location5']!=""){
						if(!savesql($link, $sql, "isii", array($new_cypherID, $_POST['sample5'], $_POST['location5'], $_SESSION['userID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					}
					if(isset($_POST['sample6']) && $_POST['sample6']!="" && $_POST['location6']!=""){
						if(!savesql($link, $sql, "isii", array($new_cypherID, $_POST['sample6'], $_POST['location6'], $_SESSION['userID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					}
					if(isset($_POST['sample7']) && $_POST['sample7']!="" && $_POST['location7']!=""){
						if(!savesql($link, $sql, "isii", array($new_cypherID, $_POST['sample7'], $_POST['location7'], $_SESSION['userID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					}
					if(isset($_POST['sample8']) && $_POST['sample8']!="" && $_POST['location8']!=""){
						if(!savesql($link, $sql, "isii", array($new_cypherID, $_POST['sample8'], $_POST['location8'], $_SESSION['userID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					}
					if(isset($_POST['sample9']) && $_POST['sample9']!="" && $_POST['location9']!=""){
						if(!savesql($link, $sql, "isii", array($new_cypherID, $_POST['sample9'], $_POST['location9'], $_SESSION['userID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					}
					if(isset($_POST['sample10']) && $_POST['sample10']!="" && $_POST['location10']!=""){
						if(!savesql($link, $sql, "isii", array($new_cypherID, $_POST['sample10'], $_POST['location10'], $_SESSION['userID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					}
				}
			}
		}
	}else{
		if(isset($_POST['confirm']) && $_POST['confirm']!="" && $_POST['confirm']!=null){
			//echo "confirmed";
			$cypherID     = clean($_POST['cypherID'    ]);
			$add_date     = clean($_POST['add_date'    ]);
			$add_spec     = clean($_POST['add_spec'    ]);
			$spectext     = clean($_POST['spectext'    ]);
			$add_batch    = clean($_POST['add_batch'   ]);
			$add_comments = clean($_POST['add_comments']);

			//get cypher code
			$cyphertext = date2cypher($add_date);

			//get expiry date
			$expiry = getexpiry($add_date, $add_spec);

			$sql="
				# get spec text for confirmed cypher
				Select
					dw_spec.specText
				From
					dw_spec
				Where
					dw_spec.specID = ?
			";
			if(!$spec_query = mysqli_prepared_query($link, $sql, "i", array($add_spec), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			$spec_row = $spec_query[0];

			$add_batch = str_replace('/','-', $add_batch); //replace slashes with dashes. When submitting to lab it thinks the date is a directory (Could not open subforms/4/pre-reg-ODL-EA08-06/07/2017-LAC-Lactose-04.csv for writing, check path exists)

			$sql="
				# create duplicate cypher
				INSERT INTO dw_cypher            ( cypherText, cypherOrderID, cypherSpec, cypherManuDate, cypherExpiryDate, cypherNotesFP,          cypherSite  ,   cypherModUser   , cypherModDate)
				VALUES                           (       ?   ,       ?      ,       ?   ,       ?       ,       ?         ,       ?      ,                ?     ,         ?         ,     now()    )
			";
			if(!$cypherID = savesql($link, $sql, "ssisssii", array($cyphertext,   $add_batch ,  $add_spec,      $add_date,      $expiry    , $add_comments, $_SESSION['userSite'], $_SESSION['userID']              ), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);

			$sql="
				# sampling plan - auto add samples for duplicate cypher ".$cypherID."
				Select
					dw_insert.insertUnit,
					dw_insert.insertLocation
				From
					dw_insert
				Where
					dw_insert.insertSpec = ?
			";
			if(!$insert_query = mysqli_prepared_query($link, $sql, "i", array($add_spec), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			if(mysqli_prepared_num_rows($insert_query)>0){
				foreach($insert_query as $insert_row){
					if(isset($insert_row['insertUnit']) && $insert_row['insertUnit']!="" && $insert_row['insertUnit']!=null) $unitText = clean(ucfirst($insert_row['insertUnit']));
					else $unitText = date('H:i'); //current time, 24 hour, leading 0 (00:00)
					$sql="
						# auto add unit for dup cypher
						Insert into dw_unit          (unitCypher,  unitText,                unitLocation  , unitActive, unitModUser, unitModDate)
						Values                       (    ?     ,      ?   ,                    ?         ,     1     ,     ?      ,    now()   )
					";
					if(!savesql($link, $sql, "isii", array( $cypherID, $unitText, $insert_row['insertLocation'],         $_SESSION['userID']         ), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
				}
			}

		}else{
			if(isset($_POST['edit_cypherID']) && $_POST['edit_cypherID']!="" && $_POST['edit_cypherID']!=null){
				//edit existing cypher details
				$edit_cypher_orderID = clean($_POST['edit_cypher_orderID']);
				$edit_cypher_orderID = str_replace('/','-', $edit_cypher_orderID); //replace slashes with dashes. When submitting to lab it thinks the date is a directory (Could not open subforms/4/pre-reg-ODL-EA08-06/07/2017-LAC-Lactose-04.csv for writing, check path exists)

				if(isset($_POST['edit_cypher_auto_expiry']) && ($_POST['edit_cypher_auto_expiry']==1 || $_POST['edit_cypher_auto_expiry']=='1') && isset($_POST['edit_cypher_product'])) $expiry = getexpiry($_POST['edit_date'], $_POST['edit_cypher_product']);
				else $expiry = clean($_POST['edit_expiry']);

				if(!isset($_POST['edit_cypher_received_date']) || $_POST['edit_cypher_received_date']=="") $edit_cypher_received_date = Null;
				else $edit_cypher_received_date = $_POST['edit_cypher_received_date'];

				if(!isset($_POST['edit_cypher_received_by']) || $_POST['edit_cypher_received_by']=="") $edit_cypher_received_by = Null;
				else $edit_cypher_received_by = $_POST['edit_cypher_received_by'];

				$sql="
					UPDATE dw_cypher SET
						cypherText         = ?,
						cypherOrderID      = ?,
						cypherSpec         = ?,
						cypherManuDate     = ?,
						cypherExpiryDate   = ?,
						cypherNotesFP      = ?,
						cypherModDate      = now(),
						cypherModUser      = ?,
						cypherChangeCode   = ?,
						cypherReceivedDate = ?,
						cypherReceivedBy   = ?
					WHERE cypherID       = ?
				";
				if(!savesql($link, $sql, "ssisssisssi", array(
					date2cypher($_POST['edit_date']),
					$edit_cypher_orderID,
					$_POST['edit_cypher_product'],
					$_POST['edit_date'],
					$expiry,
					$_POST['edit_cypher_notes'],

					$_SESSION['userID'],
					$_POST['edit_cypher_reason'],
					$edit_cypher_received_date,
					$edit_cypher_received_by,
					$_POST['edit_cypherID']
				), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);

				//insert file
				if(isset($_FILES['edit_cypher_file']) && $_FILES['edit_cypher_file']['error']==0 && $_FILES['edit_cypher_file']['size']>1){
					//http://www.php-mysql-tutorial.com/wikis/mysql-tutorials/uploading-files-to-mysql-database.aspx

					$fileName = $_FILES['edit_cypher_file']['name'];
					$tmpName  = $_FILES['edit_cypher_file']['tmp_name'];
					$fileSize = $_FILES['edit_cypher_file']['size'];
					$fileType = $_FILES['edit_cypher_file']['type'];

					$fp      = fopen($tmpName, 'r');
					$content = fread($fp, filesize($tmpName));
					$content = addslashes($content); //this is important
					fclose($fp);

					$sql="
						INSERT INTO dw_file          ( filename,  filesize,  filetype,  content)
						VALUES                       (     ?   ,      ?   ,      ?   ,     ?   )
					";
					if(!savesql($link, $sql, "sssb", array($fileName, $fileSize, $fileType, $content), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);

					$sql="
						# done file upload, now to link with cypher
						Select fileID
						From dw_file
						Where fileID > ?
						Order By fileID Desc
						Limit 1
					";
					if(!$file_query = mysqli_prepared_query($link, $sql, "i", array(0), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					$file_row = $file_query[0];

					$sql="
						UPDATE dw_cypher SET
							cypherFile   = ?
						WHERE cypherID = ?
					";
					if(!savesql($link, $sql, "ii", array($file_row['fileID'], $edit_cypherID), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
				}
			}else{
				if(isset($_POST['sample_cypher_new']) && $_POST['sample_cypher_new']!="" && $_POST['sample_cypher_new']!=null && isset($_POST['sample_location_new']) && !empty($_SESSION) && $_SESSION['userLevel'] <= $_SESSION['admin_unit_add']){
					$sample_cypher_new = clean($_POST['sample_cypher_new']);
					$sample_new = clean(ucfirst($_POST['sample_new']));
					$sample_location_new = clean($_POST['sample_location_new']);
					if($sample_location_new=="" || $sample_location_new==null) $sample_location_new=0;

					$sql="
						# check if sample already exists
						Select
							dw_unit.unitID
						From
							dw_unit
						Where
							dw_unit.unitText     = ? And
							dw_unit.unitCypher   = ? And
							dw_unit.unitLocation = ?
					";
					if(!$sample_query = mysqli_prepared_query($link, $sql, "sii", array($sample_new, $sample_cypher_new, $sample_location_new), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					if(mysqli_prepared_num_rows($sample_query)>0){
						//sample already exists
						$message['type']="error";
						$message['text'] = "That sample already exists! Please enter a different sample text";
					}else{
						//sample does not exist
						$sql="
							INSERT INTO dw_unit          (    unitCypher    ,   unitText ,     unitLocation    , unitActive, unitModUser, unitModDate)
							VALUES                       (        ?         ,       ?    ,         ?           ,     1     ,     ?      ,    now()   )
						";
						if(!savesql($link, $sql, "isii", array($sample_cypher_new, $sample_new, $sample_location_new,         $_SESSION['userID']         ), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					}
				}else{
					if(isset($_POST['sample_cypher_vu_b']) && $_POST['sample_cypher_vu_b']!="" && $_POST['sample_cypher_vu_b']!=null){
						//update existing sample
						$sample_cypher_vu_b = clean($_POST['sample_cypher_vu_b']); //cypherid
						$sample_id_vu_b = clean($_POST['sample_id_vu_b']); //unitid
						$sample_vu_b = clean(ucfirst($_POST['sample_vu_b'])); //sampletext
						$sample_location_vu_b = clean($_POST['sample_location_vu_b']); //locationid
						$sample_comp_vu_b = clean($_POST['sample_comp_vu_b']); //compid
						if(isset($_POST['sample_active_vu_b'])) $sample_active_vu_b = clean($_POST['sample_active_vu_b']); //active status
						else $sample_active_vu_b = 0;
						$sample_reason_vu_b = clean($_POST['sample_reason_vu_b']); //change reason

						if($sample_comp_vu_b==null || $sample_comp_vu_b=="" || $sample_comp_vu_b==0 || $sample_comp_vu_b=='0'){
							//not part of a comp
							$sql="
								UPDATE dw_unit SET
									unitText       = ?,
									unitCypher     = ?,
									unitLocation   = ?,
									unitCompText   = null,
									unitActive     = ?,
									unitModUser    = ?,
									unitModDate    = now(),
									unitChangeCode = ?
								WHERE unitID     = ?
							";
							if(!savesql($link, $sql, "siiiisi", array(
								$sample_vu_b,
								$sample_cypher_vu_b,
								$sample_location_vu_b,

								$sample_active_vu_b,
								$_SESSION['userID'],

								$sample_reason_vu_b,
								$sample_id_vu_b
							), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
						}else{
							//part of a comp
							$sql="
								UPDATE dw_unit SET
									unitText       = ?,
									unitCypher     = ?,
									unitLocation   = ?,
									unitCompText   = ?,
									unitActive     = ?,
									unitModUser    = ?,
									unitModDate    = now(),
									unitChangeCode = ?
								WHERE unitID     = ?
							";
							if(!savesql($link, $sql, "siiiii si", array(
								$sample_vu_b,
								$sample_cypher_vu_b,
								$sample_location_vu_b,
								$sample_comp_vu_b,
								$sample_active_vu_b,
								$_SESSION['userID'],

								$sample_reason_vu_b,
								$sample_id_vu_b
							), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
						}
					}
				}
			}
		}
	}

	if(isset($_POST['edit_delete']) && isset($_POST['edit_cypherID'])){
		//check to see if there are any units
		$sql="
			Select unitID
			From dw_unit
			Where unitCypher = ?
		";
		if(!$query = mysqli_prepared_query($link, $sql, "i", array($_POST['edit_cypherID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		if(mysqli_prepared_num_rows($query)>0){
			$message['type'] = "error";
			$message['text'] = "<span class='glyphicon glyphicon-warning-sign' aria-hidden='true'></span> The cypher contains samples (some of these might be inactive), and cannot be deleted";
		}else{
			//check if it's over a week old
			$sql="
				Select cypherManuDate
				From dw_cypher
				Where cypherID = ?
			";
			if(!$query = mysqli_prepared_query($link, $sql, "i", array($_POST['edit_cypherID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			$row = $query[0];
			if(date('Y-m-d',strtotime($row['cypherManuDate']))>date('Y-m-d',strtotime('-7 days'))){
				$message['type'] = "error";
				$message['text'] = "<span class='glyphicon glyphicon-warning-sign' aria-hidden='true'></span> The cypher is less than a week old. You will need to wait until it is at least a week old first";
			}else{
				if($_SESSION['userLevel']<=$_SESSION['admin_cypher_delete']){
					$sql="
						delete from dw_cypher
						where cypherid = ?
					";
					if(!savesql($link, $sql, "i", array($_POST['edit_cypherID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					$message['type'] = "ok";
					$message['text'] = "Cypher deleted";
				}else{
					$message['type'] = "error";
					$message['text'] = "<span class='glyphicon glyphicon-warning-sign' aria-hidden='true'></span> Sorry but you do not have the correct access level to delete cyphers";
				}
			}
		}
	}

	$title = $cypherorbatchtext."s";
	require "inc/head.php";
	$menu = "cypher";
	require "inc/menu.php";

	if($debug) showdebug();
?>

<div id="topDIV" >
	<h1 class="text-center">
		<?php
			switch($_SESSION['cypherorbatch']){
				case 0:
					echo "Cyphers";
					break;
				case 1:
					echo "Batches";
					break;
				default:
					echo "Cyphers/Batches";
			}
			if($_SESSION['userLevel']<= $_SESSION['admin_cypher_add']) {
				echo "&nbsp;<button type='button' class='btn btn-default btn-primary hidden-print' data-toggle='modal' data-target='#new_cypher' onclick='update_cypher_new();' id='create_new_cypher_button'><span class='glyphicon glyphicon-plus' aria-hidden='true'></span>&nbsp;Create new</button>";
			}
		?>
	</h1>
</div>

<div id="main"        class="container-fluid" style="display:nonex;" role="main" >
	<!--
	  __  __       _
	 |  \/  | __ _(_)_ __
	 | |\/| |/ _` | | '_ \
	 | |  | | (_| | | | | |
	 |_|  |_|\__,_|_|_| |_|

	-->
	<table class="table table-hover sorttable" id="table">
		<thead>
			<tr id="table-head" style="background-color:white;color:inherit;white-space:nowrap;">
				<th class="text-center th_buttons" id="th_buttons" ><span class="sr-only">Buttons</span></th>
				<th class="text-center th_date"    id="th_date"    >Date</th>
				<th class="text-center th_file"    id="th_file"    ><!-- File --></th>
				<th class="text-center th_cypher"  id="th_cypher"  ><?php
					switch($_SESSION['cypherorbatch']){
						case 0:
							echo "Cyphers";
							break;
						case 1:
							echo "Batches";
							break;
						default:
							echo "Cyphers/Batches";
					}
				?></th>
				<th class="text-center th_product" id="th_product" >Product</th>
				<th class="text-center th_samples" id="th_samples" >Samples</th>
				<th class="text-center th_units"   id="th_units"   >Pallets</th>
				<th class="text-center th_bags"    id="th_bags"    >Bags made</th>
				<th class="text-center th_kgs"     id="th_kgs"     >Kgs made</th>
				<?php if($_SESSION['userLevel']==1 || $_SESSION['userLevel']=="1"){ ?>
					<th class="text-center th_mod"   id="th_mod"     >Modified by</th>
				<?php } ?>
				<th style="display:none;"          id="th_rec_date">Received date</th>
				<th style="display:none;"          id="th_rec_by"  >Received by</th>
				<th style="display:none;"          id="th_file"    >File ID</th>
				<th class="th_notes"               id="th_notes"   >Notes</th>
				<th style="display:none;"          id="th_specUnitTypeText"  >specUnitTypeText</th>
			</tr>
		</thead>
		<tbody>
			<?php

				$sql="
					# sql for main table
					Select
						dw_cypher.cypherID, dw_cypher.cypherText, dw_cypher.cypherOrderID, dw_spec.specText,
						dw_cypher.cypherManuDate, dw_cypher.cypherExpiryDate, dw_cypher.cypherNotesFP,
						dw_expiry.expiryYear, dw_expiry.expiryMonth, dw_expiry.expiryDay, dw_user.userFirst,
						dw_user.userLast, dw_cypher.cypherModDate, dw_spec.specStyle, dw_change.changeText,
						dw_spec.specUnitTypeText, dw_cypher.cypherReceivedDate, dw_cypher.cypherReceivedBy,
						dw_file.fileName, dw_file.fileID, dw_file.fileSize, dw_file.fileType
					From
						dw_change Right Join
						(dw_user Right Join
						(dw_expiry Right Join
						(dw_spec Right Join
						dw_cypher
							On dw_spec.specID = dw_cypher.cypherSpec)
							On dw_expiry.expiryID = dw_spec.specExpiry)
							On dw_user.userID = dw_cypher.cypherModUser)
							On dw_change.changeID = dw_cypher.cypherChangeCode Left Join
						dw_file
							On dw_cypher.cypherFile = dw_file.fileID
					Where dw_cypher.cypherSite = ?
					Order By dw_cypher.cypherManuDate DESC, dw_spec.specOrder
					Limit ?
				";
				if(!$cypher_query = mysqli_prepared_query($link, $sql, "ii", array($_SESSION['userSite'], $cyphers_per_page), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
				if(mysqli_prepared_num_rows($cypher_query)>0){
					$get_cypher_exists = false;
					foreach($cypher_query as $cypher_row){
						if((isset($_GET['c']) && $cypher_row['cypherID']==$_GET['c']) || (isset($_GET['u']) && $cypher_row['cypherID']==$_GET['u'])) $get_cypher_exists = true;
						/*
							_____                            _                        _
						 |  ___|__  _ __    ___  __ _  ___| |__     ___ _   _ _ __ | |__   ___ _ __
						 | |_ / _ \| '__|  / _ \/ _` |/ __| '_ \   / __| | | | '_ \| '_ \ / _ \ '__|
						 |  _| (_) | |    |  __/ (_| | (__| | | | | (__| |_| | |_) | | | |  __/ |_ _ _
						 |_|  \___/|_|     \___|\__,_|\___|_| |_|  \___|\__, | .__/|_| |_|\___|_(_|_|_)
																														|___/|_|
						*/
						//if($debug) echo "[cypher] get units for '".$cypher_row['cypherID']."'<br>";
						$unitinfo = get_units($cypher_row['cypherID']); //this is used to get data for table
						if(isset($_GET['c']) && $_GET['c']!="") $c = clean($_GET['c']);
						else $c = 0;
						if(isset($_GET['u']) && $_GET['u']!="") $c = clean($_GET['u']);
						else $c = 0;
						?>
							<tr class="text-nowrap style<?php echo $cypher_row['specStyle']; if($cypher_row['cypherID']==$c) echo " active"; ?>" id="cypher-<?php echo $cypher_row['cypherID']; ?>">
								<td class="text-center th_buttons">
									<div style="display:none;" id="cypher_expiry_<?php echo $cypher_row['cypherID']; ?>">
										<?php echo date('d/m/Y', strtotime($cypher_row['cypherExpiryDate'])); ?>
									</div>
									<div style="display:none;" id="cypher_expiry2_<?php echo $cypher_row['cypherID']; ?>">
										<?php
											$date1 = date('Y-m-d', strtotime($cypher_row['cypherManuDate']." +".$cypher_row['expiryYear']." years"));
											$date2 = date('Y-m-d', strtotime($date1." +".$cypher_row['expiryMonth']." months"));
											$date3 = date('Y-m-d', strtotime($date2." +".$cypher_row['expiryDay']." days"));
											echo     date('d/m/Y', strtotime($date3));
										?>
									</div>

									<form style="display:inline;" action="results.php?r=<?php echo $cypher_row['cypherID']; ?>" method="get">
										<input type="hidden" name="r" value="<?php echo $cypher_row['cypherID']; ?>">
										<button type="submit" class="btn btn-default btn-xs">
											<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
											<span class="sr-only">View results</span>
											<span class="hidden-xs"> View results</span>
										</button>
									</form>
									<?php if($_SESSION['userLevel']<= $_SESSION['admin_cypher_edit']){ ?>
									<button type="button" class="btn btn-xs" data-toggle="modal" data-target="#edit_cypher" onclick="update_cypher_edit(<?php echo $cypher_row['cypherID'].", ".(int)$debug.", ".$_SESSION['cypherorbatch']; ?>);">
										<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
										<span class="sr-only">Edit <?php echo $cypherorbatchtext; ?></span>
										<span class="hidden-xs"> Edit <?php echo $cypherorbatchtext; ?></span>
									</button>
									<?php } ?>
								</td>
								<td class="text-center th_date"    id="cypher_date_<?php     echo $cypher_row['cypherID']; ?>"><?php echo date('d/m/Y', strtotime($cypher_row['cypherManuDate'])); ?></td>
								<td class="text-center th_file2"   id="cypher_file2_<?php    echo $cypher_row['cypherID']; ?>"><?php if($cypher_row['fileName']!="") echo "<a href='inc/download.php?id=".$cypher_row['fileID']."' title='".$cypher_row['fileName']."'><img src='images/file.png' width='25' height='25' alt='file'></a>"; ?></td>
								<td class="text-center th_cypher"  id="cypher_text_<?php     echo $cypher_row['cypherID']; ?>"><?php
									if($_SESSION['cypherorbatch']==0 || $_SESSION['cypherorbatch']=='0') echo $cypher_row['cypherText'];
									else if($_SESSION['cypherorbatch']==1 || $_SESSION['cypherorbatch']=='1') echo $cypher_row['cypherOrderID'];
									else echo $cypher_row['cypherText']." ".$cypher_row['cypherOrderID']; //2=both
									if($debug) echo " <small>[".$cypher_row['cypherID']."]</small>";
									?></td>
								<td class="text-center th_product" id="cypher_product_<?php  echo $cypher_row['cypherID']; ?>"><?php echo $cypher_row['specText']; ?></td>
								<td class="text-center th_samples" id="cypher_samples_<?php  echo $cypher_row['cypherID']; ?>">
									<!--
										 __                       _
										/ _\ __ _ _ __ ___  _ __ | | ___
										\ \ / _` | '_ ` _ \| '_ \| |/ _ \
										_\ \ (_| | | | | | | |_) | |  __/
										\__/\__,_|_| |_| |_| .__/|_|\___|
																			 |_|
									-->
									<div style='display:none;' id='sample_list_<?php echo $cypher_row['cypherID']; ?>' >
										<?php
											//get list of samples. when the user clicks on the button (which is just about to get made) the list here will replace the new modal div
											//this is a <select> purely so we can navigate the DOM using javascript and access items in it, and convert to <li>'s
											//as well as getting first and last samples, also need to create the badge, which shows number of samples
											$sql="
												Select
													dw_unit.unitID,
													dw_unit.unitText,
													dw_unit.unitActive,
													dw_location.locationID,
													dw_location.locationText,
													dw_user.userFirst,
													dw_user.userLast,
													dw_change.changeText,
													dw_unit.unitModDate,
													dw_unit.unitCompText
												From
													dw_user Right Join
													(dw_change Right Join
													(dw_location Right Join
													dw_unit
														On dw_location.locationID = dw_unit.unitLocation)
														On dw_change.changeID = dw_unit.unitChangeCode)
														On dw_user.userID = dw_unit.unitModUser
												Where
													dw_unit.unitCypher = ?
												Order By
													dw_unit.unitActive Desc,
													Case dw_unit.unitText
														When 'F' Then 1
														When 'M' Then 2
														When 'L' Then 3
														Else 4
													End,
													Field(dw_unit.unitText, 'F', 'M', 'L', 'Comp', 'comp', 'Comp1', 'Comp 1', 'Comp2', 'Comp 2'),
													LPad(dw_unit.unitText, 20, 0),
													dw_location.locationOrder,
													dw_location.locationText
											";
											if(!$sample_query = mysqli_prepared_query($link, $sql, "i", array($cypher_row['cypherID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
										?>
										<select name='vu_<?php echo $cypher_row['cypherID']; ?>' >
											<?php
												$num_samples = 0;
												if(mysqli_prepared_num_rows($sample_query)>0){
													foreach($sample_query as $sample_row){
														echo "<option value='".$sample_row['unitID'].",".$sample_row['locationID']."'>".$sample_row['unitText'].",".$sample_row['locationText'].",".$sample_row['unitActive'].",".$sample_row['unitCompText'].","; //use js later to extract this info (will be called 'sel')
															if($sample_row['changeText']!="" && $sample_row['changeText']!=null) echo $sample_row['userFirst'].$sample_row['userLast'][0]." ".$sample_row['changeText']." ";
															else echo "Created by ".$sample_row['userFirst'].$sample_row['userLast'][0].", ";
															echo date('d/m/y',strtotime($sample_row['unitModDate']))."</option>";
														if($sample_row['unitActive']==1 || $sample_row['unitActive']=="1"){
															$num_samples++;
														}
													}
												}
											?>
										</select>
										<div id="cypher_first_unit_<?php echo $cypher_row['cypherID']; ?>"><?php echo $unitinfo[0]; ?></div>
										<div id="cypher_last_unit_<?php  echo $cypher_row['cypherID']; ?>"><?php echo $unitinfo[1]; ?></div>
									</div>
									<div style='display:none;' >
										<?php
											/*
											$sql="
												Select
													dw_unit.unitID,
													dw_unit.unitText
												From
													dw_unit
												Where
													(dw_unit.unitText Like '%comp%' Or dw_unit.unitText Like 'silo%') And
													dw_unit.unitActive = 1 And
													dw_unit.unitCypher = ?
												Order By
													dw_unit.unitText
											";
											if(!$comp_query = mysqli_prepared_query($link, $sql, "i", array($cypher_row['cypherID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
											*/
										?>
										<select name='sample_comp_vu_<?php echo $cypher_row['cypherID']; ?>' id='comp_list_<?php echo $cypher_row['cypherID']; ?>' >
											<option value='0'>Not part of comp</option>
											<?php
												$num_comps = 0;
												foreach($sample_query as $comp_row){
													if(stristr($comp_row['unitText'], 'comp') || stristr($comp_row['unitText'], 'silo')) echo "<option value='".$comp_row['unitID']."'>".$comp_row['unitText']."</option>";
												}
											?>
										</select>
									</div>
									<?php
										echo "<button type='button' class='btn btn-xs' data-toggle='modal' data-target='#view_units' onclick='update_samples(".$cypher_row['cypherID'].","; if($debug) echo "1"; else echo "0"; echo ",".$allow_edit.",\"".$cypherorbatchtext."\");' id='cypher_samples_".$cypher_row['cypherID']."'>";
										if($num_samples==0) echo "<span class='badge'>0</span>";
										else{
											if($unitinfo[0]==$unitinfo[1]) echo $unitinfo[0];
											else echo $unitinfo[0]."-".$unitinfo[1];
											echo " <span class='badge'>".$num_samples."</span>";
										}
										echo "</button>";
									?>
								</td>
								<td class="text-center th_units"   id="cypher_units_<?php    echo $cypher_row['cypherID']; ?>"><?php if($cypher_row['specStyle']==1) echo number_format($unitinfo[2]); ?></td><!-- Pallets -->
								<td class="text-center th_bags"    id="cypher_bags_<?php     echo $cypher_row['cypherID']; ?>"><?php if($cypher_row['specStyle']==1) echo number_format($unitinfo[3]); ?></td><!-- Bags -->
								<td class="text-center th_kgs"     id="cypher_kgs_<?php      echo $cypher_row['cypherID']; ?>"><?php if($cypher_row['specStyle']==1) echo number_format($unitinfo[4]); ?></td><!-- KGs -->
								<?php
									if($_SESSION['userLevel']==1 || $_SESSION['userLevel']=="1"){
										$fullname = $cypher_row['userFirst']." ".$cypher_row['userLast'][0];
									?>
									<td class="text-center th_mod" id="cypher_mod_<?php echo $cypher_row['cypherID']; ?>" title="<?php echo $cypher_row['changeText']; ?>" ><?php echo $fullname." ".date('j/n/y',strtotime($cypher_row['cypherModDate'])); ?></td>
								<?php } ?>
								<td style="display:none;"          id="cypher_rec_date_<?php echo $cypher_row['cypherID']; ?>"><?php echo $cypher_row['cypherReceivedDate']; ?></td>
								<td style="display:none;"          id="cypher_rec_by_<?php   echo $cypher_row['cypherID']; ?>"><?php echo $cypher_row['cypherReceivedBy']; ?></td>
								<td style="display:none;"          id="cypher_file_<?php     echo $cypher_row['cypherID']; ?>"><?php
									if($cypher_row['fileName']!=""){
										echo "<a href='inc/download.php?id=".$cypher_row['fileID']."'><img src='images/file.png'>&nbsp;".$cypher_row['fileName']."</a>&nbsp;(".number_format(($cypher_row['fileSize']/1024),1)." KB)";
									}
								?></td>
								<td class="text-justify text-overflow th_notes" id="cypher_notes_<?php echo $cypher_row['cypherID']; ?>"><?php echo $cypher_row['cypherNotesFP']; ?></td>
								<td style="display:none;"          id="cypher_spec_unit_type_text_<?php echo $cypher_row['cypherID']; ?>"><?php echo $cypher_row['specUnitTypeText']; ?></td>
							</tr>
						<?php
					}
					//check to see if get data is in sql

					if(!$get_cypher_exists){
						if(isset($_GET['c']) && $_GET['c']!="") $c = clean($_GET['c']);
						else $c = 0;
						if(isset($_GET['u']) && $_GET['u']!="") $c = clean($_GET['u']);
						else $c = 0;
						echo '<script>console.log("cypher didnt exist, getting now");</script>';
						//need to include the required cypher (from get)
						if(!empty($_GET['c']) && $c==0) $c=clean($_GET['c']);
						$sql="# sql for main table
							Select
								dw_cypher.cypherID, dw_cypher.cypherText, dw_cypher.cypherOrderID, dw_spec.specText,
								dw_cypher.cypherManuDate, dw_cypher.cypherExpiryDate, dw_cypher.cypherNotesFP,
								dw_expiry.expiryYear, dw_expiry.expiryMonth, dw_expiry.expiryDay, dw_user.userFirst,
								dw_user.userLast, dw_cypher.cypherModDate, dw_spec.specStyle, dw_change.changeText,
								dw_spec.specUnitTypeText, dw_cypher.cypherReceivedDate, dw_cypher.cypherReceivedBy,
								dw_file.fileName, dw_file.fileID, dw_file.fileSize, dw_file.fileType
							From
								dw_change Right Join
								(dw_user Right Join
								(dw_expiry Right Join
								(dw_spec Right Join
								dw_cypher
									On dw_spec.specID = dw_cypher.cypherSpec)
									On dw_expiry.expiryID = dw_spec.specExpiry)
									On dw_user.userID = dw_cypher.cypherModUser)
									On dw_change.changeID = dw_cypher.cypherChangeCode Left Join
								dw_file
									On dw_cypher.cypherFile = dw_file.fileID
							Where
								dw_cypher.cypherID = ? And
								dw_cypher.cypherSite = ?
						";
						if(!$cypher_query = mysqli_prepared_query($link, $sql, "ii", array($c, $_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);

						echo '<script>console.log("c:'.$c.'");</script>';
						echo '<script>console.log("userSite:'.$_SESSION['userSite'].'");</script>';
						echo '<script>console.log("'.mysqli_prepared_num_rows($cypher_query).' records found");</script>';
						if(mysqli_prepared_num_rows($cypher_query)>0){
							$cypher_row = $cypher_query[0];
							$unitinfo = get_units($cypher_row['cypherID']); //this is used to get data for table
							?>
							<tr class="text-nowrap style<?php echo $cypher_row['specStyle']; if($cypher_row['cypherID']==$c) echo " active"; ?>" id="cypher-<?php echo $cypher_row['cypherID']; ?>">
								<td class="text-center th_buttons">
									<div style="display:none;" id="cypher_expiry_<?php echo $cypher_row['cypherID']; ?>">
										<?php echo date('d/m/Y', strtotime($cypher_row['cypherExpiryDate'])); ?>
									</div>
									<div style="display:none;" id="cypher_expiry2_<?php echo $cypher_row['cypherID']; ?>">
										<?php
											$date1 = date('Y-m-d', strtotime($cypher_row['cypherManuDate']." +".$cypher_row['expiryYear']." years"));
											$date2 = date('Y-m-d', strtotime($date1." +".$cypher_row['expiryMonth']." months"));
											$date3 = date('Y-m-d', strtotime($date2." +".$cypher_row['expiryDay']." days"));
											echo     date('d/m/Y', strtotime($date3));
										?>
									</div>

									<form style="display:inline;" action="results.php?r=<?php echo $cypher_row['cypherID']; ?>" method="get">
										<input type="hidden" name="r" value="<?php echo $cypher_row['cypherID']; ?>">
										<button type="submit" class="btn btn-default btn-xs">
											<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
											<span class="sr-only">View results</span>
											<span class="hidden-xs"> View results</span>
										</button>
									</form>
									<?php if($_SESSION['userLevel']<= $_SESSION['admin_cypher_edit']){ ?>
										<button type="button" class="btn btn-xs" data-toggle="modal" data-target="#edit_cypher" onclick="update_cypher_edit(<?php echo $cypher_row['cypherID'].", ".(int)$debug.", ".$_SESSION['cypherorbatch']; ?>);">
											<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
											<span class="sr-only">Edit <?php echo $cypherorbatchtext; ?></span>
											<span class="hidden-xs"> Edit <?php echo $cypherorbatchtext; ?></span>
										</button>
									<?php } ?>
								</td>
								<td class="text-center th_date"    id="cypher_date_<?php     echo $cypher_row['cypherID']; ?>"><?php echo date('d/m/Y', strtotime($cypher_row['cypherManuDate'])); ?></td>
								<td class="text-center th_file2"   id="cypher_file2_<?php    echo $cypher_row['cypherID']; ?>"><?php if($cypher_row['fileName']!="") echo "<a href='inc/download.php?id=".$cypher_row['fileID']."' title='".$cypher_row['fileName']."'><img src='images/file.png' width='25' height='25' alt='file'></a>"; ?></td>
								<td class="text-center th_cypher"  id="cypher_text_<?php     echo $cypher_row['cypherID']; ?>"><?php
										if($_SESSION['cypherorbatch']==0 || $_SESSION['cypherorbatch']=='0') echo $cypher_row['cypherText'];
										else if($_SESSION['cypherorbatch']==1 || $_SESSION['cypherorbatch']=='1') echo $cypher_row['cypherOrderID'];
										else echo $cypher_row['cypherText']." ".$cypher_row['cypherOrderID']; //2=both
										if($debug) echo " <small>[".$cypher_row['cypherID']."]</small>";
									?></td>
								<td class="text-center th_product" id="cypher_product_<?php  echo $cypher_row['cypherID']; ?>"><?php echo $cypher_row['specText']; ?></td>
								<td class="text-center th_samples" id="cypher_samples_<?php  echo $cypher_row['cypherID']; ?>">
									<!--
										 __                       _
										/ _\ __ _ _ __ ___  _ __ | | ___
										\ \ / _` | '_ ` _ \| '_ \| |/ _ \
										_\ \ (_| | | | | | | |_) | |  __/
										\__/\__,_|_| |_| |_| .__/|_|\___|
																			 |_|
									-->
									<div style='display:none;' id='sample_list_<?php echo $cypher_row['cypherID']; ?>' >
										<?php
											//get list of samples. when the user clicks on the button (which is just about to get made) the list here will replace the new modal div
											//this is a <select> purely so we can navigate the DOM using javascript and access items in it, and convert to <li>'s
											//as well as getting first and last samples, also need to create the badge, which shows number of samples
											$sql="
												Select
													dw_unit.unitID,
													dw_unit.unitText,
													dw_unit.unitActive,
													dw_location.locationID,
													dw_location.locationText,
													dw_user.userFirst,
													dw_user.userLast,
													dw_change.changeText,
													dw_unit.unitModDate,
													dw_unit.unitCompText
												From
													dw_user Right Join
													(dw_change Right Join
													(dw_location Right Join
													dw_unit
														On dw_location.locationID = dw_unit.unitLocation)
														On dw_change.changeID = dw_unit.unitChangeCode)
														On dw_user.userID = dw_unit.unitModUser
												Where
													dw_unit.unitCypher = ?
												Order By
													dw_unit.unitActive Desc,
													Case dw_unit.unitText
														When 'F' Then 1
														When 'M' Then 2
														When 'L' Then 3
														Else 4
													End,
													Field(dw_unit.unitText, 'F', 'M', 'L', 'Comp', 'comp', 'Comp1', 'Comp 1', 'Comp2', 'Comp 2'),
													LPad(dw_unit.unitText, 20, 0),
													dw_location.locationOrder,
													dw_location.locationText
											";
											if(!$sample_query = mysqli_prepared_query($link, $sql, "i", array($cypher_row['cypherID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
										?>
										<select name='vu_<?php echo $cypher_row['cypherID']; ?>' >
											<?php
												$num_samples = 0;
												if(mysqli_prepared_num_rows($sample_query)>0){
													foreach($sample_query as $sample_row){
														echo "<option value='".$sample_row['unitID'].",".$sample_row['locationID']."'>".$sample_row['unitText'].",".$sample_row['locationText'].",".$sample_row['unitActive'].",".$sample_row['unitCompText'].","; //use js later to extract this info (will be called 'sel')
														if($sample_row['changeText']!="" && $sample_row['changeText']!=null) echo $sample_row['userFirst'].$sample_row['userLast'][0]." ".$sample_row['changeText']." ";
														else echo "Created by ".$sample_row['userFirst'].$sample_row['userLast'][0].", ";
														echo date('d/m/y',strtotime($sample_row['unitModDate']))."</option>";
														if($sample_row['unitActive']==1 || $sample_row['unitActive']=="1"){
															$num_samples++;
														}
													}
												}
											?>
										</select>
										<div id="cypher_first_unit_<?php echo $cypher_row['cypherID']; ?>"><?php echo $unitinfo[0]; ?></div>
										<div id="cypher_last_unit_<?php  echo $cypher_row['cypherID']; ?>"><?php echo $unitinfo[1]; ?></div>
									</div>
									<div style='display:none;' >
										<?php
											/*
											$sql="
												Select
													dw_unit.unitID,
													dw_unit.unitText
												From
													dw_unit
												Where
													(dw_unit.unitText Like '%comp%' Or dw_unit.unitText Like 'silo%') And
													dw_unit.unitActive = 1 And
													dw_unit.unitCypher = ?
												Order By
													dw_unit.unitText
											";
											if(!$comp_query = mysqli_prepared_query($link, $sql, "i", array($cypher_row['cypherID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
											*/
										?>
										<select name='sample_comp_vu_<?php echo $cypher_row['cypherID']; ?>' id='comp_list_<?php echo $cypher_row['cypherID']; ?>' >
											<option value='0'>Not part of comp</option>
											<?php
												$num_comps = 0;
												foreach($sample_query as $comp_row){
													if(stristr($comp_row['unitText'], 'comp') || stristr($comp_row['unitText'], 'silo')) echo "<option value='".$comp_row['unitID']."'>".$comp_row['unitText']."</option>";
												}
											?>
										</select>
									</div>
									<?php
										echo "<button type='button' class='btn btn-xs' data-toggle='modal' data-target='#view_units' onclick='update_samples(".$cypher_row['cypherID'].","; if($debug) echo "1"; else echo "0"; echo ",".$allow_edit.",\"".$cypherorbatchtext."\");' id='cypher_samples_".$cypher_row['cypherID']."'>";
										if($num_samples==0) echo "<span class='badge'>0</span>";
										else{
											if($unitinfo[0]==$unitinfo[1]) echo $unitinfo[0];
											else echo $unitinfo[0]."-".$unitinfo[1];
											echo " <span class='badge'>".$num_samples."</span>";
										}
										echo "</button>";
									?>
								</td>
								<td class="text-center th_units"   id="cypher_units_<?php    echo $cypher_row['cypherID']; ?>"><?php if($cypher_row['specStyle']==1) echo number_format($unitinfo[2]); ?></td><!-- Pallets -->
								<td class="text-center th_bags"    id="cypher_bags_<?php     echo $cypher_row['cypherID']; ?>"><?php if($cypher_row['specStyle']==1) echo number_format($unitinfo[3]); ?></td><!-- Bags -->
								<td class="text-center th_kgs"     id="cypher_kgs_<?php      echo $cypher_row['cypherID']; ?>"><?php if($cypher_row['specStyle']==1) echo number_format($unitinfo[4]); ?></td><!-- KGs -->
								<?php
									if($_SESSION['userLevel']==1 || $_SESSION['userLevel']=="1"){
										$fullname = $cypher_row['userFirst']." ".$cypher_row['userLast'][0];
										?>
										<td class="text-center th_mod" id="cypher_mod_<?php echo $cypher_row['cypherID']; ?>" title="<?php echo $cypher_row['changeText']; ?>" ><?php echo $fullname." ".date('j/n/y',strtotime($cypher_row['cypherModDate'])); ?></td>
									<?php } ?>
								<td style="display:none;"          id="cypher_rec_date_<?php echo $cypher_row['cypherID']; ?>"><?php echo $cypher_row['cypherReceivedDate']; ?></td>
								<td style="display:none;"          id="cypher_rec_by_<?php   echo $cypher_row['cypherID']; ?>"><?php echo $cypher_row['cypherReceivedBy']; ?></td>
								<td style="display:none;"          id="cypher_file_<?php     echo $cypher_row['cypherID']; ?>"><?php
										if($cypher_row['fileName']!=""){
											echo "<a href='inc/download.php?id=".$cypher_row['fileID']."'><img src='images/file.png'>&nbsp;".$cypher_row['fileName']."</a>&nbsp;(".number_format(($cypher_row['fileSize']/1024),1)." KB)";
										}
									?></td>
								<td class="text-justify text-overflow th_notes" id="cypher_notes_<?php echo $cypher_row['cypherID']; ?>"><?php echo $cypher_row['cypherNotesFP']; ?></td>
								<td style="display:none;"          id="cypher_spec_unit_type_text_<?php echo $cypher_row['cypherID']; ?>"><?php echo $cypher_row['specUnitTypeText']; ?></td>
							</tr>
							<?php
						}
					}else{
						echo '<script>console.log("cypher already existed, dont need to get it agian");</script>';
					}
				}
				echo "<tr id='load1'><td colspan='11' class='text-center'><button class='btn btn-default' onclick='loadmore(1);'>Load more</button></td></tr>";
			?>
		</tbody>
	</table>

</div>

<div id="new_cypher"  class="modal fade" tabindex="-1" role="dialog" aria-labelledby="new_cypherLabel"  aria-hidden="true">
	<!--
		__   __                                   __
		| \  | | _____      __    ___ _   _ _ __ | |__   ___ _ __
		|  \ | |/ _ \ \ /\ / /  / __| | | | '_ \| '_ \ / _ \ '__|
		| | \| |  __/\ V  V /  | (__| |_| | |_) | | | |  __/ |
		|_| \ _|\___| \_/\_/    \___|\__, | .__/|_| |_|\___|_|
	                               |___/|_|
		-->
	<div class="modal-dialog">
		<div class="modal-content" id="new-cypher-modal">
			<form class="container-fluid form-inline panel-info" method="post">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
					<h2 class="modal-title" id="new_cypherLabel">New <?php echo $cypherorbatchtext; ?> details</h2>
				</div>
				<div class="modal-body">
					<div class="row">
						<div class="form-group">
							<?php
								switch($_SESSION['cypherorbatch']){
									case 0: //cyphers
										echo "<label for='add_date' class='sr-only'>Manufacture date</label>
											<input type='date' class='form-control restrict_width' id='add_date' name='add_date' value='".date("Y-m-d")."' required >
											<input type='hidden' id='add_batch' name='add_batch' value='' >";
										break;
									case 1: //batches
										// Issue #9 - ensure uniqueness
										if($_SESSION['csv_unique']==1){
											$value = 1;
											$date = date("Y-m-d");
											while (true) {
												$batch = $date."-".str_pad($value,2,"0",STR_PAD_LEFT);
												$sql="
													Select cypherID
													From dw_cypher
													Where cypherOrderID = ? and cypherSite = ?
												";
												if(!$batch_query = mysqli_prepared_query($link, $sql, "si", array($batch, $_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
												//if the batch does not exist, quit the loop
												if(mysqli_prepared_num_rows($batch_query)==0) break;
												$value++;
											}
										}else{
											$batch = "";
										}
										echo "<label for='add_date' class='sr-only'>Manufacture date</label>
											<input type='date' class='form-control restrict_width' id='add_date' name='add_date' value='".date("Y-m-d")."' required >
											<label for='add_batch' class='sr-only'>Batch/Order ID</label>
											<input type='text' class='form-control restrict_width filename_fix' id='add_batch' name='add_batch' value='".$batch."' placeholder='Batch/Order ID' required maxlength='14'>";
										break;
									case 2: //both
										echo "<label for='add_date' class='sr-only'>Manufacture date</label>
											<input type='date' class='form-control restrict_width' id='add_date' name='add_date' value='".date("Y-m-d")."' required >
											</div><div class='form-group'>
											<label for='add_batch' class='sr-only'>Batch/Order ID</label>
											<input type='text' class='form-control restrict_width filename_fix' id='add_batch' name='add_batch' placeholder='Batch/Order ID' maxlength='14'>";
										break;
									default:
										echo "<label for='add_date' class='sr-only'>Manufacture date</label>
											<input type='date' class='form-control restrict_width' id='add_date' name='add_date' value='".date("Y-m-d")."' required >
											</div><div class='form-group'>
											<label for='add_batch' class='sr-only'>Batch/Order ID</label>
											<input type='text' class='form-control restrict_width filename_fix' id='add_batch' name='add_batch' placeholder='Batch/Order ID' maxlength='14'>";
										reporterror();
								}
							?>
							</div>
						<div class='form-group'>
							<div style="width:250px;max-width:250px;display:inline;">
								<label for="add_spec" class="sr-only">Product</label>
								<select class="form-control" id="add_spec" name="add_spec" style="width:250px;max-width:250px" >
									<option disabled selected>Product</option>
									<!-- products will go here (cypher.js:update_cypher_new) #product_list -->
								</select>
							</div>
						</div>
					</div>
					<div class="row">
						<label for="add_comments" class="sr-only">Notes</label>
						<input type="text" class="form-control" id="add_comments" name="add_comments" placeholder="Notes (optional)" style="width:100%;" onkeyup="check_rz('add_comments');" >
					</div>
					<div class="row">
						<div class='nobr' style="margin-top:20px; margin-bttom:10px;">
							<h3 style="display:inline;">Add samples</h3>&nbsp;<a href="sampling_plan.php">View auto add sample list</a>
						</div>
					</div>
					<div id="auto_samples"></div>
					<div class="row" id="s1" >
						<div style="width:500px;display:inline;">
							<input type="text" class="form-control" name="sample1" id="sample1" placeholder="Sample" onblur="showdiv('s2');">
							<?php time_input('sample1'); ?>
							<select name="location1" id="location1" class='form-control restrict_width' onchange="showdiv('s2');"></select>
						</div>
					</div>
					<?php
						for($i=2; $i<=9; $i++){
							echo "
								<div class='row' id='s".$i."' style='display:none;'>
									<div style='width:500px;display:inline;'>
										<input type='text' class='form-control' name='sample".$i."' id='sample".$i."' placeholder='Sample' onblur=\"showdiv('s".($i+1)."');\">";
										time_input('sample'.$i);
										echo "<select name='location".$i."' id='location".$i."' class='form-control restrict_width' onchange=\"showdiv('s".($i+1)."');\"></select>
									</div>
								</div>
							";
						}
					?>
					<div class="row" id="s10" style="display:none;">
						<div style='width:500px;display:inline;'>
							<input type="text" class="form-control" name="sample10" id="sample10" placeholder="Sample" >
							<?php time_input('sample10'); ?>
							<select name="location10" id="location10" class="form-control restrict_width" ></select>
						</div>
					</div>

					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal"><span class='glyphicon glyphicon-remove' aria-hidden='true'></span>&nbsp;Cancel</button>
						<button type="submit" class="btn btn-primary" id="new_cypher_button" onclick="please_wait('new_cypher_button');"><span class='glyphicon glyphicon-ok' aria-hidden='true'></span>&nbsp;Create</button>
					</div>
				</div>
			</form>
		</div>
	</div>
</div>

<div id="edit_cypher" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="edit_cypherLabel" aria-hidden="true">
	<!--
		 _____    _ _ _                      _
		| ____|__| (_) |_    ___ _   _ _ __ | |__   ___ _ __
		|  _| / _` | | __|  / __| | | | '_ \| '_ \ / _ \ '__|
		| |__| (_| | | |_  | (__| |_| | |_) | | | |  __/ |
		|_____\__,_|_|\__|  \___|\__, | .__/|_| |_|\___|_|
														 |___/|_|
	-->
	<div class="modal-dialog">
		<div class="modal-content">
			<form class="container-fluid panel-info" method="post" enctype="multipart/form-data" >
				<input type="hidden" name="edit_cypherID" id="edit_cypherID">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
					<h2 class="modal-title" id="edit_cypherLabel">Edit <?php echo $cypherorbatchtext; ?> details</h2>
				</div>

				<div class="modal-body">
					<div class="form-group">
						<label for="edit_cypher_date">Date <!--[if IE]><em>(in american format)</em><![endif]--></label>
						<input type="date" class="form-control" id="edit_cypher_date" name="edit_date" required onchange="update('edit_cypher_reason', 'C3');" >
					</div>

					<div class="form-group" <?php if($_SESSION['cypherorbatch']==1 || $_SESSION['cypherorbatch']=='1') echo "style='display:none;'"; ?> >
						<label for="edit_cypher_text">Cypher</label>
						<p class='form-control-static' id='edit_cypher_text'></p>
					</div>

					<div class="form-group" <?php if($_SESSION['cypherorbatch']==0 || $_SESSION['cypherorbatch']=='0') echo "style='display:none;'"; ?> >
						<label for="edit_cypher_orderID">Batch/Order</label>
						<input type="text" class="form-control filename_fix" id="edit_cypher_orderID" name="edit_cypher_orderID" maxlength="12" placeholder="Batch" onchange="update('edit_cypher_reason', 'C5');" >
					</div>

					<div class="checkbox" id="edit_cypher_expiry_check" >
						<input type="checkbox" name="edit_cypher_auto_expiry" id="edit_cypher_auto_expiry" value="1" checked onchange="update_expiry();" style="margin-left:0px;" data-toggle="toggle" data-size="small" data-on="Auto" data-off="Manual" data-width="75" data-onstyle="success" >
						<script>
							//http://www.bootstraptoggle.com/
							$(function() {
								//$('#edit_cypher_auto_expiry').bootstrapToggle();
							})
						</script>
						<label for="edit_cypher_auto_expiry" id="edit_cypher_auto_expiry_text"> Auto expiry</label>
					</div>
					<div class="form-group" id="edit_cypher_expiry_div" >
						<label for="edit_cypher_expiry">Expiry</label>
						<input type="date" class="form-control" id="edit_cypher_expiry" name="edit_expiry" onchange="update('edit_cypher_reason', 'C2');" >
					</div>

					<div class="form-group">
						<label for="edit_product">Product</label>
						<select class="form-control" id="edit_product" name="edit_cypher_product" required onchange="update('edit_cypher_reason', 'C1');" >
							<option disabled selected>Product</option>
							<!-- Products go here -->
						</select>
					</div>

					<div class="form-group" id="edit_cypher_units">
						<label for="edit_cypher_first_unit">Sample range</label>
						<div class="input-group" >
							<div id='edit_samples_link'></div>
							<!--
							<span class="input-group-addon">First</span>
							<input type="text" class="form-control restrict_width" id="edit_cypher_first_unit" name="edit_cypher_first_unit" placeholder="Actual first sample" onkeyup="validate_unit('edit_cypher_first_unit');">
							<?php time_input('edit_cypher_first_unit'); ?>
							<span class="input-group-addon">Last</span>
							<input type="text" class="form-control restrict_width" id="edit_cypher_last_unit"  name="edit_cypher_last_unit"  placeholder="Actual last sample"  onkeyup="validate_unit('edit_cypher_last_unit');" >
							<?php time_input('edit_cypher_last_unit'); ?>
							-->
						</div>
					</div>

					<div class="form-group" id="received">
						<label for="edit_cypher_received_date">Received into lab</label>
						<div class="input-group row" >
							<div class="col-sm-6">
								<input type="date" class="form-control" name="edit_cypher_received_date" id="edit_cypher_received_date" onchange="receive(<?php echo $_SESSION['userID']; ?>);">
							</div>
							<div class="col-sm-6" style="padding-left:0">
								<?php
									$sql="
										Select userID, userFirst, userLast
										From dw_auth
										Where userSite = ? And userActive = 1
										Order by userFirst, userLast
									";
									if(!$user_query = mysqli_prepared_query($auth_link, $sql, "i", array($_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
									echo "<select class='form-control' name='edit_cypher_received_by' id='edit_cypher_received_by' ><option value='0'>Not received</option>";
										foreach($user_query as $user_row){
											echo "<option value='".$user_row['userID']."' ";
											if($user_row['userID']==$_SESSION['userID']) echo "selected ";
											echo ">".$user_row['userFirst']."&nbsp;".$user_row['userLast']."</option>";
										}
									echo "</select>";
								?>
							</div>
						</div>
					</div>

					<div class="form-group">
						<label for="edit_cypher_file">File</label>
						<div id="cypher_file">
							<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
							<input type="file" class="form-control" id="edit_cypher_file" name="edit_cypher_file" placeholder="Choose a file" >
						</div>
					</div>

					<div class="form-group">
						<label for="edit_cypher_notes">Notes</label>
						<input type="text" class="form-control" id="edit_cypher_notes" name="edit_cypher_notes" placeholder="Notes (optional)" onchange="update('edit_cypher_reason', 'C4');" onkeyup="check_rz('edit_cypher_notes');" >
					</div>

					<input type="hidden" name="edit_cypher_reason" id="edit_cypher_reason">
				</div>

				<div class="modal-footer" id='edit_footer'>
					<?php
						if($_SESSION['userLevel']<=$_SESSION['admin_cypher_delete']){
							//check if cypher contains units
							echo "<button type='submit' class='btn btn-danger' name='edit_delete' ><span class='glyphicon glyphicon-trash' aria-hidden='true'></span>&nbsp;Delete</button>";
						}
					?>
					<button type="button" class="btn btn-default" data-dismiss="modal"><span class='glyphicon glyphicon-remove' aria-hidden='true'></span>&nbsp;Cancel</button>
					<button type="submit" class="btn btn-primary" id="edit_cypher_button" onclick="please_wait('edit_cypher_button');"><span class='glyphicon glyphicon-save' aria-hidden='true'></span>&nbsp;Save</button>
				</div>

			</form>
		</div>
	</div>
</div>

<div id="view_units"  class="modal"      tabindex="-1" role="dialog" aria-labelledby="view_unitsLabel"  aria-hidden="true">
	<!--
		__     ___                             _ _
		\ \   / (_) _____      __  _   _ _ __ (_) |_ ___
		 \ \ / /| |/ _ \ \ /\ / / | | | | '_ \| | __/ __|
			\ V / | |  __/\ V  V /  | |_| | | | | | |_\__ \
			 \_/  |_|\___| \_/\_/    \__,_|_| |_|_|\__|___/
	-->
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
				<h2 class="modal-title" id="view_unitsLabel">Sample details</h2>
			</div>
			<div class="modal-body" >

				<ul id="sample_list" style="padding-left:25px;">
					<!-- sample list will go here, updated via cypher.js:update_samples() -->
				</ul>

				<form class="form-inline" method="post">
					<input type="hidden" name="sample_cypher_new" id="sample_cypher_new">
					<div class="form-group">
						<label for="sample_new" class="sr-only">Sample</label>
						<input type="text" class="form-control" id="sample_new" name="sample_new" placeholder="New sample" style="max-width:100px;" required >
						<?php time_input('sample_new'); ?>
					</div>
					<div class="form-group">
						<label for="sample_location_new" class="sr-only">Location</label>
						<select id="sample_location_new" name="sample_location_new" class="form-control" required >
							<option disabled selected>Location</option>
							<!-- locations to go here, updated via location_list div -->
						</select>
					</div>
					<button type="button" class="btn btn-default" id="view_units_button" onclick="add_sample('view_units_button',<?php echo $_SESSION['userID']; ?>);">Add</button>
				</form>

			</div>
			<div class="modal-footer">
				<p class="help-block pull-left" id="bottom_help">
					<a class='btn btn-default' role='button' href="print_labels.php"><span class="glyphicon glyphicon-print" aria-hidden="true"></span>&nbsp;Print labels</a>
				</p>
				<button type="button" class="btn btn-default btn-primary" data-dismiss="modal" onclick="close_view_units();"><span class='glyphicon glyphicon-save' aria-hidden='true'></span>&nbsp;Save</button>
			</div>
			<div style='display:none' id='comp_list'></div>
		</div>
	</div>
</div>

<div id="product_list"  style="display:none;">
	<!--
		 ____                _            _     _ _     _
		|  _ \ _ __ ___   __| |_   _  ___| |_  | (_)___| |_
		| |_) | '__/ _ \ / _` | | | |/ __| __| | | / __| __|
		|  __/| | | (_) | (_| | |_| | (__| |_  | | \__ \ |_
		|_|   |_|  \___/ \__,_|\__,_|\___|\__| |_|_|___/\__|
	-->
	<?php
		$sql="
			# get product list for later use
			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
		";
		// keep specStyle 4 enabled for sending away forms to lab
		if(!$product_query = mysqli_prepared_query($link, $sql, "i", array($_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
	?>
	<select >
		<option disabled selected >Product</option>
		<?php
			foreach($product_query as $product_row){
				echo "<option value='".$product_row['specID']."'";
				if(isset($_POST['add_spec']) && $_POST['add_spec']!="" && $_POST['add_spec']!=null && $product_row['specID']==$_POST['add_spec']) echo " selected"; //use the value from previously created cypher
				echo ">".$product_row['specText'];
				if($product_row['specText']!= $product_row['specShortDesc'] && $product_row['specShortDesc']!=null && $product_row['specShortDesc']!="") echo " - ".$product_row['specShortDesc'];
				if($debug) echo " [".$product_row['specID']."]";
				echo "</option>";

				// <option value='01'>WMP - Whole milk powder (+12 months) [01]</option>

			}
		?>
	</select>
</div>

<div id="location_list" style="display:none;">
	<!--
		 _                    _   _               _ _     _
		| |    ___   ___ __ _| |_(_) ___  _ __   | (_)___| |_
		| |   / _ \ / __/ _` | __| |/ _ \| '_ \  | | / __| __|
		| |__| (_) | (_| (_| | |_| | (_) | | | | | | \__ \ |_
		|_____\___/ \___\__,_|\__|_|\___/|_| |_| |_|_|___/\__|

	-->
	<?php
		$sql="
			# get location list for later use
			Select
				dw_location.locationID,
				dw_locgroup.locGroupText,
				dw_location.locationText
			From
				dw_locgroup Right Join
				dw_location
					On dw_locgroup.locGroupID = dw_location.locationGroup
			Where
				dw_location.locationSite = ? And
				dw_location.locationActive = 1
			Order By
				dw_locgroup.locGroupOrder,
				dw_locgroup.locGroupText,
				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__);
		$group = array();
		foreach($location_query as $row){
			$group[$row['locGroupText']][] = $row;
		}
		foreach ($group as $key => $values) {
			echo "<optgroup label='".$key."'>";
			foreach ($values as $value) {
				echo "	<option value='".$value['locationID']."'";
					if(isset($_POST['sample_location_new']) && $_POST['sample_location_new']!="" && $_POST['sample_location_new']!=null && $_POST['sample_location_new']==$value['locationID']) echo " selected"; //set location to previously created sample
					else if($value['locationID']==$_SESSION['default_location']) echo " selected"; //default location (found in dw_settings)
					echo ">".htmlentities($value['locationText']); //safely converts '&' to '&amp;', which causes an error in IE
					if($debug) echo " [".$value['locationID']."]";
				echo "</option>\n";
			}
			echo "</optgroup>\n";
		}
	?>
</div>

<div id="cypher_list"   style="display:none;">
	<!--
		____            _                 _ _     _
	 / ___|   _ _ __ | |__   ___ _ __  | (_)___| |_
	| |  | | | | '_ \| '_ \ / _ \ '__| | | / __| __|
	| |__| |_| | |_) | | | |  __/ |    | | \__ \ |_
	 \____\__, | .__/|_| |_|\___|_|    |_|_|___/\__|
				|___/|_|

	-->
	<?php
		$sql="
			# get cypher list for later use
			Select
				dw_cypher.cypherID,
				dw_cypher.cypherText,
				dw_spec.specText
			From
				dw_cypher Left Join
				dw_spec
					On dw_cypher.cypherSpec = dw_spec.specID
			Where
				dw_cypher.cypherSite = ?
			Order By
				dw_cypher.cypherManuDate Desc,
				dw_spec.specOrder
		";
		//dont LIMIT this because it ends up showing blank for earlier ones
		if(!$cypher_query = mysqli_prepared_query($link, $sql, "i", array($_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		foreach($cypher_query as $value){
			echo "	<option value='".$value['cypherID']."'>".$value['cypherText'];
			if($debug) echo " [".$value['cypherID']."]";
			echo " ".$value['specText']."</option>\n";
		}
	?>
</div>

<script src="js/cypher.js?v=2.5">/* Include JS specific to cypher.php (this file) */</script>
<script>

	<?php
		if(isset($_GET['c']) && $_GET['c']!="" && $_GET['c']!=null && !isset($_POST['edit_cypherID']) && !isset($_POST['sample_new']) && !isset($_POST['sample_id_vu_b'])){
			$sql="
				# see if the cypher actually exists
				Select
					dw_cypher.cypherID
				From
					dw_cypher
				Where
					dw_cypher.cypherID = ? And
					dw_cypher.cypherSite = ?
			";
			echo '/*';
			if(!$qrycypherid = mysqli_prepared_query($link, $sql, "ii", array($_GET['c'], $_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			echo '*/';
			if(mysqli_prepared_num_rows($qrycypherid)==1){
				echo "
					$('#edit_cypher').modal('show');
					update_cypher_edit(".clean($_GET['c']).", ".($debug ? "1" : "0").", ".$_SESSION['cypherorbatch'].");
				";
			}else reporterror("Cypher does not exist, either typo or someones trying to do a sneaky peek at some other factorys data", $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		}else{
			//echo "<button type='button' class='btn btn-xs' data-toggle='modal' data-target='#view_units' onclick='update_samples(".$cypher_row['cypherID'].",".$debug.",".$allow_edit.",\"".$cypherorbatchtext."\");' id='cypher_samples_".$cypher_row['cypherID']."'>";
			if(isset($_GET['u']) && $_GET['u']!="" && $_GET['u']!=null && !isset($_POST['add_date']) && (!isset($_POST['edit_cypherID']) || !isset($_POST['sample_id_vu_b']) || isset($_POST['sample_new']))){
				$sql="
					# see if cypher actually exists
					Select
						dw_cypher.cypherID
					From
						dw_cypher
					Where
						dw_cypher.cypherID = ?
				";
				echo '/*';
				if(!$qrycypherid = mysqli_prepared_query($link, $sql, "i", array($_GET['u']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
				echo '*/';
				if(mysqli_prepared_num_rows($qrycypherid)==1){
					echo "
						$('#view_units').modal('show');
						update_samples(".clean($_GET['u']).", ".($debug ? "1" : "0").", ".$_SESSION['cypherorbatch'].", ".$allow_edit.", \"".$cypherorbatchtext."\");
					";
				}else{
					//reporterror("Cypher does not exist", $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
				}
			}else{
				if(isset($_POST['sample_cypher_new']) && $_POST['sample_cypher_new']!="" && isset($_POST['sample_new']) && $_POST['sample_new']!=""){
					//show modal again after someone has added a sample
					echo "
						$('#view_units').modal('show');
						update_samples(".$_POST['sample_cypher_new'].", ".($debug ? "1" : "0").", ".$_SESSION['cypherorbatch'].", ".$allow_edit.", \"".$cypherorbatchtext."\");
					";
				}
			}
		}
	?>

	function loadmore(id){
		$.get( "ajax/loadmore_cypher.php", {
			limit: id
		}).done(function( data ) {
			if( data!="" ){
				//console.log( data );
				$("#load" + id).after(data + "<tr id='load" + (id+1) + "'><td colspan='11' class='text-center'><button class='btn btn-default' onclick='loadmore(" + (id+1) + ");'>Load more</button></td></tr>");
				$("#load" + id).hide();
			}
		});

	}

</script>
<script src="js/better-dom.js"></script>
<script src="js/better-i18n-plugin.js"></script>
<script src="js/better-time-element.js"></script>
<script src="js/better-emmet-plugin.js"></script>
<script src="js/better-dateinput-polyfill.js"></script>
<?php require "inc/footer.php"; ?>
