<?php

/* $Revision: 1.26 $ */

$PageSecurity = 2;
include('includes/session.inc');
include('includes/SQL_CommonFunctions.inc');

if(!isset($_GET['indentno']) && !isset($_POST['indentno'])){
        $title = _('Select a Purchase Order');
        include('includes/header.inc');
        echo '<div class="centre"><br><br><br>';
        prnMsg( _('Select a Purchase Order Number to Print before calling this page') , 'error');
        echo '<br><br><br><table class="table_index">
		<tr><td class="menu_group_item">
                <li><a href="'. $rootpath . '/PO_SelectOSPurchOrder.php?'.SID .'">' . _('Outstanding Purchase Orders') . '</a></li>
                <li><a href="'. $rootpath . '/PO_SelectPurchOrder.php?'. SID .'">' . _('Purchase Order Inquiry') . '</a></li>
                </td></tr></table></div><br><br><br>';
        include('includes/footer.inc');
        exit();

	echo '<div class="centre"><br><br><br>' . _('This page must be called with a purchase order number to print');
	echo '<br><a href="'. $rootpath . '/index.php?' . SID . '">' . _('Back to the menu') . '</a></div>';
	exit;
}

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

$title = _('Print Indent Number').' '. $indentno;

$sql='SELECT indent_status
		FROM indents
		WHERE indent_id='.$indentno;
$result=DB_query($sql, $db);
$myrow=DB_fetch_array($result);
$OrderStatus=$myrow['indent_status'];

if ($OrderStatus!=_('Authorised') and $OrderStatus!=_('Printed')) {
	include('includes/header.inc');
	prnMsg( _('Purchase orders can only be printed once they have been authorised').'. '.
		_('This order is currently at a status of').' '.$OrderStatus,'warn');
	include('includes/footer.inc');
	exit;
}

$ViewingOnly = 0;
if (isset($_GET['ViewingOnly']) && $_GET['ViewingOnly']!='') {
	$ViewingOnly = $_GET['ViewingOnly'];
} elseif (isset($_POST['ViewingOnly']) && $_POST['ViewingOnly']!='') {
	$ViewingOnly = $_POST['ViewingOnly'];
}


if (isset($_POST['DoIt'])  AND ($_POST['PrintOrEmail']=='Print' || $ViewingOnly==1) ){
	$MakePDFThenDisplayIt = True;
} elseif (isset($_POST['DoIt']) AND $_POST['PrintOrEmail']=='Email' AND strlen($_POST['EmailTo'])>6){
	$MakePDFThenEmailIt = True;
}

