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

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

// Receipt Interface

$mHaulierRef 		= $_GET['haulierreference'];
$mConnect   		= $_GET['connection'];
$mUser				= $_GET['user'];
$mPwd				= $_GET['pword'];
$mHost              = $_GET['host'];
$mDbName			= $_GET['dbase'];
$mTableName 		= $_GET['table'];
$mFilter			= $_GET['filter'];
$mReturnFields		= $_GET['returnfields'];
$mCurrentUser       = $_GET['currentuser'];
$mOutput			= $_GET['output'];

$mFilter = str_replace("|AND|","&",$mFilter);
$mFilter = str_replace("/dbase/",$mDbName,$mFilter);

include('../barcode/php-barcode.php');
require('../barcode/fpdf.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,'Receipt Detail',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);
    }	

// Get Receipt Reference Codes
	function LoadDoc ($mHost, $mUser, $mPwd, $mDbName, $mHaulierRef)
	{
// Read Headers
		$docs = array();
// mysql connection
		$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
			exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
		
		$mDataQuery = "SELECT receipt_header.document_reference AS document_reference, product_type.product_type_code AS product_type_code FROM receipt_header LEFT JOIN product_type ON receipt_header.product_type_id=product_type.id WHERE haulier_reference='".$mHaulierRef."'";
// mysql query construct
		if(!mysqli_query($mConnection,$mDataQuery))
			exit("FAIL-".mysqli_error($mConnection));
		$mData = mysqli_query($mConnection,$mDataQuery);
		$i = 0;
		while($mRow = mysqli_fetch_assoc($mData)) 
		{
			$docs[] =($mRow);
			$i++;
		}
		mysqli_close($mConnection);
		return $docs;
//    print_r($data.":".$mDataQuery.":".$i);
	}

// Load data
	function LoadDataPdf($mHost, $mUser, $mPwd, $mDbName, $mDocumentRef)
	{
// 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 receipt_detail.part_number AS partNumber,receipt_detail.ran_order AS ranOrder,receipt_detail.serial_reference AS serialReference, receipt_detail.received_qty AS quantity FROM receipt_header LEFT JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id LEFT JOIN part ON receipt_body.part_number=part.part_number JOIN receipt_detail ON receipt_body.id=receipt_detail.receipt_body_id LEFT JOIN inventory_master ON receipt_detail.part_number=inventory_master.part_number AND receipt_detail.serial_reference=inventory_master.serial_reference WHERE receipt_header.document_reference='".$mDocumentRef."'";
		$mDataQuery .= " ORDER BY receipt_detail.ran_order, receipt_detail.part_number, receipt_detail.serial_reference";
		if (!mysqli_query($mConnection,$mDataQuery))
			exit("FAIL-".mysqli_error($mConnection));
// mysql query construct
		$mData = mysqli_query($mConnection,$mDataQuery);
		$i = 0;
		while($mRow = mysqli_fetch_assoc($mData)) 
		{
			$data[] =($mRow);
			$i++;
		}
		mysqli_close($mConnection);
		return $data;
//    print_r($data.":".$mDataQuery.":".$i);
	}

// Simple table
	function BasicTablePdf($header, $data)
	{
// Initial Line
		$this->ln(30);
// Column widths
		$w = array(30, 30, 30, 30, 20, 10, 10, 20, 12);
// Header
		$i = 0;
		foreach($header as $col)
		{
			$this->Cell($w[$i],7,$col,0);
			$i++;
		}
		$this->Ln();
// Data
		foreach($data as $row)
		{
			$i = 0;
			foreach($row as $col)
			{
				if ($i == 4)
					$this->Cell($w[$i],6,$col,0,0,'R');
				else
					$this->Cell($w[$i],6,$col,0);
				$i++;
			}
			$this->Ln();
		}
	}
	
