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

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

// Small Label

include('../barcode/php-barcode.php');
require('../barcode/fpdf.php');
// require(dirname(__FILE__) . '/../../vimsconfig/phpConfig.php');

class PDF extends FPDF
{
// Page header
	function Header()
	{
// Logo
		$this->Image('../../../images/vel_logo_large.jpg',10,6,50);
// Arial bold 15
		$this->SetFont('Arial','B',15);
// Move to the right
		$this->Cell(100);
// Title
		$this->Cell(50,10,'Pallet',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',8);
// date / time
		$date = date('d/m/Y h:i:s a', time());
// Page number
		$this->Cell(0,10,'Page '.$this->PageNo().'   Date '.$date,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);
    }	
	
// Simple table
	function BasicTable($header, $data)
	{
// Initial Line
		$this->ln(30);
// Column widths
		$w = array(40,0);
// Header
		$i = 0;
		foreach($header as $col)
		{
			$this->Cell($w[$i],7,$col,1);
			$i++;
		}
		$this->Ln();
// Data
		foreach($data as $row)
		{
			$i = 0;
			$this->Cell($w[1],6,$row['FLD01'],1);
/*			
			foreach($row as $col)
			{
				if (($i==1))
					$this->Cell($w[$i],6,$col,1,0,'R');
				else
					$this->Cell($w[$i],6,$col,1);
				$i++;
			}
*/
			$this->Ln();
		}
	}
	
// Barcode table
	function BarcodeTablePdf($header, $data)
	{
// 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   = 10;   // 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
// Headings
		$this->AddPage();
		$this->Text(10,50,"Report Date: ".$date);
		
		$this->SetFont('Arial','',$fontSize);
		$this->SetTextColor(0, 0, 0);
// Initial Line
		$this->ln(30);
// Column widths
		$w = array(40, 0);
// Header
		$i = 0;
		foreach($header as $col)
		{
			$this->Cell($w[$i],7,$col,0);
			$i++;
		}
		$this->Ln();
// Data
		$l = 0;
		foreach($data as $row)
		{
			$x = 30;
			foreach($row as $key=>$col)
			{
				$barCol = $col;
				$barcode = Barcode::fpdf($this, $black, $x, $y, $angle, $type,$barCol, $width, $height);
				$this->TextWithRotation($x, $y+8, $col, $angle);
				$i++;
				$x = $x+50;
			}
			$y = $y+20;
			$this->Ln();
			$l = $l+1;
			if ($l > 9)
			{
				$this->AddPage();
				$this->Text(10,50,"Report Date: ".$date);
// Header
				$i = 0;
				$this->ln(30);
				foreach($header as $col)
				{
					$this->Cell($w[$i],7,$col,0);
					$i++;
				}
				$this->Ln();
				$l = 0;
				$y = 70;
			}
		}
	}	
}

// Load data
function LoadData($mHost, $mUser, $mPwd, $mDbName, $mPrefix, $mTransactionTypeId, $mNumber)
{
// 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());
	$mFirstTagId = 0;
// Add New Pallet Tags
	for ($i = 0;$i<$mNumber;$i++)
	{
		$mDataQuery = "INSERT INTO tag (id,version,auto_generated,current_location_id,date_created,document_header_id,last_updated,last_updated_by,tag_reference,validated,active,picked) VALUES(DEFAULT,0,0,null,now(),null,now(),'".$mCurrentUser."','PLT000000',1,1,0)";
		if (!mysqli_query($mConnection,$mDataQuery))
			return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
		$mTagId=mysqli_insert_id($mConnection);
		$mTagReference = "000000".round($mTagId);
		if (substr($mTransactionTypeId,0,2) == "PB")
			$mTagReference = "PCK".substr($mTagReference,-6);
		elseIf (substr($mTransactionTypeId,0,2) == "RB")
			$mTagReference = "RCV".substr($mTagReference,-6);
		elseIf (substr($mTransactionTypeId,0,3) == "JRB")
			$mTagReference = "RXD".substr($mTagReference,-6);
		elseIf (substr($mTransactionTypeId,0,3) == "REP")
			$mTagReference = "REP".substr($mTagReference,-6);
		else
			$mTagReference = "PLT".substr($mTagReference,-6);
		$mDataQuery = "UPDATE tag SET tag_reference='".$mTagReference."' WHERE id=".$mTagId." LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			return "FAIL-5".mysqli_error($mConnection).$mDataQuery;
		if ($mFirstTagId == 0)
			$mFirstTagId = $mTagId;
	}	
	$mDataQuery = "SELECT CONCAT('".$mPrefix."',tag_reference) AS FLD01 FROM tag WHERE id >=".$mFirstTagId." LIMIT 100";
// mysql query construct
	if (!mysqli_query($mConnection,$mDataQuery))
		exit("FAIL-".mysqli_error($mConnection).":".$mdataQuery);
	
	$mData = mysqli_query($mConnection,$mDataQuery);
	$i = 0;
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
		$data[] =($mRow);
		$i++;
	}
	mysqli_close($mConnection);
	
//	print_r("Rows:".$i.":".$mDataQuery);

