<?php 
if(!isset($_SESSION)) { 
  session_start(); 
  include('../includes/dbcon.php');
}
if(empty($_SESSION['rm_id'])):
header('Location:../index.php');
endif;
$cval=0;
//$grn_no=0;

//////////////// Get Sequence Number ----------------------- 
 $querydoc=mysqli_query($con,"select * from sequence where seq_id=7 ")or die(mysqli_error());

    while($row=mysqli_fetch_array($querydoc)){ 
    $receipt_no=$row['cno'];  
    }

//////////////////End of gettinh sequence Number ------------------
?>
<!DOCTYPE html>
<html lang="en">


<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Sales Invox | Debtor Settlement </title>
  <!-- plugins:css -->
  <?php include('../includes/commonheader.php');?>
<style>
      div.scroll {
         display: block; 
            border: 0px solid red; 
            padding: 5px; 
            margin-top: 5px; 
            width: 100%; 
            height: 300px; 
            overflow-y: scroll; 
      }
    </style>

    <style>
#mydiv {
  width: 100%;
  padding: 5px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 10px;
}
</style>


</head>
<body>
 <?php include('../includes/header.php');?>
 <?php include('../includes/leftsidebar.php');?>
           <!-- partial -->
 <div class="main-panel">        
        <div class="content-wrapper">

          <div class="page-header">
            <h3 class="page-title">
               Serttlments
            </h3>
          
          </div>
          <div class="col-22 grid-margin">
              <div class="card">
                <div class="card-body">
              
                          
    <form class="needs-validation" novalidate method="post" action="settle_new_add.php" enctype="multipart/form-data" onsubmit="return validateForm()">                   
                    <div class="row">                     
                      <div class="col-md-4">
                        <div class="form-group row">
                          <label class="col-sm-3 col-form-label">Customer </label>
                          <div class="col-sm-9">
                          <select class="form-control select2" style="width: 100%;" name="cus_id" id="cus_id" required >
           <option value="0">~~~Select ~~~~</option>  
          <?php            
          $querydoc=mysqli_query($con,"select *,CONCAT(`customer_master`.`cus_name`,', ',`customer_master`.`cus_code`) AS `cus` from customer_master  ")or die(mysqli_error());
          
          while($rowd=mysqli_fetch_array($querydoc)){
          ?>
          <option value="<?php echo $rowd['cus_id'];?>"><?php echo $rowd['cus'];?></option>        
          <?php }?>
          </select> 
                          </div>
                        </div>




                      </div>
                      <div class="col-md-4">                  
                          <div class="form-group row">
                          <label class="col-sm-3 col-form-label">Documets (DB) </label>
                          <div class="col-sm-9">
                            <select class="form-control select2" style="width: 100%;" name="db_doc" id="db_doc" required>
                <option value="0">~~~Select ~~~~</option>
                <!-- Invoice numbers will be loaded dynamically using AJAX -->
            </select>
                          </div> 

                          </div>  

                      </div>                            
                  <div class="col-md-4">
                        <div class="form-group row">
                          <label class="col-sm-3 col-form-label">Document (Cr) </label>
                          <div class="col-sm-8">
                           <select class="form-control select2" style="width: 100%;" name="cr_doc" id="cr_doc" required>
                <option value="0">~~~Select ~~~~</option>
                <!-- Invoice numbers will be loaded dynamically using AJAX -->
            </select>

                          </div>
                        </div>

                    </div> <!-------End of first form raw------->

            

</div>
<div class="row">                     
                     
                                                
                 


<!-------Third raw------->

</div>
<div class="row">                     
                    
                                         
             
 </div>
<!---------end of third raw----------->


 <div class="scroll">             
                    <table id="item-disp"  class="table"> 
                        
                      <thead>
                        <tr>
                          <th>#</th>
                          <th>Document</th>
                          <th>Date</th>
                          <th>Type</th>
                          <th>Amount</th>
                          <th>Balance</th>
                          <th>Settle Amount</th>
                          <th>Apply</th>
                                                
</tr>
</thead>
</table>
</div>

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


<button type="submit" class="btn btn-primary">Save</button>
<button class="btn btn-light">Cancel</button>
</form>
</div>


  <div class="content-wrapper">

  </div>  <!----- <div class="content-wrapper">------>
  </div>
          
          
  </div>

 </div><!-----End of main panel--~~~~~~~~~~~~~~~~~~~~~~~--------------->
 </div><!-----Dont Delete this DIV--~~~~~~~~~~~~~~~~~~~~~~~--------------->
</div>
</div>
  <!-- container-scroller -->
<?php include('../includes/footer.php');?>
<?php include('../includes/commonjs.php');?>
 
</body>


</html>

<script>
    $( document ).ready(function() {
         // alert("Please Select Order Type");

    });

