<?php
ob_start();

$PageSecurity=0;

include('includes/session.inc');
$Title=_('ERP Home');
include('includes/newheader.php');

?>

		
  					
	<script src="angular/angular.min.js"></script>  
        
 
     
     
		

   
  
 									
									<?php
//this is where you paste. Below paste it:

$ViewTopic = 'ARReports';
$BookMark = 'CustomerStatements';

// If this file is called from another script, we set the required POST variables from the GET
// We call this file from SelectCustomer.php when a customer is selected and we want a statement printed

if (isset($_POST['PrintPDF'])) {
	$PaperSize='A4_Landscape';
}

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

	$_POST['PrintPDF'] = $PrintPDF;
	$PaperSize='A4_Landscape';
}

if (isset($_POST['PrintPDF']) AND ($_POST['account']) !=="All" AND ($_POST['department']) =="0"){

	$SQLd = "SELECT *
				                            
		                            FROM debtoraccount
									WHERE account_number = '" . $_POST['account']."'
		                            ";

$resultd=DB_query($SQLd);
$myrowdebtor=DB_fetch_array($resultd);
	$debtorno = $myrowdebtor['debtorno'];
	
	$Accountnumber = $_POST['account'];
$PaperSize='A4_Landscape';


	include('includes/PDFStarter.php');
	$pdf->addInfo('Title', _('Customer Statements') );
	$pdf->addInfo('Subject', _('Statements for') . ' ' .$_POST['account']);
	$PageNumber = 1;
	$line_height=16;

	$FirstStatement = True;


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

/* Do a quick tidy up to settle any transactions that should have been settled at the time of allocation but for whatever reason weren't */
	$ErrMsg = _('There was a problem settling the old transactions.');
	$DbgMsg = _('The SQL used to settle outstanding transactions was');
	$sql = "UPDATE debtortrans SET settled=1
			WHERE ABS(debtortrans.ovamount+debtortrans.ovdiscount+debtortrans.ovfreight+debtortrans.ovgst-debtortrans.alloc)<0.009";
	$SettleAsNec = DB_query($sql, $ErrMsg, $DbgMsg);


	

/*Figure out who all the customers in this range are */





	$ErrMsg= _('There was a problem retrieving the customer information for the statements from the database');
	$sql = "SELECT debtorsmaster.debtorno,
				debtorsmaster.name,
				debtorsmaster.address1,
				debtorsmaster.address2,
				debtorsmaster.address3,
				debtorsmaster.address4,
				debtorsmaster.address5,
				debtorsmaster.address6,
				debtorsmaster.lastpaid,
				debtorsmaster.lastpaiddate,
				currencies.currency,
				currencies.decimalplaces AS currdecimalplaces,
				paymentterms.terms
			FROM debtorsmaster INNER JOIN currencies
				ON debtorsmaster.currcode=currencies.currabrev
			INNER JOIN paymentterms
				ON debtorsmaster.paymentterms=paymentterms.termsindicator
			WHERE debtorsmaster.debtorno ='" . $debtorno."'
		
			";
	$StatementResults=DB_query($sql, $ErrMsg);

	if (DB_Num_Rows($StatementResults) == 0){
		$Title = _('Print Statements') . ' - ' . _('No Customers Found');
	   // require('includes/header.inc');
		echo '<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/printer.png" title="' . _('Print') . '" alt="" />' . ' ' . _('Print Customer Account Statements') . '</p>';
		prnMsg( _('There were no Customers matching your selection of '). $_POST['FromCust']. ' - '.
			$_POST['ToCust'].'.' , 'error');
//		echo '</div>';
		//include('includes/footer.inc');
		exit();
	}

	$StmtHeader=DB_fetch_array($StatementResults); /*loop through all the customers returned */

	/*now get all the outstanding transaction ie Settled=0 */
		$ErrMsg =  _('There was a problem retrieving the outstanding transactions for') . ' ' .	$StmtHeader['name'] . ' '. _('from the database') . '.';
		$sql = "SELECT systypes.typename,
					debtortrans.transno,
					debtortrans.trandate,
					debtortrans.ovamount+debtortrans.ovdiscount+debtortrans.ovfreight+debtortrans.ovgst as total,
					debtortrans.alloc,
					debtortrans.ptax,
						debtortrans.retention,
					debtortrans.account_number,
					debtortrans.department,
					debtortrans.ovamount+debtortrans.ovdiscount+debtortrans.ovfreight+debtortrans.ovgst-debtortrans.alloc-debtortrans.ptax-debtortrans.retention as ostdg
				FROM debtortrans INNER JOIN systypes
					ON debtortrans.type=systypes.typeid
				WHERE 
				debtortrans.account_number='" . $_POST['account'] . "'
				AND debtortrans.settled=0
				AND debtortrans.cancelled=0
				
				
				";

		if ($_SESSION['SalesmanLogin'] != '') {
			$sql .= " AND debtortrans.salesperson='" . $_SESSION['SalesmanLogin'] . "'";
		}

		$sql .= " ORDER BY debtortrans.trandate";

		$OstdgTrans=DB_query($sql, $ErrMsg);

	   	$NumberOfRecordsReturned = DB_num_rows($OstdgTrans);

/*now get all the settled transactions which were allocated this month */
		$ErrMsg = _('There was a problem retrieving the transactions that were settled over the course of the last month for'). ' ' . $StmtHeader['name'] . ' ' . _('from the database');
	   	if ($_SESSION['Show_Settled_LastMonth']==1){
	   		$sql = "SELECT DISTINCT debtortrans.id,
								systypes.typename,
								debtortrans.transno,
								debtortrans.trandate,
								debtortrans.ovamount+debtortrans.ovdiscount+debtortrans.ovfreight+debtortrans.ovgst AS total,
								debtortrans.alloc,
								debtortrans.ptax,
						debtortrans.retention,
								debtortrans.account_number,
					debtortrans.department,
								debtortrans.ovamount+debtortrans.ovdiscount+debtortrans.ovfreight+debtortrans.ovgst-debtortrans.alloc-debtortrans.ptax-debtortrans.retention AS ostdg
						FROM debtortrans INNER JOIN systypes
							ON debtortrans.type=systypes.typeid
						INNER JOIN custallocns
							ON (debtortrans.id=custallocns.transid_allocfrom
								OR debtortrans.id=custallocns.transid_allocto)
						WHERE custallocns.datealloc >='" .
							Date('Y-m-d',Mktime(0,0,0,Date('m')-1,Date('d'),Date('y'))) . "'
						
						AND debtortrans.account_number='" . $_POST['account'] . "'
						AND debtortrans.settled=1
						AND debtortrans.cancelled=0";
			

			if ($_SESSION['SalesmanLogin'] != '') {
				$sql .= " AND debtortrans.salesperson='" . $_SESSION['SalesmanLogin'] . "'";
			}

			$sql .= " ORDER BY debtortrans.trandate";

			$SetldTrans=DB_query($sql, $ErrMsg);
			$NumberOfRecordsReturned += DB_num_rows($SetldTrans);

	   	}

	  	if ( $NumberOfRecordsReturned >=1){

		/* Then there's a statement to print. So print out the statement header from the company record */

	      		$PageNumber =1;

			if ($FirstStatement==True){
				$FirstStatement=False;
	      		} else {
				$pdf->newPage();
	      		}

	      		include('includes/PDFStatementPageHeaderAccount.inc');


			if ($_SESSION['Show_Settled_LastMonth']==1){
				if (DB_num_rows($SetldTrans)>=1) {

					$FontSize=12;
					$pdf->addText($Left_Margin+1,$YPos+5,$FontSize, _('Settled Transactions'));

					$YPos -= (2*$line_height);

					$FontSize=10;

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

						//get department name and subname
				
				//get department name since department id is known by now
			$departmentid = $myrow['department'];
			
			
			$SQL9 = "SELECT departmentid,
			                departmentname
			
														
		                            FROM department
									
			WHERE departmentid = '".$departmentid."'";
			$result9=DB_query($SQL9);
			$myrow9=DB_fetch_array($result9);

				$DisplayAlloc = locale_number_format($myrow['alloc'],$StmtHeader['currdecimalplaces']);
						$ptax = locale_number_format($myrow['ptax'],$StmtHeader['currdecimalplaces']);
						$reten = locale_number_format($myrow['retention'],$StmtHeader['currdecimalplaces']);
				$DisplayOutstanding = locale_number_format($myrow['ostdg'],$StmtHeader['currdecimalplaces']);

				$FontSize=9;
				$LeftOvers = $pdf->addTextWrap($Left_Margin+1,$YPos,60,$FontSize, _($myrow['typename']), 'left');
				$LeftOvers = $pdf->addTextWrap($Left_Margin+80,$YPos,50,$FontSize,$myrow['transno'], 'left');
				$LeftOvers = $pdf->addTextWrap($Left_Margin+150,$YPos,50,$FontSize,ConvertSQLDate($myrow['trandate']), 'left');
				$LeftOvers = $pdf->addTextWrap($Left_Margin+200,$YPos,50,$FontSize,$myrow['account_number'], 'left');
				$LeftOvers = $pdf->addTextWrap($Left_Margin+250,$YPos,50,$FontSize,$myrow9['departmentname'], 'left');
				$FontSize=10;
				if ($myrow['total']>0){
					$DisplayTotal = locale_number_format($myrow['total'],$StmtHeader['currdecimalplaces']);
					$LeftOvers = $pdf->addTextWrap($Left_Margin+310,$YPos,50,$FontSize,$DisplayTotal, 'right');
				} else {
					$DisplayTotal = locale_number_format(-$myrow['total'],$StmtHeader['currdecimalplaces']);
					$LeftOvers = $pdf->addTextWrap($Left_Margin+310,$YPos,50,$FontSize,$DisplayTotal, 'right');
				}

				$LeftOvers = $pdf->addTextWrap($Left_Margin+400,$YPos,50,$FontSize,$DisplayAlloc, 'right');
						$LeftOvers = $pdf->addTextWrap($Left_Margin+450,$YPos,50,$FontSize,$ptax, 'right');
						$LeftOvers = $pdf->addTextWrap($Left_Margin+500,$YPos,50,$FontSize,$reten, 'right');
				$LeftOvers = $pdf->addTextWrap($Left_Margin+550,$YPos,50,$FontSize,$DisplayOutstanding, 'right');

				/*Now show also in the remittance advice sectin */
				$FontSize=8;
				$LeftOvers = $pdf->addTextWrap($Perforation+10,$YPos,60,$FontSize, _($myrow['typename']), 'left');
				$LeftOvers = $pdf->addTextWrap($Perforation+55,$YPos,50,$FontSize,$myrow['transno'], 'left');
				$LeftOvers = $pdf->addTextWrap($Perforation+100,$YPos,50,$FontSize,$DisplayOutstanding, 'right');


						if ($YPos-$line_height <= $Bottom_Margin){
		/* head up a new statement page */

							$PageNumber++;
							$pdf->newPage();
							include ('includes/PDFStatementPageHeaderAccount.inc');
						} //end if need a new page headed up

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

					} //end while there transactions settled this month to print out
				}
			} // end of if there are transaction that were settled this month

	      		if (DB_num_rows($OstdgTrans)>=1){

		      		$YPos -= ($line_height);
				if ($YPos-(2 * $line_height) <= $Bottom_Margin){
					$PageNumber++;
					$pdf->newPage();
					include ('includes/PDFStatementPageHeaderAccount.inc');
				}
			/*Now the same again for outstanding transactions */

			$FontSize=12;
			$pdf->addText($Left_Margin+1,$YPos+20,$FontSize, _('Outstanding Transactions') );
			$YPos -= $line_height;

			while ($myrow=DB_fetch_array($OstdgTrans)){
				
				//get department name and subname
				
				//get department name since department id is known by now
			$departmentid = $myrow['department'];
			
			
			$SQL9 = "SELECT departmentid,
			                departmentname
			
														
		                            FROM department
									
			WHERE departmentid = '".$departmentid."'";
			$result9=DB_query($SQL9);
			$myrow9=DB_fetch_array($result9);

				$DisplayAlloc = locale_number_format($myrow['alloc'],$StmtHeader['currdecimalplaces']);
						$ptax = locale_number_format($myrow['ptax'],$StmtHeader['currdecimalplaces']);
						$reten = locale_number_format($myrow['retention'],$StmtHeader['currdecimalplaces']);
				$DisplayOutstanding = locale_number_format($myrow['ostdg'],$StmtHeader['currdecimalplaces']);

				$FontSize=9;
				$LeftOvers = $pdf->addTextWrap($Left_Margin+1,$YPos,60,$FontSize, _($myrow['typename']), 'left');
				$LeftOvers = $pdf->addTextWrap($Left_Margin+80,$YPos,50,$FontSize,$myrow['transno'], 'left');
				$LeftOvers = $pdf->addTextWrap($Left_Margin+150,$YPos,50,$FontSize,ConvertSQLDate($myrow['trandate']), 'left');
				$LeftOvers = $pdf->addTextWrap($Left_Margin+200,$YPos,50,$FontSize,$myrow['account_number'], 'left');
				$LeftOvers = $pdf->addTextWrap($Left_Margin+250,$YPos,50,$FontSize,$myrow9['departmentname'], 'left');
				$FontSize=10;
				if ($myrow['total']>0){
					$DisplayTotal = locale_number_format($myrow['total'],$StmtHeader['currdecimalplaces']);
					$LeftOvers = $pdf->addTextWrap($Left_Margin+310,$YPos,50,$FontSize,$DisplayTotal, 'right');
				} else {
					$DisplayTotal = locale_number_format(-$myrow['total'],$StmtHeader['currdecimalplaces']);
					$LeftOvers = $pdf->addTextWrap($Left_Margin+350,$YPos,50,$FontSize,$DisplayTotal, 'right');
				}

				$LeftOvers = $pdf->addTextWrap($Left_Margin+400,$YPos,50,$FontSize,$DisplayAlloc, 'right');
						$LeftOvers = $pdf->addTextWrap($Left_Margin+450,$YPos,50,$FontSize,$ptax, 'right');
						$LeftOvers = $pdf->addTextWrap($Left_Margin+500,$YPos,50,$FontSize,$reten, 'right');
				$LeftOvers = $pdf->addTextWrap($Left_Margin+550,$YPos,50,$FontSize,$DisplayOutstanding, 'right');
				
				/*Now show also in the remittance advice sectin */
				$FontSize=8;
				$LeftOvers = $pdf->addTextWrap($Perforation+10,$YPos,60,$FontSize, _($myrow['typename']), 'left');
				$LeftOvers = $pdf->addTextWrap($Perforation+55,$YPos,50,$FontSize,$myrow['transno'], 'left');
				$LeftOvers = $pdf->addTextWrap($Perforation+100,$YPos,50,$FontSize,$DisplayOutstanding, 'right');

				if ($YPos-$line_height <= $Bottom_Margin){
		/* head up a new statement page */

					$PageNumber++;
					$pdf->newPage();
					include ('includes/PDFStatementPageHeaderAccount.inc');
				} //end if need a new page headed up

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

			} //end while there are outstanding transaction to print
		} // end if there are outstanding transaction to print


		/* check to see enough space left to print the totals/footer
		which is made up of 2 ruled lines, the totals/aging another 2 lines
		and details of the last payment made - in all 6 lines */
		if (($YPos-$Bottom_Margin)<(4*$line_height)){

		/* head up a new statement/credit note page */
			$PageNumber++;
			$pdf->newPage();
			include ('includes/PDFStatementPageHeaderAccount.inc');
		}
			/*Now figure out the aged analysis for the customer under review */
			
			
				$sqlbalances="SELECT account_number, balance, current,1month,2month,3month_plus
					FROM debtoraccount where account_number = '" . $Accountnumber."' ";
		$resultfromdebtoraccount =DB_query($sqlbalances);
			$myrowfromdebtoraccount = DB_fetch_array($resultfromdebtoraccount);
			$balance = $myrowfromdebtoraccount['balance'];
			
			$current = $myrowfromdebtoraccount['current'];
			$onemonth = $myrowfromdebtoraccount['1month'];
			$twomonth = $myrowfromdebtoraccount['2month'];
			$threemonthplus = $myrowfromdebtoraccount['3month_plus'];
				

			$SQL = "SELECT debtorsmaster.debtorno,
				debtorsmaster.name,
				debtorsmaster.lastpaid,
				debtorsmaster.lastpaiddate,
				debtortrans.account_number,
				
				paymentterms.terms,
			
				SUM(
					debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc - debtortrans.ptax - debtortrans.retention
				) AS balance,
				SUM(debtortrans.ptax) AS ptaxbalance,
						SUM(debtortrans.retention) AS retentionbalance,
				SUM(
					CASE WHEN (paymentterms.daysbeforedue > 0)
					THEN
						CASE WHEN (TO_DAYS(Now()) - TO_DAYS(debtortrans.trandate)) >= paymentterms.daysbeforedue
						THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc - debtortrans.ptax - debtortrans.retention
						ELSE 0 END
					ELSE
						CASE WHEN TO_DAYS(Now()) - TO_DAYS(DATE_ADD(DATE_ADD(debtortrans.trandate, " . INTERVAL('1', 'MONTH') . "), " . INTERVAL('(paymentterms.dayinfollowingmonth - DAYOFMONTH(debtortrans.trandate))', 'DAY') .")) >= 0
						THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc - debtortrans.ptax - debtortrans.retention ELSE 0 END
					END
				) AS due,
				SUM(
					CASE WHEN (paymentterms.daysbeforedue > 0)
					THEN
						CASE WHEN (TO_DAYS(Now()) - TO_DAYS(debtortrans.trandate)) > paymentterms.daysbeforedue AND TO_DAYS(Now()) - TO_DAYS(debtortrans.trandate) >= (paymentterms.daysbeforedue + " . $_SESSION['PastDueDays1'] . ")
						THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc - debtortrans.ptax - debtortrans.retention ELSE 0 END
					ELSE
						CASE WHEN TO_DAYS(Now()) - TO_DAYS(DATE_ADD(DATE_ADD(debtortrans.trandate, " . INTERVAL('1', 'MONTH') . "), " . INTERVAL ('(paymentterms.dayinfollowingmonth - DAYOFMONTH(debtortrans.trandate))', 'DAY') . ")) >= " . $_SESSION['PastDueDays1'] . "
						THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc - debtortrans.ptax - debtortrans.retention
						ELSE 0 END
					END
				) AS overdue1,
			
			
					SUM(CASE WHEN DATEDIFF(CURDATE(), LAST_DAY(debtortrans.trandate)) >= 30 AND DATEDIFF(CURDATE(), LAST_DAY(debtortrans.trandate)) < 60 THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc - debtortrans.ptax - debtortrans.retention ELSE 0 END) AS '30days',
					SUM(CASE WHEN DATEDIFF(CURDATE(), LAST_DAY(debtortrans.trandate)) >= 60 AND DATEDIFF(CURDATE(), LAST_DAY(debtortrans.trandate)) < 90 THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc - debtortrans.ptax - debtortrans.retention ELSE 0 END) AS '60days',
				SUM(CASE WHEN DATEDIFF(CURDATE(), LAST_DAY(debtortrans.trandate)) >= 90 THEN debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc - debtortrans.ptax - debtortrans.retention ELSE 0 END) AS '90days'
		
				
				FROM debtorsmaster,
					paymentterms,
					
					debtortrans
				WHERE debtorsmaster.paymentterms = paymentterms.termsindicator
				
				AND debtortrans.account_number = '" . $Accountnumber."'
					
					
					
				AND debtortrans.cancelled=0
				AND debtortrans.trandate > '2020-01-01 00:00:00'
				AND debtortrans.settled=0
			
				GROUP BY debtorsmaster.debtorno,
					debtorsmaster.name,
					debtortrans.account_number,
					paymentterms.terms,
					paymentterms.daysbeforedue,
					paymentterms.dayinfollowingmonth
					 
				HAVING
					ROUND(ABS(SUM(debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount - debtortrans.alloc - debtortrans.ptax - debtortrans.retention ))) > 0";

		
			
	$ErrMsg = _('This customer could not be added because');
			$result4 = DB_query($SQL,$ErrMsg);
	
				
				
			
		$AgedAnalysis = DB_fetch_array($result4);
			
			
			
			$CurrDecimalPlaces = $AgedAnalysis['decimalplaces'];
				$DisplayDue = locale_number_format($AgedAnalysis['due']-$AgedAnalysis['overdue1'],$CurrDecimalPlaces);
		$DisplayCurrent = locale_number_format($AgedAnalysis['balance']-$AgedAnalysis['due'],$CurrDecimalPlaces);
		$DisplayBalance = locale_number_format(($AgedAnalysis['balance']),$CurrDecimalPlaces);

		$Lastpaid = locale_number_format($AgedAnalysis['lastpaid'],$CurrDecimalPlaces);
		$Lastpaiddate =  $AgedAnalysis['lastpaiddate'];                  
		
		
		$TotBal += $AgedAnalysis['balance'];
		$TotDue += ($AgedAnalysis['due']-$AgedAnalysis['overdue1']);
		$TotCurr += ($AgedAnalysis['balance']-$AgedAnalysis['due']);
	    $days30 += $AgedAnalysis['30days']; 
		$days60 += $AgedAnalysis['60days']; 	
		$days90 += $AgedAnalysis['90days']; 	
			
			$finalbalance = $TotBal ;
		
				
				$retentionBalance = locale_number_format($AgedAnalysis['retentionbalance'],2);
			
			

			$pdf->line($Page_Width-$Right_Margin, $Bottom_Margin+(4*$line_height),$Left_Margin,$Bottom_Margin+(4*$line_height));

			$FontSize=10;


			$pdf->addText($Left_Margin+50, ($Bottom_Margin+10)+(3*$line_height)+4, $FontSize, _('Current'). ' ');
			$pdf->addText($Left_Margin+133, ($Bottom_Margin+10)+(3*$line_height)+4, $FontSize, _('30 Days').' ');
			//$pdf->addText($Left_Margin+216, ($Bottom_Margin+10)+(3*$line_height)+4, $FontSize, $_SESSION['PastDueDays1'] . '-' . $_SESSION['PastDueDays2'] . ' ' . _('days') );
			$pdf->addText($Left_Margin+216, ($Bottom_Margin+10)+(3*$line_height)+4, $FontSize, _('60 Days'));
			$pdf->addText($Left_Margin+299, ($Bottom_Margin+10)+(3*$line_height)+4, $FontSize, _('90 Days'));
			
			$pdf->addText($Left_Margin+372, ($Bottom_Margin+10)+(3*$line_height)+4, $FontSize, _('Total Balance'));
			$pdf->addText($Left_Margin+450, ($Bottom_Margin+10)+(3*$line_height)+4, $FontSize, _('Total Retention') );
			//$pdf->addText($Left_Margin+575, ($Bottom_Margin+10)+(3*$line_height)+4, $FontSize, _('Old Bal') );
			//$pdf->addText($Left_Margin+520, ($Bottom_Margin+10)+(3*$line_height)+4, $FontSize, _('Total Retention') );

			$LeftOvers = $pdf->addTextWrap($Left_Margin+10, $Bottom_Margin+(2*$line_height)+8,70,$FontSize,round($TotCurr,2) , 'right');
			$LeftOvers = $pdf->addTextWrap($Left_Margin+85, $Bottom_Margin+(2*$line_height)+8,70,$FontSize,round($days30,2) , 'right');
			$LeftOvers = $pdf->addTextWrap($Left_Margin+185, $Bottom_Margin+(2*$line_height)+8,70,$FontSize,round($days60,2), 'right');

			$LeftOvers = $pdf->addTextWrap($Left_Margin+275, $Bottom_Margin+(2*$line_height)+8,70,$FontSize,round($days90,2), 'right');
				$LeftOvers = $pdf->addTextWrap($Left_Margin+362, $Bottom_Margin+(2*$line_height)+8,70,$FontSize,$finalbalance, 'right');

			//$LeftOvers = $pdf->addTextWrap($Left_Margin+422, $Bottom_Margin+(2*$line_height)+8,70,$FontSize,$finalbalance, 'right');
		//	$LeftOvers = $pdf->addTextWrap($Left_Margin+422, $Bottom_Margin+(2*$line_height)+8,70,$FontSize,_(' '), 'right');
		//	$LeftOvers = $pdf->addTextWrap($Left_Margin+510, $Bottom_Margin+(2*$line_height)+8,70,$FontSize,$retentionBalance, 'right');


			/*draw a line under the balance info */
			$YPos = $Bottom_Margin+(2*$line_height);
			$pdf->line($Left_Margin, $YPos,$Perforation,$YPos);


			if (mb_strlen($StmtHeader['lastpaiddate'])>1 AND $StmtHeader['lastpaid']!=0){
				$pdf->addText($Left_Margin+5, $Bottom_Margin+13, $FontSize, _('Last payment received').' ' . ConvertSQLDate($StmtHeader['lastpaiddate']) .
					'    ' . _('Amount received was').' ' . locale_number_format($StmtHeader['lastpaid'],$StmtHeader['currdecimalplaces']));

			}
	$pdf->addText($Left_Margin+300, $Bottom_Margin+2, $FontSize, _('Powered By E-Business ERP Systems'));
			/* Show the bank account details */
			//$pdf->addText($Perforation-250, $Bottom_Margin+32, $FontSize, _('Please make payments to our account:') . ' ' . $DefaultBankAccountNumber);
			//$pdf->addText($Perforation-250, $Bottom_Margin+32-$line_height, $FontSize, _('Quoting your account reference') . ' ' . $StmtHeader['debtorno'] );

			/*also show the total due in the remittance section */
			if ($AgedAnalysis['balance']>0){ /*No point showing a negative balance for payment! */
					$FontSize=8;
					$LeftOvers = $pdf->addTextWrap($Perforation+2, $Bottom_Margin+(2*$line_height)+8,40,$FontSize, _('Payment'), 'left');
					$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $Bottom_Margin+(2*$line_height)+8,88,$FontSize,$finalbalance, 'right');

			}

		} /* end of check to see that there were statement transactons to print */

	
