<?php
header('Cache-Control: no-cache, no-store, must-revalidate');   
header('Expires: 0');
date_default_timezone_set('Europe/London');
set_time_limit(300);
// error_reporting(E_ALL);
// ini_set('display_errors', 1);

// RTS Zebra 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($_SERVER['DOCUMENT_ROOT'].'/rdtkuk/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,'RTS',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);
    }
// 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
		$ty = 82;
// 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 (($key == "FLD03"))
				{
					$barcode = Barcode::fpdf($this, $black, $x, $y, $angle, $type,$barCol, $width, $height);
					$this->TextWithRotation($x, $y+8, $col, $angle);
				}
				else
				{
					if (strlen($col) > 0)
					{
						if ($key == "FLD07")
							$this->TextWithRotation(30, $ty, "Loc.", $angle);
						elseif ($key == "FLD01")
							$this->TextWithRotation(30, $ty, "Ref.", $angle);
						elseif ($key == "FLD06")
							$this->TextWithRotation(30, $ty, "Model", $angle);
						elseif ($key == "FLD02")
							$this->TextWithRotation(30, $ty, "Part", $angle);
						else
							$this->TextWithRotation(30, $ty, $key, $angle);
						$this->TextWithRotation(40, $ty, $col, $angle);
						$ty=$ty+5;
					}
				}
				$c++;
				
				$i++;
				if ($x == 30)
					$x = $x+20;
				else
					$x = $x+30;
			}
			$y = $ty+8;
			$ty = $ty+20;
//			$this->Ln();
//			$l = $l+1;
//			if ($l > 9)
			if ($ty > 250)
			{
				$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;
				$ty = 80;
			}
		}
	}	
}

// Load data
function LoadData($mHost, $mUser, $mPwd, $mDbName, $mRtsReference,$mSerialReference=null,$mPartNumber=null)
{
//	return "FAIL-".$mSerialReference;
// date / time
	$date = date('d/m/Y h:i', time());
// 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 rts_header.order_reference AS FLD01, rts_header.machine_model AS FLD06";
	$mDataQuery .=",rts_body.baan_location AS FLD07";
	$mDataQuery .=",rts_detail.part_number AS FLD02, rts_detail.serial_reference AS FLD03, rts_detail.received_qty AS FLD04,rts_detail.location_code AS FLD09";
	$mDataQuery .=",SUBSTRING(part.part_description,1,20) AS FLD05,'".$date."' AS FLD08";
	$mDataQuery .=" FROM rts_header";
	$mDataQuery .=" JOIN rts_body ON rts_header.id=rts_body.rts_header_id";
	$mDataQuery .=" JOIN rts_detail ON rts_body.id=rts_detail.rts_body_id";
	$mDataQuery .=" LEFT JOIN part ON rts_detail.part_number=part.part_number";
	$mDataQuery .=" WHERE rts_header.id > 0";
	$mDataQuery .=" AND rts_header.order_reference='".$mRtsReference."'";
	if (!empty($mSerialReference))
	{	
		$mDataQuery .=" AND rts_detail.serial_reference='".$mSerialReference."'";
	}
	if (!empty($mPartNumber))
	{
		$mDataQuery .=" AND rts_detail.part_number='".$mPartNumber."'";
	}
	
	if (!$mData = mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).":".$mDataQuery;

//	exit("FAIL-".mysqli_error($mConnection).":".$mDataQuery."-".mysqli_num_rows($mData));
	$i = 0;
	while ($mRow = mysqli_fetch_assoc($mData))		
	{
		$i++;
		$data[] =($mRow);
	}
	mysqli_close($mConnection);
	if ($i == 0)
		return "FAIL-No Matching records ".$mDataQuery;
	else
		return $data;	
}

