<?php
ob_start();
include('includes/session.inc');
$Title = _('Create Invoice');
include('includes/SQL_CommonFunctions.inc');


	

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


//first check whether this costing is approved or not


	
$SQL = "SELECT customer,branchcode,month,year,account_number,department,invoice_date,lpo,gl_type,sales_gl,cogs_gl,comments,status,modified_by
	               
			FROM billing
			WHERE bill_id='" . $billingid. "'
			";
	
			$result = DB_query($SQL);
	
			$myrow = DB_fetch_array($result) ;
		$status = $myrow['status'];

$gltype =$myrow['gl_type'];
$salegl=$myrow['sale_gl'];
$cogsgl =$myrow['cogs_gl'];

$date =$myrow['invoice_date'];
		//open projectdetail table to start gathering informations which we will first insert at salesorders table  and get pdf headers written. Salesorders will assist in converting quotation to invoice. This below is simply a quote generation.
		

			$sql81 =  "SELECT sum(total) as salestotal,sum(total_cost) as costtotal
			FROM bill_items
			
			WHERE bill_id = '" . $billingid. "'
			";
	$ErrMsg = _('This customer could not be added because');
			$result81 = DB_query($sql81,$ErrMsg);
$myrow81 = DB_fetch_array($result81);
$totalsales = $myrow81['salestotal'];
$costsales = $myrow81['costtotal'];

if ($status=='approved'){
	
		$quotedated = date('Y-m-d',strtotime($myrow['invoice_date']));
		$quotedate = date('d-m-Y',strtotime($myrow['invoice_date']));
	
	$yeardate = date('Y',strtotime($myrow['invoice_date']));
$monthdate =date('m',strtotime($myrow['invoice_date']));
	$SQL77 = "SELECT 	departmentname
							 
			FROM department
			WHERE departmentid='" . $myrow['department'] . "'
			";
	
	$result77 = DB_query($SQL77);
	
	$myrow77 = DB_fetch_array($result77) ;
		
	$departmentname = $myrow77['departmentname'];	
//get debtor headoffice details:
		$SQL100 = "SELECT 	name,
							address1,
						     address2,
				   			 address3,
							 address4,
							 address5,
							 address6
							 
			FROM debtorsmaster
			WHERE debtorno='" . $myrow['customer'] . "'
			";
	
	$result100 = DB_query($SQL100);
	
	$myrow100 = DB_fetch_array($result100) ;
		$debtorname = $myrow100['name'];
		
		$address1 = $myrow100['address1'];
		$address2 = $myrow100['address2'];
		$address3 = $myrow100['address3'];
		$address4 = $myrow100['address4'];
		$address5 = $myrow100['address5'];
		$address6=  $myrow100['address6'];
		
		
		
		
		//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'];
		
		



$InvoiceNo = GetNextTransNo(10, $db);
			//get periodno 
	
	$OrderNo = GetNextTransNo(30, $db);
	    $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'];	
				
	
		$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'];
	
	$sql = "INSERT INTO salesorders (
								orderno,
								lpo,
								debtorno,
								branchcode,
								account_number,
								bill_id,								
								comments,
								orddate,
								ordertype,
								shipvia,
								deliverto,
								deladd1,
								deladd2,
								deladd3,
								deladd4,
								deladd5,
								deladd6,
								contactphone,
								contactemail,
								freightcost,
								fromstkloc,
								deliverydate,
								amount,
								total_cost,
								quotedate,								
								confirmeddate,
								quotation,
								
								status,
								deliverblind,
								department,
								preparedby)
							VALUES (
								'". $OrderNo . "',
								'" . $myrow['lpo'] . "',
								'" . $myrow['customer'] . "',
								'" . $myrow['branchcode'] . "',
								'". $myrow['account_number'] ."',
								'". $billingid ."',
								'". $myrow['comments']."',
								'". $quotedated ."',
								'DF',
								'1',
								'".$debtorname."',
								'". $branchad1."',
								'". $branchad2 ."',
								'". $branchad3 ."',
								'". $branchad4 ."',
								'". $branchad5."',
								'". $branchad6 ."',
								'". $phoneno ."',
								'". $email ."',
								'0',
								'SUVA',
								'". $quotedated ."',
										'". $totalsales."',
												'". $costsales."',
							     '". $quotedated ."',
								'". $quotedated ."',
								'0',
								
								'Invoiced',
								'1',
								'". $myrow77['departmentname']."',
								'". $realname."'
								)";

		//$ErrMsg = _('This customer could not be added because');
		
			$result = DB_query($sql);
	
	
