<?php
/* $Id: index.php 6941 2014-10-26 23:18:08Z daintree $*/
error_reporting(E_ALL & ~E_NOTICE);
ob_start();
$PageSecurity=0;

include('includes/session.inc');
$Title=_('ERP Home');
include('includes/newheader.php');
include('includes/SQL_CommonFunctions.inc');
?>

	 <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <link href='jquery-ui.min.css' type='text/css' rel='stylesheet' >
    <script src="jquery-3.2.1.min.js" type="text/javascript"></script>
    <script src="jquery-ui.min.js" type="text/javascript"></script>
  <script type="text/javascript" src="simple.money.format.js"></script>
  <script type="text/javascript" src="scripts/jquery.formatCurrency-1.4.0.js"></script>

  <script>
  $( function() {
    $( "#datepicker" ).datepicker({
    dateFormat: 'dd/mm/yy',//check change
    changeMonth: true,
    changeYear: true
});
  } );
	  
  </script>	
  		
  	  <script type="text/javascript">
  $(document).ready(function(){				
	$(document).on('keydown', '.item_name', function() {
  
var id = this.id;
  var splitid = id.split('_');
  var index = splitid[1];

  // Initialize jQuery UI autocomplete
  $( '#'+id ).autocomplete({
   source: function( request, response ) {
    $.ajax({
     url: "invoice/searchitem.php",
     type: 'post',
     dataType: "json",
     data: {
      search: request.term,request:1
     },
     success: function( data ) {
      response( data );
		 
     }
    });
   },
   select: function (event, ui) {
    $(this).val(ui.item.label); // display the selected text
    var stockid = ui.item.value; // selected value

    // AJAX
    $.ajax({
     url: 'invoice/searchitem.php',
     type: 'post',
     data: {stockid:stockid,request:2},
     dataType: 'json',
     success:function(response){
 
      var len = response.length;

		 
      if(len > 0){
 
      var itemid = response[0]['stockid'];
       var price = response[0]['price'];

       // Set value to textboxes
		   document.getElementById('itemid_'+index).value = itemid;
       document.getElementById('orderitemprice_'+index).value = price;
       document.getElementById('orderitemquantity_'+index).value = 1;
       document.getElementById('orderitemactualamount_'+index).value = price;
       document.getElementById('orderitemtax1rate_'+index).value = 9;
		  
		  var vatamount = price * 0.09;
		 
		  var total = parseInt(price, 10) + parseInt(vatamount, 10);
		  document.getElementById('orderitemtax1amount_'+index).value = vatamount;
		  
		   document.getElementById('orderitemfinalamount_'+index).value = total.toFixed(2);
		   document.getElementById('final_total_amt').value = total.toFixed(2);
 
      }
 
     }
    });

    return false;
   }
  });
 });
			

			
			
			
	});
		    </script>
	<script src="angular/angular.min.js"></script>  
        
 <div class="container-fluid">
     <?
     echo '<form method="post" id= "invoice_form" action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '">';
	
	echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';?>
        <div class="table-responsive">
          <table class="table table-bordered">
            <tr>
              <td colspan="2" align="center"><h2 style="margin-top:10.5px">Create Quotation</h2></td>
            </tr>
            <tr>
                <td colspan="2">
                  <div class="row">
                    <div class="col-sm-6">
                      To,<br />
                        <b>RECEIVER (Quote TO)</b><br />
                       <select name="customer" required = "required">
                       <?
                       $SQL = "SELECT 
											debtorno,
											name
		                            FROM debtorsmaster";

$result=DB_query($SQL);




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

	//check customer name and project name
	
	if (isset($_POST['customer']) AND $_POST['customer']==$myrow['debtorno']){
	    
		echo '<option selected="selected" value="' . $myrow['debtorno'] . '">' . $myrow['name'].' - ' .$myrow['debtorno']  .'</option>';
	} else {
			echo '<option value="' . $myrow['debtorno'] . '">' . $myrow['name'].' - ' .$myrow['debtorno'] .'</option>';
	}
	
	
	
}
echo '</select>';
						   echo '<div class="row"><div class="col-sm-8"><select name="account" placeholder="Account Number">';
							
							
echo '</select></div></div>';
	   
						echo '<div class="row"><div class="col-sm-8"> <select name="department" required = "required">';
                    
                       $SQL = "SELECT 
											departmentid,
											departmentname
		                            FROM department";

