<?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,'Pick 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',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, $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   = 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
		
// Sheet 1
		
// Headings
		$this->AddPage();
		$this->Text(10,50,"Report Date: ".$date);
		
		$this->SetFont('Arial','',$fontSize);
		$this->SetTextColor(0, 0, 0);
// Initial Line
		$this->ln(30);
// counts
		$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 Num");
		$this->Text($x, $y+5, $mCustomerRef);
		$barcode = Barcode::fpdf($this, $black, $x+50, $y, $angle, $type,$mCustomerRef, $width, $height);
// benum
		$x = 50;
		$y = $y+30;
		$this->SetFont('Arial','',50);
		$this->TextWithRotation($x, $y, $data[0]['benum'], $angle);
// 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($x,$y,"Supply Type: Cross Dock");
		}
		$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']);
				$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);
				}
			}
		}
		
// Sheet 2

// 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:    ".(int)$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($x,$y,"Supply Type: Cross Dock");
		}
		$this->Text($x+80,$y,"Assy Station: ".$dgit);
// Column widths
		$w = array(40,80,20,40,10);
// 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 = 0;
		$this->SetFont('Arial','',12);
		$y = $y+20;
		foreach($data as $row)
		{
			$c = 0;
			$x = 30;

			$this->Cell($w[0],15,'',1,0,'L');
			$this->Cell($w[1],15,$row['part_description'],1);
			$this->Cell($w[2],15,(int)$row['qty_expected'],1,0,'R');
			$this->Cell($w[3],15,'',1,0,'L');
			$this->Cell($w[4],15,'',1,0,'L');
//			$this->Text($x, $y, $col);
			$barCol = $row['part_number'];
			$this->Text($x-10,$y+1,$row['part_number']);
			$barcode = Barcode::fpdf($this, $black, $x, $y+6, $angle, $type,$barCol, $width, 8);

			$c++;
				
			$i++;
			$y = $y+15;
			$this->Ln();
			$l = $l+1;
			if ($l > 9)
			{
				$this->AddPage();
				$this->Text(10,30,"Report Date: ".$date);
			}
		}		
	}	
}

// 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());
		
	$mDataQuery = "SELECT document_header.document_reference_code AS document_reference, document_header.expected_delivery AS expected_delivery,document_header.benum AS benum, document_header.pick_type AS pick_type,document_header.lgnum AS warehouse";
	$mDataQuery .= ",document_body.wempf AS vehicle_reference, document_body.qty_expected/part.conversion_factor AS qty_expected";
	$mDataQuery .= ",part.part_number AS part_number, part.part_description AS part_description";
	$mDataQuery .= ",0 AS no_items, 0 AS total_qty";
	$mDataQuery .= " FROM document_header";
	$mDataQuery .= " JOIN document_body on document_header.id=document_body.document_header_id";
	$mDataQuery .= " LEFT JOIN part ON document_body.part_id=part.id";
	$mDataQuery .= " WHERE document_header.tanum='".$mCustomerRef."'";
	$mDataQuery .= " ORDER BY document_header.tanum, document_header.document_reference";
	if (!$mData = mysqli_query($mConnection,$mDataQuery))
		$data[0] = "FAIL-".mysqli_error($mConnection).":".$mDataQuery;// mysql query construct

//	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;
}

/*
// 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 pickPrint($mCustomerRef, $mPrinter, $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";
	
//	return "FAIL-TEST1-".$mPrefix."-".$mPrinter."-".$mNumber."-".$mLabel;
	
	$data = LoadData($mHost, $mUser, $mPwd, $mDbName, $mCustomerRef);
	
	$pdf = new PDF();
// 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 = "../../../vimsreports/picksheet".$mCurrentUser.".pdf";
		$pdf->Output($mPdf,$mOutput);
	}
	else
	{
		$mPdf = "../../../vimsreports_arcv/picksheet".$mCurrentUser.".pdf";
		$pdf->Output($mPdf,'');
	}
	return "OK  -picksheetPdf";
//	print_r("FAIL-TEST1");
}

// Scheduled Function
function scheduledTask($mPassParm)
{
// 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";
		return pickPrint($mCustomerRef, $mPrinter, $mHost, $mUser, $mPwd, $mDbName, $mOutput);
	}
	return "OK  -";
}

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

?>