<?php
  //invoice.php  
  include('db_con.php');
  
  include('function.php');
  
  if (isset($_SESSION['user_id'])) {
    $user_type = $_SESSION['user_type'];
    $user_id = $_SESSION['user_id'];
    $user_name = $_SESSION['user_name'];
    $branch_id = $_SESSION['branch_id'];
    $branch_name = $_SESSION['branch_name'];
    $store_id = $_SESSION['store_id'];
    $store_name = $_SESSION['store_name'];
}else{
  header('Location: login');
  die();
}
$dated = date('Y-m-d');
  $jv_id = $_GET["id"];
  settype($jv_id, "integer");
  
      
     ?>
  
  
<!DOCTYPE html>
<html>
<head>
  <?php include('include/head.php'); ?>
  <link rel="stylesheet" href="css/datepicker.css">
  <link rel="stylesheet" href="css/jquery.datetimepicker.css">
  <link rel="stylesheet" href="css/jquery.datetimepicker.min.css">
  <link rel="stylesheet" href="css/jquery.jquery-ui.min.css">
  
  
</head>
<body>
  <?php include('include/header.php'); ?>
  <?php include('include/sidebar.php'); ?>
<div class="main-container">
  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <div class="content-header">
      <div class="container-fluid">
        <div class="row mb-2">
          <div class="col-sm-6">
            <h1 class="m-0 text-dark"></h1>
          </div><!-- /.col -->
          <div class="col-sm-6">
            <ol class="breadcrumb float-sm-right">
              <li class="breadcrumb-item"><a href="#">GL</a></li>
              <li class="breadcrumb-item"><a href="jv.php">Jvs</a></li>
              <li class="breadcrumb-item active">New Jv </li>
            </ol>
          </div><!-- /.col -->
        </div><!-- /.row -->
      </div><!-- /.container-fluid -->
    </div>
    <!-- /.content-header -->
    <!-- Main content -->
    <section class="content">
      <div class="container-fluid">
        <!-- Small boxes (Stat box) -->
     <span id="alert_action"></span>
  <?php