$result=DB_query($SQL);




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

	//check customer name and project name
	
	if (isset($_POST['department']) AND $_POST['department']==$myrow['departmentid']){
	    
		echo '<option selected="selected" value="' . $myrow['departmentid'] . '">' . $myrow['departmentname'].' - ' .$myrow['departmentid']  .'</option>';
	} else {
			echo '<option value="' . $myrow['departmentid'] . '">' . $myrow['departmentname'].' - ' .$myrow['departmentid'] .'</option>';
	}
	
	
	
}
echo '</select></div></div>';   
						
		
						   ?>
                       
                         
                    </div>
                    <div class="col-sm-4">
                     
                 
                      <input  type="text" name="order_date" id="datepicker" class="form-control input-sm orderdate" placeholder="Select Invoice Date" required = "required" />
                      
                      <input type="text" name="lpo" id="lpo" class="form-control input-sm" placeholder="Enter LPO No." />
                      <?
                     
                    
							echo '<select name="salesgl">';
                    
                       $SQL = "SELECT 
											accountcode,
											accountname
		                            FROM chartmaster where group_ ='Sales'";

$result=DB_query($SQL);




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

	//check customer name and project name
	
	if (isset($_POST['salesgl']) AND $_POST['salesgl']==$myrow['accountcode']){
	    
		echo '<option selected="selected" value="' . $myrow['accountcode'] . '">' . $myrow['accountname'].' - ' .$myrow['accountcode']  .'</option>';
	} else {
			echo '<option value="' . $myrow['accountcode'] . '">' . $myrow['accountname'].' - ' .$myrow['accountcode'] .'</option>';
	}
	
	
	
}
echo '</select>';   
						
						echo '<select name="cogsgl">';
                    
                       $SQL = "SELECT 
											accountcode,
											accountname
		                            FROM chartmaster where group_ ='Cost of Goods Sold'";

$result=DB_query($SQL);




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

	//check customer name and project name
	
	if (isset($_POST['cogsgl']) AND $_POST['cogsgl']==$myrow['accountcode']){
	    
		echo '<option selected="selected" value="' . $myrow['accountcode'] . '">' . $myrow['accountname'].' - ' .$myrow['accountcode']  .'</option>';
	} else {
			echo '<option value="' . $myrow['accountcode'] . '">' . $myrow['accountname'].' - ' .$myrow['accountcode'] .'</option>';
	}
	
	
	
}
echo '</select>';
								echo '<select name="project" >';
                    
                       $SQL = "SELECT 
											projectid,
											project_name
		                            FROM projectdetails";