if (isset($indentno) && $indentno != "" && $indentno > 0){
	//Check this up front. Note that the myrow recordset is carried into the actual make pdf section
	/*retrieve the order details from the database to print */
	$ErrMsg = _('There was a problem retrieving the purchase order header details for Order Number'). ' ' . $OrderNo .
			' ' . _('from the database');
	$sql = "SELECT *
		FROM indents 
		WHERE indent_id = " . $indentno;
	$result=DB_query($sql,$db, $ErrMsg);

	if (DB_num_rows($result)==0){ /*There is ony one order header returned */

		$title = _('Print Indent Error');
		include('includes/header.inc');
		echo '<div class="centre"><br><br><br>';
		prnMsg( _('Unable to Locate Indent(190+$y) Number') . ' : ' . $indentno . ' ', 'error');
		echo '</div><br><br><br>';
		include('includes/footer.inc');
		exit();

	} elseif (DB_num_rows($result)>0){ /*There is only one order header returned */

	   
//if there is a valid order number


	
	$PaperSize = 'A4';

	include('includes/PDFStarter.php');

	$pdf->addinfo('Title', _('Indent Details') );
	$pdf->addinfo('Subject', _('Indent Number').' ' . $indentno);

	$line_height=16;
	   /* Then there's an order to print and its not been printed already (or its been flagged for reprinting)
	   Now ... Has it got any line items */

	   $PageNumber = 1;
	   $ErrMsg = _('There was a problem retrieving the line details for indent') . ' ' . $indentno . ' ' .
			_('from the database');
	   $sql = "SELECT * from indents
			WHERE indent_id =" . $indentno;
	   $result=DB_query($sql,$db);

	   if (DB_num_rows($result)>0){
	   /*Yes there are line items to start the ball rolling with a page header */

		$FontSize = 8;
	$YPos = $Page_Height - $Top_Margin;
	$pdf->selectFont('./fonts/Helvetica.afm');
	$pdf->addText($Left_Margin,$YPos,$FontSize,$_SESSION['CompanyRecord']['coyname']);
	$pdf->addText($Page_Width-$Right_Margin-120,$YPos,$FontSize, _('Printed'). ': ' . Date($_SESSION['DefaultDateFormat'])  . '   ' . _('Page'). ' ' . $PageNumber);

	$YPos -= $line_height;
	$FontSize =10;
	$pdf->selectFont('./fonts/Helvetica-Bold.afm');
	$Heading = _('Indent Details ') . $showFrom . $showTo;
	$pdf->addText($Left_Margin, $YPos, $FontSize, $Heading);
	
	
	$FontSize = 8;


		$POLine=DB_fetch_array($result);

		$LeftOvers = $pdf->addTextWrap($Left_Margin+1,$YPos-25,130,9,'Indent No.', 'left');
		$LeftOvers = $pdf->addTextWrap($Left_Margin+1+90,$YPos-25,130,9,$POLine['indent_id'], 'left');
		$LeftOvers = $pdf->addTextWrap($Left_Margin+1+90+75,$YPos-25,130,9,'Indent Status', 'left');
		$LeftOvers = $pdf->addTextWrap($Left_Margin+1+90+75+70,$YPos-25,130,9,$POLine['indent_status'], 'left');
		
		$LeftOvers = $pdf->addTextWrap($Left_Margin+1,$YPos-45,130,9,'From Location', 'left');
		
		$sql = "SELECT loccode, locationname FROM locations where loccode = '".$POLine['fromloccode']."'";
		$resultStkLocs = DB_query($sql,$db);
		$myrow=DB_fetch_array($resultStkLocs);
		
		$LeftOvers = $pdf->addTextWrap($Left_Margin+1+90,$YPos-45,130,9,$myrow['locationname'], 'left');
			
		$LeftOvers = $pdf->addTextWrap($Left_Margin+1+60+75,$YPos-45,130,9,'Status Comments', 'left');
		$LeftOvers = $pdf->addTextWrap($Left_Margin+1+60+75+100,$YPos-45,130,9,$POLine['status_comments'], 'left');
		
		$sql = "SELECT loccode, locationname FROM locations where loccode = '".$POLine['toloccode']."'";
		$resultStkLocs = DB_query($sql,$db);
		$myrow=DB_fetch_array($resultStkLocs);
		
		$LeftOvers = $pdf->addTextWrap($Left_Margin+1,$YPos-65,130,9,'To Location', 'left');
		$LeftOvers = $pdf->addTextWrap($Left_Margin+1+90,$YPos-65,130,9,$myrow['locationname'], 'left');
		
		$LeftOvers = $pdf->addTextWrap($Left_Margin+1,$YPos-85,130,9,'Raised By', 'left');
		$LeftOvers = $pdf->addTextWrap($Left_Margin+1+90,$YPos-85,130,9,$POLine['raised_by'], 'left');		
			
		$LeftOvers = $pdf->addTextWrap($Left_Margin+1,$YPos-105,130,9,'Remarks', 'left');
		$LeftOvers = $pdf->addTextWrap($Left_Margin+1,$YPos-125,130,9,$POLine['remarks'], 'left');
			
		$FontSize = 10;
		
		

		
		/*Draw a rectangle to put the headings in     */
		$pdf->line($Page_Width-$Right_Margin, $YPos-145,$Left_Margin, $YPos-145);
		$pdf->line($Page_Width-$Right_Margin, $YPos-165,$Left_Margin, $YPos-165);
		$pdf->line($Page_Width-$Right_Margin, $YPos-145,$Page_Width-$Right_Margin, $YPos-165);
		$pdf->line($Left_Margin, $YPos-145,$Left_Margin, $YPos-165);
		
		/*set up the headings */
		$Xpos = $Left_Margin+1;
		
		$LeftOvers = $pdf->addTextWrap($Xpos,$YPos-160,220 - $Left_Margin,$FontSize,_('S.No.'),'centre');
		$LeftOvers = $pdf->addTextWrap(120,$YPos-160,60,$FontSize,_('Code'),'centre');
		$LeftOvers = $pdf->addTextWrap(200,$YPos-160,60,$FontSize,_('Description'),'centre');
		$LeftOvers = $pdf->addTextWrap(380,$YPos-160,60,$FontSize,_('Units'),'centre');
		$LeftOvers = $pdf->addTextWrap(470,$YPos-160,60,$FontSize,_('Req. Qty.'),'centre');
		
		$sql = "SELECT * FROM indent_items i
				LEFT JOIN stockmaster s ON s.stockid = i.item_code
				WHERE i.indent_id = $POLine[indent_id]";
		$result = DB_query($sql,$db);
		$i=1;
		$y = 10;
		while($myrow=DB_fetch_array($result)){
			$LeftOvers = $pdf->addTextWrap($Xpos,$YPos-(170+$y),220 - $Left_Margin,$FontSize,$i,'centre');
			$LeftOvers = $pdf->addTextWrap(120,$YPos-(170+$y),60,$FontSize,$myrow['item_code'],'centre');
			$LeftOvers = $pdf->addTextWrap(200,$YPos-(170+$y),60,$FontSize,$myrow['description'],'centre');
			$LeftOvers = $pdf->addTextWrap(380,$YPos-(170+$y),60,$FontSize,$myrow['units'],'centre');
			$LeftOvers = $pdf->addTextWrap(470,$YPos-(170+$y),60,$FontSize,$myrow['req_qty'],'centre');
			$i++;
			$y=$y+10;
		}
		
		$YPos =$YPos - (2*$line_height);

			
			/*increment a line down for the next line item */
			$YPos -= $line_height;

		} //end while there are line items to print out

		

		
		

		//fine code
		
        	
		$pdf->line($Left_Margin, $YPos-(140+$y), $Page_Width-$Right_Margin, $YPos-(140+$y));

		

		
		 
		
	} /*end if there are order details to show on the order*/
    //} /* end of check to see that there was an order selected to print */

    //failed var to allow us to print if the email fails.
    $failed = false;
 //   if ($MakePDFThenDisplayIt){

    	$buf = $pdf->output();
    	$len = strlen($buf);
    	header('Content-type: application/pdf');
    	header('Content-Length: ' . $len);
    	header('Content-Disposition: inline; filename=PurchaseOrder.pdf');
    	header('Expires: 0');
    	header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    	header('Pragma: public');

    	$pdf->stream();

    

} /* There was enough info to either print or email the purchase order */
 else { /*the user has just gone into the page need to ask the question whether to print the order or email it to the supplier */

	include ('includes/header.inc');
	echo '<form action="' . $_SERVER['PHP_SELF'] . '?' . SID . '" method=post target="_blank">';

	if ($ViewingOnly==1){
		echo '<input type=hidden name="ViewingOnly" VALUE=1>';
	}
	echo '<br><br>';
	echo '<input type=hidden name="OrderNo" VALUE="'. $OrderNo. '">';
	echo '<table><tr><td>'. _('Print or Email the Order'). '</td><td>
		<select name="PrintOrEmail">';

	if (!isset($_POST['PrintOrEmail'])){
		$_POST['PrintOrEmail'] = 'Print';
	}

	if ($_POST['PrintOrEmail']=='Print'){
		echo '<option selected VALUE="Print">'. _('Print');
		echo '<option VALUE="Email">' . _('Email');
	} else {
		echo '<option VALUE="Print">'. _('Print');
		echo '<option selected VALUE="Email">'. _('Email');
	}
	echo '</select></td></tr>';

	echo '<tr><td>'. _('Show Amounts on the Order'). '</td><td>
		<select name="ShowAmounts">';
		
	if (!isset($_POST['ShowAmounts'])){
		$_POST['ShowAmounts'] = 'Yes';
	}

	if ($_POST['ShowAmounts']=='Yes'){
		echo '<option selected VALUE="Yes">'. _('Yes');
		echo '<option VALUE="No">' . _('No');
	} else {
		echo '<option VALUE="Yes">'. _('Yes');
		echo '<option selected VALUE="No">'. _('No');
	}
	
	echo '</select></td></tr>';
	if ($_POST['PrintOrEmail']=='Email'){
		$ErrMsg = _('There was a problem retrieving the contact details for the supplier');
		$SQL = "SELECT suppliercontacts.contact,
				suppliercontacts.email
			FROM suppliercontacts INNER JOIN purchorders
			ON suppliercontacts.supplierid=purchorders.supplierno
			WHERE purchorders.orderno=$OrderNo";
		$ContactsResult=DB_query($SQL,$db, $ErrMsg);

		if (DB_num_rows($ContactsResult)>0){
			echo '<tr><td>'. _('Email to') .':</td><td><select name="EmailTo">';
			while ($ContactDetails = DB_fetch_array($ContactsResult)){
				if (strlen($ContactDetails['email'])>2 AND strpos($ContactDetails['email'],'@')>0){
					if ($_POST['EmailTo']==$ContactDetails['email']){
						echo '<option selected VALUE="' . $ContactDetails['email'] . '">' . $ContactDetails['Contact'] . ' - ' . $ContactDetails['email'];
					} else {
						echo '<option VALUE="' . $ContactDetails['email'] . '">' . $ContactDetails['contact'] . ' - ' . $ContactDetails['email'];
					}
				}
			}
			echo '</select></td></tr></table>';
		} else {
			echo '</table><br>';
			prnMsg ( _('There are no contacts defined for the supplier of this order') . '. ' .
				_('You must first set up supplier contacts before emailing an order'), 'error');
			echo '<br>';
		}
	} else {
		echo '</table>';
	}
	echo '<br><div class="centre"><input type=submit name="DoIt" VALUE="' . _('OK') . '"></div>';
	echo '</form>';
	include('includes/footer.inc');
}


?>
