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

include('../barcode/php-barcode.php');
require('../barcode/fpdf.php');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../../phpmailer/Exception.php';
require '../../phpmailer/PHPMailer.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_name AS product_name 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(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_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."'";
// 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($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 BarcodeTable($header, $data, $docRef, $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.35;    // 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,"Document Reference: ".$docRef);
		$this->Text(100,50,"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;
			$this->Ln();
			$l = $l+1;
			if ($l > 13)
			{
				$this->AddPage();
				$this->Text(10,50,"Document Reference: ".$docRef);
				$this->Text(100,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;
			}
		}
	}
}

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, prefix_name AS prefix FROM default_setting";
// 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);
	return $prefix;
//    print_r($data.":".$mDataQuery.":".$i);
}
// 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
//	$pdf = new PDF();

function mainProcess($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.70";

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

// 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->LoadData($mHost, $mUser, $mPwd, $mDbName, $mHaulierRef);
		$pdf->BarcodeTable($header,$data,$mHaulierRef,$prefix);
		$pdf->Ln(5);
	}
	else
	{
		for ($i = 0; $i < count($docs); ++$i)
		{
			$data = $pdf->LoadData($mHost, $mUser, $mPwd, $mDbName, $docs[$i]['document_reference']);
			$pdf->BarcodeTable($header,$data,$docs[$i]['document_reference'],$prefix);
			$pdf->Ln(5);
		}
	}

	if ($mOutput == "")
		$pdf->Output();
	elseif ($mOutput == "M")
	{
		$mPdf = "../../vimsmail/receiptpartdetail.pdf";
		$pdf->Output($mPdf,"F");
		$mailPath = "../../vimsmail";
//		$mailto = "geoffthorpe@hotmail.co.uk";
		$mailfrom = "vims@vanteceurope.com";
		$subject = "Receipt Detail";
		$message = "Receipt Detail";
		$mailTos = array("geoff-thorpe.hq@vantec-gl.com","sarah-mcmann.ak@vantec-gl.com");
//	$mailto = "geoff-thorpe.hq@vantec-gl.com";
		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);
	}
}
if ($mFilter == "")
	mainProcess($mHost, $mUser, $mPwd, $mDbName,$mHaulierRef,$mOutput);	
?>