<?php
header('Cache-Control: no-cache, no-store, must-revalidate');   
header('Expires: 0');

// error_reporting(E_ALL);
// ini_set('display_errors', 1);

// Pick Sheet

function test($mParm)
{
	$root = $_SERVER['DOCUMENT_ROOT'];
	$dir = (dirname(__FILE__));
	return "OK  -TEST2 -".$root."-".$dir;
}

$root = $_SERVER['DOCUMENT_ROOT'];
include_once($root.'/rdtrrmc/rdtvims/barcode/php-barcode.php');
include_once($root.'/rdtrrmc/rdtvims/barcode/fpdf.php');

// include('../barcode/php-barcode.php');
// require('../barcode/fpdf.php');

// require(dirname(__FILE__) . '/../../vimsconfig/phpConfig.php');

class PDF extends FPDF
{
// Page header
	function Header()
	{
// root dir
		$root = $_SERVER['DOCUMENT_ROOT'];
// Logo
//		$this->Image($root.'/images/vel_logo_large.jpg',10,6,50);
		$this->Image($root.'/images/rrmc_logo.jpg',10,6,10);
// Arial bold 15
		$this->SetFont('Arial','B',15);
// Move to the right
		$this->Cell(100);
// Title
		$this->Cell(50,10,'Picking Sheet',0,0,'C');
// Line break
		$this->Ln(20);
	}

// Page footer
	function Footer()
	{
// Position at 1.5 cm from bottom
		$this->SetY(-15);
// Arial italic 8
		$this->SetFont('Arial','I',10);
// date / time
		$date = date('d/m/Y h:i:s a', time());
// Page number
		$this->Cell(0,10,'Page '.$this->PageNo().' of {nb}      Date '.$date,0,0,'C');
//		$this->Cell(0,10,'Page '.$this->PageNo().' of {nb}',0,0,'C');
	}
	
