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


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

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

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

//first check whether this costing is approved or not

$SQL = "SELECT name, status
	               
			FROM projectcosting
			WHERE pcid='" . $pcid. "'
			";
	
			$result = DB_query($SQL);
	
			$myrow = DB_fetch_array($result) ;
		$status = $myrow['status'];
$projectname= $myrow['name'];
if ($status !== 'approved costing'){
	
	$message = "This costing Sheet 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 costing'){
		
		
		
$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,
	              
				   customer,
				   account_number,
				   contact_number,
				   required_date,
				   start_date,
				   comments
			FROM projectdetails 
			WHERE projectid='" . $jobno . "'
			";
	
			$result = DB_query($SQL);
	
			$myrow = DB_fetch_array($result) ;
		
		$ac = $myrow['account_number'];
		
			$debtorno = $myrow['customer'];
					
	$contactnumber = $myrow['contact_number'];
		
	$deliverydate =  date('Y-m-d', $myrow['required_date']);
			
	$confirmeddate =  date('Y-m-d', $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
	
		
		//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'];
		
		
		//get customer branch code from debtoraccounts table
		
			$SQL1 = "SELECT branchcode,
			                departmentid
				   
			FROM debtoraccount 
			WHERE account_number='" . $ac . "'
			";
	
	$result1 = DB_query($SQL1);
	
	$myrow1 = DB_fetch_array($result1) ;
		
		$branchcode = $myrow1['branchcode'];
		$departmentid = $myrow1['departmentid'];
		
		
		//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'];
		
		
		
	$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();

	   $OrderNo = GetNextTransNo(30, $db);
		
		$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 ."',
								'". $confirmeddate."',
								'1',
								'Not Invoiced',
								'1',
								'". $username."'
								)";

		//$ErrMsg = _('This customer could not be added because');
		
			$result = DB_query($sql);
	
	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/PDFquotePageHeader.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.
		
		$sql4 = "SELECT 
					projectid,
					name,
					quote_terms
					
			FROM projectcosting
			WHERE pcid='" . $pcid . "'
			";
	$ErrMsg = _('This customer could not be added because');
			$result4 = DB_query($sql4,$ErrMsg);
	
		
	$myrow4 = DB_fetch_array($result4) ;
		
		
	 
		$quoteterms = $myrow4['quote_terms'];
	
	$materials='Materials-';
	$others='Others-';
		
		$sql5 = "SELECT projectcostingid,
					pcid,
					cost_type,
												item_id,
												item_details,
												narrative,
												unit_cost,
												qty,
												uom,
												total_cost,
												margin,
												price
			FROM projectcostingdetail
			WHERE pcid='" . $pcid . "'
			";
	$ErrMsg = _('This customer could not be added because');
			$result5= DB_query($sql5,$ErrMsg);
	
	$totalvep = 0;
		while ( $myrow5 = DB_fetch_array($result5)){
			 $orderline = $myrow5['projectcostingid'];
			 $costtype= $myrow5['cost_type'];
			 
			
			$totalpricevep = ($myrow5['unit_cost'] * $myrow5['qty']) / (1 - ($myrow5['margin']/100));

				$unitprice = $myrow5['unit_cost']  / (1 - ($myrow5['margin']/100));
			
			
			
				
				//insert in salesorderdetails
				
				$sql6 = "INSERT INTO salesorderdetails (
											orderlineno,
											orderno,
											stkcode,
											unitprice,
											quantity,
											discountpercent,
											narrative,
											poline,
											itemdue)
										VALUES  (
								'".  $orderline . "',
								'" . $OrderNo . "',
								'" . $myrow5['item_id'] . "',
								'". $unitprice."',
								'". $myrow5['qty']."',
								0,
								'".$myrow5['narrative']."',
								'',
								'". $quotedated."'
								)";

							$ErrMsg = _('This customer could not be added because');
			$result6 = DB_query($sql6,$ErrMsg);
	
	
								//$myrow6 = DB_fetch_array($result6) ;
				
				
				//write to pdf
				
				$ovamount = $unitprice * $myrow5['qty'];
			    
			   $totalvep = $totalvep + $ovamount;
			
				
				$stup = locale_number_format($unitprice,2);
				
				$stovm = locale_number_format($ovamount,2);

					$LeftOvers = $pdf->addTextWrap($Left_Margin+3,$YPos,95,$FontSize, $myrow5['item_id']);
								
			     	$LeftOvers = $pdf->addTextWrap($Left_Margin+100,$YPos,251,$FontSize, $myrow5['item_details'] );
					
					$LeftOvers = $pdf->addTextWrap($Left_Margin+353,$YPos,96,$FontSize,$stup,'centre');
					$LeftOvers = $pdf->addTextWrap($Left_Margin+453,$YPos,95,$FontSize,$myrow5['qty'],'right');
					$LeftOvers = $pdf->addTextWrap($Left_Margin+553,$YPos,35,$FontSize,$myrow5['uom'],'centre');
					$LeftOvers = $pdf->addTextWrap($Left_Margin+590,$YPos,50,$FontSize,'','right');
					$LeftOvers = $pdf->addTextWrap($Left_Margin+642,$YPos,120,$FontSize,$stovm,'right');
				
								
				$YPos -= ($line_height);

					$lines=explode("\r\n",htmlspecialchars_decode($myrow5['narrative']));
					for ($i=0;$i<sizeOf($lines);$i++) {
						while (mb_strlen($lines[$i])>1) {
							if ($YPos>30)  {
								/* head up a new invoice/credit note page */
								/* draw the vertical column lines right to the bottom */
								PrintLinesToBottom ();
	   		        				include ('includes/PDFquotePageHeader.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 > 30 ) {

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

				} //end while there invoice are line items to print out
			

			$YPos -= $line_height;

			/* check to see enough space left to print the 4 lines for the totals/footer */
			if ($YPos>30) {
				PrintLinesToBottom ();
				include ('includes/PDFquotePageHeader.inc');
			}
			
			
			
			
			

			
		

			/* 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,280,$FontSize,_('Quotation Terms'));
		//      $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;
			
			$vat = $totalvep * 0.09;
			
			$totalvip = $totalvep+$vat;
	
	       //2 decimal point outpu
	
	$vatfinal = locale_number_format($vat,2);
				$displaytotalfinal= locale_number_format($totalvip,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, _(''));
			$LeftOvers = $pdf->addTextWrap($Left_Margin+642,$YPos-6,120,$FontSize,$DisplayFreight, 'right');

			$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 QUOTE'));
				$FontSize=9;
				$YPos-=4;
				$LeftOvers = $pdf->addTextWrap($Left_Margin+280,$YPos,220,$FontSize,$quoteterms);
				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('evergreenquote_' . $OrderNo . '.pdf');

		
			$filename = 'quotations/evergreenquote_' . $OrderNo. '.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 quote no: ') . $OrderNo. '</p>';
					
			echo '<br/>';
	echo $quotedate ;
		
	
	$pdf->__destruct();
		
	
		
				
}

			
		
			
		
			
		
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+(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));

	$PageNumber++;

}
		
		
			    
		
	


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

?>