$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') . ' ' . $_GET['orderno']);
$FontSize = 12;
$line_height = 12;// Recommended: $line_height = $x * $FontSize.
		
		include('includes/PDFInvoiceHeaderCIT.inc');


	



		

			$sql8 =  "SELECT *
			FROM bill_items
			
			WHERE bill_id = '" . $billingid. "'
			";
	$ErrMsg = _('This customer could not be added because');
			$result8 = DB_query($sql8,$ErrMsg);
	
		
 $totalvep = 0;
			while ($myrow1 = DB_fetch_array($result8)) { 
		
		
			
		//todays date.This is to show today quote was generated
	
		
		//insert in salesorderdetails
				
				$sql6 = "INSERT INTO salesorderdetails (
											orderlineno,
											orderno,
											stkcode,
											stock_name,
											unitprice,
											quantity,
											uom,
											cost_price,
											sales_gl,
											cogs_gl,
											discountpercent,
										
											poline,
											itemdue)
										VALUES  (
								'".   $myrow1['id'] . "',
								'" . $OrderNo . "',
								'" . $myrow1['stock_id'] . "',
								'" . $myrow1['description'] . "',
								'". $myrow1['unit_price']."',
								'". $myrow1['qty']."',
								'". $myrow1['uom']."',
								'". $myrow1['cost_price']."',
								'". $myrow1['sales_gl']."',
								'". $myrow1['cogs_gl']."',
								0,
								
								'',
								'". $quotedated."'
								)";

							$ErrMsg = _('This customer could not be added because');
			$result6 = DB_query($sql6,$ErrMsg);
		//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.
		
				
				//if gl type was multiple then process below:
				
				
			
			   $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/PDFInvoiceHeaderCIT.inc');
		} //end if need a new page headed up

			
			
						
			
	
				
	
								//$myrow6 = DB_fetch_array($result6) ;
				
				
				//write to pdf
				
				$total = $myrow1['total'];
			    
			 
			   $totalvep = $totalvep + $myrow1['total'];
				
				$stup = locale_number_format($myrow1['unit_price'],4);
				
				$stovm = locale_number_format($ovamount,2);

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

		$LeftOvers = $pdf->addText($Left_Margin, $YPos+$FontSize, $FontSize,$myrow1['description']);
		$LeftOvers = $pdf->addText(145, $YPos+$FontSize, $FontSize, $myrow55['description']);
	
		$LeftOvers = $pdf->addTextWrap(520, $YPos,85,$FontSize,$myrow1['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, $total,'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/PDFInvoiceHeaderCIT.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/PDFInvoiceHeaderCIT.inc');
	} //end if need a new page headed up

			
				
		}	
		

		
			
		
		
		$FontSize = 10;
		

			
	$vat = $totalvep * 0.09;
			
			$totalvip = $totalvep+$vat;
	       //2 decimal point outpu
	
	$vatfinal = locale_number_format($vat,2);
				$displaytotalfinal= locale_number_format($totalvip,2);
	
	$totalvepdec = locale_number_format($totalvep,2);
		
			$DisplayFreight = 0;
			
			
			
	$YPos -= $line_height;
	/*rule off for total */
			$pdf->line($Page_Width-$Right_Margin-773, $YPos+7,$Page_Width-$Right_Margin,$YPos+7);
	$pdf->line($Page_Width-$Right_Margin-773, $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, _('$').$totalvepdec, 'right');

$YPos -= $FontSize;
	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90-655, $YPos-8, 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-10, 655, $FontSize, _('Total VIP'),'right');
	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos-11, 90, $FontSize, _('$').$displaytotalfinal, 'right');

	// Print salesorders.comments:
	$YPos -= $FontSize*2;
	$pdf->addText($XPos+250, $YPos+$FontSize-150, $FontSize, _('TERMS: PAYMENT DUE ON 20th OF THE FOLLOWING MONTH OF PURCHASE'),'centre');
	$pdf->addText($XPos+200, $YPos+$FontSize-165, $FontSize, _('OUR BANKS: Westpac Bank: A/C: 9804778075 | ANZ Bank: A/C: 11879362 | BSP Bank: A/C: 9837614'));
	$pdf->addText($XPos+300, $YPos+$FontSize-195, $FontSize, _('Wormald Fire & Security appreciates your business!'));
	$pdf->addText($XPos, $YPos+$FontSize-215, $FontSize, _('Comments').':');
	$Width2 = $Page_Width-$Right_Margin-120;// Width to print salesorders.comments.
$LeftOvers =	$pdf->addText($XPos, $YPos+$FontSize-55, $FontSize, $myrow['comments']);
	//$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/PDFInvoiceHeaderCIT.inc');
		}
		$LeftOvers = $pdf->addTextWrap(40, $YPos, $Width2, $FontSize, $LeftOvers);
	}
$pdf->addText($XPos+330, $YPos+$FontSize-250, $FontSize, _('Powered by E-Business ERP System'));
 /*end if there are line details to show on the quotation*/

//debtor trans and debtor vat
			$SQLdebtor = "INSERT INTO debtortrans (transno,
									type,
									debtorno,
									bill_id,
							
									branchcode,
									trandate,
									inputdate,
									prd,
									settled,
									reference,
									tpe,
									order_,
									lpo,
									rate,
									ovamount,
									ovgst,
								
									invtext,
									account_number,
									department,
									entered_by)
				VALUES (
					'" . $InvoiceNo. "',
					'10',
					'" . $myrow['customer']. "',
					'" . $billingid. "',
					'" . $myrow['branchcode']. "',
					'" . $quotedated. "',
					'" . $myrow['invoice_date'] . "',
					
					'" . $PeriodNo . "',
					'0',
					'Billing Invoice',
					'DE',
					
					 '" . $OrderNo . "',
					 '" . $myrow['lpo'] . "',
					'1',
					'" . $totalvep . "',
					'" . $vat . "',
					
					'" . $myrow['comments'] . "',
					'" . $myrow['account_number']. "',
					'" . $myrow['department']. "',
					'" . $realname . "'
					)";
		$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',
									'" . $vat. "')";

		$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  billing set status = 'locked' where bill_id = '" . $billingid . "'";
	
		$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);
	

	
	

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

		
		
	
	$pdf->__destruct();
		
	
}
else
	$message = "This Billing  is not approved yet. Ask your manager to approve it first before generating invoice";
	echo "<script type='text/javascript'>alert('$message');</script>";
		echo "<script type='text/javascript'>javascript:history.go(-1)</script>"; 
	exit();
	
				


			
		
	
		
			
		

		
		
			    
		
	


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

?>