//print outstanding invoices petaining to this account
	
		$sql99 = "SELECT 
					*
				FROM debtortrans 
				WHERE account_number='" . $Accountnumber . "'
				
				AND settled=0
				AND cancelled=0
				AND type = 10";

$Trans99=DB_query($sql99);
	while ($myrow99=DB_fetch_array($Trans99)){
		$orderno = $myrow99['order_'];
		$InvoiceNo = $myrow99['transno'];
		
		
		
$realname= $myrow99['entered_by'];
		
				
		
$SQLuser = "SELECT email
	               
			FROM www_users
			WHERE realname='" . $realname. "'
			";
	
			$resultuser = DB_query($SQLuser);
	
			$myrowuser = DB_fetch_array($resultuser) ;
		
		$emailm= $myrowuser['email'];
		
$SQL = "SELECT *
	               
			FROM salesorders
			WHERE orderno='" . $orderno. "'
			";
	
			$result = DB_query($SQL);
	
			$myrow = DB_fetch_array($result) ;

$_POST['lpo'] = $myrow['lpo'];


$accountnumber = $Accountnumber;

$_POST['account'] = $accountnumber;
//$_POST['lpo'] = $myrowac['lpo'];

$sql4011 =  "SELECT billing_name, sub_billing_name
			FROM debtoraccount
			
			WHERE account_number = '" . $accountnumber. "'
			";
	$ErrMsg = _('This customer could not be added because');
			$result4011 = DB_query($sql4011,$ErrMsg);
	$myrow4011 = DB_fetch_array($result4011) ;

		$billingname = $myrow4011['billing_name'];

$subbillingname = $myrow4011['sub_billing_name'];


$SQL = "SELECT *
	               
			FROM debtortrans
			WHERE transno='" . $InvoiceNo. "'
			";
	
			$result = DB_query($SQL);
	
			$myrow1000 = DB_fetch_array($result) ;

$quotedated = date('Y-m-d', strtotime($myrow1000['trandate']));
		$quotedate = date('d-m-Y',strtotime($myrow1000['trandate']));
$yeardate = date('Y',strtotime($myrow1000['trandate']));
$monthdate =date('M',strtotime($myrow1000['trandate']));

$retention = $myrow1000['retention'];
$cashcustomeradd = $myrow1000['cash_customer_address'];
$cashcustomer = $myrow1000['cash_customer_name'];
$debtorno = $myrow1000['debtorno'];
$contactperson = $myrow1000['contact_person'];
		$sql4 =  "SELECT projectid,
	               project_type,
				   project_name,
				   retention_rate,
				  
				   customer,
				   branch,
				
				   contact_number,
				   required_date,
				   start_date,
				 
				   comments
			FROM projectdetails
			
			WHERE projectid = '" . $myrow['job_no']. "'
			";
	$ErrMsg = _('This customer could not be added because');
			$result4 = DB_query($sql4,$ErrMsg);
	
		
	$myrow4 = DB_fetch_array($result4) ;

//look for department id
	$sql40 =  "SELECT departmentname
			FROM department
			
			WHERE departmentid = '" . $myrow1000['department']. "'
			";
	$ErrMsg = _('This customer could not be added because');
			$result40 = DB_query($sql40,$ErrMsg);
	$myrowd =DB_fetch_array($result40);
		$department = $myrowd['departmentname'];


//$quotedate = $myrow['orddate'];
	$myrow40 = DB_fetch_array($result40) ;

		//$userid = $_SESSION['UserID'];
		

		
//get debtor headoffice details:
		$SQL100 = "SELECT 	name,
							address1,
						     address2,
				   			 address3,
							 address4,
							 address5,
							 address6,
							 paymentterms
							 
			FROM debtorsmaster
			WHERE debtorno='" . $debtorno . "'
			";
	 
	$result100 = DB_query($SQL100);
	
	$myrow100 = DB_fetch_array($result100) ;

		$debtorname = $myrow100['name'];
		

	

 
 
if($debtorname == 'CASH SALE'){
	
	 $billingname = $cashcustomer;
	
}

$address1 = $myrow100['address1'];
		$address2 = $myrow100['address2'];
		$address3 = $myrow100['address3'];
		$address4 = $myrow100['address4'];
		$address5 = $myrow100['address5'];
		$address6=  $myrow100['address6'];
		
		
		$SQL1002 = "SELECT 	*
							 
			FROM paymentterms
			WHERE termsindicator='" . $myrow100['paymentterms'] . "'
			";
	
	$result1002 = DB_query($SQL1002);
	
	$myrow1002 = DB_fetch_array($result1002) ;
		
		

$readableduedate = CalcDueDate(ConvertSQLDate($myrow1000['trandate']), $myrow1002['dayinfollowingmonth'], $myrow1002['daysbeforedue']);
		
		//now get other customer details from custbranch tables
		
				$SQL2 = "SELECT brname,
								braddress1,
								braddress2,
								braddress3,
								phoneno,
								contactname,
								email
				   
			FROM custbranch
			WHERE branchcode='" . $myrow['branchcode']. "'
			";
	
	$result2 = DB_query($SQL2);
	
	$myrow2 = DB_fetch_array($result2) ;
		
		$branchname = $myrow2['brname'];
		$branchad1 = $myrow2['braddress1'];
		$branchad2 = $myrow2['braddress2'];
		$branchad3 = $myrow2['braddress3'];
		$branchad4 = $myrow2['braddress3'];
		$branchad5 = $myrow2['braddress3'];
		$branchad6 = $myrow2['braddress3'];
		$phoneno = $myrow2['phoneno'];
		$contactname = $myrow2['contactname'];
		$email = $myrow2['email'];
		
		
		
	//$username = $_SESSION['UsersRealName'];
		
	//	$userid = $_SESSION['userid'];	
			$dash = '-';
		
		
		//insert in salesorders to create new sales order/quote. The system can only add quotation and cant update it.
		//$Result = DB_Txn_Begin();

	     
			//get periodno 
	
	
	    $query22 = "SELECT 
						periodno,
		             lastdate_in_period
		                 
					  
		          FROM periods
				    WHERE YEAR(lastdate_in_period) = '" . $yeardate . "'
					AND MONTH(lastdate_in_period)  = '" . $monthdate. "'";
				
        $result22=DB_query($query22);
        $myrow22=DB_fetch_array($result22);
      
				$PeriodNo = $myrow22['periodno'];
		     	$data = $myrow22['lastdate_in_period'];	
				
	
//$PaperSize = 'A4_Landscape';// PDFStarter.php: $Page_Width=842; $Page_Height=595; $Top_Margin=30; $Bottom_Margin=30; $Left_Margin=40; $Right_Margin=30;
//include('includes/PDFStarter.php');
//$pdf->addInfo('Title', _('Customer Invoice') );
//$pdf->addInfo('Subject', _('Invoice') . ' ' . $InvoiceNo);
$FontSize = 12;
$line_height = 12;// Recommended: $line_height = $x * $FontSize.
		
		include('includes/PDFInvoiceHeader.inc');



		
			$SQL1 = "SELECT *
			FROM salesorderdetails 
			WHERE orderno='" . $orderno . "'
			";
	
			$result1 = DB_query($SQL1);

			while ($myrow1 = DB_fetch_array($result1)) { 
		
		
		//todays date.This is to show today quote was generated
	
		
		
		//start digging to get projectcosting details. Key field is pcid. After which you use this to determine line items from projectcostingdetail and projectcostingdetaillabor tables. Once this values have been determined insert in salesorderdetails and also write to pdf.
		
		
	
			
			   $ListCount ++;
				

		$YPos -= $line_height;// Increment a line down for the next line item.
				

		if ((mb_strlen($myrow1['narrative']) >200 AND $YPos-$line_height <= 75)
			OR (mb_strlen($myrow1['narrative']) >1 AND $YPos-$line_height <= 62)
			OR $YPos-$line_height <= 50){
		/* We reached the end of the page so finsih off the page and start a newy */
			include ('includes/PDFInvoiceHeader.inc');
		} //end if need a new page headed up

			
			
						
			
	
				
	
								//$myrow6 = DB_fetch_array($result6) ;
				
				
				//write to pdf
				
				$ovamount = $myrow1['unitprice'] * $myrow1['quantity'];
			    
			 
			
				
				$stup = locale_number_format($myrow1['unitprice'],2);
				
				$stovm = locale_number_format($ovamount,2);
				
				$qty =locale_number_format($myrow1['quantity'],2);
				
if ($stovm == '0'){
	
	$stovm = '';
	$myrow1['uom'] = '';
	$myrow1['tax_code']='';
	$stup='';
	$qty ='';
}
		
				
				if ($myrow1['tax_code'] =='Vat'){
					
					$myrow1['tax_code'] ='VAT';
				}
	
			
			$FontSize = 10;// Font size for the line item.

		$LeftOvers = $pdf->addText($Left_Margin, $YPos+$FontSize, $FontSize,$myrow1['stkcode']);
		$LeftOvers = $pdf->addText(145, $YPos+$FontSize, $FontSize, $myrow1['stock_name']);
	   
				$LeftOvers = $pdf->addTextWrap(470, $YPos,85,$FontSize,$myrow1['tax_code'],'right');
		$LeftOvers = $pdf->addTextWrap(520, $YPos,85,$FontSize,$qty,'right');
				$LeftOvers = $pdf->addTextWrap(600, $YPos,85,$FontSize,$myrow1['uom'],'right');
		$LeftOvers = $pdf->addTextWrap(650, $YPos,85,$FontSize,$stup,'right');
		$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos, 90, $FontSize, $stovm,'right');
			
			
			// Prints salesorderdetails.narrative:
		$FontSize2 = $FontSize*0.8;// Font size to print salesorderdetails.narrative.
		$Width2 = $Page_Width-$Right_Margin-145;// Width to print salesorderdetails.narrative.
		$LeftOvers = trim($myrow1['narrative']);
		//**********
		$LeftOvers = str_replace('\n', ' ', $LeftOvers);// Replaces line feed character.
		$LeftOvers = str_replace('\r', '', $LeftOvers);// Delete carriage return character
		$LeftOvers = str_replace('\t', '', $LeftOvers);// Delete tabulator character
			
			while (mb_strlen($LeftOvers) > 1) {
			$YPos -= $FontSize2;
			if ($YPos < ($Bottom_Margin)) {// Begins new page.
				include ('includes/PDFInvoiceHeader.inc');
			}
			$LeftOvers = $pdf->addTextWrap(145, $YPos, $Width2, $FontSize2, $LeftOvers);
		}
			
			if ((mb_strlen($quoteterms) >200 AND $YPos-$line_height <= 75)
			OR (mb_strlen($quoteterms) >1 AND $YPos-$line_height <= 62)
			OR $YPos-$line_height <= 50){
		/* We reached the end of the page so finish off the page and start a newy */
			include ('includes/PDFInvoiceHeader.inc');
	} //end if need a new page headed up

		}	
		

		
			
		
		
		$FontSize = 10;
	$finalamount = ($myrow1000['ovamount'] + $myrow1000['ovgst'] - $myrow1000['retention']) ;

