<?php

/* $Id: index.php 6941 2014-10-26 23:18:08Z daintree $*/

error_reporting(E_ALL & ~EF_NOTICE);

ob_start();

$PageSecurity=0;



include('includes/session.inc');

$Title=_('ERP Home');

include('includes/newheader.php');

include('includes/SQL_CommonFunctions.inc');


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

?>



	 <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 31/07/2023

		   document.getElementById('itemid_'+index).value = itemid;

       document.getElementById('orderitemprice_'+index).value = price;

       document.getElementById('orderitemquantity_'+index).value = 1;

       document.getElementById('orderitemactualamount_'+index).value = price;
		  
		  const orderDate = parseDate($(".orderdate").val());
const date2023 = parseDate('31/07/2023');
const date2025 = parseDate('31/07/2025');

let vatamount = 0;

if (orderDate <= date2023) {
  document.getElementById('orderitemtax1rate_' + index).value = 9;
  vatamount = price * 0.09;
} else if (orderDate > date2023 && orderDate <= date2025) {
  document.getElementById('orderitemtax1rate_' + index).value = 15;
  vatamount = price * 0.15;
} else {
  document.getElementById('orderitemtax1rate_' + index).value = 12.5;
  vatamount = price * 0.125;
}

		  

     

		  

		 

		 

		  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 Invoice</h2></td>

            </tr>

            <tr>

                <td colspan="2">

                  <div class="row">

                    <div class="col-sm-6">

                      To,<br />

                        <b>RECEIVER (BILL TO)</b><br />

                       <select name="customer" required = "required">

                       <?

						   $userid = $_SESSION['UserID'];

						   

                       $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" required = "required">';

							

							

echo '</select></div></div>';

	   

						echo '<div class="row"><div class="col-sm-8"> <select name="department" required = "required">';

                  if ($userid =='nisha'){  

                       $SQL = "SELECT 

											departmentid,

											departmentname

		                            FROM department where departmentid = 7
									OR departmentid = 25";



$result=DB_query($SQL);









//echo '<option value="0">0 - ' . _('None Available') . '</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>';

	}

	

	

	

}

				  }

						      elseif ($userid =='schand' || $userid =='stephanie' || $userid =='manueli'  ||$userid =='losa'){  

                       $SQL = "SELECT 

											departmentid,

											departmentname

		                            FROM department where departmentid = 6 

									OR departmentid = 25";



$result=DB_query($SQL);









//echo '<option value="0">0 - ' . _('None Available') . '</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>';

	}

	

	

	

}

				  }

						     elseif ($userid =='sharukh' ){  

                       $SQL = "SELECT 

											departmentid,

											departmentname

		                            FROM department where departmentid = 18 

									OR departmentid = 19";



$result=DB_query($SQL);









//echo '<option value="0">0 - ' . _('None Available') . '</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>';

	}

	

	

	

}

				  }

						   elseif ($userid =='lusi' || $userid =='riaz'  ){  

                       $SQL = "SELECT 

											departmentid,

											departmentname

		                            FROM department where departmentid = 9 

									OR departmentid = 10";



$result=DB_query($SQL);









//echo '<option value="0">0 - ' . _('None Available') . '</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>';

	}

	

	

	

}

				  }
						   
						   elseif ($userid =='mere'||$userid =='zubia' ||$userid =='sureta' ||$userid =='lina'  ||$userid =='crispus'  ){  

                       $SQL = "SELECT 

											departmentid,

											departmentname

		                            FROM department where departmentid = 9 
									OR departmentid = 11";



$result=DB_query($SQL);









//echo '<option value="0">0 - ' . _('None Available') . '</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>';

	}

	

	

	

}

				  }
						   elseif ($userid =='lina'  ||$userid =='crispus'  ){  

                       $SQL = "SELECT 

											departmentid,

											departmentname

		                            FROM department where departmentid = 9 
								";



$result=DB_query($SQL);









//echo '<option value="0">0 - ' . _('None Available') . '</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>';

	}

	

	

	

}

				  }
						   //'7','9','10','13','14','16','19','23','28','29'

						    elseif ($userid =='roneelp' ||$userid =='saula'||$userid =='ronil' || $userid =='vineshkumar'|| $userid =='waqa'){  

                       $SQL = "SELECT 

											departmentid,

											departmentname

		                            FROM department where departmentid = 2 
									OR departmentid = 19 

									";



$result=DB_query($SQL);









//echo '<option value="0">0 - ' . _('None Available') . '</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>';

	}

	

	

	

}

				  }
			    elseif ($userid =='rowen'|| $userid =='rramlu' || $userid =='nitika'  || $userid =='Priti' || $userid =='zibran' ){  

                       $SQL = "SELECT 

											departmentid,

											departmentname

		                            FROM department 
									where departmentid = 8 
									OR departmentid = 21
								

									";



$result=DB_query($SQL);









//echo '<option value="0">0 - ' . _('None Available') . '</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>';

	}

	

	

	

}

				  }
				  
				    elseif ($userid =='ragnesh' || $userid =='Avishek' ){  

                       $SQL = "SELECT 

											departmentid,

											departmentname

		                            FROM department where departmentid = 3 
								
								

									";



$result=DB_query($SQL);









//echo '<option value="0">0 - ' . _('None Available') . '</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>';

	}

	

	

	

}

				  }
						    elseif ($userid =='ilimo'||$userid =='salata'||$userid =='marica'|| $userid=='semi'){  

                       $SQL = "SELECT 

											departmentid,

											departmentname

		                            FROM department where departmentid = 1 

									";



$result=DB_query($SQL);









//echo '<option value="0">0 - ' . _('None Available') . '</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>';

	}

	

	

	

}

				  }

						   

						   elseif ($userid =='admin' || $userid =='ravinesh' || $userid =='rtaito' || $userid =='sharukh'  ) {

							                        $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>';   

						

		

						   ?>

                       
 <input type="text" name="contactperson" id="contactperson" class="form-control input-sm" placeholder="Enter Contact Person Name(Att:)." />
                         

                    </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." />

						  <input type="text" name="cashcustomer" id="cashcustomer" class="form-control input-sm" placeholder="Enter Cash Customer Name for Billing" />

						 <input type="text" name="cashcustomeradd" id="cashcustomeradd" class="form-control input-sm" placeholder="Enter Cash Customer Address for Billing" />

                    <?

								echo '<select name="project" >';

                    if (isset($projectid)){
						
						 $SQL = "SELECT 

											projectid,

											project_name,

											wip_income

		                            FROM projectdetails
									
									WHERE projectid = '".$projectid."'";
						
						
						$result=DB_query($SQL);
						while ($myrow=DB_fetch_array($result)){



	//check customer name and project name

	


	    



			echo '<option value="' . $myrow['projectid'] . '">' . htmlspecialchars($myrow['wip_income']).' - ' .htmlspecialchars($myrow['project_name'].' - '.$myrow['projectid'], ENT_QUOTES,'UTF-8') . '</option>';

	

	

	

	

}
						
						
					} else{

                       $SQL = "SELECT 

											projectid,

											project_name,

											wip_income

		                            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'] . '">' . htmlspecialchars($myrow['wip_income']).' - ' .htmlspecialchars($myrow['project_name'].' - '.$myrow['projectid'], ENT_QUOTES,'UTF-8') . '</option>';

	} else {

			echo '<option value="' . $myrow['projectid'] . '">' . htmlspecialchars($myrow['wip_income']).' - ' .htmlspecialchars($myrow['project_name'].' - '.$myrow['projectid'], ENT_QUOTES,'UTF-8') . '</option>';

	}

	

	

	

}
					}

