<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.0/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.0/jquery-confirm.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"></script>
<div class="middleSec catbyMdl">

  <div class="headingD">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <i class="fa fa-user" aria-hidden="true"></i> Bill Genarate
            <a href="<?php echo base_url(); ?>billing/" class="btn btn-warning pull-right">Back</a>
        </div>
  <div class="clearfix"></div>
  </div>

        

  <div class="showPageSec chartPagHgtD catby">

    <div class="container-fluid">

          <div class="row">
                

            <form role="form" method="post" id="rateForm">
                


                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 padleftright0">
                  <div class="nameTblD">
                    <h4>Bill Details</h4>
                    <table class="table">
                      <tr>
                        <td><input type="text" class="form-control" name="bill_no" required placeholder="Enter Bill No. *"></td>
                        <td><input type="text" class="form-control" name="cus_name" required placeholder="Customer Name *"></td>
                        <td><input type="email" class="form-control" name="cus_email" placeholder="Email ID"></td>
                        <td><input type="text" class="form-control" name="cus_phone" required placeholder="Mobile No. *"></td>
                      </tr>
                      <tr>
                        <td><input type="text" class="form-control" name="delivery_mode" required placeholder="Mode of Payment *"></td>
                        <td><input type="text" class="form-control" name="supply_reff" placeholder="Supply Ref."></td>
                        <td><input type="text" class="form-control" name="oth_reff" placeholder="Other Refferance(s)"></td>
                        <td><select class="form-control valid" name="tax_type" required="" aria-required="true" aria-invalid="false">
                                <option value="">Select Tax Mode</option>
                                <option value="With GST">With GST</option>
                                <option value="Without GST">Without GST</option>
                            </select>
                        </td>
                      </tr>
                      <tr>
                        <td><input type="text" class="form-control" name="gst" placeholder="GST Number"></td>
                        <td ><input type="text" class="form-control" required name="state" placeholder="State Name *"></td>
                        <td><input type="text" class="form-control" name="city" required placeholder="City *"></td>
                        <td><input type="text" class="form-control" name="pin" required placeholder="Pin *"></td>
                      </tr>
                      <tr>
                        <td colspan="4"><textarea class="form-control" name="cus_address" required placeholder="Full Address *"></textarea></td>
                      </tr>
                      <tr>
                        <td><input type="text" class="form-control" name="dispath_documence" placeholder="Despatch Document No"></td>
                        <td><input type="text" class="form-control" name="document_through" placeholder="Despatched through"></td>
                        <td colspan="2"><input type="text" class="form-control" name="delivery_note" placeholder="Delivery Note"></td>
                      </tr>
                    </table>
                  </div>
                </div>
                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                    <div class="invoiceNewTableD">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Sl No.</th>
                                    <th>Product Code</th>
                                    <th>Item Name</th>
                                    <th>Description</th>
                                    <th>Qty.</th>
                                    <th>Price</th>
                                    <th>Total</th>
                                    <th>Action</th>
                                </tr>
                            </thead>

                            <tbody id="Content">
                                <tr  class="tr_input">
                                    <td width="8%"><input type="number" class="form-control" name="slno[]" value="1" id="slno_1"></td>
                                    <td width="15%"><input type="text" class="form-control product_code" name="hsn[]" id="hsn_1" ><input type="hidden" class="form-control" name="inv_id[]" id="inv_1"></td>
                                    <td width="15%"><input type="text" class="form-control autocomplete" name="itemName[]" id="autocomplete_1"></td>
                                    <input type="hidden" name="mrp[]" id="mrp_1">
                                    <td width="20%"><input type="text" class="form-control" name="des[]" id="des_1"></td>
                                    <td width="8%"><input type="number" min="1" max="10" class="form-control changesNo" name="qty[]" id="qty_1"></td>
                                    <td width="10%"><input type="number" class="form-control changesNo" name="price[]" id="price_1"></td>
                                    <td width="15%"><input type="number" class="form-control totalLinePrice" name="amount[]" id="amount_1" readonly></td>
                                    <td width="9%"><button type="button" class="btn btn-primary" id="Add"><i class="fa fa-plus" aria-hidden="true"></i> Add Lines</button></td>
                                </tr>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="6" align="right"> <strong>Subtotal</strong></td>
                                    <td align="right"><input type="text" name="subtotal" id="subTotal" class="form-control" value="<?php echo $total.'.00'; ?>"></td>
                                    <td><button type="submit" class="btn btn-success" id="SaveButton" style="display: none;">Save Bill</button></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
                
            </form>


      </div>
    </div>
  </div>
</div>



<?php  

include "layout/footer.php";

