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


		//get session data
$userid = $_SESSION['UserID'];

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

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

//first check whether this costing is approved or not

$SQL = "SELECT phase_name,start_date, end_date,actual_material,actual_labor,actual_others,billing_amount_vep,narrative, comments,status
	               
			FROM progressive_billing
			WHERE pgid='" . $id. "'
			";
	
			$result = DB_query($SQL);
	
			$myrow = DB_fetch_array($result) ;
		$status = $myrow['status'];
$phasename= $myrow['phase_name'];
$narrative= $myrow['narrative'];
$commentbill= $myrow['comments'];
$billingamountvep= $myrow['billing_amount_vep'];



 

$yeardate = date('Y',strtotime( $myrow['end_date']));
$monthdate =date('m',strtotime( $myrow['end_date']));
$monthname =date('M',strtotime( $myrow['end_date']));



if ($status !== 'approved'){
	
	$message = "This bill setup  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();
	
}

		//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.
		
	elseif ($status == 'approved'){
		
		
		
$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 = "SELECT projectid,
	               project_type,
				   project_name,
				   retention_rate,
				   department,
				   customer,
				   branch,
				   account_number,
				   contact_number,
				   required_date,
				   start_date,
				   sales_gl,
				   cogs_gl,
				   comments
			FROM projectdetails 
			WHERE projectid='" . $jobno . "'
			";
	
			$result = DB_query($SQL);
	
			$myrow = DB_fetch_array($result) ;
		
		$ac = $myrow['account_number'];
		
			$debtorno = $myrow['customer'];
		$branchcode = $myrow['branch'];
		$projecttype = $myrow['project_type'];
		$projectname = $myrow['project_name'];
		$department = $myrow['department'];
		$salesgl = $myrow['sales_gl'];
		$cogsgl = $myrow['cogs_gl'];
				$retention= $myrow['retention_rate'];	
	$contactnumber = $myrow['contact_number'];
		
	$deliverydate =  $myrow['required_date'];
			
	$confirmeddate =  $myrow['start_date'];
			$comments = $myrow['comments'];
		
		$quotedated = date('Y-m-d');
		$quotedate = date('d-m-Y');
		//todays date.This is to show today quote was generated
	$retenrate = $retention/100;
		
		//get debtor headoffice details:
		$SQL100 = "SELECT 	name,
							address1,
						     address2,
				   			 address3,
							 address4,
							 address5,
							 address6
							 
			FROM debtorsmaster
			WHERE debtorno='" . $debtorno . "'
			";
	
	$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='" . $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'];
		
		

		
		
		//insert in salesorders to create new sales order/quote. The system can only add quotation and cant update it.
		//$Result = DB_Txn_Begin();

	    $InvoiceNo = GetNextTransNo(10, $db);
		
		$OrderNo = GetNextTransNo(30, $db);
	//get periodno 
	
	
	    $query2 = "SELECT 
						periodno,
		             lastdate_in_period
		                 
					  
		          FROM periods
				    WHERE YEAR(lastdate_in_period) = '" . $yeardate . "'
					AND MONTH(lastdate_in_period)  = '" . $monthdate. "'";
				
        $result2=DB_query($query2);
        $myrow2=DB_fetch_array($result2);
      
				$PeriodNo = $myrow2['periodno'];
		     	$data = $myrow2['lastdate_in_period'];	
		
		$sql = "INSERT INTO salesorders (
								orderno,
								debtorno,
								branchcode,
								account_number,
								job_no,								
								comments,
								orddate,
								ordertype,
								shipvia,
								deliverto,
								deladd1,
								deladd2,
								deladd3,
								deladd4,
								deladd5,
								deladd6,
								contactphone,
								contactemail,
								freightcost,
								fromstkloc,
								deliverydate,
								quotedate,
								
								confirmeddate,
								quotation,
								status,
								deliverblind,
								preparedby)
							VALUES (
								'". $OrderNo . "',
								'" . $debtorno . "',
								'" . $branchcode . "',
								'". $ac ."',
								'". $jobno ."',
								'". $comments ."',
								'". $quotedated ."',
								'DF',
								'1',
								'".$debtorname."',
								'". $branchad1."',
								'". $branchad2 ."',
								'". $branchad3 ."',
								'". $branchad4 ."',
								'". $branchad5."',
								'". $branchad6 ."',
								'". $phoneno ."',
								'". $email ."',
								'0',
								'SUVA',
								'". $deliverydate ."',
							     '". $quotedated ."',
								'". $quotedated ."',
								'0',
								'Invoiced',
								'1',
								'". $userid."'
								)";

		//$ErrMsg = _('This customer could not be added because');
		
			$result = DB_query($sql);
	
			$sql6 = "INSERT INTO salesorderdetails (
											orderlineno,
											orderno,
											stkcode,
											unitprice,
											quantity,
											discountpercent,
											narrative,
											poline,
											itemdue)
										VALUES  (
								'1',
								'" . $OrderNo . "',
								'CONTRACTBILL',
								'". $billingamountvep."',
								'1',
								0,
								'".$narrative."',
								'',
								'". $quotedated."'
								)";

							
			$result6 = DB_query($sql6);
	
		
		
	include ('includes/class.pdf.php');

	/* This invoice is hard coded for A4 Landscape invoices or credit notes so can't use PDFStarter.inc */
		

	$Page_Width=842;
	$Page_Height=595;
	$Top_Margin=30;
	$Bottom_Margin=30;
	$Left_Margin=40;
	$Right_Margin=30;


	$pdf = new Cpdf('L', 'pt', 'A4');
	$pdf->addInfo('Creator', 'ebusinessERP http://www.ebusinessfiji.com');
	$pdf->addInfo('Author', 'ebusinessERP ' . $Version);

	

	$pdf->setAutoPageBreak(0);
	$pdf->setPrintHeader(false);
	$pdf->setPrintFooter(false);
	$pdf->AddPage();
	$pdf->cMargin = 0;
