<?php
ob_start();

include('includes/session.inc');



include('includes/SQL_CommonFunctions.inc');


		
  if (isset($_GET['status'])) {
		$_SESSION['status'] = stripslashes($_GET['status']);
	}
	$status = $_SESSION['status'];
 if (isset($_GET['id'])) {
		$_SESSION['id'] = stripslashes($_GET['id']);
	}
	$monitoringid = $_SESSION['id'];

		  if (isset($_GET['start_date'])) {
		$_SESSION['start_date'] = stripslashes($_GET['start_date']);
	}
	$start_date = $_SESSION['start_date'];

  if (isset($_GET['end_date'])) {
		$_SESSION['end_date'] = stripslashes($_GET['end_date']);
	}
	$end_date = $_SESSION['end_date'];


  if (isset($_GET['due_date'])) {
		$_SESSION['due_date'] = stripslashes($_GET['due_date']);
	}
	$due_date = $_SESSION['due_date'];


  if (isset($_GET['invoice_date'])) {
		$_SESSION['invoice_date'] = stripslashes($_GET['invoice_date']);
	}
	$invoice_date = $_SESSION['invoice_date'];
		

if ($status =="locked" || $status =="pending"){
	$message = "Status is locked or pending. You cant Process unless  management changes it to approved";
	echo "<script type='text/javascript'>alert('$message');</script>";
echo "<script type='text/javascript'>javascript:history.go(-1)</script>"; 
	exit();
	
}
	else {								
		
		
		$quotedate = date('d-m-Y',strtotime($invoice_date));
$readableduedate = date('d-m-Y',strtotime($due_date));
//$quotedateraw = $_POST['order_date'] ;

 //$sqldate= FormatDateForSQL(DB_escape_string($_POST['order_date'] ));

	$userid = $_SESSION['UserID'];
		
				
$SQLuser = "SELECT email,realname
	               
			FROM www_users
			WHERE userid='" . $userid. "'
			";
	
			$resultuser = DB_query($SQLuser);
	
			$myrowuser = DB_fetch_array($resultuser) ;
		$emailm= $myrowuser['email'];
$realname= $myrowuser['realname'];
		
			$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', _('MOnitoring') );
$FontSize = 12;
$line_height = 12;// Recommended: $line_height = $x * $FontSize.
		

$sql4 =  "SELECT *
			FROM monitoring_master_data
			WHERE active = '1'
			AND type ='1'
			
			";
	$ErrMsg = _('This customer could not be added    because');
			$result4 = DB_query($sql4,$ErrMsg);
		
		

		
		
		
		
			
while ($myrow4 = DB_fetch_array($result4)) {
			
			$account =$myrow4['account_number'];
	      $firstname =$myrow4['first_name'];
		  $lastname =$myrow4['last_name'];
	  $businessname =$myrow4['business_name'];
	  $billcity =$myrow4['bill_city'];
	  $billaddr =$myrow4['bill_address'];
			
		$yeardate = date('Y',strtotime($invoice_date));
		$monthdate =date('M',strtotime($invoice_date));
			
			   
		

	$department = 'Monitoring';	


		
	

$InvoiceNo = GetNextTransNo(10, $db);

			//get periodno 

	

	$OrderNo = GetNextTransNo(30, $db);

		      
			//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'];	
				


	$sql = "INSERT INTO salesorders (

								orderno,

							    monitoring_customer,

								

								orddate,

								ordertype,

								shipvia,

								status,

								department,

								preparedby)

							VALUES (

								'". $OrderNo . "',

								'" . $myrow4['id'] . "',								

							

								'". $invoice_date ."',

								'DF',

								'1',

															
								'Invoiced',


								'". $department ."',

								'". $realname."'

								)";



		//$ErrMsg = _('This customer could not be added because');

		

			$result = DB_query($sql);

	

	   

	   

	   //get the payid from above

				$sqlpayid =  "SELECT orderno

						 

			FROM salesorders  ORDER BY orderno DESC LIMIT 1;

			

			";

	$ErrMsg = _('This customer could not be added because');

			$resultpayid = DB_query($sqlpayid,$ErrMsg);

			$myrowpayid = DB_fetch_array($resultpayid);

			

			$lastid = $myrowpayid['orderno'];

			
	   

		include('includes/PDFInvoiceHeaderMonitoring.inc');



		
		
		//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.
		
			$YPos -= $line_height;//
	
			
		$vepamount= $myrow4['vep_amount'];
		
		$vat = ($vepamount * 0.09);
		
			$vatfinal = locale_number_format($vat,2);
		
		$finalamount = $vepamount + $vatfinal;
		
		$displaytotalfinal= locale_number_format($finalamount,2);
	
	$LeftOvers = $pdf->addText(130, $YPos+$FontSize, $FontSize,_('Monitoring Premises'));
		$LeftOvers = $pdf->addText(130, $YPos+$FontSize, $FontSize,_('__________________'));
				
$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90,$YPos,85,$FontSize,$vepamount,'right');

	
				


			
	//loop and display all premises
	