	function TextWithRotation($x, $y, $txt, $txt_angle, $font_angle=0)
    {
        $font_angle+=90+$txt_angle;
        $txt_angle*=M_PI/180;
        $font_angle*=M_PI/180;
    
        $txt_dx=cos($txt_angle);
        $txt_dy=sin($txt_angle);
        $font_dx=cos($font_angle);
        $font_dy=sin($font_angle);
    
        $s=sprintf('BT %.2F %.2F %.2F %.2F %.2F %.2F Tm (%s) Tj ET',$txt_dx,$txt_dy,$font_dx,$font_dy,$x*$this->k,($this->h-$y)*$this->k,$this->_escape($txt));
        if ($this->ColorFlag)
            $s='q '.$this->TextColor.' '.$s.' Q';
        $this->_out($s);
    }	

// Barcode table
	function BarcodeTablePdf($header, $data, $mCustomerRef)
	{
// date / time
		$date = date('d/m/Y h:i:s a', time());
// barcode settings
		$fontSize = 8;
		$marge    = 5;   // between barcode and hri in pixel
		$x        = 30;  // barcode center
		$y        = 70;  // barcode center
		$height   = 12;   // barcode height in 1D ; module size in 2D
		$width    = 0.25;    // barcode width in 1D ; not use in 2D
		$angle    = 0;   // rotation in degrees  
		$code     = 'VANTEC'; // barcode text;)
		$type     = 'code39';
		$black    = '000000'; // color in hex
		
// Sheet 1
		
// Headings
		$this->AddPage();
		$this->Text(10,30,"Report Date: ".$date);
		
		$this->SetFont('Arial','',$fontSize);
		$this->SetTextColor(0, 0, 0);
// Initial Line
		$this->ln(30);
// counts
		$y = 35;
		$x = 30;
		$this->SetFont('Arial','',15);
		$this->Text($x,$y,"No. Of Items: ".$data[0]['no_items']);
		$this->Text($x,$y+5,"Total Qty:    ".(int)$data[0]['total_qty']);
// Customer Ref.
		$x = 100;
		$this->SetFont('Arial','',15);
		$this->Text($x,$y,"TO Number");
		$this->Text($x, $y+5, $mCustomerRef);
		$barcode = Barcode::fpdf($this, $black, $x+60, $y, $angle, $type,$mCustomerRef, $width, $height);
		$this->Text($x,$y+15,"Rolling Number");
		$this->Text($x+40, $y+15, $data[0]['rolling_no']);
// benum
		$x = 30;
		$y = $y+40;
		$this->SetFont('Arial','B',65);
		$this->TextWithRotation($x, $y, $data[0]['benum'], $angle);
// dgit / Expected Delivery Date
		$x = 55;
		$y = $y+15;
		$this->SetFont('Arial','',20);
		$dgit = $data[0] ['expected_delivery'];
		$dgit = substr($dgit,8,2)."/".substr($dgit,5,2)."/".substr($dgit,0,4)." ".substr($dgit,11,5);
		$this->Text($x,$y,"DGIT: ".$dgit);
// Supply Type
		$x = 30;
		$y = $y+10;
		$this->SetFont('Arial','',15);
		$dgit = $data[0] ['benum'];
		$dgit = substr($dgit,3);
		if ($data[0] ['pick_type'] == "XD")
		{
			$this->Text($x,$y,"Supply Type: Cross Dock");
		}
		elseif ($data[0] ['pick_type'] == "RP")
		{
			$this->Text($x,$y,"Supply Type: Resequence");
		}		
		$this->Text($x+80,$y,"Assy Station: ".$dgit);
// Column widths
		$w = array(40, 0);
// Header
		$x = 60;
		$y = $y+10;
		$this->SetFont('Arial','',20);
		$this->Text($x,$y,"Vehicle Order Numbers");
		$this->Ln();
// Data
		$l = 0;
		$this->SetFont('Arial','',15);
		$y = $y+10;
		$prev = "";
		foreach($data as $row)
		{
			if ($row['vehicle_reference'] != $prev)
			{
				$prev = $row['vehicle_reference'];
				$c = 0;
				$x = 30;
				$barCol = $row['vehicle_reference'];
				$this->Text($x, $y, $row['vehicle_reference']);
				if (barcol != "")
					$barcode = Barcode::fpdf($this, $black, $x+120, $y, $angle, $type,$barCol, $width, $height);
				$c++;
				$i++;
				$y = $y+15;
				$this->Ln();
				$l = $l+1;
				if ($l > 9)
				{
					$this->AddPage();
					$this->Text(10,50,"Report Date: ".$date);
					$y = 70;
					$l = 0;
				}
			}
		}
		
// Sheet 2

// Page Break
		$prvTray = $data[0]['tray'];
		
/*
// Headings
		$this->AddPage();
		$this->Text(10,30,"Report Date: ".$date);
		
		$this->SetFont('Arial','',$fontSize);
		$this->SetTextColor(0, 0, 0);
// Initial Line
		$this->ln(30);
// counts
		$y = 35;
		$x = 30;
		$this->SetFont('Arial','',10);
		$this->Text($x,$y,"No. Of Items: ".$data[0]['no_items']);
		$this->Text($x,$y+5,"Total Qty:    ".(float)$data[0]['total_qty']);
// Customer Ref.
		$x = 100;
		$this->SetFont('Arial','',10);
		$this->Text($x,$y,"TO Num");
		$this->Text($x, $y+5, $mCustomerRef);
		$barcode = Barcode::fpdf($this, $black, $x+50, $y, $angle, $type,$mCustomerRef, $width, $height);
// benum
		$x = 60;
		$y = $y+20;
		$this->SetFont('Arial','',30);
		$this->Text($x, $y, $data[0]['benum']);
// dgit / Expected Delivery Date
		$x = 55;
		$y = $y+10;
		$this->SetFont('Arial','',20);
		$dgit = $data[0] ['expected_delivery'];
		$dgit = substr($dgit,8,2)."/".substr($dgit,5,2)."/".substr($dgit,0,4)." ".substr($dgit,11,5);
		$this->Text($x,$y,"DGIT: ".$dgit);
// Supply Type
		$x = 30;
		$y = $y+10;
		$this->SetFont('Arial','',15);
		$dgit = $data[0] ['benum'];
		$dgit = substr($dgit,3);
		if ($data[0] ['pick_type'] == "XD")
		{
			$this->Text(10,$y,"Supply Type: Cross Dock");
		}
		$this->Text($x+80,$y,"Assy Station: ".$dgit);
// Warehouse
		$this->Text(10,$y+5,"Warehouse: ".$data[0]['warehouse']);
// Tray
		$this->Text(110,$y+5,"Tray:  ".$prvTray);
// Column widths
		$w = array(50,80,15,40,5);
// Header
		$header = array('Part Number','Description','Qty.','Sequence','X');
		$i = 0;
		$this->ln(25);
		foreach($header as $col)
		{
			$this->Cell($w[$i],7,$col,1);
			$i++;
		}
		$this->Ln();
		$x = 60;
// Initial Line
//		$this->ln(30);
*/

// Data
		$l = 10;
		$this->SetFont('Arial','',12);
		$y = 100;
		foreach($data as $row)
		{
// Test for Tray Change
			if ($row['tray'] != $prvTray)
			{
				$l = 10;
				$prvTray = $row['tray'];
			}
			if ($l > 5)
			{
// Headings
				$this->AddPage();
				$this->Text(10,30,"Report Date: ".$date);
		
				$this->SetFont('Arial','',$fontSize);
				$this->SetTextColor(0, 0, 0);
// Initial Line
				$this->ln(30);
// counts
				$y = 35;
				$x = 30;
				$this->SetFont('Arial','',10);
				$this->Text($x,$y,"No. Of Items: ".$data[0]['no_items']);
				$this->Text($x,$y+5,"Total Qty:    ".(float)$data[0]['total_qty']);
// Customer Ref.
				$x = 100;
				$this->SetFont('Arial','',10);
				$this->Text($x,$y,"TO Number");
				$this->Text($x, $y+5, $mCustomerRef);
				$barcode = Barcode::fpdf($this, $black, $x+50, $y, $angle, $type,$mCustomerRef, $width, $height);
// benum
				$x = 60;
				$y = $y+20;
				$this->SetFont('Arial','',30);
				$this->Text($x, $y, $data[0]['benum']);
// dgit / Expected Delivery Date
				$x = 55;
				$y = $y+10;
				$this->SetFont('Arial','',20);
				$dgit = $data[0] ['expected_delivery'];
				$dgit = substr($dgit,8,2)."/".substr($dgit,5,2)."/".substr($dgit,0,4)." ".substr($dgit,11,5);
				$this->Text($x,$y,"DGIT: ".$dgit);
// Supply Type
				$this->SetFont('Arial','',15);
				$x = 30;				
				$y = $y+10;
				$this->Text(10,$y,"Vehicle Order: ".$row['vehicle_reference']);
// Supply Type				
				$y = $y+5;				
				$dgit = $data[0] ['benum'];
				$dgit = substr($dgit,3);
				if ($data[0] ['pick_type'] == "XD")
				{
					$this->Text(10,$y,"Supply Type: Cross Dock");
				}
				$this->Text($x+80,$y,"Assy Station: ".$dgit);
// Warehouse
				$this->Text(10,$y+5,"Warehouse: ".$data[0]['warehouse']);
// Tray
				$this->Text(110,$y+5,"Tray:  ".$prvTray);
// Column widths
				$w = array(50,80,15,40,5);
// Header
				$header = array('Part Number','Description','Qty.','Sequence','X');
				$i = 0;
				$this->ln(35);
				foreach($header as $col)
				{
					$this->Cell($w[$i],7,$col,1);
					$i++;
				}
				$this->Ln();
				$x = 60;
				$l = 0;
			
				$y = 110;
				$this->SetFont('Arial','',12);
			}								
			
			$c = 0;
			$x = 30;

			$this->Cell($w[0],25,'',1,0,'L');
			$this->Cell($w[1],25,$row['part_description'],1);
			$this->Cell($w[2],25,(float)$row['qty_expected'],1,0,'R');
			$this->Cell($w[3],25,$row['sequence_no'],1,0,'L');
			$this->Cell($w[4],25,'',1,0,'L');
//			$this->Text($x, $y, $col);
			$barCol = $row['part_number'];
			$this->Text(20,$y,$row['part_number']);
			$barcode = Barcode::fpdf($this, $black, 33, $y+8, $angle, $type,$barCol, 0.25, 12);

			$c++;
				
			$i++;
			$y = $y+25;
			$this->Ln();
			$l = $l+1;

/*			
// Test for Tray Change
			if ($row['tray'] != $prvTray)
			{
				$l = 10;
				$prvTray = $row['tray'];
			}
			if ($l > 6)
			{
// Headings
				$this->AddPage();
				$this->Text(10,30,"Report Date: ".$date);
		
				$this->SetFont('Arial','',$fontSize);
				$this->SetTextColor(0, 0, 0);
// Initial Line
				$this->ln(30);
// counts
				$y = 35;
				$x = 30;
				$this->SetFont('Arial','',10);
				$this->Text($x,$y,"No. Of Items: ".$data[0]['no_items']);
				$this->Text($x,$y+5,"Total Qty:    ".(float)$data[0]['total_qty']);
// Customer Ref.
				$x = 100;
				$this->SetFont('Arial','',10);
				$this->Text($x,$y,"TO Num");
				$this->Text($x, $y+5, $mCustomerRef);
				$barcode = Barcode::fpdf($this, $black, $x+50, $y, $angle, $type,$mCustomerRef, $width, $height);
// benum
				$x = 60;
				$y = $y+20;
				$this->SetFont('Arial','',30);
				$this->Text($x, $y, $data[0]['benum']);
// dgit / Expected Delivery Date
				$x = 55;
				$y = $y+10;
				$this->SetFont('Arial','',20);
				$dgit = $data[0] ['expected_delivery'];
				$dgit = substr($dgit,8,2)."/".substr($dgit,5,2)."/".substr($dgit,0,4)." ".substr($dgit,11,5);
				$this->Text($x,$y,"DGIT: ".$dgit);
// Supply Type
				$x = 30;
				$y = $y+10;
				$this->SetFont('Arial','',15);
				$dgit = $data[0] ['benum'];
				$dgit = substr($dgit,3);
				if ($data[0] ['pick_type'] == "XD")
				{
					$this->Text(10,$y,"Supply Type: Cross Dock");
				}
				$this->Text($x+80,$y,"Assy Station: ".$dgit);
// Warehouse
				$this->Text(10,$y+5,"Warehouse: ".$data[0]['warehouse']);
// Tray
				$this->Text(110,$y+5,"Tray:  ".$prvTray);
// Column widths
				$w = array(50,80,15,40,5);
// Header
				$header = array('Part Number','Description','Qty.','Sequence','X');
				$i = 0;
				$this->ln(25);
				foreach($header as $col)
				{
					$this->Cell($w[$i],7,$col,1);
					$i++;
				}
				$this->Ln();
				$x = 60;
				$l = 0;
			
				$y = 100;
				$this->SetFont('Arial','',12);
			}
*/
		}		
	}	
}