// Barcode table
	function BarcodeTablePdf($header, $data, $docRef, $haulierRef, $prefix)
	{
// 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,"Haulier Reference: ".$haulierRef);
		$this->Text(100,50,"Ran Count: ".count($data));
		$this->Text(10,55,"Document Reference: ".$docRef);
		$this->Text(100,55,"Report Date: ".$date);
		
		$this->SetFont('Arial','',$fontSize);
		$this->SetTextColor(0, 0, 0);
// Initial Line
		$this->ln(30);
// Column widths
		$w = array(60, 50, 50, 50);
// 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;
				if ($barCol != "")
				{
					for($i=0;$i<count($prefix);$i++)
					{
						if (strtolower($key) == strtolower($prefix[$i]['fieldName']))
							$barCol = $prefix[$i]['prefix'].$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+15;
			$y = $y+20;
			$this->Ln();
			$l = $l+1;
//			if ($l > 13)
			if ($l > 9)	
			{
				$this->AddPage();
				$this->Text(10,50,"Haulier Reference: ".$haulierRef);
				$this->Text(100,50,"Ran Count: ".count($data));
				$this->Text(10,55,"Document Reference: ".$docRef);
				$this->Text(100,55,"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;
			}
		}
	}
}

// Get Receipt Reference Codes
function LoadDocRan($mHost, $mUser, $mPwd, $mDbName, $mHaulierRef)
{
// Read Headers
	$docs = array();
// mysql connection
	$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
		exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
		
	$mDataQuery = "SELECT receipt_header.document_reference AS document_reference, product_type.product_type_code AS product_type_code FROM receipt_header LEFT JOIN product_type ON receipt_header.product_type_id=product_type.id WHERE haulier_reference='".$mHaulierRef."'";
// mysql query construct
	if(!mysqli_query($mConnection,$mDataQuery))
		exit("FAIL-".mysqli_error($mConnection));
	$mData = mysqli_query($mConnection,$mDataQuery);
	$i = 0;
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
		$docs[] =($mRow);
		$i++;
	}
	mysqli_close($mConnection);
	return $docs;
//    print_r($data.":".$mDataQuery.":".$i);
}

// Load data
function LoadDataRan($mHost, $mUser, $mPwd, $mDbName, $mDocumentRef)
{
// 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 receipt_header.expected_delivery_date AS deliveryDate, receipt_body.part_number AS partNumber,inventory_master.ran_order AS ranOrder,receipt_detail.serial_reference AS serialReference, receipt_detail.received_qty AS quantity FROM receipt_header LEFT JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id LEFT JOIN part ON receipt_body.part_number=part.part_number LEFT JOIN receipt_detail ON receipt_body.id=receipt_detail.receipt_body_id LEFT JOIN inventory_master ON receipt_detail.part_number=inventory_master.part_number AND receipt_detail.serial_reference=inventory_master.serial_reference WHERE receipt_header.document_reference='".$mDocumentRef."' ORDER BY inventory_master.part_number, inventory_master.ran_order, inventory_master.serial_reference";
	$mDataQuery = "SELECT max(receipt_header.expected_delivery_date) AS deliveryDate, receipt_detail.part_number AS partNumber, receipt_detail.ran_order AS ranOrder, sum(receipt_detail.received_qty) AS quantity FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id JOIN receipt_detail ON receipt_body.id=receipt_detail.receipt_body_id WHERE receipt_header.document_reference='".$mDocumentRef."' GROUP BY receipt_detail.part_number, receipt_detail.ran_order ORDER BY receipt_detail.part_number, receipt_detail.ran_order";
// mysql query construct
	$mData = mysqli_query($mConnection,$mDataQuery);
	$i = 0;
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
		$data[] =($mRow);
		$i++;
	}
	mysqli_close($mConnection);
	return $data;
//    print_r($data.":".$mDataQuery.":".$i);
}