echo '</select>';

						

						  

                     

                    

							echo '<select name="salesgl" required="required">';

                    

                       $SQL = "SELECT 

											accountcode,

											accountname

		                            FROM chartmaster where group_ ='Sales'";



$result=DB_query($SQL);









//echo '<option value="0">0 - ' . _('None Available') . '</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>';   

						

						?>

                   

                    </div>

                  </div>

                  <br />

                  <table id="invoice-item-table" class="table table-bordered">

                    <tr>

                      <th width="7%">ID</th>

                      <th width="30%">Item Name</th>

                      <th width="5%">Quantity</th>

                      <th width="5%">Price</th>

                      <th width="5%">Actual Amt.</th>

                     
                      <th width="5%" rowspan="2">Total</th>

                      <th width="3%" rowspan="2"></th>

                    </tr>

                    <tr>

                      <th></th>

                      <th></th>

                      <th></th>

                      <th></th>

                      <th></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_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>

						

			 <td align="right" > <input type="text" name="retention" id="retention" class="form-control input-sm" placeholder="Enter retention amount (VEP) value" />	

               </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="Invoicing.php">  <button type="button" name="invoicing" id="invoicing" class="btn btn-success">Invoice Listings</button></a>
					
					<?php 
					
					if (isset($projectid)){
						
						?>
						<a href="project.php">  <button type="button" name="project" id="project" class="btn btn-success">Projects Listings</button></a>
						
						<?php 
					}
					
					
					?>

                </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;

$salesgl = $_POST['salesgl'];
$contactperson = $_POST['contactperson'];

    //update GL and change status
	
	

	//fire contract fiji wide
if ($salesgl == '7100500'){
		
		
$old_sales_code = '103';
$old_gl_code = 'G610';
}
	//7102400 Security Guard Contract Income

if ($salesgl == '7102400'){
		
		
	 $old_sales_code = '602';
     $old_gl_code = 'G70021';
										
}
	   if ($salesgl == '7102400'){
		
		
		$old_sales_code = '601';
		$old_gl_code = 'G70011';
	   }
	
	//security mobile income
			   if ($salesgl == '7102401'){
		
		
		$old_sales_code = '604';
       $old_gl_code = 'G70022';
								
		
	}
	   if ($salesgl == '7102401'){
		
		
	$old_sales_code = '603';
    $old_gl_code = 'G70012';
										

		
	}
	  if ($salesgl == '7102401'){
		
		
		$old_sales_code = '609';
      $old_gl_code = 'G70031';
										
				
	}
	
		   if ($salesgl == '7102400'){
		
		
		 $old_sales_code = '609';
        $old_gl_code = 'G70031';
							
		
	}
	
	