// Load data
function LoadData($mHost, $mUser, $mPwd, $mDbName, $mCustomerRef)
{
// Read file lines
	$data = array();
// mysql connection
	$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
		exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error()."-".$mHost);
		
	$mDataQuery  = "SELECT document_header.id AS id, document_header.document_reference_code AS document_reference, document_header.expected_delivery AS expected_delivery,document_header.benum AS benum, CASE WHEN document_header.lgnum IS null THEN 'LSP' ELSE document_header.lgnum END AS warehouse";
	$mDataQuery .= ",document_header.order_type AS order_type, document_header.pick_type AS pick_type, document_header.tanum AS customer_reference";
	$mDataQuery .= ", document_header.rolling_no AS rolling_no";
	$mDataQuery .= ",document_body.tray AS tray,document_body.sequence_no AS sequence_no";
	$mDataQuery .= ",CASE WHEN substr(document_detail.serial_reference,3,1)='-' THEN document_detail.serial_reference WHEN document_body.wempf IS null THEN '' WHEN document_body.wempf = '' THEN '' ELSE document_body.wempf END AS vehicle_reference, document_detail.qty_expected/part.conversion_factor AS qty_expected";
	$mDataQuery .= ",part.part_number AS part_number, substring(part.part_description,1,28) AS part_description";
	$mDataQuery .= ",0 AS no_items, 0 AS total_qty";
	$mDataQuery .= " FROM document_header";
	$mDataQuery .= " LEFT JOIN document_body ON document_header.id=document_body.document_header_id";
	$mDataQuery .= " LEFT JOIN document_detail ON document_body.id=document_detail.document_body_id";
	$mDataQuery .= " LEFT JOIN part ON document_body.part_id=part.id";
	if (($mCustomerRef != null) && ($mCustomerRef != ""))
		$mDataQuery .= " WHERE document_header.tanum='".$mCustomerRef."'";
	else
		$mDataQuery .= " WHERE (tanum IS NOT null AND tanum <> '') AND ((document_header.printed IS null) OR (document_header.printed = 0))";
	$mDataQuery .= " ORDER BY document_header.tanum, document_header.document_reference";
	if (!$mData = mysqli_query($mConnection,$mDataQuery))
		$data[0] = "FAIL-".mysqli_error($mConnection).":".$mDataQuery;

