<?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'];
        $user_acc_no = $_SESSION['user_acc_no'];
}else{
  header('Location: login');
  die();
}
$sr_id = $_GET["id"];
$ref_id = $sr_id;

    ?>
<!DOCTYPE html>
<html>
<head>
<title><?php  if(basename(__FILE__, '.php'=='csr_edit')){echo 'Cash Return Sale Edit';}?></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">
  <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="#">Accounts Receivable</a></li>
              <li class="breadcrumb-item"><a href="csr">Cash sr Invoices</a></li>
              <li class="breadcrumb-item active">Edit Cash Invoice </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["edit"]) && isset($_GET["id"]))
      {
        
        $sr_id = $_GET["id"];
        $statement = $connect->prepare("
         SELECT m.dated,m.inv_no,m.po_no,m.chal_no,m.cust_name,m.contact,m.sm_id,m.bilty_no,m.description,m.discount,m.discount_dsc,m.freight,m.freight_dsc,m.emp_id,m.title_id,m.gst,m.gst_pr,s.sname from sr m, sr_detail d, sales_man s, employees e,titles t where m.sr_id=d.sr_id and s.sm_id=m.sm_id and t.id=m.title_id and m.emp_id=e.emp_id and m.sr_id = :sr_id
            LIMIT 1
        ");
        $statement->execute(
          array(
            ':sr_id'       =>  $sr_id
            )
          );
        $result = $statement->fetchAll();
        include('include/script.php');
       
 
        foreach($result as $row)
        {
        ?>
      
        <script>
        $(document).ready(function(){
          
          $('#dated').val("<?php echo $row["dated"]; ?>");
            $('#po_no').val("<?php echo $row["po_no"]; ?>");
              $('#bilty_no').val("<?php echo $row["bilty_no"]; ?>");
                $('#chal_no').val("<?php echo $row["chal_no"]; ?>");
                  $('#cust_name').val("<?php echo $row["cust_name"]; ?>");
                    $('#contact').val("<?php echo $row["contact"]; ?>");
                      $('#description').val("<?php echo $row["description"]; ?>");
                        $('#emp_id').val("<?php echo $row["emp_id"]; ?>");
                        $('#gst').val("<?php echo $row["gst"]; ?>");
                        $('#gst_pr').val("<?php echo $row["gst_pr"]; ?>");
                        $('.gst_pr').val("<?php echo $row["gst_pr"]; ?>");
                          $('#title_id').val("<?php echo $row["title_id"]; ?>");
                            $('#inv_no').val("<?php echo $row["inv_no"]; ?>");
                              $('#discount').val("<?php echo $row["discount"]; ?>");
                                $('#discount_dsc').val("<?php echo $row["discount_dsc"]; ?>");
                                  $('#freight').val("<?php echo $row["freight"]; ?>");
                                    $('#freight_dsc').val("<?php echo $row["freight_dsc"]; ?>");
                                    $('#sm_id').val("<?php echo $row["sm_id"]; ?>");
        
               
          $('.select2').select2();
          $('.loaded').val(1);
        });
        </script>
        
        <form method="post" id="data_form" AutoComplete="off" />
        <div class="table-responsive">
          <table class="table table-bordered">
            <tr>
              <td colspan="2" align="center"><h2 style="margin-top:10.5px">Edit Cash Return Invoice <?php echo $_GET['id'];?></h2></td>
            </tr>
            <br />
            <br />
            <tr>
                <td colspan="2">
                  <div class="row">
                    <div class="col-md-6">
                      <br />
                                             
                     <input type="text" name="contact" id="contact" class="form-control contact" placeholder="contact" required />
                        <br />
                        
                        <input type="text" name="cust_name" id="cust_name" class="form-control cust_name" placeholder="Customer Name" required />
                     
                        <br />
                        <input type="text" name="description" id="description" class="form-control" placeholder="Enter Description" />
                        <br />
                        
                       
                    </div>
                    <div class="col-md-6">
                     
                      <br />
                      <table>
                      <tr>
                      <td>
                      <b>Inv No. :</b><input type="text" name="inv_no" id="inv_no" class="form-control inv_no" readonly>
                       <td>
                       
                       <b>GST :</b>
                      <select name="gst" id="gst" class="form-control gst" required />
                    
                      
                     <option value="OFF">GST OFF</option>
                      <option value="ON">GST ON</option>
                      </select></td>
                      
                    
                    
                      <td colspan="2">
                         <b>Date :</b>
                      <input type="text" name="dated" id="dated" class="form-control input-sm" placeholder="Select Date"  readonly AutoComplete="off" required />
                      </td>
                      </tr>
                      
                      <tr>
                      <td>
                      <b>Due Days:</b><input type="text" name="due_day" id="due_day" class="form-control due_day" value="0" readonly>
                      </td>
                      <td>
                      <b>PO No. :</b><input type="text" name="po_no" id="po_no" class="form-control po_no">
                      </td>
                      <td>
                      <b>Bilty No. :</b><input type="text" name="bilty_no" id="bilty_no" class="form-control bilty_no">
                      </td>
                      <td>
                      <b>Chal No. :</b><input type="text" name="chal_no" id="chal_no" class="form-control chal_no"></td>
                      </tr>
                      <tr>                
                     
                     
                      </tr>
                      <tr>
                      
                      
                      
                      
                      <td colspan="2">
                      <b>Delivered By :</b>
                      <select name="emp_id" id="emp_id" class="form-control input-sm emp_id" required />
                           <?php echo fill_emp($connect);?>
                        </select>
                        </td>
                      <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>
                      <th width="5%">Sr</th>
                      
                      <th width="25%">Select Type</th>
                      <th width="25%">Item Name</th>
                      <th width="10%">Qty</th>
                      <th width="15%">Rate</th>
                      <th width="20%">Amount</th>
                      
                    </tr>
                   
                    
                    <?php
                    $statement = $connect->prepare("
                      SELECT t.type_name,i.item_name,i.type_id,d.item_no,d.ctn,d.qty,d.rate,
                      
                      d.qty*d.rate amount,d.cost
                      from sr_detail d, items i,item_type t where t.type_id=i.type_id and i.item_id=d.item_no and d.sr_id = :sr_id
                    ");
                    $statement->execute(
                      array(
                        ':sr_id'       =>  $sr_id
                      )
                    );
                    $item_result = $statement->fetchAll();
                    $m = 0;
                    $gross_amount = 0;
                    foreach($item_result as $sub_row)
                    {
                      $item_amount = $sub_row['amount'];
                      $m = $m + 1;
                      $gross_amount = $gross_amount + $item_amount;
                    ?>
                   <tr id="row_id_<?php echo $m; ?>">
                      <td><span id="sr_no"><?php echo $m; ?></span></td>
                      <td><input type="hidden" name="item_no[]" id="item_no<?php echo $m; ?>" class="form-control input-sm number_only item_no" value="<?php echo $sub_row["item_no"]; ?>" /><select name="type_id[]" id="type_id<?php echo $m; ?>" data-srno="<?php echo $m;?>" class="form-control type_id" required />
                      <option value="<?php echo $sub_row["type_id"]; ?>"><?php echo $sub_row["type_name"]; ?></option>
                          <?php echo fill_itemtype($connect);?>
                        </select></td>
                     <td><select name="item_name[]" id="item_name<?php echo $m; ?>" data-srno="<?php echo $m;?>" class="form-control item_name" required />
                      <option value="<?php echo $sub_row["item_name"]; ?>"><?php echo $sub_row["item_name"]; ?></option>
                          
                        </select></td>
                        
                      <td><input type="text" name="qty[]" id="qty<?php echo $m; ?>" class="form-control input-sm number_only qty" value="<?php echo $sub_row["qty"]; ?>" /></td>
                      <td><input type="text" name="rate[]" id="rate<?php echo $m; ?>" class="form-control input-sm number_only rate" value="<?php echo $sub_row["rate"]; ?>"/></td>
                      <td><input type="text" name="amount[]" id="amount<?php echo $m; ?>"  class="form-control input-sm amount" value="<?php echo $sub_row["amount"]; ?>"readonly /></td>                      
                      
                      <td><button type="button" name="remove_row[]" id="<?php echo $m; ?>" class="btn btn-danger btn-xs remove_row form-control">X</button> </td>
                      
                      
                     </td>
                    
                    </tr>
                    <?php
                   
                    }
                    ?>
                  
                  </table>
                   <div align="right">
                    <button type="button" name="add_row" id="add_row" class="form-control btn btn-success btn-xs">Add More Item</button>
                  </div>
                   <div align="left">
                      
                  
                    <span id="item_detail"></span>
                   
                  </div>
                 
                </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%"align="right"><b>GST :<span id="gst_pr"></span> (%) :</td>
                <td width="80%" align="right"><b><input type="text" name="gst_amount" id="gst_amount" class="form-control gst_amount"  value="<?php echo $grosss_amount;?>" style="text-align:right" readonly></b></td>
              </tr>
               
             
              
               <tr>
                <td width="80%"><input type="text" name="discount_dsc" id="discount_dsc" class="form-control discount_dsc" placeholder="Less Detail :"></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" placeholder="Add Detail :"></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="<?php echo $m; ?>" />
                 
                        <input type="hidden" name="gst_pr" class="gst_pr" />
                        <input type="hidden" name="loaded" class="loaded" />
                        <input type="hidden" name="sr_id" class="sr_id" id="sr_id" value="<?php echo $sr_id;?>" />
                        <input type="hidden" name="btn_action" class="btn_action" id="btn_action" />
                  <input type="submit" name="btn_save" id="btn_save" class="form-control btn btn-primary " value="Update" />
                  
                </td>
                <tr>
                
              </tr>
              </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>
  
<datalist id="datalist1">
  
</datalist>
</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;
   document.getElementById("emp_id").selectedIndex = 1;
  </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
    });
  })
  
   
  </script>
     
      <script>
      $(document).ready(function(){
       var total_amount = $('#total_amount').text();
        var count = "<?php echo $m;?>";
         var loaded = $('.loaded').val();
        if(loaded==1)
        {
          cal_final_total(count);
          loaded = 0;
          $('.loaded').val(loaded);
        }
        var first_row = $('#first_row').val();
        if(first_row ==0)
        {
         var html_code = '';
          html_code += '<tr id="row_id_'+count+'">';         
          html_code += '<td><span id="sr_no">'+count+'</span></td>';
           
          html_code += '<td><input type="hidden" name="item_no[]" id="item_no'+count+'" data-srno="'+count+'" class="form-control input-sm item_no" required><select name="type_id[]" id="type_id'+count+'" data-srno="'+count+'" class="form-control input-sm type_id select2" required><?php echo fill_itemtype($connect);?></select></td>';
         html_code += '<td><input type="text" name="item_name[]" id="item_name'+count+'" data-srno="'+count+'" class="form-control input-sm number_only item_name" list="datalist1" required></td>';
         
          html_code += '<td><input type="text" name="qty[]" id="qty'+count+'" data-srno="'+count+'" class="form-control input-sm number_only qty" required></td>';
          html_code += '<td><input type="text" name="rate[]" id="rate'+count+'" data-srno="'+count+'" class="form-control input-sm number_only rate" required></td>';
          html_code += '<td><input type="text" name="amount[]" id="amount'+count+'" data-srno="'+count+'" readonly class="form-control input-sm amount" />';
          
          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>';
          $('#invoice-item-table').append(html_code);
          $('.select2').select2();         
          $('#total_item').val(count);
          $('#type_id'+count).focus();
          first_row++;
          $('#first_row').val(first_row);  
           $('#contact').focus();
           //$('#item_name'+count).editableSelect();
          }
        $(document).on('click', '#add_row', function(){
          count++;
           $('#item_detail').html('');
           $('#item_info').html('');
          $('#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><input type="hidden" name="item_no[]" id="item_no'+count+'" data-srno="'+count+'" class="form-control input-sm item_no" required><select name="type_id[]" id="type_id'+count+'" data-srno="'+count+'" class="form-control input-sm type_id select2" required><?php echo fill_itemtype($connect);?></select></td>';
         html_code += '<td><input type="text" name="item_name[]" id="item_name'+count+'" data-srno="'+count+'" class="form-control input-sm number_only item_name" list="datalist1" required></td>';
          html_code += '<td><input type="text" name="qty[]" id="qty'+count+'" data-srno="'+count+'" class="form-control input-sm number_only qty" required></td>';
          html_code += '<td><input type="text" name="rate[]" id="rate'+count+'" data-srno="'+count+'" class="form-control input-sm number_only rate" required></td>';
          html_code += '<td><input type="text" name="amount[]" id="amount'+count+'" data-srno="'+count+'" readonly class="form-control input-sm amount" />';
          
          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>';
          $('#invoice-item-table').append(html_code);      
          
          $('.select2').select2(); 
          $('#type_id'+count).focus();        
          
        });       
        
      $(document).on('click', '.remove_row', function(){
            var row_id = $(this).attr("id");
           
            $('#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'+count).val('');
                $('#datalist1').html(data);
                
               //$('#item_name'+count).editableSelect();
              }
           
         })
      });
       
       $(document).on('blur', '.gst', function(){
          var gst = $('#gst').val();
          var gst_pr = 0;
           $('#gst_pr').text(gst_pr);
            $('.gst_pr').val(gst_pr);
          cal_final_total(count);
          if(gst =='ON')
          {
         
          $.ajax({
                url:"gst_data.php",
                method:"POST",
                data:{gst:gst},
                dataType:"json",
                success:function(data){
                     $('#gst_pr').text(data.gst_value);
                     $('.gst_pr').val(data.gst_value);
                     cal_final_total(count);
                     
                }
           });
         }
        });  
      
         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 = $('.gst_pr').val();
          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) + parseFloat(gst_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', '.qty', function(){
  
    var item_no = $('#item_no'+count).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'+count).val();
          var item_name = $('#item_name'+count).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'+count).val(data.item_id);      
                    }else{$('#item_no'+count).val(0);$('#item_info').text('New Item Will Be add');}
                  
                  }
                
                })
          
        }); 
        $(document).on('blur', '.rate', function(){
         var item_id = $('#item_no'+count).val(); 
         if(item_id ==0)
                    {
                      if(confirm("Are you sure you want to add this item?"))
                      {
                        
                        var btn_action = 'add';
                        var type_id = $('#type_id'+count).val();
                        var item_name = $('#item_name'+count).val();
                        $.ajax({
                          url:"create_item.php",
                          method:"POST",
                          data:{type_id:type_id, item_name:item_name, btn_action:btn_action},
                          dataType:"json",
                          success:function(data)
                          {
                            $('#item_no'+count).val(data.item_id);
                            alert('Item Added');
                           
                           
                          }
                        })
                      }
                      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('update');
            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.location = "csr";
              }
            })
          });
        $(document).on('blur', '.amount', function(){
          $('#add_row').focus();
        });
         $(document).on('blur', '.cust_name', function(){
         var elmnt = document.getElementById("type_id"+count);
          elmnt.scrollIntoView();
          $('#type_id'+count).focus();
        });
          $(document).on('blur', '.contact', function(){
          $('#cust_name').focus();
        });
       
        //$("#item_type"+count).change(function(){
        //var itemtype = $(".item_type option:selected").val();
       
      
        $(document).on('blur', '.rate', 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
      }
      
}
      ?>
     