<style>
.loader {
        position: fixed;
        left: 0px;
        top: 0px;
        width: 100%;
        height: 100%;
        z-index: 9999;
        background: url('<?php echo base_url(); ?>assets/images/page-loader-1.gif') 50% 50% no-repeat ;
        display: none;
    }
</style>
<div class="wrapper">
    <div class="container">
        <!-- Page-Title -->
        <div class="row">
            <div class="col-sm-12">
                <div class="pull-left">          
                    <h4 class="page-title"><?php echo $heading;?> </h4>
                </div>
                <?php if($this->session->userdata('ho')=="No"){?>
                <div class="btn-group pull-right">
                <a href="<?php echo base_url().'add_requisition/'.$requisition_detail[0]['requisition_number'];?>" class="btn btn-custom waves-effect waves-light m-t-15" >Add More Products<span class="m-l-5"><i class="fa fa-plus"></i></span></a>
                </div>
                <?php } ?>
            </div>            
        </div>

        <div class="row">
            <div class="col-sm-12">
                <div class="card-box table-responsive">
                    <h4 class="header-title m-t-0 m-b-30">&nbsp;</h4>
                    <div id="loader" class="loader"></div>
                    <table id="tblrequisitions" class="table table-striped table-bordered table-responsive nowrap" cellspacing="0" width="100%">
                        <thead>
                            <tr>
                                <?php if($this->session->userdata('ho')=="Yes"){?>
                                <th></th>
                                <?php } ?>
                                <th>Req. #</th>
                                <th>ID.</th>
                                <th>Branch</th>
                                <?php // if($this->session->userdata('ho')=="Yes"){?>
                                <th>Store</th>
                                <?php // } ?>
                                <th>Product ID</th>
                                <th>Product</th>
                                <th>Req. Date</th>
                                <th>Status</th>
                                <th>Requested Qty.</th>                                
                                <?php if($this->session->userdata('ho')=='Yes'){?>
                                <th>Transfer From Batch</th>   
                                <th>Transfer Qty.</th>   
                                <th>By</th>                         
                                <th>Check</th>    
                                <th>Check</th>
                                
                                <?php } ?>
                                
                            </tr>
                        </thead>
                        <tbody>
                            <?php $rowid=0; $total_req = 0; foreach($requisition_detail as $req){?>
                                <?php $rowid++;?>
                                <?php if($req['business_id']!=$this->session->userdata('businessid') && $this->session->userdata('ho')=="No"){?>
                                
                                <?php } else {?>    
                                <tr>
                                    <?php  if($this->session->userdata('ho')=="Yes"){?>
                                        <?php if($req['requisition_status']=='Active'){?>
                                        <td key="checkbox" type="checkbox"><input id="checkbox_<?php echo $req['id_branch_requisition']."_".$req['requisition_number'];?>" type="checkbox" class="checkbox-row form-control" >  </td>
                                        <?php } else { ?>
                                        <td></td>    
                                        <?php } ?>
                                    <?php  } ?>
                                    <td ><?php echo $req['requisition_number'];?></td>
                                    <td><?php echo $req['id_branch_requisition'];?></td>
                                    <td id="<?php echo $req['business_id'];?>"><?php echo $req['business_name'];?></td>
                                    <?php //  if($this->session->userdata('ho')=="Yes"){?>
                                    <td>
                                        <select disabled="disabled"  id="to_store" style="width: 90px;" class="form-control">
                                            <?php foreach($stores as $s){?>
                                                <?php if($s['business_id']==$req['business_id']){?> 
                                                <option <?php if($s['id_business_stores'] == $req['store_id']){ echo 'selected="selected"'; } ?> to_store_id="<?php echo $s['id_business_stores'] ?>"><?php echo $s['business_store'];?></option>
                                                <?php } ?>
                                            <?php } ?>
                                        </select>

                                    </td>
                                    <?php // } ?>
                                    <td product_id="<?php echo $req['product_id'];?>">
                                        <a href="<?php echo base_url('batches');?>/<?php echo $req['product_id'];?>" ><?php echo $req['product_id'];?></a>
                                    </td>
                                    <td>
                                        <?php if($this->session->userdata('ho')=='Yes' && substr($heading,0, 11) != 'Requisitions'){?>
                                        <a href="<?php echo base_url()."product_requisitions/".$req['product_id'];?>" style="word-wrap:break-word; width:100px;" ><?php echo $req['product'];?></a>
                                        <?php } else {  echo $req['business_brand_name'].' '.$req['product'];} ?></td>
                                    <td><?php echo $req['requistion_date'];?></td>
                                    <?php if($this->session->userdata('ho')=='Yes' && substr($heading,0, 11) != 'Requisitions'){?>
                                        <td <?php if($req['requisition_status']!='Active'){ echo 'class="text-danger"';} ?>><?php echo $req['requisition_status'];?></td>
                                    <?php } else { ?>
                                        <td>
                                            <div class="input-group input-group-sm inline">
                                                <select id="status_<?php echo $req['id_branch_requisition'];?>_<?php echo $rowid ?>" class="form-control">
                                                    <option ></option>
                                                    <option value="Not Approved" <?php if($req['requisition_status']=='Not Approved'){ echo 'selected="selected"';}?>>Not Approved</option>
                                                    <option value="Active" <?php if($req['requisition_status']=='Active'){ echo 'selected="selected"';}?>>Active</option>                                                
                                                    <option value="Cancelled" <?php if($req['requisition_status']=='Cancelled'){ echo 'selected="selected"';}?>>Cancel</option>                                                
                                                </select>
                                                <span class="input-group-btn">
                                                <button type="button" onclick="update_status(<?php echo $req['id_branch_requisition'];?>,'status_<?php echo $req['id_branch_requisition'];?>_<?php echo $rowid ?>')" class="btn waves-effect waves-light btn-pink" ><i class="fa fa-save"></i></button>
                                            </div>
                                        </td>
                                    <?php } ?>

                                    <?php 
                                            $required_qty= $req['required_qty'] - $req['tranfer_in_qty']; 
                                            //echo $required_qty; 
                                            $total_req=$total_req+$required_qty;
                                            
                                        ?>
                                    <?php if($this->session->userdata('ho')=='Yes' && substr($heading,0, 11) != 'Requistions'){?>
                                        <td style="text-align:right;"><?php echo $required_qty;?></td>
                                    <?php } else { ?>
                                        <td style="text-align:right;">
                                            <div class="input-group input-group-sm inline">
                                                <input style="border:none; text-align:right;" class="form-control" id="update_qty_<?php echo $req['product_id'];?>_<?php echo $rowid;?>" type='number' min=0 value="<?php echo $required_qty;?>">
                                                <span class="input-group-btn">
                                                <button type="button" onclick="update_qty(<?php echo $req['id_branch_requisition'];?>,'update_qty_<?php echo $req['product_id'];?>_<?php echo $rowid;?>');" class="btn waves-effect waves-light btn-pink" ><i class="fa fa-save"></i></button>
                                            </span>
                                            </div>
                                        </td>    
                                    <?php } ?>
                                    <?php if($this->session->userdata('ho')=='Yes'){?>
                                    <td>
                                    <div class="row">
                                        
                                        <div class="col-md-8">
                                            <select onclick="get_batches(<?php echo $req['product_id'];?>, 'batchselect_<?php echo $req['id_branch_requisition'];?>_<?php echo $rowid;?>');" id="batchselect_<?php echo $req['id_branch_requisition'];?>_<?php echo $rowid;?>" class="form-control mSelect col-md-10" style="width:200px">
                                            
                                            </select>
                                        </div>                                       
                                    </div>
                                    </td>     
                                    <td id="tdtransferqty">
                                        <input class="form-control" style="width:70px;" name="transfer_qty" id="transfer_qty" type="number" min=0 value="0" onchange="if(this.value > <?php echo $required_qty;?>){this.value=<?php echo $required_qty;?>}  if(this.value > parseInt($('#batchselect_<?php echo $req['id_branch_requisition'];?>  option:selected').attr('totalstock'))){this.value=$('#batchselect_<?php echo $req['id_branch_requisition'];?>  option:selected').attr('totalstock');}">
                                    </td>
                                    <td><?php echo $req['created_by']; ?></td>
                                    <td>                                        
                                        <a target="productcheck" href="<?php echo base_url('batches/');?><?php echo $req['product_id'];?>"  class="btn btn-sm btn-primary">Check HO</a>
                                    </td>    
                                    <td>                                        
                                        <a target="productcheck" href="<?php echo base_url('storeproductbatches/');?><?php echo $req['product_id'];?>/<?php echo $req['id_business_stores'];?>"  class="btn btn-sm btn-primary">Check Branch</a>
                                    </td>
                                   
                                    <?php } ?>                                 
                                </tr>
                            <?php }}?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <?php if($this->session->userdata('ho')=="Yes"){?>
                                <th><input class="checkbox form-control" type="checkbox" id="checkall" onclick="selectall();" ></th>
                                <?php } ?>
                                <th> <?php if($this->session->userdata('ho')=="Yes"){?>check all<?php } ?></th>
                                <th></th>
                                <?php // if($this->session->userdata('ho')=="Yes"){?>
                                <th></th>
                                <?php // } ?>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th style="text-align:right;"><?php echo $total_req;?></th>
                                <?php if($this->session->userdata('ho')=='Yes'){?>
                                <th></th>    
                                <th></th>                           
                                <th></th>
                                <th></th>
                                <th></th>
                                <?php } ?>
                                
                            </tr>
                        </tfoot>
                    </table>
                </div>
                <?php if($this->session->userdata('ho')=="Yes"){?>
                <div class="card-box">
                    <div class="row">
                        <div class="col-md-12">
                            <button onclick="transfer();" class="btn btn-success pull-right">Save</button>
                        </div>
                    </div>
                </div>
                <?php } ?>
            </div>
        </div>

        <!--Add Transfer Modal-->
        <div id="addtransfer" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="addtransfer" aria-hidden="true" style="display: none;">
            <div class="modal-dialog">
                <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 a new Transfer Note</h4>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            
                            <div class="col-lg-6">
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="storefrom" class="control-label">From Store</label>
                                            <select id="storefrom" name="storefrom" class="form-control" >
                                                <?php foreach ($hostores as $store) { ?>
                                                     <option frombusinessid="<?php echo $store['business_id'];?>" <?php if($store['business_id']==$this->session->userdata('businessid')){echo "selected='selected'";}?> value="<?php echo $store['id_business_stores']; ?>"><?php echo $store['business_store']; ?></option>
                                                <?php   } ?>
                                            </select>
                                        </div> 
                                    </div> 
                                </div>
                            </div>
                            
                            <div class="col-lg-6">
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label  for="storeto" class="control-label">To Store</label>
                                            <select id="storeto" name="storeto" class="form-control" >
                                                <?php foreach ($stores as $store) { ?>
                                                    <option tobusinessid="<?php echo $store['business_id'];?>" value="<?php echo $store['id_business_stores']; ?>"><?php echo $store['business_store']; ?></option>                                                    
                                                <?php } ?>
                                            </select>
                                        </div> 
                                    </div> 
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-lg-12">
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="product" class="control-label">Products</label>
                                            <input readonly="readonly" type="text" class='form-control' id="product" name="product"  placeholder="Select Products" >
                                        </div> 
                                    </div> 
                                </div>
                            </div>                            
                        </div>
                        <div class="row">
                            <div class="col-md-6"></div>
                            <div class="col-md-6">
                                <button style="float:right" onclick="addOrderRows();" type="button" class="btn btn-sm btn-purple waves-effect ">Add Product <i class="ti ti-arrow-circle-down"></i></button>
                            </div>
                        </div>
                        <div class='row ' style="min-height: 150px;">
                            <div id='order-product-list' class='col-md-12'>
                                <div class="table-responsive">
                                    <table class="table" id="ordertbl">
                                        <thead>
                                            <tr>
                                                <th></th>
                                                <th style="display:none;">BatchID</th>
                                                <th>Batch#</th>
                                                <th>Product</th>                                                
                                                <th>From</th>
                                                <th>To</th>
                                                <th>Available</th>
                                                <th class="text-custom">Qty</th>
                                                <th class="text-custom">Price</th>
                                                <th>Remove</th>
                                            </tr>
                                        </thead>
                                        <tbody>

                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
                        <button onclick="addnew();" type="button" class="btn btn-custom waves-effect waves-light orderloader"><span>Save</span></button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div>
        <!--End Product Modal-->

        <script>
            $('document').ready(function (){
                //$(".mSelect").select2();

                $('#tblrequisitions').DataTable({
                    lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],                    
                    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"}],
                        order: {
                            idx: 2,
                            dir: 'asc'
                        },    
                    responsive: !0
                });
            });

            function openaddnew(tostoreid, tobusinessid, productid, product) {
               // console.log(productid);
              //  console.log(product);

                var fromelement = $('#storefrom').find('option:selected');                 
                var frombusinessid = fromelement.attr("frombusinessid"); 
                var fromstoreid = fromelement.val();
               

                haveselected=false;
                $("#storefrom > option").each(function(){
                    $(this).removeAttr("selected");    
                    if ($(this).attr('frombusinessid') != frombusinessid) {
                        $(this).attr("disabled","disabled");                                                 
                    }else{
                        $(this).removeAttr("disabled");  
                        if(haveselected==false){                           
                            $(this).attr("selected","selected");                   
                        }
                        haveselected=true
                    }
                });

                haveselected=false;
                $("#storeto > option").each(function(){
                    $(this).removeAttr("selected");    
                    if ($(this).attr('tobusinessid') != tobusinessid) {
                        $(this).attr("disabled","disabled");                                                 
                    }else{
                        $(this).removeAttr("disabled");  
                        if(haveselected==false){                           
                            $(this).attr("selected","selected");                   
                        }
                        haveselected=true
                    }
                });
                
                
                $("#product").attr('product_id', productid);
                $("#product").val(product);

                $("#addtransfer").modal({
                    backdrop: 'static',
                    keyboard: false,
                    show: true
                });
            }

            function selectall(){
                if($("#checkall").is(':checked') == true){
                    $('#tblrequisitions tr').each(function(row, tr) {
                        //console.log($(tr).find('td:eq(7) input[type="text"]').val());
                        $("#checkbox_"+$(tr).find('td:eq(2)').text()+"_"+$(tr).find('td:eq(1)').text()).prop("checked",true);
                        // if(typeof($(tr).find('td:eq(7) input[type="text"]').val())!=='undefined'){
                        //     totalpayable = totalpayable + parseFloat($(tr).find('td:eq(7) input[type="text"]').val());
                        // }               
                    });
                } else {
                    $('#tblrequisitions tr').each(function(row, tr) {
                        //console.log(tr);
                        $("#checkbox_"+$(tr).find('td:eq(2)').text()+"_"+$(tr).find('td:eq(1)').text()).prop("checked",false);
                    });
                }
            }

            function transfer(){
                var TableData = new Array(); var x=0;
                $('#tblrequisitions tr').each(function(row, tr) {
                    //console.log(tr);       
                    //console.log($(tr).find('td:eq(0)').children('input[type="checkbox"]'));
                    if($(tr).find('td:eq(0)').children('input[type="checkbox"]').is(':checked') == true){
                        var batch = $(tr).find('td:eq(10)').find('select').find(':selected');
                       // console.log($(batch[0]).attr('totalstock'));
                        if($(tr).find('td:eq(10)').find('select option:selected').attr('batch_id')!=undefined){ //batch is present
                            //if(parseInt($(tr).find('td:eq(10)').find('select option:selected').attr('totalstock')) >= $(tr).find('td:eq(11)').find('input').val()){ //selected batch has qty
                            if(parseInt($(batch[0]).attr('totalstock')) >= $(tr).find('td:eq(11)').find('input').val()){    
                                if(parseInt($(tr).find('td:eq(11)').find('input').val())>=1){ //transfer qty is less then 1
                                    TableData[x] = {
                                    "requisition_id": $(tr).find('td:eq(2)').text()
                                    ,"to_business_id": $(tr).find('td:eq(3)').attr('id')
                                    ,"tostore": $(tr).find('td:eq(4)').find('select option:selected').attr('to_store_id')
                                    ,"product_id": $(tr).find('td:eq(5)').attr('product_id')
                                    ,"requested_qty": $(tr).find('td:eq(9)').text()
                                    ,"batch_id":  $(batch[0]).attr('batch_id') //$(tr).find('td:eq(10)').find('select option:selected').attr('batch_id')
                                    ,"batch_qty": $(batch[0]).attr('totalstock') // $(tr).find('td:eq(10)').find('select option:selected').attr('totalstock')
                                    ,"transfer_qty": $(tr).find('td:eq(11)').find('input').val()
                                    }
                                    x=x+1;
                                }
                            } else {
                                swal({
                                title: "Low Batch Quantity",
                                text: "Selected Batch Qty is lower then the Qty being transferred for Requsition Id: "+$(tr).find('td:eq(2)').text() ,
                                type: "info",
                                confirmButtonText: 'OK!'
                            });
                            return false;
                            }
                        } else {
                            swal({
                                title: "Batch Missing",
                                text: "No Batch Selected to transfer from Requsition Id: "+$(tr).find('td:eq(2)').text() ,
                                type: "info",
                                confirmButtonText: 'OK!'
                            });
                            return false;
                        }
                    }
                });
              
                // console.log(TableData);
                // return false;
                TableData = $.toJSON(TableData);
                $.ajax({
                    type: "POST",
                    url: "<?php echo base_url();?>product_controller/bulk_transfer_qty",                   
                    data: {orderdata: TableData},
                    success: function(data) {
                        console.log(data);
                        location.reload();
                    }
                });                

            }

            function get_batches(product_id, elemid){
               
                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]['measure_qty']+'" 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");
                        }
                    });
                }
              
            }

            function update_qty(id_requisition, elem){

                elem = "#"+elem;

                var qty = $(elem).val();

                $.ajax({
                    type:"POST",
                        url: "<?php echo base_url();?>requisition_controller/update_requisition_qty",
                        data:{'id_branch_requisition': id_requisition, 'qty': qty},
                        dataType: "text",
                        async: false,
                        success: function(data){
                            toastr.info(data, 'Requisition Update');
                            if(data!='success'){
                                location.reload();
                            }
                        }                   

                });



            }

            function update_status(id_requisition, elem){

                elem = "#"+elem+" option:selected";

                var status = $(elem).val();

                $.ajax({
                    type:"POST",
                        url: "<?php echo base_url();?>requisition_controller/update_requisition_status",
                        data:{'id_branch_requisition': id_requisition, 'status': status},
                        dataType: "text",
                        async: false,
                        success: function(data){
                            toastr.info(data, 'Requisition Update');
                            if(data!='success'){
                                location.reload();
                            }
                        }                   

                });
            }

        </script>