<?php
	/* (C) DairyWindow 2012-2017 */
	
	require "inc/connect.php";
	$totalkgs = 0;
	
	// POST[first_8361] => G1929x

	if(isset($_POST['del']) && $_POST['del']!="" && $_POST['del']!=null){
		$sql="
			Update dw_cypher
			Set cypherActive = 0
			Where cypherID  = ?
		";
		if(!savesql($link, $sql, "i", array($_POST['del']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
	}else{
		foreach($_POST as $key=>$value){
			if($value!="" && $value!=null){
				if(stristr($key, '_')){ //make sure there is an underscore in there
					$array = explode('_', $key);
					if($array[1]!="" && $array[1]!=null){ //make sure cypherid is present
						$extra = "Unit";
						if($array[0]=="part") $extra = "Pallet";
						if($array[0]=="kgs" ) $extra = "made";
						$sql="
							Update dw_cypher Set
								cypher".$array[0].$extra." = ?,
								cypherModUser = ?,
								cypherModDate = now()
							Where cypherID = ?
						";
						if(!savesql($link, $sql, "sii", array($value, $_SESSION['userID'], $array[1]), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					}
				}
			}
		}
	}
	
	if(date('n')>= $_SESSION['season_start']) $startDate = date('Y')."-".$_SESSION['season_start']."-01";
	else $startDate = (date('Y')-1)."-".$_SESSION['season_start']."-01";
	
	$title = "Production spreadsheet";
	require "inc/head.php";
	$menu = "prodspreadsheet";
	require "inc/menu.php";
	
	if($debug) showdebug();
?>
	
	<div id="topDIV" >
		<h1 class="text-center"><?php echo $title; ?></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>
	
	<script src="js/jquery.min.js?v=2.1"><!-- jQuery (necessary for Bootstrap's JavaScript plugins) --></script>
	
	<div class="col-md-3 hidden-print" role="complementary">
		<form class="form-horizontal" method="get" style="position:fixed;">
			<div class="form-group">
				<label for="spec" class="col-sm-2 control-label">Product</label>
				<div class="col-sm-10">
					<select id="spec" name="p" class="form-control" onchange="submit();">
						<!-- specs will go here, done via prodspreadsheet.js -->
					</select>
				</div>
			</div>
			<div class="form-group">
				<div class="col-sm-offset-2 col-sm-10">
					<button type="submit" class="btn btn-primary">Refresh</button>
					<a class="btn btn-default" href="javascript:window.print();" role="button"><img src="images/printer_small.png">&nbsp;Print this page</a>
				</div>
			</div>
		</form>
	</div>
	
	<div class="table-responsive col-md-9" id="main" role="main" style="display:none;">
		<table class="table table-hover" id="table">
			<thead>
				<tr id="table_head" style="background-color:white;color:inherit;white-space:nowrap;">
					<th class="text-center col-sm-1 th_button hidden-print" id="th_button"    >&nbsp;</th>
					<th class="text-center col-sm-1 th_cypher"              id="th_cypher"    ><?php if($_SESSION['cypherorbatch']==0) echo "Cypher"; else echo "Batch"; ?></th>
					<th class="text-center col-sm-1 th_product"             id="th_product"   >Product</th>
					<th class="text-center col-sm-1 th_firstunit"           id="th_firstunit" >First unit</th>
					<th class="text-center col-sm-1 th_lastunit"            id="th_lastunit"  >Last unit</th>
					<?php if($debug){ ?>                                    
					<th class="text-center col-sm-1 th_unitsmade"           id="th_unitsmade" >Pallets made</th>
					<th class="text-center col-sm-1 th_palletsize"          id="th_palletsize">Items per pallet</th>
					<th class="text-center col-sm-1 th_partpallet"          id="th_partpallet">Part pallet items</th>
					<th class="text-center col-sm-1 th_damages"             id="th_damages"   >Damages</th>
					<th class="text-center col-sm-1 th_bagsmade"            id="th_bagsmade"  >Items made</th>
					<th class="text-center col-sm-1 th_avgweight"           id="th_avgweight" >Avg weight</th>
					<?php } ?>                                              
					<th class="text-center col-sm-1 th_kgsmade"             id="th_kgsmade"   >KGs made</th>
				</tr>
			</thead>
			<tbody>
				<?php
					if(isset($_GET['p']) && $_GET['p']!="" && $_GET['p']!="0"){
						$sql="
							# sql for main table
							Select
								dw_cypher.cypherID,
								dw_cypher.cypherText,
								dw_cypher.cypherOrderID,
								dw_spec.specText,
								dw_cypher.cypherFirstUnit,
								dw_cypher.cypherLastUnit,
								dw_cypher.cypherPartPallet,
								dw_cypher.cypherKGsmade,
								dw_spec.specKGperPallet,
								dw_spec.specBagSize,
								dw_spec.specID,
								dw_cypher.cypherManuDate,
								dw_spec.specBagSize,
								dw_user.userID
							From
								dw_spec Right Join
								dw_cypher On dw_spec.specID = dw_cypher.cypherSpec Left Join
								dw_user On dw_cypher.cypherModUser = dw_user.userID
							Where
								dw_cypher.cypherActive    = 1 And
								dw_spec.specStyle         = 1 And
								dw_spec.specActive        = 1 And
								dw_cypher.cypherManuDate >= ? And
								dw_spec.specID            = ? And
								dw_spec.specSite          = ?
							Group By
								dw_cypher.cypherID,
								dw_user.userFirst,
								dw_user.userLast
							Order By
								dw_cypher.cypherManuDate Desc,
								dw_spec.specOrder
						";
						if(!$cypher_query = mysqli_prepared_query($link, $sql, "sii", array($startDate, $_GET['p'], $_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					}else{
						$sql="
							Select
								dw_cypher.cypherID,
								dw_cypher.cypherText,
								dw_cypher.cypherOrderID,
								dw_spec.specText,
								dw_cypher.cypherFirstUnit,
								dw_cypher.cypherLastUnit,
								dw_cypher.cypherPartPallet,
								dw_cypher.cypherKGsmade,
								dw_spec.specKGperPallet,
								dw_spec.specBagSize,
								dw_spec.specID,
								dw_cypher.cypherManuDate,
								dw_spec.specBagSize,
								dw_user.userID
							From
								dw_spec Right Join
								dw_cypher On dw_spec.specID = dw_cypher.cypherSpec Left Join
								dw_user On dw_cypher.cypherModUser = dw_user.userID
							Where
								ucase(substr(dw_spec.specText, 1, 3)) != 'AMF' And
								dw_cypher.cypherActive    = 1 And
								dw_spec.specStyle         = 1 And
								dw_spec.specActive        = 1 And
								dw_cypher.cypherManuDate >= ? And
								dw_spec.specSite          = ?
							Group By
								dw_cypher.cypherID,
								dw_user.userFirst,
								dw_user.userLast
							Order By
								dw_cypher.cypherManuDate Desc,
								dw_spec.specOrder
						";
						if(!$cypher_query = mysqli_prepared_query($link, $sql, "si", array($startDate, $_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					}
					require "inc/get_units.php";
					foreach($cypher_query as $cypher_row){
						
						$unitinfo = get_units($cypher_row['cypherID']); //this is used to get data for table
						$sql="
							# get damages
							Select
								Sum(dw_damages.damageBags) As SumOfDamageBags
							From
								dw_damages
							Where
								dw_damages.damageDate = ? And
								dw_damages.damageSite = ? And
								dw_damages.damageSpec = ?
						";
						if(!$damage_query = mysqli_prepared_query($link, $sql, "sii", array($cypher_row['cypherManuDate'], $_SESSION['userSite'], $cypher_row['specID']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
						$damage_row = $damage_query[0];
						if($damage_row['SumOfDamageBags']=="" || $damage_row['SumOfDamageBags']==null) $damage_row['SumOfDamageBags']=0;
						
						if($cypher_row['specBagSize']==0) $fiftysix = $cypher_row['specKGperPallet'];
						else $fiftysix = $cypher_row['specKGperPallet']/$cypher_row['specBagSize'];
						$meanweight = $cypher_row['specBagSize'];
						
						if($cypher_row['cypherFirstUnit']!="" && $cypher_row['cypherFirstUnit']!=null) $firstunit = $cypher_row['cypherFirstUnit'];
						else $firstunit = $unitinfo[0];
						if($firstunit=="") $firstunit="-"; //need something here so people can click on it
						
						if($cypher_row['cypherLastUnit']!="" && $cypher_row['cypherLastUnit']!=null) $lastunit = $cypher_row['cypherLastUnit'];
						else $lastunit = $unitinfo[1];
						if($lastunit=="") $lastunit="-"; //need something here so people can click on it
						
						//$units = number_format($unitinfo[2]);
						if(!function_exists('addletter')) require "inc/addletter.php";
						$firstunitforcalc=(int)addletter(substr($firstunit,0,1), substr($firstunit,1)); //add a number at the start instead of a letter
						$lastunitforcalc =(int)addletter(substr($lastunit ,0,1), substr($lastunit ,1));
						$units = number_format($lastunitforcalc-$firstunitforcalc,0,"","");
						if($firstunit!='-' && $units<1) $units = 1;
						
						if($cypher_row['cypherPartPallet']>0 && $damage_row['SumOfDamageBags']<1){
							$bagsmade = ((($units-1)*$fiftysix)+$cypher_row['cypherPartPallet']);
							$bagtooltip = "(((".$units."-1)*".$fiftysix.")+".$cypher_row['cypherPartPallet'].")";
						}else if($cypher_row['cypherPartPallet']>0 && $damage_row['SumOfDamageBags']>0){
							$bagsmade = (((($units-1)*$fiftysix)+$cypher_row['cypherPartPallet'])-$damage_row['SumOfDamageBags']);
							$bagtooltip = "((((".$units."-1)*".$fiftysix.")+".$cypher_row['cypherPartPallet'].")-".$damage_row['SumOfDamageBags'].")";
						}else if($cypher_row['cypherPartPallet']<1 && $damage_row['SumOfDamageBags']>0){
							$bagsmade = (($units*$fiftysix)-$damage_row['SumOfDamageBags']);
							$bagtooltip = "((".$units."*".$fiftysix.")-".$damage_row['SumOfDamageBags'].")";
						}else{
							$bagsmade = $units*$fiftysix;
							$bagtooltip = $units."*".$fiftysix;
						}
						if($bagsmade<0) $bagsmade=0;
						if($firstunit!='-' && $bagsmade<1) $bagsmade = 1;
						
						if($cypher_row['userID']=='0') $class="text-success";
						else $class="";
						
						echo "<tr class='".$class."'>
							<td class='col-sm-1 text-center hidden-print ".$class."'>
								<form method='post'>
									<button class='btn btn-default btn-xs' type='submit' value='delete' title='Delete'>
										<input type='hidden' name='del' value='".$cypher_row['cypherID']."'>
										<span class='glyphicon glyphicon-trash' aria-hidden='true'></span>
										Remove
									</button>
								</form>
							</td><!-- Delete button -->
							<td class='col-sm-1 text-center ".$class."'>";
								if($debug) echo "<small>[".$cypher_row['cypherID']."]</small> ";
								echo date('d/m/y',strtotime($cypher_row['cypherManuDate']))."&nbsp;";
								if($_SESSION['cypherorbatch']==0) echo $cypher_row['cypherText'];
								if($_SESSION['cypherorbatch']==1) echo $cypher_row['cypherOrderID'];
								if($_SESSION['cypherorbatch']==2) echo $cypher_row['cypherText']."&nbsp;".$cypher_row['cypherOrderID'];
								echo "</td><!-- Cypher -->
							<td class='col-sm-1 text-center ".$class."'>".$cypher_row['specText']."</td><!-- Product -->
							<td class='col-sm-1 text-center ".$class."' data-toggle='tooltip' data-placement='bottom' >
								<div id='view_first_".$cypher_row['cypherID']."' style='cursor:pointer;' title='From Cypher page (click to change)' onclick=\"replace('view_first_".$cypher_row['cypherID']."', 'edit_first_".$cypher_row['cypherID']."');\" >".$firstunit."</div>
								<div id='edit_first_".$cypher_row['cypherID']."' style='display:none;' >
									<form method='post' style='display:inline;' id='form_first".$cypher_row['cypherID']."'>
										<input type='text' style='text-align:center;' class='form-control input-sm' name='first_".$cypher_row['cypherID']."' id='first_".$cypher_row['cypherID']."' value='".$firstunit."' onblur=\"submit2(".$cypher_row['cypherID'].", '".$firstunit."', 'first');\">
									</form>
								</div>
							</td><!-- First -->
							<td class='col-sm-1 text-center ".$class."' data-toggle='tooltip' data-placement='bottom' >
								<div id='view_last_".$cypher_row['cypherID']."' style='cursor:pointer;' title='From Cypher page (click to change)' onclick=\"replace('view_last_".$cypher_row['cypherID']."', 'edit_last_".$cypher_row['cypherID']."');\" >".$lastunit."</div>
								<div id='edit_last_".$cypher_row['cypherID']."' style='display:none;' >
									<form method='post' style='display:inline;' id='form_last".$cypher_row['cypherID']."'>
										<input type='text' style='text-align:center;' class='form-control input-sm' name='last_".$cypher_row['cypherID']."' id='last_".$cypher_row['cypherID']."' value='".$lastunit."' onblur=\"submit2(".$cypher_row['cypherID'].", '".$lastunit."', 'last');\">
									</form>
								</div>
							</td><!-- Last -->
							"; if($debug) echo "
							<td class='col-sm-1 text-center ".$class."' data-toggle='tooltip' data-placement='bottom' title='".$lastunit."-".$firstunit."'>".$units."</td><!-- # pallets made -->
							<td class='col-sm-1 text-center ".$class."' data-toggle='tooltip' data-placement='bottom' title='From products page'><a href='product.php?p=".$cypher_row['specID']."'>".number_format($fiftysix)."</a></td><!-- Container per pallet -->
							<!--<td class='col-sm-1 text-center ".$class."' data-toggle='tooltip' data-placement='bottom' title='From Cypher page (click to change)'><a href='cypher.php?c=".$cypher_row['cypherID']."'>".number_format($cypher_row['cypherPartPallet'])."</a></td>-->
							<td class='col-sm-1 text-center ".$class."' data-toggle='tooltip' data-placement='bottom' >
								<div id='view_part_".$cypher_row['cypherID']."' style='cursor:pointer;' title='From Cypher page (click to change)' onclick=\"replace('view_part_".$cypher_row['cypherID']."', 'edit_part_".$cypher_row['cypherID']."');\" >".number_format($cypher_row['cypherPartPallet'])."</div>
								<div id='edit_part_".$cypher_row['cypherID']."' style='display:none;' >
									<form method='post' style='display:inline;' id='form_part".$cypher_row['cypherID']."'>
										<input type='text' style='text-align:center;' class='form-control input-sm' name='part_".$cypher_row['cypherID']."' id='part_".$cypher_row['cypherID']."' value='".number_format($cypher_row['cypherPartPallet'])."' onblur=\"submit2(".$cypher_row['cypherID'].", '".number_format($cypher_row['cypherPartPallet'])."', 'part');\">
									</form>
								</div>
							</td><!-- Part pallets -->
							<td class='col-sm-1 text-center ".$class."' data-toggle='tooltip' data-placement='bottom' title='From Shift notes'><a href='shiftnotes.php?c=".$cypher_row['cypherManuDate']."'>".number_format($damage_row['SumOfDamageBags'])."</a></td><!-- Damages -->
							<td class='col-sm-1 text-center ".$class."' data-toggle='tooltip' data-placement='bottom' title='".$bagtooltip."'>".number_format($bagsmade)."</td><!-- Bags made -->
							<td class='col-sm-1 text-center ".$class."' data-toggle='tooltip' data-placement='bottom' title='From products page'><a href='product.php?p=".$cypher_row['specID']."'>".number_format($meanweight,3)."</a></td><!-- Mean weight -->
							";
							if($cypher_row['cypherKGsmade']==0 || $cypher_row['cypherKGsmade']==null) $cypherKGsmade = $bagsmade*$meanweight;
							else $cypherKGsmade = $cypher_row['cypherKGsmade'];
							$totalkgs += $cypherKGsmade;
							echo "
							<td class='col-sm-1 text-center ".$class."' data-toggle='tooltip' data-placement='bottom' >
								<div id='view_kgs_".$cypher_row['cypherID']."' ";
								if($cypher_row['cypherKGsmade']==0 || $cypher_row['cypherKGsmade']==null) echo " title='".$bagsmade."*".$meanweight."' class='text-success' ";
								else echo " title='Manually typed' ";
								echo " onclick=\"replace('view_kgs_".$cypher_row['cypherID']."', 'edit_kgs_".$cypher_row['cypherID']."');\" >".number_format($cypherKGsmade)."</div>
								<div id='edit_kgs_".$cypher_row['cypherID']."' style='display:none;' >
									<form method='post' style='display:inline;' id='form_kgs".$cypher_row['cypherID']."'>
										<input type='number' style='text-align:center;' class='form-control input-sm' name='kgs_".$cypher_row['cypherID']."' id='kgs_".$cypher_row['cypherID']."' value='".$cypherKGsmade."' onblur=\"submit2(".$cypher_row['cypherID'].", '".$cypherKGsmade."', 'kgs');\">
									</form>
								</div>
							</td><!-- KGs made -->
						</tr>";
					}
					echo "<tr><td class='hidden-print'>&nbsp;</td><td colspan='";
					if($debug) echo "10";
					else echo "4";
					echo "' style='text-align:right;'>Total</td><td class='text-center'><strong>".number_format($totalkgs)."</strong></td></tr>";
				?>
			</tbody>
		</table>
	</div>
	
	<div id="spec_list" style="display:none;">
		<?php
			$sql="
				Select
				  dw_spec.specID,
				  dw_spec.specText
				From
				  dw_spec
				Where
				  dw_spec.specActive = 1 And
				  dw_spec.specSite  = ? And
					dw_spec.specStyle = 1
				Order By
				  dw_spec.specOrder
			";
			if(!$spec_query = mysqli_prepared_query($link, $sql, "i", array($_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		?>
		<option value="0">All products</option>
		<?php
			foreach($spec_query as $spec_row){
				echo "<option value='".$spec_row['specID']."' ";
				if(isset($_GET['p']) && $_GET['p']==$spec_row['specID']) echo "selected ";
				echo ">".$spec_row['specText']."</option>";
			}
		?>
	</div>
	
	<script src="js/prodspreadsheet.js"><!-- Include JS specific to prodspreadsheet.php (this file) --></script>
	<script>
		populate_specs();
	</script>
	<?php require "inc/footer.php"; ?>
