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

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

// odette 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,'Part',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 == "FLD01") || ($key == "FLD05") || ($key == "FLD12"))
				{
					$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 == "FLD16")
							$this->TextWithRotation(30, $ty, "Desc.", $angle);
						elseif ($key == "FLD03")
							$this->TextWithRotation(30, $ty, "Ran.", $angle);
						elseif ($key == "FLD06")
							$this->TextWithRotation(30, $ty, "Snp.", $angle);
						elseif ($key == "FLD07")
							$this->TextWithRotation(30, $ty, "Vendor", $angle);
						elseif ($key == "FLD17")
							$this->TextWithRotation(30, $ty, ".", $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, $mRanOrOrder,$mPartNumber,$mSnp,$mNumber,$mSerialReference)
{
//	return "FAIL-".$mSerialReference;
// date / time
	$date = date('mdhis', 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());
	if (($mSerialReference=="") || ($mSerialReference==null))	
		$mDataQuery = "SELECT '' AS FLD01, part.part_number AS FLD05, part.part_description AS FLD16, part.vendor_part_code AS FLD18, '000000000000001' AS FLD12, UPPER('".$mRanOrOrder."') AS FLD03,'".$mSnp."' AS FLD06, vendor_reference_code AS FLD07, vendor_name AS FLD17, CASE WHEN part.requires_count =1 THEN 'Y' ELSE '' END AS count FROM part LEFT JOIN vendor ON part.vendor_id=vendor.id WHERE part.part_number='".$mPartNumber."' LIMIT 1";
	else
		$mDataQuery = "SELECT '' AS FLD01, part.part_number AS FLD05, part.part_description AS FLD16, part.vendor_part_code AS FLD18, '' AS FLD12, UPPER('".$mRanOrOrder."') AS FLD03,'".$mSnp."' AS FLD06, vendor_reference_code AS FLD07, vendor_name AS FLD17, CASE WHEN part.requires_count =1 THEN 'Y' ELSE '' END AS count FROM part LEFT JOIN vendor ON part.vendor_id=vendor.id WHERE part.part_number='".$mPartNumber."' LIMIT 1";
// 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).$mSerialReference;
	$i = 0;
	$mRow = mysqli_fetch_assoc($mData);
	while($i < $mNumber)		
	{
		$i++;
		if ($mSerialReference=="" || $mSerialReference==null)
			$mRow['FLD12'] = $date.substr('000'.$i,-3);
		else
			$mRow['FLD12'] = $mSerialReference;
		$data[] =($mRow);
	}
	mysqli_close($mConnection);
	if ($i == 0)
		return "FAIL-No Matching records";
	else
		return $data;	
}

// Odette label
function label($mLabel, $data, $mPrinter)
{
	$mLabelContent = "";
// Label Layout
/*
LABEL
1X1100004990010L780002
1X1100004080010L780002                      
1X1100000940010L780002
1X1100004090532L002045                      
1X1100000060398L002286                      
1X1100004090398L002148                     
1X1100002330400L393002                      
1X1100001480400L393002                      
1X1100001730006L393002
1X1100004520400L393002                      
1X1100004090666L002044
1X1100000960605L002054
1X1100002910010L780002
1911S0005150085P022P024VIMS
1911S0004800010P011P009ADVICE NOTE-NO.(N)
1911S0003900010P011P009PART NO.(P)
1911S0002700010P011P009QUANTITY(Q)
1911S0001550010P011P009SUPPLIER(V)
1911S0000750010P011P009SERIAL(S)
1911S0001320405P011P009DATE
1911S0002750405P011P009DESCRIPTION
1911S0005150430P022P024FLD01
1911S0004690144P022P018FLD03                       
1911S0003580145P043P036FLD05
1911S0002370112P043P036FLD06
1911S0000600130P018P018FLD12
1911S0002440405P025P024FLD16
1911S0004580405P020P015FLD17
1911S0000600405P020P015FLD18
1aC405004150050NFLD03
1aK806002950052PFLD05
1aK805501780050QFLD06
1aC404500990050VFLD07
1aC404500050050SFLD12
*/

//	print_r("Label:".$mLabel);
// Load Label Template
	$mPrintData = __DIR__."/".$mLabel;
//	print_r("Test-".$printData);

	$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;
	$mContent1 = "";
	$mContent2 = "";
	$c = -1;
	
// Build label from template
	foreach($lines as $line)
	{
		if (substr($line,0,5) != "LABEL")
		{
			if ($c == 0)
				$mContent1 .= $line."\n";
			else
				$mContent2 .= $line."\n";
		}
		else
		{
			$c++;
			if ($c > $mLabelsAcross)
				$c = 0;
		}
	}
// 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)
		{
// 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);
//			$mLabelContent .= $mLabelContent1.$mLabelContent2;

// Restore Print Layout for next labels
			$mLabelContent1 = $mContent1;
			$mLabelContent2 = $mContent2;
			$c = 0;
		}
	}
// Print Remaining label if Two across
	if ($c > 0)
	{
		$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);
	
	if ($mLabelContent != "")
		$mLabelContent = "FAIL-".$mLabelContent;
	return $mLabelContent;
}

// 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($mRanOrOrder,$mPartNumber,$mSnp,$mNumber,$mPrinter,$mLabel,$mHost,$mUser,$mPwd,$mDbName,$mOutput,$mSerialReference="")
{
// 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 = "odette.txt";
	
//	return "FAIL-TEST1-".$mPartNumber."-".$mPrinter."-".$mLabel."-".$mSerialReference;
	
	$data = LoadData($mHost, $mUser, $mPwd, $mDbName, $mRanOrOrder,$mPartNumber,$mSnp,$mNumber,$mSerialReference);
	if (substr($data,0,2)=="FA")
		return $data;
//	return LoadData($mHost, $mUser, $mPwd, $mDbName, $mFromLoc, $mToLoc);
	if ($mPrinter)
		$mResult = label($mLabel, $data, $mPrinter);
	if (substr($mResult,0,2)=="FA")
		return $mResult;

	$pdf = new PDF();
// Column headings
	$header = "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 = "../../../vimsreports/partlabel".$mCurrentUser.".pdf";
		$pdf->Output($mPdf,$mOutput);
	}
	else
	{
		$mPdf = "../../../vimsreports_arcv/partlabel".$mCurrentUser.".pdf";
		$pdf->Output($mPdf,'f');
	}
	return "OK  -partLabelPdf - Printer ".$mPrinter;
//	print_r("FAIL-TEST1");
}

/*
// 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);
*/
?>