$result=DB_query($SQL);




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

	//check customer name and project name
	
	if (isset($_POST['project']) AND $_POST['project']==$myrow['projectid']){
	    
		echo '<option selected="selected" value="' . $myrow['projectid'] . '">' . $myrow['project_name'].' - ' .$myrow['projectid']  .'</option>';
	} else {
			echo '<option value="' . $myrow['projectid'] . '">' . $myrow['project_name'].' - ' .$myrow['projectid'] .'</option>';
	}
	
	
	
}
echo '</select>';
						?>
                   
                    </div>
                  </div>
                  <br />
                  <table id="invoice-item-table" class="table table-bordered">
                    <tr>
                      <th width="7%">ID</th>
                      <th width="20%">Item Name</th>
                      <th width="5%">Quantity</th>
                      <th width="5%">Price</th>
                      <th width="10%">Actual Amt.</th>
                      <th width="12.5%" colspan="2">VAT(%)</th>
                      <th width="12.5%" colspan="2">STT (%)</th>
                      <th width="12.5%" colspan="2">ECAL(%)</th>
                      <th width="12.5%" rowspan="2">Total</th>
                      <th width="3%" rowspan="2"></th>
                    </tr>
                    <tr>
                      <th></th>
                      <th></th>
                      <th></th>
                      <th></th>
                      <th></th>
                      <th>Rate</th>
                      <th>Amt.</th>
                      <th>Rate</th>
                      <th>Amt.</th>
                      <th>Rate</th>
                      <th>Amt.</th>
                    </tr>
                    <tr>
                      <td><input type="text" name="item_id[]" id="itemid_1" class="form-control input-sm item_id" /></td>
                      <td><input type="text" name="item_name[]" id="itemname_1" class="form-control input-sm item_name" /></td>
                      <td><input type="text" name="order_item_quantity[]" id="orderitemquantity_1" data-srno="1" class="form-control input-sm order_item_quantity" /></td>
                      <td><input type="text" name="order_item_price[]" id="orderitemprice_1" data-srno="1" class="form-control input-sm number_only order_item_price" /></td>
                      <td><input type="text" name="order_item_actual_amount[]" id="orderitemactualamount_1" data-srno="1" class="form-control input-sm order_item_actual_amount"  /></td>
                      <td><input type="text" name="order_item_tax1_rate[]" id="orderitemtax1rate_1" data-srno="1" class="form-control input-sm number_only order_item_tax1_rate" /></td>
                      <td><input type="text" name="order_item_tax1_amount[]" id="orderitemtax1amount_1" data-srno="1"  class="form-control input-sm order_item_tax1_amount" /></td>
                      <td><input type="text" name="order_item_tax2_rate[]" id="orderitemtax2rate_1" data-srno="1" class="form-control input-sm number_only order_item_tax2_rate" /></td>
                      <td><input type="text" name="order_item_tax2_amount[]" id="orderitemtax2amount_1" data-srno="1"  class="form-control input-sm order_item_tax2_amount" /></td>
                      <td><input type="text" name="order_item_tax3_rate[]" id="orderitemtax3rate_1" data-srno="1" class="form-control input-sm number_only order_item_tax3_rate" /></td>
                      <td><input type="text" name="order_item_tax3_amount[]" id="orderitemtax3amount_1" data-srno="1"  class="form-control input-sm order_item_tax3_amount" /></td>
                      <td><input type="text" name="order_item_final_amount[]" id="orderitemfinalamount_1" data-srno="1"  class="form-control input-sm order_item_final_amount" /></td>
                      <td></td>
                    </tr>
                  </table>
                  <div align="right">
                    <button type="button" name="add_row" id="add_row" class="btn btn-success btn-xs">+</button>
                  </div>
                </td>
              </tr>
            
                    </div>
                    <tr style="font-size: 20pix;">
                <td align="right" >  <textarea name="order_notes" id="order_notes" class="form-control" placeholder="Enter Notes/Comments"></textarea></td>
               
              </tr>
              <tr>
              <tr >
                <td align="right" style=" background-color:bisque"><b><font size="+3">Total</font></td>
                <td align="right" style="background-color:bisque"><b><font size="+3"><span id="final_total_amt"></span></b></font></td>
              </tr>
              <tr>
                <td colspan="2"></td>
              </tr>
              <tr>
                <td colspan="2" align="center">
                  <input type="hidden" name="total_item" id="total_item" value="1" />
                  <input type="submit" name="create_invoice" id="create_invoice" class="btn btn-info" value="Create" />
                <a href="Quotations.php">  <button type="button" name="invoicing" id="invoicing" class="btn btn-success">Quotation Listings</button></a>
                </td>
              </tr>
          </table>
        </div>
      </form>
     
     
		

   
 *- 
 									
									<?php
//this is where you paste. Below paste it:

$customer =$_POST['customer'] ;
$quotedateraw = $_POST['order_date'] ;

 $sqldate= FormatDateForSQL(DB_escape_string($_POST['order_date'] ));
$invoiceterms= $_POST['invoiceterms'] ;
$comments = $_POST['comments'] ;
$retention = $_POST['retention'] ;
$retenrate = $retention/100;

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

