<?php

/* $Id: PrintCustTransDOPortrait.php 5103 2012-06-22 YS Chin $ */

include('includes/session.php');

$ViewTopic = 'ARReports';
$BookMark = 'PrintDeliveryOrder';

if (isset($_GET['FromTransNo'])) {
	$FromTransNo = filter_number_format($_GET['FromTransNo']);
} elseif (isset($_POST['FromTransNo'])){
	$FromTransNo = filter_number_format($_POST['FromTransNo']);
} else {
	$FromTransNo = '';
}

if (isset($_GET['PrintPDF'])) {
	$PrintPDF = $_GET['PrintPDF'];
} elseif (isset($_POST['PrintPDF'])) {
	$PrintPDF = $_POST['PrintPDF'];
}

If (!isset($_POST['ToTransNo'])
	OR trim($_POST['ToTransNo'])==''
	OR filter_number_format($_POST['ToTransNo']) < $FromTransNo) {

	$_POST['ToTransNo'] = $FromTransNo;
}

$FirstTrans = $FromTransNo; /* Need to start a new page only on subsequent transactions */

If (isset($PrintPDF)
	and $PrintPDF!=''
	and isset($FromTransNo)
	and $FromTransNo!=''){

	include ('includes/PDFStarter.php');

	$Page_Width=595;
	$Page_Height=842;
	$Top_Margin=30;
	//$Bottom_Margin=30;
	$Bottom_Margin=120;
	$Left_Margin=40;
	$Right_Margin=30;

	$pdf = new Cpdf('P', 'pt', 'A4');
	$pdf->addInfo('Author','EMP ' . $Version);
	$pdf->addInfo('Creator','EMP');

	$pdf->addInfo('Title',_('Delivery Order') . ' ' . $FromTransNo . ' to ' . $_POST['ToTransNo']);
	$pdf->addInfo('Subject',_('Delivery Order') . ' ' . $FromTransNo . ' ' . _('to') . ' ' . $_POST['ToTransNo']);

	$pdf->setAutoPageBreak(0);
	$pdf->setPrintHeader(false);
	$pdf->SetPrintFooter(false);
	$pdf->AddPage();
	$pdf->cMargin = 0;

	$FirstPage = true;
	$line_height=16;

	while ($FromTransNo <= filter_number_format($_POST['ToTransNo'])){

	/*retrieve the DO details from the database to print
	notice that salesorder record must be present to print the DO purging of sales orders will
	nobble the DO reprints */

	// check if the user has set a default bank account for DOs, if not leave it blank
		$sql = "SELECT bankaccounts.invoice,
				bankaccounts.bankaccountnumber,
				bankaccounts.bankaccountcode
				FROM bankaccounts
				WHERE bankaccounts.invoice = '1'";
		$result=DB_query($sql,$db,'','',false,false);
		if (DB_error_no($db)!=1) {
			if (DB_num_rows($result)==1){
				$myrow = DB_fetch_array($result);
				$DefaultBankAccountNumber = _('Account:') .' ' .$myrow['bankaccountnumber'];
				$DefaultBankAccountCode =  _('Bank Code:') .' ' .$myrow['bankaccountcode'];
			} else {
				$DefaultBankAccountNumber = '';
				$DefaultBankAccountCode =  '';
			}
		} else {
			$DefaultBankAccountNumber = '';
			$DefaultBankAccountCode =  '';
		}
		// gather the DO data

		$sql = "SELECT debtortrans.trandate,
				debtortrans.ovamount,
				debtortrans.ovdiscount,
				debtortrans.ovfreight,
				debtortrans.ovgst,
				debtortrans.rate,
				debtortrans.invtext,
				debtortrans.consignment,
				debtorsmaster.name,
				debtorsmaster.address1,
				debtorsmaster.address2,
				debtorsmaster.address3,
				debtorsmaster.address4,
				debtorsmaster.address5,
				debtorsmaster.address6,
				debtorsmaster.currcode,
				debtorsmaster.invaddrbranch,
				debtorsmaster.taxref,
				paymentterms.terms,
				salesorders.deliverto,
				salesorders.deladd1,
				salesorders.deladd2,
				salesorders.deladd3,
				salesorders.deladd4,
				salesorders.deladd5,
				salesorders.deladd6,
				salesorders.customerref,
				salesorders.orderno,
				salesorders.orddate,
				locations.locationname,
				shippers.shippername,
				custbranch.brname,
				custbranch.braddress1,
				custbranch.braddress2,
				custbranch.braddress3,
				custbranch.braddress4,
				custbranch.braddress5,
				custbranch.braddress6,
				custbranch.brpostaddr1,
				custbranch.brpostaddr2,
				custbranch.brpostaddr3,
				custbranch.brpostaddr4,
				custbranch.brpostaddr5,
				custbranch.brpostaddr6,
				salesman.salesmanname,
				debtortrans.debtorno,
				debtortrans.branchcode,
				currencies.decimalplaces
			FROM debtortrans INNER JOIN debtorsmaster
			ON debtortrans.debtorno=debtorsmaster.debtorno
			INNER JOIN custbranch
			ON debtortrans.debtorno=custbranch.debtorno
			AND debtortrans.branchcode=custbranch.branchcode
			INNER JOIN salesorders
			ON debtortrans.order_ = salesorders.orderno
			INNER JOIN shippers
			ON debtortrans.shipvia=shippers.shipper_id
			INNER JOIN salesman
			ON custbranch.salesman=salesman.salesmancode
			INNER JOIN locations
			ON salesorders.fromstkloc=locations.loccode
			INNER JOIN paymentterms
			ON debtorsmaster.paymentterms=paymentterms.termsindicator
			INNER JOIN currencies
			ON debtorsmaster.currcode=currencies.currabrev
			WHERE debtortrans.type=10
			AND debtortrans.transno='" . $FromTransNo . "'";

		if (isset($_POST['PrintEDI']) and $_POST['PrintEDI']=='No') {
			$sql = $sql . " AND debtorsmaster.ediinvoices=0";
		}
	

	   $result=DB_query($sql,$db,'','',false,false);

	   if (DB_error_no($db)!=0) {

		$Title = _('Transaction Print Error Report');
		include ('includes/header.php');

		prnMsg( _('There was a problem retrieving the delivery order details for number') . ' ' . $InvoiceToPrint . ' ' . _('from the database') . '. ' . _('To print a DO, the sales order record, the customer transaction record and the branch record for the customer must not have been purged') . '. ' . _('To print a credit note only requires the customer, transaction, salesman and branch records be available'),'error');
		if ($debug==1){
		    prnMsg (_('The SQL used to get this information that failed was') . '<br />' . $sql,'error');
		}
		include ('includes/footer.php');
		exit;
	    }

	    if (DB_num_rows($result)==1)
	    {
		$myrow = DB_fetch_array($result);

		$ExchRate = $myrow['rate'];

		$sql = "SELECT stockmoves.stockid,
				stockmaster.description,
				-stockmoves.qty as quantity,
				stockmoves.discountpercent,
				((1 - stockmoves.discountpercent) * stockmoves.price * " . $ExchRate . "* -stockmoves.qty) AS fxnet,
				(stockmoves.price * " . $ExchRate . ") AS fxprice,
				stockmoves.narrative,
				stockmaster.controlled,
				stockmaster.serialised,
				stockmaster.units,
				stockmoves.stkmoveno,
				stockmaster.decimalplaces
			FROM stockmoves INNER JOIN stockmaster
			ON stockmoves.stockid = stockmaster.stockid
			WHERE stockmoves.type=10
			AND stockmoves.transno='" . $FromTransNo . "'
			AND stockmoves.show_on_inv_crds=1";
		

		$result=DB_query($sql,$db);
		if (DB_error_no($db)!=0) {
			$Title = _('Transaction Print Error Report');
			include ('includes/header.php');
			echo '<br />' . _('There was a problem retrieving the delivery order stock movement details for DO number') . ' ' . $FromTransNo . ' ' . _('from the database');
			if ($debug==1){
			    echo '<br />' . _('The SQL used to get this information that failed was') . '<br />' . $sql;
			}
			include('includes/footer.php');
			exit;
		}


		if (DB_num_rows($result)>0){

			$FontSize = 9;
			$PageNumber = 1;
	
			include('includes/emp_PDFTransDOPageHeaderPortrait.inc');
			$FirstPage = False;

			while ($myrow2=DB_fetch_array($result))
			{
				if ($myrow2['discountpercent'] == 0)
				{
					$DisplayDiscount = '';
				}
				else
				{
					$DisplayDiscount = locale_number_format($myrow2['discountpercent'] * 100, 2) . '%';
					$DiscountPrice = $myrow2['fxprice'] * (1 - $myrow2['discountpercent']);
				}
				
				$NewPageRequired;
				if($NewPageRequired){
					include('includes/emp_PDFTransDOPageHeaderPortrait.inc');
					$NewPageRequired=false;
				}
			
				$DisplayNet = locale_number_format($myrow2['fxnet'],$myrow['decimalplaces']);
				$DisplayPrice = locale_number_format($myrow2['fxprice'],$myrow['decimalplaces']);
				$DisplayQty = locale_number_format($myrow2['quantity'],$myrow2['decimalplaces']);

				$LeftOvers = $pdf->addTextWrap($Left_Margin+5,$YPos,71,$FontSize-3,$myrow2['stockid']);
				//20140825 YS Chin: Increased text width from 186 to 300
				$LeftOvers = $pdf->addTextWrap($Left_Margin+80,$YPos,300,$FontSize,$myrow2['description']);
				$lines=1;

				while ($LeftOvers!='')
				{
					//20140825 YS Chin: Increased text width from 186 to 300
					$LeftOvers = $pdf->addTextWrap($Left_Margin+80,$YPos-(10*$lines),300,$FontSize,$LeftOvers);
					$lines++;
				}


				$LeftOvers = $pdf->addTextWrap($Left_Margin+400,$YPos,26,$FontSize,$myrow2['units'],'center');
				$LeftOvers = $pdf->addTextWrap($Left_Margin+450,$YPos,36,$FontSize,$DisplayQty,'right');
								
				if ($myrow2['controlled']==1){

					$GetControlMovts = DB_query("SELECT moveqty,
									serialno
									FROM stockserialmoves
									WHERE stockmoveno='" . $myrow2['stkmoveno'] . "'",$db);

					if ($myrow2['serialised']==1)
					{
						while ($ControlledMovtRow = DB_fetch_array($GetControlMovts)){
							$YPos -= (10*$lines);
							$LeftOvers = $pdf->addTextWrap($Left_Margin+82,$YPos,100,$FontSize,$ControlledMovtRow['serialno'],'left');
							if ($YPos-$line_height <= $Bottom_Margin){
								/* head up a new DO/credit note page */
								/*draw the vertical column lines right to the bottom */
								PrintLinesToBottom ();
	   		        			include ('includes/emp_PDFTransDOPageHeaderPortrait.inc');
			   				} //end if need a new page headed up
						}
					}
					else
					{
						while ($ControlledMovtRow = DB_fetch_array($GetControlMovts)){
							$YPos -= (10*$lines);
							$LeftOvers = $pdf->addTextWrap($Left_Margin+82,$YPos,100,$FontSize,(-$ControlledMovtRow['moveqty']) . ' x ' . $ControlledMovtRow['serialno'],'left');
							if ($YPos-$line_height <= $Bottom_Margin){
								/* head up a new DO/credit note page */
								/*draw the vertical column lines right to the bottom */
								PrintLinesToBottom ();
	   		        			include ('includes/emp_PDFTransDOPageHeaderPortrait.inc');
			   				} //end if need a new page headed up
						}
					}
				}
				$YPos -= ($FontSize*$lines);

				$lines=explode('\r\n',htmlspecialchars_decode($myrow2['narrative']));
				for ($i=0;$i<sizeOf($lines);$i++)
				{
					while (mb_strlen($lines[$i])>1)
					{
						if ($YPos-$line_height <= $Bottom_Margin)
						{
							/* head up a new DO/credit note page */
							/*draw the vertical column lines right to the bottom */
							PrintLinesToBottom ();
							include ('includes/emp_PDFTransDOPageHeaderPortrait.inc');
						} //end if need a new page headed up
						
						/*increment a line down for the next line item */
						if (mb_strlen($lines[$i])>1)
						{
							//20140825 YS Chin: Increased text width from 181 to 300
							$lines[$i] = $pdf->addTextWrap($Left_Margin+85,$YPos,300,$FontSize,stripslashes($lines[$i]));
						}
						$YPos -= ($line_height);
					}
				}
				
				if (($YPos-$Bottom_Margin)<(4*$line_height)){

					/* head up a new DO/credit note page */
					/*draw the vertical column lines right to the bottom */
					//PrintLinesToBottom ();
					//include ('includes/PDFTransDOPageHeaderPortrait.inc');
					
					$pdf->line($Left_Margin+78, $TopOfColHeadings+12,$Left_Margin+78,$Bottom_Margin+(4*$line_height));
					/*Print a column vertical line */
					$pdf->line($Left_Margin+388, $TopOfColHeadings+12,$Left_Margin+388,$Bottom_Margin+(4*$line_height));
			
					$pdf->line($Left_Margin+448, $TopOfColHeadings+12,$Left_Margin+448,$Bottom_Margin+(4*$line_height));
			
					/*Rule off at bottom of the vertical lines */
					$pdf->line($Left_Margin, $Bottom_Margin+(4*$line_height),$Page_Width-$Right_Margin,$Bottom_Margin+(4*$line_height));
			
					/*Now print out the footer and totals */
			
					/*Print out the DO text entered */
					$YPos = $Bottom_Margin+(3*$line_height);
					
					$FontSize=8;
					
					$pdf->addText($Page_Width-$Right_Margin-390, ($YPos+6) - ($line_height*-0.5),$FontSize, _('Acknowledged Receipt by:'));
					
					$pdf->line($Page_Width-$Right_Margin-288, $YPos+$line_height,$Page_Width-$Right_Margin-288,$Bottom_Margin);
					$pdf->addText($Page_Width-$Right_Margin-280, ($YPos+6) - ($line_height*1),$FontSize, _('........................................................'));
					$pdf->addText($Page_Width-$Right_Margin-280, ($YPos+6) - ($line_height*1.7),$FontSize, _('Name:'));
					$pdf->addText($Page_Width-$Right_Margin-280, ($YPos+6) - ($line_height*2.4),$FontSize, _('Date:'));
					
					$pdf->line($Left_Margin+388, $YPos+$line_height,$Left_Margin+388,$Bottom_Margin);
					$pdf->addText($Left_Margin+390, ($YPos+6) - ($line_height*-0.5),$FontSize, _('Company Stamp:'));
					
					$YPos+=10;
					$NewPageRequired=true;
					
				} //end if need a new page headed up
			} /*end while there are line items to print out*/
			
			//20140912 YS Chin: Place invoice text within invoice body
			$FontSize =9;
			$LeftOvers=explode('\r\n',DB_escape_string($myrow['invtext']));
			for ($i=0;$i<sizeOf($LeftOvers);$i++)
			{
				if ($YPos-$line_height <= $Bottom_Margin)
				{
					PrintLinesToBottom ();
					include ('includes/PDFTransPageHeaderPortrait.inc');
				}
				$pdf->addText($Left_Margin+85, $YPos, $FontSize, $LeftOvers[$i]);
				$YPos -= ($FontSize);
			}
			//20140912 YS Chin: Place invoice text within invoice body
			
		} /*end if there are stock movements to show on the DO or credit note*/

		$YPos -= $line_height;

		/* check to see enough space left to print the 4 lines for the totals/footer */
		/*if (($YPos-$Bottom_Margin)<(4*$line_height))
		{
			PrintLinesToBottom ();
			include ('includes/PDFTransDOPageHeaderPortrait.inc');
		}*/
		
		/*Print a column vertical line  with enough space for the footer*/
		/*draw the vertical column lines to 4 lines shy of the bottom
		to leave space for DO footer info ie totals etc*/
		$pdf->line($Left_Margin+78, $TopOfColHeadings+12,$Left_Margin+78,$Bottom_Margin+(4*$line_height));

		/*Print a column vertical line */
		//$pdf->line($Left_Margin+268, $TopOfColHeadings+12,$Left_Margin+268,$Bottom_Margin+(4*$line_height));

		/*Print a column vertical line */
		//$pdf->line($Left_Margin+348, $TopOfColHeadings+12,$Left_Margin+348,$Bottom_Margin+(4*$line_height));

		/*Print a column vertical line */
		//$pdf->line($Left_Margin+388, $TopOfColHeadings+12,$Left_Margin+388,$Bottom_Margin+(4*$line_height));

		/*Print a column vertical line */
		$pdf->line($Left_Margin+388, $TopOfColHeadings+12,$Left_Margin+388,$Bottom_Margin+(4*$line_height));

		$pdf->line($Left_Margin+448, $TopOfColHeadings+12,$Left_Margin+448,$Bottom_Margin+(4*$line_height));

		/*Rule off at bottom of the vertical lines */
		$pdf->line($Left_Margin, $Bottom_Margin+(4*$line_height),$Page_Width-$Right_Margin,$Bottom_Margin+(4*$line_height));

		/*Now print out the footer and totals */

		//$DisplaySubTot = locale_number_format($myrow['ovamount'],$myrow['decimalplaces']);
		//$DisplayFreight = locale_number_format($myrow['ovfreight'],$myrow['decimalplaces']);
		//$DisplayTax = locale_number_format($myrow['ovgst'],$myrow['decimalplaces']);
		//$DisplayTotal = locale_number_format($myrow['ovfreight']+$myrow['ovgst']+$myrow['ovamount'],$myrow['decimalplaces']);

		/*Print out the DO text entered */
		$YPos = $Bottom_Margin+(3*$line_height);
	
		/* Print out the payment terms */
  		//$pdf->addTextWrap($Left_Margin+5,$YPos+3,280,$FontSize,_('Payment Terms') . ': ' . $myrow['terms']);

		//$FontSize =8;
		//$LeftOvers=explode('\r\n',DB_escape_string($myrow['invtext']));
		//for ($i=0;$i<sizeOf($LeftOvers);$i++) {
		//	$pdf->addText($Left_Margin+5, $YPos-8-($i*8), $FontSize, $LeftOvers[$i]);
		//}
		//$FontSize = 10;

		//$pdf->addText($Page_Width-$Right_Margin-220, $YPos+12,$FontSize, _('Sub Total'));
		//$LeftOvers = $pdf->addTextWrap($Left_Margin+450,$YPos+5,72,$FontSize,$DisplaySubTot, 'right');

		//$pdf->addText($Page_Width-$Right_Margin-220, ($YPos+12)-$line_height+5,$FontSize, _('Freight'));
		//$LeftOvers = $pdf->addTextWrap($Left_Margin+450,$YPos-$line_height+5,72,$FontSize,$DisplayFreight, 'right');

		//$pdf->addText($Page_Width-$Right_Margin-220, ($YPos+12)-(2*$line_height)+5,$FontSize, _('Tax'));
		//$LeftOvers = $pdf->addTextWrap($Left_Margin+450,$YPos-(2*$line_height)+5,72, $FontSize,$DisplayTax, 'right');

		/*rule off for total */
		//$pdf->line($Page_Width-$Right_Margin-222, $YPos-(2*$line_height),$Page_Width-$Right_Margin,$YPos-(2*$line_height));

		/*vertical to separate totals from comments and ROMALPA */
		//$pdf->line($Page_Width/2, $YPos+$line_height,$Page_Width/2,$Bottom_Margin);
		
		$FontSize=10;
		
		//if(!$NewPageRequired)
		//{
		//$pdf->addText($Page_Width-$Right_Margin-390, ($YPos+6) - ($line_height*-0.5),$FontSize, _('Acknowledged Receipt by:'));
		
		//$pdf->line($Page_Width-$Right_Margin-288, $YPos+$line_height,$Page_Width-$Right_Margin-288,$Bottom_Margin);
		//$pdf->addText($Page_Width-$Right_Margin-280, ($YPos+6) - ($line_height*1),$FontSize, _('........................................................'));
		//$pdf->addText($Page_Width-$Right_Margin-280, ($YPos+6) - ($line_height*1.7),$FontSize, _('Name:'));
		//$pdf->addText($Page_Width-$Right_Margin-280, ($YPos+6) - ($line_height*2.4),$FontSize, _('Date:'));
		
		//$pdf->line($Left_Margin+388, $YPos+$line_height,$Left_Margin+388,$Bottom_Margin);
		//$pdf->addText($Left_Margin+390, ($YPos+6) - ($line_height*-0.5),$FontSize, _('Company Stamp:'));
		//}
		//$YPos+=10;
		//$pdf->addText($Page_Width-$Right_Margin-220, ($YPos+6) - ($line_height*3),$FontSize, _('TOTAL INVOICE'));
		//$FontSize=8;
		
		//By Edward 20120717
		$pdf->addText($Left_Margin+10,$YPos-60,$FontSize, "Prepared By:");
		$pdf->addText($Left_Margin+10,$YPos-60-$FontSize*4,$FontSize, "....................................");
		$pdf->addText($Left_Margin+10,$YPos-60-$FontSize*5,$FontSize, "Name:");
		$pdf->addText($Left_Margin+10,$YPos-60-$FontSize*6,$FontSize, $_SESSION['CompanyRecord']['coyname']);
		
		$pdf->addText($Page_Width-$Right_Margin-220,$YPos-60,$FontSize, "Accepted By:");
		$pdf->addText($Page_Width-$Right_Margin-220,$YPos-60-$FontSize*4,$FontSize, "....................................");
		$pdf->addText($Page_Width-$Right_Margin-220,$YPos-60-$FontSize*5,$FontSize, "Name:");
		$pdf->addText($Page_Width-$Right_Margin-220,$YPos-60-$FontSize*6,$FontSize, $myrow['name']);
		//End of addition by Edward 20120717
	    
		//20140825 YS Chin: reactivated Romalpa Clauses for DO
		$LeftOvers = $pdf->addTextWrap($Left_Margin+10,$YPos,500,$FontSize,$_SESSION['RomalpaClause']);
		while (mb_strlen($LeftOvers)>0 AND $YPos > $Bottom_Margin){
			$YPos -=10;
			$LeftOvers = $pdf->addTextWrap($Left_Margin+10,$YPos,500,$FontSize,$LeftOvers);
		}
		
		/* Add Images for Visa / Mastercard / Paypal */
		//if (file_exists('companies/' . $_SESSION['DatabaseName'] . '/payment.jpg')) {
		//	$pdf->addJpegFromFile('companies/' . $_SESSION['DatabaseName'] . '/payment.jpg',$Page_Width/2 -60,$YPos-15,0,20);
		//}
		
		// Print Bank acount details if available and default for invoices is selected
		//$pdf->addText($Page_Width-$Right_Margin-450, $YPos - ($line_height*3)+22,$FontSize, $DefaultBankAccountCode . '  ' . $DefaultBankAccountNumber);
		//$FontSize=10;
	
		//$LeftOvers = $pdf->addTextWrap($Left_Margin+450,35,72, $FontSize,$DisplayTotal, 'right');
	    } /* end of check to see that there was an DO record to print */

	    $FromTransNo++;
	} /* end loop to print DOs */

	if (isset($_GET['Email'])){ //email the DO to address supplied
		include ('includes/htmlMimeMail.php');
		$FromTransNo--; //reverse the increment to retain the correct transaction number
		$FileName = $_SESSION['reports_dir'] . '/' . $_SESSION['DatabaseName'] . '_' . $InvOrCredit . '_' . $_GET['FromTransNo'] . '.pdf';
		$pdf->Output($FileName,'F');
		$mail = new htmlMimeMail();

		$Attachment = $mail->getFile($FileName);
		$mail->setText(_('Please find attached') . ' ' . $InvOrCredit . ' ' . $_GET['FromTransNo'] );
		$mail->SetSubject($InvOrCredit . ' ' . $_GET['FromTransNo']);
		$mail->addAttachment($Attachment, $FileName, 'application/pdf');
		$mail->setFrom($_SESSION['CompanyRecord']['coyname'] . ' <' . $_SESSION['CompanyRecord']['email'] . '>');
		$result = $mail->send(array($_GET['Email']));

		unlink($FileName); //delete the temporary file
			$Title = _('Emailing') . ' ' .$InvOrCredit . ' ' . _('Number') . ' ' . $FromTransNo;
			include('includes/header.php');
			echo '<p>' . $InvOrCredit . ' '  . _('number') . ' ' . $FromTransNo . ' ' . _('has been emailed to') . ' ' . $_GET['Email'];
			include('includes/footer.php');
		exit;

	} else { //its not an email just print the DO to PDF
		$pdf->OutputD($_SESSION['DatabaseName'] . '_' . $InvOrCredit . '_' . $FirstTrans. '.pdf');

	}
	$pdf->__destruct();
} else { /*The option to print PDF was not hit */

	//20140912 YS Chin: rectify variable name from $Title to #Title
	$Title=_('Select Delivery Order To Print');
	include('includes/header.php');

	if (!isset($FromTransNo) OR $FromTransNo=='') {

	/*if FromTransNo is not set then show a form to allow input of either a single DO number or a range of DOs to be printed. Also get the last DO number created to show the user where the current range is up to */

		echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '" method="post">';
		echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';

		echo '<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/printer.png" title="' . _('Print') . '" alt="" />' . ' ' . _('Print Delivery Order (Portrait Mode)') . '</p>';
	
		echo '<table class="selection">';
		echo '<tr>
				<td width="50%">' . _('Start Delivery Order number to print') . '</td>
				<td width="50%"><input class="number" type="text" max="6" size="7" name="FromTransNo" /></td>
			</tr>';
		echo '<tr>
				<td>' . _('End Delivery Order number to print') . '</td>
				<td><input class="number" type="text" max="6" size="7" name="ToTransNo" /></td>
			</tr>
			</table>';
		echo '<div class="centre">
				<br />
				<!--input type="submit" name="Print" value="' . _('Print Preview') . '" /-->
				<br />
				<input type="submit" name="PrintPDF" value="' . _('Print PDF') . '" />
			</div>';

		$sql = "SELECT typeno FROM systypes WHERE typeid=10";

		$result = DB_query($sql,$db);
		$myrow = DB_fetch_row($result);

		echo '<div class="page_help_text"><b>' . _('The last DO created was number') . ' ' . $myrow[0] . '</b><br />' . _('If only a single DO is required') . ', ' . _('enter the DO number to print in the Start transaction number to print field and leave the End transaction number to print field blank') . '. ' . _('Only use the end invoice to print field if you wish to print a sequential range of invoices') . '';

	} else {

		while ($FromTransNo <= $_POST['ToTransNo']){

	/*retrieve the DO details from the database to print
	notice that salesorder record must be present to print the DO purging of sales orders will
	nobble the DO reprints */

			

			   $sql = "SELECT debtortrans.trandate,
							debtortrans.ovamount,
							debtortrans.ovdiscount,
							debtortrans.ovfreight,
							debtortrans.ovgst,
							debtortrans.rate,
							debtortrans.invtext,
							debtortrans.consignment,
							debtorsmaster.name,
							debtorsmaster.address1,
							debtorsmaster.address2,
							debtorsmaster.address3,
							debtorsmaster.address4,
							debtorsmaster.address5,
							debtorsmaster.address6,
							debtorsmaster.currcode,
							salesorders.deliverto,
							salesorders.deladd1,
							salesorders.deladd2,
							salesorders.deladd3,
							salesorders.deladd4,
							salesorders.deladd5,
							salesorders.deladd6,
							salesorders.customerref,
							salesorders.orderno,
							salesorders.orddate,
							shippers.shippername,
							custbranch.brname,
							custbranch.braddress1,
							custbranch.braddress2,
							custbranch.braddress3,
							custbranch.braddress4,
							custbranch.braddress5,
							custbranch.braddress6,
							salesman.salesmanname,
							debtortrans.debtorno,
							currencies.decimalplaces
						FROM debtortrans INNER JOIN debtorsmaster
						ON debtortrans.debtorno=debtorsmaster.debtorno
						INNER JOIN custbranch
						ON debtortrans.debtorno=custbranch.debtorno
						AND debtortrans.branchcode=custbranch.branchcode
						INNER JOIN salesorders
						ON debtortrans.order_ = salesorders.orderno
						INNER JOIN shippers
						ON debtortrans.shipvia=shippers.shipper_id
						INNER JOIN salesman
						ON custbranch.salesman=salesman.salesmancode
						INNER JOIN locations
						ON salesorders.fromstkloc=locations.loccode
						INNER JOIN paymentterms
						ON debtorsmaster.paymentterms=paymentterms.termsindicator
						INNER JOIN currencies
						ON debtorsmaster.currcode=currencies.currabrev
						WHERE debtortrans.type=10
						AND debtortrans.transno='" . $FromTransNo . "'";
			

			$result=DB_query($sql,$db);
			if (DB_num_rows($result)==0 OR DB_error_no($db)!=0) {
				echo '<p>' . _('There was a problem retrieving the DO or credit note details for note number') . ' ' . $InvoiceToPrint . ' ' . _('from the database') . '. ' . _('To print a DO, the sales order record, the customer transaction record and the branch record for the customer must not have been purged') . '. ' . _('To print a credit note only requires the customer, transaction, salesman and branch records be available');
				if ($debug==1){
					prnMsg( _('The SQL used to get this information that failed was') . '<br />' . $sql,'warn');
				}
				break;
				include('includes/footer.php');
				exit;
			} elseif (DB_num_rows($result)==1){

				$myrow = DB_fetch_array($result);
	/* Then there's an DO (or credit note) to print. So print out the DO header and GST Number from the company record */
				if (count($_SESSION['AllowedPageSecurityTokens'])==1 AND in_array(1, $_SESSION['AllowedPageSecurityTokens']) AND $myrow['debtorno'] != $_SESSION['CustomerID']){
					echo '<p><font color="red" size="4">' . _('This transaction is addressed to another customer and cannot be displayed for privacy reasons') . '. ' . _('Please select only transactions relevant to your company');
					exit;
				}

				$ExchRate = $myrow['rate'];
				$PageNumber = 1;

				echo '<table class="table1">
						<tr>
							<td valign=top width="10%"><img src="' . $_SESSION['LogoFile'] . '" /></td>
							<td bgcolor="#bbbbbb"><b>';

				   echo '<font size="4">' . _('DELIVERY ORDER') . ' ';
				
				echo '</b>' . _('Number') . ' ' . $FromTransNo . '</font>
					<br /><font size="1">' . _('Tax Authority Ref') . '. ' . $_SESSION['CompanyRecord']['gstno'] . '</td>
					</tr>
					</table>';

	/*Now print out the logo and company name and address */
				echo '<table class"table1">
						<tr>
							<td><font size="4" color="#333"><b>' . $_SESSION['CompanyRecord']['coyname'] . '</b></font>
							<br />';
				echo $_SESSION['CompanyRecord']['regoffice1'] . '<br />';
				echo $_SESSION['CompanyRecord']['regoffice2'] . '<br />';
				echo $_SESSION['CompanyRecord']['regoffice3'] . '<br />';
				echo $_SESSION['CompanyRecord']['regoffice4'] . '<br />';
				echo $_SESSION['CompanyRecord']['regoffice5'] . '<br />';
				echo $_SESSION['CompanyRecord']['regoffice6'] . '<br />';
				echo _('Telephone') . ': ' . $_SESSION['CompanyRecord']['telephone'] . '<br />';
				echo _('Facsimile') . ': ' . $_SESSION['CompanyRecord']['fax'] . '<br />';
				echo _('Email') . ': ' . $_SESSION['CompanyRecord']['email'] . '<br />';

				echo '</td>
					<td width="50%" class="number">';

	/*Now the customer charged to details in a sub table within a cell of the main table*/

				echo '<table class="table1">
						<tr>
							<td align="left" bgcolor="#bbbbbb"><b>' . _('Charge To') . ':</b></td>
						</tr>
						<tr>
							<td bgcolor="#eeeeee">';
				echo $myrow['name'] .
					'<br />' . $myrow['address1'] .
					'<br />' . $myrow['address2'] .
					'<br />' . $myrow['address3'] .
					'<br />' . $myrow['address4'] .
					'<br />' . $myrow['address5'] .
					'<br />' . $myrow['address6'];

				echo '</td>
					</tr>
					</table>';
				/*end of the small table showing charge to account details */
				echo _('Page') . ': ' . $PageNumber;
				echo '</td>
					</tr>
					</table>';
				/*end of the main table showing the company name and charge to details */

				
				   echo '<table class="table1">
				   		<tr>
				   			<td align=left bgcolor="#bbbbbb"><b>' . _('Charge Branch') . ':</b></td>
							<td align=left bgcolor="#bbbbbb"><b>' . _('Delivered To') . ':</b></td>
						</tr>';
				   echo '<tr>
				   		<td bgcolor="#eeeeee">' .$myrow['brname'] .
									'<br />' . $myrow['braddress1'] .
									'<br />' . $myrow['braddress2'] .
									'<br />' . $myrow['braddress3'] .
									'<br />' . $myrow['braddress4'] .
									'<br />' . $myrow['braddress5'] .
									'<br />' . $myrow['braddress6'] .
						'</td>';

				   echo '<td bgcolor="#eeeeee">' . $myrow['deliverto'] .
									'<br />' . $myrow['deladd1'] .
									'<br />' . $myrow['deladd2'] .
									'<br />' . $myrow['deladd3'] .
									'<br />' . $myrow['deladd4'] .
									'<br />' . $myrow['deladd5'] .
									'<br />' . $myrow['deladd6'] .
						'</td>';
				   echo '</tr>
				   </table><hr>';

				   echo '<table class="table1">
				   		<tr>
							<td align=left bgcolor="#bbbbbb"><b>' . _('Your Order Ref') . '</b></td>
							<td align=left bgcolor="#bbbbbb"><b>' . _('Our Order No') . '</b></td>
							<td align=left bgcolor="#bbbbbb"><b>' . _('Order Date') . '</b></td>
							<td align=left bgcolor="#bbbbbb"><b>' . _('DO Date') . '</b></td>
							<td align=left bgcolor="#bbbbbb"><b>' . _('Sales Person') . '</font></b></td>
							<td align=left bgcolor="#bbbbbb"><b>' . _('Shipper') . '</b></td>
							<td align=left bgcolor="#bbbbbb"><b>' . _('Consignment Ref') . '</b></td>
						</tr>';
				   	echo '<tr>
							<td bgcolor="#EEEEEE">' . $myrow['customerref'] . '</td>
							<td bgcolor="#EEEEEE">' .$myrow['orderno'] . '</td>
							<td bgcolor="#EEEEEE">' . ConvertSQLDate($myrow['orddate']) . '</td>
							<td bgcolor="#EEEEEE">' . ConvertSQLDate($myrow['trandate']) . '</td>
							<td bgcolor="#EEEEEE">' . $myrow['salesmanname'] . '</td>
							<td bgcolor="#EEEEEE">' . $myrow['shippername'] . '</td>
							<td bgcolor="#EEEEEE">' . $myrow['consignment'] . '</td>
						</tr>
					</table>';

				   $sql ="SELECT stockmoves.stockid,
						   		stockmaster.description,
								-stockmoves.qty as quantity,
								stockmoves.discountpercent,
								((1 - stockmoves.discountpercent) * stockmoves.price * " . $ExchRate . "* -stockmoves.qty) AS fxnet,
								(stockmoves.price * " . $ExchRate . ") AS fxprice,
								stockmoves.narrative,
								stockmaster.units,
								stockmaster.decimalplaces
							FROM stockmoves INNER JOIN stockmaster
							ON stockmoves.stockid = stockmaster.stockid
							WHERE stockmoves.type=10
							AND stockmoves.transno='" . $FromTransNo . "'
							AND stockmoves.show_on_inv_crds=1";

				
				echo '<hr>';
				echo '<div class="centre"><font size="2">' . _('All amounts stated in') . ' ' . $myrow['currcode'] . '</font></div>';

				$result=DB_query($sql,$db);
				if (DB_error_no($db)!=0) {
					echo '<br />' . _('There was a problem retrieving the DO or credit note stock movement details for DO number') . ' ' . $FromTransNo . ' ' . _('from the database');
					if ($debug==1){
						 echo '<br />' . _('The SQL used to get this information that failed was') . '<br />' . $sql;
					}
					exit;
				}

				if (DB_num_rows($result)>0){
					echo '<table class="table1">
							<tr>
								<th>' . _('Item Code') . '</th>
								<th>' . _('Item Description') . '</th>
								<th>' . _('Quantity') . '</th>
								<th>' . _('Unit') . '</th>
								<th>' . _('Price') . '</th>
								<th>' . _('Discount') . '</th>
								<th>' . _('Net') . '</th>
							</tr>';

					$LineCounter =17;
					$k=0;	//row colour counter

					while ($myrow2=DB_fetch_array($result)){

					      if ($k==1){
						  $RowStarter = '<tr class="EvenTableRows">';
						  $k=0;
					      } else {
						  $RowStarter = '<tr class="OddTableRows">';
						  $k=1;
					      }

					      echo $RowStarter;

					      $DisplayPrice =locale_number_format($myrow2['fxprice'],$myrow['decimalplaces']);
					      $DisplayQty = locale_number_format($myrow2['quantity'],$myrow2['decimalplaces']);
					      $DisplayNet = locale_number_format($myrow2['fxnet'],$myrow['decimalplaces']);

					      if ($myrow2['discountpercent']==0){
						   $DisplayDiscount ='';
					      } else {
						   $DisplayDiscount = locale_number_format($myrow2['discountpercent']*100,2) . '%';
					      }

					      printf ('<td>%s</td>
						      		<td>%s</td>
									<td class="number">%s</td>
									<td class="number">%s</td>
									<td class="number">%s</td>
									<td class="number">%s</td>
									<td class="number">%s</td>
									</tr>',
									$myrow2['stockid'],
									$myrow2['description'],
									$DisplayQty,
									$myrow2['units'],
									$DisplayPrice,
									$DisplayDiscount,
									$DisplayNet);

					      if (mb_strlen($myrow2['narrative'])>1){
					      		echo $RowStarter .
									'<td></td>
									<td colspan="6">' . $myrow2['narrative'] . '</td>
									</tr>';
							$LineCounter++;
					      }

					      $LineCounter++;

					      if ($LineCounter == ($_SESSION['PageLength'] - 2)){

						/* head up a new DO page */

						   $PageNumber++;
						   echo '</table>
								<table class="table1">
								<tr>
									<td valign="top"><img src="' . $_SESSION['LogoFile'] . '" /></td>
									<td bgcolor="#bbbbbb"><b>';

						   	    echo '<font size="4">' . _('DELIVERY ORDER') . ' ';
						   
						   echo '</b>' . _('Number') . ' ' . $FromTransNo . '</font><br /><font size="1">' . _('GST Number') . ' - ' . $_SESSION['CompanyRecord']['gstno'] . '</td>
							</tr>
							</table>';

	/*Now print out company name and address */
						    echo '<table class="table1">
							<tr>
							<td><font size="4" color="#333"><b>' . $_SESSION['CompanyRecord']['coyname'] . '</b></font><br />';
						    echo $_SESSION['CompanyRecord']['regoffice1'] . '<br />';
						    echo $_SESSION['CompanyRecord']['regoffice2'] . '<br />';
						    echo $_SESSION['CompanyRecord']['regoffice3'] . '<br />';
						    echo $_SESSION['CompanyRecord']['regoffice4'] . '<br />';
						    echo $_SESSION['CompanyRecord']['regoffice5'] . '<br />';
						    echo $_SESSION['CompanyRecord']['regoffice6'] . '<br />';
						    echo _('Telephone') . ': ' . $_SESSION['CompanyRecord']['telephone'] . '<br />';
						    echo _('Facsimile') . ': ' . $_SESSION['CompanyRecord']['fax'] . '<br />';
						    echo _('Email') . ': ' . $_SESSION['CompanyRecord']['email'] . '<br />';
						    echo '</td><td class="number">' . _('Page') . ': ' .  $PageNumber . '</td>
								</tr>
								</table>';
						    echo '<table class="table1">
									<tr>
										<th>' . _('Item Code') . '</th>
										<th>' . _('Item Description') . '</th>
										<th>' . _('Quantity') . '</th>
										<th>' . _('Unit') . '</th>
										<th>' . _('Price') . '</th>
										<th>' . _('Discount') . '</th>
										<th>' . _('Net') . '</th>
									</tr>';

						    $LineCounter = 10;

					      } //end if need a new page headed up
					} //end while there are line items to print out
					echo '</table>';
				} /*end if there are stock movements to show on the DO*/

				/* check to see enough space left to print the totals/footer */
				$LinesRequiredForText = floor(mb_strlen($myrow['invtext'])/140);

				if ($LineCounter >= ($_SESSION['PageLength'] - 8 - $LinesRequiredForText)){

					/* head up a new DO page */

					$PageNumber++;
					echo '<table class="table1">
							<tr>
								<td valign="top"><img src="' . $_SESSION['LogoFile'] . '" /></td>
								<td bgcolor="#bbbbbb"><b>';
									echo '<font size="4">' . _('DELIVERY ORDER') .' ';
									echo '</b>' . _('Number') . ' ' . $FromTransNo . '</font>
									<br />
								</td>
							</tr>
						</table>';

	/*Print out the logo and company name and address */
					echo '<table class="table1">
							<tr>
								<td><font size="4" color="#333"><b>' . $_SESSION['CompanyRecord']['coyname'] . '</b></font><br />';
					echo $_SESSION['CompanyRecord']['regoffice1'] . '<br />';
					echo $_SESSION['CompanyRecord']['regoffice2'] . '<br />';
					echo $_SESSION['CompanyRecord']['regoffice3'] . '<br />';
					echo $_SESSION['CompanyRecord']['regoffice4'] . '<br />';
					echo $_SESSION['CompanyRecord']['regoffice5'] . '<br />';
					echo $_SESSION['CompanyRecord']['regoffice6'] . '<br />';
					echo _('Telephone') . ': ' . $_SESSION['CompanyRecord']['telephone'] . '<br />';
					echo _('Facsimile') . ': ' . $_SESSION['CompanyRecord']['fax'] . '<br />';
					echo _('Email') . ': ' . $_SESSION['CompanyRecord']['email'] . '<br />';
					echo '</td><td class="number">' . _('Page') . ': ' . $PageNumber . '</td>
						</tr>
						</table>';
					echo '<table class="table1">
							<tr>
								<th>' . _('Item Code') . '</th>
								<th>' . _('Item Description') . '</th>
								<th>' . _('Quantity') . '</th>
								<th>' . _('Unit') . '</th>
								<th>' . _('Price') . '</th>
								<th>' . _('Discount') . '</th>
								<th>' . _('Net') . '</th>
							</tr>
						</table>';

					$LineCounter = 10;
				}

	/*Space out the footer to the bottom of the page */

				echo '<br /><br />' . $myrow['invtext'];

				$LineCounter=$LineCounter+2+$LinesRequiredForText;
				while ($LineCounter < ($_SESSION['PageLength'] -6)){
					echo '<br />';
					$LineCounter++;
				}

				/*Now print out the footer and totals */
				$DisplaySubTot = locale_number_format($myrow['ovamount'],$myrow['decimalplaces']);
				$DisplayFreight = locale_number_format($myrow['ovfreight'],$myrow['decimalplaces']);
				$DisplayTax = locale_number_format($myrow['ovgst'],$myrow['decimalplaces']);
				$DisplayTotal = locale_number_format($myrow['ovfreight']+$myrow['ovgst']+$myrow['ovamount'],$myrow['decimalplaces']);
			     
				/*Print out the DO text entered */
				echo '<table class="table1"><tr>
					<td class="number">' . _('Sub Total') . '</td>
					<td class="number" bgcolor="#EEEEEE" width="15%">' . $DisplaySubTot . '</td></tr>';
				echo '<tr><td class="number">' . _('Freight') . '</td>
					<td class="number" bgcolor="#EEEEEE">' . $DisplayFreight . '</td></tr>';
				echo '<tr><td class="number">' . _('Tax') . '</td>
					<td class="number" bgcolor="#EEEEEE">' . $DisplayTax . '</td></tr>';
				
				echo '<tr><td class="number"><b>' . _('TOTAL INVOICE') . '</b></td>
				   <td class="number" bgcolor="#EEEEEE"><u><b>' . $DisplayTotal . '</b></u></td></tr>';
			   
				
				echo '</table>';
			} /* end of check to see that there was an DO record to print */
			$FromTransNo++;
		} /* end loop to print DOs */
	} /*end of if FromTransNo exists */
	include('includes/footer.php');

} /*end of else not PrintPDF */



function PrintLinesToBottom () {

	global $pdf;
	global $PageNumber;
	global $TopOfColHeadings;
	global $Left_Margin;
	global $Bottom_Margin;
	global $line_height;

	/*draw the vertical column lines right to the bottom */
	$pdf->line($Left_Margin+78, $TopOfColHeadings+12,$Left_Margin+78,$Bottom_Margin);

	/*Print a column vertical line */
	$pdf->line($Left_Margin+268, $TopOfColHeadings+12,$Left_Margin+268,$Bottom_Margin);

	/*Print a column vertical line */
	$pdf->line($Left_Margin+348, $TopOfColHeadings+12,$Left_Margin+348,$Bottom_Margin);

	/*Print a column vertical line */
	$pdf->line($Left_Margin+388, $TopOfColHeadings+12,$Left_Margin+388,$Bottom_Margin);

	/*Print a column vertical line */
	$pdf->line($Left_Margin+418, $TopOfColHeadings+12,$Left_Margin+418,$Bottom_Margin);

	$pdf->line($Left_Margin+448, $TopOfColHeadings+12,$Left_Margin+448,$Bottom_Margin);

	$PageNumber++;

}

?>
