<?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'){
		
		$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 = "SELECT projectid,
	              project_type,
				   customer,
				   branch,
				   department,
				   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'];
		$departmentname = $myrow['department'];
		
		$projecttype = $myrow['project_type'];
			$debtorno = $myrow['customer'];
					$branchcode = $myrow['branch'];
	$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
	
		
		//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();

	   $OrderNo = GetNextTransNo(30, $db);
		
	
$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 Quotation') );
$pdf->addInfo('Subject', _('Quotation') . ' ' . $_GET['QuotationNo']);
$FontSize = 12;
$line_height = 12;// Recommended: $line_height = $x * $FontSize.
		
		include('includes/PDFQuotationPageHeader1.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,
					notes
					
					
			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['notes'];
	
	$materials='Materials-';
	$others='Others-';
		
		$sql5 = "SELECT projectcostingid,
					pcid,
					cost_type,
												item_id,
												item_details,
												narrative,
												unit_cost,
												qty,
												uom,
												total_cost,
												margin,
												price,
												sales_gl,
												cogs_gl
			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)){
			
			   $ListCount ++;

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

		if ((mb_strlen($myrow2['narrative']) >200 AND $YPos-$line_height <= 75)
			OR (mb_strlen($myrow2['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/PDFQuotationPageHeader1.inc');
		} //end if need a new page headed up

			
			
			
			$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,
											stock_name,
											unitprice,
											quantity,
											uom,
											cost_price,
											total,
											total_cost,
											sales_gl,
											cogs_gl,
											discountpercent,
											narrative,
											poline,
											itemdue)
										VALUES  (
								'".  $orderline . "',
								'" . $OrderNo . "',
								'" . $myrow5['item_id'] . "',
								'" . $myrow5['item_details'] . "',
								'". $unitprice."',
								'". $myrow5['qty']."',
									'". $myrow5['uom']."',
										'". $myrow5['unit_cost']."',
										'". $unitprice * $myrow5['qty'] ."',
										'". $myrow5['unit_cost']* $myrow5['qty'] ."',
										'". $myrow5['sales_gl']."',
										'". $myrow5['cogs_gl']."',
								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);

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

		$LeftOvers = $pdf->addText($Left_Margin, $YPos+$FontSize, $FontSize,$myrow5['item_id']);
		$LeftOvers = $pdf->addText(145, $YPos+$FontSize, $FontSize, $myrow5['item_details']);
	
		$LeftOvers = $pdf->addTextWrap(585, $YPos,85,$FontSize,$myrow5['qty'],'right');
		$LeftOvers = $pdf->addTextWrap(650, $YPos,85,$FontSize,$stup,'right');
		$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos, 90, $FontSize, $stovm,'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($myrow5['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/PDFQuotationPageHeader1.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/PDFQuotationPageHeader1.inc');
	} //end if need a new page headed up

		}	
		
					$sql55 = "SELECT sum(total_cost) as totalcost
			FROM projectcostingdetail
			WHERE pcid='" . $pcid . "'
			";
	$ErrMsg = _('This customer could not be added because');
			$result55= DB_query($sql55,$ErrMsg);
	           $myrow55 = DB_fetch_array($result55);
		
		$totalcost = $myrow55['totalcost'];
		
		$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,
								amount,
								total_cost,
								status,
								deliverblind,
								department,
								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 ."',
								'1',
								'". $totalvep."',
								'". $totalcost."',
								'Not Invoiced',
								'1',
								'". $departmentname."',
								'". $realname."'
								)";

		//$ErrMsg = _('This customer could not be added because');
		
			$result = DB_query($sql);
	
			
		
		
		$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;
			
			
			
	$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, _('VEP'),'right');
	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos-7, 90, $FontSize, locale_number_format($totalvep,2), '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, _('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+300, $YPos+$FontSize, $FontSize, _('TERMS: Price is valid till 30 Days from the quote date.'),'centre');
	$pdf->addText($XPos+300, $YPos+$FontSize-15, $FontSize, _('Wormald Fire & Security looking forward in serving you'));
	$pdf->addText($XPos, $YPos+$FontSize-45, 15, _('Notes').':');
	
	$Width2 = $Page_Width-$Right_Margin-120;// Width to print salesorders.comments.
		$LeftOvers =	$pdf->addText($XPos, $YPos+$FontSize-65, $FontSize, $quoteterms);
		//$LeftOvers = $pdf->addTextWrap($Page_Width+$Left_Margin+10, $YPos, 90, $FontSize,_('Notes') , 'right');
	//$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/PDFQuotationPageHeader1.inc');
		}
		$LeftOvers = $pdf->addTextWrap(40, $YPos, $Width2, $FontSize, $LeftOvers);
	}

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

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

		
		
	
	$pdf->__destruct();
		
	
		
				
}

			
		
			
		
			
		

		
		
			    
		
	


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

?>
