<?php
ob_start();
include('includes/session.inc');
$Title = _('Banking Batch');
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>


<?php

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

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

	
//collect reasons for cancelation


					$userid = $_SESSION['UserID'];

include('includes/newheader.php');
echo '<p> </p> <p></p><p class="page_title_text"><img alt="" src="'.$RootPath.'/css/'.$Theme.
		'/images/printer.png" title="' .// Icon image.
		_('Reasons for Cancellation .  ') . '" /> ' .// Icon title.
		_('Please this process needs to be done by the Finance Team in charge of banking') . '</p>';// Page title.
echo '<form method="post" action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '">';
	echo '<div class="col-sm-12">';// div class=?
	echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
echo '<table id= "firsttable" class="table">';

	echo '<tr>

		<td>' . _('Invoice Date') . ':</td>';

echo '<td>   <input  type="text" name="order_date" id="datepicker"  placeholder="" required = "required" /></td>

      </tr>';

	echo '<tr>

		<td>' . _('Invoice Date') . ':</td>';

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

      </tr>';
 

$SQL = "SELECT project_name,account_number
		                            FROM projectdetails
									
									WHERE projectid = '".$projectid."'";
						
						
						$result=DB_query($SQL);
						$myrow=DB_fetch_array($result);

$projectname = $myrow['project_name'];
	$accountnumber=$myrow['account_number'];


$SQL = "SELECT *
		FROM technician_worksheet
		WHERE id = '".$worksheetid."'";
$ErrMsg = _('The bank accounts could not be retrieved because');
$DbgMsg = _('The SQL used to retrieve the bank accounts was');
$AccountsResults = DB_query($SQL,$ErrMsg,$DbgMsg);




?>

    <table class="table-responsive">
                          <tr>

                      <th ></th>

                      <th ></th>
						 </tr>
						 
					   <tr>
						  <td><b>Project ID/JobNo:</b></td>
						  <td> <?php echo $projectid; ?></td>
						 </tr>
					 
						 <tr>
						  <td><b>Project Name:</b></td>
						  <td> <?php echo $projectname; ?></td>
						 </tr>
						 <tr>
						  <td><b>Account Number:</b></td>
						  <td> <?php echo $accountnumber; ?></td>
						 </tr>
					 
						
					  
		

                         </table>


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

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

                      <th></th>

                    
                    
                    </tr>

                  
<?php

	
							
	 
										$sqlbalances= "SELECT technician_worksheet_materials.stockid,technician_worksheet_materials.qty,stockmaster.description,stockmaster.price
		                            FROM technician_worksheet_materials
									INNER JOIN stockmaster on stockmaster.stockid=technician_worksheet_materials.stockid
									
									WHERE id = '".$worksheetid."'";
						
		$resultfromdebtoraccount =DB_query($sqlbalances);
	 
	
	 $count =0;
while ($myrowfromdebtoraccount = DB_fetch_array($resultfromdebtoraccount)){


	
	
          		
          		echo 		
					'<tr id= "row_id_' . $count . '" >
					<td><input type="text" name="item_id[]" id="itemid_1" class="form-control input-sm item_id" value="'.$myrowfromdebtoraccount['stockid'].'" /></td>
					 										
					<td><input type="text" name="item_name[]" id="itemname_1" class="form-control input-sm item_name" value="'.$myrowfromdebtoraccount['description'].'"/></td>
					<td><input type="text" name="order_item_quantity[]" id="orderitemquantity_1" data-srno="1" class="form-control input-sm order_item_quantity" value="'.$myrowfromdebtoraccount['qty'].'"/></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" value="'.$myrowfromdebtoraccount['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>
					
			      <td><button type="button" name="remove_row" id="'.$count.'"class="btn btn-danger btn-xs remove_row">X</button></td>
				
					</tr>';
		
		$count++;
	
	
	
			//$ac[]=	$accountnumber;
				//$cust=$AgedAnalysis['name'];
				
				//$bal[]=$finalbalance;
				//$cur[] = $finalcurrent;
			//	$thirty[]= $final30days;
			//	$sixty[]= $final60days;
			//	$ninety[]= $final90daysplus;
				
				
				// $data_arr[] = array("customer" =>$cust,"account" =>$accountnumber,"bal" =>$finalbalance,"cur" =>$finalcurrent,"thirty" =>$final30days,"sixty" =>$final60days,"ninety" =>$final90daysplus);
		}
				?>						
				
                  </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

if(isset($_POST["create_invoice"])) {
	
	$message = "You cant generate yet as the management has not approved it yet to use this!";
	echo "<script type='text/javascript'>alert('$message');</script>";
		 
	exit();
	
}
		

		
		
			    
		
	


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

?>
<script>

jQuery(document).ready(function($){



   // event must be delegated from .xcrud

	



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

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

  

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

		

			if (userid == 'schand'){

	var department =parseInt(6);

			var depart=parseInt(0)
			var depart=parseInt(25)

		}

			if (userid == 'stephanie'){

	var department =parseInt(6);

			var depart=parseInt(0)
			var depart=parseInt(25)

		}

		if (userid == 'waqa'){

	var department =parseInt(6);

			var depart=parseInt(0)
var depart=parseInt(25)
		}

		if (userid == 'nisha'){

	var department =parseInt(7);

			var depart=parseInt(0)
var depart=parseInt(25)
		}

		if (userid == 'lusi'){

	var department =parseInt(9);

			

			var depart=parseInt(10)

			

		}

			if (userid == 'rowen'){

	var department =parseInt(8);

			var department =parseInt(21);	


			

		}
				if (userid == 'rramlu'){

		var department =parseInt(8);

			var department =parseInt(21);	

			


			

		}
		
			if (userid == 'ragnesh'){

	var department =parseInt(3);

			


			

		}

		if (userid == 'ruth'){

	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 == '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" 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_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>