if(isset($_POST["create_invoice"]) && ($_POST['customer'] == $customer )){
		$userid = $_SESSION['UserID'];
	
		//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.
	
	   
	   
	   $SQL77 = "SELECT 	departmentname
							 
			FROM department
			WHERE departmentid='" . $_POST['department'] . "'
			";
	
	$result77 = DB_query($SQL77);
	
	$myrow77 = DB_fetch_array($result77) ;
		
	$departmentname = $myrow77['departmentname'];	
//get debtor headoffice details:
		$SQL100 = "SELECT 	name,
							address1,
						     address2,
				   			 address3,
							 address4,
							 address5,
							 address6
							 
			FROM debtorsmaster
			WHERE debtorno='" . $_POST['customer'] . "'
			";
	
	$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'];
		
		
		
		$SQL2 = "SELECT branchcode
			FROM debtoraccount
			WHERE account_number='" . $_POST['account']. "'
			";
	
	$result2 = DB_query($SQL2);
	
	$myrow2 = DB_fetch_array($result2) ;
		//now get other customer details from custbranch tables
		
				$SQL21 = "SELECT brname,
								braddress1,
								braddress2,
								braddress3,
								phoneno,
								contactname,
								email
				   
			FROM custbranch
			WHERE branchcode='" . $myrow2['branchcode']. "'
			";
	
	$result21 = DB_query($SQL21);
	
	$myrow21 = DB_fetch_array($result2) ;
		
		$branchname = $myrow21['brname'];
		$branchad1 = $myrow21['braddress1'];
		$branchad2 = $myrow21['braddress2'];
		$branchad3 = $myrow21['braddress3'];
		$branchad4 = $myrow21['braddress3'];
		$branchad5 = $myrow21['braddress3'];
		$branchad6 = $myrow21['braddress3'];
		$phoneno = $myrow21['phoneno'];
		$contactname = $myrow21['contactname'];
		$email = $myrow21['email'];
		
		



//$InvoiceNo = GetNextTransNo(10, $db);
			//get periodno 
	
	$OrderNo = GetNextTransNo(30, $db);
	    $query22 = "SELECT 
						periodno,
		             lastdate_in_period
		                 
					  
		          FROM periods
				    WHERE YEAR(lastdate_in_period) = '" . $yeardate. "'
					AND MONTH(lastdate_in_period)  = '" . $monthdate. "'";
				
        $result22=DB_query($query22);
        $myrow22=DB_fetch_array($result22);
      
				$PeriodNo = $myrow22['periodno'];
		     	$data = $myrow22['lastdate_in_period'];	
				
	
		$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 = "INSERT INTO salesorders (
								orderno,
								lpo,
								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,
								department,
								preparedby)
							VALUES (
								'". $OrderNo . "',
								'" . $_POST['lpo'] . "',
								'" . $_POST['customer'] . "',
								'" . $myrow2['branchcode'] . "',
								'". $_POST['account'] ."',
								'". $_POST['project']  ."',
								'". $_POST['order_notes']."',
								'". $sqldate ."',
								'DF',
								'1',
								'".$debtorname."',
								'". $branchad1."',
								'". $branchad2 ."',
								'". $branchad3 ."',
								'". $branchad4 ."',
								'". $branchad5."',
								'". $branchad6 ."',
								'". $phoneno ."',
								'". $email ."',
								'0',
								'SUVA',
								'". $sqldate ."',
								
							     '". $sqldate ."',
								'". $sqldate ."',
								'0',
								
								'Not Invoiced',
								'1',
								'". $myrow77['departmentname']."',
								'". $realname."'
								)";

		//$ErrMsg = _('This customer could not be added because');
		
			$result = DB_query($sql);
	
	   
	   
	   //get the payid from above
				$sqlpayid =  "SELECT orderno
						 
			FROM salesorders  ORDER BY orderno DESC LIMIT 1;
			
			";
	$ErrMsg = _('This customer could not be added because');
			$resultpayid = DB_query($sqlpayid,$ErrMsg);
			$myrowpayid = DB_fetch_array($resultpayid);
			
			$lastid = $myrowpayid['orderno'];

	