//Fire Equipment contract
	 if ($salesgl == '7102301'){
		
		
	$old_sales_code = '104';
    $old_gl_code = 'G610';
					
		
	}
	
	//Fire sprinkler contract
	
	 if ($salesgl == '7102300'){
		
		 $old_sales_code = '107';
                                        	$old_gl_code = 'G610';
					
		
	}

	//Fire Prepaid suva
	
	 if ($salesgl == '7101005'){
		
		
		 $old_sales_code = '111';
                                        	$old_gl_code = 'G61101';
					
	}
	
	
	//FE Sales
	 if ($salesgl == '7100900'){
		
		
		$old_sales_code = '202';
                                        	$old_gl_code = 'W7020102';
							
		
	}
	 if ($salesgl == '7100900'){
		
		
		 $old_sales_code = '302';
                                        	$old_gl_code = 'W7020202';
							
		
	}
   if ($salesgl == '7100900'){
		
		
		 $old_sales_code = '402';
                                        	$old_gl_code = 'W7020302';
						
	}
	
	// FE servicing
	   if ($salesgl == '7101003'){
		
		
		$old_sales_code = '210';
                                        	$old_gl_code = 'W7020106';
						
		
	}
	   if ($salesgl == '7101003'){
		
		
		$old_sales_code = '310';
                                        	$old_gl_code = 'W7020206';
						
		
	}
		  if ($salesgl == '7101003'){
		
	$old_sales_code = '410';
    $old_gl_code = 'W7020306';
					
		
	}
	
	//fire alarm small jobs
	
	  if ($salesgl == '7100600'){
		
		
		 $old_sales_code = '207';
                                        	$old_gl_code = 'W7060103';
								
		
	}
	   if ($salesgl == '7100600'){
		
		$old_sales_code = '307';
                                        	$old_gl_code = 'W7060203';
					
		
	}
		//7102200 Fire Sprinkler Small Jobs
	   if ($salesgl == '7102200'){
		
		
		$old_sales_code = '212';
        $old_gl_code = 'W7060107';
										
		
	}
	   if ($salesgl == '7102200'){
		
	 $old_sales_code = '312';
                                        	$old_gl_code = 'W7060207';
						
	}
		 //7100700  Annuals Survey  fee
	
	
	//7101001 Fire alarm monthly testing

	//7100300 Brigade Sales
	   if ($salesgl == '7100300'){
		
		
	 $old_sales_code = '201';
                                        	$old_gl_code = 'W7020101';
							
	}
	   if ($salesgl == '7100300'){
		
		$old_sales_code = '301';
                                        	$old_gl_code = 'W7020201';
							
		
	}
		  if ($salesgl == '7100300'){
		
		$old_sales_code = '401';
                                        	$old_gl_code = 'W7020301';
								
		
	}
	
	
	
	//7101006 Fire Pump Biannual Servicing
	
	
//7100603 Special Hazard R102 Servicing
   if ($salesgl == '7100603'){
		
		
		$old_sales_code = '301';
                                        	$old_gl_code = 'W7020201';
									
	}
	
	//7101001 Fire alarm weekly testing

	   if ($salesgl == '7101001'){
		
		
		 $old_sales_code = '205';
                                        	$old_gl_code = 'W7040103';
								
		
	}
	   if ($salesgl == '7101001'){
		
		
	$old_sales_code = '305';
                                        	$old_gl_code = 'W7040203';
									
	}
	   if ($salesgl == '7101001'){
		
		
		 $old_sales_code = '405';
                                        	$old_gl_code = 'W7040303';
								
	}
	
	//7100700  Annuals Survey  fee
	   if ($salesgl == '7100700'){
		
		
		 $old_sales_code = '204';
                                        	$old_gl_code = 'W7030103';
							
		
	}
	   if ($salesgl == '7100700'){
		
		
		 $old_sales_code = '304';
                                        	$old_gl_code = 'W7040203';
									
		
	}
	
	
	
	//7101000	Fire Training Sales
	
		   if ($salesgl == '7101000'){
		
	$old_sales_code = '206';
                                        	$old_gl_code = 'W7020401';
									
		
	}
	   if ($salesgl == '7101000'){
		
		$old_sales_code = '306';
                                        	$old_gl_code = 'W7020402';
								
		
	}
	
	//7100200 Installs Access System Small Jobs Income
			   if ($salesgl == '7100200'){
		
		
		$old_sales_code = '704';
                                        	$old_gl_code = 'S70004';
								
		
	}
	   if ($salesgl == '7100200'){
		
		
	$old_sales_code = '734';
                                        	$old_gl_code = 'S700204';
								
	}
	   if ($salesgl == '7100200'){
		
		
		 $old_sales_code = '703';
                                        	$old_gl_code = 'S700301';
								
		
	}
	
	//access system contract 7100100
	
		   if ($salesgl == '7100100'){
		
		
	$old_sales_code = '600';
                                        	$old_gl_code = 'G610';
								
		
	}
	   if ($salesgl == '7100200'){
		
		
		$old_sales_code = '700';
                                        	$old_gl_code = 'G610';
										
	}
	//cctv contract 7100400
	   if ($salesgl == '7100400'){
		
		
	$old_sales_code = '600';
                                        	$old_gl_code = 'G610';
								
	}
	   if ($salesgl == '7100400'){
		
		
		$old_sales_code = '700';
                                        	$old_gl_code = 'G610';
							
		
	}

	//cctv small jobs
			   if ($salesgl == '7100401'){
		
		
		$old_sales_code = '704';
             $old_gl_code = 'S70004';
		
	}
	   if ($salesgl == '7100401'){
		
		
		$old_sales_code = '734';
                                        	$old_gl_code = 'S700204';
							
		
	}
	
	//7100602	Installs Alarm Small Jobs
	
	 if ($salesgl == '7100602'){
		
		
	 $old_sales_code = '704';
                                        	$old_gl_code = 'S70004';
									
		
	}
	   if ($salesgl == '7100602'){
		
		
	$old_sales_code = '734';
                                        	$old_gl_code = 'S700204';
								
		
	}
	
	//7100601	Installs Alarm Contract
	  if ($salesgl == '7100601'){
		
		
	$old_sales_code = '600';
                                        	$old_gl_code = 'G610';
								
		
	}
	   if ($salesgl == '7100601'){
		
		 $old_sales_code = '700';
                                        	$old_gl_code = 'G610';
								
		
	}
	
	
	//7100201	Installs Prepaid Incomen G61101

		  if ($salesgl == '7100201'){
		
		
	 $old_sales_code = '801';
                                        	$old_gl_code = 'G61101';
					
	}
	   if ($salesgl == '7100201'){
		
		$old_sales_code = '621';
                                        	$old_gl_code = 'G61101';
								
	}
	
	// 7100202 installs alarm testing
	  if ($salesgl == '7100202'){
		
		
		 $old_sales_code = '701';
                                        	$old_gl_code = 'S70002';
							
		
	}
	  
	
	//monitoring
	
	  if ($salesgl == '7101800' || $salesgl == '7102000' ){
		
		
		$old_sales_code = '803';
                                        	$old_gl_code = 'S70005';
							
	}
	
	//cit
	
	  if ($salesgl == '7102600'){
		
		$old_sales_code = '900';
                                        	$old_gl_code = 'G70050';
								
		
	}
	
	


	