$sqlm =  "SELECT *
			FROM monitoring_premises
			WHERE account_number ='" . $myrow4['account_number'] . "'
			AND active = '1'
	        
			";
	$ErrMsg = _('This customer could not be added    because');
			$resultmonitoring = DB_query($sqlm,$ErrMsg);
				
			$count =0;
				
		while ($myrowm = DB_fetch_array($resultmonitoring)) {
				
	
			
		
				//add to sales orders details and show pdf
			
			 $sql6 = "INSERT INTO salesorderdetails (

											orderlineno,

											orderno,

											stkcode,

											stock_name,

											unitprice,

											quantity,

											uom,

											tax_code,


											sales_gl,
											
											poline,

											itemdue)

										VALUES  (

								'".   $count. "',

								'" . $OrderNo . "',

								'monitoring',

								'" .  $myrowm['premises'] . "',

								'". $myrowm['monthly_rate']."',

								'1',

								'each',

								'Vat',

							

								'S70005',

								

								0,

							
								'". $invoice_date."'

								)";



							$ErrMsg = _('This customer could not be added because');

			$result6 = DB_query($sql6,$ErrMsg);
			
			
      
			
    
			
			   $ListCount ++;
				

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

		

			

					$FontSize = 10;// Font size for the line item.



		$LeftOvers = $pdf->addText(130, $YPos+$FontSize, $FontSize,$myrowm['premises']);

		//$LeftOvers = $pdf->addText(145, $YPos+$FontSize, $FontSize, _(''));

	//$LeftOvers = $pdf->addTextWrap(450, $YPos,85,$FontSize,_(''),'right');

	//	$LeftOvers = $pdf->addTextWrap(510, $YPos,85,$FontSize,_(''),'right');

	  //$LeftOvers = $pdf->addTextWrap(570, $YPos,85,$FontSize,_(''),'right');

		

				$LeftOvers = $pdf->addTextWrap(650, $YPos,85,$FontSize,$myrowm['monthly_rate'],'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/PDFInvoiceHeaderMonitoring.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/PDFInvoiceHeaderMonitoring.inc');
				
				
				
	} //end if need a new page headed up

		  
		  
		  
		  
		  
	  $count++;
			
			
		
			
		
		}	
		

//above
	   

      //$order_total_tax = $order_total_tax1 + $order_total_tax2 + $order_total_tax3;

		

	   		

	//update status

//check amount in master records
	
	
		
	

  



				

		$FontSize = 10;

	



	$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, _('$').$vepamount, '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, _(''), 'right');

$YPos -= $FontSize;

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

	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos-9, 90, $FontSize, _('$').$vatfinal, 'right');

	   

	$YPos -= $FontSize;



	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90-655, $YPos-12, 655, $FontSize, _('Total(VIP)'),'right');

	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos-13, 90, $FontSize, _('$').$displaytotalfinal, '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: 9837614'));
$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-120;// Width to print salesorders.comments.