$vat = locale_number_format($myrow1000['ovgst'],2);

	$YPos -= $line_height;
/*rule off for total */
			$pdf->line($Page_Width-$Right_Margin-810, $YPos+7,$Page_Width-$Right_Margin,$YPos+7);
	$pdf->line($Page_Width-$Right_Margin-810, $YPos+5,$Page_Width-$Right_Margin,$YPos+5);

	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90-655, $YPos-6, 655, $FontSize, _('Total(VEP)'),'right');
	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos-7, 90, $FontSize,_('$').locale_number_format($myrow1000['ovamount'],2), 'right');

$YPos -= $FontSize;
	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90-655, $YPos-8, 655, $FontSize, _('Retention:'), 'right');
	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos-9, 90, $FontSize, _('-$').locale_number_format($myrow1000['retention'],2), 'right');
	$YPos -= $FontSize;

	$YPos -= $FontSize;
	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90-655, $YPos-10, 655, $FontSize, _('Taxes'), 'right');
	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos-11, 90, $FontSize, _('$').$vat, 'right');
	$YPos -= $FontSize;

	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90-655, $YPos-12, 655, $FontSize, _('Total'),'right');
	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos-13, 90, $FontSize, _('$').locale_number_format($finalamount,2), 'right');

	// Print salesorders.comments:
	$YPos -= $FontSize*2;
	$pdf->addText($XPos+250, $YPos+$FontSize-20, $FontSize, _('TERMS: PAYMENT DUE ON 20th OF THE FOLLOWING MONTH OF PURCHASE'),'centre');
	$pdf->addText($XPos+200, $YPos+$FontSize-35, $FontSize, _('OUR BANKS: Westpac Bank: A/C: 9804778075 | ANZ Bank: A/C: 11879362 | BSP Bank: A/C: 9737614'));
