<?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');

  $sql="select max(s_id) from sale";
  $statement = $connect->query($sql);
  $inv_no = $statement->fetchColumn();
  $inv_no++;
  
  ?>
<!DOCTYPE html>
<html>
<head>
  <title><?php  if(basename(__FILE__, '.php'=='wsale_new.php')){echo 'Credit Invoice';}?></title>
  <?php include('include/head.php'); ?>
  <style>
    #net_profit {
      font-size: 20px;
      color:green;
    }
    .lp_rate {
      color:red;
    }
  </style>
</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 Credit Sale (<?php echo $inv_no;?>)</h2></td>
            </tr>
        
            <tr>
                <td colspan="2">
                  <div class="row">
                    <div class="col-md-6">
                      <br />
                        <select name="cust_id" id="cust_id" class="form-control select2" required />
                           <?php echo fill_party($connect);?>
                        </select>
                        <br />
                     <br />
                        
                        <input type="text" name="description" id="description" class="form-control description" placeholder="Enter Description"  />
                        <br />
                         
                       
                    </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>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>
                      </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 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>   
               <table width="100%" id="invoice-item-table" class="table table-bordered">
                   <tr>        
       
           
          <td width="40%"><input type="hidden" name="item_id" id="item_id" class="form-control input-sm item_id" ><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_cost" id="item_cost"  class="form-control input-sm number_only item_cost" step="any" placeholder="Cost"></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>
                     <span id="item_type_history"></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%"><input type="text" name="discount_dsc" id="discount_dsc" class="form-control discount_dsc" placeholder="Less Detail :"></td>
                <td width="20%" 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="20%" 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 :</b></td>
                <td width="20%" align="right"><b><span id="net_total"></span></b></td>
              </tr>
              <?php if($user_type=='admin')
              {
                echo 
                '
                <tr class="lp_rate">
                <td width="80%"align="right" ><b>Total LP :</b></td>
                <td width="20%" align="right"><b><span id="total_cost_amount"></span></b></td>
              </tr>
                <tr>
                <td width="80%"align="right"><b>Net Profit :</b></td>
                <td width="20%" align="right"><b><span id="net_profit"></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="sale_target" id="sale_target"class="form-control"  />
                        <input type="hidden" name="cr_limit" id="cr_limit" class="form-control"  />
                        <input type="hidden" name="cur_balance" id="cur_balance" class="form-control"   />
                        <input type="hidden" name="over_dues" id="over_dues" class="form-control" />
                    <input type="hidden" name="gst_pr" class="gst_pr" /> 
                    <input type="hidden" name="loaded" id="loaded" value="0" />
                    <input type="hidden" name="btn_action" id="btn_action" class="btn_action" /> 
                    <input type="hidden" name="first_row" id="first_row" class="first_row" value="0" /> 
                    <input type="hidden" name="cust_name" id="cust_name" /> 
                   
                  
                   <table>
                    <tr>   
                  <table>
                    <tr>   
                  <td><input type="submit" name="save" id="btn_save" class="form-control btn btn-primary" value="Save" /></td>
                 
                </tr>
              </table>
                </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'); ?>
</body>
</html>
<div id="dataModal" class="modal fade">
          <div class="modal-dialog">
            <form method="post" id="data_form">
              <div class="modal-content">
              <div class="modal-header">
                
            <h4 class="modal-title"><i class="fa fa-plus"></i> Enter Cost</h4>
              </div>
              <div class="modal-body">           
            
            <div class="form-group">
              <label>Must Enter Item Cost For New Item</label>
              <input type="text" name="item_cost" id="item_cost" class="form-control" />
            </div>
            
           
              </div>
              <div class="modal-footer">
                <input type="hidden" name="item_id" id="item_id" />
                <input type="hidden" name="btn_action" id="btn_action" />
                
                <input type="submit" name="action" id="action" class="form-control btn btn-info" value="Add" />
                
              </div>
            </div>
            </form>
          </div>
        </div>
<script>
  
   document.getElementById("title_id").selectedIndex = 1;
   document.getElementById("emp_id").selectedIndex = 1;
    var f1 = flatpickr(document.getElementById('dated'));
   
  </script>
 <script>
 $(document).ready(function(){
    $('.select2').select2();
    $(window).keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
  });
  })
   
  </script>
     
    
      <script>
      $(document).ready(function(){
        
      
       var total_amount = $('#total_amount').text();
         var loaded = $('#loaded').val();
       if(loaded==0){$('#cust_id').focus();loaded=1;$('#loaded').val(1);}
        var count = 0; 
        var tot_item_cost = 0;      
        var net_profit = 0;
       $(document).on('click', '#add_row', function(){

          var item_no = $('#item_id').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);
           var cost = $('#item_cost').val();
           var cost_amount = parseFloat(qty) * parseFloat(cost);
           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><input type="hidden" name="cost[]" id="cost'+count+'" data-srno="'+count+'" class="form-control input-sm number_only cost" step="any" value="'+cost+'" readOnly><input type="hidden" name="cost_amount[]" id="cost_amount'+count+'" data-srno="'+count+'" class="form-control input-sm number_only cost_amount" step="any" value="'+cost_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('');
           $('#item_id').val(null);
           $('#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();

            var item_no = $('#item_id').val();
            var cust_id = $('#cust_id').val();
            var type_id = x;
            $.ajax({
              url:"find_item.php",
              method:"POST",
              data:{type_id:x},
              dataType:"text",
              success:function(data)
              {
                
                $('#item_name').val('');
                $('#datalist1').html(data);
                
              
              }
           
         })
                  $.ajax({
            url:"item_type_history.php",
            method:"POST",
            data:{type_id:type_id, cust_id:cust_id},
            dataType:"json",
            success:function(data)
            {   
               if(x > 0)
              {
             // $('#rate'+count).val(data.rate);
              
              $('#item_type_history').html(data.item_type_history);
                $('#item_detail').html(null);
              }
              
              
            }
          })
      });
       
       
         function cal_final_total(count)
        {
         var final_item_amount = 0;
         var  final_dis_amount = 0;
         var final_cost_amount = 0;
          for(j=1; j<=count; j++)
          {
            var qty = 0;
            var rate = 0;
            var cost = 0;
            var amount = 0;
            var cost_amount = 0;
           
           
            var total_amount = 0;
           
           
            qty = $('#qty'+j).val();
            if(qty > 0)
            {
              rate = $('#rate'+j).val();
              cost = $('#cost'+j).val();
              
              if(rate > 0)
              {
                amount = parseFloat(qty) * parseFloat(rate);
                cost_amount = parseFloat(qty) * parseFloat(cost);
                $('#amount'+j).val(amount);
                $('#cost_amount'+j).val(cost_amount);             
                
           
                final_item_amount = parseFloat(final_item_amount) + parseFloat(amount);     
                final_cost_amount = parseFloat(final_cost_amount) + parseFloat(cost_amount);
               
              
              }
            }
          }
          var new_final_item_amount = Number(final_item_amount).toFixed(2);
          var new_final_cost_amount = Number(final_cost_amount).toFixed(2);
          $('#total_amount').text(new_final_item_amount);
          $('#total_cost_amount').text(new_final_cost_amount);
          
          
          var net_total = 0;
          var gst_amount= 0;
         gst_pr = 0;
          net_total = parseFloat(final_item_amount) ;
        
         
          //$('#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);  
          var net_profit = parseFloat(final_item_amount) - parseFloat(final_cost_amount);
          $('#net_profit').text(net_profit);
        //    $('#gst_amount').val(new_gst_amount);            
          
          
        }        
        
 $(document).on('blur', '.item_qty', function(){
  
    var item_no = $('#item_id').val();
    var cust_id = $('#cust_id').val();
   
    
    $.ajax({
      url:"item_history.php",
      method:"POST",
      data:{item_no:item_no, cust_id:cust_id},
      dataType:"json",
      success:function(data)
      {   
         if(item_no > 0)
        {
        $('#item_type_history').html(null);
        
        $('#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_id').val(data.item_id);
                      $('#item_cost').val(data.item_cost);     
                    }else{$('#item_id').val(0);$('#item_info').text('New Item Will Be add');}
                  
                  }
                
                })
          
        }); 
        $(document).on('blur', '.item_rate', function(){
         var item_id = $('#item_id').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');
                           
                           
                          }
                        })
                      }
                      else
                      {
                        return false;
                      }
                    }
                  
          
        }); 
     
         $(document).on('blur', '.description', function(){
        // var elmnt = document.getElementById("type_id"+count);
          //elmnt.scrollIntoView();
          $('#type_id').focus();
        });
        
          $(document).on('submit', '#data_form',function(event){
            event.preventDefault();
              cal_final_total(count);
              var net_total = $('#net_total').text();
              if(net_total < 1)
                {alert('Invoice Not Acceptable');
                return false;
                }
            $('#btn_save').val('Wait...');
            $('#btn_save').attr('disabled','disabled');
            $('#btn_action').val('save');
            var _data = $(this).serialize();
            $.ajax({
              url:"sales_action.php",
              method:"POST",
              data:_data,
              success:function(data)
              {
               $('#alert_action').fadeIn().html('<div class="alert alert-success">'+data+'</div>');
              window.open("sale_invoice_a5?print=1&id=0","_blank");
            window.location = "sales";
              }
            })
          });
          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:"sales_action.php",
              method:"POST",
              data:_data,
              success:function(data)
              {
               $('#alert_action').fadeIn().html('<div class="alert alert-success">'+data+'</div>');
               window.open("sale_invoice_a5?print=1&id=0","_blank");
                window.location = "sales";
              }
            })
          }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:"sales_action.php",
              method:"POST",
              data:_data,
              success:function(data)
              {
               $('#alert_action').fadeIn().html('<div class="alert alert-success">'+data+'</div>');
               window.open("sale_invoice_a5?print=1&id=0","_blank");
                window.location = "wsale_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', '.qty', 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
      }
      
      ?>