<?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;
$edate=date("Y-m-d"); 
//////////////// Get Sequence Number ----------------------- 
 $querydoc=mysqli_query($con,"select * from sequence where seq_type='re' ")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 | Receipt Management </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;
}

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

<style>
  .add-bal {
    font-size: 40px; /* Adjust the font size as needed */
     color: red; 
  }
</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">
                New Receipt
            </h3>
          
          </div>
          <div class="col-22 grid-margin">
              <div class="card">
                <div class="card-body">
              
                          
    <form class="needs-validation" novalidate method="post" action="receipt_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">Rec No: </label>
                          <div class="col-sm-9">
                            <input type="text" class="form-control" id="rno" name="rno" value=<?php echo $receipt_no ; ?> readonly>
                          </div>
                        </div>




                      </div>
                      <div class="col-md-4">                  
                          <div class="form-group row">
                          <label class="col-sm-3 col-form-label">Type </label>
                          <div class="col-sm-9">
                          <select class="form-control select2" style="width: 100%;" name="rtype" id="rtype" required >
           <option value="0">~~~Select ~~~~</option>  
          <?php            
          $querydoc=mysqli_query($con,"select * from receipt_type  ")or die(mysqli_error());
          
          while($rowd=mysqli_fetch_array($querydoc)){
          ?>
          <option value="<?php echo $rowd['receipt_type'];?>"><?php echo $rowd['receipt_type'];?></option>        
          <?php }?>
          </select> 
                          </div> 

                          </div>  

                      </div>                            
                  <div class="col-md-4">
                        <div class="form-group row">
                          <label class="col-sm-3 col-form-label">Receipt Date: </label>
                          <div class="col-sm-8">
                            <input type="date" class="form-control" id="gdate" name="gdate" value= <?php echo $edate;?> readonly>
 
                          </div>
                        </div>

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

            

</div>
<div class="row">                     
                      <div class="col-md-4">
                        <div class="form-group row">
                          <label class="col-sm-3 col-form-label">Amount: </label>
                          <div class="col-sm-9">
                             <input type="text" class="form-control" id="amount" name="amount" onchange="checkAmount()">
                           
                          </div>
                        </div>




                      </div>
                      <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">Ref: </label>
                          <div class="col-sm-8">
                            <input type="text" class="form-control" id="ref" name="ref" >

                          </div>
                        </div>

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


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

</div>
<div class="row">                     
                      <div class="col-md-4">
                        <div class="form-group row">
                          <label class="col-sm-3 col-form-label">Employee </label>
                          <div class="col-sm-9">
                           
                            <select class="form-control select2" style="width: 100%;" name="emp_id" id="emp_id" required >
           <option value="0">~~~Select ~~~~</option>  
          <?php            
          $queryemp=mysqli_query($con,"SELECT * FROM employee_master  ")or die(mysqli_error());
          
          while($rowemp=mysqli_fetch_array($queryemp)){
          ?>
          <option value="<?php echo $rowemp['emp_id'];?>"><?php echo $rowemp['emp_name'];?></option>        
          <?php }?>
          </select> 
 
                          </div>
                        </div>
                      </div>
                                         
                          <div class="col-md-4">                  
                          <div class="form-group row">
                          <label class="col-sm-3 col-form-label">Tot Apply </label>
                          <div class="col-sm-9">
                      
                          <input id="totalInput" class="form-control" type="number" name="totalInput" value="0" readonly>

                          </div> 

                          </div>  


                      </div> 
                           <div class="col-md-4">
                        <div class="form-group row">
                          <label class="col-sm-3 col-form-label">Cash Received Date: </label>
                          <div class="col-sm-8">
                            <input type="date" class="form-control" id="cashdate" name="cashdate" >

                          </div>
                        </div>




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

<!---------end of third raw----------->
<!------------------------     New Chq Raw -------------->
     <div id="mydiv">
                    <div class="row">                     
                      <div class="col-md-4">
                        <div class="form-group row">
                          <label class="col-sm-3 col-form-label">Cheque No </label>
                          <div class="col-sm-9">
                            <input type="text" class="form-control" id="chqno" name="chqno" >
                          </div>
                        </div>
                      </div>

               <div class="col-md-4">
                        <div class="form-group row">
                          <label class="col-sm-3 col-form-label">Cheque Date </label>
                          <div class="col-sm-9">
                            <input type="date" class="form-control" id="chqdate" name="chqdate" >
                          </div>
                        </div>
                      </div>

  <div class="col-md-4">
    <div class="form-group row">
        <label class="col-sm-3 col-form-label">Cheque Bank</label>
        <div class="col-sm-9">
            <select class="form-control select2" style="width: 100%;" name="cbank" id="cbank" required>
                <option value="0">~~~Select ~~~~</option>
                <?php
                $querydoc = mysqli_query($con, "SELECT * FROM bank_master") or die(mysqli_error());
                while ($rowd = mysqli_fetch_array($querydoc)) {
                    ?>
                    <option value="<?php echo $rowd['bank_id']; ?>"><?php echo $rowd['bank_name']; ?></option>
                <?php } ?>
            </select>
        </div>
    </div>