// Simple table
function BasicTableRan($data, $docRef, $mOutput)
{
	$mIfCount = "000000000";
	$mIfRan = "        ";
	$mIfDeliveryDate = "";
	$mIfQuantity = "000000000";
	$mIfRef = substr($docRef,-5);
	$mIfDate = date('Ymd', time());
	sleep(1);
	$mIfTime = date('His', time());
// Create Interface File
	$if_file = "../../vimsout/Warehouse_RAN_Receipt.D".$mIfDate.".T".$mIfTime.".txt";
	$handle = fopen($if_file, 'w') or die('Cannot open file:  '.$if_file);
// date / time
	$date = date('YmdHis', time());
// Headings
	$mIfData = "HDAUTRANS WHRECEPT".$mIfRef."0L".$date."         \"\r\n";
	fwrite($handle, $mIfData);
// Data
	$l = 1;
	foreach($data as $row)
	{
		$mIfData = "DT";
		$mIfRan = $row['ranOrder']."        ";
		$mIfDeliveryDate = ($row['deliveryDate']);
		$mIfDeliveryDate = str_replace("-","",$mIfDeliveryDate);
		$mIfDeliveryDate = str_replace(":","",$mIfDeliveryDate);
		$mIfDeliveryDate = str_replace(" ","",$mIfDeliveryDate);
		$mIfDeliveryDate = substr($mIfDeliveryDate,0,12);
		if ($mIfDeliveryDate == "")
			$mIfDeliveryDate = "000000000000";
		if ($row['ranOrder'] == "")
			$mIfData .= "NO-RAN  ";
		else
			$mIfData .= substr($mIfRan,0,8);
		$mIfData .= $mIfDeliveryDate;
		$mIfQuantity = "0000000".round(($row['quantity']));
		$mIfQuantity = substr($mIfQuantity,-7);
		$mIfData .= $mIfQuantity;
//		$mIfData .= $row['serialReference']."\r\n";
		$mIfData .= "                   \"\r\n";
		fwrite($handle, $mIfData);
		$l++;
//		foreach($row as $key=>$col)
//		{
//		}
	}
// Footer
	$l++;
	$mIfCount .= $l;
	$mRecCount = substr($mIfCount,-9);
	$mIfData = "FTAUTRANS WHRECEPT".$mIfRef."0L".$date.$mRecCount."\"\r\n";
	fwrite($handle, $mIfData);
	fclose($handle);
// email
	if ($mOutput == "M")
	{
		$mailPath = "../../vimsout";
		$mailfrom = "vims@vanteceurope.com";
		$subject = "WHRECPT";
		$message = "WHRECPT";
		$mailTos = array("geoff-thorpe.hq@vantec-gl.com","sarah-mcmann.ak@vantec-gl.com");
		for ($i=0;$i<count($mailTos);++$i)
			mail_attachment("Warehouse_RAN_Receipt.D".$mIfDate.".T".$mIfTime.".txt", $mailPath, $mailTos[$i], $mailfrom, $subject, $message);
	}
}

function getPrefix($mHost, $mUser, $mPwd, $mDbName)
{
// Read Headers
	$prefix = array();
// mysql connection
	$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
		exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
		
	$mDataQuery = "SELECT field_name AS fieldName, substr(prefix_name,1,1) AS prefix FROM default_setting";
// mysql query construct
	if(!mysqli_query($mConnection,$mDataQuery))
		exit("FAIL-".mysqli_error($mConnection));
	$mData = mysqli_query($mConnection,$mDataQuery);
	$i = 0;
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
		$prefix[] =($mRow);
		$i++;
	}
	mysqli_close($mConnection);
	return $prefix;
//    print_r($data.":".$mDataQuery.":".$i);
}

// get Interface Settings
function getInterface($mHost, $mUser, $mPwd, $mDbName)
{
	$mailTos = array();
	// mysql connection
	$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
		exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
		
	$mDataQuery = "SELECT distribution_list AS email FROM report WHERE job_name = 'receiptinterface' LIMIT 1";
// mysql query construct
	if(!mysqli_query($mConnection,$mDataQuery))
		exit("FAIL-".mysqli_error($mConnection).$mDataQuery.mysqli_num_rows($Data));
	$mData = mysqli_query($mConnection,$mDataQuery);
	$i = 0;
	$email = "";
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
		$email =($mRow['email']);
		$i++;
	}
	mysqli_close($mConnection);
	if ($i == 0)
		$email = "geoff-thorpe@vantec-gl.com";
	
//	print_r("TEST1:".$email.":".$i);
	return $email;
}

// Mail
function mail_attachment($filename, $path, $mailto, $mailfrom, $subject, $message) 
{
	$file = $path."/".$filename;
	$content = file_get_contents( $file);
	$content = chunk_split(base64_encode($content));
	$uid = md5(uniqid(time()));
	$name = basename($file);

// header
	$header = "From: ".$mailfrom."\r\n";
	$header .= "Reply-To: \r\n";
	$header .= "MIME-Version: 1.0\r\n";
	$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";

// message & attachment
	$nmessage = "--".$uid."\r\n";
	$nmessage .= "Content-type:text/plain; charset=iso-8859-1\r\n";
	$nmessage .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
	$nmessage .= $message."\r\n\r\n";
	$nmessage .= "--".$uid."\r\n";
	$nmessage .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
	$nmessage .= "Content-Transfer-Encoding: base64\r\n";
	$nmessage .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
	$nmessage .= $content."\r\n\r\n";
	$nmessage .= "--".$uid."--";

	if (mail($mailto, $subject, $nmessage, $header))
	{
//		print_r("OK  -mail");
		return true; // Or do something here
	} 
	else 
	{
//		print_r("FAIL-mail error ".$mailto."-".$subject."-".$nmessage."-".$header);
		return false;
	}
}

