<?php

/* $Revision: 1.20 $ */

/*Through deviousness and cunning, this system allows Purchase Orderss for any date range that recalcuates the p & l balances
and shows the balance sheets as at the end of the period selected - so first off need to show the input of criteria screen
while the user is selecting the criteria the system is posting any unposted transactions */


$PageSecurity = 8;

include ('includes/session.inc');
$title = _('Purchase Orders');
include('includes/SQL_CommonFunctions.inc');
include('includes/AccountSectionsDef.inc'); //this reads in the Accounts Sections array



if ((! isset($_POST['FromPeriod']) AND ! isset($_POST['ToPeriod'])) OR isset($_POST['SelectADifferentPeriod'])){

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

	/*Show a form to allow input of criteria for TB to show */
	echo '<table><tr><td>' . _('Select Period From:') . '</td><td><input name="FromPeriod" maxlength="25" id="FromPeriod" tabindex="1" class="text" style="width: 140px; position: relative; left: 1%;" type="text" readonly="">
				<img src="'.$rootpath.'/images/cal.gif" id="FromPeriod_trigger"  />
	<script type="text/javascript">
				
                  new Calendar({
                          inputField: "FromPeriod",
                          dateFormat: "%d-%m-%Y",
                          trigger: "FromPeriod_trigger",
                          bottomBar: false,
                          onSelect: function() {                                  
                                  this.hide();
                          }
                  });  				 
                </script></td></tr>';
	
	echo '<tr><td>' . _('Select Period To:') .'</td><td><input name="ToPeriod" maxlength="25" id="ToPeriod" tabindex="1" class="text" style="width: 140px; position: relative; left: 1%;" type="text" readonly="">
				<img src="'.$rootpath.'/images/cal.gif" id="ToPeriod_trigger"  />
	<script type="text/javascript">
				
                  new Calendar({
                          inputField: "ToPeriod",
                          dateFormat: "%d-%m-%Y",
                          trigger: "ToPeriod_trigger",
                          bottomBar: false,
                          onSelect: function() {                                  
                                  this.hide();
                          }
                  });  				 
                </script></td></tr></table>';

	echo '<div class="centre"><input type=submit Name="ShowTB" Value="' . _('Submit') .'">';
	echo "<input type=submit Name='PrintPDF' Value='"._('PrintPDF')."'></div>";

/*Now do the posting while the user is thinking about the period to select */

	include ('includes/GLPostings.inc');

} else if (isset($_POST['PrintPDF'])) {
	
	include('includes/PDFStarter.php');
	$PageNumber = 0;
	$FontSize = 10;
	$pdf->addinfo('Title', _('Purchase Orders') );
	$pdf->addinfo('Subject', _('Purchase Orders') );
	$line_height = 12;

	$condition = '';
	$fromPeriod = $_POST['FromPeriod'];
	
	if(!empty($fromPeriod)){
		$condition .= " AND purchorders.orddate >= '".date('Y-m-d',strtotime($fromPeriod))."'";
		$showFrom = 'from '.$fromPeriod;
	}
		
	$toPeriod = $_POST['ToPeriod'];
	if(!empty($toPeriod)){
		$condition .= " AND purchorders.orddate <= '".date('Y-m-d',strtotime($toPeriod))."'";
		$showTo = ' to '.$toPeriod;
	}

	$SQL = "SELECT purchorders.realorderno,
						purchorders.orderno,
						suppliers.suppname,
						purchorders.orddate,
						purchorders.status,
						purchorders.initiator,
						purchorders.requisitionno,
						purchorders.allowprint,
						suppliers.currcode,
						SUM(purchorderdetails.unitprice*purchorderdetails.quantityord) AS ordervalue,
						total_amount
					FROM purchorders,
						purchorderdetails,
						suppliers
					WHERE purchorders.orderno = purchorderdetails.orderno
					AND purchorders.supplierno = suppliers.supplierid
					$completed
					$condition
					GROUP BY purchorders.orderno ASC,
						purchorders.realorderno,
						suppliers.suppname,
						purchorders.orddate,
						purchorders.status,
						purchorders.initiator,
						purchorders.requisitionno,
						purchorders.allowprint,
						suppliers.currcode";

	$AccountsResult = DB_query($SQL,$db);
	if (DB_error_no($db) !=0) {
		$title = _('Purchase Orders') . ' - ' . _('Problem Report') . '....';
		include('includes/header.inc');
		prnMsg( _('No general ledger accounts were returned by the SQL because') . ' - ' . DB_error_msg($db) );
		echo '<br><a href="' .$rootpath .'/index.php?' . SID . '">'. _('Back to the menu'). '</a>';
		if ($debug==1){
			echo '<br>'. $SQL;
		}
		include('includes/footer.inc');
		exit;
	}
	
	include('includes/PDFPurchaseOrderHeader.inc');
	
	$j = 1;
	$Level = 1;
	

	while ($myrow=DB_fetch_array($AccountsResult)) {
			$FormatedOrderDate = ConvertSQLDate($myrow['orddate']);
			$FormatedOrderValue = number_format($myrow['ordervalue'],2);
		
			$YPos -= (.5 * $line_height);
			
			$pdf->selectFont('./fonts/Helvetica-Bold.afm');
			$LeftOvers = $pdf->addTextWrap($Left_Margin,$YPos,60,$FontSize,$myrow["orderno"]);
			$LeftOvers = $pdf->addTextWrap($Left_Margin+60,$YPos,120,$FontSize,$FormatedOrderDate);
			$LeftOvers = $pdf->addTextWrap($Left_Margin+130,$YPos,70,$FontSize,$myrow['initiator']);
			$LeftOvers = $pdf->addTextWrap($Left_Margin+180,$YPos,120,$FontSize,$myrow['suppname']);
			$LeftOvers = $pdf->addTextWrap($Left_Margin+320,$YPos,70,$FontSize,$myrow['currcode']);
			$LeftOvers = $pdf->addTextWrap($Left_Margin+380,$YPos,70,$FontSize,$myrow['total_amount']);
			$LeftOvers = $pdf->addTextWrap($Left_Margin+450,$YPos,70,$FontSize,$myrow['status']);
			
			
			$pdf->selectFont('./fonts/Helvetica.afm');
			$YPos -= $line_height;		
				
		$j++;
	}  //end of while loop	
	
	$pdfcode = $pdf->output();
	$len = strlen($pdfcode);
	
	if ($len<=20){
		$title = _('Print Purchase Orders Error');
		include('includes/header.inc');
		echo '<p>';
		prnMsg( _('There were no entries to print out for the selections specified') );
		echo '<br><a href="'. $rootpath.'/index.php?' . SID . '">'. _('Back to the menu'). '</a>';
		include('includes/footer.inc');
		exit;
	} else {
		header('Content-type: application/pdf');
		header('Content-Length: ' . $len);
		header('Content-Disposition: inline; filename=CustomerList.pdf');
		header('Expires: 0');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Pragma: public');

		$pdf->Stream();

	}
	exit;
} else {

	include('includes/header.inc');
	echo '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '?' . SID . '">';
	echo '<input type=hidden name="FromPeriod" VALUE="' . $_POST['FromPeriod'] . '"><input type=hidden name="ToPeriod" VALUE="' . $_POST['ToPeriod'] . '">';
	
	$condition = '';
	$fromPeriod = $_POST['FromPeriod'];
	
	if(!empty($fromPeriod)){
		$condition .= " AND purchorders.orddate >= '".date('Y-m-d',strtotime($fromPeriod))."'";
		$showFrom = ' from '.$fromPeriod;
	}
		
	$toPeriod = $_POST['ToPeriod'];
	if(!empty($toPeriod)){
		$condition .= " AND purchorders.orddate <= '".date('Y-m-d',strtotime($toPeriod))."'";
		$showTo = ' to '.$toPeriod;
	}
	
	$SQL = "SELECT purchorders.realorderno,
						purchorders.orderno,
						suppliers.suppname,
						purchorders.orddate,
						purchorders.status,
						purchorders.initiator,
						purchorders.requisitionno,
						purchorders.allowprint,
						suppliers.currcode,
						SUM(purchorderdetails.unitprice*purchorderdetails.quantityord) AS ordervalue,
						total_amount
					FROM purchorders,
						purchorderdetails,
						suppliers
					WHERE purchorders.orderno = purchorderdetails.orderno
					AND purchorders.supplierno = suppliers.supplierid
					$completed
					$condition
					GROUP BY purchorders.orderno ASC,
						purchorders.realorderno,
						suppliers.suppname,
						purchorders.orddate,
						purchorders.status,
						purchorders.initiator,
						purchorders.requisitionno,
						purchorders.allowprint,
						suppliers.currcode";


	$AccountsResult = DB_query($SQL,
				$db,
				 _('No general ledger accounts were returned by the SQL because'),
				 _('The SQL that failed was:'));

	echo '<div align="right" style="padding-right:10px"><font size=4 color=BLUE><a href="javascript:history.back();">&laquo;Back</a></font></div><br>';
	echo '<div class="centre"><font size=4 color=BLUE><b>'. _('Purchase Order') . $showFrom . $showTo .'</b></font></div><br>';

	/*show a table of the accounts info returned by the SQL
	Account Code ,   Account Name , Month Actual, Month Budget, Period Actual, Period Budget */

	echo '<table cellpadding=2>';
	$TableHeader = '<tr><th>' . _('Order #') .
			'</th><th>' . _('Order Date') .
			'</th><th>' . _('Initiated by') .
			'</th><th>' . _('Supplier') .
			'</th><th>' . _('Currency') .						
			'</th><th>' . _('Order Total including tax') .
			'</th><th>' . _('Status') .
			'</th></tr>';

	echo $TableHeader;
	$j = 1;
	$k=0; //row colour counter	

	while ($myrow=DB_fetch_array($AccountsResult)) {

		if ($k==1){ /*alternate bgcolour of row for highlighting */
			echo '<tr class="EvenTableRows">';
			$k=0;
		} else {
			echo '<tr class="OddTableRows">';
			$k++;
		}

		
		if ($myrow['status']==_('Authorised')) {
			$PrintPurchOrder = '<a target="_blank" href="' . $rootpath . '/PO_PDFPurchOrder.php?' . SID . '&OrderNo=' . $myrow['orderno'] . '&realorderno=' . $myrow['realorderno'] . '&ViewingOnly=2">' . _('Print') . '</a>';
		} else {
			$PrintPurchOrder = 'Print';
		}
		
		$FormatedOrderDate = ConvertSQLDate($myrow['orddate']);
		$FormatedOrderValue = number_format($myrow['ordervalue'],2);

// the tailed two column
//			<td>%s</font></td>
//			<td align=right>%s</font></td>
//			$myrow['requisitionno'],	
//			$myrow['initiator']);
//			'</td><td class="tableheader">' . _('Requisition') .
//			'</td><td class="tableheader">' . _('Initiator') .	               		
//		        <td><a href='%s'>" . _('Receive') . "</a></td>			

		$orderno = '<a href="'.$rootpath.'/GLPurchaseOrderDetails.php?order_no='.$myrow["orderno"].'">'.$myrow["orderno"].'</a>';
		printf("<td>%s</font></td>
			<td>%s</td>
			<td>%s</td>
			<td>%s</td>
			<td>%s</font></td>			
			<td class=number>%s</font></td>
			<td>%s</td>			
			</tr>",
			$orderno,						
			$FormatedOrderDate,			
			$myrow['initiator'],
			$myrow['suppname'],
			$myrow['currcode'],						
			$myrow['total_amount'],
			$myrow['status']			
			);



		$j++;
		If ($j == 12){
			$j=1;
			 echo $TableHeader;
		}
	//end of page full new headings if
	}
	//end of while loop



	

	echo '</table>';
	echo '<div class="centre"><input type=submit Name="SelectADifferentPeriod" Value="' . _('Select A Different Period') . '"></div>';
}
echo '</form>';
include('includes/footer.inc');

?>