$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"]) && (isset($_POST['salesgl']))){

	

	

	//security check

		$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.

	

	   $debtorno = $_POST['customer'];

	   

	   $SQL77 = "SELECT 	departmentname

							 

			FROM department

			WHERE departmentid='" . $_POST['department'] . "'

			";

	

	$result77 = DB_query($SQL77);

	

	$myrow77 = DB_fetch_array($result77) ;

		

	$department = $myrow77['departmentname'];	

//get debtor headoffice details:

		$SQL100 = "SELECT 	name,

							address1,

						     address2,

				   			 address3,

							 address4,

							 address5,

							 address6,

							 paymentterms

							 

			FROM debtorsmaster

			WHERE debtorno='" . $_POST['customer'] . "'

			";

	

	$result100 = DB_query($SQL100);

	

	$myrow100 = DB_fetch_array($result100) ;

		$debtorname = $myrow100['name'];

		$debtorno = $_POST['customer'];

		$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'];

		

		

$sql4011 =  "SELECT billing_name, sub_billing_name

			FROM debtoraccount

			

			WHERE account_number = '" .  $_POST['account']. "'

			";

	$ErrMsg = _('This customer could not be added because');

			$result4011 = DB_query($sql4011,$ErrMsg);

	$myrow4011 = DB_fetch_array($result4011) ;



		$billingname = $myrow4011['billing_name'];



$subbillingname = $myrow4011['sub_billing_name'];





	

	if ($debtorname == 'CASH SALE'){

		

		$billingname = $_POST['cashcustomer'];

		

	}

	$cashcustomeradd = $_POST['cashcustomeradd'];

	

$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'];


	

	

		$SQL1002 = "SELECT 	*

							 

			FROM paymentterms

			WHERE termsindicator='" . $myrow100['paymentterms'] . "'

			";

	

	$result1002 = DB_query($SQL1002);

	

	$myrow1002 = DB_fetch_array($result1002) ;

		

	



$readableduedate = CalcDueDate(ConvertSQLDate($sqldate), $myrow1002['dayinfollowingmonth'], $myrow1002['daysbeforedue']);

	

	

	$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',

								

								'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'];


//$customernumber = $_POST['customer'] ;
	
	$departmenid = $_POST['department'];
	
	if ($customer == '165' && $departmenid =='11') {
		
		
		
$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/PDFInvoiceHeaderAHC.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_after_tax = 0;

	   $FontSize = 10;
$LeftOvers = $pdf->addText(245, $YPos+$FontSize, $FontSize,_('TO PROVIDE SECURITY SERVICES FOR THE AUSTRALIAN HIGH COMMISSION SUVA'));
$LeftOvers = $pdf->addText(290, $YPos, $FontSize,_('(37 PRINCES ROAD) AND NOMINATED RESIDENCES, SUVA, FIJI'));
		

 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_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";

		  }



		  		
             $stockname =($_POST["item_name"][$count]);
	 
			$stocknamefinal = preg_replace('/[^A-Za-z0-9 ]/', '',$stockname);	

        $sql6 = "INSERT INTO salesorderdetails (

											orderlineno,

											orderno,

											stkcode,

											stock_name,

											unitprice,

											quantity,

											uom,

											tax_code,

											cost_price,

											sales_gl,

											

											discountpercent,

										

											poline,

											itemdue)

										VALUES  (

								'".   $count. "',

								'" . $OrderNo . "',

								'" . $_POST["item_id"][$count] . "',

								'" . $stockname. "',

								'". trim($_POST["order_item_price"][$count])."',

								'". trim($_POST["order_item_quantity"][$count])."',

								'". $uom."',

								'Vat',

								'". round($cost,2)."',

								'". $_POST['salesgl']."',

								

								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/PDFInvoiceHeader.inc');

	//	} //end if need a new page headed up



			

	$qtyD =trim($_POST["order_item_quantity"][$count]);

	 $lineqty = locale_number_format($qtyD,2);

	 
	 if ($sqldate <= '2023-07-31'){
	$taxlineitem = (trim($_POST["order_item_price"][$count])  * 0.09);
	 
	 }elseif ($sqldate > '2023-07-31' && $sqldate <= '2025-07-31'){
	     
	  $taxlineitem = (trim($_POST["order_item_price"][$count])  * 0.15);
	 }else{
		 $taxlineitem = (trim($_POST["order_item_price"][$count])  * 0.125);
		 
	 }
	 $linetotal= trim($_POST["order_item_actual_amount"][$count]);

	 
	 
	$stup = locale_number_format($linetotal,2);


$lineitemtotal = (trim($_POST["order_item_price"][$count]) + $taxlineitem );
				

if ($lineitemtotal  == "0" ){

	

	$lineitemtotal  = '';



	$taxlineitem ='';


}

	 if ($lineqty > 0){
		 
		 $taxname = 'VAT';
	 }
				



			

			$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(570, $YPos,85,$FontSize,trim($_POST["order_item_price"][$count]),'right');

		

				$LeftOvers = $pdf->addTextWrap(650, $YPos,85,$FontSize,$taxlineitem,'right');

				$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90,$YPos,85,$FontSize,$lineitemtotal,'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/PDFInvoiceHeaderAHC.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/PDFInvoiceHeaderAHC.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;

	

			



		

$vepamountafterretention = ($order_total_before_tax - $retention);

			
if ($sqldate <= '2023-07-31'){

	$vat = ($vepamountafterretention * 0.09);
	
	}elseif ($sqldate > '2023-07-31' && $sqldate <= '2025-07-31') {
		
		$vat = ($vepamountafterretention * 0.15);
	}

	else{
		
		$vat = ($vepamountafterretention * 0.125);
	}

			

	       //2 decimal point outpu

	

	$vatfinal = locale_number_format($vat,2);

				

	

	$totalvepdec = locale_number_format($totalvep,2);

		

			$DisplayFreight = 0;

			

	$finalamount = $vepamountafterretention + $vat;

	

			$displaytotalfinal= locale_number_format($finalamount,2);

	$YPos -= $line_height;

	/*rule off for total */

			$pdf->line($Page_Width-$Right_Margin-810, $YPos+7,$Page_Width-$Right_Margin,$YPos+7);

	

	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90-655, $YPos-6, 655, $FontSize, _('Total(VEP)'),'right');

	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos-7, 90, $FontSize, _('$').locale_number_format($order_total_before_tax,2), 'right');

