<style>
     tr.strikethrough > td {text-decoration:line-through !important; color:red;} 
</style>
<div class="wrapper">
    <div class="container">
        <!-- Page-Title -->
        <div class="row">
            <div class="col-sm-12">
                
                <h4 class="page-title">Create Franchise Order</h4>
            </div>
        </div>

         <div class="row">
            <div class="col-sm-12">
                <div class="card-box">
                    <h4 class="header-title m-t-0 m-b-30">Select The Franchise</h4>
                    <form method="post" action = "<?php echo base_url();?>franchise_controller/new_order">
                        <div class="row">
                            <div class="col-md-4">
                                <select class="form-control" id="selected_franchise" name='selected_franchise' <?php if($selected_franchise!=='all'){echo "disabled='disabled'";} ?>>
                                    <option value='all'></option>
                                    <?php foreach ($franchises as $f){?>
                                        <option <?php if($f['id_franchises']==$selected_franchise){echo "selected='selected'";} ?> value='<?php echo $f['id_franchises'];?>'><?php echo $f['franchise_name']. ' | '. $f['franchise_owner'];?></option>
                                    <?php } ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <input type="hidden" name="run_franchise_orders" id="voucher_add_csrf" value=""/>
                                <button type="submit"  onclick="$('#run_franchise_orders').val($('#cook').val());" class="btn btn-pink btn-bordred waves-effect w-md waves-light m-b-5">Get</button>
                            </div>
                        </div>
                    </form>
                </div>
                
                <!--Products Sale Form-->
                <?php if(isset($franchise)){ ?>
                        <div class="row" id="retail-divorder" >
                            <div class="col-md-12">
                                <!--<form id="ordderform">-->
                                <div class="card-box">
                                    <h4 class="header-title m-t-0 m-b-30">Create Franchise Order</h4>
                                    <div class="row">
                                        <div class="col-md-2">
                                            <div class="form-group">
                                                <label for="franchise_name" class="control-label">Name</label>
                                                <input readonly="readonly" type="text" class="form-control" id="franchise_name" name="franchise_name" placeholder="Name" value='<?php echo $franchise->franchise_name;?>'>
                                                <input type="hidden" class="form-control" id="order-customer-id" name="order-customer-id" value='<?php echo $franchise->id_franchises;?>'>
                                                <input type='hidden' name='order_id' id='order_id' <?php if(isset($orderid)&&null!==$orderid){ echo "value='".$orderid."'";} ?>>
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <div class="form-group">
                                                <label for="franchise_ntn" class="control-label">NTN</label>
                                                <input readonly="readyonly" type="text" class="form-control" id="franchise_ntn" name="franchise_ntn" placeholder="NTN" value='<?php echo $franchise->franchise_ntn;?>'>
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <div class="form-group">
                                                <label for="franchise_owner" class="control-label">Owner</label>
                                                <input readonly="readyonly" type="text" class="form-control" id="franchise_owner" name="franchise_owner" placeholder="Owner" value='<?php echo $franchise->franchise_owner;?>'>
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <div class="form-group">
                                                <label for="franchise_discount" class="control-label">Franchise Discount %</label>
                                                <input readonly="readyonly" type="text" class="form-control" id="franchise_discount" name="franchise_discount" placeholder="Discount" value='<?php echo $franchise->franchise_discount;?>'>
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <div class="form-group">
                                                <label for="franchise_limit" class="control-label">Franchise Credit Limit</label>
                                                <input readonly="readyonly" type="text" class="form-control" id="franchise_limit" name="franchise_limit" placeholder="Limit" value='<?php echo $franchise->franchise_limit;?>'>
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <div class="form-group">
                                                <label for="order_extra" class="control-label">Branch or Other Details</label>
                                                <input type="text" class="form-control" id="order_extra" name="order_extra" placeholder="Extra details" value='<?php echo $franchise->franchise_order_extra;?>'>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label for="retail-order-products" class="control-label">Select Product</label>
                                                <input type="text" class='form-control' id="retail-order-products" name="order-products"  placeholder="Brand Product Category . . .">
                                                <!--<select class='form-control' id="retail-order-products" name="order-products" > </select>-->
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                    <label for="checkboxall" class="control-label">?</label>
                                    <div class="checkbox checkbox-success">
                                        <input onchange="retail_getproducts();" id="checkboxall" type="checkbox">
                                        <label for="checkboxall">
                                            Show All Stores
                                        </label>
                                    </div>
                                </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label for="retail-order-staff" class="control-label">Sold By</label>
                                                <select class='form-control'  id="retail-order-staff" name="order-staff"> 

                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <div class="form-group">
                                                <label for="order-customer-qty" class="control-label">Qty.</label>
                                                <input class="form-control numeric" type="number" id="order-customer-qty" name="order-customer-qty" value="1">
                                            </div>
                                        </div>
                                    </div>
                                    <?php $editable=false; if(sizeof($order)>=1){ if($order[0]['order_status']=='Open'){$editable=true;}}else{$editable=true;}?>
                                    <?php if($editable==true){?>
                                    <div class='row'>
                                        <div class='col-md-6'></div>
                                        <div class='col-md-6'>
                                            <button style='float:right' onclick='addFranchiseOrderRows();' type='button' class='btn btn-sm btn-purple waves-effect '>Add Product <i class='ti ti-arrow-circle-down'></i></button>
                                        </div>
                                    </div>
                                    <?php } ?>
                                    <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 style="display:none;">Customer ID</th>
                                                            <th>Product ID</th>
                                                            <th>Product </th>
                                                            <th>Details</th>
                                                            <th>Category</th>
                                                            <th>Batch</th>
                                                            <th style="display:none;">Staff ID</th>
                                                            <th>Sold By</th>
                                                            <th>Qty.</th>
                                                            <th>Price</th>
                                                            
                                                            <th style="text-align:right;">Total</th>
                                                            <th style="text-align:right;">Discount</th>
                                                             
                                                            <th style="text-align:right;">Discounted Price</th>
                                                            <th  id="month">Month</th>
                                                            <th id="year">Year</th>
                                                            <th style="display:none;" id="product_type"></th>
                                                            <th>Remove</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php $totalvalue=0; $totaldiscount=0; if(sizeof($order) > 0){
                                                            
                                                            foreach($order as $item){
                                                            ?>
                                                        <tr>
                                                            <td style="display:none;"><?php echo $item['franchise_id']; ?></td>
                                                            
                                                            <td class='id' row='<?php echo $item['product_id'];?>'><input type='hidden' id='product_id' name='product_id' value='<?php echo $item['product_id'];?>'><?php echo $item['product_id'];?></td>
                                                            <td><?php echo $item['product_name']; ?></td>
                                                            <td class="productdetail" style="text-align:left;"><input type="text" class="productdetail" name="productdetail" id="productdetail<?php echo $item['product_id'];?>" style="width: 80px; border: none; text-align:left;" value="<?php echo $item['product_detail']; ?>"/></td>
                                                            <td><?php echo $item['category']; ?></td>
                                                            <td class='batchid' batch_id='<?php echo $item['batch_id']; ?>'><?php echo $item['batch']; ?></td>
                                                            <td style="display:none;"><?php echo $item['staff_id']; ?></td>
                                                            <td><?php echo $item['staff_name']; ?></td>
                                                            <td class="qty" stockfrom="<?php echo $item['stockfrom']; ?>"><?php echo $item['qty']; ?></td>
                                                            <td><input onchange="" style="border:none;" name="price" value="<?php echo $item['unit_price']; ?>"></td>
                                                            <td style="text-align:right;"><?php echo $item['unit_price'] * $item['qty']; ?></td>
                                                            <td class="discount" unit_discount="<?php echo $item['unit_discount'];?>" style="text-align:right;"><input type="text"  onblur="discount_by_product(this.value, '<?php echo $item['product_id'];?>');" class="numeric discount_by_product" name="discount_by_product" id="discount_by_product<?php echo $item['product_id'];?>" style="width: 80px; border: none; text-align:right;" value="<?php echo $item['unit_discount'];?>"></td>
                                                            <?php $totaldiscount=$totaldiscount+($item['unit_discount']*$item['qty']);?>
                                                            <td discounted_price="<?php echo $item['discounted_price'];?>" style="text-align:right;"><?php echo CURRENCY_CODE;?>.<span class="combat" id="unitcost<?php echo $item['product_id'];?>"><?php echo $item['discounted_price'] ;?></span><input type="hidden" name="orignal_product_price" id="orignal_product_price<?php echo $item['product_id'];?>" value="<?php echo $item['discounted_price'];?>"></td>
                                                            <?php $totalvalue=$totalvalue + $item['discounted_price'] ;?>
                                                            
                                                            <?php if(null!==$item['order_month']){?>
                                                            <td class="month" style="text-align:left;"><select><option value="1">Jan</option><option value="2">Feb</option><option value="3">Mar</option><option value="4">Apr</option><option value="5">May</option><option value="6">Jun</option><option value="7">Jul</option><option value="8">Aug</option><option value="9">Sep</option><option value="10">Oct</option><option value="11">Nov</option><option value="12">Dec</option></select></td>
                                                            <td class="year" style="text-align:left;"><select><option value="2020">2020</option><option selected="selected" value="2021">2021</option><option value="2022">2022</option></select></td>
                                                            
                                                            <?php }else { ?>
                                                            <td class="month>"></td>
                                                            <td class="year>"></td>
                                                            
                                                            <?php } ?>
                                                            
                                                            <td><span class="label label-danger" onclick="removebyrow('<?php echo $item['product_id']; ?>');" style="cursor:pointer">x</span></td></td>
                                                        </tr>
                                                        <?php }} ?>
                                                    </tbody>
                                                    <tfoot>
                                                        <tr>
                                                            <th colspan="9" style="border-top:1px solid #808080;"></th>
                                                            <th style="text-align:right; border-top:1px solid #808080;"><input style="border: none; text-align:right;" readonly="readonly" id="totaldiscount" value="<?php echo $totaldiscount;?>"></th>
                                                            <th style="text-align:right; border-top:1px solid #808080;"><input style="border: none; text-align:right;" readonly="readonly" id="totalvalue" value="<?php echo $totalvalue;?>"></th>
                                                            <th style="border-top:1px solid #808080;"></th>
                                                            <th style="border-top:1px solid #808080;"></th>
                                                            <th style="border-top:1px solid #808080;"></th>
                                                        </tr>
                                                    </tfoot>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                    <?php if($editable==true){?>
                                    <div class="row" style="text-align: right">
                                        <form action="open_order_invoice" method="post" target="_blank">
                                            <input type="hidden" class="form-control" id="order-id" name="order-id">
                                             <input type="hidden" name="csrf_test_name" id="retail_modal_csrf" value=""/>
                                            <div class="col-md-6" style="text-align:left">
                                                <button id="btngengdn" onclick="$('#retail_modal_csrf').val($('#cook').val());" style='display:none;' class="btn btn-pink waves-effect waves-light">Create GDN</button>
                                            </div>
                                        </form>
                                        <div class="col-md-6" style="text-align: right">
                                            <button type="button" onclick="franchise_updateorder();" class="btn btn-info waves-effect waves-light">Save Changes</button>
                                        </div>
                                    </div>
                                    <?php } ?>
                                </div>
                                <!--</form>-->
                            </div>
                        </div>        
                <?php } ?>
                <!--End Products Sale Form-->
                
                
                
            </div>
         </div>
    </div> <!--End Container-->
    <script>
    $(document).ready(function() {
        retail_getproducts();
        retail_getstaff();
        
        $("#selected_franchise").select2();
        
    });
    
    
    
    
    
    function franchise_updateorder(val='') {
        
        if ($("#order_id").val() === "" || $("#order_id").val() === "0") { //add new order
            var TableData;
            TableData = retail_storeOTblValues();
            TableData = $.toJSON(TableData);
            if (TableData.length > 2) {
                $.ajax({
                    type: "POST",
                    
                    url: '<?php echo base_url().'franchise_controller/add_order'; ?>',
                    
                    data: {
                        orderdata:TableData,
                        franchiseid:$("#order-customer-id").val(),
                        franchisename:$("#franchise_name").val(),
                        franchisentn:$("#franchise_ntn").val(),
                        orderstatus: 'Open',
                        franchise_order_value: $("#totalvalue").val(),
                        franchise_order_discount: $("#totaldiscount").val(),
                        order_extra: $("#order_extra").val()
                    },
                    success: function(data) {
                        var result = data.split("|");
                        if (result[0] === "success") {
                            $("#order_id").val(result[1]);
                            
                                toastr.success('Franchise Order created!', 'Done!');                               
                           
                            
                        } else {
                            swal({
                                title: "Error",
                                text: result[1],
                                type: "error",
                                confirmButtonText: 'OK!'
                            });
                        }
                    }
                });
            } else {
                swal({
                    title: "You have not added any Products",
                    text: 'Select Product and staff member providing that made the sale.',
                    type: "error",
                    confirmButtonText: 'OK!'
                });
            }
        } else { //update existing order
            var TableData;
            TableData = retail_storeOTblValues();
            TableData = $.toJSON(TableData);
            if (TableData.length > 2) {
                $.ajax({
                    type: "POST",
                    url: '<?php echo base_url().'franchise_controller/update_order'; ?>',
                    data: {
                        orderdata:TableData,
                        orderid:$("#order_id").val(),
                        franchise_order_value: $("#totalvalue").val(),
                        franchise_order_discount: $("#totaldiscount").val()
                    },
                    success: function(data) {
                        if(data === 'invoiced'){
                            swal({
                                title: "Already Invoiced!",
                                text: 'This Franchise Order is already invoiced.',
                                type: "error",
                                confirmButtonText: 'OK!'
                            });
                            return false;
                        }
                        var result = data.split("|");
                        if (result[0] === "success") {
                            
                                toastr.success('Order updated!', 'Done!');                               
                            
                        } else {
                            swal({
                                title: "Error",
                                text: result[1],
                                type: "error",
                                confirmButtonText: 'OK!'
                            });
                        }
                    }
                });
            } else {
                swal({
                    title: "You have not added any Products",
                    text: 'Select Product and staff member providing that made the sale.',
                    type: "error",
                    confirmButtonText: 'OK!'
                });
            }
        }
    }
    
    
    function retail_storeOTblValues(){
    
        var TableData = new Array();
        $('#ordertbl tr').each(function(row, tr) {
            TableData[row] = {
                 "customerid": $(tr).find('td:eq(0)').text()
                , "productid": $(tr).find('td:eq(1)').text()
                , "productname": $(tr).find('td:eq(2)').text()
                , "productdetail": $(tr).find('td:eq(3) input').val()
                , "category": $(tr).find('td:eq(4)').text()
                , "batch": $(tr).find('td:eq(5)').text()
                , "batch_id": $(tr).find('td:eq(5)').attr('batch_id')
                , "staffid": $(tr).find('td:eq(6)').text()
                , "staff": $(tr).find('td:eq(7)').text()
                , "qty": $(tr).find('td:eq(8)').text()
                , "stockfrom": $(tr).find('td:eq(8)').attr('stockfrom')
                , "unit_price": $(tr).find('td:eq(9) input').val()
                , "unit_discount": $(tr).find('td:eq(11)').attr('unit_discount')
                , "discounted_price": $(tr).find('td:eq(12)').attr('discounted_price')
                , "month": $(tr).find('td:eq(13) select').val()
                , "year": $(tr).find('td:eq(14) select').val()
                , "product_type": $(tr).find('td:eq(15) input').val()
            }
        });
        TableData.shift();  // first row will be empty - so remove
        TableData.pop();  // last row will be empty - so remove
        return TableData;
    }
    
    
    function addFranchiseOrderRows() {
        
        var stockfrom="in_stock";
        
        if ($("#order-customer-qty").val() === "" || $("#order-customer-qty").val() === "0" || $("#retail-order-products option:selected").val() === "select") {
            swal({
                title: "Product & Quantity Should not be empty!",
                text: 'Please select all the above options before proceeding.',
                type: "info",
                confirmButtonText: 'OK!'
            });
            return false;
        }
      
        r = $("#retail-order-products").val().split(',');
        var data = $("#retail-order-products").select2('data');
        
        var product_id = parseInt(data.id_business_products);
        var in_stock = parseInt(data.instock);
        var product_name = data.product;
        var category = data.category;
        var batch = data.batch_number;
        var batch_id = data.batch_id;
        var price = data.price;
        var unit_type =data.unit_type;
        var measure_unit=data.measure_unit;
        var qty_per_unit = data.qty_per_unit;
        var product_type = data.product_type;
       
        var selected_qty = parseInt($("#order-customer-qty").val());
        
        if(parseInt(selected_qty)>in_stock ){
             swal({
                title: "Quantity cannot be more then available stock!",
                text: 'Please enter correct qty before proceeding.',
                type: "warning",
                confirmButtonText: 'OK!'
            });
            return false;
        } else {
            addFranchiseOrderRow1(stockfrom, product_id, product_name, category, batch, batch_id, price, in_stock, unit_type, measure_unit, qty_per_unit, product_type);
        }

    }
    
    function addFranchiseOrderRow1(stockfrom, product_id, product_name, category, batch, batch_id, price, in_stock, unit_type, measure_unit, qty_per_unit, product_type){
        var mhtml = "";
        
        var qty = parseInt($("#order-customer-qty").val());
        //console.log('order add '+qty);
        if (parseInt(product_id) > 0) {

            var rowcount=0;
            var pTotalQty=0;
           
            var alreadyexist= retail_storeOTblValues();
            var ae = false;
            if(alreadyexist.length > 0){
              
                $('#ordertbl tr').each(function(row, tr) {
                   
                    if($(tr).find('td:eq(1)').text()==product_id && $(tr).find('td:eq(5)').attr('batch_id')==batch_id){
                        pTotalQty = pTotalQty + parseInt($(tr).find('td:eq(7)').text()) + qty;
                       
                        if(pTotalQty > in_stock){
                            swal({
                                title: "Quantity cannot be more then available stock!",
                                text: 'Please enter correct qty before proceeding.',
                                type: "warning",
                                confirmButtonText: 'OK!'
                            });
                            
                            ae=true;
                        } else {
                            
//                            swal({
//                                title: "Already added in the list!",
//                                text: 'Please remove and add again with correct quantities.',
//                                type: "warning",
//                                confirmButtonText: 'OK!'
//                            });
//                            
//                            ae=true;
//            
//                            if($('#retail-order-staff option:selected').val()>0){
//                                $(tr).find('td:eq(6)').text($('#retail-order-staff option:selected').val()); //staffid
//                                $(tr).find('td:eq(7)').text($('#retail-order-staff option:selected').text()); //staff name
//                            }
//                            ae=true;
                        }    
                    }
                })
               
            }
            
            if(ae===true){
                return false;
            } else{
                 var rowstillnow = $("#order-product-list tr").length;
        
                if(rowstillnow > 50){
                    swal({
                            title: "Maximum of 50 products in an order!",
                            text: 'Please Create a Different Order for the rest of the Products.',
                            type: "warning",
                            confirmButtonText: 'OK!'
                        });
                    return false;
                }
                mhtml += '<tr>';
                mhtml += '<td style="display:none;">' + $("#order-customer-id").val() + '</td>';
                //mhtml += "<td class='id' row='"+rowcount+"'>" + product_id + "</td>";
                mhtml += "<td class='id' row='"+product_id+"'><input type='hidden' id='product_id' name='product_id' value='"+ parseInt(product_id)  +"'>" + product_id + "</td>";
                mhtml += "<td>" + product_name + "</td>";
                mhtml += "<td class='productdetail' style='text-align:left;'><input type='text' class='productdetail' name='productdetail' id='productdetail"+ parseInt(product_id)  +"' style='width: 80px; border: none; text-align:left;' value=''/></td>";
                mhtml += "<td>" + category + "</td>";
                mhtml += "<td class='batchid' batch_id='"+batch_id+"'>" + batch + "</td>";
                mhtml += "<td style='display:none;'>";
                $('#retail-order-staff').children('option:selected').each(function() {
                    if($(this).val()!==""){
                        mhtml += $(this).val();
                    }
                });
                mhtml += "</td>";
                mhtml += "<td>";
                $('#retail-order-staff').children('option:selected').each(function() {
                    if($(this).val()!==""){
                        mhtml += $(this).text();
                    }
                });
                mhtml += "</td>";

                mhtml += '<td class="qty" stockfrom="'+ stockfrom +'">' + qty + '</td>';
                mhtml += '<td class="price"><input onchange="price_by_product(this.value, \''+parseInt(product_id)+'\');" name="price" class="decimal" style="border:none;" value="' + price + '"></td>';
                
                mhtml += '<td style="text-align:right;">'+ parseFloat(price)*parseFloat(qty) +'</td>';
                mhtml += '<td class="discount" unit_discount="'+(parseFloat(price)*parseFloat($("#franchise_discount").val()))/100+'" style="text-align:right;"><input read type="text"  onblur="discount_by_product(this.value, \''+parseInt(product_id)+'\');" class="numeric discount_by_product" name="discount_by_product" id="discount_by_product'+product_id+'" style="text-align:right; border: none;" value="'+ ((parseFloat(price)*parseFloat($("#franchise_discount").val()))/100)*parseFloat(qty) +'"></td>';
               
                mhtml += '<td discounted_price="'+ (parseFloat(price)-(parseFloat(price)*parseFloat($("#franchise_discount").val()))/100)*parseFloat(qty) +'" style="text-align:right;"><?php echo CURRENCY_CODE;?>.<span class="combat" id="unitcost'+product_id+'">' + (parseFloat(price)-(parseFloat(price)*parseFloat($("#franchise_discount").val()))/100)*parseFloat(qty)  + '</span><input type="hidden" name="orignal_product_price" id="orignal_product_price'+product_id+'" value="' + (parseFloat(price)-(parseFloat(price)*parseFloat($("#franchise_discount").val()))/100) * parseFloat(qty)  + '"></td>'
                
                if(product_type=='Subscription'){
                    $("#month").show();
                    $("#year").show();
                    mhtml += '<td class="month" style="text-align:left;">';
                    mhtml += '<select>';
                    <?php foreach($months as $month){?>
                    mhtml += '<option value="<?php echo $month['id_months'];?>"><?php echo $month['month_name'];?></option>';
                    <?php } ?>                    
                    mhtml += '</select>';
                    mhtml += '</td>';
                    var d = new Date();
                    var p = d.getFullYear() - 1;
                    var c = d.getFullYear();
                    var n = d.getFullYear() + 1;
                    mhtml += '<td class="year" style="text-align:left;">';
                    mhtml += '<select>';
                    mhtml += '<option value="'+ p +'">'+ p +'</option>';
                    mhtml += '<option selected="selected" value="'+ c +'">'+ c +'</option>';
                    mhtml += '<option value="'+ n +'">'+ n +'</option>';
                    mhtml += '</select>';
                    mhtml += '</td>';
                } else if($("#month").is(':visible')){
                    mhtml += '<td class="month" style="text-align:left;"></td>';
                    mhtml += '<td class="year" style="text-align:left;"></td>';
                }
    
                mhtml += '<td ><span class="label label-danger" onclick="removebyrow(\'' + product_id + '\');" style="cursor:pointer">x</span></td>';
                mhtml += "</tr>";
        
       
                $("#order-product-list tbody").append(mhtml);
                update_total();
                $("#order-customer-qty").val('1');
                $("#retail-order-staff").val('');
                //$('#retail-order-products').val('select');
               
            }
        }
    }
    

    
    
    
    function removebyrow(val) {
       // console.log(val);
        $('#order-product-list').find("td.id").each(function(index) {
        //    console.log($(this).attr("row"));
            if ($(this).attr("row") === val) {
                $(this).closest('tr').remove();
            }
        });
        update_total();
    }
    
    function removeproduct(val) {
        $('#order-product-list').find("td.id").each(function(index) {
            if ($(this).html() == val) {
                $(this).closest('tr').remove();
            }
        });
        update_total()
    }
    
    function retail_getstaff() {

        $('#retail-order-staff').html('<option></option>');
        
        $.ajax({
            type: 'POST',
            data:{param:'none'},
            //url: 'Scheduler_controller/getAllStaff',
            url: '<?php echo base_url().'Scheduler_controller/getAllStaff'; ?>',
            dataType: "json",
            cache: false,
            async: true,
            success: function(data) {
                for (x = 0; x < data.length; x++) {
                    if(data[x]['staff_active'] == "Y"){
                        $('#retail-order-staff').append('<option value=' + data[x]['id_staff'] + '>' + data[x]['staff_fullname'] + '</option>');
                       
                    }
                }
            }
        });

    }
  
    function retail_getproducts() {
       // console.log($('#checkboxall').is(':checked'));
        var businessid=<?php echo $this->session->userdata('businessid');?>;
        if($('#checkboxall').is(':checked')){
            businessid="";
        }
        
        $("#retail-order-products").select2({
            ajax: {
              url: '<?php echo base_url().'product_controller/getproducts'; ?>',
              dataType: 'json',
              quietMillis: 1000,
              data: function (term, page) {
                  
                return {
                    productname: term, // search term
                    page_limit: 30, // page size
                    page: page, // page number
                    businessid: businessid
                };
              },
              results: function (data, page) {
                  
                    var more = (page * 30) < data.length;
                    return {results: data, more: more};
                }
              },
            escapeMarkup: function (m) { return m; }, // let our custom formatter work
            minimumInputLength: 1,
            formatResult: function (option) {
                return option.business_brand_name + ' - ' + option.product+ ' - ' + option.mcategory + ' ' + option.qty_per_unit + ' ' + option.measure_unit + ' - Batch: ' + option.batch + ' ('+ option.business_store +': ' + option.instock +') ';
            },
            formatSelection: function (option) {
                return option.business_brand_name + ' - ' + option.product+ ' - ' + option.mcategory + ' ' + option.qty_per_unit + ' ' + option.measure_unit + ' - Batch: ' + option.batch + ' ('+ option.business_store +': ' + option.instock+')' ;
            }
          });
        
    }
    
    function price_by_product(val, productid) {
        var result = 0;
        var total=0;
       $('#ordertbl tr').each(function(row, tr) {
            
            var product = $(tr).find('td:eq(1)').text();
            if (product === productid) {
                var qty = $(tr).find('td:eq(8)').text();
                var price = $(tr).find('td:eq(9) input').val();
                var discount = $(tr).find('td:eq(11) input').val();;
                console.log(qty);
                console.log(price);
                console.log(discount);
                
                result= (parseFloat(price)*parseFloat(qty))-parseFloat(discount);
                total=parseFloat(price)*parseFloat(qty);
               // console.log(result);
                $(tr).find('td:eq(10)').text(total);
                $(tr).find('td:eq(12) span').text(result);
                $(tr).find('td:eq(12)').attr('discounted_price', result);
                
               // $(tr).find('td:eq(10)').attr('unit_discount', discount);
            }
        });
        
        update_total();
    }
    
    
     function discount_by_product(val, productid) {
        var result = 0;
        var total=0;
       $('#ordertbl tr').each(function(row, tr) {
            
            var product = $(tr).find('td:eq(1)').text();
            if (product === productid) {
                var qty = $(tr).find('td:eq(8)').text();
                var price = $(tr).find('td:eq(9) input').val();
                var discount = val;
               // console.log(qty);
              //  console.log(price);
               // console.log(discount);
                
                result= (parseFloat(price)*parseFloat(qty))-parseFloat(discount);
                total=parseFloat(price)*parseFloat(qty);
               // console.log(result);
                $(tr).find('td:eq(10)').text(total);
                $(tr).find('td:eq(12) span').text(result);
                $(tr).find('td:eq(12)').attr('discounted_price', result);
                
                $(tr).find('td:eq(11)').attr('unit_discount', discount);
            }
        });
        
        update_total();
    }
    
    function update_total(){
       
        var theTotal = 0;
        var theDiscount=0;
        $("table td:nth-child(13) .combat").each(function () {
            
            var val = $(this).text();//.replace(" ", "").replace(",-", "");
            theTotal += parseFloat(val);
        });
        $("table td:nth-child(12) .discount_by_product").each(function () {
            
            var disc = $(this).val();//.replace(" ", "").replace(",-", "");
            theDiscount += parseFloat(disc);
        });

        

        $('#totalvalue').val(Math.round(theTotal));
        $('#totaldiscount').val(Math.round(theDiscount));
     
    }
    
    </script>
    
   