$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 Invoice') );
$pdf->addInfo('Subject', _('Invoice') . ' ' . $_GET['orderno']);
$FontSize = 12;
$line_height = 12;// Recommended: $line_height = $x * $FontSize.
		
		include('includes/PDFQuotationPageHeader2.inc');


	 $SQLuser = "SELECT email,realname
	               
			FROM www_users
			WHERE userid='" . $userid. "'
			";
	
			$resultuser = DB_query($SQLuser);
	
			$myrowuser = DB_fetch_array($resultuser) ;
		$emailm= $myrowuser['email'];


	$order_total_before_tax = 0;
    $order_total_tax1 = 0;
    $order_total_tax2 = 0;
    $order_total_tax3 = 0;
    $order_total_tax = 0;
    $order_total_after_tax = 0;
	   
		
 for($count=0; $count<$_POST["total_item"]; $count++)
      {
        $order_total_before_tax = $order_total_before_tax + floatval(trim($_POST["order_item_actual_amount"][$count]));

        $order_total_tax1 = $order_total_tax1 + floatval(trim($_POST["order_item_tax1_amount"][$count]));

        $order_total_tax2 = $order_total_tax2 + floatval(trim($_POST["order_item_tax2_amount"][$count]));

        $order_total_tax3 = $order_total_tax3 + floatval(trim($_POST["order_item_tax3_amount"][$count]));

        $order_total_after_tax = $order_total_after_tax + floatval(trim($_POST["order_item_final_amount"][$count]));
		  
		  
		  //check whether item name is stock or nonstock items
		  
		 
		  
		  $SQL2 = "SELECT units,materialcost
			FROM stockmaster
			WHERE stockid='" . $_POST["item_id"][$count]. "'
			";
	
	$result2 = DB_query($SQL2);
	
	$myrow2 = DB_fetch_array($result2) ;
		  $uom = $myrow2['units'];
		   $cost = $myrow2['materialcost'];
		  if  ($myrow2['units'] ==''){
			  
			  $uom = "each";
		  }

		  		
			if ($order_total_tax1 > 0 AND $order_total_tax2 == 0 AND $order_total_tax3 == 0){
				
				$taxname = "Vat";
				
			} 
		  elseif ($order_total_tax2 > 0 AND $order_total_tax1 == 0 AND $order_total_tax3 == 0 ){
				
				$taxname= "STT";
				
			}elseif ($order_total_tax3 > 0 AND $order_total_tax1 == 0 AND $order_total_tax2 == 0 ){
				
				$taxname = "Ecal";
				
			}elseif ($order_total_tax1 > 0 AND $order_total_tax2 > 0 AND $order_total_tax3 > 0 ){
				
				$taxname = "Vat,STT,Ecal";
				
			}elseif ($order_total_tax1 > 0 AND $order_total_tax2 > 0 AND $order_total_tax3 == 0 ){
				
				$taxname = "Vat,STT";
				
			}elseif ($order_total_tax1 > 0 AND $order_total_tax2 == 0 AND $order_total_tax3 > 0 ){
				
				$taxname = "Vat,Ecal";
				
			}else {
				
				$taxname = "None";
				
			}
		  
        $sql6 = "INSERT INTO salesorderdetails (
											orderlineno,
											orderno,
											stkcode,
											stock_name,
											unitprice,
											quantity,
											uom,
											tax_code,
											cost_price,
											sales_gl,
											cogs_gl,
											discountpercent,
										
											poline,
											itemdue)
										VALUES  (
								'".   $count. "',
								'" . $OrderNo . "',
								'" . $_POST["item_id"][$count] . "',
								'" . trim($_POST["item_name"][$count]) . "',
								'". trim($_POST["order_item_price"][$count])."',
								'". trim($_POST["order_item_quantity"][$count])."',
								'". $uom."',
								'". $taxname."',
								'". $cost."',
								'". $_POST['salesgl']."',
								'". $_POST['cogsgl']."',
								0,
								
								'',
								'". $sqldate."'
								)";

							$ErrMsg = _('This customer could not be added because');
			$result6 = DB_query($sql6,$ErrMsg);
		//start digging to get projectcosting details. Key field is pcid. After which you use this to determine line items from projectcostingdetail and projectcostin
      
       $ListCount ++;
				

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

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

			
	
	
				
	

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

		$LeftOvers = $pdf->addText($Left_Margin, $YPos+$FontSize, $FontSize,trim($_POST["item_id"][$count]));
		$LeftOvers = $pdf->addText(145, $YPos+$FontSize, $FontSize, trim($_POST["item_name"][$count]));
	$LeftOvers = $pdf->addTextWrap(470, $YPos,85,$FontSize,$taxname,'right');
		$LeftOvers = $pdf->addTextWrap(500, $YPos,85,$FontSize,trim($_POST["order_item_quantity"][$count]),'right');
		  $LeftOvers = $pdf->addTextWrap(550, $YPos,85,$FontSize,$uom,'right');
		
				$LeftOvers = $pdf->addTextWrap(650, $YPos,85,$FontSize,trim($_POST["order_item_price"][$count]),'right');
				$LeftOvers = $pdf->addTextWrap(750, $YPos,85,$FontSize,$stup,'right');
		$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos, 90, $FontSize, $order_total_before_tax ,'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($myrow1['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/PDFQuotationPageHeader2.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/PDFQuotationPageHeader2.inc');
	} //end if need a new page headed up

			
				
		}	
		

	   
      $order_total_tax = $order_total_tax1 + $order_total_tax2 + $order_total_tax3;
		
	   		
	//update status

  

				
		$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;
			
			
			
	$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, _('Total'),'right');
	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos-7, 90, $FontSize, _('$').$order_total_before_tax, 'right');

$YPos -= $FontSize;
	
	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90-655, $YPos-8, 655, $FontSize, _('Taxes'), 'right');
	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos-9, 90, $FontSize, _('$').$order_total_tax, 'right');
	 
	   
	$YPos -= $FontSize;

	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90-655, $YPos-10, 655, $FontSize, _('Total inc taxes'),'right');
	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos-11, 90, $FontSize, _('$').$order_total_after_tax, 'right');

	// Print salesorders.comments:
	$YPos -= $FontSize*2;
	$pdf->addText($XPos+250, $YPos+$FontSize-150, $FontSize, _('TERMS: PAYMENT DUE ON 20th OF THE FOLLOWING MONTH OF PURCHASE'),'centre');
	$pdf->addText($XPos+200, $YPos+$FontSize-165, $FontSize, _('OUR BANKS: Westpac Bank: A/C: 9804778075 | ANZ Bank: A/C: 11879362 | BSP Bank: A/C: 9837614'));
	$pdf->addText($XPos+300, $YPos+$FontSize-195, $FontSize, _('Wormald Fire & Security appreciates your business!'));
	$pdf->addText($XPos, $YPos+$FontSize-215, $FontSize, _('Comments/Notes').':');
	$Width2 = $Page_Width-$Right_Margin-120;// Width to print salesorders.comments.