/* END Brought from class.pdf.php constructor */

	$FirstPage = true;
	$line_height=16;
	 $FontSize = 10;
				$PageNumber = 1;

				include('includes/PDFinvoicePageHeader.inc');
		
		
		
		//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.
	
			
				
				
				
				
				//write to pdf
				
				$ovamount = $unitprice * $myrow5['qty'];
			    
			   $totalvep = $billingamountvep;
			
				
			

					$LeftOvers = $pdf->addTextWrap($Left_Margin+3,$YPos,95,$FontSize, $id);
								
			     	$LeftOvers = $pdf->addTextWrap($Left_Margin+100,$YPos,251,$FontSize, $phasename );
					
					$LeftOvers = $pdf->addTextWrap($Left_Margin+353,$YPos,96,$FontSize,$billingamountvep,'centre');
					$LeftOvers = $pdf->addTextWrap($Left_Margin+453,$YPos,95,$FontSize,'','right');
					$LeftOvers = $pdf->addTextWrap($Left_Margin+553,$YPos,35,$FontSize,'','centre');
					$LeftOvers = $pdf->addTextWrap($Left_Margin+590,$YPos,50,$FontSize,'','right');
					$LeftOvers = $pdf->addTextWrap($Left_Margin+642,$YPos,120,$FontSize,$billingamountvep,'right');
				
					$YPos -= ($line_height);
			$lines=explode("\r\n",htmlspecialchars_decode($narrative));
					for ($i=0;$i<sizeOf($lines);$i++) {
						while (mb_strlen($lines[$i])>1) {
							if ($YPos-$line_height <= $Bottom_Margin) {
								/* head up a new invoice/credit note page */
								/* draw the vertical column lines right to the bottom */
								PrintLinesToBottom ();
	   		        				include('includes/PDFinvoicePageHeader.inc');
			   				} //end if need a new page headed up

			   				/* increment a line down for the next line item */
			   				if (mb_strlen($lines[$i])>1){
								$lines[$i] = $pdf->addTextWrap($Left_Margin+100,$YPos,245,$FontSize,stripslashes($lines[$i]));
							}
							$YPos -= ($line_height);
						}
					} //end for loop around lines of narrative to display
					if ($YPos <= $Bottom_Margin) {

						/* head up a new invoice/credit note page */
						/*draw the vertical column lines right to the bottom */
						PrintLinesToBottom ();
						include('includes/PDFinvoicePageHeader.inc');
					} //end if need a new page headed up

				
			$YPos -= $line_height;
			
				
				
				
				
				
			
			
			
		
			
		

			/* Print a column vertical line  with enough space for the footer */
			/* draw the vertical column lines to 4 lines shy of the bottom to leave space for invoice footer info ie totals etc */
			$pdf->line($Left_Margin+97, $TopOfColHeadings+12,$Left_Margin+97,$Bottom_Margin+(4*$line_height));

			/* Print a column vertical line */
			$pdf->line($Left_Margin+350, $TopOfColHeadings+12,$Left_Margin+350,$Bottom_Margin+(4*$line_height));

			/* Print a column vertical line */
			$pdf->line($Left_Margin+450, $TopOfColHeadings+12,$Left_Margin+450,$Bottom_Margin+(4*$line_height));

			/* Print a column vertical line */
			$pdf->line($Left_Margin+550, $TopOfColHeadings+12,$Left_Margin+550,$Bottom_Margin+(4*$line_height));

			/* Print a column vertical line */
			$pdf->line($Left_Margin+587, $TopOfColHeadings+12,$Left_Margin+587,$Bottom_Margin+(4*$line_height));

			$pdf->line($Left_Margin+640, $TopOfColHeadings+12,$Left_Margin+640,$Bottom_Margin+(4*$line_height));

			/* Rule off at bottom of the vertical lines */
			$pdf->line($Left_Margin, $Bottom_Margin+(4*$line_height),$Page_Width-$Right_Margin,$Bottom_Margin+(4*$line_height));

			/* Now print out the footer and totals */

			

				$DisplaySubTot = locale_number_format($myrow['ovamount'],$myrow['decimalplaces']);
				$DisplayFreight = locale_number_format($myrow['ovfreight'],$myrow['decimalplaces']);
				$DisplayTax = locale_number_format($myrow['ovgst'],$myrow['decimalplaces']);
				$DisplayTotal = locale_number_format($myrow['ovfreight']+$myrow['ovgst']+$myrow['ovamount'],$myrow['decimalplaces']);


			

			/* Print out the invoice text entered */
			$YPos = $Bottom_Margin+(3*$line_height);
	       
			/* Print out the payment terms */
			$pdf->addTextWrap($Left_Margin+5,$YPos+3,380,$FontSize,_('TERMS: PAYMENT DUE ON 20th OF THE FOLLOWING MONTH OF PURCHASE'));
			$pdf->addTextWrap($Left_Margin+5,$YPos-10,600,$FontSize,_('BANK DETAILS: '));
	$pdf->addTextWrap($Left_Margin+5,$YPos-20,600,$FontSize,_('Westpac Bank: A/C: 9804778075 | ANZ Bank: A/C: 11879362 | BSP Bank: A/C: 9837614'));
	$pdf->addTextWrap($Left_Margin+200,$YPos-40,600,$FontSize,_('Wormald Fire & Security appreciates your Business!:'));
		//      $pdf->addText($Page_Width-$Right_Margin-392, $YPos - ($line_height*3)+22,$FontSize, _('Bank Code:***** Bank Account:*****'));
		//	$FontSize=10;

			$FontSize =8;
			$LeftOvers = $pdf->addTextWrap($Left_Margin+5,$YPos-12,280,$FontSize,_(''));
			if (mb_strlen($LeftOvers)>0) {
				$LeftOvers = $pdf->addTextWrap($Left_Margin+5,$YPos-24,280,$FontSize,$LeftOvers);
				if (mb_strlen($LeftOvers)>0) {
					$LeftOvers = $pdf->addTextWrap($Left_Margin+5,$YPos-36,280,$FontSize,$LeftOvers);
					/*If there is some of the InvText leftover after 3 lines 200 wide then it is not printed :( */
				}
			}
			$FontSize = 10;
			
			
	
		$retentionamount =  $totalvep * $retenrate;
	
	$finaltotalvep = $totalvep - $retentionamount;
	$vat = $finaltotalvep * 0.09;
			
			$totalvip = $finaltotalvep+$vat;
	       //2 decimal point outpu
	
	$vatfinal = locale_number_format($vat,2);
				$displaytotalfinal= locale_number_format($totalvip,2);
	
	$totalvepdec = locale_number_format($totalvip,2);
	$reten = locale_number_format($retentionamount,2);
			$DisplayFreight = 0;

			$pdf->addText($Page_Width-$Right_Margin-220, $YPos+15,$FontSize, _('Sub Total'));
			$LeftOvers = $pdf->addTextWrap($Left_Margin+642,$YPos+5,120,$FontSize,locale_number_format($totalvep,2), 'right');

			$pdf->addText($Page_Width-$Right_Margin-220, $YPos+2,$FontSize, _('Retention:'));
	$pdf->addText($Page_Width-$Right_Margin-170, $YPos+2,$FontSize, $retention );
	$pdf->addText($Page_Width-$Right_Margin-150, $YPos+2,$FontSize,  _('%') );
			$LeftOvers = $pdf->addTextWrap($Left_Margin+642,$YPos-6,120,$FontSize,$reten, 'right');
	
	
			//$pdf->addText($Page_Width-$Right_Margin-220, $YPos-10,$FontSize, _('Total VIP'));
			//$LeftOvers = $pdf->addTextWrap($Left_Margin+642,$YPos-($line_height)-5,120, $FontSize,$totalvipdec, 'right');
	
	//terms
	//$pdf->addText($Page_Width-$Right_Margin-700, $YPos-10,$FontSize, _('TERMS: Payment due on 20th following month of purchase'));
			
	
		$pdf->addText($Page_Width-$Right_Margin-220, $YPos-10,$FontSize, _('VAT'));
			$LeftOvers = $pdf->addTextWrap($Left_Margin+642,$YPos-($line_height)-5,120, $FontSize,$vatfinal, 'right');

			/*rule off for total */
			$pdf->line($Page_Width-$Right_Margin-222, $YPos-(2*$line_height),$Page_Width-$Right_Margin,$YPos-(2*$line_height));

			/*vertical to separate totals from comments and ROMALPA */
			$pdf->line($Page_Width-$Right_Margin-222, $YPos+$line_height,$Page_Width-$Right_Margin-222,$Bottom_Margin);

			$YPos+=10;
			
				$pdf->addText($Page_Width-$Right_Margin-220, $YPos - ($line_height*2)-10,$FontSize, _('TOTAL INVOICE DUE'));
				$FontSize=9;
				$YPos-=4;
				$LeftOvers = $pdf->addTextWrap($Left_Margin+280,$YPos,220,$FontSize,$commentbill);
				while (mb_strlen($LeftOvers)>0 AND $YPos > $Bottom_Margin) {
					$YPos-=12;
					$LeftOvers = $pdf->addTextWrap($Left_Margin+280,$YPos,220,$FontSize,$LeftOvers);
				}
				
			$LeftOvers = $pdf->addTextWrap($Left_Margin+642,35,120, $FontSize,$displaytotalfinal, 'right');
		

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

		
			$filename = 'invoices/evergreeninvoice_' . $InvoiceNo. '.pdf';
					