$pdf->addText($XPos+300, $YPos+$FontSize-45, $FontSize, _('BILL PAY AVAILABLE VIA ONLINE BANKING'));
	$pdf->addText($XPos+300, $YPos+$FontSize-55, $FontSize, _('Evergreen International Fiji LLC appreciates your business!'));
$pdf->addText($XPos+330, $YPos+$FontSize-70, $FontSize, _('Powered by E-Business ERP 2.0'));
	$pdf->addText($XPos, $YPos+$FontSize-75, $FontSize, _('Notes').':');

	$Width2 = $Page_Width-$Right_Margin-140;// Width to print salesorders.comments.
    $LeftOvers = $pdf->addTextWrap($XPos, $YPos+$FontSize-95,780, $FontSize, $myrow1000['invtext']);
	        if (mb_strlen($LeftOvers)>0) {
				$LeftOvers = $pdf->addTextWrap($XPos,$YPos+$FontSize-110,780,$FontSize,$LeftOvers);
				if (mb_strlen($LeftOvers)>0) {
					$LeftOvers = $pdf->addTextWrap($XPos,$YPos+$FontSize-120,780,$FontSize,$LeftOvers);
					/*If there is some of the InvText leftover after 3 lines 200 wide then it is not printed :( */
				}
			}
         