$LeftOvers =	$pdf->addText($XPos, $YPos+$FontSize-55, $FontSize, $_POST['order_notes']);
	//$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/PDFQuotationPageHeader2.inc');
		}
		$LeftOvers = $pdf->addTextWrap(40, $YPos, $Width2, $FontSize, $LeftOvers);
	}
$pdf->addText($XPos+330, $YPos+$FontSize-250, $FontSize, _('Powered by E-Business ERP System'));
 /*end if there are line details to show on the quotation*/
 
//debtor trans and debtor vat
		
			
     
			
			//increase trade debtors
	
	
			
	//update status
	
	
	$SQL20 = "UPDATE  salesorders set amount = '" . $order_total_before_tax . "',
									  tax1 = '" . $order_total_tax1 . "',
									 tax2 = '" . $order_total_tax2 . "',
									tax3 = '" . $order_total_tax3 . "',
									total_amount = '" . $order_total_after_tax . "'
									where orderno = '" . $OrderNo . "'";
	
		$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();
	
		$pdf->OutputD('evergreeninvoice_' . $InvoiceNo. '.pdf');

		
		
	
	$pdf->__destruct();
	
	
		$message = "This invoice has been generated!";
	echo "<script type='text/javascript'>alert('$message');</script>";
	
		echo "<script type='text/javascript'>javascript:history.go(-1)</script>"; 
	

	
	

	 //its not an email just print the invoice to PDF
	
	//upload data in Debtor

	
}

		
		
			
		
			
		
		
		
			    
		
	
//echo 'Quotation Created Successfully'. $jobno.'!';
//header("location:Invoicing.php");



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





			  
 	echo '</div >';
	?>
						

		
					</div>
				</div>
			</div>
					
					

						<!--end:: Widgets/Stats-->

						<!--Begin::Section-->
						

		<!-- end::Quick Sidebar -->

		<!-- begin::Scroll Top -->
		<div id="m_scroll_top" class="m-scroll-top">
			<i class="la la-arrow-up"></i>
		</div>

		<!-- end::Scroll Top -->

		<!-- begin::Quick Nav -->
		

		<!-- begin::Quick Nav -->
<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>

		<!--end::Page Scripts -->
	</body>

	<!-- end::Body -->
</html>
 
      
<?php



/*The module link codes are hard coded in a switch statement below to determine the options to show for each tab */
include('includes/MainMenuLinksArray.php');