$YPos -= $FontSize;
	//$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90-655, $YPos-8, 655, $FontSize, _('Retention:'), 'right');
	//$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos-9, 90, $FontSize, _('-$').$retention, 'right');

$YPos -= $FontSize;

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

	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos-13, 90, $FontSize, _('$').$displaytotalfinal, 'right');

//line
$pdf->line($Page_Width-$Right_Margin-810, $YPos+$FontSize-25,$Page_Width-$Right_Margin,$YPos+$FontSize-25);
	
	// Print salesorders.comments:
	$YPos -= $FontSize*2;
	$pdf->addText($XPos+250, $YPos+$FontSize-25, $FontSize, _('TERMS: PAYMENT DUE ON 20th OF THE FOLLOWING MONTH OF PURCHASE'),'centre');
	$pdf->addText($XPos+200, $YPos+$FontSize-35, $FontSize, _('OUR BANKS: Westpac Bank: A/C: 9804778075 | ANZ Bank: A/C: 11879362 | BSP Bank: A/C: 9737614 | HFC Bank: A/C: 100118984'));
$pdf->addText($XPos+300, $YPos+$FontSize-45, $FontSize, _('BRED Bank: 043581800012 | BILL PAY AVAILABLE VIA ONLINE BANKING'));
	$pdf->addText($XPos+300, $YPos+$FontSize-55, $FontSize, _('Evergreen International Fiji LLC appreciates your business!'));
$pdf->addText($XPos+330, $YPos+$FontSize-70, $FontSize, _('Powered by E-Business ERP 2.0'));
	$pdf->addText($XPos, $YPos+$FontSize-75, $FontSize, _('Notes').':');

	$Width2 = $Page_Width-$Right_Margin-120;// Width to print salesorders.comments.

$LeftOvers =	$pdf->addTextWrap($XPos, $YPos+$FontSize-95,780,$FontSize, $_POST['order_notes']);

	//$LeftOvers = trim($quoteterms);

		//$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

	//**********

	   if (mb_strlen($LeftOvers)>0) {

				$LeftOvers = $pdf->addTextWrap($XPos,$YPos+$FontSize-110,780,$FontSize,$LeftOvers);

				if (mb_strlen($LeftOvers)>0) {

						//$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

	//**********

					$LeftOvers = $pdf->addTextWrap($XPos,$YPos+$FontSize-120,780,$FontSize,$LeftOvers);

					/*If there is some of the InvText leftover after 3 lines 200 wide then it is not printed :( */

				}

			}

	//**********

	$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/PDFInvoiceHeaderAHC.inc');

		}

		$LeftOvers = $pdf->addTextWrap(40, $YPos, $Width2, $FontSize, $LeftOvers);

	}

//$pdf->addText($XPos+330, $YPos+$FontSize-250, $FontSize, _('Powered by E-Business ERP 2.0'));

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

 

	

	$timenow = time();

	$modifieddatetime = date("Y-m-d h:i:sa", $timenow);

	

//debtor trans and debtor vat

			$SQLdebtor = "INSERT INTO debtortrans (transno,

									type,

									debtorno,

									projectid,

									branchcode,

									trandate,

									inputdate,

									prd,

									settled,

									reference,

									tpe,

									order_,

									lpo,

									rate,

									ovamount,

									ovgst,

									retention,

									sales_gl,

									old_sales_code,
									old_gl_code,

									invtext,

									account_number,

									department,

									entered_by,

									entered_date,

									cash_customer_name,

									cash_customer_address,
									contact_person)

				VALUES (

					'" . $InvoiceNo. "',

					'10',

					'" . $_POST['customer']. "',

					'" . $_POST['project']. "',

					'" . $myrow2['branchcode']. "',

					'" . $sqldate. "',

					'" . $sqldate . "',

					

					'" . $PeriodNo . "',

					'0',

					'General Invoice',

					'DE',

					

					 '" . $OrderNo . "',

					 '" . $_POST['lpo'] . "',

					'1',

					'" . $order_total_before_tax . "',

					'" . $vatfinal . "',

					'" . $retention . "',

					 '" .$_POST['salesgl'] . "',

					 '" .$old_sales_code . "',
					  '" .$old_gl_code . "',

					'" . $_POST['order_notes'] . "',

					'" . $_POST['account']. "',

					'" . $_POST['department']. "',

					'" . $realname . "',

					'" . $modifieddatetime . "',

					'" . $_POST['cashcustomer']. "',

					'" . $_POST['cashcustomeradd']. "',
					'" . $_POST['contactperson']. "'

					)";

		$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');

			