// Print label
function label($mLabel, $data, $mPrinter,$mLabelsAcross=0)
{
//    print_r ($mLabel."-".$mPrinter."-".$mLabelsAcross);
	$mLabelContent = "";
// Label Layout
/*
HEADER
"^XA"
LABEL1
^PR2
^FO30,60^A0,30^FDFLD08^FS
^FO30,90^A0,30^FDLocation: FLD07 \ FLD09^FS
^FO250,60^A0,40^FDRTS: FLD01^FS
^FO30,120^A0,30^FDModel:^FS
^FO150,120^A0,50^FDFLD06^FS
^FO30,160^A0,30^FDPart:^FS
^FO150,160^A0,50^FDFLD02^FS
^FO460,160^A0,30^FDQty:^FS
^FO505,160^A0,40^FDFLD04^FS
^FO40,210^A0,50^FDFLD05^FS
^FO40,260^BY2^B3N,N,90,N,N^FDSFLD03^FS
^FO200,360^A0,30^FDFLD03^FS
FOOTER
"^XZ"
*/

// Load Label Template
	$mPrintData = __DIR__."/".$mLabel;

	$mFh = fopen($mPrintData, 'r');
	$mLabel = fread($mFh, filesize($mPrintData));
	fclose($mFh);
// Add NewLine Characters
	$lines=explode(PHP_EOL,$mLabel);
// No, Labels to a row (0=single label, 1=double labels)	
//	$mLabelsAcross = 0;
    $mHeaders = array();
	$mContent1 = "";
	$mContent2 = "";
    $mFooters = array();
	$c = 0;
    $i = 0;
	
// Build label from template
	foreach($lines as $line)
	{
        if (trim($line) == "HEADER")
        {
            $c = 0;
            continue;
        }
		if (trim($line) == "LABEL")
        {
            $c = 1;
            continue;
        }
        if (trim($line) == "LABEL1")
        {
            $c = 1;
            continue;
        }
        if (trim($line) == "LABEL2")
        {
            $c = 2;
            continue;
        }
        if (trim($line) == "FOOTER")
        {
            $c = 9;
            continue;
        }
        if ($c == 0)
            $mHeaders[] = trim($line);
        if ($c == 1)
            $mContent1 .= trim($line)."\n";
        if ($c == 2)
            $mContent2 .= trim($line)."\n";
        if ($c == 9)
            $mFooters[] = trim($line);
	}
//	exit("FAIL-TEST1-".$mPrintData."-".$mContent1."-".$c);
// Label Data
	$mLabelContent1 = $mContent1;
	$mLabelContent2 = $mContent2;
// Populate Label with data	
	$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 > $mLabelsAcross)
		{
//			print_r("OKMS-".$c);
// Send Label to Printer
			$fp = fsockopen($mPrinter, 9100, $errno, $errstr, 30);
			if ($fp !== false)
			{
				if (!empty($mHeaders))
				{
					foreach ($mHeaders as $mHeader)
					{
						fwrite ($fp,$mHeader.'\n');
	//					print_r ($mHeader);
					}
				}
				else
				{
					fwrite ($fp,"\x02L\n");
					fwrite ($fp,"H08\n");
					fwrite ($fp,"D11\n");
				}
				fwrite($fp,$mLabelContent1.$mLabelContent2);
//				print_r($mLabelContent1.$mLabelContent2);
				if (!empty($mFooters))
				{
					foreach ($mFooters as $mFooter)
					{
						fwrite ($fp,$mFooter.'\n');
	//					print_r ($mFooter); 
					}
				}
				else
				{
					fwrite ($fp,"E\n"); 
				}
				fclose($fp);
				return "OKMS-RTS Label Printed to - ".$mPrinter." ";
// Restore Print Layout for next labels
				$mLabelContent1 = $mContent1;
				$mLabelContent2 = $mContent2;
				$c = 0;
			}
			else
			{
				$c = 0;
			}
		}
	}
// Print Remaining label if Two across
	if ($c > 0)
	{
//		print_r("OKMS-");
		$fp = fsockopen($mPrinter, 9100, $errno, $errstr, 30);
		if ($fp !== false)
		{
			if (!empty($mHeaders))
			{
				foreach ($mHeaders as $mHeader)
				{
					fwrite ($fp,$mHeader.'\n');
//					print_r ($mHeader);
				}
			}
			else
			{
				fwrite ($fp,"\x02L\n");
				fwrite ($fp,"H08\n");
				fwrite ($fp,"D11\n");
			}
			fwrite($fp,$mLabelContent1);
//				print_r($mLabelContent1.$mLabelContent2);
			if (!empty($mFooters))
			{
				foreach ($mFooters as $mFooter)
				{
					fwrite ($fp,$mFooter.'\n');
//					print_r ($mFooter); 
				}
			}
			else
			{
				fwrite ($fp,"E\n"); 
			}
			fclose($fp);
			return "OKMS-RTS Label Printed to - ".$mPrinter." ";
		}
	}
}