if (isset($SupplierLogin) AND $SupplierLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=1">' . _('View or Amend outstanding offers') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=2">' . _('Create a new offer') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=3">' . _('View any open tenders without an offer') . '</a></p>
			</td>
			</tr>
		</table>';
	include('includes/footer.inc');
	exit;
} elseif (isset($CustomerLogin) AND $CustomerLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/CustomerInquiry.php?CustomerID=' . $_SESSION['CustomerID'] . '">' . _('Account Status') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectOrderItems.php?NewOrder=Yes">' . _('Place An Order') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectCompletedOrder.php?SelectedCustomer=' . $_SESSION['CustomerID'] . '">' . _('Order Status') . '</a></p>
			</td>
			</tr>
		</table>';

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

if (isset($_GET['Application'])){ /*This is sent by this page (to itself) when the user clicks on a tab */
	$_SESSION['Module'] = $_GET['Application'];
}








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

function GetRptLinks($GroupID) {
/*
This function retrieves the reports given a certain group id as defined in /reports/admin/defaults.php
in the acssociative array $ReportGroups[]. It will fetch the reports belonging solely to the group
specified to create a list of links for insertion into a table to choose a report. Two table sections will
be generated, one for standard reports and the other for custom reports.
*/
	global $db, $RootPath, $ReportList;
	require_once('reportwriter/languages/en_US/reports.php');
	require_once('reportwriter/admin/defaults.php');
	$GroupID=$ReportList[$GroupID];
	$Title= array(_('Custom Reports'), _('Standard Reports and Forms'));

	$sql= "SELECT id,
				reporttype,
				defaultreport,
				groupname,
				reportname
			FROM reports
			ORDER BY groupname,
					reportname";
	$Result=DB_query($sql,'','',false,true);
	$ReportList = '';
	while ($Temp = DB_fetch_array($Result)) $ReportList[] = $Temp;

	$RptLinks = '';
	for ($Def=1; $Def>=0; $Def--) {
        $RptLinks .= '<li class="menu_group_headers">';
        $RptLinks .= '<b>' .  $Title[$Def] . '</b>';
        $RptLinks .= '</li>';
		$NoEntries = true;
		if ($ReportList) { // then there are reports to show, show by grouping
			foreach ($ReportList as $Report) {
				if ($Report['groupname']==$GroupID AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/ReportMaker.php?action=go&amp;reportid=' . $Report['id'] . '">' . _($Report['reportname']) . '</a></p>';
					$RptLinks .= '</li>';
					$NoEntries = false;
				}
			}
			// now fetch the form groups that are a part of this group (List after reports)
			$NoForms = true;
			foreach ($ReportList as $Report) {
				$Group=explode(':',$Report['groupname']); // break into main group and form group array
				if ($NoForms AND $Group[0]==$GroupID AND $Report['reporttype']=='frm' AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/folders.gif" width="16" height="13" alt="" />&nbsp;';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/FormMaker.php?id=' . $Report['groupname'] . '"></p>';
					$RptLinks .= $FormGroups[$Report['groupname']] . '</a>';
					$RptLinks .= '</li>';
					$NoForms = false;
					$NoEntries = false;
				}
			}
		}
		if ($NoEntries) $RptLinks .= '<li class="menu_group_item">' . _('There are no reports to show!') . '</li>';
	}
	return $RptLinks;
}
	
?>
<!-- Modal HTML embedded directly into document -->
<div id="ex1" class="modal">
  <p>Thanks for clicking. That felt good.</p>
  <a href="#" rel="modal:close">Close</a>
</div>


<!-- Modal -->
 <div class="modal fade" id="getCodeModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
   <div class="modal-dialog modal-lg">
      <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
         <h4 class="modal-title" id="myModalLabel"> API CODE </h4>
       </div>
       <div class="modal-body" id="getCode" style="overflow-x: scroll;">
       
          
          
       </div>
    </div>
   </div>
 </div>
<script>
jQuery(document).ready(function($){

   // event must be delegated from .xcrud
	

	$( "select[name='customer']" ).change(function () {
    var debtorno = $(this).val();


    if(debtorno) {


        $.ajax({
            url: "invoice/accountnumber.php",
            dataType: 'Json',
            data: {'id':debtorno},
            success: function(data) {
                $('select[name="account"]').empty();
                $.each(data, function(key, value) {
                    $('select[name="account"]').append('<option value="'+ key +'">'+ value +'</option>');
                });
            }
        });


    }else{
        $('select[name="account"]').empty();
    }
});

	
		
		var final_total_amt = $('#final_total_amt').text();
        var count = 1;
        
        $(document).on('click', '#add_row', function(){
	
			
          count++;
          $('#total_item').val(count);
          var html_code = '';
          html_code += '<tr id="row_id_'+count+'">';
          html_code += '<td><input type="text"  name="item_id[]" id="itemid_'+count+'" class="form-control input-sm item_id" disabled /></td>';
          
          html_code += '<td><input type="text" name="item_name[]" id="itemname_'+count+'" class="form-control input-sm item_name" /></td>';
          
          html_code += '<td><input type="text" name="order_item_quantity[]" id="orderitemquantity_'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_quantity" /></td>';
          html_code += '<td><input type="text" name="order_item_price[]" id="orderitemprice_'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_price" /></td>';
          html_code += '<td><input type="text" name="order_item_actual_amount[]" id="orderitemactualamount_'+count+'" data-srno="'+count+'" class="form-control input-sm order_item_actual_amount" readonly /></td>';
          
          html_code += '<td><input type="text" name="order_item_tax1_rate[]" id="orderitemtax1rate_'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_tax1_rate" /></td>';
          html_code += '<td><input type="text" name="order_item_tax1_amount[]" id="orderitemtax1amount_'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_tax1_amount" /></td>';
          html_code += '<td><input type="text" name="order_item_tax2_rate[]" id="orderitemtax2rate_'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_tax2_rate" /></td>';
          html_code += '<td><input type="text" name="order_item_tax2_amount[]" id="orderitemtax2amount_'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_tax2_amount" /></td>';
          html_code += '<td><input type="text" name="order_item_tax3_rate[]" id="orderitemtax3rate_'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_tax3_rate" /></td>';
          html_code += '<td><input type="text" name="order_item_tax3_amount[]" id="orderitemtax3amount_'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_tax3_amount" /></td>';
          html_code += '<td><input type="text" name="order_item_final_amount[]" id="orderitemfinalamount_'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_final_amount" /></td>';
          html_code += '<td><button type="button" name="remove_row" id="'+count+'" class="btn btn-danger btn-xs remove_row">X</button></td>';
          html_code += '</tr>';
          $('#invoice-item-table').append(html_code);
        });
        
        $(document).on('click', '.remove_row', function(){
          var row_id = $(this).attr("id");
          var total_item_amount = $('#orderitemfinalamount_'+row_id).val();
          var final_amount = $('#final_total_amt').text();
          var result_amount = parseFloat(final_amount) - parseFloat(total_item_amount);
          $('#final_total_amt').text(result_amount);
          $('#row_id_'+row_id).remove();
          count--;
          $('#total_item').val(count);
        });

        function cal_final_total(count)
        {
          var final_item_total = 0;
          for(j=1; j<=count; j++)
          {
            var quantity = 0;
            var price = 0;
            var actual_amount = 0;
            var tax1_rate = 0;
            var tax1_amount = 0;
            var tax2_rate = 0;
            var tax2_amount = 0;
            var tax3_rate = 0;
            var tax3_amount = 0;
            var item_total = 0;
            quantity = $('#orderitemquantity_'+j).val();
            if(quantity > 0)
            {
              price = $('#orderitemprice_'+j).val();
              if(price > 0)
              { 
                actual_amount = parseFloat(quantity) * parseFloat(price);
                $('#orderitemactualamount_'+j).val(actual_amount);
                tax1_rate = $('#orderitemtax1rate_'+j).val();
                if(tax1_rate > 0)
                {
                  tax1_amount = parseFloat(actual_amount)*parseFloat(tax1_rate)/100;
                  $('#orderitemtax1amount_'+j).val(tax1_amount);
                }
                tax2_rate = $('#orderitemtax2rate_'+j).val();
                if(tax2_rate > 0)
                {
                  tax2_amount = parseFloat(actual_amount)*parseFloat(tax2_rate)/100;
                  $('#orderitemtax2amount_'+j).val(tax2_amount);
                }
                tax3_rate = $('#orderitemtax3rate_'+j).val();
                if(tax3_rate > 0)
                {
                  tax3_amount = parseFloat(actual_amount)*parseFloat(tax3_rate)/100;
                  $('#orderitemtax3amount_'+j).val(tax3_amount);
                }
                item_total = parseFloat(actual_amount) + parseFloat(tax1_amount) + parseFloat(tax2_amount) + parseFloat(tax3_amount);
                final_item_total = parseFloat(final_item_total) + parseFloat(item_total);
                $('#orderitemfinalamount_'+j).val(item_total);
              }
            }
          }
			
          $('#final_total_amt').text(final_item_total);
			
        }
		

	 $(document).on('blur', '.order_item_quantity', function(){
          cal_final_total(count);
        });

        $(document).on('blur', '.order_item_price', function(){
          cal_final_total(count);
        });

        $(document).on('blur', '.order_item_tax1_rate', function(){
          cal_final_total(count);
        });

        $(document).on('blur', '.order_item_tax2_rate', function(){
          cal_final_total(count);
        });

        $(document).on('blur', '.order_item_tax3_rate', function(){
          cal_final_total(count);
        });

        $('#create_invoice').click(function(){
          

         


          for(var no=1; no<=count; no++)
          {
            if($.trim($('#itemname_'+no).val()).length == 0)
            {
              alert("Please Enter Item Name");
              $('#itemname_'+no).focus();
              return false;
            }

            if($.trim($('#orderitemquantity_'+no).val()).length == 0)
            {
              alert("Please Enter Quantity");
              $('#orderitemquantity_'+no).focus();
              return false;
            }

            if($.trim($('#orderitemprice_'+no).val()).length == 0)
            {
              alert("Please Enter Price");
              $('#orderitemprice_'+no).focus();
              return false;
            }

          }

          $('#invoice_form').submit();

        });

	

	
	
	 });
	
	
	
	

	
	
	
	
</script>


<script type="text/javascript">
jQuery(document).on("ready xcrudafterrequest",function(){
    
});
</script>