// Output PDF
$pdf->Output($filename, 'F');
		
			echo '<br /><p></p><p></p> <p></p> <p></p> <p></p>  <p class="page_title_text"><a href="' . $filename . '">' . _('View this invoice no: ') . $InvoiceNo. '</p>';
					
			echo '<br/>';
	
		
	
	$pdf->__destruct();
		
	//upload data in Debtor
	
        
	 
			
	//start = FormatDateForSQL($start);
	
		


	
			//update salesorderdetails status to trace whether quotation is invoiced or not

	
	
				
}

			
		
			
		
			
		
		
		
			    
		
	
//echo 'Quotation Created Successfully'. $jobno.'!';




//echo 'Quotation Created Successfully'. $jobno.'!';
echo '</div>';
echo '</div>';

//include('includes/footer.inc'); 
	
	function PrintLinesToBottom () {

	global $pdf;
	global $PageNumber;
	global $TopOfColHeadings;
	global $Left_Margin;
	global $Bottom_Margin;
	global $line_height;

	/* draw the vertical column lines right to the bottom */
	$pdf->line($Left_Margin+97, $TopOfColHeadings+12,$Left_Margin+97,$Bottom_Margin);

	/* Print a column vertical line */
	$pdf->line($Left_Margin+350, $TopOfColHeadings+12,$Left_Margin+350,$Bottom_Margin);

	/* Print a column vertical line */
	$pdf->line($Left_Margin+450, $TopOfColHeadings+12,$Left_Margin+450,$Bottom_Margin);

	/* Print a column vertical line */
	$pdf->line($Left_Margin+550, $TopOfColHeadings+12,$Left_Margin+550,$Bottom_Margin);

	/* Print a column vertical line */
	$pdf->line($Left_Margin+587, $TopOfColHeadings+12,$Left_Margin+587,$Bottom_Margin);

	$pdf->line($Left_Margin+640, $TopOfColHeadings+12,$Left_Margin+640,$Bottom_Margin);

	$PageNumber++;
	}
?>
