<?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'];
    $user_acc_no = $_SESSION['user_acc_no'];
}else{
  header('Location: login');
  die();
}
 
$dated = date('Y-m-d');  

if(isset($_POST["save"]))
  {
     $new_dated = $_POST['dated'];
             if($user_type=='user')
             {
            $sql = "select app_value from app_options where app_name='datedown' and user_id = '".$user_id."'";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $datedown = $statement->fetchColumn();
            $sql = "select app_value from app_options where app_name='dateup' and user_id = '".$user_id."'";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $dateup = $statement->fetchColumn();
             $sql = "SELECT date_sub(curdate(),interval '".$datedown."' day)";
              $statement = $connect->prepare($sql);
              $statement->execute(); // no need to add `$sql` here, you can take that out
              $pre_dated = $statement->fetchColumn();
    if($new_dated < $pre_dated){echo 'Invoice Can not be save in Previous date pre_dated is : '.$pre_dated .' Post Date : '.$new_dated ;return false;}
     $above_dated = Date('Y-m-d', strtotime("+".$dateup .' days'));
    if($new_dated > $above_dated){echo 'Invoice Can not be save in Above date Above dated is :'.$above_dated .' New Date is '. $new_dated;return false;}
        }
    $due_day = $_POST['due_day'];
   
    $due_date =Date('Y-m-d', strtotime("+".$due_day." days"));
   if($_POST['due_day']==0){$due_date=$new_dated;}
   if($_POST['due_day']==''){$due_date=$new_dated;}
    
    $statement = $connect->prepare("
     INSERT INTO purchase
        (po_no,branch_id,inv_no,dated,due_date,v_id,sv_id,description,discount,discount_dsc,inv_amt,due_day,freight,freight_dsc,gst,gst_pr,user_id,status)
        VALUES (:po_no, :branch_id, :inv_no, :dated, :due_date, :v_id, :sv_id, :description, :discount, :discount_dsc, :inv_amt, :due_day, :freight, :freight_dsc, :gst, :gst_pr, :user_id, :status)
    ");
    $statement->execute(
      array(
         ':po_no'             =>  0,
          ':branch_id'             =>  1,
          ':inv_no'             =>  trim($_POST["inv_no"]),
          ':dated'             =>  $_POST["dated"],
       ':due_date'             =>  $due_date,
          ':v_id'          =>  trim($_POST["v_id"]),
          ':sv_id'          =>  0,
          ':description'       =>  $_POST["description"],
          ':discount'       =>  trim($_POST["discount"]),
          ':discount_dsc'       =>  trim($_POST["discount_dsc"]),
          ':inv_amt'       =>  0,
          ':due_day'       =>  $_POST["due_day"],          
          ':freight'       =>  trim($_POST["freight"]),
          ':freight_dsc'       =>  trim($_POST["freight_dsc"]),
          ':gst'       =>  'OFF',
          ':gst_pr'       =>  0,
          ':user_id'       =>  $user_id,          
          ':status'       =>  'Active'
          
      )
    );
      
        $statement = $connect->query("SELECT LAST_INSERT_ID()");
         $p_id = $statement->fetchColumn();
          $sql = "delete from p_detail";
          $statement = $connect->prepare($sql);
          $statement->execute();
      for($count=0; $count<$_POST["total_item"]; $count++)
      {
        $statement = $connect->prepare("
          INSERT INTO purchase_detail
          (p_id,item_no,store_id,ctn,qty,rate,ln_no)
          VALUES(:p_id, :item_no, :store_id, :ctn, :qty, :rate, :ln_no)
        ");
        $statement->execute(
          array(
            ':p_id'               =>  $p_id,            
            ':item_no'              =>  trim($_POST["item_no"][$count]),
            ':store_id'              =>  1,            
            ':ctn'          =>  trim($_POST["ctn"][$count]),
            ':qty'          =>  trim($_POST["qty"][$count]),
            ':rate'           =>  trim($_POST["rate"][$count]),
            
            ':ln_no'        => $count
        
          )
        );
      }    
        $sql ="
          select sum(qty*rate) from purchase_detail where p_id = '".$p_id."'
          
          ";
        $statement = $connect->prepare($sql);
        $statement->execute();
        $inv_amt = $statement->fetchColumn();     
      $sql = "update purchase set inv_amt = '".$inv_amt."' where p_id = '".$p_id."'";
          $statement = $connect->prepare($sql);
          $statement->execute();
          $sql = "select inv_amt from purchase where p_id = '".$p_id."'";
          $statement = $connect->prepare($sql);
          $statement->execute();
          $inv_amt = $statement->fetchColumn();
          $sql = "select discount from purchase where p_id = '".$p_id."'";
          $statement = $connect->prepare($sql);
          $statement->execute();
          $discount = $statement->fetchColumn();

           //create jv
         
         
          $due_day = $_POST["due_day"];
          $ref_id = $p_id;
         
            $sql = "SELECT IFNULL(max(jv_no),0) FROM jv WHERE branch_id = '".$branch_id."'";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $jv_no = $statement->fetchColumn();
            $jv_no++; 
         
          
         
            $inv_no = $_POST["inv_no"];
          
      
        $sql = "SELECT sum(qty*rate) FROM purchase_detail WHERE p_id = '".$p_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $purchase = $statement->fetchColumn();
             
             
             $sql = "SELECT gst_pr FROM purchase WHERE p_id = '".$p_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $gst_pr = $statement->fetchColumn();
             $sql = "SELECT freight FROM purchase WHERE p_id = '".$p_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $freight = $statement->fetchColumn();
           
           if($gst_pr > 0)
           {
           $gst_amount = $purchase * $gst_pr / 100;
         }else {$gst_amount = 0;}
            
           
            $sql = "SELECT discount FROM purchase WHERE p_id = '".$p_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $discount = $statement->fetchColumn();
            
            if($discount > 0)
            {
              $purchase = $purchase - $discount;
            }
            $sql = "SELECT MAX(jv_no) FROM jv WHERE branch_id = '".$branch_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $jv_no = $statement->fetchColumn();
            settype($jv_no, "integer");
            $jv_no++;
       
            
            $v_id = $_POST['v_id'];
           // $sv_id = $_POST['sv_id'];
            
            
            
           
              $purchase_account = $v_id;
           
            $source = 'AP Inv';
            $description = 'AP Credit Invoice ' .$p_id .', ' .$inv_no .', ' .$_POST['description'] ;
            $due_day = $_POST['due_day'];
          
            
            $statement = $connect->prepare("
              INSERT INTO jv 
                (jv_no,branch_id,dated,source,ref_id,description,user_id)
                VALUES (:jv_no, :branch_id, :dated, :source, :ref_id, :description, :user_id)
    ");
    $statement->execute(
      array(
          ':jv_no'             =>  $jv_no,
          ':branch_id'             =>  $branch_id,
          ':dated'             =>  $_POST['dated'],
          ':source'          =>  $source,
          ':ref_id'          =>  $p_id,
          ':description'       =>  $description,
       
          ':user_id'       =>  $user_id
      )
    );
     $statement = $connect->query("select max(jv_id) from jv");
      $jv_id = $statement->fetchColumn();
      
        $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,debit,credit)
          VALUES(:jv_id, :acc_no, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  1031001,
            ':debit'          =>  $purchase,
            ':credit'           =>  0
            
          )
        );
        
        
          $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,debit,credit)
          VALUES(:jv_id, :acc_no, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  2012002,
            ':debit'          =>  $gst_amount,
            ':credit'           =>  0
                        
          )
        );
        
        
        $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,debit,credit)
          VALUES(:jv_id, :acc_no, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  2012003,
            ':debit'          =>  $freight,
            ':credit'           =>  0
                        
          )
        );
         $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,debit,credit)
          VALUES(:jv_id, :acc_no, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  $user_acc_no,
            ':debit'          =>  0,
            ':credit'           =>  $freight
                        
          )
        );
        $payable = $purchase + $gst_amount;
        $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,debit,credit)
          VALUES(:jv_id, :acc_no, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  $purchase_account,
            ':debit'          =>  0,
            ':credit'           =>  $payable
                     
          )
        );
        
        /////End Jv/////
     
           stock_update($connect);          
         
          $freight =  trim($_POST["freight"]);
          $gst = trim($_POST["gst"]);             
          
          $tot_exp = $freight ;
         if($tot_exp > 0)
          {
           $cost_up = $tot_exp / $inv_amt; 
          }
         
          $cost_down = 0;
          $cost_up = 0;
         
          if($discount > 0)
          {
            
            $cost_down = $discount / $inv_amt;
            $cost_up = $cost_up - $cost_down;
          }
          $sql = "update purchase_detail set cost_up = '".$cost_up."' where p_id = '".$p_id."'";
          $statement = $connect->prepare($sql);
          $statement->execute();
        
         
          $sql = "update purchase_detail set cost_rate = rate * cost_up where p_id = '".$p_id."'";
          $statement = $connect->prepare($sql);
          $statement->execute();
         
          $sql = "update purchase_detail set adj_cost = rate + cost_rate where p_id = '".$p_id."'";
          $statement = $connect->prepare($sql);
          $statement->execute();
          $sql = "update purchase_detail d, items i set d.pre_cost = i.item_cost,
          d.pre_stock=i.stock-d.qty where i.item_id=d.item_no and d.p_id = '".$p_id."'";
          $statement = $connect->prepare($sql);
          $statement->execute();
           $sql = "update purchase_detail set pre_stock = 0
          where pre_stock < 0 and p_id = '".$p_id."'";
          $statement = $connect->prepare($sql);
          $statement->execute();
          $sql = "update purchase_detail set pre_stock = 0
          where pre_cost = 0 and p_id = '".$p_id."'";
          $statement = $connect->prepare($sql);
          $statement->execute();
            $sql = "update purchase_detail set pre_amount = pre_cost*pre_stock,
            cur_amount = qty*adj_cost where p_id = '".$p_id."'";
          $statement = $connect->prepare($sql);
          $statement->execute();
           $sql = "update purchase_detail set total_amount = pre_amount+cur_amount,
            total_stock = qty+pre_stock where p_id = '".$p_id."'";
            
          $statement = $connect->prepare($sql);
          $statement->execute();
           $sql = "update purchase_detail set item_cost = total_amount / total_stock
             where p_id = '".$p_id."'";
            
          $statement = $connect->prepare($sql);
          $statement->execute();
         
          $sql = "update items i,purchase_detail d set i.item_cost =
         d.adj_cost where d.p_id = '".$p_id."' and d.item_no=i.item_id";
          $statement = $connect->prepare($sql);
          $statement->execute();

          if($_POST['lprate'] == 'ON')
          {
            $sql = "update items i,purchase_detail d set i.lp_rate =
         d.rate where d.p_id = '".$p_id."' and d.item_no=i.item_id";
          $statement = $connect->prepare($sql);
          $statement->execute();
          }

            
       
         
        header('Location: purchase');
    
  }        
  
  
  ?>
