<?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,'Location',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,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[0],6,$row['LOC12'],1);
			$this->Cell($w[1],6,$row['LOC36'],1);
			$this->Cell($w[2],6,$row['HASH'],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)
		{
			$c = 0;
			$x = 30;
			foreach($row as $key=>$col)
			{
				$barCol = $col;
				if ($c > 1)
					$barcode = Barcode::fpdf($this, $black, $x, $y, $angle, $type,$barCol, $width, $height);
				else
					$this->TextWithRotation($x, $y+8, $col, $angle);
				$c++;
				
				$i++;
				if ($x == 30)
					$x = $x+20;
				else
					$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, $mFromLoc)
{
// 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());
		
	$mDataQuery = "SELECT substr(location.location_code,1,2) AS LOC12, substr(location.location_code,3,8) AS LOC36, location.location_hash AS HASH FROM location WHERE location.location_code = '".$mFromLoc."' OR location.location_hash = '".$mFromLoc."'";
// mysql query construct
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).":".$mDataQuery;

	$mData = mysqli_query($mConnection,$mDataQuery);
//	return "FAIL-".mysqli_error($mConnection).":".$mDataQuery."-".mysqli_num_rows($mData);
	$i = 0;
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
		$data[] =($mRow);
		$i++;
	}
	mysqli_close($mConnection);
	return $data;
}

// Location label
function LocLabel($mLabel, $data, $mPrinter)
{
//	print_r("Label:".$mLabel);
// Load Label Template

// Label Template
 	$mLabelFmt = 
 "LABEL1
 1911S0000100030P067P030LOC12
 1911S0000100080P067P030LOC36
 1aC507000100180HASH
LABEL2
 1911S0000100440P067P030LOC12
 1911S0000100490P067P030LOC36
 1aC507000100590HASH";	

//	$mPrintData = __DIR__."/".$mLabel;
//	$mFh = fopen($mPrintData, 'r');
//	$mLabelFmt = fread($mFh, 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("Layout:".$mContent);
// 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("FAIL-".$mLabelContent1);
//			print_r("FAIL-".$mLabelContent2);

// Restore Print Layout for next labels
			$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);
//	print_r("Data:".$mLabelContent1);
//	print_r("Data:".$mLabelContent2);
}

// 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($mFromLoc, $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 = "location.txt";

	$mNumber = 100;
	
//	return "FAIL-TEST1-".$mPrefix."-".$mPrinter."-".$mNumber."-".$mLabel;
	
	$data = LoadData($mHost, $mUser, $mPwd, $mDbName, $mFromLoc);
	
	if ($mPrinter)
		locLabel($mLabel, $data, $mPrinter);

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

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

	if ($mOutput == "")
		$pdf->Output();
	elseif($mOutput == "f")
	{
		$mPdf = "../../../vimsreports/loclabel".$mCurrentUser.".pdf";
		$pdf->Output($mPdf,$mOutput);
	}
	else
	{
		$mPdf = "../../../vimsreports_arcv/loclabel".$mCurrentUser.".pdf";
		$pdf->Output($mPdf,'f');
	}
	return "OK  -locLabelPdf";
//	print_r("FAIL-TEST1");
}

/*
// Data loading
$mFunction			= $_GET['function'];
$mFromLoc			= $_GET['fromloc'];
$mToLoc				= $_GET['toloc'];
$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);
*/
?>