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

include('includes/header.inc');


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>' . _('Approved CIT Billing Profile ') . ':</td>
							<td><select name="quotenumber" required = "required">';
							
							$SQL = "SELECT billing_id,
											customer,
											branchcode,
											month,
				                           year,
										   status
		                            FROM cit_billing_profile
		                             WHERE status = 'approved'";

$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['customer'] . "'
			";
	
	$result300 = DB_query($SQL300);
	
	$myrow300 = DB_fetch_array($result300) ;
	
	
	
	if (isset($_POST['quotenumber']) AND $_POST['quotenumber']==$myrow['billing_id']){
	    
		echo '<option selected="selected" value="' . $myrow['billing_id'] . '">' . $myrow['billing_id'].' - ' .$myrow300['name'] . ' - ' .$myrow['branchcode'] . ' - ' .$myrow['month'] . ' -'.$myrow['year'] .'</option>';
	} else {
			echo '<option value="' . $myrow['billing_id'] . '">' . $myrow['billing_id'].' - ' .$myrow300['name'] . ' - ' .$myrow['branchcode'] . ' - ' .$myrow['month'] . ' -'.$myrow['year'] .'</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 '<td>' . _('Link to Account') . ':</td>
							<td><select name="Account">';
							
							$SQL = "SELECT debtoraccount.account_number,
							               debtoraccount.branchcode,
										   debtoraccount.departmentid,
				                           custbranch.brname,
										   department.departmentname											
		                            FROM debtoraccount
									INNER JOIN debtorsmaster ON debtoraccount.debtorno = debtorsmaster.debtorno
			INNER JOIN custbranch ON debtoraccount.branchcode = custbranch.branchcode
			INNER JOIN department ON debtoraccount.departmentid = department.departmentid
			WHERE debtoraccount.debtorno = '383'
			
			
		                             ORDER BY account_number";

$result=DB_query($SQL);
//echo '<option value="0">0 - ' . _('None') . '</option>';
while ($myrow=DB_fetch_array($result)){
	
		echo '<option selected="selected" value="' . $myrow['account_number'] . '">' . $myrow['account_number'].' - ' .$myrow['brname'] . ' - ' .$myrow['departmentname'] . '</option>';
	
	
	
	
}
echo '</select></td>';
	




echo '</td>';


echo '</td>';

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



echo '</div>';

echo '</div>';


			
            


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

$comments = $_POST['comments'] ;
$account = $_POST['Account'] ;
$retenrate = $retention/100;

$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));
$transdate = date("Y-m-d h:m:s", 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 
		             customer,
					 branchcode,
					 month,
					 year
					 
			
		          FROM cit_billing_profile
				    
				   WHERE billing_id = '" . $quoteno  . "'";
        
       $result700=DB_query($query700);
        $myrow700=DB_fetch_array($result700);
        		
			$ac = $myrow700['account_number'];
			$branchcode = $myrow700['branchcode'];
			$debtorno = $myrow700['customer'];
	        	$billingmonth= $myrow700['month'];
		$billingyear = $myrow700['year'];
		
	
		
		
		//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/CITPDFinvoicePageHeader.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.
		
		
		
		$sql5 = "SELECT description,
												qty,
												uom,
												unit_price,
												total
			FROM cit_bill_items
			WHERE billing_id='" . $quoteno . "'
			";
	$ErrMsg = _('This customer could not be added because');
			$result5= DB_query($sql5,$ErrMsg);
	
	
	
	
	$totalvep = 0;
		while ( $myrow5 = DB_fetch_array($result5)){
			
			
			//get stock name
			$sql55 = "SELECT description
			FROM stockmaster
			WHERE stockid='" . $myrow5['description'] . "'
			";
	
			$result55= DB_query($sql55,$ErrMsg);
			$myrow55 = DB_fetch_array($result55);
			 
				$total = $myrow5['total'];
			
			    $unitprice = $myrow5['unit_price'];
				
				$stockname = $myrow55['description'];
				//write to pdf
				
			    
			   $totalvep = $totalvep + $myrow5['total'];
			
				
				$stup = locale_number_format($unitprice,4);
				
				$stovm = locale_number_format($total,2);

					$LeftOvers = $pdf->addTextWrap($Left_Margin+3,$YPos,95,$FontSize, $myrow5['description']);
								
			     	$LeftOvers = $pdf->addTextWrap($Left_Margin+100,$YPos,251,$FontSize, $stockname );
					
					$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/CITPDFinvoicePageHeader.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/CITPDFinvoicePageHeader.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 */

			

				

			

			/* 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+130,$YPos-40,600,$FontSize,_('Wormald Fire & Security appreciates your Business! Powered by E-Business ERP System'));
		//      $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);
	
	$totalvepdec = locale_number_format($totalvep,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-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,$comments);
				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');
		
//debtor trans and debtor vat
			$SQLdebtor = "INSERT INTO debtortrans (transno,
									type,
									debtorno,
									branchcode,
									trandate,
									inputdate,
									prd,
									settled,
									reference,
									tpe,
									order_,
									rate,
									ovamount,
									ovgst,
									invtext,
									account_number,
									department,
									entered_by)
				VALUES (
					'" . $InvoiceNo. "',
					'10',
					'" . $debtorno . "',
					'" . $branchcode . "',
					'" . $transdate . "',
					'" . $transdate . "',
					
					'" . $PeriodNo . "',
					'0',
					'CIT Invoice',
					'DE',
					'" . $InvoiceNo . "',
					'1',
					'" . $totalvep . "',
					'" . $vat . "',
					'',
					'" . $account . "',
					'18',
					'" . $userid . "'
					)";
		$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);
         
			
			
			//gl entries
			
			//$TransNo = GetNextTransNo( 10, $db);
			
			//idebit debtor
			
			$SQL = "INSERT INTO gltrans (type,
									typeno,
									trandate,
									periodno,
									account,
									narrative,
									amount,
									posted,
									tag,
									departmentid)
				VALUES ('10',
					'" . $InvoiceNo. "',
					'" . $transdate . "',
					'" . $PeriodNo . "',
					'1200002',
					'CIT Billing',
					'" . $totalvip. "',
					'1',
					'18',
					'18'
					)";
		$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($SQL,$ErrMsg,$DbgMsg,true);
         
			//increae sales
			
			$SQL1 = "INSERT INTO gltrans (type,
									typeno,
									trandate,
									periodno,
									account,
									narrative,
									amount,
									posted,
									tag,
									departmentid)
				VALUES ('10',
					'" . $InvoiceNo . "',
					'" . $transdate . "',
					'" . $PeriodNo . "',
					'7102600',
					'',
					'" . -$totalvep. "',
					'1',
					'18',
					'18')";
		$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($SQL1,$ErrMsg,$DbgMsg,true);
       
	//$result= DB_Txn_Commit();
			
				//increae vat payable
			
			$SQL2 = "INSERT INTO gltrans (type,
									typeno,
									trandate,
									periodno,
									account,
									narrative,
									amount,
									posted,
									tag,
									departmentid)
				VALUES ('10',
					'" . $InvoiceNo. "',
					'" . $transdate . "',
					'" . $PeriodNo . "',
					'2200023',
					'',
					'" . -$vat. "',
					'1',
					'18',
					'18')";
		$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($SQL2,$ErrMsg,$DbgMsg,true);
       
	//update status
	
	$SQL20 = "UPDATE  cit_billing_profile set status = 'locked' where billing_id = '" . $quoteno . "'";
	
		$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');

		
			$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/>';
	      
	         echo $totalvep;	
		 
	
	$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'); 
	
	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++;
	}
?>