if(isset($_GET["update"]) && isset($_GET["id"]))
      {
        $jv_id = $_GET["id"];
        $statement = $connect->prepare("
          SELECT * FROM jv 
            WHERE jv_id = :jv_id
            LIMIT 1
        ");
        $statement->execute(
          array(
            ':jv_id'       =>  $_GET["id"]
            )
          );
        $result = $statement->fetchAll();
        foreach($result as $row)
        {
          
        ?>
        <script src="vendors/scripts/script.js"></script>
        <script>
        $(document).ready(function(){
          
          $('#dated').val("<?php echo $row["dated"]; ?>");
          $('#description').val("<?php echo $row["description"]; ?>");
          $('#jv_id').val("<?php echo $jv_id; ?>");
          $('.loaded').val(1);
         
          
        });
        </script>
       
        <form method="post" id="data_form">
      <br />
      
        <div class="table-responsive">
          <table class="table table-bordered">
            <tr>
              <td colspan="2" align="center"><h2 style="margin-top:10.5px">Edit Jv Detail</h2></td>
            </tr>
            <tr>
            <span id="doc_status" class="doc_status"></span>
            </tr>
            <tr>
                <td colspan="2">
                  <div class="row">
                    <div class="col-md-8">
                              
              
                 
                  
                  <input type="text" name="description" id="description" class="form-control input-sm" placeholder="Description" />
                   <br />
                    </div>
                    <div class="col-md-4">
                                                    
                      <input type="text" name="dated" id="dated" class="form-control input-sm" readonly  AutoComplete="off" required />
                  <br />
                     
                    </div>
                  </div>
                  
                  <table id="jv-item-table" class="table table-bordered">
                   <tr>
                      <th width="5%">Sr#.</th>
                      <th width="35%">Account Name</th>
                      <th width="30%">Narration</th>
                      <th width="15%">Debit</th>
                      <th width="15%">Credit</th>
                      <th></th>
                      
                      
                    </tr>
                    <?php
                    $statement = $connect->prepare("
                      SELECT m.acc_name,d.acc_no,d.narr,d.debit,d.credit FROM jv_detail d,accounts m
                      WHERE m.acc_no=d.acc_no and d.jv_id = :jv_id
                    ");
                    $statement->execute(
                      array(
                        ':jv_id'       =>  $_GET["id"]
                      )
                    );
                    $item_result = $statement->fetchAll();
                    $m = 0;
                    foreach($item_result as $sub_row)
                    {
                      $m = $m + 1;
                    ?>
                    <tr id="row_id_<?php echo $m; ?>">
                      <td><span id="sr_no"><?php echo $m; ?></span></td>
                        <td><select name="acc_no[]" id="acc_no<?php echo $m; ?>" class="form-control input-sm acc_no select2" required />
                        <option value="<?php echo $sub_row["acc_no"]; ?>"><?php echo $sub_row["acc_name"]; ?></option>
                          <?php echo fill_accounts($connect);?>
                        </select></td>
                      <td><input type="text" name="narr[]" id="narr<?php echo $m; ?>"  class="form-control input-sm narr" value="<?php echo $sub_row["narr"]; ?>" /></td>  
                      <td><input type="text" name="debit[]" id="debit<?php echo $m; ?>"  class="form-control input-sm number_only debit" value="<?php echo $sub_row["debit"]; ?>" /></td>
                      <td><input type="text" name="credit[]" id="credit<?php echo $m; ?>" class="form-control input-sm number_only credit" value="<?php echo $sub_row["credit"]; ?>"/>
                      </td>
                      
                     <td><button type="button" name="remove_row[]" id="<?php echo $m; ?>" class="form-control btn btn-danger btn-xs remove_row">X</button> </td>
                    </tr>
                     <?php
                   
                    }
                    ?>
                  </table>
                  <div align="right">
                    <button type="button" name="add_row" id="add_row" class="form-control btn btn-success btn-xs">+</button>
                  </div>
                    <div align="left">
                    <span>Balance : </span><span id="acc_balance"></span>
                  </div>
                  </td>
                  </tr>
                
             
              <tr>
                <td width="70%" align="right"><b>Total Debit : <b></td><td><span id="total_debit"></span></b></td>
               
                </tr><tr>
                <td width="70%" align="right"><b>Total Credit : <b></td><td><span id="total_credit"></span></b></td>   
                
               
              </tr>
              <tr>
                <td colspan="2"></td>
              </tr>
             
              <tr>
                <td colspan="2" align="center">
                  <input type="hidden" name="total_item" id="total_item" value="<?php echo $m; ?>" />
                  <input type="hidden" name="jv_id" id="jv_id" value="<?php echo $jv_id; ?>" />
                  <input type="hidden" name="btn_action" id="btn_action" />
                  <input type="submit" name="update" id="btn_save" class="form-control btn btn-info" value="Update" />
                  <input type="hidden" name="loaded" class="loaded" />
                </td>
              </tr>
          </table>
        </div>
      </form>
       
      </div>
             
        
        
      </div><!-- /.container-fluid -->
    </section>
    <!-- /.content -->
 
  <!-- /.content-wrapper -->
 
    </div>
    </div>
 
  
  <script src="js/jquery-ui.js"></script>
  <script src="js/jquery-ui.min.js"></script>
  
  
  
</body>
</html>

  <script>
  var isSubmitting = false
$(document).ready(function () {
    $('#data_form').submit(function(){
        isSubmitting = true
    })
    $('#data_form').data('initial-state', $('#data_form').serialize());
    $(window).on('beforeunload', function() {
        if (!isSubmitting && $('#data_form').serialize() != $('#data_form').data('initial-state')){
            return 'You have unsaved changes which will not be saved.'
        }
    });
})
</script>
 <script>
 
  $(document).ready(function(){
    $(window).keydown(function(event){
    if(event.keyCode == 13) {
    
      event.preventDefault();
    }
  });
    $('#dated').datepicker({
      dateFormat: 'yy-mm-dd',
      changeMonth: true,
      changeYear: true
    });
  })
  
  </script>
 <script>
  $(document).ready(function(){
    $('#dated').datepicker({
      dateFormat: 'yy-mm-dd',
      changeMonth: true,
      changeYear: true
    });
  })
  </script>
  <script>
  $('.select2').select2();
  </script>
       <script>
      $(document).ready(function(){
        var final_total_amt = $('#total_amount').text();
        var count = "<?php echo $m; ?>";
        var loaded = $('.loaded').val();
        if(loaded==1)
        {
          cal_final_total(count);
          loaded = 0;
          $('.loaded').val(loaded);
        }
        
        
        $(document).on('click', '#add_row', function(){
          count++;
          $('#total_item').val(count);
          var html_code = '';
          html_code += '<tr id="row_id_'+count+'">';
          html_code += '<td><span id="sr_no">'+count+'</span></td>';          
          html_code += '<td><select name="acc_no[]" id="acc_no'+count+'" data-srno="'+count+'" class="form-control acc_no select2"><?php echo fill_accounts($connect); ?></select></td>';
          html_code += '<td><input type="text" name="narr[]" id="narr'+count+'" data-srno="'+count+'" class="form-control input-sm narr" /></td>';
          html_code += '<td><input type="text" name="debit[]" id="debit'+count+'" data-srno="'+count+'" class="form-control input-sm number_only debit" /></td>';
          html_code += '<td><input type="text" name="credit[]" id="credit'+count+'" data-srno="'+count+'" class="form-control input-sm number_only credit" /></td>';          
          
          html_code += '<td><button type="button" name="remove_row" id="'+count+'" class="form-control btn btn-danger btn-xs remove_row">X</button></td>';
          html_code += '</tr>';
          $('#jv-item-table').append(html_code);
          $('.select2').select2();
          $('#acc_no'+count).focus();
          
        });
        
       $(document).on('click', '.remove_row', function(){
          var row_id = $(this).attr("id");
         
          $('#row_id_'+row_id).remove();
          count--;
          $('#total_item').val(count);
          cal_final_total(count);
        });
          
  $(document).on('blur', '.narr', function(){
        var acc_no = $('#acc_no'+count).val();
    
   
    
    $.ajax({
      url:"acc_balance.php",
      method:"POST",
      data:{acc_no:acc_no},
      dataType:"json",
      success:function(data)
      {       
        
        $('#acc_balance').html(data.acc_balance);
        
        
      }
    })
  });
        function cal_final_total(count)
        {
          var total_debit_amt = 0;
          var total_credit_amt = 0;
          var or_debit = 0;
            var or_credit = 0;
          
          for(j=1; j<=count; j++)
          {
            
            
            var debit_amt = $('#debit'+j).val();
            var credit_amt = $('#credit'+j).val();
           
            
            
            
            if(debit_amt>0 && credit_amt >0)
            {
              alert("Enter Only Debit Or Credit Amount")
              return false;
            }
            
            
            if(debit_amt > 0)
            {
              total_debit_amt = parseFloat(total_debit_amt) + parseFloat(debit_amt);
              
              or_debit = debit_amt;
              $('#or_debit'+j).val(or_debit);
              
             
            }else
            {
              $('#or_debit'+j).val(0);
            }
            if(credit_amt > 0)
            {
              total_credit_amt = parseFloat(total_credit_amt) + parseFloat(credit_amt);
              
              or_credit = credit_amt;
              $('#or_credit'+j).val(or_credit);
               
             
            }else
            {
              $('#or_credit'+j).val(0);
            }
            
          
            
          }
          
          $('#total_debit').text(total_debit_amt);
          $('#total_credit').text(total_credit_amt);
        }
        
        //$("#item_type"+count).change(function(){
        //var itemtype = $(".item_type option:selected").val();
       
      
        
        $(document).on('blur', '.debit', function(){
          
          cal_final_total(count);
          
          
          
        });
        $(document).on('blur', '.credit', function(){
          cal_final_total(count);
         
        });
        
        
        $(document).on('submit', '#data_form', function(event){
           event.preventDefault();
          var tot_debit = $('#total_debit').text();
         var tot_credit = $('#total_credit').text();
         if(tot_debit=='' && tot_credit =='')
         {
          alert("Enter Debit Or Credit Amount");
          return false; 
         }else if(tot_debit !== tot_credit)
         {
          alert("Debit and Credit Are Not Equal");
          return false;
         }else
         {
          $('#btn_save').val('Wait...');
          $('#btn_save').attr('disabled','disabled');
          $('#btn_action').val('update');
          var _data = $(this).serialize();
          $.ajax({
            url:"jv_action.php",
            method:"POST",
            data:_data,
            success:function(data)
            {
             $('#alert_action').fadeIn().html('<div class="alert alert-success">'+data+'</div>');
              
              window.location = "jv";
              
            }
          })
         }
          
         
          
          
          $('#invoice_form').submit();
        });
      });
      </script>
       <?php
     }
   }
?>