<style type="text/css">
    @media print
    {
        .noprint {display:none;}
    }
</style>
<div class="wrapper">
    <div class="container">
        <!-- Page-Title -->
        <div class="row">
            <div class="col-sm-12">
               
                <h4 class="page-title">Active Dispatch Requests</h4>
            </div>
        </div>
        
        <div class="row">
            <div class="col-md-4">
                <div class="form-group">
                    
                </div>
            </div>
            <div class="col-md-4">
                <div class="form-group"></div>
            </div>
        </div>
        
        <div class="col-sm-12">
                <div class="card-box table-responsive">
                    <h4 class="header-title m-t-0 m-b-30">&nbsp;</h4>
                    <table id="datatable-buttons" class="table table-bordered">
                        <thead>
                            <tr>
                                <th>Request</th>
                                <th>Visit</th>
                                <th>Customer</th>
                                <th>Service</th>
                                <th class="text-success">Staff</th>
                                <th>Product</th>                                
                                <th>Qty</th>
                                <th>MU</th>
                                <th>Batch ID | # - Store - Available</th>
                                <th>Dispatch Qty</th>
                                <th>Dispatch</th>
                                <th>Add Product</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $rowid=1; $visitid=0; $service_id=0;?>
                            <?php foreach($dispatch_requests as $dr){ ?>
                            
                            <?php //$already_dispatched = $this->dispatch_model->visit_service_dispatches($dr['visit_service_id'], $dr['product_id']);?>                                   
                            <?php //if(isset($already_dispatched)){
                                $required_qty  = $dr['product_qty'] ;
                                $dr['product_qty'] = $dr['product_qty'] - $dr['already_dispatched'];
                            //}
                            ?>
                            
                            
                            <?php if($visitid==$dr['customer_visit_id']){?>
                            <tr id="<?php echo $rowid;?>">
                                <td request_id="<?php echo $dr['id_dispatch_request'];?>"><?php echo $dr['id_dispatch_request'];?></td>
                                <td visit_id="<?php echo $dr['customer_visit_id'];?>" visit_service_id="<?php echo $dr['visit_service_id'];?>" visit_service_staff_id="<?php echo $dr['visit_service_staff_id'];?>"></td>
                                <td customer_id = "<?php echo $dr['customer_id'];?>"><?php echo $dr['customer_name'];?></td>
                                <td service_id="<?php echo $dr['service_id'];?>"><?php echo $dr['service_name'];?></td>
                                <td staff_id="<?php echo $dr['staff_id'];?>"><strong><?php echo $dr['staff_name'];?></strong></td>
                                <td product_id="<?php echo $dr['product_id'];?>"><strong><?php echo $dr['product_id'].'-'.$dr['product_name'];?></td>                                
                                <td><?php echo $required_qty;?></td>
                                <td measure_unit="<?php echo $dr['measure_unit'];?>" unit_type="<?php echo $dr['unit_type'];?>" qty_per_unit="<?php echo $dr['qty_per_unit'];?>"><?php echo $dr['product_unit'];?></td>
                                <td>
                                    <div class="row">
                                        <div class="col-md-8">
                                            <select onclick="get_batches(<?php echo $dr['product_id']; ?>,'product_batches_<?php echo $dr['product_id'];?>_<?php echo $rowid;?>');" id="product_batches_<?php echo $dr['product_id'];?>_<?php echo $rowid;?>" class="form-control col-md-10" style="width:200px">
                                            
                                            </select>
                                           
                                        </div>
                                        <div class="col-md-4">
                                            <button type='button' onclick="$('#id_dispatch_request').val(<?php echo $dr['id_dispatch_request'];?>);  $('#product_modal').modal('show');"  class="btn btn-sm btn-pink"><i class="fa fa-refresh"></i></button>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div class="input-group">                                        
                                        <input class="form-control" class="decimal" onkeyup="if(this.value > <?php echo $dr['product_qty'];?> || this.value<0){this.value = <?php echo $dr['product_qty'];?>}" type="number" min=0 max="<?php echo $dr['product_qty']; ?>" name="dispatch_measure" id="dispatch_measure_<?php echo $dr['id_dispatch_request'];?>" value="<?php echo $dr['product_qty'];?>">
                                        <span class="input-group-addon"><?php echo $dr['measure_unit'];?></span>
                                    </div>
                                </td>
                                <td >
                                    <?php if($dr['product_qty']>0){?>
                                    <button onclick="dispatch_product(<?php echo $rowid;?>);" class="btn btn-xs btn-success ">Dispatch</button>
                                    <?php } else {?>
                                    <i class="txt-success fa fa-check"></i>
                                    <?php } ?>
                                </td>
                                <td>                                    
                                    <?php if($service_id!=$dr['service_id']){ ?>
                                        <button type='button' onclick="open_add_product_modal(<?php echo $rowid;?>,'<?php echo $dr['measure_unit']; ?>'); "  class="btn btn-sm btn-info m-l-5"><i class="fa fa-plus"></i></button>
                                        <?php $service_id=$dr['service_id']; ?>
                                    <?php } ?>
                                </td>
                            </tr>
                            <?php } else { ?>
                            <tr id="<?php echo $rowid;?>">
                                <td style="border-top:1px solid #808080;" request_id="<?php echo $dr['id_dispatch_request'];?>"><?php echo $dr['id_dispatch_request'];?></td>
                                <td style="border-top:1px solid #808080;" visit_id="<?php echo $dr['customer_visit_id'];?>" visit_service_id="<?php echo $dr['visit_service_id'];?>"  visit_service_staff_id="<?php echo $dr['visit_service_staff_id'];?>"><a target="_blank" href="<?php echo base_url();?>dispatch_note_print/0/<?php echo $dr['customer_visit_id'];?>"><?php echo $dr['customer_visit_id'];?></a></td>
                                <td style="border-top:1px solid #808080;" customer_id = "<?php echo $dr['customer_id'];?>"><?php echo $dr['customer_name'];?></td>
                                <td style="border-top:1px solid #808080;" service_id="<?php echo $dr['service_id'];?>"><?php echo $dr['service_name'];?></td>
                                <td style="border-top:1px solid #808080;" staff_id="<?php echo $dr['staff_id'];?>"><strong><?php echo $dr['staff_name'];?></strong></td>
                                <td style="border-top:1px solid #808080; font-weight:700;" product_id="<?php echo $dr['product_id'];?>"><?php echo $dr['product_id'].'-'. $dr['product_name'];?></td>                                
                                <td style="border-top:1px solid #808080;"><?php echo $required_qty;?></td>
                                <td style="border-top:1px solid #808080;" measure_unit="<?php echo $dr['measure_unit'];?>"  unit_type="<?php echo $dr['unit_type'];?>" qty_per_unit="<?php echo $dr['qty_per_unit'];?>"><?php echo $dr['product_unit'];?></td>
                                <td style="border-top:1px solid #808080;" >
                                    <div class="row">
                                        <div class="col-md-8">
                                            <select onclick="get_batches(<?php echo $dr['product_id']; ?>,'product_batches_<?php echo $dr['product_id'];?>_<?php echo $rowid; ?>');" id="product_batches_<?php echo $dr['product_id'];?>_<?php echo $rowid; ?>"  class="form-control col-md-10" style="width:200px">
                                            
                                            </select>
                                        </div>
                                        <div class="col-md-4">
                                            <button type='button' onclick="$('#id_dispatch_request').val(<?php echo $dr['id_dispatch_request'];?>);  $('#product_modal').modal('show');"  class="btn btn-sm btn-pink"><i class="fa fa-refresh"></i></button>
                                            
                                        </div>
                                    </div>
                                </td>
                                <td style="border-top:1px solid #808080;">
                                    <div class="input-group">
                                        
                                        <input class="form-control" class="decimal" onkeyup="if(this.value > <?php echo $dr['product_qty'];?> || this.value<0){this.value = <?php echo $dr['product_qty'];?>}" type="number" min=0 max="<?php echo $dr['product_qty']; ?>" name="dispatch_measure" id="dispatch_measure_<?php echo $dr['id_dispatch_request'];?>" value="<?php echo $dr['product_qty'];?>">
                                        <span class="input-group-addon"><?php echo $dr['measure_unit'];?></span>
                                    </div>
                                </td>
                                <td style="border-top:1px solid #808080;">
                                    <?php if($dr['product_qty']>0){?>
                                    <button onclick="dispatch_product(<?php echo $rowid;?>);" class="btn btn-xs btn-success ">Dispatch</button>
                                    <?php } else {?>
                                    <i class="txt-success fa fa-check"></i>
                                    <?php } ?>
                                    <!--<button onclick="remove_request(<?php echo $rowid;?>);" class="btn btn-xs btn-pink m-t-5"><i class="fa fa-trash"></i></button>-->
                                </td>
                                <td>
                                    <button type='button' onclick="open_add_product_modal(<?php echo $rowid;?>,'<?php echo $dr['measure_unit']; ?>'); "  class="btn btn-sm btn-info m-l-5"><i class="fa fa-plus"></i></button>
                                    <?php $service_id=$dr['service_id']; ?>        
                                </td>
                            </tr>    
                            <?php $visitid=$dr['customer_visit_id'];  }?>                                                                         
                            <?php $rowid++;} ?>                                
                            
                        </tbody>
                    </table>
                </div>
        </div>        
        
    </div>   
    