<!DOCTYPE html>
<html>
<head>
  <title><?php  if(basename(__FILE__, '.php'=='purchase_new.php')){echo 'New Purchase';}?></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="#">Payables</a></li>
              <li class="breadcrumb-item"><a href="purchase">Purchase Invoices</a></li>
              <li class="breadcrumb-item active">New Purchase 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["add"]))
      {
      ?>
       <script>
        $(document).ready(function(){
          
          $('#due_day').val(0);
          
         });
        </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">New Purchase Invoice</h2></td>
            </tr>
            <tr>
                <td colspan="2">
                  <div class="row">
                    <div class="col-md-8">
                      
                        <select name="v_id" id="v_id" class="form-control input-sm v_id select2" data-show-subtext="true" data-live-search="true" 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-4">
                      
                     <table>
                      <tr><td>
                     <select name="lprate" id="lprate" class="form-control lprate" required />
                    
                      
                      <option value="ON">LP ON</option>
                      <option value="OFF">LP OFF</option>
                      </select>
                      </td><td>
                    
                   
                      <input type="text" name="inv_no" id="inv_no" class="form-control input-sm" placeholder="Invoice No." /></td></tr>
                      <tr><td>
                      <input type="text" name="due_day" id="due_day" class="form-control input-sm" placeholder="Due Days" AutoComplete="off" /></td>
                      
                      
                      <td><input type="text" name="dated" id="dated" class="form-control input-sm" readonly placeholder="Select Date" AutoComplete="off" value="<?php echo $dated;?>" /></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"></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%"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" 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" 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="btn_action" id="btn_action" />
                  <input type="hidden" name="gst_pr" class="gst_pr" />
                  <input type="submit" name="save" id="btn_save" class="form-control btn btn-primary" value="Save" />
                  
                </td>
              </tr>
          </table>
        </div>
      </form>
      </div>
             
        
        
      </div><!-- /.container-fluid -->
    </section>
    <!-- /.content -->
 
  <!-- /.content-wrapper -->
 
    </div>
    </div>
  <?php include('include/script.php'); ?>
  
 
  <script src="js/jquery-ui.js"></script>
  <script src="js/jquery-ui.min.js"></script>
  
<datalist id="datalist1">
  
</datalist>
</body>
</html>

<script>

$(document).ready(function () {

    $('#data_form').submit(function(){

      if(confirm('Are You Sure You Want Save'))
      {
        return true;
      }else {return false;}

    })
});

 
  $(document).ready(function(){
    $(window).keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
  });
    
  
  $('.select2').select2();
    
  </script>
</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 count = 0;
        var loaded = $('#loaded').val();
      if(loaded==0){$('#v_id').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");
         
          $('#row_id_'+row_id).remove();
           cal_final_total(count);
          count--;
          $('#total_item').val(count);
        });
       
       $(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);
                     
                }
           });
         }
        });
        $(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);      
                    }else{$('#item_no').val(0);$('#item_info').text('New Item Will Be add');}
                  
                  }
                
                })
          
        }); 
       $(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);
                
               //$('#item_name'+count).editableSelect();
              }
           
         })
      });
       $(document).on('blur', '.item_qty', function(){
                var item_no = $('#item_no').val();
                var v_id = $('#v_id').val();
               
                
                $.ajax({
                  url:"purchase_history.php",
                  method:"POST",
                  data:{item_no:item_no, v_id:v_id},
                  dataType:"json",
                  success:function(data)
                  {   
                     if(item_no > 0)
                    {
                   // $('#rate'+count).val(data.rate);
                    
                    $('#item_detail').html(data.item_detail);
                    }
                    
                    
                  }
                })
             });
        
        
    
       $(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 = $('#item_rate').val();
                        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('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);
                
               //$('#item_name'+count).editableSelect();
              }
           
         })
      });
        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', '.description', function(){
          
          $('#inv_no').focus();
        });
      
        $(document).on('blur', '.v_id', function(){
          $('#type_id').focus();
        });
      
        
       
        $(document).on('blur', '.discount', function(){
          cal_final_total(count);
        });
        $(document).on('blur', '.freight', function(){
           cal_final_total(count);
        });
         $(document).on('click', '#save', function(){
             cal_final_total(count);
         });
       
       
      });
      </script>
      <?php
      }
      
      ?>     