	return $data;
}

// Pallet label
function pltLabel($mLabel, $data, $mPrinter)
{
// Load Label Template
	$mPrintData = __DIR__."/".$mLabel;

// Label Template
$mLabelFmt = 
"LABEL1
1aA305000400035FLD01
1911S0000230035P015P018FLD01
LABEL2
1aA305000400445FLD01
1911S0000230445P015P018FLD01";
				
//	$mFh = fopen($mPrintData, 'r');
//	$mLabelFmt = fread($mFh, filesize($mPrintData));
//	print_r("FAIL-Label:".$mPrintData."-".$mLabelFmt."-".filesize($mPrintData));
//	fclose($mFh);
	
// Add NewLine Characters
	$lines=explode(PHP_EOL,$mLabelFmt);
	$mContent1 = "";
	$mContent2 = "";
	$c = -1;
	foreach($lines as $line)
	{
		if (substr($line,0,5) != "LABEL")
			if ($c == 0)
				$mContent1 .= $line."\n";
			else
				$mContent2 .= $line."\n";
//			$mContent[0] .=$line."\n";
		else
		{
			$c++;
			if ($c > 1)
				$c = 0;
		}
	}
//	print_r("FAIL-Layout:".$mContent1."-".$mContent2);
// Label Data
	$mLabelContent1 = $mContent1;
	$mLabelContent2 = $mContent2;
	$c = 0;
	foreach($data as $row)
	{
		$i = 0;
		foreach($row as $k=>$v)
		{
// Replace Template placeholder with Value
			if ($c == 0)
				$mLabelContent1 = str_replace($k,$v,$mLabelContent1);
			else
				$mLabelContent2 = str_replace($k,$v,$mLabelContent2);
			$i++;
		}
		$c++;
		if ($c > 1)
		{
// Send Label to Printer

//			print_r("Printer:".$mPrinter);
			$fp = fsockopen($mPrinter, 9100, $errno, $errstr, 30);
			fputs ($fp,"\x02L\n");
			fputs ($fp,"H08\n");
			fputs ($fp,"D11\n");
			fprintf($fp,$mLabelContent1.$mLabelContent2);
			fputs ($fp,"E\n"); 

//			print_r("Data1:".$mLabelContent1);
//			print_r("Data2:".$mLabelContent2);
			$mLabelContent1 = $mContent1;
			$mLabelContent2 = $mContent2;
			$c = 0;
		}
	}
	if ($c == 1)
	{
		$fp = fsockopen($mPrinter, 9100, $errno, $errstr, 30);
		fputs ($fp,"\x02L\n");
		fputs ($fp,"H08\n");
		fputs ($fp,"D11\n");
		fprintf($fp,$mLabelContent1);
		fputs ($fp,"E\n"); 

//		print_r("Data3:".$mLabelContent1);
	}
	fclose($fp);
}

