<?php
	/* (C) DairyWindow 2012-2017 */
	
	/*
		A4 is 210 wide and 297 high
		|6|66|66|66|6|
	*/
	
	require "inc/connect.php";
	$counter = 1;
	$current_col = 1;
	
	if(isset($_GET['cypher']) && $_GET['cypher']!="" && $_GET['cypher']!=0) $cypher = clean($_GET['cypher']);
	else $cypher = 0;
	
	if(isset($_GET['cols']) && $_GET['cols']!="" && $_GET['cols']!=0) $cols = clean($_GET['cols']);
	else $cols = 3;
	
	if(isset($_GET['rows']) && $_GET['rows']!="" && $_GET['rows']!=0) $rows = clean($_GET['rows']);
	else $rows = 8;
	
	if(isset($_GET['skip']) && $_GET['skip']!="" && $_GET['skip']!=0) $skip = clean($_GET['skip']);
	else $skip = 0;
	
	$pagewidth = 195;
	$pageheight = 270;
	$gap = 3;
	$barcodewidth = 10;
	//$cellwidth = $pagewidth/$cols; //need to remember A4 margins
	$cellwidth = ($pagewidth-(($cols-1)*$gap))/$cols;
	$cellheight = $pageheight/$rows;
	
	require('inc/barcode.php');
	
	if(isset($_GET['print'])){
		
		$x=1; $y=1; $data = array();
		
		require('inc/pdf/fpdf.php');
		define('FPDF_FONTPATH','inc/pdf/');
		
		class PDF extends FPDF {
			//Cell with horizontal scaling if text is too wide
			function CellFit($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='', $scale=false, $force=true){
				//Get string width
				$str_width= $this->GetStringWidth($txt);

				//Calculate ratio to fit cell
				if($w==0) $w = $this->w-$this->rMargin-$this->x;
				if($str_width==0) $ratio = ($w-$this->cMargin*2);
				else $ratio = ($w-$this->cMargin*2)/$str_width;

				$fit = ($ratio < 1 || ($ratio > 1 && $force));
				if ($fit){
					if ($scale)	{
						//Calculate horizontal scaling
						$horiz_scale= $ratio*100.0;
						//Set horizontal scaling
						$this->_out(sprintf('BT %.2F Tz ET', $horiz_scale));
					}else{
						//Calculate character spacing in points
						$char_space=($w-$this->cMargin*2-$str_width)/max($this->MBGetStringLength($txt)-1, 1)*$this->k;
						//Set character spacing
						$this->_out(sprintf('BT %.2F Tc ET', $char_space));
					}
					//Override user alignment (since text will fill up cell)
					$align='';
				}

				//Pass on to Cell method
				$this->Cell($w, $h, $txt, $border, $ln, $align, $fill, $link);

				//Reset character spacing/horizontal scaling
				if($fit) $this->_out('BT '.($scale ? '100 Tz' : '0 Tc').' ET');
			}

			//Cell with horizontal scaling only if necessary
			function CellFitScale($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link=''){
				$this->CellFit($w, $h, $txt, $border, $ln, $align, $fill, $link, true, false);
			}

			//Cell with horizontal scaling always
			function CellFitScaleForce($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link=''){
				$this->CellFit($w, $h, $txt, $border, $ln, $align, $fill, $link, true, true);
			}

			//Cell with character spacing only if necessary
			function CellFitSpace($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link=''){
				$this->CellFit($w, $h, $txt, $border, $ln, $align, $fill, $link, false, false);
			}

			//Cell with character spacing always
			function CellFitSpaceForce($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link=''){
				//Same as calling CellFit directly
				$this->CellFit($w, $h, $txt, $border, $ln, $align, $fill, $link, false, true);
			}

			//Patch to also work with CJK double-byte text
			function MBGetStringLength($s){
				if($this->CurrentFont['type']=='Type0'){
					$len = 0;
					$nbbytes = strlen($s);
					for ($i = 0; $i < $nbbytes; $i++){
						if (ord($s[$i])<128)
							$len++;
						else{
							$len++;
							$i++;
						}
					}
					return $len;
				}
				else return strlen($s);
			}
		}
		
		$pdf = new PDF();
		$pdf->AddPage();
		$pdf->SetFont('Arial','',10);
		$pdf->SetMargins(7, 14, 7);
		$pdf->SetAutoPageBreak(false);
		$pdf->Ln(4);
		
		//skip cells
		if($skip>0){
			for($i=0; $i<$skip; $i++){
				$data[$x][$y]['cypherManuDate'] = " ";
				$data[$x][$y]['specText'] = " ";
				$data[$x][$y]['specShortDesc'] = " ";
				$data[$x][$y]['locationText'] = " ";
				$data[$x][$y]['unitText'] = " ";
				$data[$x][$y]['unitID'] = " ";
				$x++;
				if($x>$cols){
					$x=1;
					$y++;
				}
			}
		}
		
		$sql="
			Select
				dw_cypher.cypherText,
				dw_cypher.cypherManuDate,
				dw_cypher.cypherOrderID,
				dw_spec.specText,
				dw_spec.specShortDesc,
				dw_spec.specStyle,
				dw_unit.unitID,
				dw_unit.unitText,
				dw_location.locationText
			From
				dw_cypher Left Join
				dw_spec
					On dw_cypher.cypherSpec = dw_spec.specID Right Join
				dw_unit
					On dw_unit.unitCypher = dw_cypher.cypherID Left Join
				dw_location
					On dw_unit.unitLocation = dw_location.locationID
			Where
				dw_cypher.cypherID = ? And
				dw_location.locationActive = 1 And
				dw_unit.unitActive = 1
			Order by
				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', 'Comp1', 'Comp 1', 'Comp2', 'Comp 2'),
				LPad(dw_unit.unitText, 20, 0),
				dw_location.locationOrder,
				dw_location.locationText
		";
		if(!$cypherquery = mysqli_prepared_query($link, $sql, "i", array($cypher), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		$cellcount = mysqli_prepared_num_rows($cypherquery);
		foreach($cypherquery as $cypherarray){
			$data[$x][$y]['unitID'        ] = $cypherarray['unitID'        ];
			$data[$x][$y]['cypherManuDate'] = $cypherarray['cypherManuDate'];
			$data[$x][$y]['cypherText'    ] = $cypherarray['cypherText'    ];
			$data[$x][$y]['cypherOrderID' ] = $cypherarray['cypherOrderID' ];
			$data[$x][$y]['specText'      ] = $cypherarray['specText'      ];
			$data[$x][$y]['specShortDesc' ] = $cypherarray['specShortDesc' ];
			$data[$x][$y]['locationText'  ] = $cypherarray['locationText'  ];
			$data[$x][$y]['unitText'      ] = $cypherarray['unitText'      ];
			$x++;
			if($x>$cols){
				$x=1;
				$y++;
			}
			$specStyle = $cypherarray['specStyle'];
			if($specStyle==1){
				$print_date = true;
			}else{
				if(isset($_GET['print_date']) && $_GET['print_date']==1){
					$print_date = true;
				}else{
					$print_date = false;
				}
			}
			
		}
		
		$x=1; $y=1;
		do{
			for($i=0; $i<$cols; $i++){
				if(isset($data[$x+$i][$y])){
					$pdf->CellFitScale($barcodewidth, $cellheight/4,'','',0,'C');
					if($data[$x+$i][$y]['cypherManuDate']==" " || !$print_date) $pdf->CellFitScale($cellwidth-$barcodewidth, $cellheight/4,"",'',0,'C');
					else{
						if($specStyle==1) $pdf->CellFitScale($cellwidth-$barcodewidth, $cellheight/4, $data[$x+$i][$y]['cypherText']." ".$data[$x+$i][$y]['cypherOrderID'],'',0,'C');
						else $pdf->CellFitScale($cellwidth-$barcodewidth, $cellheight/4,date('d/m/Y',strtotime($data[$x+$i][$y]['cypherManuDate'])),'',0,'C');
					}
					$pdf->CellFitScale($gap, $cellheight/4,'');
				}
				$counter++;
			}
			$pdf->Ln();
			for($i=0; $i<$cols; $i++){
				if(isset($data[$x+$i][$y])){
					//generate barcode
					if($data[$x+$i][$y]['unitID']!=" ") barcode("images/barcodes/U".$data[$x+$i][$y]['unitID'].".png", "U".$data[$x+$i][$y]['unitID'], $cellheight, "vertical", "code128a", true);
					//display barcode
					if($data[$x+$i][$y]['unitID']!=" ") $pdf->Image("images/barcodes/U".$data[$x+$i][$y]['unitID'].".png", $pdf->GetX()+($i*$cellwidth)+($i*$gap)+1, $pdf->GetY()-($cellheight/4)+2, $barcodewidth, $cellheight-5, 'PNG');
				}
			}
			for($i=0; $i<$cols; $i++){
				if(isset($data[$x+$i][$y])){
					$pdf->CellFitScale($barcodewidth, $cellheight/4,'','',0,'C');
					if($data[$x+$i][$y]['specText']==" ") $pdf->CellFitScale($cellwidth-$barcodewidth, $cellheight/4,"",'',0,'C');
					else $pdf->CellFitScale($cellwidth-$barcodewidth, $cellheight/4, $data[$x+$i][$y]['specText']." (".$data[$x+$i][$y]['specShortDesc'].")",'',0,'C');
					$pdf->CellFitScale($gap, $cellheight/4,'');
				}
			}
			$pdf->Ln();
			for($i=0; $i<$cols; $i++){
				if(isset($data[$x+$i][$y])){
					$pdf->CellFitScale($barcodewidth, $cellheight/4,'','',0,'C');
					$pdf->CellFitScale($cellwidth-$barcodewidth, $cellheight/4, $data[$x+$i][$y]['locationText'],'',0,'C');
					$pdf->CellFitScale($gap, $cellheight/4,'');
				}
			}
			$pdf->Ln();
			for($i=0; $i<$cols; $i++){
				if(isset($data[$x+$i][$y])){
					$pdf->CellFitScale($barcodewidth, $cellheight/4,'','',0,'C');
					$pdf->SetFont('Arial','B',11);
					$pdf->CellFitScale($cellwidth-$barcodewidth, $cellheight/4, $data[$x+$i][$y]['unitText'],'',0,'C');
					$pdf->SetFont('Arial','',10);
					$pdf->CellFitScale($gap, $cellheight/4,'');
				}
			}
			$pdf->Ln();
			if($y%$rows==0) $pdf->AddPage();
			$y++;
			
			/*
			$x+= $cols;
			if($x>$cols){
				$x=1;
				if($y%$rows==0) $pdf->AddPage();
				$y++;
			}
			*/
		}while($counter <= ($cellcount+$skip));
		$pdf->Output();
		exit();
	}
	
	$title = "Print labels";
	require "inc/head.php";
	$menu = "print_labels";
	require "inc/menu.php";
	
	if($debug) showdebug();
?>

<div id='loading' ><img src='images/loading-small.gif' alt='Please wait. Loading...' width='111' height='156' style='margin-top:150px;' class='center-block'><br><div class='text-center'><img src='images/carregando.gif' width='16' height='16'>&nbsp;Please wait while loading...</div></div>

<h1 class='text-center hidden-print'>Print sample labels</h1>

<div class='col-md-3 hidden-print' role='complementary' >

	<form class="form-horizontal" method="get" id='mainform' style='position:fixed;'>
		<div class="form-group">
			<label for="cypher" class="col-sm-2 control-label">Cypher/Batch</label>
			<div class="col-sm-10">
				<?php
					$sql="
						Select
							dw_cypher.cypherID,
							dw_cypher.cypherText,
							dw_cypher.cypherManuDate,
							dw_cypher.cypherOrderID,
							dw_spec.specText,
							dw_spec.specShortDesc
						From
							dw_cypher Left Join
							dw_spec
								On dw_cypher.cypherSpec = dw_spec.specID
						Where
							dw_cypher.cypherSite = ? And
							dw_spec.specActive = 1 And
							dw_cypher.cypherManuDate >= ?
						Order By
							dw_cypher.cypherManuDate Desc,
							dw_spec.specOrder
					";
					if(!$cypherquery = mysqli_prepared_query($link, $sql, "is", array($_SESSION['userSite'], date('Y-m-d',strtotime((date('Y')-1)."-".$_SESSION['season_start']."-01"))), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					echo "<select id='cypher' name='cypher' class='form-control' onchange='submit();'>";
						foreach($cypherquery as $cypherarray){
							echo "<option value='".$cypherarray['cypherID']."'";
								if(isset($_GET['cypher']) && $_GET['cypher']==$cypherarray['cypherID']) echo " selected";
								echo ">".date('d/m/Y',strtotime($cypherarray['cypherManuDate']))." ".$cypherarray['cypherText']." ".$cypherarray['cypherOrderID']." ".$cypherarray['specText']." ".$cypherarray['specShortDesc'];
								if($debug) echo " [".$cypherarray['cypherID']."]";
							echo "</option>";
						}
					?>
				</select>
			</div>
		</div>
		
		<div class="form-group">
			<label for="cols" class="col-sm-2 control-label">Columns</label>
			<div class="col-sm-10">
				<input type='number' name='cols' id='cols' class='form-control' min='1' value='<?php echo $cols; ?>' onkeyup='update_total();' >
			</div>
		</div>
		
		<div class="form-group">
			<label for="rows" class="col-sm-2 control-label">Rows</label>
			<div class="col-sm-10">
				<input type='number' name='rows' id='rows' class='form-control' min='1' value='<?php echo $rows; ?>' onkeyup='update_total();' >
			</div>
		</div>
		
		<div class="form-group">
			<label for="rows" class="col-sm-2 control-label">Total</label>
			<div class="col-sm-10">
				<p class="form-control-static" id="total"><?php echo $cols*$rows; ?></p>
			</div>
		</div>
		
		<div class="form-group">
			<label for="skip" class="col-sm-2 control-label">Skip</label>
			<div class="col-sm-10">
				<input type='number' name='skip' class='form-control' min='0' value='<?php echo $skip; ?>'>
			</div>
		</div>
		
		<?php
			$sql="
				# get spec type to see if its IP
				Select
					dw_spec.specStyle
				From
					dw_cypher Inner Join
					dw_spec
						On dw_cypher.cypherSpec = dw_spec.specID
				Where
					dw_cypher.cypherID = ?
			";
			if(!$stylequery = mysqli_prepared_query($link, $sql, "i", array(isset($_GET['cypher']) ? $_GET['cypher'] : 0), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			$stylearray = $stylequery[0];
			$specstyle = $stylearray['specStyle'];
			if($specstyle!=1){
		?>
		<div class='form-group'>
			<label for='print_date' class='col-sm-2 control-label'>Print date</label>
			<div class='col-sm-10'>
				<input type='checkbox' data-toggle='toggle' id='print_date' name='print_date' data-onstyle='success' data-offstyle='default' data-on='Yes' data-off='No' value='1' >
				<!--<input type='hidden' id='print_datex' value='1' >-->
				<script>
					$(function() {
						$('#print_date').bootstrapToggle();
					})
					//var print_datex = document.getElementById('print_datex').value;
					var print_date = document.getElementById('print_date');
					
					if(print_date.checked || 1==<?php if(isset($_GET['print_date']) && $_GET['print_date']==1) echo "1"; else echo "0";?>){
						print_date.checked = true;
						if(typeof $('#print_date').bootstrapToggle=='function') $('#print_date').bootstrapToggle('on');
					}else{
						print_date.checked = false;
						if(typeof $('#print_date').bootstrapToggle=='function') $('#print_date').bootstrapToggle('off');
					}
				</script>
			</div>
		</div>
			<?php } ?>
		<div class="form-group">
			<div class="col-sm-offset-2 col-sm-10">
				<button type="submit" class="btn btn-primary"><span class='glyphicon glyphicon-search' aria-hidden='true'></span>&nbsp;Preview</button>
				<button type="submit" class="btn btn-default" name="print"><span class='glyphicon glyphicon-print' aria-hidden='true'></span>&nbsp;Print barcodes</button><br>
				<!--<a class="btn btn-default" href="javascript:(function(){alert('Please set page margins to zero');window.print();})();" role="button"><img src="images/printer_small.png">&nbsp;Print</a>-->
				<a class="btn btn-default" href="subform.php?cypher=<?php echo $cypher; ?>" role="button"><img src='images/subform.png'>&nbsp;Sub form</a>
				<a class="btn btn-default" href="barcode.php" role="button"><img src='images/barcode.png'>&nbsp;Scan samples</a>
			</div>
		</div>
		
		<div class="form-group">
			<div class="col-sm-offset-2 col-sm-10">
				<a href='https://www.officemax.co.nz/search?FilterFeature=ProductFeatureNames.Group:eq:Category,Value:eq:Everyday%20Printer%20Labels&PageProduct=1' target='_blank'>OfficeMax labels</a>&nbsp;<img src='images/ext_link.gif'><br>
				<?php
					switch($cols){
						case 2:
							echo "<a href='https://www.officemax.co.nz/search?ProductSearch=1950738' target='_blank'>OfficeMax labels (2x7)</a>&nbsp;<img src='images/ext_link.gif'>";
							break;
						case 3:
							echo "<a href='https://www.officemax.co.nz/search?ProductSearch=1950770' target='_blank'>OfficeMax labels (3x7)</a>&nbsp;<img src='images/ext_link.gif'><br>";
							echo "<a href='https://www.officemax.co.nz/search?ProductSearch=1950789' target='_blank'>OfficeMax labels (3x8)</a>&nbsp;<img src='images/ext_link.gif'>";
							break;
					}
				?>
			</div>
		</div>
		
	</form>
</div>

<div id='main' class='col-md-9' >
	<div class='pull-right'>
		<table border='1'>
			<?php
			
				$sql="
					Select
						dw_cypher.cypherText,
						dw_cypher.cypherManuDate,
						dw_cypher.cypherOrderID,
						dw_spec.specText,
						dw_spec.specShortDesc,
						dw_spec.specStyle,
						dw_unit.unitID,
						dw_unit.unitText,
						dw_location.locationText
					From
						dw_cypher Left Join
						dw_spec
							On dw_cypher.cypherSpec = dw_spec.specID Right Join
						dw_unit
							On dw_unit.unitCypher = dw_cypher.cypherID Left Join
						dw_location
							On dw_unit.unitLocation = dw_location.locationID
					Where
						dw_cypher.cypherID = ? And
						dw_location.locationActive = 1 And
						dw_unit.unitActive = 1
					Order by
						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', 'Comp1', 'Comp 1', 'Comp2', 'Comp 2'),
						LPad(dw_unit.unitText, 20, 0),
						dw_location.locationOrder,
						dw_location.locationText
				";
				if(!$cquery = mysqli_prepared_query($link, $sql, "i", array($cypher), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
				echo "<tr>";
				
				//skip cells
				for($i=0; $i<$skip; $i++){
					echo "<td class='text-center' width='".$cellwidth."mm' height='".$cellheight."px;' style='width:".$cellwidth."mm;min-width:".$cellwidth."mm;max-width:".$cellwidth."mm;height:".$cellheight."mm;min-height:".$cellheight."mm;max-height:".$cellheight."mm;table-layout:fixed;'>&nbsp;</td>";
					$counter++;
					if($counter > $cols){
						echo "</tr><tr>";
						$counter = 1;
					}
				}
				
				foreach($cquery as $carray){
					echo "<td class='text-center' width='".$cellwidth."mm' height='".$cellheight."px;' style='width:".$cellwidth."mm;min-width:".$cellwidth."mm;max-width:".$cellwidth."mm;height:".$cellheight."mm;min-height:".$cellheight."mm;max-height:".$cellheight."mm;table-layout:fixed;'>
						<table width='100%' border='0'>
							<tr>
								<td rowspan='4' width='20%' style='width:20%;'>
									";
									//generate barcode
									barcode("images/barcodes/U".$carray['unitID'].".png", "U".$carray['unitID'], $cellheight, "vertical", "code128a", true);
									//display barcode
									echo "
									<img src='images/barcodes/U".$carray['unitID'].".png' alt='U".$carray['unitID']."' />
								</td>
								<td class='date'>";
									if($carray['specStyle']==1){
										if($_SESSION['cypherorbatch']==0) echo $carray['cypherText'];
										if($_SESSION['cypherorbatch']==1) echo $carray['cypherOrderID'];
										if($_SESSION['cypherorbatch']==2) echo $carray['cypherText']." ".$carray['cypherOrderID'];
									}else{
										if(isset($_GET['print_date']) && $_GET['print_date']==1){
											echo date('d/m/Y',strtotime($carray['cypherManuDate']));
										}else{
											echo "&nbsp;";
										}
									}
								echo "</td>
							</tr>
							<tr>
								<td style='overflow:hidden;'>";
									if($carray['specText']==$carray['specShortDesc']) echo $carray['specText'];
									else echo substr($carray['specText']." (".$carray['specShortDesc'].")",0,20);
								echo "</td>
							</tr>
							<tr>
								<td>".$carray['locationText']."</td>
							</tr>
							<tr>
								<td><strong>".$carray['unitText']."</strong></td>
							</tr>
						</table>
					</td>";
					
					$counter++;
					if($counter > $cols){
						echo "</tr>";
						if($current_col%$rows==0){
							echo "</tr><tr height='50px' style='height=50px;min-height=50px;max-height=50px;'><td colspan='".$cols."' height='50px' style='height=50px;min-height=50px;max-height=50px;'>&nbsp;</td></tr><tr>";
						}
						echo "<tr>";
						$counter = 1;
						$current_col++;
					}
				}
				echo "</tr>";
			?>
		</table>
	</div>
</div>

<script src="js/print_labels.js?v=2.1"></script>

<?php require "inc/footer.php"; ?>