// Main Process
function mainProcessPdf($mHost, $mUser, $mPwd, $mDbName,$mHaulierRef,$mOutput)
{
	$pdf = new PDF();
// Column headings
	$header = array("Part Number","Ran/Order","Serial Ref.","Quantity");

// Data loading
	if ($mHost == "")
		$mHost = "172.16.1.39";

	if ($mUser == "")
		$mUser = "root";
	if ($mPwd == "")
		$mPwd = "root";
	if ($mDbName == "")
		$mDbName = "vims";

// date / time
	$date = date('d/m/Y h:i:s a', time());
// PDF Font
	$pdf->SetFont('Arial','',10);
// Field Prefixes
	$prefix = getPrefix($mHost, $mUser, $mPwd, $mDbName);

// populate Document References
	$docs = $pdf->LoadDoc($mHost, $mUser, $mPwd, $mDbName, $mHaulierRef);
	if ((count($docs) == 0) || ($docs[0] == ""))
	{
		$data = $pdf->LoadDataPdf($mHost, $mUser, $mPwd, $mDbName, $mHaulierRef);
		$pdf->BarcodeTablePdf($header,$data,"unknown",$mHaulierRef,$prefix);
		$pdf->Ln(5);
	}
	else
	{
		for ($i = 0; $i < count($docs); ++$i)
		{
			$data = $pdf->LoadDataPdf($mHost, $mUser, $mPwd, $mDbName, $docs[$i]['document_reference']);
			$pdf->BarcodeTablePdf($header,$data,$docs[$i]['document_reference'],$mHaulierRef, $prefix);
			$pdf->Ln(5);
		}
	}
	if ($mOutput == "")
		$pdf->Output();
	elseif ($mOutput == "M")
	{
		$mPdf = "../../vimsmail/receiptpartdetail.pdf";
		$pdf->Output($mPdf,"F");
		$mailPath = "../../vimsmail";
		$mailfrom = "vims@vanteceurope.com";
		$subject = "Receipt Detail:".$docs[0]['document_reference'];
		$message = "Receipt Detail ".$docs[0]['document_reference']." Trailer ".$mHaulierRef;
		$mailTos = array();
		$email = getInterface($mHost, $mUser, $mPwd, $mDbName);
		$mailTos = explode(",",$email);
		for ($i=0;$i<count($mailTos);++$i)
		{
			mail_attachment("receiptpartdetail.pdf", $mailPath, $mailTos[$i], $mailfrom, $subject, $message);
		}
	}
	elseif ($mOutput == "F")
	{
		$mPdf = "../../vimsreports/receiptdetail".$mCurrentUser.".pdf";
		$pdf->Output($mPdf,$mOutput);
	}
}

// Main Process
function mainProcessRan($mHost, $mUser, $mPwd, $mDbName,$mHaulierRef,$mOutput)
{
// Data loading
	if ($mHost == "")
		$mHost = "172.16.1.39";

	if ($mUser == "")
		$mUser = "root";
	if ($mPwd == "")
		$mPwd = "root";
	if ($mDbName == "")
		$mDbName = "vims";

// date / time
	$date = date('d/m/Y h:i:s a', time());

// populate Document References
	$docs = LoadDocRan($mHost, $mUser, $mPwd, $mDbName, $mHaulierRef);
	if ((count($docs) == 0) || ($docs[0] == ""))
	{
		$data = LoadDataRan($mHost, $mUser, $mPwd, $mDbName, $mHaulierRef);
		BasicTableRan($data,$mHaulierRef,$mOutput);
	}
	else
	{
		for ($i = 0; $i < count($docs); ++$i)
		{
			$data = LoadDataRan($mHost, $mUser, $mPwd, $mDbName, $docs[$i]['document_reference']);
			BasicTableRan($data,$docs[$i]['document_reference'],$mOutput);
		}
	}
}

if ($mFilter == "")
	mainProcessPdf($mHost, $mUser, $mPwd, $mDbName,$mHaulierRef,$mOutput);	
?>