// 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($_SERVER['DOCUMENT_ROOT']."/rdtkuk/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($mPrinter,$mLabel,$mCurrentUser,$mRtsReference,$mSerialReference,$mPartNumber=null,$mLabelsAcross=0,$mOutput='n')
{
//    return "FAIL-TEST-".$mDecantId;
// DB defaults
	$mDbDefaults = defaultDbConnection();
	$mHost = $mDbDefaults[0];
	$mUser = $mDbDefaults[1];
	$mPwd = $mDbDefaults[2];
	$mDbName = $mDbDefaults[3];
// date / time
	$date = date('d/m/Y h:i:s a', time());
	
	if (empty($mPrinter))
    {
// Build Report-file name
        $reportName = "lbl_rts_datamax";        
        list($code,$printer) = getRtsPrinter($reportName,$mHost, $mUser, $mPwd, $mDbName);	
    }
    else
	{
        list($code,$printer) = getRtsPrinter($mPrinter,$mHost, $mUser, $mPwd, $mDbName);
		$reportName = $code;
	}
	if (empty($code))
	{
		exit ("FAIL-Printer ".$printer." Not Found using code ".$reportName);
	}
//	exit("FAIL-TEST1-".$code." ".$printer);
	$data = LoadData($mHost, $mUser, $mPwd, $mDbName, $mRtsReference,$mSerialReference,$mPartNumber);
	if (is_string($data) && substr($data,0,2)=="FA")
		return $data;
//	if ($mPrinter)
//		decantLabel($mLabel, $data, $mPrinter);
	if (stripos($code,"zeb") !== false)
	{
		if (($mLabel == null) || ($mLabel == "") || (!$mLabel))
			$mLabel = "rts_zebra.prn";
//		return("FAIL-zebra".$code);
		$pdf = new PDF('P','mm','A4');
// Check if printer is connected
		if (ping($printer) == false)
		{
			exit ("FAIL-Printer ".$printer." Not Found");
		}	
		$mReturn = label($mLabel, $data, $printer,$mLabelsAcross);
		$mOutput = "z";
	}
	elseif (stripos($code,"datamax") !== false)
	{
		if (($mLabel == null) || ($mLabel == "") || (!$mLabel))
			$mLabel = "rts_datamax_small.prn";
//		exit("FAIL-Datamax-".$mLabel." ".$printer);
		$pdf = new PDF('P','mm','A4');
// Check if printer is connected
		if (ping($printer) == false)
		{
			exit ("FAIL-Printer ".$printer." Not Found");
		}
//		exit ("FAIL-".var_dump($data));
		$mReturn = label($mLabel, $data, $printer,$mLabelsAcross);
		$mOutput = "z";
	}
	elseif (stripos($code,"A5") !== false)
	{
//		return("FAIL-A5".$code);
		$pdf = new PDF('P','mm','A4');
	}
	else
	{
//		exit("FAIL-A4".$code);
		$pdf = new PDF('L','mm','A4');
	}
// Column headings
	$header = ["Reference","Part","Desc","vendor","Serial","Ran","Qty"];
	$pdf->SetFont('Arial','',12);

	$pdf->BarcodeTablePdf($header,$data);
	$pdf->Ln(5);

	if ($mOutput == "")
		$pdf->Output();
	elseif($mOutput == "f")
	{
		$mPdf = $_SERVER['DOCUMENT_ROOT']."/vimsreports/decantlabel".$mCurrentUser.".pdf";
		$pdf->Output($mPdf,$mOutput);
	}
	else
	{
		if (!file_exists($_SERVER['DOCUMENT_ROOT']."/vimsreports_arcv/".$code)) 
		{
			if (mkdir($_SERVER['DOCUMENT_ROOT']."/vimsreports_arcv/".$code)) 
			{
				$dir = $_SERVER['DOCUMENT_ROOT']."/vimsreports_arcv/".$code;
			} 
			else 
			{
				$dir = $_SERVER['DOCUMENT_ROOT']."/vimsreports_arcv";
			}
		}
		else
		{
			$dir = $_SERVER['DOCUMENT_ROOT']."/vimsreports_arcv/".$code;
		}
		$mPdf = $dir."/rtslabel".$mCurrentUser.".pdf";
		$pdf->Output($mPdf,'f');
	}

    if ((file_exists($mPdf) && $mOutput != "z"))
    {
        $mReturn = sendPdf($mPdf, $printer);
    
		if (($mReturn == "") || ($mReturn == null))
		{
			return ("OKMS-rtslabel");
		}
		if (substr($mReturn,0,2)=="OK")
			return "OKMS-RTS labels printed -".$mPrinter;
		else
			return "FAIL-".$mReturn;
	}
	if (is_string($mReturn) && substr($mReturn,0,4) != "OK  ")
	{
		exit ($mReturn);
	}
	else
	{
		return "OKMS-RTS labels printed -".$mPrinter;
	}
//    return ("IFRAME-/vimsreports_arcv/decantlabel".$mCurrentUser.".pdf");
//	print_r("FAIL-TEST1");
}