//$pdf->addText($XPos, $YPos+$FontSize-120, $FontSize, _('Test'). $LeftOvers);
	//$LeftOvers = trim($quoteterms);
	//**********
	$LeftOvers = str_replace('\n', ' ', $LeftOvers);// Replaces line feed character.
	$LeftOvers = str_replace('\r', '', $LeftOvers);// Delete carriage return character
	$LeftOvers = str_replace('\t', '', $LeftOvers);// Delete tabulator character
	//**********
	while(mb_strlen($LeftOvers) > 1) {
		$YPos -= $FontSize;
		if ($YPos < ($Bottom_Margin)) {// Begins new page.
			include ('includes/PDFInvoiceHeader.inc');
		}
		$LeftOvers = $pdf->addTextWrap($XPos, $YPos, $Width2, $FontSize, $LeftOvers);
	}



		
		
		
		
	}//end printing all invoices
ob_end_clean();
        $pdf->OutputD($_SESSION['DatabaseName'] . '_CustStatements_Account_' .$Accountnumber. date('Y-m-d') . '.pdf');
        $pdf->__destruct();





echo '</div>';
echo '</div>';



} 
elseif (isset($_POST['PrintPDF']) AND ($_POST['account']) =="All" AND ($_POST['department']) !=="0") {
	
	echo "Please note due to server overloading we have disabled invoices been attached to statements. If you want to attach invoices into statements in all departments instead of single then there is a overnight script that you will need to click and let it run for 10-20 min depending on your customer base. This allows system to process and it will email you when its done. Meantime this script will only process  statements only.";
//	echo "<script type='text/javascript'>alert('$message');</script>";
//echo "<script type='text/javascript'>javascript:history.go(-1)</script>"; 
	//exit();
	



	
}




