<?php
  //invoice.php  
  include('db_con.php');
  
  include('function.php');
  stock_update($connect);
  
  
 
  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'];
    $user_acc_no = $_SESSION['user_acc_no'];
}else{
  header('Location: login');
  die();
}
            stock_update($connect);
            $sql = "SELECT MAX(inv_no) FROM sr WHERE inv_type = 'Cash' and branch_id = '".$branch_id."'";
            $statement = $connect->prepare($sql);
            $statement->execute();
            $inv_no = $statement->fetchColumn();
            settype($inv_no, "integer");
            $inv_no++;
             $sql = "SELECT MAX(sr_id) FROM sr";
            $statement = $connect->prepare($sql);
            $statement->execute();
            $sr_id = $statement->fetchColumn();
            
            $sr_id++;
            $dated = date('Y-m-d');
  
  
  ?>
<!DOCTYPE html>
<html>
<head>
<title><?php  if(basename(__FILE__, '.php'=='csr_new.php')){echo 'New Return Cash Sale';}?></title>
  <?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">
  
  
  
</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><!-- /.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["add"]))
      {
      ?>
      
        
       <form method="post" id="data_form"  AutoComplete="off"  />
        <div class="table-responsive">
          <table class="table table-bordered">
            <tr>
              <td colspan="2" align="center"><h2>New Cash Sale Return  (<?php echo $sr_id;?>)</h2></td>
            </tr>
         
            <tr>
                <td colspan="2">
                  <div class="row">
                    <div class="col-md-6">
                    <table>
                      
                   
                     <tr><td colspan="2">
                        <div class="input-group">
                        <input type="text" name="contact" id="contact" class="form-control contact" placeholder="contact" required /><div class="input-group-addon" ><button type="button" id="contact_search" class="btn btn-primary"><i class="fa fa-search"></i></button></div>
                      </div></td>
                        </tr>
                        <tr><td>
                        <input type="text" name="cust_name" id="cust_name" class="form-control cust_name" placeholder="Customer Name"  /></td><td>
                     
                        
                        <input type="text" name="description" id="description" class="form-control description" placeholder="Enter Description"  />
                        </td></tr>
                       
                    </table>     
                    </div>
                    <div class="col-md-6">
                     
                    
                      <table>
                      <tr>
                      
                      <td>
                         <b>Date :</b>
                      <input type="text" name="dated" id="dated" class="form-control input-sm" placeholder="Select Date" value="<?php echo $dated; ?>" readonly AutoComplete="off" required />
                      </td>

                      <td>
                         <b>Bilty No. :</b>
                     <input type="text" name="bilty_no" class="form-control bilty_no" placeholder="Builty No.">
                      </td>
                      </tr>
                      
                      <tr>
                    
                    
                     <td colspan="2">
                       <b>Print Titles :</b>
                      <select name="title_id" id="title_id" class="form-control input-sm title_id" required />
                           <?php echo fill_titles($connect);?>
                        </select>
                      </td>
                      </tr>
                     
                      </table>
                    
                      
                    </div>
                  </div>
                  <br />
                
                  <table width="100%" id="invoice-item-table" class="table table-bordered">
                   <tr>        
       
           
          <td width="40%"><input type="hidden" name="item_no" id="item_no" class="form-control input-sm item_no" ><select name="type_id" id="type_id"  class="form-control input-sm type_id select2"><?php echo fill_itemtype($connect);?></select></td>
         <td width="25%"><input type="text" name="item_name" id="item_name" class="form-control input-sm number_only item_name" list="datalist1" placeholder="Description"></td>         
          <td width="15%"><input type="number" name="item_qty" id="item_qty"  class="form-control input-sm number_only item_qty" placeholder="Qty"></td>
          <td width="15%"><input type="number" name="item_rate" id="item_rate"  class="form-control input-sm number_only item_rate" step="any" placeholder="Rate"><input type="hidden" name="item_rate" id="item_cost"  class="form-control input-sm number_only item_cost" step="any" placeholder="Cost"></td></td>
             <td width="5%"><button type="button" name="add_row" id="add_row" class="form-control btn btn-success btn-xs"><i class="fa fa-download"></i></button></td>
                  </table>
                        <div align="left">
                    <span id="item_info"></span>
                     <span id="item_detail"></span>
                     
                  </div>        
                   <table id="items-table" class="table table-responsive table-bordered">
                     <thead>
                       <tr>
                        <td width="3%">#</td><td width="57%">Item</td><td width="10%">Qty</td><td width="15%">Rate</td><td width="20%">Amount</td><td width="5%"></td>
                       </tr>
                     </thead>
                    </table>               
                  
               
                </td>
              </tr>
              <tr>
                <td align="right"><b>Gross Amount</td>
                <td align="right"><b><span id="total_amount"></span></b></td>
              </tr>
            
               <tr>
                <td width="80%"><input type="text" name="discount_dsc" id="discount_dsc" class="form-control discount_dsc" value="Discount :"></td>
                <td width="80%" align="right"><input type="text" name="discount" id="discount" class="form-control discount" placeholder="Less Amount" style="text-align:right"></td>
              </tr>
                <tr>
                <td width="80%"><input type="text" name="freight_dsc" id="freight_dsc" class="form-control freight_dsc" value="Freight :"></td>
                <td width="80%" align="right"><input type="text" name="freight" id="freight" class="form-control freight" placeholder="Add Amount" style="text-align:right"></td>
              </tr>
             
              <tr>
                <td width="80%"align="right"><b>Net Amount :</td>
                <td width="80%" align="right"><b><span id="net_total"></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="0" />
                  <input type="hidden" name="loaded" id="loaded" value="0" />
                 <input type="hidden" name="first_row" id="first_row" class="first_row" value="0" /> 
                
                     
                    <input type="hidden" name="gst_pr" class="gst_pr" />     
                      <input type="hidden" name="btn_action" id="btn_action" class="btn_action" />     
                 <table>
                    <tr>   
                  <td><input type="submit" name="btn_save" id="btn_save" class="form-control btn btn-primary" value="Save" /></td>
                 
                </tr>
              </table>
                </td>
              </tr>
          </table>
        </div>
      </form>
      </div>
             
        
        
      </div><!-- /.container-fluid -->
    </section>
    <!-- /.content -->
 
  <!-- /.content-wrapper -->
 
    </div>
    </div>
  
  
<datalist id="datalist1">
  
</datalist>
<?php include('include/script.php');?>
<script src="js/jquery-ui.js"></script>
  <script src="js/jquery-ui.min.js"></script>
</body>
</html>
<script type="text/javascript">
    document.getElementById("contact_search").onclick = function () {
      var contact = $('#contact').val();
        window.open('rpt_contact_history?id='+contact,'_blank');
    };
</script>
<script>
  
   document.getElementById("title_id").selectedIndex = 1;
   var f1 = flatpickr(document.getElementById('dated'));
  </script>
<script>
$(document).ready(function () {
    $('.btn_save').click(function(event) {
   
         if(!event.detail || event.detail == 1){ return true; }
  else 
    { return false; }
 
  });
});
</script>
 <script>
 
  $(document).ready(function(){
    $(window).keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }

  });
      $('#dated').datepicker({
      dateFormat: 'yy-mm-dd',
      changeMonth: true,
      changeYear: true
    });
 
  })
  $('.select2').select2();
   
  </script>
     
      <script>
      $(document).ready(function(){
       var total_amount = $('#total_amount').text();
       var loaded = $('#loaded').val();
       if(loaded==0){$('#contact').focus();loaded=1;$('#loaded').val(1);}
        var count = 0;       

     $(document).on('click', '#add_row', function(){

          var item_no = $('#item_no').val();
           if(item_no==''){$('#type_id').focus();}
           var item_name = $('#item_name').val();
           var type_id = $('#type_id').select2('data')[0]['text'];
           var item = type_id+ ' - ' +item_name;
           var qty = $('#item_qty').val();
           var rate = $('#item_rate').val();
           var amount = parseFloat(qty) * parseFloat(rate);

           if(type_id ==''){$('#type_id').focus();return false;}
           if(item_name ==''){$('#item_name').focus();return false;}
           if(qty ==''){$('#item_qty').focus();return false;}
           if(rate ==''){$('#item_rate').focus();return false;}
          if(item_no > 0)
          {       
          

           count++;
           $('#total_item').val(count);
          var html_code = '';
          html_code += '<tr id="row_id_'+count+'">';
          html_code += '<td>'+count+'</td>';
          html_code += '<td><input type="hidden" name="item_no[]" id="item_no'+count+'" data-srno="'+count+'" class="form-control item_no input-sm" step="any" value="'+item_no+'" readOnly><input type="text" name="item_name[]" data-srno="'+count+'" class="form-control" value="'+item+'" readOnly></td>';         
        
          html_code += '<td><input type="number" name="qty[]" id="qty'+count+'" data-srno="'+count+'" class="form-control input-sm qty" step="any" value="'+qty+'"></td>';
          html_code += '<td><input type="number" name="rate[]" id="rate'+count+'" data-srno="'+count+'" class="form-control input-sm number_only rate" step="any" value="'+rate+'" readOnly></td>';
          html_code += '<td><input type="number" name="amount[]" id="amount'+count+'" data-srno="'+count+'" class="form-control input-sm number_only amount" step="any" value="'+amount+'" readOnly></td>';
        
       
          html_code += '<td><button type="button" name="remove_row" id="'+count+'" class="form-control btn-xs btn-danger btn-xs remove_row">X</button></td>';
          html_code += '</tr>';
          $('#items-table').append(html_code);

           $('#item_detail').text('');
           $('#item_qty').val('');
           $('#item_rate').val('');
           $('#item_name').val('');
           $('#type_id').val('refresh');
           cal_final_total(count);          
          $('#type_id').focus();
        }else{return false;}
        
        });
        
      $(document).on('click', '.remove_row', function(){
            var row_id = $(this).attr("id");
           if(confirm("Are you sure you want delete it permanently?"))
          {
            $('#row_id_'+row_id).remove();
             cal_final_total(count);
            count--;
            $('#total_item').val(count);
          }
         });     
      $(document).on('select2:select','.select2', function(e){
            var x = $(this).val();
            $.ajax({
              url:"find_item.php",
              method:"POST",
              data:{type_id:x},
              dataType:"text",
              success:function(data)
              {
                
                $('#item_name').val('');
                $('#datalist1').html(data);
                
              
              }
           
         })
      });      
       
      
         function cal_final_total(count)
        {
         var final_item_amount = 0;
         var  final_dis_amount = 0;
         
          for(j=1; j<=count; j++)
          {
            var qty = 0;
            var rate = 0;
            var amount = 0;
           
           
            var total_amount = 0;
           
           
            qty = $('#qty'+j).val();
            if(qty > 0)
            {
              rate = $('#rate'+j).val();
              
              if(rate > 0)
              {
                amount = parseFloat(qty) * parseFloat(rate);
                $('#amount'+j).val(amount);             
                
           
                final_item_amount = parseFloat(final_item_amount) + parseFloat(amount);     
               
               
              
              }
            }
          }
          var new_final_item_amount = Number(final_item_amount).toFixed(2);
          $('#total_amount').text(new_final_item_amount);
          
          
          var net_total = 0;
          var gst_amount= 0;
         gst_pr = 0;
          net_total = parseFloat(final_item_amount) ;
          if(gst_pr > 0)
          {
            gst_amount = parseFloat(final_item_amount) * parseFloat(gst_pr)/100;
          }
         
         // $('#gst_amount').val(gst_amount);
          net_total = parseFloat(final_item_amount);
          
         // $('#total_item_discount').text(final_dis_amount);
          // $('#total_item_discount').text(final_dis_amount);
       var discount = $('#discount').val();
         var freight = $('#freight').val();
           if(discount==''){discount=0;}
         if(freight==''){freight=0;}
         net_total = parseFloat(net_total) -  parseFloat(discount) + parseFloat(freight);
     //   net_total = new Number(net_total).toLocaleString("en-US");
        // gst_amount = new Number(gst_amount).toLocaleString("en-US");
       var new_net_total =  Number(net_total).toFixed(2);
       //var new_gst_amount = Number(gst_amount).toFixed(2);
          $('#net_total').text(new_net_total);  
        
         //   $('#gst_amount').val(new_gst_amount);            
          
        }        
           
        $(document).on('blur', '.contact', function(){
          var cell_no = $('#contact').val();
          //$('#cust_name').val(null);
          $.ajax({
                url:"cell_data.php",
                method:"POST",
                data:{cell_no:cell_no},
                dataType:"json",
                success:function(data){
                     
                    $('#cust_name').val(data.cust_name);          
                   
                     
                }
           });
          if($('#cust_name').val()=='Credit Customer'){
            $('#cust_name').val(null);
          }
        });
 $(document).on('blur', '.item_qty', function(){
  
    var item_no = $('#item_no').val();
    var contact = $('#contact').val();
   
    
    $.ajax({
      url:"item_history_cash.php",
      method:"POST",
      data:{item_no:item_no, contact:contact},
      dataType:"json",
      success:function(data)
      {   
         if(item_no > 0)
        {
       // $('#rate'+count).val(data.rate);
        
        $('#item_detail').html(data.item_detail);
        }
        
        
      }
    })
  });
   
        
        
    $(document).on('blur', '.item_name', function(){
      
          var item_id = 0;
          var btn_action = 'check';
          var type_id = $('#type_id').val();
          var item_name = $('#item_name').val();
          $.ajax({
                  url:"check_item.php",
                  method:"POST",
                  data:{btn_action:btn_action,type_id:type_id,item_name:item_name},
                  dataType:"json",
                  success:function(data)
                  {
                  item_id = data.item_id;
                  if(item_id > 0)
                    {
                      $('#item_no').val(data.item_id);  
                      $('#item_cost').val(data.item_cost);       
                    }else{$('#item_no').val(0);$('#item_info').text('New Item Will Be add');}
                  
                  }
                
                })
          
        }); 
        $(document).on('blur', '.item_rate', function(){
         var item_id = $('#item_no').val(); 
         if(item_id ==0)
                    {
                      if(confirm("Are you sure you want to add this item?"))
                      {
                        var cost = prompt("Please enter Item Cost", "");
                        if(cost !=null)
                        {
                          var item_cost = cost;
                        }
                        var btn_action = 'add';
                        var type_id = $('#type_id').val();
                        var item_name = $('#item_name').val();
                        $.ajax({
                          url:"create_item.php",
                          method:"POST",
                          data:{type_id:type_id, item_name:item_name, item_cost:item_cost, btn_action:btn_action},
                          dataType:"json",
                          success:function(data)
                          {
                            $('#item_no').val(data.item_id);
                            alert('Item Added');
                            $('#item_info').text('');
                           
                           
                          }
                        })
                      }
                      else
                      {
                        return false;
                      }
                    }
                  
          
        }); 
        $(document).on('submit', '#data_form',function(event){
            event.preventDefault();
              cal_final_total(count);
              
            $('#btn_save').val('Wait...');
            $('#btn_save').attr('disabled','disabled');
            $('#btn_action').val('save');
            var _data = $(this).serialize();
            $.ajax({
              url:"csr_action.php",
              method:"POST",
              data:_data,
              success:function(data)
              {
               $('#alert_action').fadeIn().html('<div class="alert alert-success">'+data+'</div>');
             //  window.open("sale_invoice_return_a7?print=1&id=0","_blank");
                window.location = "csr";
              }
            })
          });
        /// save Only

       
        document.onkeyup = function(e) {
          if (e.which == 35) {
             cal_final_total(count);
              
            $('#btn_save').val('Wait...');
            $('#btn_save').attr('disabled','disabled');
            $('#btn_action').val('save');
            var _data = $('#data_form').serialize();
            $.ajax({
              url:"csr_action.php",
              method:"POST",
              data:_data,
              success:function(data)
              {
               $('#alert_action').fadeIn().html('<div class="alert alert-success">'+data+'</div>');
           //    window.open("sale_invoice_a7?print=1&id=0","_blank");
                window.location = "csr";
              }
            })
          }else if (e.which == 36) {
             cal_final_total(count);
              
            $('#btn_save').val('Wait...');
            $('#btn_save').attr('disabled','disabled');
            $('#btn_action').val('save');
            var _data = $('#data_form').serialize();
            $.ajax({
              url:"csr_action.php",
              method:"POST",
              data:_data,
              success:function(data)
              {
               $('#alert_action').fadeIn().html('<div class="alert alert-success">'+data+'</div>');
             //  window.open("sale_invoice_a7?print=1&id=0","_blank");
              window.location = "csr_new?add=1";
              }
            })
          }
        };

        $(document).on('blur', '.item_rate',function(){
        var cost  = $('#item_cost').val();
        var rate  = $('#item_rate').val();
      
          
        
           

                    if(parseFloat(rate) < parseFloat(cost) ){
                      $('#item_rate').val(null);
                      $('#item_rate').focus();
                      
                    }else{return true;}

          
          cal_final_total(count);
          
        }); 
  
         $(document).on('blur', '.cust_name', function(){
         
          $('#type_id').focus();
        });
          $(document).on('blur', '.contact', function(){
          $('#cust_name').focus();
        });
    
        $(document).on('blur', '.tot', function(){
          cal_final_total(count);
        });  
        
        
        $(document).on('blur', '.discount', function(){
          cal_final_total(count);
        });
        $(document).on('blur', '.freight', function(){
           cal_final_total(count);
        });   
       
        
      });
      </script>
    
      <?php
      }
      
      ?>     