<?php
	/* (C) DairyWindow 2012-2017 */

	$tests_per_page = 40;
	$left_margin = 5;

	//these cyphers will not have a cypher code printed (AMF). Requested by Brody 21/11/16
	$no_cypher = array(178,156);
	
	// Function to calculate square of value - mean
	function sd_square($x, $mean) {
		return pow($x - $mean,2);
	}
	// Function to calculate standard deviation (uses sd_square)    
	function sd($array) {
		// square root of sum of squares devided by N-1
		return sqrt(array_sum(array_map("sd_square", $array, array_fill(0,count($array), (array_sum($array) / (count($array)+0.0000000001)) ) ) ) / ((count($array)-1)+0.0000000001) ); //Changed 20/10/11 to try and stop divide by zero error
	}
	
	require "inc/connect.php";
	require "inc/fade.php";
	
	if(isset($_POST['generate']) && isset($_POST['cypher'])){
		
		require("inc/texttonumber.php"); // function for converting text result to number
		require("inc/numbertotext.php"); // function for converting number result to text
		
		if($debug) $pdfoutput = false;
		else $pdfoutput = true; //Use true for pdf output; false for html output

		if($pdfoutput){
			require("inc/pdf/fpdf.php");
			define('FPDF_FONTPATH', 'inc/pdf/font/');
			class PDF extends FPDF{
				//Page header
				function Header(){
					
					global $link;
					if($_SESSION['userSite']==5){ //Yashili
						if($this->PageNo()!=1){ //dont have page header on first page
							$textsize = 9;
							$spacing = ($textsize/2.5);
							
							$sql="
								Select
									dw_spec.specShortDesc,
									dw_spec.specText,
									dw_spec.specBlurb,
									dw_cypher.cypherText,
									dw_cypher.cypherOrderID
								From
									dw_spec Right Join
									dw_cypher On dw_spec.specID = dw_cypher.cypherSpec
								Where
									dw_cypher.cypherID  = ?
							";
							if(!$qryspec = mysqli_prepared_query($link, $sql, "i", array($_POST['cypher']), __FILE__, __LINE__)) reporterror(get_error(), $sql,__FILE__,__LINE__);
							$specarray = $qryspec[0];
							
							//logo
							//$this->Image('images/5/company_logo_pdf.jpg',20,10,null,10);
							
							$this->SetFont('Arial', 'B', $textsize);
							$this->Cell(70, $spacing, ''); //gap
							$this->Cell(40, $spacing, 'Product:');
							$this->SetFont('Arial', '', $textsize);
							$this->Cell(80, $spacing, $specarray['specShortDesc'], 0, 1);
							
							$this->SetFont('Arial', 'B', $textsize);
							$this->Cell(70, $spacing, ''); //gap
							$this->Cell(40, $spacing, 'Product code:');
							$this->SetFont('Arial', '', $textsize);
							$this->Cell(80, $spacing, $specarray['specText'], 0, 1);
							
							$this->SetFont('Arial', 'B', $textsize);
							$this->Cell(70, $spacing, ''); //gap
							$this->Cell(40, $spacing, 'Batch:');
							$this->SetFont('Arial', '', $textsize);
							if($_SESSION['cypherorbatch']=='0' || $_SESSION['cypherorbatch']==0) $this->Cell(80, $spacing, $specarray['cypherText'], 0, 1);
							else $this->Cell(80, $spacing, $specarray['cypherOrderID'], 0, 1);
							
							//$this->SetDrawColor(10,10,190);
							//$this->Line(15,25, 195,25);
							
							$this->Ln();
						}
					}else{
						global $spacing, $textsize;

						if($this->PageNo()!=1){
							//page 2
							$this->SetFont('Arial', 'BU', $textsize);
							$this->Cell(5, $spacing, '');
							$this->Cell(75, $spacing, 'TEST');
							$this->Cell(20, $spacing, 'RESULTS', 0, 0, 'C');
							if(!empty($_POST['show_samples'])) $this->Cell(20, $spacing, 'SAMPLES', 0, 0, 'C');
							if(!empty($_POST['show_method'])) $this->Cell(65, $spacing, 'TEST METHOD');
							$this->Ln(10);
						}
					}
				}
				
				//Page footer
				function Footer(){
					global $link, $testcount, $tests_per_page, $spacing, $left_margin;
					if($_SESSION['userSite']==5){
						$textsize=8;
						$spacing = ($textsize/2.5);
						$this->SetFont('Arial', '', $textsize);
						$this->SetY(-10); //mm from bottom
						$this->SetTextColor(0,0,255);
						$this->Cell(40, $spacing, 'I_MS_8.9.4_tem V1.0', 0, 0, 'L');
						$this->Cell(115, $spacing, 'Print date '.date('d/m/Y g:i a'), 0, 0, 'C');
						$this->Cell(40, $spacing, 'Page '.$this->PageNo().' of {nb}', 0, 0, 'R');
					
					}else{

						if($testcount < $tests_per_page || $this->PageNo()!=1){

							if($_POST['sig']!="" && $_POST['sig']!=null) $user = clean($_POST['sig']);else $user = $_SESSION['userID'];
							$sql = "
								select
									dw_user.userID,
									dw_user.userFirst,
									dw_user.userLast,
									dw_user.userTitle
								from
									dw_user
								where
									dw_user.userID = ?
							";
							if(!$qryUser = mysqli_prepared_query($link, $sql, "i", array($user), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							$user = $qryUser[0];

							$textsize = 8;
							$spacing = ($textsize / 2.5);
							$this->SetFont('Arial', 'B', $textsize);

							$this->SetY(-75); //7.5cm from bottom

							if(isset($_POST['blurb3']) && $_POST['blurb3']!=""){

								$blurbs = explode('<br>', $_POST['blurb3']);
								foreach($blurbs as $blurb){
									$this->Cell($left_margin, $spacing, ''); //gap
									if($blurb!='') $this->multicell(130, $spacing, strip_tags($blurb));
								}
								$this->Ln();
							}


							$this->SetY(-65); //6.5cm from bottom

							$blurbs = explode('<br>', str_replace('&nbsp;', ' ', $_POST['blurb']));
							foreach($blurbs as $blurb){
								$this->Cell(5, $spacing, ''); //gap
								if($blurb!='') $this->multicell(180, $spacing, strip_tags($blurb));
							}
							if($_SESSION['userID']==$user['userID'] && file_exists('images/sigs/'.$user['userID'].'.jpg')){
								//                                                 x , y  , w  , h
								$this->image('images/sigs/'.$user['userID'].'.jpg', 40, null, null, 20); //automatic width
							}else{
								$this->SetX(40);
								$this->Cell(30, 20, '', 0, 1); //Hand written signature will go here
							}

							$this->SetY(-25); //2.5cm from bottom

							$textsize = 11;
							$this->SetFont('Arial', 'B', $textsize);
							$spacing = ($textsize / 2.5);
							$this->Cell(5, $spacing, '');
							$this->Cell(30, $spacing, 'Signatory:');
							if($user['userID']==0) $this->Cell(100, $spacing, $_SESSION['userFirst'].' '.$_SESSION['userLast'], 0, 1); //Dairy Window
							else $this->Cell(100, $spacing, $user['userFirst'].' '.$user['userLast'], 0, 1);
							$this->Cell(5, $spacing, '');
							$this->Cell(30, $spacing, 'Title:');
							if($user['userID']==0) $this->Cell(100, $spacing, $_SESSION['userTitle'], 0, 1);else $this->Cell(100, $spacing, $user['userTitle'], 0, 1);
							$textsize = 8;
							$this->SetFont('Arial', 'B', $textsize);
							$spacing = ($textsize / 2.5);
							$this->Cell(5, $spacing, '');
							$this->Ln(5);

							$this->Cell(180, $spacing, 'Issued by manufacturer '.$_SESSION['comp_name_long'].' without alterations.', 0, 1, 'C');
							$this->Cell(180, $spacing, 'This COA shall not be copied or reproduced except in full. Not valid unless signed.', 0, 1, 'C');
						}else{
							//page two
							$this->SetY(-30); //mm from bottom
							$this->Cell(180, $spacing, 'Page '.$this->PageNo().' of {nb}', 0, 0, 'C');
						}
					}
				}
							
        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->AliasNbPages(); //this allows PHP to see the total number of pages in the PDF, just before output. Used in the page footer
			$pdf->SetFillColor(255, 255, 255);
		}

		$sql="
			# get cypher and spec data
			Select
				dw_cypher.cypherID,
				dw_cypher.cypherText,
				dw_cypher.cypherOrderID,
				dw_cypher.cypherManuDate,
				dw_cypher.cypherExpiryDate,
				dw_spec.specID,
				dw_spec.specText,
				dw_spec.specShortDesc,
				dw_spec.specShowLoc,
				dw_spec.specBlurb
			From
				dw_cypher Inner Join
				dw_spec On dw_cypher.cypherSpec = dw_spec.specID
			Where
				dw_cypher.cypherID = ?
		";
		if(!$qrycypher = mysqli_prepared_query($link, $sql, "i", array($_POST['cypher']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		$cypherarray = $qrycypher[0];
		
		$cypherText       = $cypherarray['cypherText'];
		$cypherOrderID    = $cypherarray['cypherOrderID'];
		$cypher           = $cypherarray['cypherID'];
		$cypherManuDate   = $_POST['cypherManuDate'];
		$cypherExpiryDate = $_POST['cypherExpiryDate'];
		$specID           = $cypherarray['specID'];
		$specText         = $cypherarray['specText'];
		$specShortDesc    = $cypherarray['specShortDesc'];
		$specShowLoc      = $cypherarray['specShowLoc'];
		$specBlurb        = $cypherarray['specBlurb'];
		
		if($pdfoutput) {
			$pdf->SetDisplayMode('fullpage');
			$pdf->SetAuthor($_SESSION['userFirst'].' '.$_SESSION['userLast'],1);
			$pdf->SetCreator('DairyWindow',1);
			switch($_SESSION['cypherorbatch']){
				case 0:
				case '0':
					$pdf->SetSubject('COA for '.$cypherText.' '.$specText,1);
					$pdf->SetTitle(  'COA for '.$cypherText.' '.$specText,1);
					break;
				case 1:
				case '1':
					$pdf->SetSubject('COA for '.$cypherOrderID.' '.$specText,1);
					$pdf->SetTitle(  'COA for '.$cypherOrderID.' '.$specText,1);
					break;
			}
			
			$pdf->AddPage();
			
			$small = 65;
			$large = 100;
			
			list($width, $height) = getimagesize('images/'.$_SESSION['userSite'].'/company_logo_pdf.jpg');
			if($width>$height) $pdf->Image('images/'.$_SESSION['userSite'].'/company_logo_pdf.jpg',155,10,40,null); //yashili
			else $pdf->Image('images/'.$_SESSION['userSite'].'/company_logo_pdf.jpg',160,5,null,30); //odl
			
			$pdf->SetXY(-60,35);
			$textsize=8;
			$pdf->SetFont('Arial', '', $textsize);
			$spacing = ($textsize/2.5);
			
			if($_SESSION['postal_addr1']!="" && $_SESSION['postal_addr1']!=null) $pdf->Cell(50, $spacing, $_SESSION['postal_addr1'], 0, 2, 'C');
			if($_SESSION['postal_addr2']!="" && $_SESSION['postal_addr2']!=null) $pdf->Cell(50, $spacing, $_SESSION['postal_addr2'], 0, 2, 'C');
			if($_SESSION['phone']!="" && $_SESSION['phone']!=null){
				//phone is true
				if($_SESSION['fax']!="" && $_SESSION['fax']!=null){
					//phone is true, fax is true
					$pdf->Cell(50, $spacing, 'T: '.$_SESSION['phone'].', F: '.$_SESSION['fax'], 0, 2, 'C');
				}else{
					//phone is true, fax is false
					$pdf->Cell(50, $spacing, 'T: '.$_SESSION['phone'], 0, 2, 'C');
				}
			}else{
				//phone is false
				if($_SESSION['fax']!="" && $_SESSION['fax']!=null){
					//phone is false, fax is true
					$pdf->Cell(50, $spacing, 'F: '.$_SESSION['fax'], 0, 2, 'C');
				//}else{
					//phone is false, fax is false
					//$pdf->Cell(50, $spacing, '', 0, 2, 'C');
				}
			}
			
			if($_SESSION['website']!="" && $_SESSION['website']!=null) $pdf->Cell(50, $spacing, $_SESSION['website'], 0, 2, 'C',False, $_SESSION['website']);
			$pdf->Ln();
			if($_SESSION['userSite']==5){ //5 is Yashili
				$textsize = 20;
				$pdf->SetFont('Arial', '', $textsize);
				$pdf->SetY(10); // 10cm from top
				$align = 'L';
				$pdf->Cell($left_margin, $spacing, '');
			}else{
				$textsize = 15;
				$pdf->SetFont('Arial', 'BU', $textsize);
				$align = 'C';
				$pdf->SetY(10); // 10cm from top
			}
			$spacing = ($textsize/2.5);
			$pdf->Cell($left_margin, $spacing, '');
			$pdf->Cell(130, $spacing, 'CERTIFICATE OF ANALYSIS', 0, 2, 'L');
			$pdf->Ln();
			$textsize = 10;
			if($_SESSION['userSite']==5){
				$pdf->SetFont('Arial', '', $textsize);
			}else{
				$pdf->SetFont('Arial', 'B', $textsize);
			}
			$spacing = ($textsize/2.5);
			if($_SESSION['userSite']==5){ //yashili
				$pdf->Cell($left_margin, $spacing, '');
					$pdf->SetFont('Arial', 'B', $textsize);
					$pdf->Cell($small, $spacing, 'Product:');
					$pdf->SetFont('Arial', '', $textsize);
					$pdf->Cell($large, $spacing, $specShortDesc, 0, 1);
				$pdf->Cell($left_margin, $spacing, '');
					$pdf->SetFont('Arial', 'B', $textsize);
					$pdf->Cell($small, $spacing, 'Product code:');
					$pdf->SetFont('Arial', '', $textsize);
					$pdf->Cell($large, $spacing, $specText, 0, 1);
				$pdf->Cell($left_margin, $spacing, '');
					$pdf->SetFont('Arial', 'B', $textsize);
					$pdf->Cell($small, $spacing, 'Manufacturing');
					$pdf->SetFont('Arial', '', $textsize);
					$pdf->Cell($large, $spacing, $_SESSION['comp_name_long'], 0, 1);
				$pdf->Cell($left_margin, $spacing, '');
					$pdf->SetFont('Arial', 'B', $textsize);
					$pdf->Cell($small, $spacing, 'plant:');
					$pdf->SetFont('Arial', '', $textsize);
					$pdf->Cell($large, $spacing, $_SESSION['comp_name'], 0, 1);
				$pdf->Cell($left_margin, $spacing, '');
					$pdf->SetFont('Arial', 'B', $textsize);
					$pdf->Cell($small, $spacing, 'Factory Reg. No:');
					$pdf->SetFont('Arial', '', $textsize);
					$pdf->Cell($large, $spacing, $_SESSION['factory_reg'], 0, 1);
				$pdf->Cell($left_margin, $spacing, '');
					$pdf->SetFont('Arial', 'B', $textsize);
					switch($_SESSION['cypherorbatch']){
						case 0:
						case '0':
							$pdf->Cell($small, $spacing, 'Cypher:');
							$pdf->SetFont('Arial', '', $textsize);
							if(isset($_GET['debug'])) $pdf->Cell($large, $spacing, $cypherText.' ('.$cypher.')', 0, 1);
							else $pdf->Cell($large, $spacing, $cypherText, 0, 1);
							break;
						case 1:
						case '1':
							$pdf->Cell($small, $spacing, 'Batch:');
							$pdf->SetFont('Arial', '', $textsize);
							if(isset($_GET['debug'])) $pdf->Cell($large, $spacing, $cypherOrderID.' ('.$cypher.')', 0, 1);
							else $pdf->Cell($large, $spacing, $cypherOrderID, 0, 1);
							break;
						default:
							$pdf->Cell($small, $spacing, 'Cypher/Batch:');
							$pdf->SetFont('Arial', '', $textsize);
							if(isset($_GET['debug'])) $pdf->Cell($large, $spacing, $cypherText.' '.$cypherOrderID.' ('.$cypher.')', 0, 1);
							else $pdf->Cell($large, $spacing, $cypherText.' '.$cypherOrderID, 0, 1);
							break;
					}
					$pdf->Cell($left_margin, $spacing, '');
					$pdf->SetFont('Arial', 'B', $textsize);
					$pdf->Cell($small, $spacing, 'Date of manufacture:');
					$pdf->SetFont('Arial', '', $textsize);
					$pdf->Cell($large, $spacing,$cypherManuDate, 0, 1);
				if(isset($_POST['additional']) && $_POST['additional']!=""){
					$pdf->Cell($left_margin, $spacing, '');
					$pdf->Cell($small, $spacing, 'Notes:');
					$pdf->Cell($large, $spacing, $_POST['additional'], 0, 1);
				}
			}else{ //other factories

				if(isset($_POST['blurb2']) && $_POST['blurb2']!=""){
					$pdf->SetFont('Arial', '', 9);
					$blurbs = explode('<br>', $_POST['blurb2']);
					foreach($blurbs as $blurb){
						$pdf->Cell($left_margin, $spacing, ''); //gap
						if($blurb!='') $pdf->multicell(130, $spacing, strip_tags($blurb));
					}
					$pdf->Ln();
				}

				$pdf->Cell($left_margin, $spacing, '');
					$pdf->Cell($small, $spacing, 'Date:');
					$pdf->Cell($large, $spacing,date('d F Y'), 0, 1);
				$pdf->Cell($left_margin, $spacing, '');
					$pdf->Cell($small, $spacing, 'Factory Reg. No:');
					$pdf->Cell($large, $spacing, $_SESSION['factory_reg'], 0, 1);
				$pdf->Cell($left_margin, $spacing, '');
					$pdf->Cell($small, $spacing, 'Product:');
					//$pdf->Cell($large, $spacing, $specShortDesc.': Specification '.$specText, 0, 1);
					$pdf->Cell($large, $spacing, $specShortDesc, 0, 1);
				$pdf->Cell($left_margin, $spacing, '');
					$pdf->Cell($small, $spacing, 'Manufacture Code:');
					//$pdf->Cell($large, $spacing, $cypherText.' - '.$specText.' '.$_POST['additional'], 0, 1);
					switch($_SESSION['cypherorbatch']){
						case 0:
						case '0':
							$pdf->Cell($large, $spacing, $cypherText, 0, 1);
							break;
						case 1:
						case '1':
							$pdf->Cell($large, $spacing, $cypherOrderID, 0, 1);
							break;
						default:
							if(in_array($specID, $no_cypher)) $pdf->Cell($large, $spacing, $cypherOrderID, 0, 1);
							else $pdf->Cell($large, $spacing, $cypherText.' '.$cypherOrderID, 0, 1);
							break;
					}

				$pdf->Cell($left_margin, $spacing, '');
					$pdf->Cell($small, $spacing, 'Date of Manufacture:');
					$pdf->Cell($large, $spacing,$cypherManuDate, 0, 1);
				if($cypherManuDate != $cypherExpiryDate){
					$pdf->Cell($left_margin, $spacing, '');
						$pdf->Cell($small, $spacing, 'Best before Date:');
						$pdf->Cell($large, $spacing,$cypherExpiryDate, 0, 1);
				}
			}

			if((isset($_POST['q1']) && $_POST['q1']!="" && $_POST['q1']!=null) || (isset($_POST['a1']) && $_POST['a1']!="" && $_POST['a1']!=null)){
				$pdf->Cell($left_margin, $spacing, '');
				$pdf->Cell($small, $spacing, $_POST['q1']);
				$pdf->Cell($large, $spacing, $_POST['a1'], 0, 1);
				$tests_per_page--;
			}
			if((isset($_POST['q2']) && $_POST['q2']!="" && $_POST['q2']!=null) || (isset($_POST['a2']) && $_POST['a2']!="" && $_POST['a2']!=null)){
				$pdf->Cell($left_margin, $spacing, '');
				$pdf->Cell($small, $spacing, $_POST['q2']);
				$pdf->Cell($large, $spacing, $_POST['a2'], 0, 1);
				$tests_per_page--;
			}
			if((isset($_POST['q3']) && $_POST['q3']!="" && $_POST['q3']!=null) || (isset($_POST['a3']) && $_POST['a3']!="" && $_POST['a3']!=null)){
				$pdf->Cell($left_margin, $spacing, '');
				$pdf->Cell($small, $spacing, $_POST['q3']);
				$pdf->Cell($large, $spacing, $_POST['a3'], 0, 1);
				$tests_per_page--;
			}
			if((isset($_POST['q4']) && $_POST['q4']!="" && $_POST['q4']!=null) || (isset($_POST['a4']) && $_POST['a4']!="" && $_POST['a4']!=null)){
				$pdf->Cell($left_margin, $spacing, '');
				$pdf->Cell($small, $spacing, $_POST['q4']);
				$pdf->Cell($large, $spacing, $_POST['a4'], 0, 1);
				$tests_per_page--;
			}
			
			if((isset($_POST['q5']) && $_POST['q5']!="" && $_POST['q5']!=null) || (isset($_POST['a5']) && $_POST['a5']!="" && $_POST['a5']!=null)){
				$pdf->Cell($left_margin, $spacing, '');
				$pdf->Cell($small, $spacing, $_POST['q5']);
				$pdf->Cell($large, $spacing, $_POST['a5'], 0, 1);
				$tests_per_page--;
			}
			if((isset($_POST['q6']) && $_POST['q6']!="" && $_POST['q6']!=null) || (isset($_POST['a6']) && $_POST['a6']!="" && $_POST['a6']!=null)){
				$pdf->Cell($left_margin, $spacing, '');
				$pdf->Cell($small, $spacing, $_POST['q6']);
				$pdf->Cell($large, $spacing, $_POST['a6'], 0, 1);
				$tests_per_page--;
			}
			if((isset($_POST['q7']) && $_POST['q7']!="" && $_POST['q7']!=null) || (isset($_POST['a7']) && $_POST['a7']!="" && $_POST['a7']!=null)){
				$pdf->Cell($left_margin, $spacing, '');
				$pdf->Cell($small, $spacing, $_POST['q7']);
				$pdf->Cell($large, $spacing, $_POST['a7'], 0, 1);
				$tests_per_page--;
			}
			if((isset($_POST['q8']) && $_POST['q8']!="" && $_POST['q8']!=null) || (isset($_POST['a8']) && $_POST['a8']!="" && $_POST['a8']!=null)){
				$pdf->Cell($left_margin, $spacing, '');
				$pdf->Cell($small, $spacing, $_POST['q8']);
				$pdf->Cell($large, $spacing, $_POST['a8'], 0, 1);
				$tests_per_page--;
			}
			
			$pdf->Ln();
			switch($_SESSION['userSite']){
				case 1:
				case '1':
					$red =   0; $green =   0; $blue = 132;
					break;
				case 2:
				case '2':
					$red = 235; $green =  45; $blue =  45;
					break;
				case 3:
				case '3':
					$red =   0; $green =   0; $blue = 132;
					break;
				case 4:
				case '4':
					$red =   4; $green =  67; $blue =  92;
					break;
				case 5:
				case '5':
					$red =  60; $green =  58; $blue = 127;
					break;
				default:
					$red =   0; $green =   0; $blue =   0;
			}
			$pdf->SetDrawColor($red, $green, $blue);
			$pdf->SetFillColor($red, $green, $blue);
			$pdf->SetLineWidth(0.5);
			$pdf->Cell(190, 1, '', 0, 1); //gap
			$pdf->Cell(5,1,'');
				if($_SESSION['userSite']!=5) $pdf->Cell(180, 0, '', 'T', 1); //line
			$pdf->Cell(190, 1, '', 0, 1); //gap
			
			$pdf->Ln();
			$pdf->SetLineWidth(0);
			$pdf->SetDrawColor(0, 0, 0);
			$pdf->SetFillColor(0, 0, 0);

			$pdf->Ln();
			if($_SESSION['userSite']==5){
				$textsize=10;
				$pdf->SetFont('Arial', '', $textsize);
			}else{
				$textsize=11;
				$pdf->SetFont('Arial', 'BU', $textsize);
			}
			$spacing = ($textsize/2);
			$pdf->Cell($left_margin, $spacing, '');
			
			if($_SESSION['userSite']==5){ //yashili
				$pdf->SetFont('Arial', 'B', $textsize);
				$pdf->Cell(50, $spacing, 'Parameter', 1, 0, 'C');
				$pdf->Cell(30, $spacing, 'Units of measure', 1, 0, 'C');
				$pdf->Cell(30, $spacing, 'Mean result', 1, 0, 'C');
				if(!empty($_POST['show_method'])) $pdf->Cell(70, $spacing, 'Test method', 1, 0, 'L');
				$pdf->Ln();
			}else{
				$pdf->Cell(75, $spacing, 'TEST');
				$pdf->Cell(20, $spacing, 'RESULTS', 0, 0, 'C');
				if(!empty($_POST['show_samples'])) $pdf->Cell(20, $spacing, 'SAMPLES', 0, 0, 'C');
				if(!empty($_POST['show_method' ])) $pdf->Cell(65, $spacing, 'TEST METHOD');
				$pdf->Ln();
			}
			$textsize = 9;
			if($_SESSION['userSite']==5) $pdf->SetFont('Arial', '', $textsize);
			else $pdf->SetFont('Arial', '', $textsize);
			$spacing = ($textsize / 2);
			//$spacing=9;
			
		}else{
			echo "<table border='1'><tr><td colspan='4'>
				Date:		".date('d F Y')."<br/>
				Factory:	".$_SESSION['factory_reg']."<br/>
				Product:	".$specShortDesc."<br/>
				Spec:		".$specText."<br/>";
				switch($_SESSION['cypherorbatch']){
					case 0:
					case '0':
						echo "Cypher:	".$cypherText."<br/>";
						break;
					case 1:
					case '1':
						echo "Batch:	".$cypherOrderID."<br/>";
						break;
				}
				echo "
				MDate:	".$cypherManuDate."<br/>
				BBefore:	".$cypherExpiryDate."
			</td></tr><tr><td><b>Test</b></td><td colspan='2'><b>Result</b></td><td><b>Method</b></td></tr>";
		}

		$sqlGroupTest='# Get list of unique tests for the result set
      SELECT
        dw_test.testID,
        dw_test.testTextCOA,
        dw_test.testMethod,
        dw_test.testUnits,
        dw_test.testFormat,
        dw_test.testRound,
        dw_test.testShowAvg
      FROM
        dw_test RIGHT JOIN
        dw_result ON dw_test.testID = dw_result.resultTest LEFT JOIN
        dw_unit ON dw_unit.unitID = dw_result.resultUnit LEFT JOIN
        dw_cypher ON dw_cypher.cypherID = dw_unit.unitCypher LEFT JOIN
        dw_spec ON dw_spec.specID = dw_cypher.cypherSpec RIGHT JOIN
        dw_coa ON dw_coa.coaSpec = dw_spec.specID AND
          dw_coa.coaTest = dw_test.testID LEFT JOIN
        dw_group ON dw_group.groupID = dw_test.testGroup
      WHERE
        dw_cypher.cypherID = ? And
        dw_test.testActive = 1
      GROUP BY
        testID
      ORDER BY
        dw_group.groupOrder,
        dw_test.testOrder';
		if(!$testarray = mysqli_prepared_query($link, $sqlGroupTest, "i", array($cypher), __FILE__, __LINE__)) reporterror(get_error(), $sqlGroupTest, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		$numbertests = mysqli_prepared_num_rows($testarray);
		if($numbertests>0){
			if($_SESSION['userSite']==5) $pdf->SetAutoPageBreak(1, 10); //Yashili
			else{
				//try to get all tests on 1 page, if possible
				if(isset($_POST['q8']) && $_POST['q8']!=""){
					$spacing = (70/$numbertests);
				}elseif(isset($_POST['q7']) && $_POST['q7']!=""){
					$spacing = (73.75/$numbertests);
				}elseif(isset($_POST['q6']) && $_POST['q6']!=""){
					$spacing = (77.5/$numbertests);
				}elseif(isset($_POST['q5']) && $_POST['q5']!=""){
					$spacing = (81.25/$numbertests);
				}elseif(isset($_POST['q4']) && $_POST['q4']!=""){
					$spacing = (85/$numbertests);
				}elseif(isset($_POST['q3']) && $_POST['q3']!=""){
					$spacing = (88.75/$numbertests);
				}elseif(isset($_POST['q2']) && $_POST['q2']!=""){
					$spacing = (92.5/$numbertests);
				}elseif(isset($_POST['q1']) && $_POST['q1']!=""){
					$spacing = (96.25/$numbertests);
				}else{
					$spacing = (100/$numbertests);
				}
				if($spacing < 4)  $spacing =  4; //min size
				if($spacing > 10) $spacing = 10; //max size
			}
		}else $spacing = 5;
		if(!$pdfoutput) echo 'Number of tests: '.$numbertests.'<br>Spacing: '.$spacing."<br>";

		$sqlLocUnit="
			# Get list of unique units for the result set (type, cypher)
			Select
			  dw_location.locationID,
			  dw_location.locationText,
			  dw_unit.unitID,
			  dw_unit.unitText
			From
			  (dw_result Left Join
			  dw_unit On dw_result.resultUnit = dw_unit.unitID Left Join
			  dw_location On dw_location.locationID = dw_unit.unitLocation) Left Join
			  dw_cypher On dw_unit.unitCypher = dw_cypher.cypherID
			Where
			  dw_cypher.cypherID = ? And
			  dw_location.locationActive = 1 And
			  dw_unit.unitActive = 1
			Group By
			  dw_unit.unitID
			Order By
			  dw_location.locationOrder,
				dw_location.locationText,
			  dw_unit.unitText
		";
		if(!$unitarray = mysqli_prepared_query($link, $sqlLocUnit, "i", array($cypher), __FILE__, __LINE__)) reporterror(get_error(), $sqlLocUnit, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		$numunits = mysqli_prepared_num_rows($unitarray);

		$testcount = 0;
		foreach($testarray as $test){
			$numsamples = 0;
			$testcount++;
			$tf = null;
			$tr = null;
			if(!$pdfoutput) echo "<tr>";
			
			//Show Group/Test
			if($pdfoutput){
				$pdf->Cell($left_margin, $spacing, '', 0, 0); //Left indent
				if($specShowLoc==1 || $specShowLoc=="1"){
					if($_SESSION['userSite']==5){
						$pdf->CellFitScale(50, $spacing,iconv('UTF-8', 'windows-1252//TRANSLIT', $test['unitText']." ".$test['locationText']." - ".$test['testTextCOA']),1,0);
						//$pdf->Cell(50, $spacing, $test['testTextCOA'], 0, 0);
					}else{
						if(!empty($test['unitText']) && !empty($test['locationText'])) $pdf->CellFitScale(75, $spacing, iconv('UTF-8', 'windows-1252//TRANSLIT', $test['unitText']." ".$test['locationText']." - ".$test['testTextCOA']." ".$test['testUnits']), 0, 0);
						else $pdf->CellFitScale(75, $spacing, iconv('UTF-8', 'windows-1252//TRANSLIT', $test['testTextCOA']." ".$test['testUnits']), 0, 0);
					}
				}else{
					if($_SESSION['userSite']==5){
						if($test['testShowAvg']==0) $pdf->CellFitScale(50, $spacing,iconv('UTF-8', 'windows-1252//TRANSLIT', $test['testTextCOA'].' #1'), 1, 0, 'C');
						else $pdf->CellFitScale(50, $spacing,iconv('UTF-8', 'windows-1252//TRANSLIT', $test['testTextCOA']), 1, 0, 'C');
						
						$pdf->CellFitScale(30, $spacing,iconv('UTF-8', 'windows-1252//TRANSLIT', $test['testUnits']), 1, 0, 'C');
					}else $pdf->CellFitScale(75, $spacing,iconv('UTF-8', 'windows-1252//TRANSLIT', $test['testTextCOA']." ".$test['testUnits']), 0, 0);
				}
				if($_SESSION['userSite']==5) $pdf->Cell(30, $spacing, $test['testUnits'],1,0);
			}
			else echo "<td>".utf8_decode($test['testTextCOA']." (".$test['testID'].") ".$test['testUnits'])."</td>";
			$averageSum = 0; //Reset for next test
			$averageCount = 0; //Reset for next test
			$result1array = array(); //Deletes the std dev array in between tests
			
			//die("cypher:".$cypher);

			$currentunit = 1;
			foreach($unitarray as $unit){
				if($unit['unitID']!=null && $unit['unitID']!=""){
					$sqlResult="
						# Get resultFriendly
						Select
						  dw_result.resultID,
						  dw_result.resultFriendly
						From
						  ((dw_result Inner Join
						  dw_test
							On dw_result.resultTest = dw_test.testID) Inner Join
						  dw_unit
							On dw_result.resultUnit = dw_unit.unitID Inner Join
						  dw_location
							On dw_unit.unitLocation = dw_location.locationID) Inner Join
						  dw_cypher
							On dw_unit.unitCypher = dw_cypher.cypherID
						Where
						  dw_unit.unitID = ? And
						  dw_test.testID = ? And
						  dw_cypher.cypherID = ? And
						  dw_location.locationActive = 1 And
						  dw_unit.unitActive = 1 And
						  dw_location.locationID = ?
						Order By
						  dw_result.resultModDate Desc # get rid of retests
						Limit 1
					";
					if(!$resultarray = mysqli_prepared_query($link, $sqlResult, "iiii", array($unit['unitID'], $test['testID'], $cypher, $unit['locationID']), __FILE__, __LINE__)) reporterror(get_error(), $sqlResult, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					if(mysqli_prepared_num_rows($resultarray)==1) $numsamples++;
					$result = $resultarray[0];

					//Get format from Test table
					if(!empty($result['resultID']) && !empty($result['resultFriendly'])){

						$last_result = $result['resultFriendly'];
						$resultformatted = texttonumber($result['resultFriendly'], $test['testFormat']);

						$tr = $test['testRound'];
						$tf = $test['testFormat'];
						
						if($test['testShowAvg']==0){
							if($pdfoutput){
								if($_SESSION['userSite']==5){
									if(is_numeric($resultformatted)) $pdf->Cell(30, $spacing, number_format($resultformatted, $tr), 1, 0, 'C');
									else $pdf->Cell(30, $spacing, $resultformatted, 1, 0, 'C');
									if($currentunit!=$numunits){
										//method
										$pdf->Cell(70, $spacing, $test['testMethod'],1,1,'L');
										//test
										$pdf->Cell($left_margin, $spacing, '', 0, 0, 'C');
										$pdf->CellFitScale(50, $spacing, $test['testTextCOA'].' #'.($currentunit+1), 1, 0, 'C');
										//units
										$pdf->Cell(30, $spacing, $test['testUnits'], 1, 0, 'C');
									}
								}else{
									if(is_numeric($resultformatted)) $pdf->Cell(20, $spacing, number_format($resultformatted, $tr), 0, 0, 'C');
									else $pdf->Cell(20, $spacing, $resultformatted, 0, 0, 'C');
								}
							}
						}else{
							$averageSum += $resultformatted;
							if($result['resultID']!=null && $result['resultID']!="") $averageCount++;
							if($result['resultID']!=null && $result['resultID']!="") $result1array[] = $resultformatted;
						}
					}
					$currentunit++;
				}
			}
			
			if($test['testShowAvg']==1){
				//Average
				if($averageCount>0) $average = ($averageSum/$averageCount);
				else $average = $averageSum;

				if($numsamples==1) $finalresult = $last_result;
				else $finalresult = numbertotext($average, $tf, $tr);

				if($pdfoutput){
					if($_SESSION['userSite']==5){
						if(is_numeric($finalresult)) $pdf->Cell(30, $spacing, number_format($finalresult, $tr), 1, 0, 'C');
						else $pdf->Cell(30, $spacing, $finalresult, 1, 0, 'C');
					}else{
						if(is_numeric($finalresult)) $pdf->Cell(20, $spacing, number_format($finalresult, $tr), 0, 0, 'C');
						else{
							$pdf->Cell(20, $spacing, $finalresult, 0, 0, 'C');
						}
					}
				}else{
					echo "<td>".$finalresult."</td>";
				}
			}
			
			//Test method
			if($_SESSION['userSite']==5){
				if($pdfoutput){
					$pdf->SetFillColor(255, 255, 255);
					$pdf->Cell(70, $spacing, $test['testMethod'], 1, 0, 'L');
					$pdf->Cell(50, $spacing, ' ', 'L', 1, 'L', 1); //TODO: check this is right
				}else echo "<td>".$test['testMethod']."</td>";
			}else{
				if($pdfoutput){
					if(!empty($_POST['show_samples'])) $pdf->Cell(20, $spacing, $numsamples, 0, 0, 'C'); //dont use $numunits, thats the total number of samples for the whole cypher
					if(!empty($_POST['show_method'])) $pdf->CellFitScale(65, $spacing, $test['testMethod']);
					$pdf->Ln();
				}else{
					if(!empty($_POST['show_samples'])) echo "<td>".$numsamples."</td>"; //dont use $numunits, thats the total number of samples for the whole cypher
					if(!empty($_POST['show_method'])) echo "<td>".$test['testMethod']."</td>";
				}
			}

			if($_SESSION['userSite']!=5 && $testcount % $tests_per_page == 0 && $pdfoutput){
				$pdf->AddPage();
			}

		}
		
		if($_SESSION['userSite']==5){
			//document footer
			$pdf->Ln();
			$sql="
				Select
					dw_user.userID,
					dw_user.userLevel,
					dw_user.userFirst,
					dw_user.userLast,
					dw_user.userTitle,
					dw_user.userEmail,
					dw_user.userSite,
					dw_user.userCOA
				From
					dw_user
				Where
					dw_user.userID = ?
			";
			if(!$qryUser = mysqli_prepared_query($link, $sql, "i", array($_POST['sig']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			$user = $qryUser[0];
			
			$blurbs = explode('<br>', $_POST['blurb']);
			foreach($blurbs as $blurb){
				$pdf->Cell($left_margin, $spacing, ''); //gap
				if($blurb!='') $pdf->multicell(180, $spacing, strip_tags($blurb).' ');
			}
			
			$pdf->Ln();
			$pdf->Cell($left_margin, $spacing, ''); //gap
			$pdf->Cell(25, $spacing, 'Compiled by:');
			$pdf->SetFont('Arial', 'B', $textsize);
			if($user['userID']==0) $pdf->Cell(75, $spacing, ' '); //Dairy Window
			else $pdf->Cell(75, $spacing, $user['userFirst'].' '.$user['userLast']);
			$pdf->SetFont('Arial', '', $textsize);
			
			$sql="
				Select
					dw_user.userID,
					dw_user.userLevel,
					dw_user.userFirst,
					dw_user.userLast,
					dw_user.userTitle,
					dw_user.userEmail,
					dw_user.userSite,
					dw_user.userCOA
				From
					dw_user
				Where
					dw_user.userID = ?
			";
			if(!$qryUser = mysqli_prepared_query($link, $sql, "i", array($_SESSION['coa_default_user']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			$user2 = $qryUser[0];
			
			$pdf->Cell(25, $spacing, 'Authorised by:');
			$pdf->SetFont('Arial', 'B', $textsize);
			$pdf->Cell(75, $spacing, $user2['userName'], 0, 1);
			
			$y = $pdf->GetY();
			if($_SESSION['userID']==$user['userID'] && file_exists('images/sigs/'.$user['userID'].'.jpg')){
				//												  x , y  , w  , h
				$pdf->image('images/sigs/'.$user['userID'].'.jpg',10,null,null,20); //automatic width
			}else{
				$pdf->SetX(40);
				$pdf->Cell(30,20, '', 0, 1); //Hand written signature will go here
			}
			if(file_exists('images/sigs/'.$user2['userID'].'.jpg')) $pdf->image('images/sigs/'.$user2['userID'].'.jpg', 110, $y, null, 20);
			$pdf->Cell(  5, $spacing, ''); //gap
			$pdf->Cell(100, $spacing, 'Date: '.date('d/m/Y'));
			$pdf->Cell(100, $spacing, 'Date: '.date('d/m/Y'));
		}
		
		if($pdfoutput){
			switch($_SESSION['cypherorbatch']){
				case 0:
				case '0':
					$pdf->Output($cypherText.'_'.$specText.'.pdf', 'D', 1);
					break;
				case 1:
				case '1':
					$pdf->Output($cypherOrderID.'_'.$specText.'.pdf', 'D', 1);
					break;
				case 2:
				case '2':
					$pdf->Output($cypherText.' '.$cypherOrderID.'_'.$specText.'.pdf', 'D', 1);
					break;
			}
		}else{
			echo "</table>";
			echo "Total tests: ".$testcount++."<br/>";
		}

		if($pdfoutput){
			$sql = "
				# Set COA as generated for this cypher
				UPDATE dw_cypher SET
					cypherCOA     = 1,
					cypherField1A = ?,
					cypherField1B = ?,
					cypherField2A = ?,
					cypherField2B = ?,
					cypherField3A = ?,
					cypherField3B = ?,
					cypherField4A = ?,
					cypherField4B = ?
				WHERE cypherID  = ?
			";
			if(!savesql($link, $sql, "ssssssssi", array($_POST['q1'], $_POST['a1'], $_POST['q2'], $_POST['a2'], $_POST['q3'], $_POST['a3'], $_POST['q4'], $_POST['a4'], $_POST['cypher']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		}

		exit();
	}
	
	$title = "Certificate of Analysis";
	require "inc/head.php";
	$menu = "coagen";
	require "inc/menu.php";
	
	if($debug) showdebug();
?>
	
	<div class='container' role='main'>
		<div class='coa'>
			<?php
				if(isset($_POST['cypher'])){
					$sql="
						# get information for the selected cypher
						Select
							dw_cypher.cypherText,
							dw_cypher.cypherManuDate,
							dw_cypher.cypherExpiryDate,
							dw_spec.specShortDesc,
							dw_spec.specBlurb,
							dw_cypher.cypherField1A,
							dw_cypher.cypherField1B,
							dw_cypher.cypherField2A,
							dw_cypher.cypherField2B,
							dw_cypher.cypherField3A,
							dw_cypher.cypherField3B,
							dw_cypher.cypherField4A,
							dw_cypher.cypherField4B
						From
							dw_spec Right Join
							dw_cypher
								On dw_spec.specID = dw_cypher.cypherSpec
						Where
							dw_cypher.cypherID = ?
					";
					if(!$cypher_query = mysqli_prepared_query($link, $sql, "i", array($_POST['cypher']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					$cypher_array     = $cypher_query[0];
					$cypherManuDate   = $cypher_array['cypherManuDate'];
					$cypherExpiryDate = $cypher_array['cypherExpiryDate'];
					$specShortDesc    = $cypher_array['specShortDesc'];
					$specBlurb        = $cypher_array['specBlurb'];
					
					$q1 = $cypher_array['cypherField1A'];
					$a1 = $cypher_array['cypherField1B'];
					$q2 = $cypher_array['cypherField2A'];
					$a2 = $cypher_array['cypherField2B'];
					$q3 = $cypher_array['cypherField3A'];
					$a3 = $cypher_array['cypherField3B'];
					$q4 = $cypher_array['cypherField4A'];
					$a4 = $cypher_array['cypherField4B'];
					
				}else{
					$cypherManuDate   = "";
					$cypherExpiryDate = "";
					$specShortDesc    = "";
					$specBlurb        = "";
				}
			?>
			
			<h1 class='text-center'>Certificate of Analysis</h1>
			
			<form class="form-horizontal" method="post" id='mainform' >
				<div class="form-group" style='width:770px;max-width:770px;margin-left:200px;'><!-- blurb2 -->
					<textarea class='textarea' name='blurb2' rows="2"><?php if(isset($_POST['blurb2'])) echo $_POST['blurb2']; ?></textarea>
				</div>
				<div class="form-group"><!-- date -->
					<label class="col-sm-2 control-label">Date</label>
					<div class="col-sm-10">
						<p class="form-control-static"><?php echo date('d F Y'); ?></p>
					</div>
				</div>
				<div class="form-group"><!-- factory -->
					<label class="col-sm-2 control-label">Factory Reg No</label>
					<div class="col-sm-10">
						<p class="form-control-static"><?php echo $_SESSION['factory_reg']; ?></p>
					</div>
				</div>
				<div class="form-group"><!-- manufacture code -->
					<label for="cypher" class="col-sm-2 control-label">Manufacture code</label>
					<div class="col-sm-10">
						<?php
							$sql="
								# get cyphers and no of units
								Select
									dw_cypher.cypherID,
									dw_cypher.cypherText,
									dw_cypher.cypherOrderID,
									dw_cypher.cypherCOA,
									dw_spec.specText,
									Count(dw_unit.unitID) As units
								From
									dw_spec Right Join
									dw_cypher On dw_spec.specID = dw_cypher.cypherSpec Left Join
									dw_unit On dw_cypher.cypherID = dw_unit.unitCypher
								Where
									dw_cypher.cypherSite = ? And
									dw_spec.specActive   = 1 And
									dw_unit.unitActive   = 1 And
									dw_spec.specStyle    = 1 And
									dw_cypher.cypherManuDate >= ?
								Group By
									dw_cypher.cypherID
								Order By
									dw_cypher.cypherManuDate Desc,
									dw_spec.specStyle,
									dw_spec.specOrder
							";
							if(!$cypher_query = mysqli_prepared_query($link, $sql, "is", array($_SESSION['userSite'], $startDate), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
						?>
						<select class='form-control' name='cypher' id='cypher' onchange="submit();">
							<option value='0'></option>
							<?php
								foreach($cypher_query as $cypher_array){
									if($cypher_array['units']>0){
										echo "<option value='".$cypher_array['cypherID']."' ";
										if(isset($_POST['cypher']) && $cypher_array['cypherID']==$_POST['cypher']) echo "selected ";
										echo ">";
										switch($_SESSION['cypherorbatch']){
											case 0: //cypher
											case '0':
												echo $cypher_array['cypherText'];
												break;
											case 1: //batch
											case '1':
												echo $cypher_array['cypherOrderID'];
												break;
											default: //both
												echo $cypher_array['cypherText']." ".$cypher_array['cypherOrderID'];
												break;
										}
										if($debug) echo " [".$cypher_array['cypherID']."]";
										echo " ".$cypher_array['specText'];
										if($debug) echo " (".$cypher_array['units'].' units)';
										if($cypher_array['cypherCOA']==1) echo " &#10004;";
										
										echo "</option>";
									}
								}
							?>
						</select>
					</div>
				</div>
				<div class="form-group"><!-- product -->
					<label class="col-sm-2 control-label">Product</label>
					<div class="col-sm-10">
						<p class="form-control-static"><?php echo $specShortDesc; ?></p>
					</div>
				</div>
				<div class="form-group"><!-- date of manufacture -->
					<label class="col-sm-2 control-label">Date of Manufacture</label>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="cypherManuDate" value="<?php if(isset($_POST['cypher'])) echo date('d F Y',strtotime($cypherManuDate)); ?>">
					</div>
				</div>
				<div class="form-group"><!-- best before -->
					<label class="col-sm-2 control-label">Best before date</label>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="cypherExpiryDate" value="<?php if(isset($_POST['cypher'])) echo date('d F Y',strtotime($cypherExpiryDate)); ?>">
					</div>
				</div>
				<div class="form-group"><!-- q1 -->
					<div class="col-sm-2">
						<input class='form-control' type='text' name='q1' id='q1' onkeyup="showdiv('divq2');"<?php
							if(isset($q1) && $q1!="") echo " value='".$q1."'";
						?> >
					</div>
					<div class="col-sm-10">
						<input class='form-control' type='text' name='a1' id='a1' onkeyup="showdiv('divq2');"<?php
							if(isset($a1) && $a1!="") echo " value='".$a1."'";
						?> >
					</div>
				</div>
				<div class="form-group" style='display:none;' id='divq2'><!-- q2 -->
					<div class="col-sm-2">
						<input class='form-control' type='text' name='q2' id='q2' onkeyup="showdiv('divq3');"<?php
							if(isset($q2) && $q2!="") echo " value='".$q2."'";
						?> >
					</div>
					<div class="col-sm-10">
						<input class='form-control' type='text' name='a2' id='a2' onkeyup="showdiv('divq3');"<?php
							if(isset($a2) && $a2!="") echo " value='".$a2."'";
						?> >
					</div>
				</div>
				<div class="form-group" style='display:none;' id='divq3'><!-- q3 -->
					<div class="col-sm-2">
						<input class='form-control' type='text' name='q3' id='q3' onkeyup="showdiv('divq4');"<?php
							if(isset($q3) && $q3!="") echo " value='".$q3."'";
						?> >
					</div>
					<div class="col-sm-10">
						<input class='form-control' type='text' name='a3' id='a3' onkeyup="showdiv('divq4');"<?php
							if(isset($a3) && $a3!="") echo " value='".$a3."'";
						?> >
					</div>
				</div>
				<div class="form-group" style='display:none;' id='divq4'><!-- q4 -->
					<div class="col-sm-2">
						<input class='form-control' type='text' name='q4' id='q4' onkeyup="showdiv('divq5');"<?php
							if(isset($q4) && $q4!="") echo " value='".$q4."'";
						?> >
					</div>
					<div class="col-sm-10">
						<input class='form-control' type='text' name='a4' id='a4' onkeyup="showdiv('divq5');"<?php
							if(isset($a4) && $a4!="") echo " value='".$a4."'";
						?> >
					</div>
				</div>
				<div class="form-group" style='display:none;' id='divq5'><!-- q5 -->
					<div class="col-sm-2">
						<input class='form-control' type='text' name='q5' id='q5' onkeyup="showdiv('divq6');">
					</div>
					<div class="col-sm-10">
						<input class='form-control' type='text' name='a5' id='a5' onkeyup="showdiv('divq6');">
					</div>
				</div>
				<div class="form-group" style='display:none;' id='divq6'><!-- q6 -->
					<div class="col-sm-2">
						<input class='form-control' type='text' name='q6' id='q6' onkeyup="showdiv('divq7');">
					</div>
					<div class="col-sm-10">
						<input class='form-control' type='text' name='a6' id='a6' onkeyup="showdiv('divq7');">
					</div>
				</div>
				<div class="form-group" style='display:none;' id='divq7'><!-- q7 -->
					<div class="col-sm-2">
						<input class='form-control' type='text' name='q7' id='q7' onkeyup="showdiv('divq8');">
					</div>
					<div class="col-sm-10">
						<input class='form-control' type='text' name='a7' id='a7' onkeyup="showdiv('divq8');">
					</div>
				</div>
				<div class="form-group" style='display:none;' id='divq8'><!-- q8 -->
					<div class="col-sm-2">
						<input class='form-control' type='text' name='q8' id='q8'>
					</div>
					<div class="col-sm-10">
						<input class='form-control' type='text' name='a8' id='a8'>
					</div>
				</div>
				<div class="text-center" ><!-- buttons -->
					<br>
					<div class="btn-group" role="group" aria-label="buttons">
						<div class="btn-group" role="group">
							<button type="button" class="btn btn-default" onclick="update_buttons(1);"><?php echo $_SESSION['group1_name']; ?></button>
							<span style='display:none;' id='group1_value1'><?php echo $_SESSION['group1_value1']; ?></span>
							<span style='display:none;' id='group1_value2'><?php echo $_SESSION['group1_value2']; ?></span>
							<span style='display:none;' id='group1_value3'><?php echo $_SESSION['group1_value3']; ?></span>
							<span style='display:none;' id='group1_value4'><?php echo $_SESSION['group1_value4']; ?></span>
						</div>
						<div class="btn-group" role="group">
							<button type="button" class="btn btn-default" onclick="update_buttons(2);"><?php echo $_SESSION['group2_name']; ?></button>
							<span style='display:none;' id='group2_value1'><?php echo $_SESSION['group2_value1']; ?></span>
							<span style='display:none;' id='group2_value2'><?php echo $_SESSION['group2_value2']; ?></span>
							<span style='display:none;' id='group2_value3'><?php echo $_SESSION['group2_value3']; ?></span>
							<span style='display:none;' id='group2_value4'><?php echo $_SESSION['group2_value4']; ?></span>
						</div>
						<div class="btn-group" role="group">
							<button type="button" class="btn btn-default" onclick="update_buttons(3);"><?php echo $_SESSION['group3_name']; ?></button>
							<span style='display:none;' id='group3_value1'><?php echo $_SESSION['group3_value1']; ?></span>
							<span style='display:none;' id='group3_value2'><?php echo $_SESSION['group3_value2']; ?></span>
							<span style='display:none;' id='group3_value3'><?php echo $_SESSION['group3_value3']; ?></span>
							<span style='display:none;' id='group3_value4'><?php echo $_SESSION['group3_value4']; ?></span>
						</div>
					</div>
				</div>
				<hr>
				<?php // results
					if(isset($_POST['cypher'])) $cypher = $_POST['cypher'];
					else $cypher = 0;
					
					$sql="
						# get test info
						Select
							dw_result.resultTest
						From
							dw_result Left Join
							dw_unit On dw_result.resultUnit = dw_unit.unitID
						Where
							dw_unit.unitActive = 1 And
							dw_unit.unitCypher = ?
						Group By
							dw_result.resultTest
					";
					$sql='# get test info
						Select
						  dw_test.testID
						From
						  dw_result Left Join
						  dw_unit On dw_result.resultUnit = dw_unit.unitID Left Join
						  dw_test On dw_test.testID = dw_result.resultTest Left Join
						  dw_cypher On dw_cypher.cypherID = dw_unit.unitCypher Left Join
						  dw_spec On dw_spec.specID = dw_cypher.cypherSpec Right Join
						  dw_coa On dw_coa.coaSpec = dw_spec.specID And dw_coa.coaTest = dw_test.testID
						Where
						  dw_unit.unitActive = 1 And
						  dw_test.testActive = 1 And
						  dw_cypher.cypherID = ?';
					if(!$test_query = mysqli_prepared_query($link, $sql, "i", array($cypher), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					$testcount = mysqli_prepared_num_rows($test_query);
					
					$sql="
						# get unit info
						Select
							dw_unit.unitID
						From
							dw_unit
						Where
							dw_unit.unitCypher = ? And
							dw_unit.unitActive = 1
					";
					if(!$unit_query = mysqli_prepared_query($link, $sql, "i", array($cypher), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					$unitcount = mysqli_prepared_num_rows($unit_query);

					if($testcount == 0 || $unitcount == 0) $glyphicon = 'glyphicon-remove';
					else $glyphicon = 'glyphicon-ok';

					if(isset($_POST['cypher'])){
						echo "
							<div class='form-group'>
								<div class='text-center'>
									<a href='results.php?r=" . clean($_POST['cypher']) . "'>
										<span class='glyphicon ".$glyphicon."' aria-hidden='true'></span>&nbsp;
										" . $testcount . " tests from " . $unitcount . " samples found
									</a>
								</div>
								<br>
							</div>
						";
					}

				?>
				<div class="form-group" style='width:770px;max-width:770px;margin-left:200px;'><!-- blurb3 -->
					<textarea class='textarea' name='blurb3'><?php if(isset($_POST['blurb3'])) echo $_POST['blurb3']; ?></textarea>
				</div>
				<div class="form-group" style='width:770px;max-width:770px;margin-left:200px;'><!-- blurb -->
          <?php
          //get blurb
          $sql='
            SELECT
              dw_spec.specBlurb
            FROM
              dw_cypher LEFT JOIN
              dw_spec ON dw_spec.specID = dw_cypher.cypherSpec
            WHERE
              dw_cypher.cypherID = ?
          ';
          if(!$blurb_query = mysqli_prepared_query($link, $sql, "i", array($cypher), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
          $specBlurb = $blurb_query[0]['specBlurb'];
          ?>
					<textarea class='textarea' name='blurb'  title="blurb"><?php
            if(!empty($specBlurb)) echo $specBlurb;
            else echo $_SESSION['blurb'];
          ?></textarea>
				</div>
				<div class="form-group"><!-- signature -->
					<label class="col-sm-2 control-label">Signature</label>
					<div class="col-sm-10">
						<label class="radio-inline"><input type="radio" name="sig" value="0" checked > <?php echo $_SESSION['userFirst'].' '.$_SESSION['userLast']; ?> (no signature)</label>
						<?php
							if($_SESSION['coa_default_user']!=$_SESSION['userID']){
								$sql="
									# get default users details
									Select
										dw_user.userFirst,
										dw_user.userLast,
										dw_user.userTitle,
										dw_user.userCOA
									From
										dw_user
									Where
										dw_user.userID = ?
								";
								if(!$qryduser = mysqli_prepared_query($link, $sql, "i", array($_SESSION['coa_default_user']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
								$userdarray = $qryduser[0];
								echo "<label class='radio-inline'><input type='radio' name='sig' value='".$_SESSION['coa_default_user']."'> ".$userdarray['userFirst']." ".$userdarray['userLast']." (no signature)</label>";
								if(($_SESSION['userCOA']=="1" || $_SESSION['userCOA']==1) && isset($_POST['cypher'])){
									echo "<label class='radio-inline'><input type='radio' name='sig' value='".$_SESSION['userID']."'> ".$_SESSION['userFirst']." ".$_SESSION['userLast']." (with signature)</label>";
								}
							}else{
								if(!file_exists('images/sigs/'.$_SESSION['userID'].'.jpg')) echo "No signature file!";
								else{
									echo "<label class='radio-inline'><input type='radio' name='sig' value='".$_SESSION['userID']."'>&nbsp;".$_SESSION['userFirst']." ".$_SESSION['userLast']." (with signature)</label>
									<img src='images/sigs/".$_SESSION['userID'].".jpg' alt='signature' />
									<input name='signature' type='hidden' value='".$_SESSION['userID']."' >";
								}
							}
						?>
					</div>
				</div>
          <?php if($_SESSION['userSite']!=5){ ?>
          <div class="form-group"><!-- # samples -->
            <label class="col-sm-2 control-label" for="show_samples">Show number of samples</label>
            <div class="col-sm-10">
              <input type="checkbox" name="show_samples" id="show_samples" value="1" data-toggle="toggle" data-on="Yes" data-off="No" <?php if(!empty($_POST['show_samples']) && $_POST['show_samples']==1) echo 'checked'; ?> >
            </div>
          </div>
          <?php } ?>
          <div class="form-group"><!-- method -->
            <label class="col-sm-2 control-label" for="show_method">Show method</label>
            <div class="col-sm-10">
              <input type="checkbox" name="show_method" id="show_method" value="1" data-toggle="toggle" data-on="Yes" data-off="No" <?php if((!empty($_POST['show_method']) && $_POST['show_method']==1) || $_SESSION['userSite']==5) echo 'checked'; ?> >
            </div>
          </div>
				<div class="text-center"><!-- generate -->
					
					<?php
						if(isset($_POST['cypher'])){

							$sql="# get spec of current cypher
								SELECT cypherSpec
								FROM dw_cypher
								WHERE cypherID = ?";
							if(!$qryspec = mysqli_prepared_query($link, $sql, 'i', array(clean($_POST['cypher'])))) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
							$spec = $qryspec[0]['cypherSpec'];

							if($testcount>0){
								if($_SESSION['userCOA']=="1"){ //if user can sign COA's...
									$sql="
										Select
											dw_coa.coaID
										From
											dw_coa Left Join
											dw_cypher
												On dw_cypher.cypherSpec = dw_coa.coaSpec
										Where
											dw_cypher.cypherID = ?";
									if(!$qrycoa = mysqli_prepared_query($link, $sql, "i", array(clean($_POST['cypher'])), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
									$num = mysqli_prepared_num_rows($qrycoa);

									if($debug) echo "num:".$num." testcount:".$testcount."<br/>";

									if($testcount < $num && $_SESSION['coagen_locked']==1){ //29/8/12 changed from if($testcount!=$num && $dw_settings['coagen_locked']==1){

										$sql='# get tests
											Select Distinct
												dw_test.testID,
												dw_test.testTextCOA
											From
												(dw_group Right Join
												(((dw_spec Right Join
												dw_cypher On dw_spec.specID = dw_cypher.cypherSpec) Right Join
												dw_unit On dw_cypher.cypherID = dw_unit.unitCypher) Right Join
												(dw_test Right Join
												dw_result On dw_test.testID = dw_result.resultTest) On dw_unit.unitID = dw_result.resultUnit) On
												dw_group.groupID = dw_test.testGroup) Right Join
												dw_coa On dw_test.testID = dw_coa.coaTest And
												dw_spec.specID = dw_coa.coaSpec
											Where
												dw_unit.unitActive = 1 And
												dw_test.testActive = 1 And
												dw_cypher.cypherID = ?
											Order By
												dw_group.groupOrder,
												dw_test.testOrder';
										if(!$qry1 = mysqli_prepared_query($link, $sql, 'i', array(clean($_POST['cypher'])))) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
										$rt = array();
										foreach($qry1 as $array1){
											$rt[] = $array1['testID'];
										}

										$sql="
											SELECT DISTINCT dw_test.testID, dw_test.testTextCOA
											FROM dw_group RIGHT JOIN (dw_test RIGHT JOIN dw_coa ON dw_test.testID = dw_coa.coaTest) ON dw_group.groupID = dw_test.testGroup
											WHERE dw_coa.coaSpec=? AND testActive=1
											ORDER BY dw_group.groupOrder, dw_test.testOrder
										";
										if(!$qry2=mysqli_prepared_query($link, $sql, 'i', array(".$spec."))) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
										$tests = array();
										foreach($qry2 as $array2){
											$found = 0;
											foreach($rt as $value){
												
												$testname = $value;
												if($value==$array2['testID']){
													if($debug) echo $value." is the same as ".$array2['testID']."<br>\n";
													$found = 1;
													break;
												}else{
													//if($debug) echo $value." is not the same as ".$array2['testID']."<br/>\n";
													$found = 0;
												}
												
											}
											if($debug) echo "Test (".$array2['testID'].")".$array2['testTextCOA']." found=".$found."<br/>\n";
											if($found==0) $tests[] = $array2['testID'];
										}
										if($debug) {
											echo "tests:\n";
											print_r($tests);
											echo "\nnum:".$num." testcount:".$testcount."<br/>\n";
										}

										$missingtest = array();
										if(count($tests)>0){
											foreach($tests as $currenttest){
												$sql="
													SELECT dw_test.testTextCOA
													FROM dw_test
													WHERE dw_test.testID = ?";
												if(!$qry3 = mysqli_prepared_query($link, $sql, 'i', array(clean($currenttest)))) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
												$missingtest[] = $qry3[0]['testTextCOA'];
											}
										}else{
											reporterror('No tests in test array', $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
										}
										
										echo "<!-- num:".$num." testcount:".$testcount." -->\n";
										
										if($num-$testcount==1){
											echo "<span class='info-center'><span class='glyphicon glyphicon-remove' aria-hidden='true'></span>&nbsp;Cannot create the COA because there are<br/>no '".$missingtest[0]."' results yet</span><br/>";
										}else{
											echo "<br><span class='info-center'><strong>There are ".$testcount." test with results found. You need ".$num." tests to create the COA.</strong><br/>Missing tests: ";
											//include "../fade.php";
											$count=0;
											$testnames = "";
											foreach($missingtest as $testname){
												$testnames .= $testname.", ";
												/*
												$count++;
												if($count>6){
													$count=1;
													echo "<br/>";
												}
												*/
											}
											echo substr($testnames,0,-2)."</span><br/>"; //backspace
										}
									}else{
										echo "<button type='submit' class='btn btn-default btn-primary' name='generate' id='generate'>Generate</button>";
									}
								}else{
									echo "<span class='info-center'><span class='glyphicon glyphicon-remove' aria-hidden='true'></span>&nbsp;You do not have the correct access level to generate COA's!</span>";
								}
							}else{
								echo "<span class='info-center'><span class='glyphicon glyphicon-remove' aria-hidden='true'></span>&nbsp;There are no results for this cypher!&nbsp;";
								if(isset($spec) && $spec!=null && $spec!=""){
									echo "<a href='coa.php?p=".$spec."&btnView=refresh'>";
								}else{
									echo "<a href='coa.php'>";
								}
								echo "Click here to add some tests.</a></span>";
							}
						}
					?>
				</div>
			</form>
		</div>
	</div>
	
	<script src="js/coagen.js?v=2.1">/* Include JS for this file */</script>
	<script src="js/tinymce/tinymce.min.js?v=2.1">/* For editable textareas */</script>
	<script>
		tinymce.init({
			selector: ".textarea",
			plugins: [
				"advlist anchor autolink charmap contextmenu hr insertdatetime lists paste searchreplace"
			],
			toolbar: false, menubar: false,
			insertdatetime_formats: ["%H:%M", "%I:%M %p", "%d %b", "%d/%m/%Y"],
			statusbar: false, resize: false,
			fontsize_formats: "8pt 9pt 10pt 12pt 14pt 18pt 24pt 36pt",
			relative_urls: false
		});
		$('[data-toggle="tooltip"]').tooltip();
		<?php
			if(isset($a1) && $a1!="") echo "                 showdiv('divq2');";
			if(isset($a2) && $a2!="") echo "showdiv('divq2');showdiv('divq3');";
			if(isset($a3) && $a3!="") echo "showdiv('divq3');showdiv('divq4');";
			if(isset($a4) && $a4!="") echo "showdiv('divq4');showdiv('divq5');";
		?>
	</script>
<?php require "inc/footer.php"; ?>