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

include('includes/header.inc');

echo '<p> </p> <p></p><p class="page_title_text"><img alt="" src="'.$RootPath.'/css/'.$Theme.
		'/images/printer.png" title="' .// Icon image.
		_('Choose from Quotation Listings ') . '" /> ' .// Icon title.
		_('Choose from All Quotations: [Quote No] [Customer Name] [Job No] [Project Name] [Account Number]') . '</p>';// Page title.
echo '<form method="post" action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '">';
	echo '<div class="col-sm-10">';// div class=?
	echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
echo '<table class="table">';

echo '<td>' . _('Quotations ') . ':</td>
							<td><select name="quotenumber" required = "required">';
							
							$SQL = "SELECT orderno,
											debtorno,
											account_number,
				                            job_no
		                            FROM salesorders
		                             WHERE quotation = 1";

$result=DB_query($SQL);




//echo '<option value="0">0 - ' . _('None Available') . '</option>';
 //echo '<option value="0">0 - ' . _('None') . '</option>';
while ($myrow=DB_fetch_array($result)){

	//check customer name and project name
	
	$SQL300 = "SELECT 	name
			FROM debtorsmaster
			WHERE debtorno='" . $myrow['debtorno'] . "'
			";
	
	$result300 = DB_query($SQL300);
	
	$myrow300 = DB_fetch_array($result300) ;
	
	
		$SQL400 = "SELECT projectid,
	               project_name
				   
			FROM projectdetails 
			WHERE projectid='" .  $myrow['job_no'] . "'
			";
	
			$result400 = DB_query($SQL400);
	
			$myrow400 = DB_fetch_array($result400) ;
	
	if (isset($_POST['quotenumber']) AND $_POST['quotenumber']==$myrow['orderno']){
	    
		echo '<option selected="selected" value="' . $myrow['orderno'] . '">' . $myrow['orderno'].' - ' .$myrow300['name'] . ' - ' .$myrow['job_no'] . ' - ' .$myrow400['project_name'] . ' -'.$myrow['account_number'] .'</option>';
	} else {
			echo '<option value="' . $myrow['orderno'] . '">' . $myrow['orderno'].' - ' .$myrow300['name'] . ' - ' .$myrow['job_no'] . ' - ' .$myrow400['project_name'] .'-'.$myrow['account_number'] .'</option>';
	}
	
	
	
}
echo '</select>';

echo '<tr>
			<td>' ._('Date On Invoice'). ':</td>
			<td><input tabindex="'.$j.'" type="text" maxlength="10" size="15" required="required" name="quotedate" id="datepicker" class="date" /></td>
		</tr>';


echo '<tr>
			<td>' ._('Invoice Terms'). ':</td>
			<td><input type="text" maxlength="100" size="30" required="required" name="invoiceterms"  /></td>
		</tr>';
echo '<tr>
			<td>' ._('Invoice Comments'). ':</td>
			<td><input type="text" maxlength="50" size="30" required="required" name="comments"  /></td>
		</tr>';

echo '</td>';

echo '<input type="submit" name="quote" value="' ._('Create Invoice') . '" />
		</div>
		';



echo '</div>';

echo '</div>';


			
            


$quoteno = $_POST['quotenumber'];
$quotedateraw = $_POST['quotedate'] ;
$invoiceterms= $_POST['invoiceterms'] ;
$comments = $_POST['comments'] ;

$quotedate = date("d-m-Y", strtotime($quotedateraw));
$quotedated = date("Y-m-d", strtotime($quotedateraw));
$yeardate = date('Y',strtotime($quotedateraw));
$monthdate =date('m',strtotime($quotedateraw));
$monthname =date('M',strtotime($quotedateraw));


if (isset($_POST['quote']) && ($_POST['quotenumber'] == $quoteno)) {
		
	
		//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.
		
	
	    $InvoiceNo = GetNextTransNo(10, $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'];	
				
	
	//get data from salesorders based on the quote number selected from the form
	
	
	
	$query700 = "SELECT 
		             account_number,
					 job_no,
					 debtorno
					 
			
		          FROM salesorders
				    
				   WHERE orderno = '" . $quoteno  . "'";
        
       $result700=DB_query($query700);
        $myrow700=DB_fetch_array($result700);
        		
			$ac = $myrow700['account_number'];
			$jobno = $myrow700['job_no'];
			$debtorno = $myrow700['debtorno'];
	
		$query800 = "SELECT 
		             project_name
					 
			
		          FROM projectdetails
				    
				   WHERE projectid = '" . $jobno  . "'";
        
       $result800=DB_query($query800);
        $myrow800=DB_fetch_array($result800);
        		
			$projectname = $myrow800['project_name'];
	
	
	
	$query500 = "SELECT 
		             departmentid,
					 branchcode
		               
					  
		          FROM debtoraccount
				    
				   WHERE account_number = '" . $ac  . "'";
        
       $result500=DB_query($query500);
        $myrow500=DB_fetch_array($result500);
        
			
			$departid=$myrow500['departmentid'];
			
			$branchcode=$myrow500['branchcode'];
	
			
	    $query600 = "SELECT 
		             departmentname
		               
					  
		          FROM department
				    
				   WHERE departmentid = '" . $departid . "'";
        
      $result600=DB_query($query600);
        $myrow600=DB_fetch_array($result600);
			
			$departname=$myrow600['departmentname'];
			
	
	
	
		
			
	
		
			
					
	
		
	
		
		
		//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'];
		
		
		
		
		//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();

	
	

	
	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.
		
		$sql4 = "SELECT pcid,
					projectid,
					name,
					quote_terms
					
			FROM projectcosting
			WHERE projectid='" . $jobno . "'
			";
	$ErrMsg = _('This customer could not be added because');
			$result4 = DB_query($sql4,$ErrMsg);
	
		
	$myrow4 = DB_fetch_array($result4) ;
		
		$pcid = $myrow4['pcid'];
	
		
	
	$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);
			
			
			
				
				
				
				
				//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($stocknarr));
					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/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 <= $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,280,$FontSize,_('Invoice 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 = $contractvalue * 0.09;
			
			$totalvip = $contractvalue+$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 INVOICE'));
				$FontSize=9;
				$YPos-=4;
				$LeftOvers = $pdf->addTextWrap($Left_Margin+280,$YPos,220,$FontSize,$invoiceterms);
				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 salesorder 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'); 

?>
