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

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

// Receipt Summary
$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);

// 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 LoadData($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";
// 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 BasicTable($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");
		for ($i=0;$i<count($mailTos);++$i)
			mail_attachment("Warehouse_RAN_Receipt.D".$mIfDate.".T".$mIfTime.".txt", $mailPath, $mailTos[$i], $mailfrom, $subject, $message);
	}
}

// get Interface Settings
function getInterface($mFilter)
{
	$mailTos = array();
	// mysql connection
	$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
		exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
		
	$mDataQuery = "SELECT email AS email FROM interface_settings WHERE interface = '".$mFilter."' LIMIT 1";
// mysql query construct
	if(!mysqli_query($mConnection,$mDataQuery))
		exit(mysqli_error($mConnection));
	$mData = mysqli_query($mConnection,$mDataQuery);
	$i = 0;
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
//		$prefix[] =($mRow);
		$i++;
	}
	mysqli_close($mConnection);
	if ($i > 0)
		$mailTos = explode($mRow["email"],",");
	return $mailTos;
}
// 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)) {
		return true; // Or do something here
	} else {
	return false;
	}
}
// Main Process
function mainProcessRan($mHost, $mUser, $mPwd, $mDbName,$mHaulierRef,$mOutput)
{
// Data loading
	if ($mHost == "")
		$mHost = "172.16.1.70";

	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 = LoadDoc($mHost, $mUser, $mPwd, $mDbName, $mHaulierRef);
	if ((count($docs) == 0) || ($docs[0] == ""))
	{
		$data = LoadData($mHost, $mUser, $mPwd, $mDbName, $mHaulierRef);
		BasicTable($data,$mHaulierRef,$mOutput);
	}
	else
	{
		for ($i = 0; $i < count($docs); ++$i)
		{
			$data = LoadData($mHost, $mUser, $mPwd, $mDbName, $docs[$i]['document_reference']);
			BasicTable($data,$docs[$i]['document_reference'],$mOutput);
		}
	}
}
	if ($mFilter == "")
 	mainProcessRan($mHost, $mUser, $mPwd, $mDbName,$mHaulierRef,$mOutput);	
?>