function validateForm() { 

   
    if($('#cus_id').val() == 0){
           alert("Please select a Customer !!!");               
            return false;
    } ////``````````````````````````````````````````


    if($('#db_doc').val() == 0){
           alert("Please select a Db  Document  !!!");               
            return false;
    } ////``````````````````````````````````````````
    //db_doc
        if($('#cr_doc').val() == 0){
           alert("Please select a Cr  Document  !!!");               
            return false;
    } ////``

// Validate appamt[] fields
    var appamtFields = $('input[name="appamt[]"]');
    var isValid = true;

    appamtFields.each(function() {
        var value = $(this).val();
        // Check if the field is empty
        if (value === '' || isNaN(value) || parseFloat(value) <= 0) {
            isValid = false;
            alert("Please enter a valid Apply Amount !!!");
            return false;  // Exit loop if validation fails
        }
    });

    if (!isValid) {
        return false;  // Prevent form submission if validation fails
    }

 } ///validateForm() { 

</script>

 <!-- End custom js for this page-->
  <script>
  $(function () {
    //Initialize Select2 Elements
    $('.select2').select2()

    //Initialize Select2 Elements
    $('.select2bs4').select2({
      theme: 'bootstrap4'
    })
  })

/////////////////////////////////////////
 function updateArray(appamt,rr) {
var ftot=0;
var docid=rr;
var tot_appamtValue=0;
var app=0;
 // var valx = parseFloat(val1.value);
var appamt_n=parseFloat(appamt);
var ptot=document.getElementById("totalInput").value;
var ptot_n=parseFloat(ptot);
var ftot=0;
ftot=appamt_n + ptot_n;
var receipt_amt1=document.getElementById("amount").value;
var receipt_amt=parseFloat(receipt_amt1);
//alert(receipt_amt);


var appamtElements = document.getElementsByName('appamt[]');

var tt=appamtElements.length;

  for (var i = 0; i < appamtElements.length; i++) {
     if (appamtElements[i].value>0){
      app=parseFloat(appamtElements[i].value);
      tot_appamtValue = tot_appamtValue  + app;
    }
  }


if (tot_appamtValue>receipt_amt){
alert("error");

}
else {
 document.getElementById("totalInput").value = tot_appamtValue ;
}




//var appamtValue = appamtElements[i].value;
//alert(tot_appamtValue);
//alert(appamt_n);
//alert(ptot_n);
//alert(ftot);
//alert(val);
//var bb=document.getElementById('ddc').value;
//alert(bb);


 }




  $('#rtype').on('change', function(){
    var paytype = $('#rtype').val();
   //alert(paytype);
  var x = document.getElementById("mydiv");
  if (paytype=='Cash'){
   // alert('cash');
       x.style.display = "none";
  }
  else {    //alert('che'); 
    x.style.display = "block"; 
  }


  //if (x.style.display === "none") {
   // x.style.display = "block";
  //} else {
   // x.style.display = "none";
  //}
   


 }) 



  ///////////////////////////////
  $('#cus_id').on('change', function(){
  var cus_id = $('#cus_id').val();


////////////////////////////////////////
// Pending debeit
            $.ajax({
                url: 'get_invoice_pending.php', // Create a separate PHP file to handle AJAX request
                type: 'POST',
                data: {cus_id: cus_id},
                success: function (data) {
                    $('#db_doc').html(data);
                }
            });
       
 ///////////////////////////////////////// 

     $.ajax({
                url: 'get_creditdoc_pending.php', // Create a separate PHP file to handle AJAX request
                type: 'POST',
                data: {cus_id: cus_id},
                success: function (data) {
                    $('#cr_doc').html(data);
                }
            });
       


////////////////////// Pending credit


  //alert(cus_id);  







     })  //// end of $('#rtype').on('change', function(){


      $('#cr_doc').on('change', function(){
        var cr_doc = $('#cr_doc').val();
        var cus_id = $('#cus_id').val();

         $("#item-disp tr").remove();
      $.ajax({
                 type: 'POST',
                 dataType: "json",
                 url: 'cus_outstanding_disp_doc.php',
                        data: {
                        'cus_id' : cus_id, 
                        'cr_doc' : cr_doc,

                         },
                cache: false,
                success: function(result1) {
                  // alert("Please enter the route you visited !!!");
                  

 var row = $('<tr class="bg-success text-black"><td width=10%>' + "Docid" + '</td><td width=10%>' + "Date" + '</td><td width=10%>'+ "Amount" + '</td><td width=10%>' + "Balance" +   '</td><td width=10%>' + "Apply Amount" +'</td>');
                 $('#item-disp').append(row);

                   for (var i=0; i<result1.length; i++) {
//var docid=result1[i].docid;
//var docid=document.getElementById('appamt[]').value;
//alert(docid);
var row = $('<tr class="table-success text-black"><td width=10%><input type="text" class="form-control" id="ddc" name="dd[]"  value="' + result1[i].docid+ '" readonly>' + '</td><td width=10%>' + result1[i].docdate +   '</td><td width=10%>' + result1[i].amount +   '</td><td width=10%>' + result1[i].bal +  
                        '</td><td width=10%><input type="hidden" class="form-control" id="doc[]" name="doc[]"  value="' + result1[i].docid+ '" readonly> <input type="text" class="form-control" id="appamt[]" name="appamt[]" onchange="updateArray(this.value, this.previousElementSibling.value)" >'  +
                       '</td>'  );

                        $('#item-disp').append(row);


                   } ///  for (var i=0; i<result1.length; i++) {

                   }   ////~~~~~~~~~~end of sucess functions
                });  ///~~~~~~~~~~~~~~~~~~end of  $.ajax({


         }) ///// 

  ////////////~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

</script>