function getRtsPrinter($mReference,$mHost, $mUser, $mPwd, $mDbName)
{
	$mRow = array();
	$mPrinter = "default";
	$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
		exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error()."-".$mHost);
	$mDataQuery = "SELECT printer_code AS printer_code, printer_address AS printer_address FROM printer_mapping WHERE printer_code='".trim($mReference)."' LIMIT 1";
	if (!$mData = mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).":".$mDataQuery;
	if (mysqli_num_rows($mData) == 0)
	{
		$mDataQuery = "SELECT printer_code AS printer_code, printer_address AS printer_address FROM printer_mapping WHERE printer_address='".trim($mReference)."' LIMIT 1";
		if (!$mData = mysqli_query($mConnection,$mDataQuery))
			return "FAIL-".mysqli_error($mConnection).":".$mDataQuery;
	}
	if (mysqli_num_rows($mData) == 0)
	{
		$mDataQuery = "SELECT printer_code AS printer_code, printer_address AS printer_address FROM printer_mapping WHERE printer_code='default' LIMIT 1";
		if (!$mData = mysqli_query($mConnection,$mDataQuery))
			return "FAIL-".mysqli_error($mConnection).":".$mDataQuery;
	}
	$mRow = mysqli_fetch_row($mData);
	mysqli_close($mConnection);
	return $mRow;
}

function sendPdf($reportName, $printer)
{
	try
	{		
		if ($printer == "default")
		{
			$pgmPath = '"c:/LibreOffice/program/soffice.exe" --pt';
			$printPath = '"'.$printer.'"';
			$filePath = '"'.$reportName.'"';
			$command = escapeshellcmd($pgmPath." ".$printPath." ".$filePath);
//			return "FAIL-TEST1-".$reportName."-".$printer;
			$output = shell_exec($command);
			echo 'OK  -'.$output." ".$pgmPath." ".$printPath." ".$filePath;
		}
		else
		{
			$pgmPath = '"c:/LibreOffice/program/soffice.exe" --pt';
			$printPath = '"'.$printer.'"';
			$filePath = '"'.$reportName.'"';
			$command = escapeshellcmd($pgmPath." ".$printPath." ".$filePath);
//			$command = '^"c:/LibreOffice/program/soffice.exe^" --pt ^"^\^\VEU-RRMC-R1.vanteceurope.local^\veu-rrmc-it-office^" ^"e:/webroot/vimsreports_arcv/decantlabel.pdf^"';
//			return "FAIL-TEST1-".$reportName."-".$printer;
//			echo shell_exec($command);

// Execute the command and capture output
			$output = array();
			$returnValue = null;
			exec($command, $output, $returnValue);
//			print_r($output);
//			echo 'FAIL-'.$output." ".$pgmPath." ".$printPath." ".$filePath;
			echo ('OK  -'.$command);
//			var_dump($output);
//			var_dump($returnValue);
		}
		return;
	}
	catch (Exception $e)
	{
		echo "FAIL-picksheetpdf-".$e;
		return;
	}
}

function ping($mAddress)
{
    if(strtolower(PHP_OS)=='winnt')
    {
        $command = "ping -n 1 -w 1000 $mAddress";
        exec($command, $output, $status);
    }
    else
    {
        $command = "ping -c 1 -w 1000 $mAddress";
        exec($command, $output, $status);
    }
    if($status === 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

/*
// Data loading
$mFunction			= $_GET['function'];
$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);
*/
?>