// Return Default mySql Connection
function defaultDbConnection()
{
// get default System Settings from xml file	
	$mSystem = "DEFAULT";
// Get System Definition XML from URL
	$mData = file_get_contents("../../vimsconfig/systemsettings.xml");
// Parse XML to XML Object Array
	$xml = simplexml_load_string($mData, 'SimpleXMLElement', LIBXML_NOCDATA);
// Split-out System Definitions from XML 'fields' Nodes
	$i = 0;

	for ($i = 0; $i <= 150; $i++) 
	{			
		$mSystemId = "";
		$mPath = "";
		$mDbHost = "";
		$mDbUser = "";
		$mDbPwd = "";
		$mDbase = "";
		$mMqServer = "";
		$mCompany = "";
		if (("".$xml->systems->system[$i]->systemid."" == "") || ("".$xml->systems->system[$i]->systemid."" == false) || ("".$xml->systems->system[$i]->systemid."" == false))
			break;
		
		$mSystemId = "".$xml->systems->system[$i]->systemid."";
		if (($mSystemId == "") || ($mSystemId == false))
			break;
		
// Store System Settings from "trandef/systemsettings.xml"		
		if (strToUpper($mSystem) == strToUpper($mSystemId))
		{
			$mPath = "".$xml->systems->system[$i]->path."";
			$mDbHost = "".$xml->systems->system[$i]->dbhost."";
			$mDbUser = "".$xml->systems->system[$i]->dbuser."";
			$mDbPwd = "".$xml->systems->system[$i]->dbpwd."";
			$mDbase = "".$xml->systems->system[$i]->dbase."";
			break;
		}
		if (($mSystemId == "") || ($mSystemId == false))
			break;
	}
	$mDbDefaults = array();
	$mDbDefaults[0] = $mDbHost;
	$mDbDefaults[1] = $mDbUser;
	$mDbDefaults[2] = $mDbPwd;
	$mDbDefaults[3] = $mDbase;
	$mDbDefaults[4] = $mPath;
	return $mDbDefaults;
}

// Print Labels
function labelPrint($mPrefix,$mNumber,$mPrinter,$mLabel,$mHost, $mUser, $mPwd, $mDbName, $mOutput="n")
{
// date / time
	$date = date('d/m/Y h:i:s a', time());
	
	if (($mPrinter == null) || ($mPrinter == "") || (!$mPrinter))
		$mPrinter = "172.16.1.42";

	if (($mLabel == null) || ($mLabel == "") || (!$mLabel))
		$mLabel = "plt.txt";

	if (($mPrefix == null) || ($mPrefix == "") || (!$mPrefix))
		$mPrefix = "P";

//	if (($mType == null) || ($mType == "") || (!$mType))
		$mType = "PLT";

	if (($mNumber == null) || ($mNumber == "") || (!$mNumber) || ($mNumber > 100))
		$mNumber = 100;
	
//	return "FAIL-TEST1-".$mPrefix."-".$mPrinter."-".$mNumber."-".$mLabel;
	
	$data = LoadData($mHost, $mUser, $mPwd, $mDbName, $mPrefix, $mType, $mNumber);
	if ($mPrinter)
		pltLabel($mLabel, $data, $mPrinter);

	$pdf = new PDF();
// Column headings
	$header = "Pallet";
	$pdf->SetFont('Arial','',12);

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

	if ($mOutput == "")
		$pdf->Output();
	elseif($mOutput == "f")
	{
		$mPdf = "../../../vimsreports/pltlabel".$mCurrentUser.".pdf";
		$pdf->Output($mPdf,$mOutput);
	}
	else
	{
		$mPdf = "../../../vimsreports_arcv/pltlabel".$mCurrentUser.".pdf";
		$pdf->Output($mPdf,'f');
	}
	return "OK  -pltLabelPdf";
}

/*
// Data loading
// Get Input Parameters from POST or GET
if ((!empty($_POST)) || (!empty($_GET)))
{
//	print_r("FAIL-TEST1");
	if (!empty($_POST))
	{
		print_r("FAIL-TEST1");
		$mFilter = "";
		foreach($_POST as $k1=>$v1)
		{
//			print_r("TEST".$k1.":".$v1);
			if ($mFilter != "")
				$mFilter .= "&";
			$mFilter .= $k1."=".$v1;
		}
	}
	elseif (!empty($_GET))
	{
		$mFilter = $_SERVER['QUERY_STRING'];
		print_r("FAIL-TEST2-").$mFilter;
	}
	$mFilter = str_replace("=",":",$mFilter);
	$mFilter = str_replace("&",",",$mFilter);

// Explode Input String Into Array - Separated by ,
	$mParms = explode(",",$mFilter);

	$mConnect   		= $mParms['connection'];
	$mUser				= $mParms['user'];
	$mPwd				= $mParms['pword'];
	$mHost              = $mParms['host'];
	$mDbName			= $mParms['dbase'];
	$mCurrentUser       = $mParms['currentuser'];
	$mPrefix 			= $mParms['prefix'];
	$mType				= $mParms['type'];
	$mNumber			= $mParms['number'];
	$mLabel      		= $mParms['label'];
	$mOutput			= $mParms['output'];
	$mPrinter			= $mParms['printer'];

	return labelPrint($mPrefix,$mNumber,$mPrinter,$mLabel,$mHost, $mUser, $mPwd, $mDbName, $mOutput);	
}
*/

?>