//	echo "FAIL-".mysqli_error($mConnection).":".$mDataQuery."-".mysqli_num_rows($mData);
	$i = 0;
	$tot = 0;
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
		$data[] =($mRow);
		$i++;
		$tot = $tot+$mRow['qty_expected'];
	}
	mysqli_close($mConnection);
	if ($i > 0)
	{
		$data[0]['no_items']=$i;
		$data[0]['total_qty']=$tot;
	}
	return $data;
}

function flagData($mHost, $mUser, $mPwd, $mDbName, $mId)
{
// mysql connection
	$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
		exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error()."-".$mHost);
	$mDataQuery = "UPDATE document_header SET printed='1' WHERE id=".$mId." LIMIT 1";
	if (!mysqli_query($mConnection,$mDataQuery))
		$data[0] = "FAIL-".mysqli_error($mConnection).":".$mDataQuery;
	mysqli_close($mConnection);
}


// Print Labels
function pickPrint($mCustomerRef, $mPrinter, $mHost, $mUser, $mPwd, $mDbName, $mOutput="f")
{
// root
	$root = $_SERVER['DOCUMENT_ROOT'];
	$currDir = (dirname(__FILE__));
// date / time
	$date = date('d/m/Y h:i:s a', time());
	
//	if (($mPrinter == null) || ($mPrinter == "") || (!$mPrinter))
//		$mPrinter = "172.16.1.42";
	
//	return "FAIL-TEST1-".$mPrefix."-".$mPrinter."-".$mNumber."-".$mLabel;
	
	$data = LoadData($mHost, $mUser, $mPwd, $mDbName, $mCustomerRef);
	
// Build Report-file name
	$reportName = $data[0]['order_type'];
	if ($data[0]['pick_type'] != "")
		$reportName .= $data[0]['pick_type'];
	else
		$reportName .= "  ";
	
	$mCustomnerRef = $data[0]['customer_reference'];
	
	$reportName .= $mCustomerRef;
	
	$pdf = new PDF();
	$pdf->AliasNbPages();
// Column headings
	$header = "Pick Sheet";
	$pdf->SetFont('Arial','',12);

	$pdf->BarcodeTablePdf($header,$data,$mCustomerRef);
	$pdf->Ln(5);

	if ($mOutput == "")
		$pdf->Output();
	elseif($mOutput == "f")
	{
//		$mPdf = $root."/vimsreports/picksheet".$mCurrentUser.".pdf";
		$mPdf = $root."/vimsreports/".$reportName.".pdf";
		$pdf->Output($mPdf,'f');
	}
	else
	{
		$mPdf = $root."/vimsreports_arcv/".$reportName.".pdf";
		$pdf->Output($mPdf,'f');
	}
// Flag Header as printed
	flagData($mHost, $mUser, $mPwd, $mDbName, $data[0]['id']);
	
	return "OK  -picksheetPdf";
//	print_r("FAIL-TEST1");
}