</div>
    <div id="product_modal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="product_modal" aria-hidden="true" style="display: none;">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title" id="custom-width-modalLabel">Change Product</h4>
                </div>
                <div class="modal-body">    
                    <form class="form" id="productform">
                    <div class="row">
                        <input id="id_dispatch_request" name="id_dispatch_request" class="form-control" type="hidden">
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                               <label for="product" id="span_product" class="control-label">Product Name</label>
                               <input id="newproduct" class="form-control" name="newproduct">
                            </div>
                        </div>
                    </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
                    <button onclick="updaterequest();" id="btnupdaterequest" type="button" class="btn btn-custom waves-effect waves-light">Save</button>
                </div>
            </div>
        </div>
    </div>

    <div id="add_product_modal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="product_modal" aria-hidden="true" style="display: none;">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title" id="custom-width-modalLabel">Add Product</h4>
                </div>
                <div class="modal-body">    
                    <form class="form" id="addproductform">
                    <div class="row">
                        <input id="add_dispatch_request_id" name="id_dispatch_request" class="form-control" type="hidden">
                        <input id="add_customer_id" name="id_customer" class="form-control" type="hidden">
                        <input id="add_service_id" name="id_service" class="form-control" type="hidden">
                        <input id="add_visit_id" name="id_visit" class="form-control" type="hidden">
                        <input id="add_visit_service_id" name="id_visit_service" class="form-control" type="hidden">
                        <input id="add_visit_service_staff_id" name="id_visit_service_staff" class="form-control" type="hidden">
                        
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                               <label for="addproduct" id="span_product" class="control-label">Product Name</label>
                               <input id="addproduct" class="form-control" name="addproduct">
                            </div>
                        </div>
                    
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="addproductqty" class="control-label">Product Qty</label>
                                <input id="addproductqty" name = "addproductqty" class="form-control decimal" >
                                <label id="lblmeasureunit"></label>
                            </div>
                        </div>
                    </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
                    <button onclick="addrequestproduct();" id="btnaddrequestproduct" type="button" class="btn btn-info waves-effect waves-light">Save</button>
                </div>
            </div>
        </div>
    </div>
    <script>
        
    $(".numeric").keypress(function(e) {
       //if the letter is not digit then display error and don't type anything
       if (e.which != 13 && e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
           return false;
       }
   });


   $(".decimal").keypress(function(e) {
       //if the letter is not digit then display error and don't type anything
       if (e.which != 13 && e.which != 8 && e.which != 0  && e.which != 46 && (e.which < 48 || e.which > 57) ) {

           return false;
       }
   });
    $(document).ready(function() {
        $("#newproduct, #addproduct").select2({
            dropdownAutoWidth:true,
            ajax: {
              url: '<?php echo base_url().'dispatch_controller/getproducts'; ?>',
              dataType: 'json',
              quietMillis: 1000,
              data: function (term, page) {
                  
                return {
                    productname: term, // search term
                    page_limit: 30, // page size
                    page: page, // page number
                    showoutofstock: '<?php echo $showoutofstock;?>'
                };
              },
              results: function (data, page) {
                 // console.log(data);
                    var more = (page * 30) < data.length;
                    return {results: data, more: more};
                }
              },
            escapeMarkup: function (m) { return m; }, // let our custom formatter work
            minimumInputLength: 4,
            formatResult: function (option) {
                var type='Retail';
                if (option.professional=="y"){type = 'Pro';}
                return option.id_business_products + '-'+ option.business_brand_name + ' - ' + option.product + ' - ' + option.mcategory + ' - Batch: ' + option.batch + ' - Type: ' + type + ' ('+ option.business_store +': '+ option.instock+')';
            },
            formatSelection: function (option) {
                var type='Retail';
                if (option.professional=="y"){type = 'Pro';}
                return option.id_business_products + '-'+ option.business_brand_name + ' - ' + option.product+ ' - ' + option.mcategory + ' - Batch: ' + option.batch + ' - Type: ' + type + ' ('+ option.business_store +': '+ option.instock+')';
            }
          });
          
        $('#datatable-buttons').DataTable({
            lengthMenu: [[25, 50, -1], [25, 50, "All"]],
            stateSave: false,
            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                dom: "Bfrtlip",
                buttons: [{extend: "copy", className: "btn-sm btn-custom btn-trans"}, {extend: "csv", className: "btn-sm btn-pink btn-trans"}, {
                    extend: "excel",
                    className: "btn-sm btn-warning btn-trans"
                }, {extend: "pdf", className: "btn-sm btn-purple btn-trans"}],
                <?php } else { ?>
                    dom: "frtlip",
                <?php } ?> 
            responsive: 0,
            stateSave: true,
            ordering: false
        });
    });
    
    function dispatch_product(id){
       
        var tr = $('tr[id="'+id+'"]')
       
        var request_id = $(tr).find('td:eq(0)').attr('request_id');
        var visit_id = $(tr).find('td:eq(1)').attr('visit_id');
        var visit_service_id = $(tr).find('td:eq(1)').attr('visit_service_id');
        var product_id = $(tr).find('td:eq(5)').attr('product_id');
        var dispatch_to_staff = $(tr).find('td:eq(4)').attr('staff_id');
        var staff_name = $(tr).find('td:eq(4)').text().trim();
        var dispatch_unit = '0';
        var dispatch_measure = $(tr).find('td:eq(9) input').val();
        var unit_type = $(tr).find('td:eq(7)').attr('unit_type');
        var measure_unit = $(tr).find('td:eq(7)').attr('measure_unit');
        var qty_per_unit = $(tr).find('td:eq(7)').attr('qty_per_unit');
        var batch = $(tr).find('td:eq(8) select option:selected').attr('batch_number');
        var batch_id = $(tr).find('td:eq(8) select option:selected').attr('batch_id');
        
        var datetime = new Date().toISOString().slice(0, 19).replace('T', ' ');
        
        if(dispatch_measure !== '' &&  dispatch_measure !== 'undefined' && batch_id !== '' & batch_id !== 'undefined'){
            
             $.ajax({
                type: 'POST',
                url: '<?php echo base_url(); ?>dispatch_controller/select_batch_add_dispatch',
                data: {
                    request_id:request_id,
                    product_id: product_id,
                    dispatch_to_staff: dispatch_to_staff,
                    staff_name: staff_name,
                    dispatch_unit:dispatch_unit,
                    dispatch_measure:dispatch_measure,
                    unit_type:unit_type,
                    measure_unit:measure_unit,
                    dispatch_date: '',
                    batch: batch,
                    batch_id: batch_id,
                    qty_per_unit: qty_per_unit,                    
                    visit_id: visit_id,
                    visit_service_id: visit_service_id
                },
                success: function(data) {
                    var result = data.split("|");
                    if (result[0] === "success") {
                        var dispatchqty=result[1];
                        var remaining = parseFloat($("#txtinstock").val())-parseFloat(dispatchqty);
                       
                        toastr.success(data, 'Item Dispatched');
                        location.reload();
                       
                    } else if (result[0] === "error") {                       
                        swal({
                            title: "Something went wrong",
                            text: result[1],
                            type: "error",
                            confirmButtonText: 'OK!'
                        }, function(){
                            location.reload();
                        });  
                    } else {
                        swal({
                            title: "Incomplete Dispatch",
                            text: result[1],
                            type: "info",
                            confirmButtonText: 'OK!'
                        }, function(){
                            location.reload();
                        });                        
                    }
                }
            });        
            }
        }
    
    function updaterequest(){
        
        $.ajax({
            type: 'POST',
            url: '<?php echo base_url(); ?>dispatch_controller/update_request',
            data: $("#productform").serialize(),
            success: function(data) {
                if(data > 0){
                    toastr.success(data, 'Product Changed');
                    location.reload();
                       
                }else{
                    swal({
                        title: "Cannot change product",
                        text: '',
                        type: "error",
                        confirmButtonText: 'OK!'
                    });
                }
            }
        });
    }

    function open_add_product_modal(id, measure_unit){

        var tr = $('tr[id="'+id+'"]')
       
       $("#lblmeasureunit").html(measure_unit);
       $("#add_dispatch_request_id").val($(tr).find('td:eq(0)').attr('request_id'));
       $("#add_customer_id").val($(tr).find('td:eq(2)').attr('customer_id'));
       $("#add_service_id").val($(tr).find('td:eq(3)').attr('service_id'));
       $("#add_visit_id").val($(tr).find('td:eq(1)').attr('visit_id'));
       $("#add_visit_service_id").val($(tr).find('td:eq(1)').attr('visit_service_id'));
       $("#add_visit_service_staff_id").val($(tr).find('td:eq(1)').attr('visit_service_staff_id'));

        $("#addproductqty").val(0);

        $('#add_product_modal').modal('show');
        
    }

    function addrequestproduct(){
        pdata = $("#addproduct").select2('data');

        console.log(pdata);
        console.log($("#addproductqty").val());

        if(null !== pdata && pdata != "" && $("#addproductqty").val() > 0){
            $.ajax({
                type: 'POST',
                url: '<?php echo base_url(); ?>dispatch_controller/add_request_product',
                data: $("#addproductform").serialize(),
                success: function(data) {
                    if(parseFloat(data) > 0){
                        location.reload();
                    }
                }
            });
        }
    }
    

    function get_batches(product_id, elemid){
               console.log('getbatch '+product_id);
               var myelem = "#"+elemid;    
               
               if($(myelem + ' option').size()==0){
                   $(myelem).empty();
                   $(".loader").fadeIn("slow");
                   $.ajax({
                       type:"POST",
                       url: "<?php echo base_url();?>requisition_controller/batches_ajax",
                       data:{'product_id': product_id, 'business_id': <?php echo $this->session->userdata('businessid');?>},
                       dataType: "json",
                       async: false,
                       success: function(data){
                           for (x = 0; x < data.length; x++) {
                               for (y = 0; y < data[x].length; y++) {
                                   if(parseFloat(data[x][y]['total_stock'])>0){
                                       $(myelem).append('<option batch_id="'+data[x][y]['id_batch']+'" batch_number="'+data[x][y]['batch_number']+'" measure_qty="'+data[x][y]['total_stock']*data[x][y]['qty_per_unit']+'" totalstock="'+data[x][y]['total_stock']+'">' + data[x][y]['id_batch']+' | '+data[x][y]['batch_number']+' - '+data[x][y]['business_store']+' - instock:'+data[x][y]['total_stock'] +'</option>');
                                       
                                   }
                               }
                           }
                           $(myelem).select2().delay(1500);
                           $(myelem).select2('open');

                           $(".loader").fadeOut("slow");
                       }
                   });
               }
             
           }
    </script>