//fix vat errors if had any UPDATE `debtortrans` SET `ovgst` = ((`ovamount` - `retention`) * 0.09)

	if ($sqldate <= '2023-07-31'){
	$sql34 = "UPDATE debtortrans set ovgst =  ((ovamount - retention) * 0.09)
							
							WHERE id = '" . $DebtorTransID."'";


			$ErrMsg = _('The employee update could not be updated because');
			$DbgMsg = _('The SQL that failed was');
			$Result34 = DB_query($sql34,$ErrMsg,$DbgMsg,true);
	}elseif ($sqldate > '2023-07-31' && $sqldate <= '2025-07-31')  {
		
			$sql34 = "UPDATE debtortrans set ovgst =  ((ovamount - retention) * 0.15)
							
							WHERE id = '" . $DebtorTransID."'";


			$ErrMsg = _('The employee update could not be updated because');
			$DbgMsg = _('The SQL that failed was');
			$Result34 = DB_query($sql34,$ErrMsg,$DbgMsg,true);
	
				
	}else {
		
			$sql34 = "UPDATE debtortrans set ovgst =  ((ovamount - retention) * 0.125)
							
							WHERE id = '" . $DebtorTransID."'";


			$ErrMsg = _('The employee update could not be updated because');
			$DbgMsg = _('The SQL that failed was');
			$Result34 = DB_query($sql34,$ErrMsg,$DbgMsg,true);
	}
	
	
			//debtortranstax


				

				$SQLdebtortax = "INSERT INTO debtortranstaxes (debtortransid,

											taxauthid,

											taxamount)

								VALUES ('" . $DebtorTransID . "',

									'5',

									'" . $vatfinal. "')";



		$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);

	   

				

			

		 

     

			

			//increase trade debtors

	

	

			

	//update status

	

	

	$SQL20 = "UPDATE  salesorders set amount = '" . $order_total_before_tax  . "',

									  tax1 = '" . $vatfinal . "',

									
									total_amount = '" . $displaytotalfinal . "'

									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_' .$debtorname.'-'.$_POST['account']. $InvoiceNo. '.pdf');



		

		

	

	$pdf->__destruct();

	

	

	





	

	



	 //its not an email just print the invoice to PDF

	

	//upload data in Debtor



		
	} else{
		
		
		
$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/PDFInvoiceHeader.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_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_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";

		  }



		  		
             $stockname =($_POST["item_name"][$count]);
	 
			$stocknamefinal = preg_replace('/[^A-Za-z0-9 ]/', '',$stockname);	

        $sql6 = "INSERT INTO salesorderdetails (

											orderlineno,

											orderno,

											stkcode,

											stock_name,

											unitprice,

											quantity,

											uom,

											tax_code,

											cost_price,

											sales_gl,

											

											discountpercent,

										

											poline,

											itemdue)

										VALUES  (

								'".   $count. "',

								'" . $OrderNo . "',

								'" . $_POST["item_id"][$count] . "',

								'" . $stockname. "',

								'". trim($_POST["order_item_price"][$count])."',

								'". trim($_POST["order_item_quantity"][$count])."',

								'". $uom."',

								'Vat',

								'". round($cost,2)."',

								'". $_POST['salesgl']."',

								

								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/PDFInvoiceHeader.inc');

	//	} //end if need a new page headed up



			

	$qtyD =trim($_POST["order_item_quantity"][$count]);

	 $lineqty = locale_number_format($qtyD,2);

	 

	 $linetotal= trim($_POST["order_item_actual_amount"][$count]);

	$stup = locale_number_format($linetotal,2);



				

if ($order_total_before_tax  == "0.00" ){

	

	$order_total_before_tax  = '';

	$uom = '';

	$taxname='';

	$stup='';

	$lineqty ='';

}

	 if ($lineqty > 0){
		 
		 $taxname = 'VAT';
	 }
				


	

			

			$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(450, $YPos,85,$FontSize,$taxname,'right');

		$LeftOvers = $pdf->addTextWrap(510, $YPos,85,$FontSize,$lineqty,'right');

		  $LeftOvers = $pdf->addTextWrap(570, $YPos,85,$FontSize,$uom,'right');

		

				$LeftOvers = $pdf->addTextWrap(650, $YPos,85,$FontSize,trim($_POST["order_item_price"][$count]),'right');

				$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90,$YPos,85,$FontSize,$stup,'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/PDFInvoiceHeader.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/PDFInvoiceHeader.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;

	

			



		

$vepamountafterretention = ($order_total_before_tax - $retention);

			

	if ($sqldate <= '2023-07-31'){

	$vat = ($vepamountafterretention * 0.09);

}elseif ($sqldate > '2023-07-31' && $sqldate <= '2025-07-31') {
		
		$vat = ($vepamountafterretention * 0.15);
	}

	else{
		
		$vat = ($vepamountafterretention * 0.125);
	}

			

	       //2 decimal point outpu

	

	$vatfinal = locale_number_format($vat,2);

				

	

	$totalvepdec = locale_number_format($totalvep,2);

		

			$DisplayFreight = 0;

			

	$finalamount = $vepamountafterretention + $vat;

	

			$displaytotalfinal= locale_number_format($finalamount,2);

	$YPos -= $line_height;

	/*rule off for total */

			$pdf->line($Page_Width-$Right_Margin-810, $YPos+7,$Page_Width-$Right_Margin,$YPos+7);

	$pdf->line($Page_Width-$Right_Margin-810, $YPos+5,$Page_Width-$Right_Margin,$YPos+5);

	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90-655, $YPos-6, 655, $FontSize, _('Total(VEP)'),'right');

	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos-7, 90, $FontSize, _('$').locale_number_format($order_total_before_tax,2), 'right');

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