$LeftOvers =	$pdf->addTextWrap($XPos, $YPos+$FontSize-95,780,$FontSize, $myrow4['notes']);

	//$LeftOvers = trim($quoteterms);

		//$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

	//**********

	   if (mb_strlen($LeftOvers)>0) {

				$LeftOvers = $pdf->addTextWrap($XPos,$YPos+$FontSize-110,780,$FontSize,$LeftOvers);

				if (mb_strlen($LeftOvers)>0) {

						//$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

	//**********

					$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 :( */

				}

			}

	//**********

	$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/PDFInvoiceHeaderMonitoring.inc');

		}

		$LeftOvers = $pdf->addTextWrap(40, $YPos, $Width2, $FontSize, $LeftOvers);

	}

//$pdf->addText($XPos+330, $YPos+$FontSize-250, $FontSize, _('Powered by E-Business ERP 2.0'));

 /*end if there are line details to show on the quotation*/

	$timenow = time();

	$modifieddatetime = date("Y-m-d h:i:sa", $timenow);

	

//debtor trans and debtor vat

			$SQLdebtor = "INSERT INTO debtortrans (transno,

									type,

									monitoring_customer,
									monitoring_id,

									monitoring_duedate,
									monitoring_startdate,
									monitoring_enddate,
									trandate,

									inputdate,

									prd,

									settled,

									reference,

									tpe,

									order_,

									
									rate,

									ovamount,

									ovgst,

									

									sales_gl,

									old_sales_code,
									old_gl_code,
									
									account_number,

									department,

									entered_by,

									entered_date)

				VALUES (

					'" . $InvoiceNo. "',

					'10',

					'" . $myrow4['id']. "',
                    '" . $monitoringid. "',
					'" . $due_date. "',
					'" . $start_date. "',
					'" . $end_date. "',

					'" . $invoice_date. "',

					'" . $invoice_date . "',

					

					'" . $PeriodNo . "',

					'0',

					'Monitoring Invoice',

					'DE',

					

					 '" . $OrderNo . "',

					 

					'1',

					'" . $vepamount. "',

					'" . $vatfinal . "',

				

					 'S70005',

					 '803',
					  'S70005',

					

					'" . $myrow4['account_number']. "',

					'11',

					'" . $realname . "',

					'" . $modifieddatetime . "'
					)";

		$ErrMsg = _('Cannot insert a GL entry for the journal line because');

		$DbgMsg = _('The SQL that failed to insert the GL Trans record was');

		$result = DB_query($SQLdebtor,$ErrMsg,$DbgMsg,true);

			

      $DebtorTransID = DB_Last_Insert_ID($db,'debtortrans','id');

			

			//debtortranstax


				

				$SQLdebtortax = "INSERT INTO debtortranstaxes (debtortransid,

											taxauthid,

											taxamount)

								VALUES ('" . $DebtorTransID . "',

									'5',

									'" . $vatfinal. "')";



		$ErrMsg =_('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The debtor transaction taxes records could not be inserted because');

		$DbgMsg = _('The following SQL to insert the debtor transaction taxes record was used');

 		$Result = DB_query($SQLdebtortax,$ErrMsg,$DbgMsg,true);

	   

				

			

		 

     

			

			//increase trade debtors

	

	

			

	//update status

	

	

	$SQL20 = "UPDATE  salesorders set amount = '" . $vepamount  . "',

									  tax1 = '" . $vatfinal . "',

									
									total_amount = '" . $displaytotalfinal . "'

									where orderno = '" . $OrderNo . "'";

	

		$ErrMsg = _('Cannot insert a GL entry for the journal line because');

		$DbgMsg = _('The SQL that failed to insert the GL Trans record was');

		$result20 = DB_query($SQL20,$ErrMsg,$DbgMsg,true);

	  

							

		}	//end of customer loop
		
		//produce pdf
		

ob_end_clean();
	 //its not an email just print the invoice to PDF
		$pdf->OutputD('NDP-monitoring_invoice'.'-'.$invoice_date.'.pdf');

		
		
	
	$pdf->__destruct();
			
			
		
		
				


	//success message and redirect to a page

$message = "Success";
	echo "<script type='text/javascript'>alert('$message');</script>";
echo "<script type='text/javascript'>javascript:history.go(-1)</script>"; 
	exit();

	}
	
?>