</div>
<div class="col-md-4">
    <div class="form-group row">
        <label class="col-sm-3 col-form-label">Cheque Branch</label>
        <div class="col-sm-9">
            <select class="form-control select2" style="width: 100%;" name="cbranch" id="cbranch" required>
              <option value="0">~~~Select ~~~~</option>
                <?php
                $querydoc = mysqli_query($con, "SELECT *,CONCAT(branch_name,', ',ref_BankBranchcode) AS bname FROM branch_master") or die(mysqli_error());
                while ($rowd = mysqli_fetch_array($querydoc)) {
                    ?>
                    <option value="<?php echo $rowd['branch_id']; ?>"><?php echo $rowd['bname']; ?></option>
                <?php } ?>
            </select>
        </div>
    </div>
</div>

<!------------------------     End of Chq Raw -------------->













     </div>

                    </div>
<!-------------------------- DD------------------------>
     <div id="mydiv1">
                    <div class="row">                     
              

               <div class="col-md-4">
                        <div class="form-group row">
                          <label class="col-sm-3 col-form-label"> Bank Acc </label>
                          <div class="col-sm-9">
                             <select class="form-control select2" style="width: 100%;" name="abank" id="abank" required>
                <option value="0">~~~Select ~~~~</option>
                <?php
                $querydoc = mysqli_query($con, "SELECT * FROM account_master ") or die(mysqli_error());
                while ($rowd = mysqli_fetch_array($querydoc)) {
                    ?>
                    <option value="<?php echo $rowd['acc_id']; ?>"><?php echo $rowd['acc_name']; ?></option>
                <?php } ?>
            </select>
                           
                          </div>
                        </div>
                      </div>

  <div class="col-md-4">
    <div class="form-group row">
        <label class="col-sm-3 col-form-label">Deposited Date </label>
        <div class="col-sm-9">
            <input type="date" class="form-control" id="adate" name="adate" >


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




<!-------------------------- DD------------------------>



<!------------------------END of DD ----------------->







     </div>

                    </div>
 <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 type="button" class="btn btn-light" onclick="window.location.href='home.php';">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() { 
//alert("validating");


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

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

  if($('#amount').val() == 0){
           alert("Please enter the Amount !!!");               
            return false;
    } ////``````````````````````````````````````````

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

 //if($('#cashdate').val() == 0){
     if ($('#rtype').val() === 'Cash' && $('#cashdate').val().trim() === '') {
           alert("Please select Cash Received Date !!!");               
            return false;
    } ////``
   // cashdate


if ($('#rtype').val() === 'DD' && $('#adate').val().trim() === '') {
           alert("Please select Cash Deposit Date !!!");               
            return false;
    } ////``

if ($('#rtype').val() === 'DD' ) {  
       if($('#abank').val() == 0){
                 alert("Please select the Bank Account !!!");               
                  return false;
          } 
    } ////``

  
 if ($('#rtype').val() === 'Cheque' && $('#chqdate').val().trim() === '') {
        alert("Please select Cheque Date !!!");               
            return false;
    } ////``         
 
if ($('#rtype').val() === 'Cheque' ) {  
       if($('#chqno').val() == 0){
                 alert("Please Enter Cheque Number !!!");               
                  return false;
          } 
    } ////``

if ($('#rtype').val() === 'Cheque' ) {  
       if($('#cbank').val() == 0){
                 alert("Please Select the Bank !!!");               
                  return false;
          } 
    } ////`

if ($('#rtype').val() === 'Cheque' ) {  
       if($('#cbranch').val() == 0){
                 alert("Please Select the Bank !!!");               
                  return false;
          } 
    } ////`



 } ///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,bb,ano) {
var ftot=0;
var docid=rr;
var tot_appamtValue=0;
var app=0;
var doc_bal=bb;
 // var valx = parseFloat(val1.value);
var appamt_n=parseFloat(appamt);