$YPos -= $FontSize;

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

	$LeftOvers = $pdf->addTextWrap($Page_Width-$Right_Margin-90, $YPos-13, 90, $FontSize, _('$').$displaytotalfinal, 'right');



	
	// Print salesorders.comments:
	$YPos -= $FontSize*2;
	$pdf->addText($XPos+250, $YPos+$FontSize-20, $FontSize, _('TERMS: PAYMENT DUE ON 20th OF THE FOLLOWING MONTH OF PURCHASE'),'centre');
	$pdf->addText($XPos+200, $YPos+$FontSize-35, $FontSize, _('OUR BANKS: Westpac Bank: A/C: 9804778075 | ANZ Bank: A/C: 11879362 | BSP Bank: A/C: 9737614 | HFC Bank: A/C: 100118984'));
$pdf->addText($XPos+300, $YPos+$FontSize-45, $FontSize, _('BILL PAY AVAILABLE VIA ONLINE BANKING'));
	$pdf->addText($XPos+300, $YPos+$FontSize-55, $FontSize, _('Evergreen International Fiji LLC appreciates your business!'));
$pdf->addText($XPos+330, $YPos+$FontSize-70, $FontSize, _('Powered by E-Business ERP 2.0'));
	$pdf->addText($XPos, $YPos+$FontSize-75, $FontSize, _('Notes').':');

	$Width2 = $Page_Width-$Right_Margin-120;// Width to print salesorders.comments.

$LeftOvers =	$pdf->addTextWrap($XPos, $YPos+$FontSize-95,780,$FontSize, $_POST['order_notes']);

	//$LeftOvers = trim($quoteterms);

		//$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

	//**********

	   if (mb_strlen($LeftOvers)>0) {

				$LeftOvers = $pdf->addTextWrap($XPos,$YPos+$FontSize-110,780,$FontSize,$LeftOvers);

				if (mb_strlen($LeftOvers)>0) {

						//$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

	//**********

					$LeftOvers = $pdf->addTextWrap($XPos,$YPos+$FontSize-120,780,$FontSize,$LeftOvers);

					/*If there is some of the InvText leftover after 3 lines 200 wide then it is not printed :( */

				}

			}

	//**********

	$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/PDFInvoiceHeader.inc');

		}

		$LeftOvers = $pdf->addTextWrap(40, $YPos, $Width2, $FontSize, $LeftOvers);

	}

//$pdf->addText($XPos+330, $YPos+$FontSize-250, $FontSize, _('Powered by E-Business ERP 2.0'));

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

 

	

	$timenow = time();

	$modifieddatetime = date("Y-m-d h:i:sa", $timenow);

	

//debtor trans and debtor vat

			$SQLdebtor = "INSERT INTO debtortrans (transno,

									type,

									debtorno,

									projectid,

									branchcode,

									trandate,

									inputdate,

									prd,

									settled,

									reference,

									tpe,

									order_,

									lpo,

									rate,

									ovamount,

									ovgst,

									retention,

									sales_gl,

									old_sales_code,
									old_gl_code,

									invtext,

									account_number,

									department,

									entered_by,

									entered_date,

									cash_customer_name,

									cash_customer_address,
									contact_person)

				VALUES (

					'" . $InvoiceNo. "',

					'10',

					'" . $_POST['customer']. "',

					'" . $_POST['project']. "',

					'" . $myrow2['branchcode']. "',

					'" . $sqldate. "',

					'" . $sqldate . "',

					

					'" . $PeriodNo . "',

					'0',

					'General Invoice',

					'DE',

					

					 '" . $OrderNo . "',

					 '" . $_POST['lpo'] . "',

					'1',

					'" . $order_total_before_tax . "',

					'" . $vatfinal . "',

					'" . $retention . "',

					 '" .$_POST['salesgl'] . "',

					 '" .$old_sales_code . "',
					  '" .$old_gl_code . "',

					'" . $_POST['order_notes'] . "',

					'" . $_POST['account']. "',

					'" . $_POST['department']. "',

					'" . $realname . "',

					'" . $modifieddatetime . "',

					'" . $_POST['cashcustomer']. "',

					'" . $_POST['cashcustomeradd']. "',
					'" . $_POST['contactperson']. "'

					)";

		$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');

			