?>
    <!-- Script -->
    <script type='text/javascript' >
    $( function() {
      $(document).on('keydown', '.autocomplete', function() {
        var id = this.id;
        var splitid = id.split('_');
        var index = splitid[1];
          $( '#'+id ).autocomplete({
            source: function( request, response ) {
                
                $.ajax({
                    url: "<?php echo base_url(); ?>billing/getData/",
                    type: 'post',
                    dataType: "json",
                    data: {
                        search: request.term
                    },
                    success: function( data ) {
                        response( data );
                    }
                });
            },
            select: function (event, ui) {
                $('#autocomplete_'+index).val(ui.item.label); // display the selected text
                $('#hsn_'+index).val(ui.item.item_code); // save selected id to input
                $('#inv_'+index).val(ui.item.inv_id); // save selected id to input
                $('#des_'+index).val(ui.item.item_desc); // save selected id to input
                $('#mrp_'+index).val(ui.item.mrp); // save selected id to input
                $('#price_'+index).val(ui.item.sell_price+'.00'); // save selected id to input
                $('#amount_'+index).val(ui.item.sell_price+'.00'); // save selected id to input
                $('#qty_'+index).val('1'); // save selected id to input
                $('#SaveButton').show(); // save selected id to input
                calculateTotal();
                return false;
            },
            focus: function(event, ui){
                $( "#autocomplete_"+index ).val( ui.item.label );
                $( "#hsn_"+index ).val( ui.item.item_code );
                $( "#inv_"+index ).val( ui.item.inv_id );
                $( "#des_"+index ).val( ui.item.item_desc );
                $( "#mrp_"+index ).val( ui.item.mrp );
                $( "#price_"+index ).val( ui.item.sell_price );
                $( "#amount_"+index ).val( ui.item.sell_price );
                $( "#qty_"+index ).val('1');
                return false;
            },
        });
        });

      $(document).on('keyup', '.product_code', function() {
        //alert('hi');
        var id = this.id;
        var splitid = id.split('_');
        var index = splitid[1];
          $( '#'+id ).autocomplete({
            source: function( request, response ) {
                
                $.ajax({
                    url: "<?php echo base_url(); ?>billing/barcodescan/",
                    type: 'post',
                    dataType: "json",
                    data: {
                        search: request.term, index: index
                    },
                    success: function( data ) {
                    if (data[0]['duplicate']=='NO') {
                         $( "#autocomplete_"+data[0]['index'] ).val( data[0]['label'] );
                    $( "#hsn_"+data[0]['index'] ).val( data[0]['item_code'] );
                    $( "#inv_"+data[0]['index'] ).val( data[0]['inv_id'] );
                    $( "#des_"+data[0]['index'] ).val( data[0]['item_desc'] );
                    $( "#mrp_"+data[0]['index'] ).val( data[0]['mrp'] );
                    $( "#price_"+data[0]['index'] ).val( data[0]['sell_price'] );
                    $( "#amount_"+data[0]['index'] ).val( data[0]['sell_price'] );
                    $( "#qty_"+data[0]['index'] ).val('1');
                    $("#qty_"+data[0]['index']).addClass('pqun_'+data[0]['item_code']);
                    $("#mrp_"+data[0]['index']).addClass('pmrp_'+data[0]['item_code']);
                    $("#price_"+data[0]['index']).addClass('pprice_'+data[0]['item_code']);
                    $("#amount_"+data[0]['index']).addClass('pamount_'+data[0]['item_code']);
                    var new_id=parseInt(data[0]['index'])+1;
                     calculateTotal();
                     addnewline();
                     $( "#hsn_"+new_id).focus();
                      $('#SaveButton').show();
                    }
                    else
                    {
                    var order_qty=$( ".pqun_"+data[0]['item_code'] ).val();
                    var orderqty=parseInt(order_qty);
                    var quantity=orderqty+1;
                    var price=data[0]['sell_price'];
                    $( ".pqun_"+data[0]['item_code'] ).val(quantity);
                    $( "#hsn_"+data[0]['index'] ).val('');
                    if( quantity!='' && price !='' ) $('.pamount_'+data[0]['item_code']).val( (parseFloat(price)*parseFloat(quantity)).toFixed(2) ); 
                      calculateTotal();
                      $('#SaveButton').show();
                    }
                    }
                });
            },
            
        });
        });

      $('#Add').click(function () {
        // Get last id 
        var lastname_id = $('.tr_input input[type=text]:nth-child(1)').last().attr('id');
        var split_id = lastname_id.split('_');

        // New index
        var index = Number(split_id[1]) + 1;
        $('<tr class="tr_input"><td width="7%"><input type="number" class="form-control" name="slno[]" id="slno_1" value="'+index+'"></td><td width="8%"><input type="text" class="form-control product_code" name="hsn[]" id="hsn_'+index+'" ><input type="hidden" class="form-control" name="inv_id[]" id="inv_'+index+'"></td><td width="15%"><input type="text" class="form-control autocomplete" name="itemName[]" id="autocomplete_'+index+'"></td><input type="hidden" name="mrp[]" id="mrp_'+index+'"><td width="20%"><input type="text" class="form-control" name="des[]" id="des_'+index+'"></td><td width="7%"><input type="number" class="form-control changesNo" name="qty[]" min="1" max="10" id="qty_'+index+'"></td><td width="8%"><input type="number" class="form-control changesNo" name="price[]" id="price_'+index+'"></td><td width="8%"><input type="number" class="form-control totalLinePrice" name="amount[]" id="amount_'+index+'" readonly></td><td width="4%"><button type="button" class="btn btn-danger remCF"><i class="fa fa-minus" aria-hidden="true"></i></button></td></tr>').appendTo('#Content');
      });
      $("#Content").on('click','.remCF',function(){
        $('#SaveButton').show();
        $(this).parent().parent().remove();
        calculateTotal();
    });

    $(document).on('change keyup blur','.changesNo',function(){
      id_arr = $(this).attr('id');
      id = id_arr.split("_");
      quantity = $('#qty_'+id[1]).val();
      price = $('#price_'+id[1]).val();
      if( quantity!='' && price !='' ) $('#amount_'+id[1]).val( (parseFloat(price)*parseFloat(quantity)).toFixed(2) ); 
      calculateTotal();
      $('#SaveButton').show();
    });
    });
    
    
    function calculateTotal(){
       
      subTotal = 0 ; total = 0; 
      $('.totalLinePrice').each(function(){
        if($(this).val() != '' )subTotal += parseFloat( $(this).val() );
      });
      $('#subTotal').val( subTotal.toFixed(2) );
      tax = $('#tax').val();
      if(tax != '' && typeof(tax) != "undefined" ){
        taxAmount = subTotal * ( parseFloat(tax) /100 );
        $('#taxAmount').val(taxAmount.toFixed(2));
        total = subTotal + taxAmount;
      }else{
        $('#taxAmount').val(0);
        total = subTotal;
      }
      $('#totalAftertax').val( total.toFixed(2) );
      //calculateAmountDue();
    }
    function split( val ) {
      return val.split( /,\s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }
    function addnewline() {
      var lastname_id = $('.tr_input input[type=text]:nth-child(1)').last().attr('id');
        var split_id = lastname_id.split('_');

        // New index
        var index = Number(split_id[1]) + 1;
        $('<tr class="tr_input"><td width="7%"><input type="number" class="form-control" name="slno[]" id="slno_1" value="'+index+'"></td><td width="8%"><input type="text" class="form-control product_code" name="hsn[]" id="hsn_'+index+'" ><input type="hidden" class="form-control" name="inv_id[]" id="inv_'+index+'"></td><td width="15%"><input type="text" class="form-control autocomplete" name="itemName[]" id="autocomplete_'+index+'"></td><input type="hidden" name="mrp[]" id="mrp_'+index+'"><td width="20%"><input type="text" class="form-control" name="des[]" id="des_'+index+'"></td><td width="7%"><input type="number" class="form-control changesNo" name="qty[]" min="1" max="10" id="qty_'+index+'"></td><td width="8%"><input type="number" class="form-control changesNo" name="price[]" id="price_'+index+'"></td><td width="8%"><input type="number" class="form-control totalLinePrice" name="amount[]" id="amount_'+index+'" readonly></td><td width="4%"><button type="button" class="btn btn-danger remCF"><i class="fa fa-minus" aria-hidden="true"></i></button></td></tr>').appendTo('#Content');
    }

    </script>
<script type="text/javascript">
function choose_rate(rate)
{
$("#display").hide();
var page='rateData';
$.ajax({
                type: "POST",
                url: "ajax.php",
                data: {
                rate: rate, page: page
                },
                success: function(html) {
                // $("#display").show();
                //$("#display").html(html).show();
                $('.service_data').append(html);
                }
                });
}
</script>

<script>

    $(document).ready(function(e) {

        $("#rateForm").on('submit', function(e) {

            e.preventDefault();

                $.ajax({

                    type: 'POST',

                    url: '<?php echo base_url(); ?>billing/save/',

                    data: new FormData(this),

                    contentType: false,

                    cache: false,

                    processData: false,

                    beforeSend: function() {

                        $('.addbtn').hide();

                        $('.addload').show();

                    },

                    success: function(msg) {
                          swal("Thankyou ", "Bill generation successful", "success", { button: "ok",});
                            $(".StatUpd").show();

                            $('.StatUpd').delay(3000).hide(200);

                            $('.addbtn').show();

                          $('.addload').hide();

                            setInterval(function() {

                                location.reload();

                            }, 3000);

                    }

                });

        });

    });

</script>

<script>



$(document).ready(function() {

    $('#myTable').DataTable({

    //"bPaginate": false,

     "bLengthChange": false,

    // "bFilter": false,

     "bInfo": false,

    "bAutoWidth": false,

    "bSort" : false

    });

} );

</script>



<style type="text/css">

  table.dataTable thead .sorting, 

table.dataTable thead .sorting_asc, 

table.dataTable thead .sorting_desc {

    background : none;

}

</style>


<script>
$(document).ready(function(){

      $('#sendEmail').click(function(){
        window.open('bill-send.php?service=<?php echo $_GET['service']; ?>','popup','width=100,height=100');
        // var service='<?php echo $service_feedback_new['se_id']; ?>';
         // $.ajax({
             // type: 'POST',
             // url: 'bill-send.php',
             // data: { service: service},
             // success: function(data){
                swal("Thankyou ", "Successfully Invoice Sent To Customer", "success", { button: "ok",});
             // }
         // });
      });

    });
</script>

<?php $this->session->unset_userdata('cart_products'); ?>