<?php
	/* (C) DairyWindow 2012-2017 */

	require 'inc/connect.php';
	if($_SESSION['userLevel'] <= $_SESSION['admin_spec_edit']) $allow_edit = 1;
	else $allow_edit = 0;

	if(isset($_POST['confirm']) && isset($_POST['extra'])){
		if(is_numeric($_POST['extra'])){
			//delete spec
			$sql = '
				delete from dw_spec
				where specID = ?
			';
			if(!savesql($link, $sql, 'i', array(clean($_POST['extra'])), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			$message['type'] = 'ok';
			$message['text'] = 'The product was deleted';
		}else{
			//go to limits page
			header("Location: ".$_POST['extra']);
			die();
		}
	}else{
		if(isset($_POST['add_text']) && $_POST['add_text']!='' && $_POST['add_text']!=null){
			//create new spec

			/*
				Version is always 1
				Active  is always 1
			*/

			$specText         = clean($_POST['add_text'     ]);
			$specGSP          = clean($_POST['add_gsp'      ]);
			$specCode         = clean($_POST['add_code'     ]);
			$specShortDesc    = clean($_POST['add_shortdesc']);
			$specLongDesc     = clean($_POST['add_longdesc' ]);
			$specExpiry       = clean($_POST['add_expiry'   ]);
			$specStyle        = clean($_POST['add_style'    ]);
			$specPO           = clean($_POST['add_specpo'   ]);
			//$specOrder        = clean($_POST['add_order'    ]);
			//if(isset($_POST['add_original_order'])) $specOriginalOrder = clean($_POST['add_original_order']);
			//else $specOriginalOrder = 1;
			$specUnitTypeText = clean($_POST['add_specunittypetext']);
			$specEmailAddy    = clean($_POST['add_emailaddy'  ]);
			if(isset($_POST['add_reason'])) $specChangeCode = clean($_POST['add_reason']);
			else $specChangeCode = '';
			$specKGperPallet  = clean($_POST['add_kgperpallet']);
			$specCSV          = clean($_POST['add_csv'        ]);
			$specBagSize      = clean($_POST['add_bagsize'    ]);
			$specKGperPallet  = clean($_POST['add_kgperpallet']);
			$specRate         = clean($_POST['add_rate'       ]);

			if(isset($_POST['add_showloc']) && $_POST['add_showloc']!="" && $_POST['add_showloc']!=null) $specShowLoc = 1;
			else $specShowLoc = 0;

			if(isset($_POST[ 'add_send'  ]) && $_POST[ 'add_send'  ]!="" && $_POST[ 'add_send'  ]!=null) $specSend    = 1;
			else $specSend    = 0;

			$sql='# check if adding a duplicate
				Select
					dw_spec.specID
				From
					dw_spec
				Where
					dw_spec.specText = ? And
					dw_spec.specSite = ?';
			if(!$select_query = mysqli_prepared_query($link, $sql, 'si', array($specText, $_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			if(mysqli_prepared_num_rows($select_query)>0){
				//error already exists
				$message['type'] = 'error';
				$message['text'] = '<span class="glyphicon glyphicon-warning-sign" aria-hidden="true"></span> Product '.$specText.' already exists';
			}else{
				$sql='# insert new spec
					INSERT INTO dw_spec                             ( specText,  specGSP,  specCode,  specShortDesc,  specLongDesc,  specExpiry,  specStyle, specVersion,  specUnitTypeText,  specSend,  specShowLoc,  specEmailAddy, specActive,     specModUser    , specModDate, specChangeCode,  specKGperPallet,  specBagSize,  specCSV,        specSite      , specPO ,  specRate)
					VALUES                                          (     ?   ,      ?  ,      ?   ,      ?        ,      ?       ,      ?     ,      ?    ,     ?      ,      ?           ,      ?   ,      ?      ,      ?        ,     ?     ,         ?          ,    now()   ,     ?         ,      ?          ,      ?      ,      ?  ,            ?         ,     ?  ,      ?   )';
					$types =                                        '     s          s         s          s               s              s            i          i             s                  i          i             s              i               i                             s                i                 i             i               i               s         d    ';
				if(!$new_spec = savesql($link, $sql, $types, array($specText, $specGSP, $specCode, $specShortDesc, $specLongDesc, $specExpiry, $specStyle,     1      , $specUnitTypeText, $specSend, $specShowLoc, $specEmailAddy,     1     , $_SESSION['userID'],             $specChangeCode, $specKGperPallet, $specBagSize, $specCSV, $_SESSION['userSite'], $specPO, $specRate), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);

				//need to sort out order of existing items

				/*																	   ↓
					Inserting before 5						1 2 3 4 5 6 7 8
					select * where order>=5    		1 2 3 4[5 6 7 8]
					set all of these to order++		1 2 3 4[6 7 8 9]
					insert at 5										1 2 3 4[5]6 7 8 9
				*/
				/*
				$sql2='
					Select
						dw_spec.specID,
						dw_spec.specOrder
					From
						dw_spec
					Where
						dw_spec.specOrder >= ? And
						dw_spec.specSite   = ?
				';
				if(!$order_query = mysqli_prepared_query($link, $sql2, 'ii', array($specOrder, $_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql2, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
				foreach($order_query as $order_row){
					$sql3='
						Update dw_spec Set
							specOrder  = ?
						Where specID = ?
					';
					if(!savesql($link, $sql3, 'ii', array(($order_row['specOrder']+1), $order_row['specID']), __FILE__, __LINE__)) reporterror(get_error(), $sql3, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
				}
				*/
				$message['type'] = 'warning';
				$message['text'] = 'Do you wish to create limits for '.$specText.'?';
				$message['extra'] = 'limit.php?s='.$new_spec;

			}
		}else{
			if(
				isset($_POST['edit_delete']) && $_POST['edit_delete']!="" && $_POST['edit_delete']!=null &&
				isset($_POST['edit_id']    ) && $_POST['edit_id'    ]!="" && $_POST['edit_id'    ]!=null
			){
				//check for duplicates
				$sql='
					# get all cyphers that have this spec
					Select
						dw_cypher.cypherID,
						dw_cypher.cypherText,
						dw_cypher.cypherOrderID
					From
						dw_cypher
					Where
						dw_cypher.cypherSpec = ? AND
						dw_cypher.cypherSite = ?
				';
				if(!$dup_query = mysqli_prepared_query($link, $sql, 'ii', array($_POST['edit_id'], $_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
				$num_rows = mysqli_prepared_num_rows($dup_query);
				if($num_rows>0){
					//cannot delete
					$message['type'] = 'error';
					if($num_rows==1){
						//get the cypher
						$message['text'] = 'Cannot delete this product because it is used by <a href="cypher.php?c='.$dup_query[0]['cypherID'].'">'.$dup_query[0]['cypherText'].' '.$dup_query[0]['cypherOrderID'].'</a>. You must delete this first';
					}else{
						$message['text'] = 'Cannot delete this product because it is used by <a href="cypher.php">'.$num_rows.' cyphers/batches</a>. You must delete these first';
					}
				}else{
					//ok to delete
					$message['type'] = 'warning';
					$message['text'] = 'Are you sure you want to delete? This action cannot be undone.';
					$message['extra'] = clean($_POST['edit_id']);
				}
			}else{
				if(isset($_POST['edit_id']) && $_POST['edit_id']!="" && $_POST['edit_id']!=null){
					$sql='
						UPDATE dw_spec SET
							specText         = ?,
							specGSP          = ?,
							specCode         = ?,
							specShortDesc    = ?,
							specLongDesc     = ?,
							specExpiry       = ?,
							specStyle        = ?,
							specVersion      = ?,
							
							specUnitTypeText = ?,
							specSend         = ?,
							specShowLoc      = ?,
							specEmailAddy    = ?,
							specActive       = ?,
							specModUser      = ?,
							specModDate      = now(),
							specChangeCode   = ?,
							specKGperPallet  = ?,
							specBagSize      = ?,
							specCSV          = ?,
							specPO           = ?,
							specRate         = ?,
							specBlurb        = ?
						WHERE specID       = ?
					';
					if(!savesql($link, $sql, 'ssssssii siisiisiissdsi', array(
						clean($_POST['edit_text']),
						clean($_POST['edit_gsp']),
						clean($_POST['edit_code']),
						clean($_POST['edit_shortdesc']),
						clean($_POST['edit_longdesc']),
						$_POST['edit_expiry'],
						$_POST['edit_style'],
						$_POST['edit_version'],

						clean($_POST['edit_specunittypetext']),
						(isset($_POST['edit_send']) ? $_POST['edit_send'] : 0),
						(isset($_POST['edit_showloc']) ? $_POST['edit_showloc'] : 0),
						$_POST['edit_emailaddy'],
						(isset($_POST['edit_active']) ? $_POST['edit_active'] : 0),
						$_SESSION['userID'],
						$_POST['edit_reason'],
						$_POST['edit_kgperpallet'],
						$_POST['edit_bagsize'],
						$_POST['edit_csv'],
						$_POST['edit_specpo'],
						$_POST['edit_rate'],
						$_POST['edit_blurb'],
						$_POST['edit_id']
					), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);

					//$specOrder         = $_POST['edit_order'];
					//$specOriginalOrder = $_POST['edit_original_order'];

					//if($specOrder != $specOriginalOrder){
						//need to sort out order of existing items
						//if($specOrder > $specOriginalOrder){
							/*
								Changing from 3 to 6									1 2(3)4 5(6)7 8 9
								select * where order>3 and order<=6		1 2 3[4 5 6]7 8 9
								set all of these to order--						1 2 3[3 4 5]7 8 9
								set order=6 where id=x								1 2[6]3 4 5 7 8 9
								final:																1 2 3 4 5[6]7 8 9
							*/
							/*
							$sql2='
								Select
									dw_spec.specID,
									dw_spec.specOrder
								From
									dw_spec
								Where
									dw_spec.specOrder >  ? And
									dw_spec.specOrder <= ? And
									dw_spec.specSite   = ?
							';
							if(!$order_query = mysqli_prepared_query($link, $sql2, 'iii', array($specOriginalOrder, $specOrder, $_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql2, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							foreach($order_query as $order_row){
								$sql3='
									Update dw_spec Set
										specOrder  = ?
									Where specID = ?
								';
								if(!savesql($link, $sql3, 'ii', array(($order_row['specOrder']+1), $order_row['specID']), __FILE__, __LINE__)) reporterror(get_error(), $sql3, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							}
							*/
						//}else{
							/*
								Changing from 6 to 3									1 2(3)4 5(6)7 8 9
								select * where order>=3 and order<6		1 2[3 4 5]6 7 8 9
								set all of these to order++						1 2[4 5 6]6 7 8 9
								set order=3 where id=x								1 2 4 5 6[3]7 8 9
								final:																1 2[3]4 5 6 7 8 9
							*/
							/*
							$sql4='
								Select
									dw_spec.specID,
									dw_spec.specOrder
								From
									dw_spec
								Where
									dw_spec.specOrder >= ? And
									dw_spec.specOrder <  ? And
									dw_spec.specSite   = ?
							';
							if(!$order_query = mysqli_prepared_query($link, $sql4, 'iii', array($specOrder, $specOriginalOrder, $_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql4, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							foreach($order_query as $order_row){
								$sql5='
									Update dw_spec Set
										specOrder  = ?
									Where specID = ?
								';
								if(!savesql($link, $sql5, 'ii', array(($order_row['specOrder']-1), $order_row['specID']), __FILE__, __LINE__)) reporterror(get_error(), $sql5, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							}
						}
					}
					*/
				}
			}
		}
	}

	$title = 'Product';
	require 'inc/head.php';
	$menu = 'product';
	require 'inc/menu.php';

	if($debug) showdebug();
?>

<div id="topDIV" >
	<h1 class="text-center">
		<?php
			echo $title;
			if($_SESSION['userLevel']<= $_SESSION['admin_spec_add']) {
				?>&nbsp;<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#new_spec" onclick="update_product_new(<?php if($debug) echo '1'; else echo '0'; ?>);" ><span class="glyphicon glyphicon-plus" aria-hidden="true"></span>&nbsp;Create new</button><?php }
		?>
	</h1>
</div>

<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>

<div id="main" class="container-fluid" style="display:none;" 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 style="display:none;"            id="th_id"       >ID</th>
				<th class="text-center th_text"      id="th_text"     >Text</th>
				<th style="display:none;"            id="th_text2"    >Code</th>
				<th class="text-center th_shortdesc" id="th_shortdesc">Description</th>
				<th style="display:none;"            id="th_longdesc" >Long description</th>
				<th class="text-center th_expiry"    id="th_expiry"   >Expiry</th>
				<th style="display:none;"            id="th_expiry2"  >Expiry</th>
				<th class="text-center th_style"     id="th_style"    >Display style</th>
				<th class="text-center th_send"      id="th_send"     >Allow sub<br>form creation</th>
				<th class="text-center th_showloc"   id="th_showloc"  >Show location<br>on COA</th>
				<th style="display:none;"            id="th_order"    >Order</th>
				<th style="display:none;"            id="th_gsp"      >GSP</th>
				<th style="display:none;"            id="th_code"     >Code</th>
				<th style="display:none;"            id="th_version"  >Version</th>
				<th style="display:none;"            id="th_unit"     >Unit</th>
				<th style="display:none;"            id="th_unit"     >KG/pallet</th>
				<th style="display:none;"            id="th_unit"     >Bag size</th>
				<th style="display:none;"            id="th_blurb"    >Blurb</th>
				<th style="display:none;"            id="th_active"   >Active</th>
				<th class="text-center th_mod"       id="th_mod"      >
					<?php if($_SESSION['userLevel']==1 || $_SESSION['userLevel']=='1') echo 'Modified by'; ?>
				</th>
			</tr>
		</thead>
		<tbody class="sortable">
			<?php
				$sql='# sql for main table
					Select
						dw_spec.specID, dw_spec.specText, dw_spec.specShortDesc, dw_spec.specLongDesc, dw_expiry.expiryText, dw_style.styleText, dw_spec.specVersion, dw_spec.specSend, dw_spec.specShowLoc, dw_user.userFirst, dw_user.userLast, dw_change.changeText, dw_spec.specActive, dw_spec.specOrder, dw_expiry.expiryID, dw_spec.specGSP, dw_spec.specCode, dw_spec.specUnitTypeText, dw_spec.specKGperPallet, dw_spec.specBagSize, dw_spec.specModDate, dw_spec.specPO, dw_spec.specRate, dw_spec.specBlurb, dw_spec.specStyle, dw_spec.specCSV, dw_spec.specEmailAddy
					From
						dw_user Right Join (
							dw_change Right Join (
								dw_style Right Join (
									dw_expiry Right Join
									dw_spec On dw_expiry.expiryID = dw_spec.specExpiry
								) On dw_style.styleID = dw_spec.specStyle
							) On dw_change.changeID = dw_spec.specChangeCode
						) On dw_user.userID = dw_spec.specModUser
					Where
						dw_spec.specSite = ? And
						dw_spec.specStyle != 4
					Order By
					 	dw_spec.specActive Desc,
						dw_spec.specStyle,
						dw_spec.specOrder,
						dw_spec.specText';
				if(!$spec_query = mysqli_prepared_query($link, $sql, 'i', array($_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
				$footer = false;
				foreach($spec_query as $spec_row){
					if(!$footer && $spec_row['specActive' ]==0){
						$footer = true;
						echo "</tbody><tfooter>";
					}
					?>
						<tr class="text-nowrap style<?php echo $spec_row['specStyle']; ?>" id="spec_<?php echo $spec_row['specID']; ?>" data-toggle="modal" data-target="#edit_spec" onclick="update_spec_edit(<?php echo $spec_row['specID']; ?>, <?php if($debug) echo '1'; else echo '0'; ?>);">
							<td style="display:none;"            id="spec_id_<?php          echo $spec_row['specID']; ?>"><?php                                                                                   echo $spec_row['specID'          ];                                                                                                                                                                                    ?></td>
							<td class="text-center th_text"      id="spec_text_<?php        echo $spec_row['specID']; ?>"><?php if($spec_row['specActive' ]==0 || $spec_row['specActive' ]=='0') echo '<span class="strikethrough">'; echo $spec_row['specText'        ]; if($debug) echo ' ['.$spec_row['specID'].']'; if($spec_row['specActive']==0 || $spec_row['specActive']=='0') echo '</span>'; ?></td>
							<td style="display:none;"            id="spec_text2_<?php       echo $spec_row['specID']; ?>"><?php                                                                                   echo $spec_row['specText'        ];                                                                                                                                                                                    ?></td>
							<td class="text-center th_shortdesc" id="spec_shortdesc_<?php   echo $spec_row['specID']; ?>"><?php if($spec_row['specActive' ]==0 || $spec_row['specActive' ]=='0') echo '<span class="strikethrough">'; echo $spec_row['specShortDesc'   ];                                                                                                   if($spec_row['specActive']==0 || $spec_row['specActive']=='0') echo '</span>'; ?></td>
							<td style="display:none;"            id="spec_longdesc_<?php    echo $spec_row['specID']; ?>"><?php                                                                                   echo $spec_row['specLongDesc'    ];                                                                                                                                                                                    ?></td>
							<td class="text-center th_expiry"    id="spec_expiry_<?php      echo $spec_row['specID']; ?>"><?php if($spec_row['specActive' ]==0 || $spec_row['specActive' ]=='0') echo '<span class="strikethrough">'; echo $spec_row['expiryText'      ];                                                                                                   if($spec_row['specActive']==0 || $spec_row['specActive']=='0') echo '</span>'; ?></td>
							<td style="display:none"             id="spec_expiry2_<?php     echo $spec_row['specID']; ?>"><?php                                                                                   echo $spec_row['expiryID'        ];                                                                                                                                                                                    ?></td>
							<td class="text-center th_style"     id="spec_style_<?php       echo $spec_row['specID']; ?>"><?php if($spec_row['specActive' ]==0 || $spec_row['specActive' ]=='0') echo '<span class="strikethrough">'; echo $spec_row['styleText'       ];                                                                                                   if($spec_row['specActive']==0 || $spec_row['specActive']=='0') echo '</span>'; ?></td>
							<td class="text-center th_send"      id="spec_send_<?php        echo $spec_row['specID']; ?>"><?php if($spec_row['specSend'   ]==1 || $spec_row['specSend'   ]=='1')                  echo '<span class="glyphicon glyphicon-ok" aria-hidden="true"></span>';                                                                                                                                                ?></td>
							<td class="text-center th_showloc"   id="spec_showloc_<?php     echo $spec_row['specID']; ?>"><?php if($spec_row['specShowLoc']==1 || $spec_row['specShowLoc']=='1')                  echo '<span class="glyphicon glyphicon-ok" aria-hidden="true"></span>';                                                                                                                                                ?></td>
							<td style="display:none;"            id="spec_order_<?php       echo $spec_row['specID']; ?>"><?php                                                                                   echo $spec_row['specOrder'       ];                                                                                                                                                                                    ?></td>
							<td style="display:none;"            id="spec_gsp_<?php         echo $spec_row['specID']; ?>"><?php                                                                                   echo $spec_row['specGSP'         ];                                                                                                                                                                                    ?></td>
							<td style="display:none;"            id="spec_code_<?php        echo $spec_row['specID']; ?>"><?php                                                                                   echo $spec_row['specCode'        ];                                                                                                                                                                                    ?></td>
							<td style="display:none;"            id="spec_version_<?php     echo $spec_row['specID']; ?>"><?php                                                                                   echo number_format($spec_row['specVersion'], 4);                                                                                                                                                                       ?></td>
							<td style="display:none;"            id="spec_unit_<?php        echo $spec_row['specID']; ?>"><?php                                                                                   echo $spec_row['specUnitTypeText'];                                                                                                                                                                                    ?></td>
							<td style="display:none;"            id="spec_kgperpallet_<?php echo $spec_row['specID']; ?>"><?php                                                                                   echo $spec_row['specKGperPallet' ];                                                                                                                                                                                    ?></td>
							<td style="display:none;"            id="spec_bagsize_<?php     echo $spec_row['specID']; ?>"><?php                                                                                   echo $spec_row['specBagSize'     ];                                                                                                                                                                                    ?></td>
              <td style="display:none;"            id="spec_blurb_<?php       echo $spec_row['specID']; ?>"><?php                                                                                   echo $spec_row['specBlurb'       ];                                                                                                                                                                                    ?></td>
							<td style="display:none;"            id="spec_active_<?php      echo $spec_row['specID']; ?>"><?php                                                                                   echo $spec_row['specActive'      ];                                                                                                                                                                                    ?></td>
							<td style="display:none;"            id="spec_csv_<?php         echo $spec_row['specID']; ?>"><?php                                                                                   echo $spec_row['specCSV'         ];                                                                                                                                                                                    ?></td>
							<td style="display:none;"            id="spec_email_<?php       echo $spec_row['specID']; ?>"><?php                                                                                   echo $spec_row['specEmailAddy'   ];                                                                                                                                                                                    ?></td>
							<td class="text-center th_mod"		   id="spec_mod_<?php         echo $spec_row['specID']; ?>" title="<?php echo $spec_row['changeText']; ?>" >
								<?php
									if($_SESSION['userLevel']==1 || $_SESSION['userLevel']=='1'){
										$fullname = $spec_row['userFirst'].' '.$spec_row['userLast'][0];
										if($spec_row['specActive' ]==0 || $spec_row['specActive' ]=='0') echo '<span class="strikethrough">'; echo $fullname.' '.date('j/n/y',strtotime($spec_row['specModDate'])); if($spec_row['specActive']==0 || $spec_row['specActive']=='0') echo '</span>';
									}
								?>
							</td>
							<td style="display:none;"            id="spec_po_<?php          echo $spec_row['specID']; ?>"><?php                                                                                   echo $spec_row['specPO'          ];                                                                                                                                                                                    ?></td>
							<td style="display:none;"            id="spec_rate_<?php        echo $spec_row['specID']; ?>"><?php                                                                                   echo $spec_row['specRate'        ];                                                                                                                                                                                    ?></td>
						</tr>
					<?php
				}
				if(!$footer) echo "</tbody>";
				else echo "</tfooter>";
			?>

	</table>
</div>

<script src="js/product.js?v=2.3">/* Include JS specific to product.php (this file) */</script>
<script src="js/tinymce/tinymce.min.js?v=2.1">/* For textarea blurb */</script>

<div id="new_spec" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="new_specLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<form class="container-fluid 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_specLabel">New product details</h2>
				</div>
				<div class="modal-body">

					<div class="form-group">
						<label for="add_text" >Product text/code</label>
						<input type="text" class="form-control filename_fix" id="add_text" name="add_text" placeholder="e.g. 1111" required >
					</div>
					<div class="form-group">
						<label for="add_shortdesc" >Short description</label>
						<input type="text" class="form-control" id="add_shortdesc" name="add_shortdesc" placeholder="e.g. WMP" required >
					</div>
					<div class="form-group">
						<label for="add_longdesc" >Long description</label>
						<input type="text" class="form-control" id="add_longdesc" name="add_longdesc" placeholder="e.g. Wholemilk Powder @ 26% for general trade" >
					</div>
					<div class="form-group">
						<label for="add_style" >Display style</label>
						<select name="add_style" id="add_style" class="form-control" onchange="if_ip_change_item_text();" >
							<option value="1" selected>Final product (unit numbers across the top, test names down the side)</option>
							<option value="2">In process / swabs (test names across the top, times down the side)</option>
							<option value="3">Tanker swabs (test names across the top, locations down the side)</option>
						</select>
					</div>
					<div class="form-group">
						<label for="add_expiry" >Expiry</label>
						<?php
							$sql="
								Select
									dw_expiry.expiryID,
									dw_expiry.expiryText
								From
									dw_expiry
								Where
									dw_expiry.expiryID > ?
								Order By
									dw_expiry.expiryYear,
									dw_expiry.expiryMonth,
									dw_expiry.expiryDay
							";
							if(!$qry_expiry = mysqli_prepared_query($link, $sql, 'i', array(0), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							echo '<select name="add_expiry" id="add_expiry" class="form-control" >';
								foreach($qry_expiry as $expiry_array){
									echo '<option value="'.$expiry_array['expiryID'].'">'.$expiry_array['expiryText'].'</option>';
								}
                            echo '</select>';
                        ?>
					</div>
					<div class="form-group">
						<label for="add_gsp" >Group Spec Product</label>
						<input type="text" class="form-control" id="add_gsp" name="add_gsp" placeholder="GSP, optional" >
					</div>
					<div class="form-group">
						<label for="add_code" >Lab product code</label>
						<select name="add_code" id="add_code" class="form-control" >
							<option value="PO">Powder</option>
							<option value="MK">Milk</option>
							<option value="CR">Cream</option>
							<option value="SW">Swabs</option>
							<option value= "" >Other</option>
						</select>
					</div>
					<div class="form-group">
						<label for="add_specunittypetext" >Item text</label>
						<input type="text" class="form-control" id="add_specunittypetext" name="add_specunittypetext" value="Unit" placeholder="What are individual items called?" required >
					</div>
					<div class="form-group">
						<label for="add_specpo" >PO <a href="po.php">Manage POs</a></label>
						<select class="form-control" id="add_specpo" name="add_specpo" >
							<option value=""><?php echo $_SESSION['order_number']; ?></option>
							<?php
								$sql='
									Select poID, poShortDesc, poLongDesc
									From dw_po
									Where poSite = ?
									Order By poShortDesc, poLongDesc
								';
								if(!$qry_po = mysqli_prepared_query($link, $sql, 'i', array($_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
								foreach($qry_po as $po_row){
									echo '<option value="'.$po_row['poShortDesc'].'" >'.$po_row['poShortDesc'];
									if($po_row['poLongDesc']!='') echo '&nbsp;('.$po_row['poLongDesc'].')';
									echo '</option>';
								}
							?>
						</select>
					</div>
					<div class="form-group" id="add_kgperpallet">
						<label for="add_kgperpallet" >KG's per pallet</label>
						<div class="input-group">
							<div class="col-xs-3" style="padding:0;" >
								<div class="input-group">
									<input type="number" class="form-control" id="add_bagsize"       name="add_bagsize"       placeholder="Amount of KG's in 1 container"   required min="1" value="25"   onchange="calc_kgperpallet('add_bagsize');" >
									<span class="input-group-addon">KG</span>
								</div>
							</div>
							<div class="col-xs-1"><div class="form-control-static">&times;</div></div>
							<div class="col-xs-3" style="padding:0;" >
								<div class="input-group">
									<input type="number" class="form-control" id="add_bagsperpallet" name="add_bagsperpallet" placeholder="Number of containers per pallet" required min="1" value="56"   onchange="calc_kgperpallet('add_bagsperpallet');" >
									<span class="input-group-addon"><span id='add_specunittypetext2'>bag</span>s</span>
								</div>
							</div>
							<div class="col-xs-1"><div class="form-control-static">=</div></div>
							<div class="col-xs-4" style="padding:0;" >
								<div class="input-group">
									<input type="number" class="form-control" id="add_kgperpallet"   name="add_kgperpallet"   placeholder="Amount of KG's in 1 pallet"      required min="1" value="1400" onchange="calc_kgperpallet('add_kgperpallet');" >
									<span class="input-group-addon">KG</span>
								</div>
							</div>
						</div>
					</div>
					<div class="form-group">
						<label for="add_rate" >Target production rate (tonnes per hour)</label>
						<input type="number" class="form-control" id="add_rate" name="add_rate" min="0">
					</div>

					<div class="form-group">
						<label for="add_csv" >Submission form filename prefix</label>
						<div class="input-group">
							<input type="text" class="form-control" id="add_csv" name="add_csv" placeholder="Optional" >
							<div class="input-group-addon"><?php echo $_SESSION['filename_prefix']; ?><span class="hidden-xs">[cypher]-[product]-[form]</span><span class="visible-xs-inline" title="cypher product form">*</span>.CSV</div>
						</div>
					</div>
					<div class="form-group">
						<label for="add_emailaddy" >Email<span class="hidden-xs"> address</span> to send sub<span class="hidden-xs">mission</span> form</label>
						<div class="input-group">
							<span class="input-group-addon"><span class="glyphicon glyphicon-envelope" aria-hidden="true"></span></span>
							<input type="email" class="form-control" id="add_emailaddy" name="add_emailaddy" placeholder="<?php echo $_SESSION['email_to']; ?>" >
						</div>
					</div>
          <div class="form-group">
            <label for="add_blurb" >Disclaimer</label>&nbsp;<span class="text-muted">(Optional, leave blank for default)</span>
            <textarea class="form-control textarea" id="add_blurb" name="add_blurb" placeholder="<?php echo $_SESSION['blurb']; ?>" rows="3"></textarea>
          </div>
          <div class="form-group">
						<label for="add_send" >Allow sub<span class="hidden-xs">mission</span> form creation? </label>
						<input type="checkbox" data-toggle="toggle" id="add_send" name="add_send" data-onstyle="success" data-offstyle="default" data-on="Yes" data-off="No" value="1" checked >
					</div>
					<div class="form-group">
						<label for="add_showloc" >Show locations on COA? </label>
						<input type="checkbox" data-toggle="toggle" id="add_showloc" name="add_showloc" data-onstyle="success" data-offstyle="default" data-on="Yes" data-off="No" value="1" >
						<span class="text-muted">(This is usually only for swabs)</span>
					</div>
					<!--
					<div class="form-group">
						<label for="add_order" >Insert in the list before</label>
						<select name="add_order" id="add_order" class="form-control" >
							<!-- populate using JS (update_product_new) -->
					<!--
						</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_spec_button" onclick="please_wait('new_spec_button');"><span class='glyphicon glyphicon-ok' aria-hidden='true'></span>&nbsp;Create</button>
				</div>
			</form>
		</div>
	</div>
</div>

<div id="edit_spec" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="edit_specLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<form class="container-fluid 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="edit_specLabel">Edit product details</h2>
				</div>

				<div class="modal-body">
					<div class="form-group"><!-- spec -->
						<label for="edit_text" >Product text/code</label>
						<input type="text" class="form-control filename_fix" id="edit_text" name="edit_text" placeholder="e.g. 1111" required onchange="update('edit_reason', 'P1');" >
					</div>
					<div class="form-group"><!-- desc -->
						<label for="edit_shortdesc" >Short description</label>
						<input type="text" class="form-control" id="edit_shortdesc" name="edit_shortdesc" placeholder="e.g. WMP" required onchange="update('edit_reason', 'P3');" >
					</div>
					<div class="form-group"><!-- style -->
						<label for="edit_style" >Display style</label>
						<select name="edit_style" id="edit_style" class="form-control" onchange="update('edit_reason', 'P6');if_ip_change_item_text();" >
							<option value="1" selected>Final product (unit numbers across the top, test names down the side)</option>
							<option value="2">In process / swabs (test names across the top, times down the side)</option>
							<option value="3">Tanker swabs (test names across the top, locations down the side)</option>
						</select>
					</div>
					<div class="form-group"><!-- expiry -->
						<label for="edit_expiry" >Expiry</label>
						<select name="edit_expiry" id="edit_expiry" class="form-control" onchange="update('edit_reason', 'P5');" >
							<!-- filled by JS -->
						</select>
					</div>
					<div class="form-group" id="edit_advanced" >
						<button type="button" class="btn" onclick="show_advanced('advanced2','edit_advanced');" >
						<span class="glyphicon glyphicon-triangle-bottom" aria-hidden="true"></span> Show advanced options</button>
					</div>
					<div id="advanced2" style="display:none;">
						<div class="form-group"><!-- long desc -->
							<label for="edit_longdesc" >Long description</label>
							<input type="text" class="form-control" id="edit_longdesc" name="edit_longdesc" placeholder="e.g. Wholemilk Powder @ 26% for general trade" onchange="update('edit_reason', 'P4');" >
						</div>
						<div class="form-group"><!-- gsp -->
							<label for="edit_gsp" >Group Spec Product</label>
							<input type="text" class="form-control" id="edit_gsp" name="edit_gsp" placeholder="GSP, optional" onchange="update('edit_reason', 'P1');" >
						</div>
						<div class="form-group"><!-- code -->
							<label for="edit_code" >Lab product code</label>
							<select name="edit_code" id="edit_code" class="form-control" onchange="update_specunittypetext();" >
								<option value="PO">Powder</option>
								<option value="MK">Milk</option>
								<option value="CR">Cream</option>
								<option value="SW">Swabs</option>
								<option value= "" >Other</option>
							</select>
						</div>
						<div class="form-group"><!-- version -->
							<label for="edit_version" >Version</label>
							<input type="number" class="form-control" id="edit_version" name="edit_version" placeholder="Version control" min="0" step="0.0001" onchange="update('edit_reason', 'P7');" >
						</div>
						<div class="form-group"><!-- unit -->
							<label for="edit_specunittypetext" >Item text</label>
							<input type="text" class="form-control" id="edit_specunittypetext" name="edit_specunittypetext" value="Unit" placeholder="What are individual items called?" required onchange="update('edit_reason', 'P1');" >
						</div>
						<div class="form-group"><!-- po -->
							<label for="edit_specpo" >PO <a href="po.php">Manage PO numbers</a></label>
							<?php
								$sql='
									# Get PO info
									Select
										dw_po.poID,
										dw_po.poShortDesc,
										dw_po.poLongDesc
									From
										dw_po
									Where
										dw_po.poSite = ?
									Order By
										dw_po.poShortDesc
								';
								if(!$po_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" id="edit_specpo" name="edit_specpo" >
								<option value=""><?php echo $_SESSION['order_number']; ?></option>
								<?php
									foreach($po_query as $po_row){
										echo '<option value="'.$po_row['poShortDesc'].'" >'.$po_row['poShortDesc'];
										if($po_row['poLongDesc']!='') echo '&nbsp;('.$po_row['poLongDesc'].')';
										echo '</option>';
									}
								?>
							</select>
						</div>
						<div class="form-group" id="edit_kgperpallet2"><!-- kg per pallet -->
							<label for="edit_kgperpallet" >KG's per pallet</label>
							<div class="input-group">
								<div class="col-xs-3" style="padding:0;" >
									<div class="input-group">
										<input type="number" class="form-control" id="edit_bagsize"       name="edit_bagsize"       placeholder="Amount of KG's in 1 container"   required min="0" onchange="calc_kgperpallet('edit_bagsize');" >
										<span class="input-group-addon">KG</span>
									</div>
								</div>
								<div class="col-xs-1"><div class="form-control-static">&times;</div></div>
								<div class="col-xs-3" style="padding:0;" >
									<div class="input-group">
										<input type="number" class="form-control" id="edit_bagsperpallet" name="edit_bagsperpallet" placeholder="Number of containers per pallet" required min="0" onchange="calc_kgperpallet('edit_bagsperpallet');" >
										<span class="input-group-addon"><span id='edit_specunittypetext2'>bag</span>s</span>
									</div>
								</div>
								<div class="col-xs-1"><div class="form-control-static">=</div></div>
								<div class="col-xs-4" style="padding:0;" >
									<div class="input-group">
										<input type="number" class="form-control" id="edit_kgperpallet"   name="edit_kgperpallet"   placeholder="Amount of KG's in 1 pallet"      required min="0" onchange="calc_kgperpallet('edit_kgperpallet');" >
										<span class="input-group-addon">KG</span>
									</div>
								</div>
							</div>
						</div>
						<div class="form-group"><!-- production rate -->
							<label for="edit_rate" >Target production rate (tonnes per hour)</label>
							<input type="number" class="form-control" id="edit_rate" name="edit_rate" onchange="update('edit_reason', 'P10');" >
						</div>
						<div class="form-group"><!-- filename -->
							<label for="edit_csv" >Submission form filename prefix</label>
							<div class="input-group">
								<input type="text" class="form-control" id="edit_csv" name="edit_csv" placeholder="Optional" onchange="update('edit_reason', 'P10');" >
								<div class="input-group-addon"><?php echo $_SESSION['filename_prefix']; ?><span class="hidden-xs">[cypher]-[product]-[form]</span><span class="visible-xs-inline" title="cypher product form">*</span>.CSV</div>
							</div>
						</div>
						<div class="form-group"><!-- email -->
							<label for="edit_emailaddy" >Email<span class="hidden-xs"> address</span> to send sub<span class="hidden-xs">mission</span> form</label>
							<div class="input-group">
								<span class="input-group-addon">@</span>
								<input type="email" class="form-control" id="edit_emailaddy" name="edit_emailaddy" placeholder="<?php echo $_SESSION['email_to']; ?>" onchange="update('edit_reason', 'P1');" >
							</div>
						</div>

	          <div class="form-group"><!-- blurb -->
              <label for="edit_blurb" >Disclaimer</label>&nbsp;<span class="text-muted">(Optional, leave blank for default)</span>
              <textarea class="form-control textarea" id="edit_blurb" name="edit_blurb" placeholder="<?php echo $_SESSION['blurb']; ?>" rows="3"></textarea>
	          </div>
                        
						<div class="form-group"><!-- allow send csv -->
							<label for="edit_send" >Allow sub<span class="hidden-xs">mission</span> form creation? </label>
							<input type="checkbox" data-toggle="toggle" id="edit_send" name="edit_send" data-onstyle="success" data-offstyle="default" data-on="Yes" data-off="No" value="1" onchange="update('edit_reason', 'P9');" >
						</div>
						<div class="form-group"><!-- locations -->
							<label for="edit_showloc" >Show locations on COA? </label>
							<input type="checkbox" data-toggle="toggle" id="edit_showloc" name="edit_showloc" data-onstyle="success" data-offstyle="default" data-on="Yes" data-off="No" value="1" onchange="update('edit_reason', 'P11');" >
							<span class="text-muted">(This is usually only for swabs)</span>
						</div>
						<div class="form-group"><!-- active -->
							<label for="edit_active" >Is the product active? </label>
							<input type="checkbox" data-toggle="toggle" id="edit_active" name="edit_active" data-onstyle="success" data-offstyle="default" data-on="Yes" data-off="No" value="1" onchange="update('edit_reason', 'P12');" >
						</div>
						<!--
						<div class="form-group"><!-- order -->
						<!--
							<label for="edit_order" >Reposition in the list after</label>
							<select name="edit_order" id="edit_order" class="form-control" onchange="update('edit_reason', 'P8');" >
								<!-- populate using JS -->
								<!--
							</select>
						</div>
					-->
					</div>
					<input type="hidden" id="edit_id" name="edit_id">
					<input type="hidden" id="edit_original_order" name="edit_original_order">
					<input type="hidden" id="edit_reason" name="edit_reason">
				</div>

				<div class="modal-footer">
          <button type="submit" class="btn btn-danger" name="edit_delete" value="1"><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_spec_button" onclick="please_wait('edit_spec_button');"><span class='glyphicon glyphicon-ok' aria-hidden='true'></span>&nbsp;Save</button>
				</div>
			</form>
		</div>
	</div>
</div>

<script>
	<?php
		if(isset($_GET['p']) && $_GET['p']!='' && $_GET['p']!=null && !isset($_POST['edit_text'])){
			$sql='
				# see if it actually exists
				Select
					dw_spec.specID
				From
					dw_spec
				Where
					dw_spec.specID   = ? And
					dw_spec.specSite = ?
			';
			if(!$qryspecid = mysqli_prepared_query($link, $sql, 'ii', array($_GET['p'], $_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			if(mysqli_prepared_num_rows($qryspecid)>0){
				//spec exists
				echo '
					$("#edit_spec").modal("show");
					update_spec_edit('.clean($_GET['p']).', '.($debug ? '1' : '0').');
				';
			}
		}
	?>
</script>
<?php require 'inc/footer.php'; ?>