if (appamt_n>doc_bal){
alert("Apply Amount Is greater than Balance Amount");
var appamtElements1 = document.getElementsByName('appamt[]');
for (var i = 0; i < appamtElements1.length; i++) {
        if (i==ano) {
            app = parseFloat(appamtElements1[i].value);
            appamtElements1[i].value=0;
            //alert(app);
        }
    }

    



        return; // Exit the function early
}


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("Apply Amount Is greater than Receipt Amount");
document.getElementById('amount').value = tot_appamtValue; 

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

 checkAmount();




 }
$(document).on('click', '.add-bal', function() {
    var index = $('.add-bal').index(this);
    var balValue = parseFloat($(this).closest('tr').find('td:eq(4)').text());
    $('.appamt-input').eq(index).val(balValue);
    updateArray(balValue, 1);
});

///////////////////////////
// Function to update apply amount and trigger validation

 //////////////////


  $('#rtype').on('change', function(){
    var paytype = $('#rtype').val();
   //alert(paytype);
  var x = document.getElementById("mydiv");
    var y = document.getElementById("mydiv1");

  if (paytype=='Cash'){
   // alert('cash');
       x.style.display = "none";
        y.style.display = "none";
  }
  if (paytype=='Cheque'){
    x.style.display = "block"; 
    y.style.display = "none";
  }

    if (paytype=='DD'){
     x.style.display = "none";
       y.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();




  //alert(cus_id);  
 $("#item-disp tr").remove();
      $.ajax({
                 type: 'POST',
                 dataType: "json",
                 url: 'cus_outstanding_disp.php',
                        data: {
                        'cus_id' : cus_id,  
                         },
                cache: false,
                success: function(result1) {
                  // alert("Please enter the route you visited !!!");
                  

 var row = $('<tr class="bg-success text-black"><td width=2%>' + "#" + '</td><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=2%><span class="add-bal" style="cursor: pointer;">+</span>' +
    '</td><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 appamt-input" id="appamt[]" name="appamt[]" onchange="updateArray(this.value, this.previousElementSibling.value, '+  result1[i].bal + ' , '+  i + ' )" ></td>');





row.find('.add-bal').click(function() {
  //alert("aa");
    // Get the index of the clicked "+" mark
    var index = $('.add-bal').index(this);
    // Get the corresponding value of result1[i].bal
    var balValue = result1[index].bal;
    // Set the value of the corresponding appamt[] input field
    $('.appamt-input').eq(index).val(balValue);
    updateArray(balValue,1)
});




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










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

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

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

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

</script>



<script>
$(document).ready(function() {
    $('#rtype').on('change', function() {
        var rtype = $(this).val();
        // Perform actions based on the selected rtype
        // You can use a switch statement or if-else conditions here
        var rno = generateRnoBasedOnRtype(rtype);
        $('#rno').val(rno);
    });
});

function generateRnoBasedOnRtype(rtype) {
  //alert(rtype);
    $.ajax({
        url: 'fetch_rno.php', // PHP script to fetch rno
        type: 'POST',
        data: {rtype: rtype},
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                $('#rno').val(response.rno);
            } else {
                console.error(response.error);
            }
        },
        error: function(xhr, status, error) {
            console.error(status + ': ' + error);
        }
    });
}


$(document).ready(function() {

  var x = document.getElementById("mydiv");
  var y = document.getElementById("mydiv1");
  x.style.display = "none";
  y.style.display = "none";

  $('#cashdate').closest('.form-group').hide();
    $('#rtype').on('change', function() {
        var rtype = $(this).val();
        if (rtype === 'Cash') {
            $('#cashdate').closest('.form-group').show();
        } else {
            $('#cashdate').closest('.form-group').hide();
        }
    });
});








</script>


<script>
    // Function to check amount against totalInput
    function checkAmount() {
        var amount = parseFloat(document.getElementById('amount').value);
        var totalInput = parseFloat(document.getElementById('totalInput').value);
        
        if (isNaN(amount) || isNaN(totalInput)) {
            alert('Invalid input. Please enter valid numbers.');
            document.getElementById('amount').value = totalInput;
            return;
        }
        
        if (amount < totalInput) {
            alert('Amount cannot be less than Total Apply value.');
            document.getElementById('amount').value = totalInput; // Reset amount to Total Apply value
        }
    }

    // Attach event listeners to the amount field
    document.getElementById('amount').addEventListener('change', checkAmount);
    document.getElementById('amount').addEventListener('blur', checkAmount);
</script>


