<div class="wrapper">
    <div class="container">
        <!-- Page-Title -->
        <div class="row">
            <div class="col-sm-12">  
                <div class="pull-left">          
                    <h4 class="page-title">Add Branch Requistions:</h4>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-sm-12">
                <div class="card-box ">
                    <div class="row">
                        <div class='col-md-12'>
                            <div class="row">
                            <div class="col-md-2">                                
                                    <label for="requisition_number">Requisition #</label>
                                    <input class="form-control text-right" readonly="readonly" type="number" placeholder="Requisition #" id="requisition_number" name="requisition_number" value="<?php if(isset($requisition_number)){if(!empty($requisition_number) && $requisition_number != null && $requisition_number!=""){echo $requisition_number; } else{echo 1;}}else {echo 1;}?>">
                                </div>
                                <div class="col-md-4">                                
                                    <label for="id_product">Product</label>
                                    <input class="form-control" placeholder="Product" id="id_product" name="id_product">                                
                                </div>
                                
                                <div class="col-md-2">                                
                                    <label for="required_qty">Required Qty.</label>
                                    <input read class="form-control text-right" type="number" min="1" placeholder="Required Qty." id="required_qty" name="required_qty" value="1">                                
                                </div>
                                <div class="col-md-2">                                
                                    <label for="required_in">Required In.</label>
                                    <select class="form-control" id="required_in" name="required_in" value="1">
                                        <?php foreach($stores as $store){ ?>
                                        <option value="<?php echo $store['id_business_stores'];?>"><?php echo $store['business_store'];?></option>
                                        <?php } ?>
                                    </select>
                                </div>
                                <div class="col-md-2">                                                                    
                                    <button onclick="addrow();" class="btn btn-md btn-success m-t-20" id="btn-add-row" >Add <i class="fa fa-icon fa-arrow-down"></i></button>                                
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-sm-12">
                <div class="card-box ">
                    <div class="row">
                        <div class='col-md-12'>
                            <table id="tbl_requisitions" class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>ID Product</th>
                                        <th>Product</th>                                        
                                        <th>Qty. Per Unit</th>
                                        <th>Measure Unit</th>
                                        <th>BarCode</th>
                                        <th>Required Qty.</th>           
                                        <th></th>                             
                                    </tr>
                                </thead>
                                <tbody>
                                   
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <button onclick="saverequisition();" class="btn btn-md btn-success pull-right">Save</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>


<script>
$(document).ready(function() {
    $("#id_product").select2({
        dropdownAutoWidth:true,
        ajax: {
            url: '<?php echo base_url().'dispatch_controller/searchproduct'; ?>',
            dataType: 'json',
            quietMillis: 1000,
            data: function (term, page) {
                
            return {
                productname: term, // search term
                page_limit: 30, // page size
                page: page
            };
            },
            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.business_brand_name + ' - ' + option.product+ ' - ' + option.qty_per_unit + ' ' + option.measure_unit + ' - ' + option.mcategory + ' - Barcode: ' + option.barcode_products;
        },
        formatSelection: function (option) {
            var type='Retail';
            if (option.professional=="y"){type = 'Pro';}
            return option.business_brand_name + ' - ' + option.product+ ' - ' + option.qty_per_unit + ' ' + option.measure_unit + ' - ' + option.mcategory + ' - Barcode: ' + option.barcode_products;
        }
    });
});

function addrow(){

    r = $("#id_product").select2('data');
    //console.log(r); 
    var product_id = parseInt(r['id_business_products']);    
    var product_name = r['product'].trim();
    var brand = r['business_brand_name'].trim();    
    var category = r['mcategory'].trim();    
    var unit_type = r['unit_type'].trim();
    var measure_unit = r['measure_unit'].trim();
    var qty_per_unit = parseFloat(r['qty_per_unit']);
    var barcode = parseFloat(r['barcode_products']);
    var ae=false;
    $('#tbl_requisitions tr').each(function(row, tr) {
        console.log($(this).find('td').text());
        if(product_id == $(this).find('td.id').text()){
            swal({
                title: "Product Already Added!",
                text: 'You can adjust the required quantity in the table.',
                type: "warning",
                confirmButtonText: 'OK!'
            });
            ae=true;
        }
    });
    if(ae==false){
        if(parseFloat($("#required_qty").val()) > 0){
            mhtml="<tr><td class='id' id='"+product_id+"'>"+product_id+"</td><td>"+brand + ' ' +product_name+"</td><td>"+qty_per_unit+"</td><td>"+measure_unit+"</td><td>"+barcode+"</td><td><input style='border:none;' type='number' name='req_qty' value='"+ $("#required_qty").val() +"' ></td><td><button class='btn btn-xs btn-danger pull-right'  onclick='removerow("+product_id+")'><i class='fa fa-remove'></i></button></td></tr>";

            $("#tbl_requisitions").append(mhtml);
        }
    }
}

function removerow(product_id){
    console.log(product_id);
    $('#tbl_requisitions').find("td.id").each(function(index) {
        console.log($(this).attr('id'));
        if ($(this).attr("id") == product_id) {
            $(this).closest('tr').remove();
        }
    });
}

function saverequisition(){

    var TableData;
    TableData = storeOTblValues();
    TableData = $.toJSON(TableData);
    
    $.ajax({
        type: 'POST',
        data:{requisition:TableData, store:$("#required_in").val()},        
        url: '<?php echo base_url().'requisition_controller/add_branch_requistion'; ?>',
        dataType: "text",
        cache: false,
        async: true,
        success: function(data) {
            location.href='<?php echo base_url();?>branch_requisition/'+$("#requisition_number").val();
        }
    });

}

function storeOTblValues(){
    var TableData = new Array();
    $('#tbl_requisitions tr').each(function(row, tr) {
        TableData[row] = {
            "product_id": $(tr).find('td:eq(0)').text()            
            , "requisition_qty": $(tr).find('td:eq(5)').find('input[name=req_qty]').val()
            , "requisition_number": $("#requisition_number").val()
            
        }
    });
    TableData.shift();  // first row will be empty - so remove
    return TableData;
}

</script>        