//fix vat errors if had any UPDATE `debtortrans` SET `ovgst` = ((`ovamount` - `retention`) * 0.09)
if ($sqldate <= '2023-07-31'){
	$sql34 = "UPDATE debtortrans set ovgst =  ((ovamount - retention) * 0.09)
							
							WHERE id = '" . $DebtorTransID."'";


			$ErrMsg = _('The employee update could not be updated because');
			$DbgMsg = _('The SQL that failed was');
			$Result34 = DB_query($sql34,$ErrMsg,$DbgMsg,true);
	}elseif ($sqldate > '2023-07-31' && $sqldate <= '2025-07-31') {
		$sql34 = "UPDATE debtortrans set ovgst =  ((ovamount - retention) * 0.15)
							
							WHERE id = '" . $DebtorTransID."'";


			$ErrMsg = _('The employee update could not be updated because');
			$DbgMsg = _('The SQL that failed was');
			$Result34 = DB_query($sql34,$ErrMsg,$DbgMsg,true);
		
		
	}else{
		$sql34 = "UPDATE debtortrans set ovgst =  ((ovamount - retention) * 0.125)
							
							WHERE id = '" . $DebtorTransID."'";


			$ErrMsg = _('The employee update could not be updated because');
			$DbgMsg = _('The SQL that failed was');
			$Result34 = DB_query($sql34,$ErrMsg,$DbgMsg,true);
		
	}
	
			//debtortranstax


				

				$SQLdebtortax = "INSERT INTO debtortranstaxes (debtortransid,

											taxauthid,

											taxamount)

								VALUES ('" . $DebtorTransID . "',

									'5',

									'" . $vatfinal. "')";



		$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);

	   

				

			

		 

     

			

			//increase trade debtors

	

	

			

	//update status

	

	

	$SQL20 = "UPDATE  salesorders set amount = '" . $order_total_before_tax  . "',

									  tax1 = '" . $vatfinal . "',

									
									total_amount = '" . $displaytotalfinal . "'

									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_' .$debtorname.'-'.$_POST['account']. $InvoiceNo. '.pdf');



		

		

	

	$pdf->__destruct();

	

	

	





	

	



	 //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

	//$( ".orderdate" ).change(function () {
		
		
		
	//	alert($(this).val());
		
//	});



	$( "select[name='customer']" ).change(function () {

    var debtorno = $(this).val();

  

	var userid = '<?php echo $userid; ?>';

		

			if (userid == 'schand'){

	var department =parseInt(6);

	
			var depart=parseInt(25)

		}
		
		if (userid == 'manueli'){

var department =parseInt(6);

		
		var depart=parseInt(25)

	}
		if (userid == 'losa'){

	var department =parseInt(6);

			
			var depart=parseInt(25)

		}
			if (userid == 'stephanie'){

	var department =parseInt(6);

		
			var depart=parseInt(25)

		}

		if (userid == 'waqa'){

	var department =parseInt(2);

		

		}

		if (userid == 'nisha'){

	var department =parseInt(7);

			
var depart=parseInt(25)
		}

		if (userid == 'lusi'){

	var department =parseInt(9);

			

			var depart=parseInt(10)

			

		}
			if (userid == 'riaz'){

	var department =parseInt(9);

			

			var depart=parseInt(10)

			

		}
				if (userid == 'mere' ){

	var department =parseInt(9);

			

			var depart=parseInt(11)

			

		}
		
			if (userid == 'crispus' ){

	var department =parseInt(9);

			

			var depart=parseInt(0)

			

		}
				if (userid == 'lina' ){

	var department =parseInt(9);

			

			var depart=parseInt(0)

			

		}
		
			if (userid == 'zubia' ){

	var department =parseInt(9);

			

			var depart=parseInt(11)

			

		}
			if (userid == 'sureta' ){

	var department =parseInt(9);

			

			var depart=parseInt(11)

			

		}
		
			if (userid == 'sharukh'){

	var department =parseInt(18);

			

			var depart=parseInt(19)

			

		}

			if (userid == 'rowen'){

	var department =parseInt(8);

			var depart =parseInt(21);	


			

		}
				if (userid == 'rramlu'){

		var department =parseInt(8);

			var depart =parseInt(21);	

			


			

		}
				if (userid == 'nitika'){

		

			var department =parseInt(8);	

			var depart =parseInt(21);	


			

		}
		
			
		if (userid == 'Priti'){

		

			var department =parseInt(8);	

			var depart =parseInt(21);	


			

		}
		if (userid == 'zibran'){

		

			var department =parseInt(8);	

			var depart =parseInt(21);	


			

		}
		
			if (userid == 'ragnesh' || userid =='Avishek' ){

	
				var department =parseInt(3);

			var depart =parseInt(0);


			

		}
if (userid == 'mosheed' ){

	var department =parseInt(2);

			

			var depart=parseInt(0)

			

		}
		if (userid == 'roneelp'){

	var department =parseInt(2);

			

			var depart=parseInt(3)

			

		}
	
		
				if (userid == 'vineshkumarp'){

	var department =parseInt(2);

			

			var depart=parseInt(3)

			

		}
		
			if (userid == 'ronil'){

	var department =parseInt(2);

			

			var depart=parseInt(3)

			

		}
		
	if (userid == 'vani'){

	var department =parseInt(2);

			

			var depart=parseInt(3)

			

		}
			if (userid == 'ilimo' ){

	var department =parseInt(1);

			

			var depart=parseInt(0)

			

		}
				if (userid == 'semi' ){

	var department =parseInt(1);

			

			var depart=parseInt(0)

			

		}
		if (userid == 'marica'){

	var department =parseInt(1);

			

			var depart=parseInt(0)

			

		}
		if (userid == 'saula'){

	var department =parseInt(2);

			

			var depart=parseInt(19)

			

		}
	if (userid == 'salata'){

	var department =parseInt(1);

			

			var depart=parseInt(0)

			

		}
		 

    if(debtorno) {





        $.ajax({

            url: "invoice/accountnumber.php",

            dataType: 'Json',

            data: {'id':debtorno ,'department': department,'depart': depart },

            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" /></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_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 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();

               
                item_total = parseFloat(actual_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);

        });





        $('#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;

           // }



       



         // }



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

			

		$('#create_invoice').hide();



        });





	

	 });

	

	

	

	



	

	

	

	

</script>





<script type="text/javascript">

jQuery(document).on("ready xcrudafterrequest",function(){

    

});

</script>