else { /*The option to print PDF was not hit */

	$Title = _('Select Statements to Print');
	//include('includes/header.inc');
	echo '<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/printer.png" title="' . _('Print') . '" alt="" />' . ' ' . _('Print Customer Account Statements with Outstanding Invoices') . '</p>';
	if (!isset($_POST['customer']) OR $_POST['customer']=='') {

	/*if FromTransNo is not set then show a form to allow input of either a single statement number or a range of statements to be printed. Also get the last statement 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 '<div>';
		echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
?>
<td>Select Customer account </td>
<td><select name="account" id = "customer" >;
							<?php
	
							$SQL = "SELECT *
				                            
		                            FROM debtoraccount
		                            ";

$result=DB_query($SQL);
//echo '<option value="0">0 - ' . _('None Available') . '</option>';
 echo '<option value="All">' . _('All ') . '</option>';
while ($myrow=DB_fetch_array($result)){
	
			echo '<option value="' . $myrow['account_number'] . '">' . $myrow['account_number'].' - ' .$myrow['billing_name'] . '</option>';
	
	
		
	
}
echo '</select>';

        echo '<br />';
		?>
<td>Select Department </td>
<td><select name="department" id = "department" >;
							<?php
	
							$SQL = "SELECT *
				                            
		                            FROM department
		                            ";

$result=DB_query($SQL);
//echo '<option value="0">0 - ' . _('None Available') . '</option>';
			echo '<option value="0">' . _('None') . '</option>';
 //echo '<option value="All">' . _('All Department') . '</option>';
	
while ($myrow=DB_fetch_array($result)){
	
			echo '<option value="' . $myrow['departmentid'] . '">' . $myrow['departmentname'].' - ' .$myrow['departmentid'] . '</option>';
	
	
		
	
}
echo '</select>';
		echo '<div class="centre">
				<input type="submit" id= "Print" name="PrintPDF" value="' .
                _('Print Statements in the Range Selected').'" />
			</div>';
        echo '</div>
              </form>';
	}
	echo '<br /><br /><br />';
	//include('includes/footer.inc');

} /*end of else not PrintPDF */

	
	

echo '</div>';
echo '</div>';




			  
 	echo '</div >';
	?>
						

		
					</div>
				</div>
			</div>
					
					
 
						<!--end:: Widgets/Stats-->

						<!--Begin::Section-->
						

		<!-- end::Quick Sidebar -->

		<!-- begin::Scroll Top -->
		<div id="m_scroll_top" class="m-scroll-top">
			<i class="la la-arrow-up"></i>
		</div>

		<!-- end::Scroll Top -->

		<!-- begin::Quick Nav -->
		

		<!-- begin::Quick Nav -->
<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>

		<!--end::Page Scripts -->
	</body>

	<!-- end::Body -->
</html>
 
      
<?php



/*The module link codes are hard coded in a switch statement below to determine the options to show for each tab */
include('includes/MainMenuLinksArray.php');

if (isset($SupplierLogin) AND $SupplierLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=1">' . _('View or Amend outstanding offers') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=2">' . _('Create a new offer') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=3">' . _('View any open tenders without an offer') . '</a></p>
			</td>
			</tr>
		</table>';
	include('includes/footer.inc');
	exit;
} elseif (isset($CustomerLogin) AND $CustomerLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/CustomerInquiry.php?CustomerID=' . $_SESSION['CustomerID'] . '">' . _('Account Status') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectOrderItems.php?NewOrder=Yes">' . _('Place An Order') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectCompletedOrder.php?SelectedCustomer=' . $_SESSION['CustomerID'] . '">' . _('Order Status') . '</a></p>
			</td>
			</tr>
		</table>';

	include('includes/footer.inc');
	exit;
}

if (isset($_GET['Application'])){ /*This is sent by this page (to itself) when the user clicks on a tab */
	$_SESSION['Module'] = $_GET['Application'];
}








//include('includes/footer.inc');

function GetRptLinks($GroupID) {
/*
This function retrieves the reports given a certain group id as defined in /reports/admin/defaults.php
in the acssociative array $ReportGroups[]. It will fetch the reports belonging solely to the group
specified to create a list of links for insertion into a table to choose a report. Two table sections will
be generated, one for standard reports and the other for custom reports.
*/
	global $db, $RootPath, $ReportList;
	require_once('reportwriter/languages/en_US/reports.php');
	require_once('reportwriter/admin/defaults.php');
	$GroupID=$ReportList[$GroupID];
	$Title= array(_('Custom Reports'), _('Standard Reports and Forms'));

	$sql= "SELECT id,
				reporttype,
				defaultreport,
				groupname,
				reportname
			FROM reports
			ORDER BY groupname,
					reportname";
	$Result=DB_query($sql,'','',false,true);
	$ReportList = '';
	while ($Temp = DB_fetch_array($Result)) $ReportList[] = $Temp;

	$RptLinks = '';
	for ($Def=1; $Def>=0; $Def--) {
        $RptLinks .= '<li class="menu_group_headers">';
        $RptLinks .= '<b>' .  $Title[$Def] . '</b>';
        $RptLinks .= '</li>';
		$NoEntries = true;
		if ($ReportList) { // then there are reports to show, show by grouping
			foreach ($ReportList as $Report) {
				if ($Report['groupname']==$GroupID AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/ReportMaker.php?action=go&amp;reportid=' . $Report['id'] . '">' . _($Report['reportname']) . '</a></p>';
					$RptLinks .= '</li>';
					$NoEntries = false;
				}
			}
			// now fetch the form groups that are a part of this group (List after reports)
			$NoForms = true;
			foreach ($ReportList as $Report) {
				$Group=explode(':',$Report['groupname']); // break into main group and form group array
				if ($NoForms AND $Group[0]==$GroupID AND $Report['reporttype']=='frm' AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/folders.gif" width="16" height="13" alt="" />&nbsp;';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/FormMaker.php?id=' . $Report['groupname'] . '"></p>';
					$RptLinks .= $FormGroups[$Report['groupname']] . '</a>';
					$RptLinks .= '</li>';
					$NoForms = false;
					$NoEntries = false;
				}
			}
		}
		if ($NoEntries) $RptLinks .= '<li class="menu_group_item">' . _('There are no reports to show!') . '</li>';
	}
	return $RptLinks;
}
	
?>
<!-- Modal HTML embedded directly into document -->
<div id="ex1" class="modal">
  <p>Thanks for clicking. That felt good.</p>
  <a href="#" rel="modal:close">Close</a>
</div>


<!-- Modal -->
 <div class="modal fade" id="getCodeModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
   <div class="modal-dialog modal-lg">
      <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
         <h4 class="modal-title" id="myModalLabel"> API CODE </h4>
       </div>
       <div class="modal-body" id="getCode" style="overflow-x: scroll;">
       
          
          
       </div>
    </div>
   </div>
 </div>
<script>
jQuery(document).ready(function($){

		$( "#customer" ).change(function () {
    var account = $(this).val();

//$('#department').attr("disabled", false);
    $('#department').hide();
			if(account == 'All') {

		

       
				//$('#department').attr("disabled", false);
               
 $('#department').show();

    }else{
        
		// $('#department').attr("disabled", true);
		
	$('#department').hide();
		//$('#department').empty();
		$('#department').val(0);
    }
		
	
		
});

	
	
   }); 
	
	

	
	
		
		

	
	
</script>


<script type="text/javascript">
jQuery(document).on("ready xcrudafterrequest",function(){
    
});
</script>