// Scheduled Function
function scheduledTask($mPassParm)
{
// root
	$root = $_SERVER['DOCUMENT_ROOT'];
	$currDir = (dirname(__FILE__));
	
//	return "FAIL-TEST3";
// Replace Chars in Input String to emulate a JSON format instead of GET format
	$mPassParm = str_replace("=",":",$mPassParm);
	$mPassParm = str_replace("&",",",$mPassParm);
// Explode Input String Into Array - Separated by ,
	$mArray1 = explode(",",$mPassParm);
// Create Associative Array by Exploding Array Elements on :
	foreach($mArray1 as $k1=>$v1)
	{
		list($k2, $v2) = explode(":",$mArray1[$k1]);
		if (strtolower($k2) == "customerreference")
			$mCustomerRef = trim($v2);
		elseif ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty") || (strtolower($k2) == "qtyallocated"))
			$mPickQty = floatval($v2);
		elseif ($k2 == "currentUser")
			$mCurrentUser = trim($v2);
		elseif ($k2 == "host")
			$mHost = trim($v2);
		elseif ($k2 == "user")
			$mUser = trim($v2);
		elseif ($k2 == "pwd")
			$mPwd = trim($v2);
		elseif ($k2 == "dbase")
			$mDbName = trim($v2);
		elseif ($k2 == "connect")
			$mConnect = trim($v2);	
		elseif ($k2 == "transactionTypeId")
			$mTransactionTypeId = strtoupper(trim($v2));
	}
	$mPrinter = "";
	$mOutout = "f";
	if ($mCustomerRef != "")
	{
		$mReturn = pickPrint($mCustomerRef, $mPrinter, $mHost, $mUser, $mPwd, $mDbName, "f");
	}
	else
	{
// mysql connection
		$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
			exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error()."-".$mHost);
		$mDataQuery = "SELECT document_header.tanum FROM document_header WHERE (document_header.printed IS NULL) OR (document_header.printed = 0)";
		if (!$mData = mysqli_query($mConnection,$mDataQuery))
			return "FAIL-".mysqli_error($mConnection).":".$mDataQuery;
		while($mRow = mysqli_fetch_assoc($mData)) 
		{
			$mReturn = pickPrint($mRow['tanum'], $mPrinter, $mHost, $mUser, $mPwd, $mDbName, "f");
		}
		mysqli_close($mConnection);
	}
//	if (substr($mReturn,0,2) == "ok")
	try
	{	
		$command = escapeshellcmd($currDir.'/pdfprint.py 2>&1');
//		$output = shell_exec($command);
		exec($command, $output, $status);
	}
	catch (Exception $e)
	{
		return "FAIL-picksheetpdf-".$e;
	}
	return "OK  -picksheetpdf-".$mReturn;
//	return "OK  -".$mHost."-".$mUser."-".$mPwd."-".$mDbName;
}


// Data loading
$mFunction			= $_GET['function'];
$mCustomerRef		= $_GET['customerreference'];
$mConnect   		= $_GET['connection'];
$mUser				= $_GET['user'];
$mPwd				= $_GET['pword'];
$mHost              = $_GET['host'];
$mDbName			= $_GET['dbase'];
$mCurrentUser       = $_GET['currentuser'];
$mLabel      		= $_GET['label'];
$mOutput			= $_GET['output'];
$mPrinter			= $_GET['printer'];

$mFilter = str_replace("|AND|","&",$mFilter);
$mFilter = str_replace("/dbase/",$mDbName,$mFilter);

return pickPrint($mCustomerRef, $mPrinter, $mHost, $mUser, $mPwd, $mDbName, $mOutput);

?>