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

        <div class="row" id="divselection">
            <div class="col-sm-12">
                <div class="card-box ">
                    <h4 class="header-title m-t-0 m-b-30">Selection:</h4>
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="row">
                                <div class="col-lg-4">
                                    <div class="row">
                                        <div class="col-lg-12"> <label class="control-label">1. Select Report</label></div>
                                    </div>
                                    <div class="row">
                                        <div class="col-lg-12"> 
                                            <select id="selectreport" onchange="reportchanged();" class="form-control">
                                                <option value="select">Select</option>
                                                <?php if($this->session->userdata('role')!=="Store Manager"){?>
                                                
                                                <optgroup label='Appointments'>
                                                    <option value="cancelled_visits">Canceled Appointments</option>
                                                    <option value="open_visits">Appointments</option>
                                                    <option value="customer_profile">Customer Profiles</option>
                                                    <option value="new_customers">New Customers</option>
                                                    <option value="new_customer_invoices">New Customer Details</option>
                                                    <option value="returning_customers">Returning Customers</option>
                                                    <option value="careof_customers">CareOf Customers</option>
                                                    <option value="sharedcustomers">Shared Customers</option>
                                                    <option value="onlineappointments">Online Appointments</option>
                                                    <option value="appointmentcreations">Operator Wise Invoices Creation</option>
                                                 </optgroup>   
                                                <optgroup label='Sales'>
                                                    <option value="sales">Sales Details</option>
                                                    <option value="msales">Monthly Sales</option>
    <!--                                                <option value="ssales">Services Sale</option>-->
                                                    <option value="psales">Products Sale Summary</option>
                                                    <option value="psaled">Products Sale Details</option>
                                                    <!--<option value="sscategory">Service Sales By Category</option>-->
                                                    <option value="ssales">Services Sale Summary</option>
                                                    <option value="ssales_dept">Services Sale Departmental</option>
                                                    <option value="ssaled">Services Sale Details</option>
                                                    <option value="voucher">Vouchers Sold</option>
                                                    <option value="cash_register">Cash Register</option>
                                                    <option value="payment_breakup">Payment Breakup</option>
                                                    <option value="bank_payments">Direct Bank Payments</option>
<!--                                                    <option value="payment_breakup_services">Payment Breakup Services</option>
                                                    <option value="payment_breakup_sale">Payment Breakup Retail</option>-->
                                                    <option value="receivables">Receivables For Open Visits</option>
                                                    <option value="advance_collected">Advance Collected</option>
                                                    <option value="retained_amount">Retained Amount</option>
                                                    <option value="retained_used">Retained Amount Used</option>
                                                    <option value="recoverinvoices">Open Recovery Invoices</option>
                                                    <option value="loyaltyredemption">Loyalty Redemption</option>
                                                    
                                                </optgroup>
                                                <?php } ?>    
                                                <optgroup label='Retail & Stock'>
                                                    <option value="pusages">Product Usage Summary</option>
                                                    <option value="stock_status">Stock Status</option>
                                                    <option value="stock_status_brand">Stock Status By Brand</option>
                                                                                                 
                                                    <option value="dispatch">Day Wise Product Dispatches</option>
                                                    <option value="dispatch_details">Dispatch Note Details</option>
                                                    <option value="dispatch_against_requests">Dispatches Against Visits</option>
                                                    <?php if($this->session->userdata('role')=="Store Manager"){?>   
                                                        <option value="utilization_summary">Staff Utilization Summary</option>
                                                        <option value="utilization">Staff Utilization (single day)</option>
                                                        <option value="psales">Products Sale Summary</option>
                                                        <option value="psaled">Products Sale Details</option>
                                                        <!--<option value="sscategory">Service Sales By Category</option>-->
                                                        <option value="ssales">Services Sale Summary</option>
                                                        <option value="ssaled">Services Sale Details</option>
                                                        <option value="voucher">Vouchers Sold</option>
                                                    <?php } ?>
                                                    
                                                </optgroup>
                                                <?php if($this->session->userdata('role')!=="Store Manager"){?>    
                                                <optgroup label='Staff'>
                                                    <!--<option value="attendance">Attendance</option>-->
                                                    <option value="commissions">Service Commissions</option>
                                                    <option value="retailcommissions">Retail Commissions</option>
                                                    <option value="staffperf">Staff Performance</option>
                                                    <option value="staff_retail_sale_summary">Staff Product Sale</option>   
                                                    <option value="requested">Requested Staff</option>
                                                    <option value="utilization_summary">Staff Utilization Summary</option>
                                                    <option value="utilization">Staff Utilization (single day)</option>
                                                    <option value="staff_blocking_summary">Staff Blocking Summary</option>
                                                    <option value="staff_blocking">Staff Blocking Detail</option>
                                                    <option value="crosssell">Staff Cross Sell</option>
                                                    
                                                </optgroup>
                                                
                                                <optgroup label='Invoices'>
                                                    <option value="invoices">Invoices</option>
                                                    <option value="recoveries">Recoveries</option>
                                                    <option value="cancelledinvoices">Cancelled Invoices</option>
                                                    <option value="cancelledadvances">Cancelled Advances</option>
                                                </optgroup>
                                                
                                                <optgroup label='Other Reports'>
                                                    <option value="taxes">Taxes Collected</option>
                                                    <option value="discount">Discounts</option>
                                                    <option value="bad_debts">Bad Debts</option>
                                                    <option value="expenses">Expenses</option>
                                                   
                                                </optgroup>    
                                                <?php } ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-lg-4">
                                    <div class="row">
                                        <div class="col-lg-12"> <label class="control-label">2. Select Dates</label></div>
                                    </div>
                                    <div class="row">
                                        <div class="col-lg-12"> 
                                            <div id="reportrange" class="form-control">
                                                <i class="glyphicon glyphicon-calendar fa fa-calendar"></i>
                                                <span></span>
                                                
                                            </div>
                                            <p class="text-sm">Select a maximum of 6 months at a time</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-lg-4">
                                    <div class="row">
                                        <div class="col-lg-12"> <label class="control-label">3. Run Report</label></div>
                                    </div>
                                    <div class="row">
                                        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6" > 
                                            <button type="button" onclick="runreport();" class="btn btn-pink btn-bordred waves-effect w-md waves-light m-b-5">Run</button>
                                        </div>
                                        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6"><i id="cog" class="fa fa-spin fa-cog" style="display:none; font-size:26px;width: auto;margin-right: 10px;"></i></div>
                                    </div>
                                </div>
                            </div>
                            <div class="row m-t-5" id="storeselection" style="display:none;">
                                <div class="col-md-12"><strong class="text-info">Optional Filters:</strong></div>
                                <div class="col-md-4" id="stores" >
                                    <div class="row">
                                        <div class="col-md-12">
                                            <label for="selectstores">Select Stores</label>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-12">
                                            <select class="form-control" id="selectstores">
                                                <?php if($this->session->userdata("ho")=='Yes'){?>
                                                <option value="">All</option>
                                                <?php } ?>
                                                <?php foreach($stores as $store){ ?>
                                                <?php if($this->session->userdata("ho")=='No'){?>
                                                <?php if($store['id_business']==$this->session->userdata['businessid']){?>
                                                    <option <?php if($store['id_business']==$this->session->userdata['businessid']){echo 'selected="selected"';}?> value="<?php echo $store['id_business_stores']?>"><?php echo $store['business_store'];?></option>
                                                <?php } ?>
                                                <?php } else { ?>
                                                    <option <?php if($store['id_business']==$this->session->userdata['businessid']){echo 'selected="selected"';}?> value="<?php echo $store['id_business_stores']?>"><?php echo $store['business_store'];?></option>
                                                <?php } ?>
                                                <?php } ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row m-t-5" id="productselection" style="display:none;">
                                <div class="col-md-12"><strong class="text-info">Optional Filters:</strong></div>
                                <div class="col-md-4" id="productbrands" >
                                    <div class="row">
                                        <div class="col-md-12">
                                            <label for="selectbrands">Select Brand</label>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-12">
                                            <select class="form-control" id="selectbrands">
                                                <?php foreach($brands as $brand){ ?>
                                                <option value="<?php echo $brand['id_business_brands']?>"><?php echo $brand['business_brand_name'];?></option>
                                                <?php } ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4" id="producttype">
                                    <div class="row">
                                        <div class="col-md-12">
                                             <label for="selectbrands">Select Product Type</label>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-12">
                                            <select class="form-control" id="selectproducttype">
                                                <option value="0">All</option>
                                                <option value="n">Retail</option>
                                                <option value="y">Professional</option>
                                            </select>
                                         </div>
                                    </div>                                    
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="row">
                                        <div class="col-md-12">
                                             <label for="selectbrands">Select Department</label>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-12">
                                            <select class="form-control" id="selectbrandstores">
                                                <?php if($this->session->userdata("ho")=='Yes'){?>
                                                <option value="">All</option>
                                                <?php } ?>
                                                <?php foreach($stores as $store){ ?>
                                                <?php if($this->session->userdata("ho")=='No'){?>
                                                <?php if($store['id_business']==$this->session->userdata['businessid']){?>
                                                    <option <?php if($store['id_business']==$this->session->userdata['businessid']){echo 'selected="selected"';}?> value="<?php echo $store['id_business_stores']?>"><?php echo $store['business_store'];?></option>
                                                <?php } ?>
                                                <?php } else { ?>
                                                    <option <?php if($store['id_business']==$this->session->userdata['businessid']){echo 'selected="selected"';}?> value="<?php echo $store['id_business_stores']?>"><?php echo $store['business_store'];?></option>
                                                <?php } ?>
                                                <?php } ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                
                            </div>
                            <div class="row m-t-5" id="roleselection" style="display:none;">
                                <div class="col-md-4" id="roleid">
                                    <label for="selectrole">Select the Role Type</label>
                                    <select id="selectrole" class="form-control">
                                        <option value="18">Call Center Op</option>
                                        <option value="2">Receptionist</option>
                                        <option value="0">Rest POS</option>

                                    </select>
                                </div>
                            </div>
                            <div class="row m-t-5" id="serviceselection" style="display:none;">
                                <div class="col-md-12"><strong class="text-info">Optional Filters:</strong></div>
                                <div class="col-md-4" id="servicetype">
                                    <div class="row">
                                        <div class="col-md-12">
                                             <label for="selectservicetype">Select Service Type</label>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-12">
                                            <select onchange="servicetypechange();" class="form-control" id="selectservicetype">
                                                <option value="0">All</option>
                                                <?php foreach($servicetypes as $servicetype){ ?>
                                                <option flag="<?php echo $servicetype['flag']; ?>" value="<?php echo $servicetype['id_service_types']; ?>"><?php echo $servicetype['service_type'];?></option>
                                                <?php } ?>
                                            </select>
                                         </div>
                                    </div>                                    
                                </div>
                                <div class="col-md-4" id="servicecategory">
                                    <div class="row">
                                        <div class="col-md-12">
                                             <label for="selectservicecategory">Select Service Category</label>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-12">
                                            <select onchange="servicecategorychange()" class="form-control" id="selectservicecategory">
                                                
                                            </select>
                                         </div>
                                    </div>                                    
                                </div>
                                
                                <div class="col-md-4" id="service">
                                    <div class="row">
                                        <div class="col-md-12">
                                             <label for="selectservice">Select Service</label>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-12">
                                            <select class="form-control" id="selectservice">
                                               
                                            </select>
                                         </div>
                                    </div>                                    
                                </div>
                            </div>
                            <div class="row m-t-5" id="staffselection" style="display:none;">  
                                 
                                <div class="col-md-4" id="staff">
                                    <div class="row">
                                        <div class="col-md-12">
                                             <label for="selectstaff">Select Staff</label>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-12">
                                            <select class="form-control" id="selectstaff">
                                                 <option value="0">All</option>
                                                <?php foreach($staff as $s){ ?>
                                                <option value="<?php echo $s['id_staff']?>"><?php echo $s['staff_fullname'];?></option>
                                                <?php } ?>
                                            </select>
                                         </div>
                                    </div>                                    
                                </div>
                            </div>
                            
                            <div class="row m-t-5" id="businessselection" style="display:none;">  
                                 
                                <div class="col-md-4" id="business">
                                    <div class="row">
                                        <div class="col-md-12">
                                             <label for="selectbusiness">Select Business</label>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-12">
                                            <select <?php if($this->session->userdata("ho")=='No'){echo "disabled";}?> class="form-control" id="selectbusiness">
                                                 <option value="0">All</option>
                                                <?php foreach($business as $b){ ?>
                                                <option value="<?php echo $b['id_business']?>"><?php echo $b['business_name'];?></option>
                                                <?php } ?>
                                            </select>
                                         </div>
                                    </div>                                    
                                </div>
                            </div>
                            
                            <div class="row m-t-5" id="customerselection" style="display:none;">  
                                 
                                <div class="col-md-4" id="customer">
                                    <div class="row">
                                        <div class="col-md-12">
                                             <label for="selectcustomer">Select Customer</label>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-12">
                                            <input class='form-control' id="selectcustomer"/>
                                         </div>
                                    </div>                                    
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-12">
                <div class="card-box">
                    <!--<h4 class="header-title m-t-0 m-b-30">&nbsp;</h4>-->
                    <p class="">
                        <button onclick="attendance_view();" class="btn btn-primary waves-effect waves-light m-b-5 atview"> <span>Month View</span> <i class="fa fa-calendar m-l-5"></i> </button>
                    </p>
                    
                    <div class="row">
                    <div id="tableshow" class="table-responsive">
                        <table class="table table-bordered dt-responsive nowrap record" cellspacing="0" width="100%">
                            <tr><td>Summary:</td>
                                <td style="text-align: right">Total</td>
                                <td id="summary"></td>
                            </tr>
                        </table>
                        <table id="tblreport" class="table table-striped table-bordered dt-responsive nowrap record" cellspacing="0" width="100%">
                            
                            <thead>
                                
                                <tr>
                                    <th>Ready</th>
                                </tr>
                            </thead>
                            <tbody>
                            <td>Run report</td>
                            </tbody>
                            <tfoot></tfoot>
                        </table>
                    </div>
                    <div id="otherview" class="table-responsive">
                        <div class="row">
                            <div class="col-lg-12">
                                <table id="monthview" class="table table-striped table-bordered dt-responsive nowrap " cellspacing="0" >
                                    <thead>
                                        <tr>
                                            <th>Month</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    <td>Run Month</td>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    </div>
                </div>
            </div><!-- end col -->
        </div>
        <!-- end row -->

        <script type="text/javascript">

            var startdate = '';
            var enddate = '';
            $(document).ready(function() {
                
                
                
                $('.atview').css('display', 'none');
                $('#otherview').css('display', 'none');
                //$('[data-toggle="tooltip"]').tooltip();

                $(document).on('click', '.usage_details_btn', function() {

                    var product_id = $(this).attr('product_id');
                    var unit = $(this).attr('unit');
                    var total_qty = $(this).attr('total_qty');
                    var units_used = $(this).attr('units_used');
                    var container_type = $(this).attr('container_type');
                    var service_count = $(this).attr('service_count');
                   
                    
                    $('#tableshow').css('display', 'block');
                    $('#otherview').css('display', 'none');
                    $('.atview').css('display', 'none');

                    $.ajax({
                        type: 'POST',
                        url: 'report_controller/product_usage_details',
                        data: {product_id: product_id, startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                        success: function(response) {
                            var data = $.parseJSON(response);
                            if (data.length > 0) {
                                var hhtml = "<tr><th>Invoice</th>" +
                                        "<th>Service</th>" +
                                        "<th>Product</th>" +
                                        "<th>Customer</th>" +
                                        "<th>Date</th>" +
                                        
                                        "<th>Product Usage</th>" +
                                        "<th>Product Measurement Unit</th>" +
                                        "</tr>";
                                var html = "";
                                var fhtml = "";
                                for (var i = 0; data.length > i; i++) {
                                    
                                    html += '<tr>';
                                    html += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ data[i]['id_invoice'] +'">' + data[i].id_invoice + '</td>';
                                    html += '<td>' + data[i].service_name  + '</td>';
                                    html += '<td>' + data[i].product_name + ' - ' + data[i].category +  '</td>';
                                    html += '<td>' + data[i].customer_name + '</td>';
                                    html += '<td>' + data[i].Date + '</td>';
                                    
                                    html += '<td>' + data[i].product_qty + '</td>';
                                    html += '<td>' + data[i].product_unit + '</td>';
                                    html += '</tr>';
                                }
                                //html += '<tr><td colspan="7"></td></tr>';
                                html += '<tr>';
                                html += '<td>Total Services : ' + service_count + '</td>';
                                html += '<td></td>';
                                html += '<td></td>';
                                html += '<td></td>';
                                
                                html += '<td></td>';
                                html += '<td>Total Usage : ' + total_qty + ' ' + unit + '</td>';
                                html += '<td>Units Used : ' + units_used + ' ' + container_type + '(s)</td>';
                                html += '</tr>';

                                $("#tblreport").dataTable().fnDestroy();
                                $("#tblreport thead").html('');
                                $("#tblreport tbody").html('');
                                $("#tblreport tfoot").html('');
                                $("#tblreport thead").append(hhtml);
                                $("#tblreport tbody").append(html);
                                //$("#tblreport tfoot").append(fhtml);
                                $.fn.dataTable.moment('DD-MM-YYYY');
                                $('#tblreport').DataTable({
                                    lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                                    stateSave: true, fixedHeader: {header: true},
                                    <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                                    buttons: [{extend: "copy", className: "btn-sm"}, 
                                        {extend: "csv", className: "btn-sm"}, 
                                        
                                        {extend: "pdf", className: "btn-sm"}, 
                                        {extend: "print", className: "btn-sm"}],
                                    <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                                });

                            }
                        }
                    });

                });

                $(document).on('click', '.commission_btn', function() {

                    var staff_id = $(this).attr('staff_id');
                    var total=0;
                    var paid=0; 
                    var totalprice=0;
                    $('#tableshow').css('display', 'block');
                    $('#otherview').css('display', 'none');
                    $('.atview').css('display', 'none');

                    $.ajax({
                        type: 'POST',
                        url: 'report_controller/commission_details',
                        data: {staff_id: staff_id, startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                        success: function(response) {
                            var data = $.parseJSON(response);
                            if (data.length > 0) {
                                var hhtml = "<tr>" +
                                        "<th>Staff Name</th>" +
                                        "<th>Helper</th>" +
                                        "<th>Service Name</th>" +
                                        "<th>Customer Visit</th>" +
                                        "<th>Invoiced</th>" +
                                        "<th>Invoice ID</th>" +
                                        "<th>Price</th>" +
                                        "<th>Paid Amount</th>" +
                                        "<th>@</th>" +
                                        "<th>Commission</th>" +
                                        "</tr>";
                                var html = "";
                                for (var i = 0; data.length > i; i++) {
                                    
                                    html += '<tr>';
                                    html += '<td>' + data[i].staff_fullname + '</td>';
                                    html += '<td>' + data[i].additional_staff + '</td>';
                                    html += '<td>' + data[i].service_type + ' ' + data[i].service_category + ' ' + data[i].service_name + '</td>';
                                    html += '<td>' + data[i].customer_visit_date + '</td>';
                                    html += '<td>' + data[i].staff_service_date + '</td>';
                                    html += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ data[i].invoice_id +'">' + data[i].invoice_id + '</a> <span class="text-danger">'+ data[i].reference_invoice_number.substr(data[i].reference_invoice_number.length-4,data[i].reference_invoice_number.length) +'</span></td>';
                                    html += '<td>' + data[i].final_price + '</td>';
                                    totalprice= totalprice+parseFloat(data[i].final_price);
                                    paid = paid+parseFloat(data[i].paid);
                                    html += '<td>' + data[i].paid + '</td>';
                                    var comm=0;
                                    if( data[i].additional_staff =='No'){
                                        html += '<td>' + data[i].staff_commission + ' %</td>';
                                        comm =parseFloat(data[i].paid) * parseFloat(data[i].staff_commission)/100;
                                    } else {
                                        html += '<td>' + data[i].helper_commission + ' %</td>';
                                        comm =parseFloat(data[i].paid) * parseFloat(data[i].helper_commission)/100;
                                    }
                                    
                                    //html += '<td>' + comm.toFixed(2)  + '</td>';
                                    html += '<td>' + data[i]['invoice_commission']  + '</td>';
                                    //total = total+comm;
                                    total = total+ parseFloat(data[i]['invoice_commission']);
                                    html += '</tr>';
                                }
                                total=total.toFixed(2);
                                paid=paid.toFixed(2);
                                $("#tblreport").dataTable().fnDestroy();
                                $("#tblreport thead").html('');
                                $("#tblreport tbody").html('');
                                $("#tblreport tfoot").html('<tr><th colspan=6></th><th>'+totalprice.toFixed(2)+'</th><th>'+paid+'</th><th></th><th><strong>'+total+'</strong></th></tr>');
                                $("#tblreport thead").append(hhtml);
                                $("#tblreport tbody").append(html);
                                //$("#tblreport tfoot").append(fhtml);
                                
                                $("#summary").html(total.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
                                //$("#summary").html('');
                                $.fn.dataTable.moment('DD-MM-YYYY');
                                $('#tblreport').DataTable({
                                    lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                                    stateSave: true, fixedHeader: {header: true},
                                    <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                                    buttons: [{extend: "copy", className: "btn-sm"}, 
                                        {extend: "csv", className: "btn-sm"}, 
                                        {extend: "pdf", className: "btn-sm"}, 
                                        {extend: "print", className: "btn-sm"}
                                    ],
                                    <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                                });

                            }
                        }
                    });

                });
                
                 $(document).on('click', '.retail_commission_btn', function() {

                    var staff_id = $(this).attr('staff_id');
                    var total=0;
                    var paid=0; 
                    $('#tableshow').css('display', 'block');
                    $('#otherview').css('display', 'none');
                    $('.atview').css('display', 'none');

                    $.ajax({
                        type: 'POST',
                        url: 'report_controller/retail_commission_details',
                        data: {staff_id: staff_id, startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                        success: function(response) {
                            var data = $.parseJSON(response);
                            if (data.length > 0) {
                                var hhtml = "<tr>" +
                                        "<th>Staff Name</th>" +
                                        "<th>Product Name</th>" +
                                        "<th>Invoce Date</th>" +                                        
                                        "<th>Invoice ID</th>" +
                                        "<th>Price</th>" +
                                        "<th>Paid Amount</th>" +
                                        "<th>@</th>" +
                                        "<th>Commission</th>" +
                                        "</tr>";
                                var html = "";
                                for (var i = 0; data.length > i; i++) {
                                    var staff_commission=0;
                                    html += '<tr>';
                                    html += '<td>' + data[i].staff_fullname + '</td>';
                                    html += '<td>' + data[i].business_brand_name + ' ' + data[i].product + ' ' + data[i].qty_per_unit + ' ' + data[i].measure_unit +'</td>';
                                    html += '<td>' + data[i].invoice_date + '</td>';
                                   
                                    html += '<td><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ data[i].invoice_id +'">' + data[i].invoice_id + '</a> <span class="text-danger">'+ data[i].reference_invoice_number.substr(data[i].reference_invoice_number.length-4,data[i].reference_invoice_number.length) +'</span></td>';
                                    html += '<td style="text-align:right;">' + data[i].discounted_price + '</td>';
                                    paid = paid+parseFloat(data[i].paid);
                                    html += '<td style="text-align:right;">' + data[i].paid + '</td>';
                                    html += '<td style="text-align:right;">' + data[i].commission + ' %</td>';
                                    
                                    
                                    staff_commission = parseFloat(data[i].paid) * data[i].commission/100;
                                    staff_commission =  data[i].staff_commission;
                                    //html += '<td style="text-align:right;">' +  staff_commission  + '</td>';
                                   
                                    html += '<td style="text-align:right;">' +  data[i]['invoice_commission']  + '</td>';

                                    html += '</tr>';
                                    //total = total + staff_commission;
                                    total = total + parseFloat(data[i]['invoice_commission']);
                                }
                                //total=total.toFixed(2);
                                paid=paid.toFixed(2);
                                $("#tblreport").dataTable().fnDestroy();
                                $("#tblreport thead").html('');
                                $("#tblreport tbody").html('');
                                $("#tblreport tfoot").html('<tr><th colspan=5></th><th style="text-align:right;">'+paid+'</th><th></th><th style="text-align:right;"><strong>'+total+'</strong></th></tr>');
                                $("#tblreport thead").append(hhtml);
                                $("#tblreport tbody").append(html);
                                //$("#tblreport tfoot").append(fhtml);
                                
                                $("#summary").html(total.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
                                //$("#summary").html('');
                                $.fn.dataTable.moment('DD-MM-YYYY');
                                $('#tblreport').DataTable({
                                    lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                                    stateSave: true, fixedHeader: {header: true},
                                    <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                                    buttons: [{extend: "copy", className: "btn-sm"}, 
                                        {extend: "csv", className: "btn-sm"}, 
                                        {extend: "pdf", className: "btn-sm"}, 
                                        {extend: "print", className: "btn-sm"}
                                    ],
                                    <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                                });

                            }
                        }
                    });

                });
                
                $.fn.dataTable.moment('DD-MM-YYYY');
                $('#tblreport').DataTable({
                    <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                    buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, 
                        {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                    <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                });

                $('#monthview').DataTable({
                    <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                    buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                            extend: "excel",
                            className: "btn-sm"
                        }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                    <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                });

                //$('#reportrange span').html(moment().subtract(29, 'days').format('MMMM D, YYYY') + ' - ' + moment().format('MMMM D, YYYY'));

                $('#reportrange').daterangepicker({
                    format: 'MM/DD/YYYY',
                    startDate: moment().subtract(15, 'days'),
                    endDate: moment(),
                    minDate: '01/01/2012',
                    maxDate: '12/31/2099',
                    dateLimit: {
                        days: 183
                    },
                    showDropdowns: true,
                    showWeekNumbers: true,
                    timePicker: false,
                    timePickerIncrement: 1,
                    timePicker12Hour: true,
                    ranges: {
                        'Today': [moment(), moment().add(1, 'days')],
                        'Yesterday': [moment().subtract(1, 'days'), moment()],
                        'Last 7 Days': [moment().subtract(6, 'days'), moment().add(1, 'days')],
                        'Last 30 Days': [moment().subtract(29, 'days'), moment().add(1, 'days')],
                        'This Month': [moment().startOf('month'), moment().endOf('month')],
                        'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                        'Last Two Months': [moment().subtract(2, 'month').startOf('month'), moment().subtract('month').endOf('month')],
                        'Last Four Months': [moment().subtract(4, 'month').startOf('month'), moment().subtract('month').endOf('month')]
                    },
                    opens: 'left',
                    drops: 'down',
                    buttonClasses: ['btn', 'btn-sm'],
                    applyClass: 'btn-success',
                    cancelClass: 'btn-default',
                    separator: ' to ',
                    locale: {
                        applyLabel: 'Submit',
                        cancelLabel: 'Cancel',
                        fromLabel: 'From',
                        toLabel: 'To',
                        customRangeLabel: 'Custom',
                        daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
                        monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
                        firstDay: 1
                    }
                }, function(start, end, label) {
                    //console.log(start.toISOString(), end.toISOString(), label);
                    startdate = start;
                    enddate = end;
                    $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
                });
                
                $('#selectreport').select2();
            });
            //TableManageButtons.init();

            
            function reportchanged(){
            
                if ($("#selectreport option:selected").val()=='stock_status'){
                    $("#storeselection").css('display', 'block');
                    
                } else {
                    $("#storeselection").css('display', 'none');
                   
                }
            
                if ($("#selectreport option:selected").val()=='stock_status_brand'){
                    $("#productselection").css('display', 'block');
                    
                } else {
                    $("#productselection").css('display', 'none');
                   
                }
                if($("#selectreport option:selected").val()=='appointmentcreations' ){
                    $("#roleselection").css('display', 'block');
                }
                if ($("#selectreport option:selected").val()=='open_visits' || $("#selectreport option:selected").val()=='ssaled' ){
                    
                    $("#serviceselection").css('display', 'block');
                    $("#staffselection").css('display', 'block');
                } else {
                    
                    $("#serviceselection").css('display', 'none');
                    $("#staffselection").css('display', 'none');
                }
                
                if($("#selectreport option:selected").val()=='loyaltyredemption' || $("#selectreport option:selected").val()=='sharedcustomers'){
                     $("#customerselection").css('display', 'block');
                    enable_customers();
                } else {
                    $("#customerselection").css('display', 'none');
                }
                
                if ($("#selectreport option:selected").val()=='staff_blocking' || $("#selectreport option:selected").val()=='staff_blocking_summary'){
                    $("#staffselection").css('display', 'block');
                } else {
                     $("#staffselection").css('display', 'none');
                }
                
                
            }

            function servicetypechange(){
                $("#selectservicecategory").empty();
                $("#selectservice").empty();
                $.ajax({
                    type: 'POST',
                    url: 'service_controller/getServicesCategories',
                    data: {service_type_id: $("#selectservicetype option:selected").val(), flag: $("#selectservicetype option:selected").attr("flag")},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var html="<option value='0'>All</option>";
                        
                        for (x = 0; x < data.length; x++) {
                            html+="<option value='"+data[x]['id_service_category']+"' flag='"+data[x]['flag']+"' '>"+data[x]['service_category']+"</option>";
                        }
                        
                        $("#selectservicecategory").append(html);
                    }
                });
            }
            
            function servicecategorychange(){
                $("#selectservice").empty();
                $.ajax({
                    type: 'POST',
                    url: 'service_controller/getServicesByCategory',
                    data: {id_service_category: $("#selectservicecategory option:selected").val(), flag: $("#selectservicecategory option:selected").attr("flag")},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var html="<option value='0'>All</option>";
                        
                        for (x = 0; x < data.length; x++) {
                            html+="<option value='"+data[x]['id_business_services']+"'>"+data[x]['service_name']+"</option>";
                        }
                        
                        $("#selectservice").append(html);
                    }
                });
            }
                
            function runreport() {
                var reportname = $('#selectreport').val();
                //console.log(reportname);
                if (startdate == "" || enddate == "") {
                    swal({
                        title: "Select Date Range",
                        text: "Please select a date Range",
                        type: "warning",
                        confirmButtonText: 'OK!'
                    });
                    return false;
                }

                //console.log(startdate.format('YYYY-MM-DD') + ' ' + enddate.format('YYYY-MM-DD'));
                $("#summary").html('');
                if (reportname === 'sales') {
                    sales();
                } else if (reportname === 'msales') {
                    msales();
                } else if (reportname === 'sscategory') {
                    sscategory();
                } else if (reportname === 'ssales') {
                    ssales();
                } else if (reportname === 'ssales_dept') {
                    ssales_dept();
                } else if (reportname === 'ssaled') {
                    ssaled();
                } else if (reportname === 'staffperf') {
                    staffperf();
                } else if (reportname === 'psales') {
                    psales();
                } else if (reportname === 'psaled') {
                    psaled()
                } else if (reportname === 'pusages') {
                    pusages();
                } else if (reportname === 'invoices') {
                    invoices();
                } else if (reportname === 'recoveries') {
                    recoveries();
                } else if (reportname === 'cancelledinvoices') {
                    cancelledinvoices();
                } else if (reportname === 'cancelledadvances') {
                    cancelledadvances();
                } else if (reportname === 'commissions') {
                    commissions();
                } else if (reportname === 'retailcommissions') {
                    retailcommissions();
                } else if (reportname === 'taxes') {
                    taxes();
                } else if (reportname === 'attendance') {
                    attendance();
                } else if (reportname === 'discount') {
                    discount();
                } else if (reportname === 'voucher') {
                    voucher();
                } else if (reportname === 'bad_debts') {
                    bad_debts();
                } else if (reportname === 'stock_status') {
                    stock_status();
                } else if (reportname === 'stock_status_brand') {
                    stock_status_brand();
                } else if (reportname === 'expenses') {
                    expenses();
                }else if (reportname === 'dispatch') {
                    dispatch();
                }else if (reportname === 'dispatch_details') {
                    dispatch_details();
                }else if (reportname === 'dispatch_against_requests') {
                    dispatch_against_requests();
                }else if(reportname === 'cancelled_visits'){
                    cancelled_visits();
                }else if(reportname === 'open_visits'){
                    open_visits();
                }else if(reportname === 'customer_profile'){
                    customer_profile();
                }else if(reportname === 'new_customers'){
                    new_customers();
                }else if(reportname === 'new_customer_invoices'){
                    new_customer_invoices();
                }else if(reportname === 'returning_customers'){
                    returning_customers();
                }else if(reportname === 'advance_collected'){
                    advance_collected();
                }else if(reportname === 'retained_amount'){
                    retained_amount();
                }else if(reportname === 'retained_used'){
                    retained_used();
                }else if(reportname === 'cash_register'){
                    cash_register();
                }else if(reportname === 'payment_breakup'){ 
                    payment_breakup();
                }else if(reportname === 'bank_payments'){ 
                    bank_payments();
                }else if(reportname === 'payment_breakup_services'){ 
                    payment_breakup_services();        
                }else if(reportname === 'payment_breakup_sale'){ 
                    payment_breakup_sale();        
                } else if(reportname === 'staff_retail_sale_summary'){
                    staff_retail_sale_summary();
                } else if(reportname === 'receivables'){
                    receivables();
                } else if(reportname === 'recoverinvoices'){
                    recoverinvoices();
                } else if (reportname === 'loyaltyredemption'){
                    loyaltyredemption();
                } else if (reportname === 'sharedcustomers'){
                    sharedcustomers();
                } else if (reportname === 'onlineappointments'){
                    onlineappointments();
                } else if (reportname === 'careof_customers'){
                    careof_customers();
                }else if (reportname === 'requested'){
                    requested();
                }else if (reportname === 'utilization'){
                    utilization();
                }else if (reportname === 'utilization_summary'){
                    utilization_summary();
                }else if (reportname === 'staff_blocking'){
                    staff_blocking();
                }else if (reportname === 'staff_blocking_summary'){
                    staff_blocking_summary();
                }else if (reportname === 'crosssell'){
                    crosssell();
                }else if (reportname === 'appointmentcreations'){
                    appointmentcreations();
                }
                
            }


            function appointmentcreations(){
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/operator_report',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD'), roleid: $("#selectrole option:selected").val()},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        //console.log(data);
                        var hhtml = "<tr><th>Visit</th><th>Created On</th><th>By</th><th>Invoice</th><th>Created On</th><th>Invoiced By</th><th>Customer Name</th><th>Customer Cell</th><th>Service Category</th><th>Service Type</th></tr>"
                        var mhtml="";
                        for (x = 0; x < data.length; x++) {
                            mhtml +="<tr>";
                            mhtml += '<td>'+ data[x].id_customer_visits +'</td>';
                            mhtml += '<td>'+ data[x].visit_created_on +'</td>';
                            mhtml += '<td>'+ data[x].visit_created_by +'</td>';
                            mhtml += '<td>'+ data[x].id_invoice +'</td>';
                            mhtml += '<td>'+ data[x].invoice_created_by +'</td>';
                            mhtml += '<td>'+ data[x].customer_name +'</td>';
                            mhtml += '<td>'+ data[x].customer_cell +'</td>';
                            mhtml += '<td>'+ data[x].service_category +'</td>';
                            mhtml += '<td>'+ data[x].service_type +'</td>';
                            mhtml += '<td>'+ data[x].paid_amount +'</td>';
                            mhtml += "</tr>";
                        }
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        
                         $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();
                    }
                });


            }

            function crosssell(){
                  $.ajax({
                    type: 'POST',
                    url: 'report_controller/crossselling_report',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var hhtml = "<tr><th>VisitID</th><th>InvoiceID</th><th>VisitDate</th><th>Customer</th><th>Cross Sold By</th><th>Serviced By</th><th>Service</th><th>Rate</th><th>FinalPrice</th></tr>";
                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            mhtml += '<tr>';
                            mhtml += '<td>'+ data[x].id_customer_visits +'</td>';
                            mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ data[x].invoice_id +'">' +  data[x].invoice_id + '</a></td>';
                            mhtml += '<td>'+ data[x].visit_date +'</td>';
                            mhtml += '<td>'+ data[x].customer_name +'</td>';
                            mhtml += '<td><strong>'+ data[x].cross_sold_by +'</strong></td>';
                            mhtml += '<td>'+ data[x].serviced_by +'</td>';
                            mhtml += '<td>'+ data[x].service_name +'</td>';
                            mhtml += '<td>'+ data[x].s_rate +'</td>';
                            mhtml += '<td>'+ data[x].final_price +'</td>';
                        }
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        
                         $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();
                    }
                });
                    
                
            }

            function sales() {
               
                $('#tableshow').css('display', 'block');
                $('.atview').css('display', 'none');
                $('#otherview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/sales',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var totalpaid=0;
                        var totalgross=0;
                        var totalbal=0;
                        var totaldiscount=0;
                        var cancel='';

                        var hhtml = "<tr><th>VisitDate</th><th>Invoiced</th><th>Invoice</th><th>Customer</th><th>Sale Type</th><th>Is Recovery?</th><th>Sub Total</th><th class='text-danger'>Discount</th><th>Gross</th><th>Taxes</th><th class='text-info'>Advance</th><th class='text-success'>Net Amount</th><th class='text-info'>Paid</th><th class='text-danger'>Balance</th><th>Remarks</th></tr>";

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            if(data[x]['invoice_status']=="valid"){
                                totalpaid=totalpaid+parseFloat(data[x]['paid']);
                                totalbal=totalbal+parseFloat(data[x]['balance']);
                                totaldiscount=totaldiscount+parseFloat(data[x]['Discount']);
                                totalgross=totalgross+parseFloat(data[x]['Gross']);
                                cancel='';
                            } else {
                                cancel='text-decoration: line-through;';
                            }
                            mhtml += '<tr>';
                            if(data[x]['reference_number']){
                                mhtml += '<td style="'+cancel+'">Recovery</td>';
                            } else if (data[x]['invoice_status']!=="valid"){ 
                                mhtml += '<td style="'+cancel+'" class="text-danger">Cancelled</td>';
                            } else {
                                mhtml += '<td style="'+cancel+'">' + data[x]['visit'] + '</td>';
                            }
                            mhtml += '<td style="'+cancel+'">' + data[x]['Invoiced'] + '</td>';
                            if(data[x]['Sale Type']=="service"){
                                mhtml += '<td style="'+cancel+'"><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ data[x]['invoice_id'] +'">' + data[x]['invoice_id'] + '</a></td>';
                            } else {
                                mhtml += '<td style="'+cancel+'"><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ data[x]['invoice_id'] +'">' + data[x]['invoice_id'] + '</a></td>';
                            }
                            mhtml += '<td style="'+cancel+'">' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td style="'+cancel+'">' + data[x]['Sale Type'] + '</td>';
                            var res = []; 
                            if(data[x]['reference_number'] && data[x]['reference_number']!=='bad debts'){res = data[x]['reference_number'].split("-")} else {res[2]=''};
                            if(data[x]['Sale Type']=="service"){                            
                                mhtml += '<td style="'+cancel+'"><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ res[2] +'">' + res[2] + '</a></td>';
                            } else {
                                mhtml += '<td style="'+cancel+'"><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ res[2] +'">' + res[2] + '</a></td>';
                            }
                            mhtml += '<td style="'+cancel+'">' + data[x]['Sub Total'] + '</td>';
                            mhtml += '<td style="'+cancel+'" class="text-danger">' + data[x]['Discount'] + '</td>';
                            mhtml += '<td style="font-weight:bold;">' + data[x]['Gross'] + '</td>';
                            //mhtml += '<td style="'+cancel+'">' + data[x]['Taxes'] + '</td>';
                            if(data[x]['reference_number']===''){
                                mhtml += '<td style="'+cancel+'">' + data[x]['Taxes'] + '</td>';
                            }else {
                                mhtml += '<td style="'+cancel+'">0</td>';
                                }
                            
                            mhtml += '<td class="text-info" style="font-weight:bold;">' + data[x]['advance'] + '</td>';
                            mhtml += '<td class="text-success" style="font-weight:bold;">' + data[x]['Net Amount'] + '</td>';
                            if(data[x]['invoice_status']=="valid"){
                                mhtml += '<td class="text-info" style="font-weight:bold;">' + data[x]['paid'] + '</td>';
                                mhtml += '<td class="text-danger" style="font-weight:bold;">' + data[x]['balance'] + '</td>';                           
                                mhtml += '<td>' + data[x]['discount_remarks'] + '</td>';
                            } else {
                                mhtml += '<td class="text-info" style="font-weight:bold; text-decoration: line-through;">0</td>';
                                mhtml += '<td class="text-danger" style="font-weight:bold; text-decoration: line-through;">0</td>';                           
                                mhtml += '<td>' + data[x]['cancelreason'] + '</td>';
                            }
                            mhtml += '</tr>';
                        }
                        

                        totaldiscount=totaldiscount.toFixed(2);
                        totalgross=totalgross.toFixed(2);
                        var fhtml="<tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th>"+totaldiscount.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</th><th>"+totalgross.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</th><th></th><th></th><th></th><th>"+totalpaid.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</th><th>"+totalbal.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",") +"</th><th></th></tr>"
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);
                       
                        $("#summary").html('Received: <strong class="text-info">'+ totalpaid.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '/-</strong>');//&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  Balance: <strong class="text-danger">' + totalbal.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '/-</strong>');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }

            function msales() {
            
                var totalpaid=0;
                
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/msales',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(alldata) {
                        var data = alldata['sales'];
                        var advance = alldata['advance'];
                        var voucher = alldata['voucher'];
                        var recoveries_total= alldata['recoveries_total'];
                        
                        var hhtml = "<tr><th>Month</th><th>Year</th><th>Gross</th><th class='text-danger'>Discount</th><th>Taxes</th><th>Advance Adjusted</th><th>Balance</th><th class='text-success'>Net Amount</th><th class='text-info'>(Invoices</th><th class='text-info'>+Recoveries</th><th class='text-info'>=Collection)</th><th>Advance</th><th>Voucher</th><th>Total</th></tr>";

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            
                            
                            
                            var totalrec = 0;
                            
                            mhtml += '<tr>';
                            mhtml += '<td><span class="label label-pink">' + data[x]['Month'] + '</span></td>';
                            mhtml += '<td><span class="label label-pink">' + data[x]['Year'] + '</span></td>';
                            mhtml += '<td>' + data[x]['Gross'] + '</td>';
                            mhtml += '<td class="text-danger">' + data[x]['Discount'] + '</td>';
                            mhtml += '<td>' + data[x]['Taxes'] + '</td>';
                            mhtml += '<td>' + data[x]['AdvanceAdj'] + '</td>';
                            mhtml += '<td>' + data[x]['balance'] + '</td>';
                            mhtml += '<td class="text-success" style="font-weight:bold;">' + data[x]['Net Amount'] + '</td>';
                            mhtml += '<td class="text-info" style="font-weight:bold;">' + parseFloat(data[x]['paid'])+ '</td>';
                            totalrec=totalrec+parseFloat(data[x]['paid']);
                            var none = true;
                            for (y = 0; y < recoveries_total.length; y++) {
                               if(recoveries_total[y]['Month']==data[x]['Month'] && recoveries_total[y]['Year']==data[x]['Year']){
                                    mhtml += '<td class="text-info" style="font-weight:bold;">' + recoveries_total[y]['paid_amount'] + '</td>';
                                    mhtml += '<td class="text-info" style="font-weight:bold;">' + (parseFloat(data[x]['paid'])+ parseFloat(recoveries_total[y]['paid_amount'])) + '</td>';
                                    totalrec=totalrec+parseFloat(recoveries_total[y]['paid_amount']);
                                    none=false;
                                } 
                            }
                            if(none==true){
                                mhtml += '<td class="text-info" style="font-weight:bold;">0</td>';
                                mhtml += '<td class="text-info" style="font-weight:bold;">'+parseFloat(data[x]['paid'])+'</td>';
                            }
                            
                            var none = true;
                            for (y = 0; y < advance.length; y++) {
                               if(advance[y]['Month']==data[x]['Month'] && advance[y]['Year']==data[x]['Year']){
                                    mhtml += '<td class="text-info" style="font-weight:bold;">' + advance[y]['TotalAdvance'] + '</td>';
                                    totalrec=totalrec+parseFloat(advance[y]['TotalAdvance']);
                                    none=false;
                                } 
                            }
                            if(none==true){
                                mhtml += '<td class="text-info" style="font-weight:bold;">0</td>';
                            }
                            
                            var none = true;
                            for (y = 0; y < voucher.length; y++) {
                               if(voucher[y]['Month']==data[x]['Month'] && voucher[y]['Year']==data[x]['Year']){
                                    mhtml += '<td class="text-info" style="font-weight:bold;">' + voucher[y]['TotalVoucher'] + '</td>';
                                    totalrec=totalrec+parseFloat(voucher[y]['TotalVoucher']);
                                    none=false;
                                } 
                            }
                            if(none==true){
                                mhtml += '<td class="text-info" style="font-weight:bold;">0</td>';
                            }
                            
                            mhtml += '<td class="text-danger" style="font-weight:bold;">' + totalrec + '</td>';
                            mhtml += '</tr>';
                            totalpaid=totalpaid + totalrec;
                        }

                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');
                        totalpaid=totalpaid.toFixed(2);
                       
                        $("#summary").html('Received: <strong class="text-info">'+ totalpaid.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '/-</strong>'); //&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  Balance: <strong class="text-danger">' + totalbal.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '/-</strong>');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }
            function sscategory(){
                var totalpaid=0;
                var totalbal=0;
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/category_sales',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var totalpaid=0;
                        var hhtml = "<tr><th>Type</th><th>Category</th><th>Count</th><th>Price</th><th>Service Discount</th><th>Invoice Discount</th><th class='text-success'>Discounted Price</th><th class='text-info'>Paid</th></tr>"; //<th class='text-danger'>Balance</th></tr>";
                        
                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
//                            if(data[x]['reference_number']==''){
//                            totalpaid=totalpaid+parseFloat(data[x]['paid']);} else {
//                            totalrecovery=totalrecovery+parseFloat(data[x]['paid']);}
                            mhtml += '<tr>';
                          
                            mhtml += '<td>' + data[x]['service_type'] + '</td>';
                            mhtml += '<td>' + data[x]['service_category'] + '</td>';
                            mhtml += '<td>' + data[x]['services'] + '</td>';
                            mhtml += '<td>' + data[x]['price'] + '</td>';
                            mhtml += '<td class="text-danger">' + data[x]['discount'] + '</td>';
                            mhtml += '<td class="text-danger">' + (parseFloat(data[x]['price'])-parseFloat(data[x]['discounted_price'])) + '</td>';
                            mhtml += '<td class="text-success" style="font-weight:bold;">' + data[x]['discounted_price'] + '</td>';
                            mhtml += '<td class="text-info" style="font-weight:bold;">' + data[x]['paid'] + '</td>';
//                            mhtml += '<td class="text-danger" style="font-weight:bold;">' + data[x]['balance'] + '</td>';
                            mhtml += '</tr>';
                            totalpaid = totalpaid + parseFloat(data[x]['paid']);
                        }
                        totalpaid=totalpaid.toFixed(2);
                        var fhtml="<tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th>"+totalpaid.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</th></tr>"
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);
                        
                      //  $("#summary").html('Received: <strong class="text-info">'+ totalpaid.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '/-</strong>');
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });            
            
            }
            
            function ssales() {
               
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/service_sales',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var totalprice=0;
                        var totaldiscount=0;

                        var hhtml = "<tr><th>SID</th><th>Type</th><th>Category</th><th>Service</th><th>Count</th><th>Price</th><th  class='text-danger'>Service Discount</th><th  class='text-danger'>Invoice Discount</th><th>Total Discount</th><th class='text-success'>Discounted Price</th></tr>";//<th class='text-danger'>Balance</th></tr>"

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            
                            totaldiscount=totaldiscount+parseFloat(data[x]['total_discount']);
                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['service_id'] + '</td>';
                            mhtml += '<td>' + data[x]['service_type'] + '</td>';
                            mhtml += '<td>' + data[x]['service_category'] + '</td>';
                            mhtml += '<td>' + data[x]['service_name'] + '</td>';
                            mhtml += '<td>' + data[x]['service_count'] + '</td>';
                            mhtml += '<td>' + data[x]['price'] + '</td>';
                            mhtml += '<td class="text-danger">' + data[x]['service_discount'] + '</td>';
                            mhtml += '<td class="text-danger">' + data[x]['invoice_discount'] + '</td>';
                            mhtml += '<td class="text-danger">' + data[x]['total_discount'] + '</td>';
                            mhtml += '<td>' + data[x]['discounted_price'] + '</td>';
                            totalprice=totalprice+parseFloat(data[x]['discounted_price'] );
                            mhtml += '</tr>';
                        }
                        totaldiscount=totaldiscount.toFixed(2);
                        totalprice=totalprice.toFixed(2);
                        var fhtml="<tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th>"+totaldiscount.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</th><th>"+totalprice.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</th></tr>";
                        
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);
                        
                      //  $("#summary").html('Received: <strong class="text-info">'+ totalpaid.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '/-</strong>');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }

            function ssales_dept() {
               
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/service_sales_dept',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var totalprice=0;
                        var totaldiscount=0;

                        var hhtml = "<tr><th>SID</th><th>Dept</th><th>Type</th><th>Category</th><th>Service</th><th>Count</th><th>Price</th><th  class='text-danger'>Service Discount</th><th  class='text-danger'>Invoice Discount</th><th>Total Discount</th><th class='text-success'>Discounted Price</th></tr>";//<th class='text-danger'>Balance</th></tr>"

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            
                            totaldiscount=totaldiscount+parseFloat(data[x]['total_discount']);
                            mhtml += '<tr>';
                            
                            mhtml += '<td>' + data[x]['service_id'] + '</td>';
                            mhtml += '<td>' + data[x]['service_department'] + '</td>';
                            mhtml += '<td>' + data[x]['service_type'] + '</td>';
                            mhtml += '<td>' + data[x]['service_category'] + '</td>';
                            mhtml += '<td>' + data[x]['service_name'] + '</td>';
                            mhtml += '<td>' + data[x]['service_count'] + '</td>';
                            mhtml += '<td>' + data[x]['price'] + '</td>';
                            mhtml += '<td class="text-danger">' + data[x]['service_discount'] + '</td>';
                            mhtml += '<td class="text-danger">' + data[x]['invoice_discount'] + '</td>';
                            mhtml += '<td class="text-danger">' + data[x]['total_discount'] + '</td>';
                            mhtml += '<td>' + data[x]['discounted_price'] + '</td>';
                            totalprice=totalprice+parseFloat(data[x]['discounted_price'] );
                            mhtml += '</tr>';
                        }
                        totaldiscount=totaldiscount.toFixed(2);
                        totalprice=totalprice.toFixed(2);
                        var fhtml="<tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th>"+totaldiscount.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</th><th>"+totalprice.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</th></tr>";
                        
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);
                        
                      //  $("#summary").html('Received: <strong class="text-info">'+ totalpaid.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '/-</strong>');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0,
                            order: [[2, 'asc']]
                        });
                        $("#cog").hide();

                    }
                });
            }

            function ssaled() {
                //service_sale_details
                var totalpaid=0;
                var totalrecovery=0;
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/service_sale_details',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD'), id_service_type:$("#selectservicetype option:selected").val(), service_type:$("#selectservicetype option:selected").text(), id_service_category:$("#selectservicecategory option:selected").val(), service_category:$("#selectservicecategory option:selected").text(), id_business_services:$("#selectservice option:selected").val(), service_name:$("#selectservice option:selected").text(), staff_id:$("#selectstaff option:selected").val(), staff_name:$("#selectstaff option:selected").text()},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var totalpaid=0;
                        var totalbal=0;
                        var totaldiscount=0;
                        var discountedprice=0;

                        var hhtml = "<tr><th>ID</th><th>Visit Date</th><th>Invoice Date</th><th>CID</th><th>Customer</th><th>Cell</th><th>Staff</th><th>SID</th><th>Ref#</th><th>Type</th><th>Category</th><th>Service</th><th>Price</th><th>Service Discount</th><th class='text-success'>Invoice Discount</th><th class='text-info'>Total Discount</th><th class='text-success'>Discounted Price</th> ";//  <th class='text-info'>Other Charges</th><th>Total Payable</th><th>Paid</th><th>Balance</th></tr>"; //<th class='text-danger'>Balance</th></tr>";

                        var mhtml = ""; var idinvoice=''; var idinvoicedetails=0;
                        for (x = 0; x < data.length; x++) {
                            if(idinvoice !== data[x]['id_invoice']){
                                totalpaid=totalpaid+parseFloat(data[x]['paid']);
                                var invoicediscount =parseFloat(data[x]['invoice_discount']);
                                totaldiscount=parseFloat(data[x]['total_discount']);
                                discountedprice= parseFloat(data[x]['discounted_price']);
                                
                                if(data[x]['reference_number']==''){
                                totalpaid=totalpaid+parseFloat(data[x]['paid']);} else {
                                totalrecovery=totalrecovery+parseFloat(data[x]['paid']);}
                                mhtml += '<tr>';
    
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ data[x]['id_invoice'] +'">' + data[x]['id_invoice'] + '</a></td>';
                                
                                mhtml += '<td>' + data[x]['visited'] + '</td>';    
                                mhtml += '<td>' + data[x]['invoiced'] + '</td>';
                                mhtml += '<td>' + data[x]['customer_id'] + '</td>';
                                mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                                mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                                mhtml += '<td>' + data[x]['staff'] + '</td>';
//                                var res = []; 
//                                if(data[x]['reference_number']){res = data[x]['reference_number'].split("-")} else {res[2]=''};
//                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ res[2] +'">' + res[2] + '</a></td>';                                
                                mhtml += '<td>' + data[x]['service_id'] + '</td>';
                                mhtml += '<td>' + data[x]['ref_number'] + '</td>';
                                mhtml += '<td>' + data[x]['service_type'] + '</td>';
                                mhtml += '<td>' + data[x]['service_category'] + '</td>';
                                mhtml += '<td>' + data[x]['service_name'] + '</td>';

                                mhtml += '<td>' + data[x]['gross_total'] + '</td>';
                                //mhtml += '<td class="text-success" style="font-weight:bold;">' + data[x]['advance_amount'] + '</td>';
                                mhtml += '<td class="text-danger">' + data[x]['service_discount'] + '</td>';
                                mhtml += '<td class="text-danger">' + invoicediscount.toFixed(2) + '</td>';
                                mhtml += '<td class="text-danger">' + totaldiscount.toFixed(2) + '</td>';
                                
                                mhtml += '<td class="text-success" style="font-weight:bold;">' + discountedprice.toFixed(2) + '</td>';
                                
//                                mhtml += '<td class="text-info" style="font-weight:bold;">' + data[x]['other_charges'] + '</td>';
//                                mhtml += '<td class="text-info" style="font-weight:bold;">' + data[x]['total_payable'] + '</td>';
//                                mhtml += '<td class="text-info" style="font-weight:bold;">' + data[x]['paid_amount'] + '</td>';
//                                mhtml += '<td class="text-info" style="font-weight:bold;">' + data[x]['balance'] + '</td>';
                                mhtml += '</tr>';
                            } else {
                                if(data[x]['id_invoice_details'] !== idinvoicedetails){
                                    totalpaid=totalpaid+parseFloat(data[x]['paid']);
                                    var invoicediscount =parseFloat(data[x]['invoice_discount']);
                                    totaldiscount=parseFloat(data[x]['total_discount']);
                                    discountedprice= parseFloat(data[x]['discounted_price']);
                                    mhtml += '<tr>';

                                    mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ data[x]['id_invoice'] +'">' + data[x]['id_invoice'] + '</a></td>';

                                    mhtml += '<td>' + data[x]['visited'] + '</td>';    
                                    mhtml += '<td>' + data[x]['invoiced'] + '</td>';
                                    mhtml += '<td>' + data[x]['customer_id'] + '</td>';
                                    mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                                    mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                                    mhtml += '<td>' + data[x]['staff'] + '</td>';

                                    //mhtml += '<td></td>';
                                    mhtml += '<td>' + data[x]['service_id'] + '</td>';
                                    mhtml += '<td>' + data[x]['ref_number'] + '</td>';
                                    mhtml += '<td>' + data[x]['service_type'] + '</td>';
                                    mhtml += '<td>' + data[x]['service_category'] + '</td>';
                                    mhtml += '<td>' + data[x]['service_name'] + '</td>';

                                    mhtml += '<td>' + data[x]['gross_total'] + '</td>';
                                    //mhtml += '<td class="text-success" style="font-weight:bold;"></td>';
                                    mhtml += '<td class="text-danger">' + data[x]['service_discount'] + '</td>';
                                    mhtml += '<td class="text-danger">' + invoicediscount.toFixed(2) + '</td>';
                                    mhtml += '<td class="text-danger">' + totaldiscount.toFixed(2) + '</td>';
                                    mhtml += '<td class="text-info" style="font-weight:bold;">'+discountedprice.toFixed(2)+'</td>';

                                    mhtml += '</tr>';
                                } else {
                                    mhtml += '<tr>';

                                    mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ data[x]['id_invoice'] +'">' + data[x]['id_invoice'] + '</a></td>';

                                    mhtml += '<td>' + data[x]['visited'] + '</td>';    
                                    mhtml += '<td>' + data[x]['invoiced'] + '</td>';
                                    mhtml += '<td>' + data[x]['customer_id'] + '</td>';
                                    mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                                    mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                                    mhtml += '<td class="text-danger">' + data[x]['staff'] + ' (Additional)</td>';

                                    //mhtml += '<td></td>';
                                    mhtml += '<td>' + data[x]['service_id'] + '</td>';
                                    mhtml += '<td>' + data[x]['ref_number'] + '</td>';
                                    mhtml += '<td class="text-danger">' + data[x]['service_type'] + '</td>';
                                    mhtml += '<td class="text-danger">' + data[x]['service_category'] + '</td>';
                                    mhtml += '<td class="text-danger">' + data[x]['service_name'] + '</td>';

                                    mhtml += '<td></td>';
                                    //mhtml += '<td class="text-success" style="font-weight:bold;"></td>';
                                    mhtml += '<td class="text-danger"></td>';
                                    mhtml += '<td class="text-danger"></td>';
                                    mhtml += '<td class="text-danger"></td>';
                                    mhtml += '<td class="text-info" style="font-weight:bold;"></td>';

                                    mhtml += '</tr>';
                                }
                            }
                            idinvoice=data[x]['id_invoice'];
                            idinvoicedetails=data[x]['id_invoice_details'];
                        }
                        
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');
                        totalpaid=totalpaid.toFixed(2);
                       // $("#summary").html('New Sale: <strong class="text-info">'+ totalpaid.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '/-</strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Recovered: <strong class="text-info">'+ totalrecovery.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '/-</strong>');
                        $.fn.dataTable.moment('DD-MM-YYYY');

                        
                        ///row grouping
                        var groupColumn = 0;
                        var table = $('#tblreport').DataTable({
                            "columnDefs": [
                                { "visible": false, "targets": groupColumn }
                            ],
                            "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            "stateSave": true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                            "dom": "Bfrtlip",
                            "buttons": [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                                "dom": "frtlip",
                            <?php } ?>
                            "order": [[ groupColumn, 'asc' ]],
                            "displayLength": 25,
                            "responsive":!0,
                            "drawCallback": function ( settings ) {
                                var api = this.api();
                                var rows = api.rows( {page:'current'} ).nodes();
                                var last=null;

                                api.column(groupColumn, {page:'current'} ).data().each( function ( group, i ) {
                                    if ( last !== group ) {
                                        $(rows).eq( i ).before(
                                            '<tr class="group"><td colspan="16">'+group+'</td></tr>'
                                        );

                                        last = group;
                                    }
                                } );
                            }
                        } );

                        // Order by the grouping
                        $('#example tbody').on( 'click', 'tr.group', function () {
                            var currentOrder = table.order()[0];
                            if ( currentOrder[0] === groupColumn && currentOrder[1] === 'asc' ) {
                                table.order( [ groupColumn, 'desc' ] ).draw();
                            }
                            else {
                                table.order( [ groupColumn, 'asc' ] ).draw();
                            }
                        } );
                        
                        
                        $("#cog").hide();

                    }
                });
            }

            function staffperf() {
                // staff performance details
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/staff_performance',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var hhtml = "<tr><th>Staff</th><th>Type</th><th>Category</th><th>Service</th><th>Count</th><th>Price</th><th>Discount</th><th>Payable</th><th>Paid</th></tr>"

                        var mhtml = "";
                        for (var x = 0; x < data.length; x++) {

                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['staff_name'] + '</td>';
                            mhtml += '<td>' + data[x]['service_type'] + '</td>';
                            mhtml += '<td>' + data[x]['service_category'] + '</td>';
                            mhtml += '<td>' + data[x]['service_name']  + '</td>';
                            mhtml += '<td>' + data[x]['service_count'] + '</td>';
                            mhtml += '<td>' + data[x]['price'] + '</td>';
                            mhtml += '<td class="text-danger">' + data[x]['discount_sum'] + '</td>';
                            mhtml += '<td class="text-success">' + data[x]['price_sum'] + '</td>';
                            mhtml += '<td class="text-info" style="font-weight:bold">' + data[x]['paid'] + '</td>';
                            mhtml += '</tr>';

                        }
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');

                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }

            function psales() {
               
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/product_sales',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var totaldiscount=0;
                        var totalprice=0;
                        var totaldiscountedprice=0;
                        var totalpaid=0;
                        var hhtml = "<tr><th>Brand</th><th>Product</th><th>Price</th><th>Quantity</th><th>Total Price</th><th>Product Discount</th><th>Invoice Discount</th><th>Total Discount</th><th>Discounted Price</th></tr>";

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            totalprice=totalprice+parseFloat(data[x]['total_price']);
                            totaldiscount=totaldiscount+parseFloat(data[x]['total_discount']);
                            totaldiscountedprice=totaldiscountedprice+parseFloat(data[x]['discounted_price']);
                            totalpaid=totalpaid+parseFloat(data[x]['paid_amount']);
                            
                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['brand_name'] + '</td>';
                            mhtml += '<td>' + data[x]['product_name'] + ' - ' + data[x]['category'] + '</td>';
                            mhtml += '<td>' + data[x]['Price'] + '</td>';
                            mhtml += '<td>' + data[x]['Quantity'] + '</td>';
                            mhtml += '<td class="text-success">' + data[x]['total_price'] + '</td>';
                            mhtml += '<td class="text-success">' + data[x]['product_discount'] + '</td>';
                            mhtml += '<td class="text-danger">' + data[x]['invoice_discount'] + '</td>';
                            mhtml += '<td class="text-danger">' + data[x]['total_discount'] + '</td>';
                            mhtml += '<td class="text-info">' + data[x]['discounted_price'] + '</td>';
                            
                            mhtml += '</tr>';
                            
                            
                        }
                        totaldiscount=totaldiscount.toFixed(2);
                        totalprice=totalprice.toFixed(2);
                        totalpaid=totalpaid.toFixed(2);
                        
                        var fhtml="<tr><th></th><th></th><th></th><th></th><th>"+totalprice.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</th><th></th><th></th><th>"+totaldiscount.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</th><th>"+totaldiscountedprice.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</th></tr>";
                        
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);
                       
                        //totalbal=totalbal.toFixed(2);
                        //$("#summary").html('Received: <strong class="text-info">'+ totalpaid.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '/-</strong>');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }

            function psaled() {
                
                //product_sale_details
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/product_sale_details',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    async: true,
                    success: function(data) {
                        var totalprice=0;
                        var totaldiscount=0;
                        var totalrecovered=0;
                        var totalpaid=0;
                        var totalcogs=0;
                        var hhtml = "<tr><th>Invoice ID</th><th>P. ID</th><th>Brand</th><th>Product</th><th>Date</th><th>Customer</th><th>Store</th><th>Sold By</th><th>Price</th><th>Quantity</th><th>Total Price</th><th>Product Discount</th><th>Invoice Discount</th><th>Total Discount</th><th>Total</th><th>COG</th></tr>";

                        var mhtml = "";
                        var cinvoiceid=0; var totaldisprice = 0;
                        for (x = 0; x < data.length; x++) {
                            
                            
                            totalprice=totalprice+parseFloat(data[x]['discounted_price']);
                            totaldiscount=totaldiscount+parseFloat(data[x]['total_discount']);
                            totalpaid=totalpaid+parseFloat(data[x]['paid_amount']);
                            
                            
                            mhtml += '<tr>';
                            mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ data[x]['id_invoice'] +'">' + data[x]['id_invoice'] + '</a></td>';
                            mhtml += '<td>' + data[x]['product_id'] + '</td>'
                            mhtml += '<td>' + data[x]['Brand'] + '</td>';
                            mhtml += '<td>' + data[x]['Product'] + ' - ' + data[x]['Category'] + '</td>';
                            mhtml += '<td>' + data[x]['Date'] + '</td>';
                            mhtml += '<td>' + data[x]['Customer'] + '</td>';
                            mhtml += '<td>' + data[x]['business_store'] + '</td>';
                            mhtml += '<td>' + data[x]['Sold By'] + '</td>';
                            
                            mhtml += '<td style="text-align:right;">' + data[x]['price'] + '</td>';
                            mhtml += '<td style="text-align:right;">' + data[x]['Quantity'] + '</td>';
                            mhtml += '<td style="text-align:right;">' + data[x]['total_price'] + '</td>';
                            mhtml += '<td class="text-info" style="text-align:right;">' + data[x]['product_discount'] + '</td>';
                            mhtml += '<td class="text-info" style="text-align:right;">' + data[x]['invoice_discount'] + '</td>';
                            mhtml += '<td class="text-danger" style="text-align:right;">' + data[x]['total_discount'] + '</td>';
                            
                            var disprice =  data[x]['total_price'] -  data[x]['total_discount'];
                            totaldisprice = totaldisprice + disprice;
                            
                            mhtml += '<td class="text-success" style="text-align:right;">' + disprice + '</td>';
                            if(cinvoiceid !== data[x]['id_invoice']){
                                mhtml += '<td class="text-primary" style="text-align:right;">' + data[x]['cog_sold'] + '</td>';
                                totalcogs=totalcogs+parseFloat(data[x]['cog_sold']);
                            }else{
                                mhtml += '<td class="text-primary" style="text-align:right;"></td>';
                            }
                            mhtml += '</tr>';
                            cinvoiceid = data[x]['id_invoice'];
                        }
                        totalcogs=totalcogs.toFixed(2);
                        totaldiscount=totaldiscount.toFixed(2);
                        totalprice=totalprice.toFixed(2);
                        totalpaid=totalpaid.toFixed(2);
                        
                        var fhtml="<tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th style='text-align:right;'>"+totaldiscount.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</th><th style='text-align:right;'>"+totaldisprice.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</th><th style='text-align:right;'>"+totalcogs.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</th></tr>";
                        
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);
                        
                        //totalbal=totalbal.toFixed(2);
                        //$("#summary").html('New Sale: <strong class="text-info">'+ totalpaid.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '/-</strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Recovered: <strong class="text-info">'+ totalrecovered.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '/-</strong>');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }


            function pusages() {
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/product_usage_summary',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {


                        var hhtml = "<tr><th>Brand</th><th>Product</th><th>Service Count</th><th>Usage</th><th>Unit</th><th>Container Type</th><th>Container Qty</th><th>Container Used</th><th>Action</th></tr>"

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {

                            mhtml += '<tr>';
                            //mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ data[x]['id_invoice'] +'">' + data[x]['id_invoice'] + '</a></td>';
                            mhtml += '<td>' + data[x]['business_brand_name'] + '</td>';
                            mhtml += '<td>' + data[x]['product_name'] + ' - ' + data[x]['category'] + '</td>';
                            mhtml += '<td>' + data[x]['product_count'] + '</td>';
                            mhtml += '<td>' + data[x]['total_qty'] + '</td>';
                            mhtml += '<td>' + data[x]['product_unit'] + '</td>';
                            mhtml += '<td>' + data[x]['Container Type'] + '</td>';
                            mhtml += '<td>' + data[x]['Container Qty'] + '</td>';
                            mhtml += '<td>' + parseFloat(data[x]['Container Used']).toFixed(2) + '</td>';
                            mhtml += '<td><button type="button" product_id="' + data[x]['product_id'] + '" unit="' + data[x]['product_unit'] + '" total_qty="' + data[x]['total_qty'] + '" container_type="' + data[x]['Container Type'] + '" units_used="' + parseFloat(data[x]['Container Used']).toFixed(2) + '" service_count="' + data[x]['product_count'] + '" class="btn btn-sm btn-info usage_details_btn">View Details</button></td>';
                            mhtml += '</tr>';
                        }
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }

            function invoices() {
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/invoices',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {

                        var hhtml = "<tr><th>ID #</th><th>Customer</th><th>Date</th><th>Type</th><th>Payment Mode</th><th>inst.</th><th>Is Recovery?</th><th>Gross Total</th><th>Service Discount</th><th>Invoice Discount</th><th>Total Discount</th><th>Discount Reason</th><th class='text-info'>Advance Adjusted</th><th class='text-info'>Retained Used</th><th>Other Charges</th><th>Service Additions</th><th>Taxes</th><th>CC Charge</th><th class='text-info'>Net Payable</th><th class='text-info'>Paid</th><th class='text-info'>Retained Amount</th><th class='text-info'>Invoice Total</th><th class='text-danger'>Balance</th><th>cc tip</th><th>Cash</th><th>Card</th><th>Check</th><th>Voucher</th><th>By</th><th>Remarks</th><th>ims_ref</th></tr>";

                        var mhtml = "";
                        var gross_amount=0; var service_discount=0; var invoice_discount=0; var total_discount=0; var advance_adjusted=0; 
                        var retained_amount_used=0; var other_charges=0; var service_addition=0; var taxes=0; var cc_charge=0; var net_payable=0; var paid_amount=0;
                        var total_payable=0; var retained_amount=0; var balance=0; var cc_tip = 0; var cash=0; var card=0; var check=0; var voucher=0; var actual_payable=0;
                        for (x = 0; x < data.length; x++) {

                            mhtml += '<tr>';
                            var res = []; 
                            if(data[x]['invoice_number']){res = data[x]['invoice_number'].split("-")} else {res[2]=''};
                            if(data[x]['invoice_type']=="service"){                            
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ res[2] +'">' +  data[x]['invoice_number'] + '</a></td>';
                            } else {
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ res[2] +'">' +  data[x]['invoice_number'] + '</a></td>';
                            }
                            mhtml += '<td>' + data[x]['customer_name'] + ' ' + data[x]['invoice_extra'] +  '</td>';
                             mhtml += '<td>' + data[x]['invoice_date'] + '</td>';
                             mhtml += '<td>' + data[x]['invoice_type'] + '</td>';
                            mhtml += '<td>' + data[x]['payment_mode'] + '</td>';
                            mhtml += '<td>' + data[x]['instrument_number'] + '</td>';
                            var resr = []; 
                            if(data[x]['reference_invoice_number']){resr = data[x]['reference_invoice_number'].split("-")} else {resr[2]=''};
                            if(data[x]['invoice_type']=="service"){                            
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ resr[2] +'">' + data[x]['reference_invoice_number'] + '</a></td>';
                            } else {
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ resr[2] +'">' + data[x]['reference_invoice_number'] + '</a></td>';
                            }
                           // if(data[x]['reference_invoice_number']==''){
                                mhtml += '<td>' + data[x]['gross_total'] + '</td>';
                                gross_amount=gross_amount+ parseFloat(data[x]['gross_total']);
                            //}else {
                            //     mhtml += '<td>0</td>';
                            //    }
                            //if(data[x]['reference_invoice_number']==''){
                                mhtml += '<td>' + data[x]['service_discount'] + '</td>';
                                service_discount=service_discount+ parseFloat(data[x]['service_discount']);
                             //}else {
                             //    mhtml += '<td>0</td>';
                            //    }   
                            //if(data[x]['reference_invoice_number']==''){    
                                mhtml += '<td>' + data[x]['invoice_discount'] + '</td>';
                                invoice_discount=invoice_discount+ parseFloat(data[x]['invoice_discount']);
                            //}else {
                            //     mhtml += '<td>0</td>';
                            //    }
                            //if(data[x]['reference_invoice_number']==''){
                                mhtml += '<td>' + data[x]['total_discount'] + '</td>';
                                total_discount=total_discount+ parseFloat(data[x]['total_discount']);
                                
                                 mhtml += '<td>' + data[x]['discount_reason'] + '</td>';
                                
                            //}else {
                            //     mhtml += '<td>0</td>';
                            //    }
                            //if(data[x]['reference_invoice_number']==''){
                                mhtml += '<td class="text-info" style="font-weight:bold;">' + data[x]['advance_adjusted'] + '</td>';
                                advance_adjusted=advance_adjusted+ parseFloat(data[x]['advance_adjusted']);
                            //}else {
                            //     mhtml += '<td>0</td>';
                            //    }
                            //if(data[x]['reference_invoice_number']==''){
                                mhtml += '<td class="text-info" style="font-weight:bold;">' + data[x]['retained_amount_used'] + '</td>';
                                retained_amount_used=retained_amount_used+ parseFloat(data[x]['retained_amount_used']);
                            //}else {
                            //     mhtml += '<td>0</td>';
                            //    }
                            //if(data[x]['reference_invoice_number']==''){
                                mhtml += '<td>' + data[x]['other_charges'] + '</td>';
                                other_charges=other_charges+ parseFloat(data[x]['other_charges']);
                                mhtml += '<td>' + data[x]['service_addition'] + '</td>';
                                service_addition=service_addition+ parseFloat(data[x]['service_addition']);
                            //}else {
                            //     mhtml += '<td>0</td>';
                            //    }    
                            //if(data[x]['reference_invoice_number']==''){
                                mhtml += '<td>' + data[x]['tax_total'] + '</td>';
                                taxes=taxes+ parseFloat(data[x]['tax_total']);
                            //}else {
                            //     mhtml += '<td>0</td>';
                            //    }
                            mhtml += '<td>' + data[x]['cc_charge'] + '</td>'; 
                            cc_charge=cc_charge+ parseFloat(data[x]['cc_charge']);
                            
                            mhtml += '<td class="text-info" style="font-weight:bold;">' + data[x]['total_payable'] + '</td>';
                             total_payable=total_payable+ parseFloat(data[x]['total_payable']);
                             
                            mhtml += '<td class="text-info" style="font-weight:bold;">' + data[x]['paid_amount'] + '</td>';
                            paid_amount=paid_amount+ parseFloat(data[x]['paid_amount']);
                            
                            mhtml += '<td class="text-info" style="font-weight:bold;">' + data[x]['retained_amount'] + '</td>';
                            retained_amount=retained_amount+ parseFloat(data[x]['retained_amount']);
                            
                            mhtml += '<td class="text-info" style="font-weight:bold;">' + data[x]['actual_payable']  + '</td>';
                            actual_payable=actual_payable+ parseFloat(data[x]['actual_payable']);
    
                            mhtml += '<td class="text-danger" style="font-weight:bold;">' + data[x]['balance'] + '</td>';
                            balance=balance+ parseFloat(data[x]['balance']);
                           // mhtml += '<td><span class="label label-pink">' + (data[x]['name'] != null ? data[x]['name'] : "") + '</span></td>';
                             mhtml += '<td>' + data[x]['cctip'] + '</td>';
                             
                            cc_tip=cc_tip + parseFloat(data[x]['cctip']);
                            
                            
                            mhtml += '<td>' + data[x]['paid_cash'] + '</td>';
                            cash=cash+ parseFloat(data[x]['paid_cash']);
                            mhtml += '<td>' + data[x]['paid_card'] + '</td>';
                            card=card+ parseFloat(data[x]['paid_card']);
                            mhtml += '<td>' + data[x]['paid_check'] + '</td>';
                            check=check+ parseFloat(data[x]['paid_check']);
                            mhtml += '<td>' + data[x]['paid_voucher'] + '</td>';
                            voucher=voucher+ parseFloat(data[x]['paid_voucher']);
                            mhtml += '<td>' + data[x]['created_by'] + '</td>';
                            mhtml += '<td>' + data[x]['remarks'] + '</td>';
                            mhtml += '<td>' + data[x]['ims_ref'] + '</td>';
                            mhtml += '</tr>';
                        }
                        //console.log(mhtml);
                        var fhtml="<tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th>"+gross_amount.toFixed(2) + "</th><th>"+service_discount.toFixed(2)+ "</th><th>"+invoice_discount.toFixed(2)+ "</th><th>"+total_discount.toFixed(2)+ "</th><th></th><th>"+advance_adjusted.toFixed(2)+ "</th><th>"+retained_amount_used.toFixed(2)+ "</th><th>"+other_charges.toFixed(2)+ "</th><th>"+service_addition.toFixed(2)+ "</th><th>"+taxes.toFixed(2)+ "</th><th>"+cc_charge.toFixed(2)+ "</th><th>"+total_payable.toFixed(2)+ "</th><th>"+paid_amount.toFixed(2)+ "</th><th>"+retained_amount.toFixed(2)+ "</th><th>"+actual_payable.toFixed(2)+ "</th><th>"+balance.toFixed(2)+ "</th><th>"+cc_tip.toFixed(2)+ "</th><th>"+cash.toFixed(2)+ "</th><th>"+card.toFixed(2)+ "</th><th>"+check.toFixed(2)+ "</th><th>"+voucher.toFixed(2)+"</th><th></th><th></th><th></th></tr>";
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);

                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }
            
            function recoveries() {
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/recoveries',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {

                        var hhtml = "<tr><th>ID #</th><th>Customer</th><th>Payment Mode</th><th>CC</th><th>Date</th><th>Type</th><th>Is Recovery?</th><th class='text-info'>Paid</th><th class='text-danger'>Balance</th><th>Sub Total</th><th>Discount</th><th>Gross</th><th>Taxes</th><th class='text-success'>Net Amount</th><th>Created By</th><th>Discount by</th><th>Contact</th><th>Email</th></tr>"

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {

                            mhtml += '<tr>';
                            var res = []; 
                            if(data[x]['invoice_number']){res = data[x]['invoice_number'].split("-")} else {res[2]=''};
                            if(data[x]['invoice_type']=="service"){                            
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ res[2] +'">' +  data[x]['invoice_number'] + '</a></td>';
                            } else {
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ res[2] +'">' +  data[x]['invoice_number'] + '</a></td>';
                            }
                            mhtml += '<td>' + data[x]['cname'] + '</td>';
                            mhtml += '<td>' + data[x]['payment_mode'] + '</td>';
                            mhtml += '<td>' + data[x]['instrument_number'] + '</td>';
                            mhtml += '<td>' + data[x]['invoice_date'] + '</td>';
                            mhtml += '<td>' + data[x]['invoice_type'] + '</td>';
                            
                            var resr = []; 
                            if(data[x]['reference_invoice_number']){resr = data[x]['reference_invoice_number'].split("-")} else {resr[2]=''};
                            if(data[x]['invoice_type']=="service"){                            
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ resr[2] +'">' + data[x]['reference_invoice_number'] + '</a></td>';
                            } else {
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ resr[2] +'">' + data[x]['reference_invoice_number'] + '</a></td>';
                            }
                            
                            mhtml += '<td class="text-info" style="font-weight:bold;">' + data[x]['paid_amount'] + '</td>';
                            mhtml += '<td class="text-danger" style="font-weight:bold;">' + data[x]['balance'] + '</td>';
                            mhtml += '<td>' + data[x]['sub_total'] + '</td>';
                            mhtml += '<td>' + data[x]['discount'] + '</td>';
                            mhtml += '<td>' + data[x]['gross_amount'] + '</td>';
                            mhtml += '<td>' + data[x]['tax_total'] + '</td>';
                            mhtml += '<td class="text-success" style="font-weight:bold;">' + data[x]['net_amount'] + '</td>';
                            mhtml += '<td>' + data[x]['by'] + '</td>';
                            mhtml += '<td><span class="label label-pink">' + (data[x]['name'] != null ? data[x]['name'] : "") + '</span></td>';
                             mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_email'] + '</td>';
                            mhtml += '</tr>';
                        }
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');

                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }

            function cancelledadvances(){
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/cancelled_advances',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {

                        var hhtml = "<tr><th>Visit ID</th><th>Advance ID</th><th>Advance Amount</th><th>Advance Date</th><th>Cancellation Date</th><th>Visit Status</th><th>Cancelled By</th></tr>"

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {

                            mhtml += '<tr>';
                            
                            mhtml += '<td>' + data[x]['customer_visit_id'] + '</td>';
                            mhtml += '<td>' + data[x]['id_visit_advance'] + '</td>';
                            mhtml += '<td>' + data[x]['advance_amount'] + '</td>';
                            mhtml += '<td>' + data[x]['advance_date'] + '</td>';
                            mhtml += '<td>' + data[x]['cancelled_on'] + '</td>';      
                            mhtml += '<td>' + data[x]['visit_status'] + '</td>';
                            mhtml += '<td class="text-danger">' + data[x]['cancelled_by'] + '</td>';                           
                           
                            mhtml += '</tr>';
                        }
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');

                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }

            function cancelledinvoices() {
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/cancelled_invoices',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {

                        var hhtml = "<tr><th>ID #</th><th>Customer</th><th>Payment Mode</th><th>CC</th><th>Date</th><th>Type</th><th>Reason</th><th>By</th><th>Is Recovery?</th><th class='text-info'>Paid</th><th class='text-danger'>Balance</th><th>Sub Total</th><th>Discount</th><th>Gross</th><th>Taxes</th><th class='text-success'>Net Amount</th><th>Discount by</th><th>Contact</th><th>Email</th></tr>"

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {

                            mhtml += '<tr>';
                            var res = []; 
                            if(data[x]['invoice_number']){res = data[x]['invoice_number'].split("-");} else {res[2]='';}
                            if(data[x]['invoice_type']=="service"){                            
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ res[2] +'">' +  data[x]['invoice_number'] + '</a></td>';
                            } else {
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ res[2] +'">' +  data[x]['invoice_number'] + '</a></td>';
                            }
                            mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td>' + data[x]['payment_mode'] + '</td>';
                            mhtml += '<td>' + data[x]['instrument_number'] + '</td>';
                            mhtml += '<td>' + data[x]['invoice_date'] + '</td>';
                            mhtml += '<td>' + data[x]['invoice_type'] + '</td>';
                            mhtml += '<td >' + data[x]['cancelreason'] + '</td>';
                            mhtml += '<td class="text-danger">' + data[x]['cancelled_by'] + '</td>';
                            var resr = []; 
                            if(data[x]['reference_invoice_number']){resr = data[x]['reference_invoice_number'].split("-")} else {resr[2]=''};
                            if(data[x]['invoice_type']=="service"){                            
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ resr[2] +'">' + data[x]['reference_invoice_number'] + '</a></td>';
                            } else {
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ resr[2] +'">' + data[x]['reference_invoice_number'] + '</a></td>';
                            }
                            
                            mhtml += '<td class="text-info" style="font-weight:bold;"><strike>' + data[x]['paid_amount'] + '</strike></td>';
                            mhtml += '<td class="text-danger" style="font-weight:bold;"><strike>' + data[x]['balance'] + '</strike></td>';
                            mhtml += '<td><strike>' + data[x]['sub_total'] + '</strike></td>';
                            mhtml += '<td><strike>' + data[x]['discount'] + '</strike></td>';
                            mhtml += '<td><strike>' + data[x]['gross_amount'] + '</strike></td>';
                            mhtml += '<td><strike>' + data[x]['tax_total'] + '</strike></td>';
                            mhtml += '<td class="text-success" style="font-weight:bold;"><strike>' + data[x]['net_amount'] + '</strike></td>';
                            mhtml += '<td><span class="label label-pink">' + (data[x]['name'] != null ? data[x]['name'] : "") + '</span></td>';
                             mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_email'] + '</td>';
                            mhtml += '</tr>';
                        }
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');

                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }

            function commissions() {
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/commissions',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {

                        var hhtml = "<tr><th>Staff Name</th><th>Month</th><th>Year</th><th>Total Services</th><th>Price</th><th>Paid</th><th>Recoveries</th><th>Commission</th><th>Total</th><th>Action</th></tr>";
                        var total=0; var totalcommission=0; var totalpaid=0; var totalrecovery=0; var totalprice=0;
                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            total= total + parseFloat(data[x]['Total'].replace(',',''));
                            totalcommission=totalcommission+parseFloat(data[x]['invoice_commission'].replace(',',''));
                            totalpaid=totalpaid+parseFloat(data[x]['Amount'].replace(',',''));
                            totalrecovery=totalrecovery+parseFloat(data[x]['Recovery'].replace(',',''));
                            totalprice=totalprice+parseFloat(data[x]['final_price'].replace(',',''));
                            
                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['staff_name'] + '</td>';
                            mhtml += '<td><span class="label label-danger">' + data[x]['Month'] + '</span></td>';
                            mhtml += '<td><span class="label label-danger">' + data[x]['Year'] + '</span></td>';
                            
                            mhtml += '<td>' + data[x]['Total Services'] + '</td>';
                            mhtml += '<td>' + data[x]['final_price'] + '</td>';
                            mhtml += '<td>' + data[x]['Amount'] + '</td>';
                            mhtml += '<td>' + data[x]['Recovery'] + '</td>';
                            mhtml += '<td>' + data[x]['invoice_commission'] + '</td>';
                            mhtml += '<td>' + data[x]['Total'] + '</td>';
                            //mhtml += '<td>' + data[x]['commission_perc'] + '%</td>';
                            //mhtml += '<td>' + data[x]['Commission'] + '</td>';
                            mhtml += '<td><button type="button" staff_id="' + data[x]['staff_id'] + '" class="btn btn-sm btn-info commission_btn"><i class="fa fa-calculator"></i> Calculate</button></td>';
                            mhtml += '</tr>';
                        }
                        var fhtml="<tr><th colspan=4></th><th>"+totalprice.toFixed(2)+"</th><th>"+totalpaid.toFixed(2)+"</th><th>"+totalrecovery.toFixed(2)+"</th><th>"+totalcommission+"</th><th>"+total.toFixed(2)+"</th><th></th></tr>";
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);
                        total=total.toFixed(2);
                        $("#summary").html(total.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
                        $("#summary").html('');
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }

            function retailcommissions() {
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/retailcommissions',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {

                        var hhtml = "<tr><th>Staff Name</th><th>Month</th><th>Year</th><th>Total Products</th><th>Paid</th><th>Recoveries</th><th>Commission</th><th>Total</th><th>Action</th></tr>";
                        var total=0; var totalcommission=0; var totalpaid=0; var totalrecovery=0;
                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            total= total + parseFloat(data[x]['Total'].replace(',',''));
                            totalcommission=totalcommission+parseFloat(data[x]['Commission'].replace(',',''));
                            totalpaid=totalpaid+parseFloat(data[x]['Amount'].replace(',',''));
                            totalrecovery=totalrecovery+parseFloat(data[x]['Recovery'].replace(',',''));
                            totalcommission=totalrecovery+parseFloat(data[x]['invoice_commission']);
                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['staff_name'] + '</td>';
                            mhtml += '<td><span class="label label-danger">' + data[x]['Month'] + '</span></td>';
                            mhtml += '<td><span class="label label-danger">' + data[x]['Year'] + '</span></td>';
                            
                            mhtml += '<td>' + data[x]['Total Products'] + '</td>';
                            mhtml += '<td>' + data[x]['Amount'] + '</td>';
                            mhtml += '<td>' + data[x]['Recovery'] + '</td>';
                            mhtml += '<td>' + data[x]['invoice_commission'] + '</td>';
                            mhtml += '<td>' + data[x]['Total'] + '</td>';
                            //mhtml += '<td>' + data[x]['commission_perc'] + '%</td>';
                            //mhtml += '<td>' + data[x]['Commission'] + '</td>';
                            mhtml += '<td><button type="button" staff_id="' + data[x]['staff_id'] + '" class="btn btn-sm btn-info retail_commission_btn"><i class="fa fa-calculator"></i> Calculate</button></td>';
                            mhtml += '</tr>';
                        }
                        //console.log(mhtml);
                        var fhtml="<tr><th colspan=4></th><th>"+totalpaid.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</th><th>"+totalrecovery.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</th><th>"+totalcommission+"</th><th>"+total.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</th><th></th></tr>";
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);
                        total=total.toFixed(2);
                        $("#summary").html(total.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
                        $("#summary").html('');
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }

            function taxes() {
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/taxes',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {

                        var hhtml = "<tr><th>Month</th><th>Year</th><th>Tax Type</th><th>Total</th></tr>"

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {

                            mhtml += '<tr>';
                            mhtml += '<td><span class="label label-danger">' + data[x]['Month'] + '</span></td>';
                            mhtml += '<td><span class="label label-danger">' + data[x]['Year'] + '</span></td>';
                            mhtml += '<td>' + data[x]['Tax Type'] + '</td>';
                            mhtml += '<td>' + data[x]['Total'] + '</td>';
                            mhtml += '</tr>';
                        }
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }

            function attendance() {
                $('#tableshow').css('display', 'block');
                $('.atview').css('display', 'block');
                $("#cog").show();
                var date_array = get_dates();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/attendance',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var staff = data['staff'];
                        var attend = data['attendance'];

                        var currdate = new Date();
                        //console.log((currdate.getMonth()+1) + "---"+ currdate.getDate());
                        var inout = "";
                        inout += '<tr><td>--</td><td>---</td>';
                        var tabl = 'IN | OUT';
                        var th;
                        var hhtml = "<tr><th>Id</th><th>Staff</th>";
                        for (var d = 0; d <= date_array.length - 1; d++) {
                            var date = date_array[d].split("-");
                            hhtml += "<th style='min-width:60px; border-right: 3px solid rgb(220,220,220);'>" + date[2] + "<br>" + date[3] + "</th>";
                            inout += '<td style="border-right: 3px solid rgb(220,220,220);">' + tabl + '</td>';
                        }
                        inout += '</tr>';
                        hhtml += "</tr>"
                        var final = "";
                        final += hhtml;
                        final += inout;

                        var mhtml = "";
                        for (x = 0; x < staff.length; x++) {
                            mhtml += '<tr>';
                            mhtml += '<td>' + staff[x]['id_staff'] + '</td>';
                            mhtml += '<td><span class="label label-success">' + staff[x]['staff_fullname'] + '</span></td>';
                            var td = "";
                            var day = "";
                            var present = "";
                            for (var d = 0; d <= date_array.length - 1; d++) {
                                for (var i = 0; i < attend.length; i++) {
                                    var dates = date_array[d].split("-");
                                    var date_match = dates[0] + "-" + dates[1] + "-" + dates[2];
                                    var time_show = attend[i]['time_show'];
                                    var timeinout = "<td class='bg-primary' title='IN'>" + attend[i]['time_show'] + '</td>\n\
                                    <td class="bg-pink text-white" title="OUT">' + (attend[i]['time_show_out'] != null ?
                                            attend[i]['time_show_out'] : '') + "</td>";
                                    if (date_match == attend[i]['time_in'] && attend[i]['staff_id'] == staff[x]['id_staff']) {
                                        //present = "<span title = '"+time_show+"' >"+timeinout+"</span>";
                                        present = "<table  class='table table-bordered table-collapse'><tr>" + timeinout + "</tr></table>";

                                    }

                                }
                                td += "<td style='border-right: 3px solid rgb(220,220,220);'>" + present + "</td>";
                                present = "";
                            }

                            mhtml += td;
                            mhtml += '</tr>';
                            day = "";
                        }

                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(final);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');

                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                                dom: "frtlip",
                            <?php } ?>
                            
                            responsive: false,
                            //"scrollX": true,
                            "autoWidth": true,
                            "columnDefs": [
                                {"width": "50%", "targets": 3}
                            ]
                        });
                        $("#cog").hide();
                        attendance_month_view(data);
                    }
                });

            }

            function get_dates() {
                var day = 1000 * 60 * 60 * 24;
                var date1 = new Date(startdate.format('YYYY-MM-DD'));
                var date2 = new Date(enddate.format('YYYY-MM-DD'));
                var DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat'];
                var diff = (date2.getTime() - date1.getTime()) / day;
                var date_array = [];
                var days_array = [];
                for (var i = 0; i <= diff; i++)
                {
                    var xx = date1.getTime() + day * i;
                    var yy = new Date(xx);
                    
                   
                    
                    var date_return = yy.getFullYear() + "-" + ((yy.getMonth()+1)<10?'0':'') + (yy.getMonth() + 1) + "-" +  yy.getDate() + "-" + DAYS[yy.getDay()];
                    date_array[i] = date_return;
                    days_array[i] = DAYS[yy.getDay()];
                    console.log(date_return);
                    //console.log(yy.getFullYear() + "-" + (yy.getMonth() + 1) + "-" + yy.getDate());
                    //console.log(yy.getDate());
                }

                return date_array;
            }

            function attendance_view() {
                if ($('.atview span').text() == 'Dates View') {
                    $('#tableshow').css('display', 'block');
                    $('.atview span').text('Month View');
                    $('#otherview').css('display', 'none');
                } else {
                    $('.atview span').text('Dates View');
                    $('#tableshow').css('display', 'none');
                    $('#otherview').css('display', 'block');
                }
            }

            function attendance_month_view(data) {
                var date_array = get_dates();
                var staff = data['staff'];
                var attend = data['attendance'];
                var attend_month = data['attendance_month_view'];
                //console.log(attend_month);
                var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                var hhtml = "<tr><th>Id</th><th>Staff</th>";
                for (var d = 0; d <= month.length - 1; d++) {
                    var date = date_array[d].split("-");
                    hhtml += "<th style='min-width:60px;'>" + month[d] + "</th>";

                }
                hhtml += "</tr>"
                var mhtml = "";
                for (var x = 0; x < staff.length; x++) {

                    mhtml += '<tr>';
                    mhtml += '<td>' + staff[x]['id_staff'] + '</td>';
                    mhtml += '<td><span class="label label-success">' + staff[x]['staff_fullname'] + '</span></td>';
                    var td = "";
                    var day = "";
                    var present = "";
                    for (var d = 0; d <= month.length - 1; d++) {
                        for (var i = 0; i < attend_month.length; i++) {
                            if (month[d] == attend_month[i]['month'] && attend_month[i]['staff_id'] == staff[x]['id_staff']) {
                                var percentage = (attend_month[i]['present'] / attend_month[i]['monthdays']) * 100;
                                present = "<span class='label label-primary'>" + Math.round(percentage) + "%</span>";

                            }

                        }
                        td += "<td>" + present + "</td>";
                        present = "";
                    }

                    mhtml += td;
                    mhtml += '</tr>';
                    day = "";
                }

                $("#monthview").dataTable().fnDestroy();
                $("#monthview thead").html('');
                $("#monthview tbody").html('');
                $("#monthview thead").append(hhtml);
                $("#monthview tbody").append(mhtml);

                $('#monthview').DataTable({
                    lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                    stateSave: true, fixedHeader: {header: true},
                    <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                    buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                            extend: "excel",
                            className: "btn-sm"
                        }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                    <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                });
                $("#cog").hide();
            }

            function discount() {
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/discount',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {

                        var hhtml = "<tr><th>Date</th><th>Invoice Number</th><th>Customer</th><th>Reason</th><th>Actual Price</th><th class='text-danger'>Service Discount</th><th class='text-danger'>Invoice Discount</th><th >Discounted Price</th><th>Remarks</th><th>Invoiced By</th></tr>";
                        var totalserviced=0;
                        var totalinvoiced=0;
                        var mhtml = "";
                        var fhtml="";
                        for (x = 0; x < data.length; x++) {

                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['Date'] + '</td>';
                            var res = []; 
                            if(data[x]['invoice_number']){res = data[x]['invoice_number'].split("-")} else {res[2]=''};
                            if(data[x]['invoice_type']=="service"){                            
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ res[2] +'">' + data[x]['invoice_number'] + '</a></td>';
                            } else {
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ res[2] +'">' + data[x]['invoice_number'] + '</a></td>';
                            }
                             mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            
                            mhtml += '<td>' + data[x]['discount_type'] + '</td>';
                            mhtml += '<td >' + data[x]['price'] + '</td>';
                           
                            mhtml += '<td class="text-danger">' + data[x]['service_discount'] + '</td>';
                            totalserviced=totalserviced+parseFloat(data[x]['service_discount']);
                            mhtml += '<td class="text-danger">' + data[x]['invoice_discount'] + '</td>';
                            totalinvoiced=totalinvoiced+parseFloat(data[x]['invoice_discount']);
                            
                            mhtml += '<td >' + data[x]['discounted_price'] + '</td>';
                            mhtml += '<td >' + data[x]['discount_remarks'] + '</td>';
                          
                            mhtml += '<td >' + data[x]['created_by'] + '</td>';
                            mhtml += '</tr>';
                        }
                        //console.log(mhtml);
                        totalserviced=totalserviced.toFixed(2);
                        totalinvoiced=totalinvoiced.toFixed(2);
                        fhtml="<tr><th colspan=5></th><th>"+totalserviced+"</th><th>"+totalinvoiced+"</th><th colspan='3'></tr>";
                        
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);

                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }

            function voucher() {
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/voucher',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        // console.log("voucher: <?php echo date('d-m-Y', time()); ?>");
                        var hhtml = "<tr><th>Date</th><th>Valid Till</th><th>Voucher #</th><th>Customer</th><th class='text-danger'>Voucher Type</th><th>Payment Mode</th><th class='text-success'>Amount</th><th class='text-success'>Remaining Amount</th></tr>"
                        var todaydate = "<?php echo date('Y-m-d'); ?>";
                        var totalcash=0;
                        var totalcard=0;
                        var totalcheck=0;
                        var totalremaining=0;
                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            var d = data[x]['valid_date'];
                            var v = d.split("-");
                            var valid_date = v[2] + '-' + v[1] + '-' + v[0];
                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['date'] + '</td>';
                            mhtml += '<td>' + (data[x]['valid_date'] >= todaydate ? '<span  style="margin-right:5px">' + valid_date + '</span> <span class="label label-success">Valid</span>' : '<span style="margin-right:5px">' + valid_date + '</span> <span class="label label-danger">Expired</span>') + '</td>';
                            mhtml += '<td>' + data[x]['voucher_number'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td class="text-danger">' + data[x]['type'] + '</td>';
                            mhtml += '<td>' + data[x]['payment_mode'] + '</td>';
                            mhtml += '<td class="text-success">' + data[x]['amount'] + '</td>';
                            mhtml += '<td class="text-success">' + data[x]['remaining_amount'] + '</td>';
                            mhtml += '</tr>';
                            totalcash+= parseInt(data[x]['paid_cash']);
                            totalcard+= parseInt(data[x]['paid_card']);
                            totalcheck+= parseInt(data[x]['paid_check']);
                            totalremaining=totalremaining + parseInt(data[x]['remaining_amount']);
                        }
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport thead").append(hhtml);
                        var totalamount = 0;
                        for (x = 0; x < data.length; x++) {
                            totalamount += parseFloat(data[x]['amount']);
                        }
                        $("#tblreport tfoot").html('');
                        $("#tblreport tfoot").append("<tr><td></td><td></td><td></td><td></td><td></td><td>Total:</td><td> " + totalamount.toFixed(2) + "</td><td>"+totalremaining.toFixed(2) + "</td></tr>");
                        $("#summary").html('Cash: '+totalcash+'<br>Card:'+totalcard+'<br>Check:'+totalcheck);
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }

            function bad_debts() {
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/bad_debts',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {


                        var hhtml = "<tr><th>Date</th><th>ID</th><th>Customer</th><th>Sale Type</th><th >Discount</th><th>Paid</th><th >Balance</th><th class='text-success'>Net Amount</th></tr>"

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {

                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['Date'] + '</td>';
                            mhtml += '<td>' + data[x]['invoice_number'] + '</td>';
                            mhtml += '<td>' + data[x]['customer'] + '</td>';
                            mhtml += '<td>' + data[x]['Sale Type'] + '</td>';
                            mhtml += '<td class="text-danger">' + data[x]['Discount'] + '</td>';
                            mhtml += '<td class="text-info" style="font-weight:bold">' + data[x]['paid_amount'] + '</td>';
                            mhtml += '<td><span class="text-danger" style="font-weight:bold"><strike>' + data[x]['balance'] + '</strike></span></td>';
                            mhtml += '<td class="text-success" style="font-wieght:bold;">' + data[x]['Net Amount'] + '</td>';
                            mhtml += '</tr>';
                        }
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');

                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }

            function stock_status() {
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/stock_status',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD'), store_id:$("#selectstores option:selected").val()},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {

                        var hhtml = "<tr><th>ID</th><th>Brand</th><th>Product</th><th>Category</th><th>sku</th><th>type</th><th>BF</th><th>Added Manually</th><th>Purchased</th><th>Transfer In</th><th>Transfer Out</th><th>Sold</th><th>Used</th><th>Returned</th><th>Remaining</th><th>In Measure</th><th>Avg. Price</th><th>Value</th></tr>";

                        var mhtml = "";
                        var fhtml="";
                        var totalvalue=0;
                        for (x = 0; x < data.length; x++) {

                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['id_business_products'] + '</td>';
                            mhtml += '<td>' + data[x]['business_brand_name'] + '</td>';
                            
                            mhtml += '<td>' + data[x]['product'] + '</td>';
                            mhtml += '<td>' + data[x]['category'] + '</td>';
                            
                            mhtml += '<td>' + data[x]['sku'] + '</td>';
                            if(data[x]['professional']=='y'){
                                mhtml += '<td>Professional</td>';
                            }else {
                                mhtml += '<td>Retail</td>';            
                            }
                            
                            mhtml += '<td >' + (data[x]['BF'] != null ? data[x]['BF'] : "0") + '</td>';
                            mhtml += '<td >' + (data[x]['Qty'] != null ? data[x]['Qty'] : "0") + '</td>';
                            mhtml += '<td >' + (data[x]['purchased'] != null ? data[x]['purchased'] : "0") + '</td>';
                            mhtml += '<td >' + (data[x]['transfer_in'] != null ? data[x]['transfer_in'] : "0") + '</td>';
                            mhtml += '<td >' + (data[x]['transfer_out'] != null ? data[x]['transfer_out'] : "0") + '</td>';
                            
                            mhtml += '<td >' + (data[x]['sold'] != null ? data[x]['sold'] : '0') + '</td>';
                            mhtml += '<td >' + (data[x]['used'] != null ? data[x]['used'] : '0') + '</td>';
                            mhtml += '<td >' + (data[x]['used'] != null ? data[x]['returned'] : '0') + '</td>';
                            mhtml += '<td>' + data[x]['total_stock'] + '</td>';
                            
                            
                            var instock = Math.round(parseFloat(data[x]['qty_per_unit'])* parseFloat(data[x]['total_stock']));
                            mhtml += '<td>' + instock + ' ' +data[x]['measure_unit'] +'</td>';
                            
                            mhtml += '<td>' + data[x]['batch_amount'] + '</td>';
                            mhtml += '<td style="text-align:right">' + data[x]['stock_value'] + '</td>';
                            totalvalue=totalvalue+ parseFloat(data[x]['stock_value']);
                            mhtml += '</tr>';
                        }
                        //console.log(mhtml);
                        fhtml = "<tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th style='text-align:right'>"+totalvalue.toFixed(2)+"</th></tr>";
                        
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);

                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }
            
            function stock_status_brand(){
                var store_id="";
                if($("#selectbrandstores option:selected").val()!==""){
                    store_id=$("#selectbrandstores option:selected").val();
                }
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/stock_status_brand',
                    data: {brandid: $("#selectbrands option:selected").val(), producttype: $("#selectproducttype option:selected").val(), startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD'), store_id:store_id},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {

                        var hhtml = "<tr><th>ID</th><th>Brand</th><th>Product</th><th>Category</th><th>SKU</th><th>Type</th><th>Brought Forward</th><th>Added Manuall</th><th>Purchased</th><th>Transfered In</th><th>Transfered Out</th><th>Sold</th><th>Used</th><th>Returned</th><th>Remaining</th><th>In Measure</th><th>Avg. Price</th><th>Value</th></tr>";

                        var mhtml = "";
                        var totalvalue=0;
                        for (x = 0; x < data.length; x++) {

                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['id_business_products'] + '</td>';
                            mhtml += '<td>' + data[x]['business_brand_name'] + '</td>';
                            mhtml += '<td>' + data[x]['product'] + ' ' + data[x]['category'] + ' ' + data[x]['qty_per_unit'] + ' ' + data[x]['measure_unit']  + '</td>';
                            mhtml += '<td>' + data[x]['category'] + '</td>';
                            mhtml += '<td>' + data[x]['sku'] + '</td>';
                            if(data[x]['professional']=='y'){
                                mhtml += '<td>Professional</td>';
                            }else {
                                mhtml += '<td>Retail</td>';            
                            }
                            
                            mhtml += '<td>' + (data[x]['BF'] != null ? data[x]['BF'] : "0") + '</td>';
                            mhtml += '<td class="text-primary">' + (data[x]['Qty'] != null ? data[x]['Qty'] : "0") + '</td>';
                            mhtml += '<td class="text-primary">' + (data[x]['purchased'] != null ? data[x]['purchased'] : "0") + '</td>';
                            mhtml += '<td class="text-primary">' + (data[x]['transfer_in'] != null ? data[x]['transfer_in'] : "0") + '</td>';
                            mhtml += '<td class="text-danger">' + (data[x]['transfer_out'] != null ? data[x]['transfer_out'] : "0") + '</td>';
                            mhtml += '<td class="text-danger">' + (data[x]['sold'] != null ? data[x]['sold'] : '0') + '</td>';
                            mhtml += '<td class="text-danger">' + (data[x]['used'] != null ? data[x]['used'] : '0') + '</td>';
                            mhtml += '<td class="text-danger">' + (data[x]['used'] != null ? data[x]['returned'] : '0') + '</td>';
                            mhtml += '<td>' + data[x]['total_stock'] + '</td>';
                             var instock = Math.round(parseFloat(data[x]['qty_per_unit'])* parseFloat(data[x]['total_stock']));
                            mhtml += '<td>' + instock + ' ' +data[x]['measure_unit'] +'</td>';
                            mhtml += '<td>' + data[x]['batch_amount'] + '</td>';
                            mhtml += '<td style="text-align:right">' + data[x]['stock_value'] + '</td>';
                            totalvalue=totalvalue+ parseFloat(data[x]['stock_value']);
                            mhtml += '</tr>';
                        }
                        var fhtml = "<tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th style='text-align:right'>"+totalvalue.toFixed(2)+"</th></tr>";
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);

                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            
            }
            
        function expenses() {
            var totalexp=0;
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/expenses',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {

                        var hhtml = "<tr><th>PV ID</th><th>Created Date</th><th>Voucher Date</th><th>Account</th><th>Description</th><th>Payment Amount</th><th>Created by</th></tr>"

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            totalexp=totalexp+parseFloat(data[x]['voucher_amount']);
                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['id_account_vouchers'] + '</td>';
                            mhtml += '<td>' + data[x]['Date'] + '</td>';
                            mhtml += '<td>' + data[x]['VDate'] + '</td>';
                            mhtml += '<td>' + data[x]['account_head'] + '</td>';
                            mhtml += '<td>' + data[x]['description'] + '</td>';
                            mhtml += '<td class="text-danger" style="font-weight:bold">' + data[x]['expenses'] + '</td>';
                            mhtml += '<td>' + data[x]['created_by'] + '</td>';
                            mhtml += '</tr>';
                        }
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');
                        totalexp=totalexp.toFixed(2);
                        $("#summary").html("Total Expense: " + totalexp.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }
            
            
            function cancelled_visits() {
            
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/cancelled_visits',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        
                        var hhtml = "<tr><th>Staff</th><th>VisitID</th><th>Booked on </th><th>Customer</th><th>Cell</th><th>Appointment Date</th><th>Category</th><th>Services</th><th class='text-danger'>Business Lost</th><th>Cancellation Reason</th><th>By</th><th>SMS (reminder)</th><th>Call</th><th>Email</th></tr>";

                        var mhtml = "";
                        var visit_id=0;
                        var total_lost=0;
                        for (x = 0; x < data.length; x++) {
                            total_lost = total_lost + parseFloat(data[x]['service_rate']);
                             mhtml += '<tr>';
                            if(data[x]['id_customer_visits'] !== visit_id){
                                mhtml += '<td>' + data[x]['staff_name'] + '</td>';
                                mhtml += '<td>' + data[x]['id_customer_visits'] + '</td>';
                                mhtml += '<td>' + data[x]['customer_visit_date'] + '</td>';                               
                                mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                                mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                                mhtml += '<td>' + data[x]['visit_service_start'] + '</td>';
                                mhtml += '<td>' + data[x]['service_category'] + '</td>';
                                mhtml += '<td>' + data[x]['service_name'] + ' ' + data[x].service_desc + '</td>';
                                mhtml += '<td class="text-danger" style="text-align:right">' + data[x]['service_rate'] + '</td>';
                                mhtml += '<td>' + data[x]['cancelreason'] + '</td>';
                                mhtml += '<td>' + data[x]['canceled_by'] + '</td>';
                                mhtml += '<td>' + data[x]['reminder_sms'] + '</td>';
                                mhtml += '<td>' + data[x]['reminder_call'] + '</td>';
                                mhtml += '<td>' + data[x]['reminder_email'] + '</td>';
                            } else {
                                mhtml += '<td></td><td></td><td></td><td></td><td></td>' ;
                                mhtml += '<td>' + data[x]['visit_service_start'] + '</td>';
                                mhtml += '<td>' + data[x]['service_category'] + '</td>';
                                mhtml += '<td>' + data[x]['service_name'] + ' ' + data[x].service_desc + '</td>';
                                mhtml += '<td class="text-danger"  style="text-align:right">' + data[x]['service_rate'] + '</td>';
                                mhtml += '<td>' + data[x]['cancelreason'] + '</td>';
                                mhtml += '<td>' + data[x]['canceled_by'] + '</td>';
                                mhtml += '<td>' + data[x]['reminder_sms'] + '</td>';
                                mhtml += '<td>' + data[x]['reminder_call'] + '</td>';
                                mhtml += '<td>' + data[x]['reminder_email'] + '</td>';
                            }
                            mhtml += '</tr>';
                            visit_id=data[x]['id_customer_visits'] ;
                        }
                        
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('<tr><th colspan="8"></th><th class="text-danger" style="text-align:right">'+parseFloat(total_lost).toFixed(2)+'</th><th colspan="5"></th></tr>');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0,
                            ordering: false
                        });
                        $("#cog").hide();

                    }
                });
            }
            
            function open_visits() {
            
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/open_visits',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD'), id_service_type:$("#selectservicetype option:selected").val(), service_type:$("#selectservicetype option:selected").text(), id_service_category:$("#selectservicecategory option:selected").val(), service_category:$("#selectservicecategory option:selected").text(), id_business_services:$("#selectservice option:selected").val(), service_name:$("#selectservice option:selected").text(), staff_id:$("#selectstaff option:selected").val()},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        
                        var hhtml = "<tr><th>Appointment</th><th>Visit ID</th><th>Booked On</th><th>Customer</th><th>Cell</th><th>Staff</th><th>Type</th><th>Category</th><th>Services</th><th>SMS (reminder)</th><th>Call</th><th>Email</th></tr>"
                        var lastvisitid=0;
                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            if(lastvisitid!==data[x]['id_customer_visits'] ){
                                mhtml += '<tr style="background:#fff">';
                                mhtml += '<td>' + data[x]['visit_service_start'] + '</td>';
                                mhtml += '<td>' + data[x]['id_customer_visits'] + '</td>';
                                mhtml += '<td>' + data[x]['date'] + '</td>';
                                
                            } else {
                                mhtml += '<tr style="background:#fff">';
                                mhtml += '<td>' + data[x]['visit_service_start'] + '</td>';
                                mhtml += '<td></td><td></td>';
                            }
                            mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                            
                            mhtml += '<td>' + data[x]['staff_name'] + '</td>';
                            mhtml += '<td>' + data[x]['service_type'] + '</td>';
                            mhtml += '<td>' + data[x]['service_category'] + '</td>';
                            mhtml += '<td>' + data[x]['service_name'] + '</td>';
                            mhtml += '<td>' + data[x]['reminder_sms'] + '</td>';
                            mhtml += '<td>' + data[x]['reminder_call'] + '</td>';
                            mhtml += '<td>' + data[x]['reminder_email'] + '</td>';
                            mhtml += '</tr>';
                            lastvisitid = data[x]['id_customer_visits'];
                        }
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            ordering: false,
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                            
                        });
                        $("#cog").hide();                       
                    }
                });
            }
            function advance_collected(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/advance_collected',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var advancetotal=0;
                        var hhtml = "<tr><th>AdvanceDate</th><th>VisitDate</th><th>Customer</th><th>Cell</th><th>Type</th><th>Category</th><th>Status</th><th>Advance Mode</th><th>Advance</th><th>Advance Inst.</th></tr>"

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            var mhref="";
                            mhtml += '<tr>';
                            if(data[x]['service_flag']=="servicetype"){mhref="<?php echo base_url();?>invoice_controller/print_advance/";}
                            else {mhref="<?php echo base_url();?>print_booking/";}
                            mhtml += '<td ><a style="text-decoration:underline" target="_blank" href="' + mhref + data[x]['id_customer_visits'] +'">' + data[x]['advance_date'] + '</a></td>';
                            mhtml += '<td>' + data[x]['visitdate'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                            mhtml += '<td>' + data[x]['service_type'] + '</td>';
                            mhtml += '<td>' + data[x]['service_category'] + '</td>';
                            mhtml += '<td>' + data[x]['visit_status'] + '</td>';
                            mhtml += '<td>' + data[x]['advance_mode'] + '</td>';
                            mhtml += '<td class="text-primary">' + data[x]['advance_amount'] + '</td>';
                            mhtml += '<td>' + data[x]['advance_inst'] + '</td>';
                            mhtml += '</tr>';
                            
                            advancetotal=advancetotal + parseFloat(data[x]['advance_amount']);
                        }
                        var fhtml="<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td>"+advancetotal+"</td><td></td></tr>"
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true, footer: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }
            
            function retained_amount(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/retained_amount',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var retainedamount=0;
                        var hhtml = "<tr><th>Invoice ID</th><th>Invoice Date</th><th>Customer Name</th><th>Customer Cell</th><th>Payment Mode</th><th>Created By</th><th>Retained Amount</th>";

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            
                            mhtml += '<tr>';
                            if(data[x]['invoice_type']=="service"){                            
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ data[x]['id_invoice'] +'">' + data[x]['id_invoice'] + '</a></td>';
                            } else {
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ data[x]['id_invoice'] +'">' + data[x]['id_invoice'] + '</a></td>';
                            }
                            
                              mhtml += '<td>' + data[x]['invoice_date'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                            mhtml += '<td>' + data[x]['payment_mode'] + '</td>';
                            mhtml += '<td>' + data[x]['created_by'] + '</td>';
                            mhtml += '<td>' + data[x]['retained_amount'] + '</td>';
                            
                            mhtml += '</tr>';
                            
                            retainedamount=retainedamount + parseFloat(data[x]['retained_amount']);
                        }
                        var fhtml="<tr><td></td><td></td><td></td><td></td><td></td><td></td><td>"+retainedamount.toFixed(2)+"</td></tr>"
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport tfoot").html('');
                        
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true, footer: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }
            
            function retained_used(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/retained_used',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var retainedamount=0;
                        var hhtml = "<tr><th>Invoice ID</th><th>Invoice Date</th><th>Customer Name</th><th>Customer Cell</th><th>Payment Mode</th><th>Created By</th><th>Retained Used</th>";

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            
                            mhtml += '<tr>';
                            if(data[x]['invoice_type']=="service"){                            
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ data[x]['id_invoice'] +'">' + data[x]['id_invoice'] + '</a></td>';
                            } else {
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ data[x]['id_invoice'] +'">' + data[x]['id_invoice'] + '</a></td>';
                            }
                            
                             mhtml += '<td>' + data[x]['invoice_date'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                            mhtml += '<td>' + data[x]['payment_mode'] + '</td>';
                            mhtml += '<td>' + data[x]['created_by'] + '</td>';
                            mhtml += '<td>' + data[x]['retained_amount_used'] + '</td>';
                            
                            mhtml += '</tr>';
                            
                            retainedamount=retainedamount + parseFloat(data[x]['retained_amount']);
                        }
                        var fhtml="<tr><td></td><td></td><td></td><td></td><td></td><td></td><td>"+retainedamount.toFixed(2)+"</td></tr>"
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport tfoot").html('');
                        
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true, footer: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }
            
            function receivables(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/receivables',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var advancetotal=0;
                        var hhtml = "<tr><th>Visit ID</th><th>Customer Name</th><th>Customer Cell</th><th>Visit Date</th><th>Price</th><th>Adv.</th><th>Receivable</th></tr>";

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            var mhref="";
                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['id_customer_visits'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                            mhtml += '<td>' + data[x]['mDate'] + '</td>';
                            mhtml += '<td>' + data[x]['price'] + '</td>';
                            mhtml += '<td>' + data[x]['advance'] + '</td>';
                            mhtml += '<td>' + data[x]['receivables'] + '</td>';
                            mhtml += '</tr>';
                            
                            advancetotal=advancetotal + parseFloat(data[x]['receivables']);
                        }
                        var fhtml="<tr><th></th><th></th><th></th><th></th><th></th><th></th><th>"+advancetotal+"</th></tr>"
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true, footer: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            
            }
            
            function recoverinvoices(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/recoveryinvoices',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var balancetotal=0;
                        var hhtml = "<tr><th>ID</th><th>Branch</th><th>Type</th><th>Invoice #</th><th>Visit Date</th><th>Invoice Date</th><th>Customer Name</th><th>Customer Cell</th><th>Balance</th><th>Sub Total</th><th>Adv.</th><th>Discount</th><th>Gross Amount</th><th>Net Amount</th><th>Created By</th></tr>";

                        var mhtml = "";
                        
                        for (x = 0; x < data.length; x++) {
                            var mhref="";
                            mhtml += '<tr>';
                            
                            mhtml += '<td><a target="_blank" href="<?php echo base_url();?>open_recovery_invoice/'+ data[x]['id_invoice'] +'/'+ data[x]['visit_id'] +'">' + data[x]['id_invoice'] + '</a></td>';
                            mhtml += '<td>' + data[x]['business_name'] + '</td>';
                            mhtml += '<td>' + data[x]['invoice_type'] + '</td>';
                            mhtml += '<td>' + data[x]['invoice_number'] + '</td>';
                            mhtml += '<td>' + data[x]['visit_time'] + '</td>';
                            mhtml += '<td>' + data[x]['invoice_date'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                            mhtml += '<td class="text-danger">' + data[x]['balance'] + '</td>';
                            mhtml += '<td>' + data[x]['sub_total'] + '</td>';
                            mhtml += '<td>' + data[x]['advance_amount'] + '</td>';
                            mhtml += '<td>' + data[x]['discount'] + '</td>';
                            mhtml += '<td>' + data[x]['gross_amount'] + '</td>';
                            mhtml += '<td>' + data[x]['net_amount'] + '</td>';
                            mhtml += '<td>' + data[x]['created_by'] + '</td>';
                            mhtml += '</tr>';
                            
                            balancetotal=balancetotal + parseFloat(data[x]['balance']);
                        }
                        var fhtml="<tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th class='text-danger'>"+balancetotal+"</th><th></th></tr>"
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true, footer: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            
            
            }
            
            function loyaltyredemption(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                
                var customer = $('#selectcustomer').select2('data');
                var totalearned=0;
                var totalused=0;
                
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/loyaltyredemption',
                    data: {customerid: customer.id_customers, startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD') },
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var hhtml = "<tr><th>Name</th><th>Cell</th><th>Card</th><th>Address</th><th>Birthday</th><th>Anniversary</th><th>Points Earned</th><th>Points Used</th><th>Remarks</th><th>By</th><th>Invoices</th><th>On</th></tr>"

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                            mhtml += '<td>' + data[x]['card'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_address'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_birthday'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_anniversary'] + '</td>';
                            mhtml += '<td>' + data[x]['earned'] + '</td>';
                            totalearned = totalearned +  parseFloat(data[x]['earned']);
                            mhtml += '<td>' + data[x]['used'] + '</td>';
                            totalused = totalused +  parseFloat(data[x]['used']);
                            mhtml += '<td>' + data[x]['remarks'] + '</td>';
                            mhtml += '<td>' + data[x]['created_by'] + '</td>';
                            
                            if(data[x]['invoice_type']=="service"){                            
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ data[x]['id_invoice']+'">' + data[x]['id_invoice'] + '</a></td>';
                            } else {
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ data[x]['id_invoice']+'">' + data[x]['id_invoice'] + '</a></td>';
                            }
                            
                            mhtml += '<td>' + data[x]['invoice_date'] + '</td>';
                            mhtml += '</tr>';
                        }
                        var available = parseInt(totalearned) - parseInt(totalused); 
                        var fhtml = "<tr><th>Name</th><th>Cell</th><th>Card</th><th>Address</th><th>Birthday</th><th>Anniversary</th><th>"+Math.round(totalearned, 2)+"</th><th>"+Math.round(totalused,2)+"</th><th>Available:"+available +"</th><th>By</th><th>Invoices</th><th>On</th></tr>"
                        
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            
                        
            }
            
            function sharedcustomers(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/sharedcustomers',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD'), business_id:$("#selectbusiness option:selected").val()},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var balancetotal=0;
                        var loyaltyused=0;
                        var hhtml = "<tr><th>ID</th><th>Type</th><th>Invoice #</th><th>Visit Date</th><th>Invoice Date</th><th>Customer Name</th><th>Customer Cell</th><th>Share From</th><th>Balance</th><th>Sub Total</th><th>Adv.</th><th>Discount</th><th>Gross Amount</th><th>Net Amount</th><th>Loyalty Used</th></tr>";

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            var mhref="";
                            mhtml += '<tr>';
                            if(data[x]['invoice_type']=="service"){                            
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ data[x]['id_invoice']+'">' + data[x]['id_invoice'] + '</a></td>';
                            } else {
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ data[x]['id_invoice']+'">' + data[x]['id_invoice'] + '</a></td>';
                            }
                            
                            mhtml += '<td>' + data[x]['invoice_type'] + '</td>';
                            mhtml += '<td>' + data[x]['invoice_number'] + '</td>';
                            mhtml += '<td>' + data[x]['visit_time'] + '</td>';
                            mhtml += '<td>' + data[x]['invoice_date'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                            mhtml += '<td class="text-primary"><b>' + data[x]['business_name'] + '</b></td>';
                            mhtml += '<td class="text-danger">' + data[x]['balance'] + '</td>';
                            mhtml += '<td>' + data[x]['sub_total'] + '</td>';
                            mhtml += '<td>' + data[x]['advance_amount'] + '</td>';
                            mhtml += '<td>' + data[x]['discount'] + '</td>';
                            mhtml += '<td>' + data[x]['gross_amount'] + '</td>';
                            mhtml += '<td>' + data[x]['net_amount'] + '</td>';
                            mhtml += '<td>' + data[x]['loyalty_used'] + '</td>';
                            mhtml += '</tr>';
                            
                            balancetotal=balancetotal + parseFloat(data[x]['balance']);
                            loyaltyused=loyaltyused + parseFloat(data[x]['loyalty_used']);
                        }
                        var fhtml="<tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th class='text-danger'>"+balancetotal+"</th><th></th><th></th><th></th><th></th><th></th><th class='text-success'>"+loyaltyused+"</tr>"
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true, footer: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            
                        
            }
            
            function onlineappointments(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/onlineappointments',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        var balancetotal=0;
                        var loyaltyused=0;
                        var hhtml = "<tr><th>ID</th><th>Customer</th><th>Cell</th><th>Booked On</th><th>Status</th><th>Appointment Time</th><th>Service</th><th>Assigned To</th></tr>";

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            var mhref="";
                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['id_customer_visits'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                            mhtml += '<td>' + data[x]['booked_on'] + '</td>';
                            mhtml += '<td>' + data[x]['visit_status'] + '</td>';
                            mhtml += '<td>' + data[x]['appointment_time'] + '</td>';
                            mhtml += '<td>' + data[x]['service_name'] + '</td>';
                            mhtml += '<td>' + data[x]['assigned_to'] + '</td>';
                            mhtml += '</tr>';
                            
                            balancetotal=balancetotal + parseFloat(data[x]['balance']);
                            loyaltyused=loyaltyused + parseFloat(data[x]['loyalty_used']);
                        }
                        var fhtml="<tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th></tr>";
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html(fhtml);
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true, footer: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            
                        
            }
            
            function careof_customers(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/careofcustomers',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        
                        var hhtml = "<tr><th>Name</th><th>Careof</th><th>Cell</th><th>Email</th><th>Address</th><th>Birthday</th><th>Anniversary</th><th>Alerts</th><th>Allergies</th><th>Added</th><th>By</th></tr>"

                        var mhtml = "";
                        var i=0;
                        for (x = 0; x < data.length; x++) {
                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_careof'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_email'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_address'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_birthday'] + '</td>';
                            mhtml += '<td>' + data[x]['anv'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_alert'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_allergies'] + '</td>';
                            //mhtml += '<td>' + data[x]['m'] + '</td>';
                            mhtml += '<td>' + data[x]['created'] + '</td>';
                            mhtml += '<td>' + data[x]['created_by'] + '</td>';
                            mhtml += '</tr>';
                            i++;
                        }
                        //console.log(mhtml);
                        $("#summary").html(i);
                        
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
                        
            }
            
            function requested(){
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/requested',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {

                        var hhtml = "<tr><th>ID #</th><th>Date</th><th>Customer</th><th>Staff</th><th>Category</th><th>Service</th><th>Price</th><th>Service Discount</th><th>Invoice Discount</th><th>Discounted Price</th></tr>";

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {

                            mhtml += '<tr>';
                            var res = []; 
                            if(data[x]['invoice_number']){res = data[x]['invoice_number'].split("-")} else {res[2]=''};
                            if(data[x]['invoice_type']=="service"){                            
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ res[2] +'">' +  data[x]['invoice_number'] + '</a></td>';
                            } else {
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ res[2] +'">' +  data[x]['invoice_number'] + '</a></td>';
                            }
                             mhtml += '<td>' + data[x]['invoice_date'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td>' + data[x]['staff_name'] + '</td>';
                            mhtml += '<td>' + data[x]['service_category'] + '</td>';
                            mhtml += '<td>' + data[x]['service_name'] + '</td>';
                            mhtml += '<td>' + data[x]['price'] + '</td>';
                            mhtml += '<td>' + data[x]['service_discount'] + '</td>';
                            mhtml += '<td>' + data[x]['invoice_discount'] + '</td>';
                           mhtml += '<td>' + data[x]['discounted_price'] + '</td>';
                            
                        
                            mhtml += '</tr>';
                        }
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');

                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }
            
            
            function utilization(){
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/staff_utilization',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        console.log(data);
                        var dutyhours=data["dutyhours"];
                        data=data["data"];
                        
                        var hhtml = "<tr><th>Staff ID</th><th>Staff</th><th>Customer</th><th>Service</th><th>Duty Hours</th><th>Service Duration</th><th>Total Utilization</th><th class='text-danger'>UnUtilized Time</th></tr>";
                        
                        var mhtml = "";
                        var laststaffid=0; var staffname=''; var customername=''; var totalcustomers=0; var totalservices=0; var totalstafftime="";
                        for (x = 0; x < data.length; x++) {
                            if(laststaffid>0 && laststaffid == data[x]['staff_id']){
                                mhtml += '<tr>';                            
                                mhtml += '<td></td>';
                                mhtml += '<td></td>';
                                mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                                if(customername !== data[x]['customer_name']){totalcustomers ++;}
                                customername= data[x]['customer_name'];
                                mhtml += '<td>' + data[x]['service_name'] + '</td>';
                                totalservices++;
                                mhtml += '<td></td>';
                                mhtml += '<td>' + data[x]['TimeDiff'] + '</td>';
                                mhtml += '<td></td>';
                                mhtml += '<td></td>';
                               
                                totalstafftime = addtime(totalstafftime, data[x]['TimeDiff']);
                                mhtml += '</tr>';
                                
                            } else { 
                           //add sum row 
                                if(laststaffid>0){
                                    mhtml += '<tr>';                            
                                    mhtml += '<td style="font-weight:bold; border-bottom:1px solid #808080;"></td>';
                                    mhtml += '<td style="font-weight:bold; border-bottom:1px solid #808080;">'+staffname+'</td>';
                                    mhtml += '<td style="font-weight:bold; border-bottom:1px solid #808080;">Total Customers: '+totalcustomers+'</td>';
                                    mhtml += '<td style="font-weight:bold; border-bottom:1px solid #808080;">'+totalservices+'</td>';
                                    mhtml += '<td style="font-weight:bold; border-bottom:1px solid #808080;">' + dutyhours["ldutyhours"] + '</td>';
                                    mhtml += '<td style="font-weight:bold; border-bottom:1px solid #808080;"></td>';
                                    mhtml += '<td style="font-weight:bold; border-bottom:1px solid #808080;">' + totalstafftime + '</td>';
                                    var unutilizedtime = subtracttime(dutyhours["ldutyhours"],totalstafftime);
                                    mhtml += '<td style="font-weight:bold; border-bottom:1px solid #808080;" class="text-danger">'+unutilizedtime+'</td>';
                                    mhtml += '</tr>';
                                }
                            //start new staff
                                staffname=data[x]['staff_fullname'] ;
                                mhtml += '<tr>';                            
                                mhtml += '<td>' + data[x]['staff_id'] + '</td>';
                                mhtml += '<td style="font-weight:bold">' + data[x]['staff_fullname'] + '</td>';
                                mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                                customername= data[x]['customer_name']; totalcustomers=1; totalservices=1;
                                mhtml += '<td>' + data[x]['service_name'] + '</td>';
                                mhtml += '<td></td>';
                                mhtml += '<td>' + data[x]['TimeDiff'] + '</td>';
                                mhtml += '<td></td>';
                                mhtml += '<td></td>';
                                totalstafftime=data[x]['TimeDiff'];
                                mhtml += '</tr>';
                                
                           }
                           laststaffid=data[x]['staff_id'] ;
                           
                        }
                        //add the last sum row 
                        if(laststaffid>0){
                            mhtml += '<tr>';                            
                            mhtml += '<td style="font-weight:bold; border-bottom:1px solid #808080;"></td>';
                            mhtml += '<td style="font-weight:bold; border-bottom:1px solid #808080;">'+staffname+'</td>';
                            mhtml += '<td style="font-weight:bold; border-bottom:1px solid #808080;">Total Customers: '+totalcustomers+'</td>';
                            mhtml += '<td style="font-weight:bold; border-bottom:1px solid #808080;">'+totalservices+'</td>';
                            mhtml += '<td style="font-weight:bold; border-bottom:1px solid #808080;">' + dutyhours["ldutyhours"] + '</td>';
                            mhtml += '<td style="font-weight:bold; border-bottom:1px solid #808080;"></td>';
                            mhtml += '<td style="font-weight:bold; border-bottom:1px solid #808080;">' + totalstafftime + '</td>';
                            var unutilizedtime = subtracttime(dutyhours["ldutyhours"],totalstafftime);
                            mhtml += '<td style="font-weight:bold; border-bottom:1px solid #808080;" class="text-danger">'+unutilizedtime+'</td>';
                            mhtml += '</tr>';
                        }
                        
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');

                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0,
                            ordering: false
                        });
                        $("#cog").hide();

                    }
                });
            }
            
            
            function utilization_summary(){
                $('#tableshow').css('display', 'block');
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/staff_utilization_summary',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        console.log(data);
                        var dutyhours=data["dutyhours"];
                        
                        data=data["data"];
                        
                        var hhtml = "<tr><th>Staff ID</th><th>Staff</th><th>From</th><th>To</th><th>Duty Hours</th><th>Total Utilization</th></tr>";
                        
                        var mhtml = ""; var totalstafftime='';
                        for (x = 0; x < data.length; x++) {
                            mhtml += '<tr>';                            
                            mhtml += '<td>' + data[x]['staff_id'] + '</td>';
                            mhtml += '<td>' + data[x]['staff_fullname'] + '</td>';                                
                            mhtml += '<td>' + data[x]['from'] + '</td>';
                            mhtml += '<td>' + data[x]['to'] + '</td>';
                            mhtml += '<td>' + data[x]["dutyhours"] + '</td>';
                            mhtml += '<td>' + data[x]['utilized'] + '</td>';
                           

                            
                            mhtml += '</tr>';                                
                        }
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');

                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0,
                            ordering: false
                        });
                        $("#cog").hide();

                    }
                });
            }
            
            function addtime(time1, time2){
                var pad = function(num) { return ("0"+num).slice(-2); }
            
                var totalDuration = time1;
                totalDuration = totalDuration.split(":");
                var hrs = parseInt(totalDuration[0],10);
                var min = parseInt(totalDuration[1],10);
                var sec = parseInt(totalDuration[2],10);
                var totalDurationSec = sec + (60*min) + (60*60*hrs); 
                
                
                var currentDuration = time2;
                currentDuration = currentDuration.split(":");
                var hrs = parseInt(currentDuration[0],10);
                var min = parseInt(currentDuration[1],10);
                var sec = parseInt(currentDuration[2],10);
                var currDurationSec = sec + (60*min) + (60*60*hrs); 
                
                
                var totalSeconds = totalDurationSec +=currDurationSec;
                
                var hours = Math.floor(totalSeconds / 3600);
                totalSeconds %= 3600;
                var minutes = Math.floor(totalSeconds / 60);
                var seconds = totalSeconds % 60;
                return pad(hours)+":"+pad(minutes)+":"+pad(seconds);
            
            }
            
            function subtracttime(time1,time2){
                var pad = function(num) { return ("0"+num).slice(-2); }
            
                var totalDuration = time1;
                totalDuration = totalDuration.split(":");
                var hrs = parseInt(totalDuration[0],10);
                var min = parseInt(totalDuration[1],10);
                var sec = parseInt(totalDuration[2],10);
                var totalDurationSec = sec + (60*min) + (60*60*hrs); 
                
                
                var currentDuration = time2;
                currentDuration = currentDuration.split(":");
                var hrs = parseInt(currentDuration[0],10);
                var min = parseInt(currentDuration[1],10);
                var sec = parseInt(currentDuration[2],10);
                var currDurationSec = sec + (60*min) + (60*60*hrs); 
                
                
                var totalSeconds =  totalDurationSec -= currDurationSec;
                
                var hours = Math.floor(totalSeconds / 3600);
                totalSeconds %= 3600;
                var minutes = Math.floor(totalSeconds / 60);
                var seconds = totalSeconds % 60;
                return pad(hours)+":"+pad(minutes)+":"+pad(seconds);
            }
            
            function cash_register(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/cash_register',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        //console.debug(data);
                        var transaction=data.transactions;
                        var denomination=data.denominations;
                        var expenses=data.expenses;
                        var vouchers=data.vouchers;
                        var yesterdaytill=data.yesterdaytill;
                       
                        
                        var hhtml = "<tr><th>WorkDate</th><th>Gross Sale</th><th>+ Advance</th><th>+ Vochers</th><th>+ Recovery</th><th>+ Retained</th><th>- Balance</th><th>- Expense</th><th>= Total Transactions</th><th>Yesterday's Till</th><th>Additional Amount</th><th>Tomorrow's Till</th><th>Collection</th><th>Cash Received</th><th>Cash Returned</th><th>Cash</th><th>Card</th><th>Check</th><th>Denomination Count</th><th>Difference</th><th>Remarks</th></tr>";
                        var mhtml = "";
                        
                        for(x=0; x<transaction.length;x++){
                                var cashReceived = parseFloat(transaction[x].Cash)>0 ? parseFloat(transaction[x].Cash) + parseFloat(transaction[x].totalReturnCash) : transaction[x].Cash;
                                var cashReturned = transaction[x].totalReturnCash !== null ? transaction[x].totalReturnCash : 0;
                                var totalCash = transaction[x].totalCash !== null ? transaction[x].totalCash : 0;
                                var totalSale = transaction[x].totalSale !== null ? transaction[x].totalSale : 0;
                                var totalBalance = transaction[x].totalBalance !== null ? transaction[x].totalBalance : 0;
                                var totalRecovery = transaction[x].totalRecovery !== null ? transaction[x].totalRecovery : 0;
                                var totalAdvance = transaction[x].totalAdvance !== null ? transaction[x].totalAdvance : 0;
                                var totalService = transaction[x].totalService !== null ? transaction[x].totalService : 0;
                                var totalRetail = transaction[x].totalRetail !== null ? transaction[x].totalRetail : 0;
                                var totalExpense = expenses[x].today_expenses !== null ? expenses[x].today_expenses : 0;
                                //var totalExpense = denomination[x].daily_expense !== null ? denomination[x].daily_expense : 0;
                                var totalVoucher = vouchers[x].totalVoucherAmount !== null ? vouchers[x].totalVoucherAmount : 0;
                                var cctip = transaction[x].cctip !== null ? transaction[x].cctip : 0;
                                
                                var Cash = transaction[x].Cash !== null ? parseFloat(transaction[x].Cash) - parseFloat(cctip) - parseFloat(cashReturned) : 0;
                                var Card = transaction[x].Card !== null ? transaction[x].Card : 0;
                                var Checks = transaction[x].Checks !== null ? transaction[x].Checks : 0;
                               
                                var Voucher = transaction[x].totalVoucher !== null ? transaction[x].totalVoucher : 0;

                                var totalVoucherCash = vouchers[x].Cash !== null ? vouchers[x].Cash : 0;
                                var totalVoucherCard = vouchers[x].Card !== null ? vouchers[x].Card : 0;
                                var totalVoucherChecks = vouchers[x].Checks !== null ? vouchers[x].Checks : 0;
                                
                                
                                
                                var yestertill = yesterdaytill[x].till_amounts !== null ? yesterdaytill[x].till_amounts : 0;
                                var totaltillamounts = denomination[x].till_amounts !== null ?  denomination[x].till_amounts : 0;
                                var additionalamount= denomination[x].cash_addition !== null ? denomination[x].cash_addition : 0;
                                var totalRetained= transaction[x].totalRetained !== null ? transaction[x].totalRetained : 0;
                                var calCash=parseFloat(parseInt(Cash) + parseInt(totalVoucherCash)).toFixed(2);
                                totalCash = parseFloat(calCash - parseInt(totalExpense)).toFixed(2);
                                totalCard = parseFloat(parseInt(Card) + parseInt(totalVoucherCard)).toFixed(2);
                                totalCheck= parseFloat(parseInt(Checks) + parseInt(totalVoucherChecks)).toFixed(2);
                                
                                
                                totalSale = parseFloat(parseInt(totalSale) + parseInt(totalVoucher)).toFixed(2);
                                
                                var cashInHand= denomination[x].cash !== null ? denomination[x].cash : 0;
                                var difference= denomination[x].diff !== null ? denomination[x].diff : 0;
                                
                                var diff=((parseFloat(parseInt(cashInHand) - parseInt(yestertill) - parseInt(additionalamount)) - parseInt(totalCash)).toFixed(2));
                               //  var diff = parseFloat(parseInt(cashInHand) - parseInt(totalCash)).toFixed(2) ;
                                 
                                var paymentCash = (parseFloat(parseInt(Cash) + parseInt(totalVoucherCash)).toFixed(2));
                                var paymentCard = (parseFloat(parseInt(Card) + parseInt(totalVoucherCard)).toFixed(2));
                                var paymentChecks = (parseFloat(parseInt(Checks) + parseInt(totalVoucherChecks)).toFixed(2));
                                
                                var totalTransaction=parseFloat((parseFloat(totalSale)+parseFloat(totalAdvance)+parseFloat(totalRecovery)+parseFloat(totalRetained))-(parseFloat(totalBalance)+parseFloat(totalExpense))).toFixed(2);
                                var collection = parseFloat(parseInt(paymentCash)+parseInt(paymentCard)+parseInt(paymentChecks)).toFixed(2);
                                
                                mhtml += '<tr>';
                                mhtml += '<td>'+ transaction[x].passeddate +'</td>';
                               
                                mhtml += '<td style="font-weight:bold; text-align:right">'+ totalSale + '</td>';
                               
                                mhtml += '<td class="text-default" style="text-align:right">' + totalAdvance + '</td>';
                                mhtml += '<td class="text-default" style="text-align:right">' + totalVoucher + '</td>';
                                
                                mhtml += '<td class="text-success" style="text-align:right">' + totalRecovery + '</td>';
                                mhtml += '<td style="text-align:right">'+ totalRetained +'</td>';
                                mhtml += '<td class="text-danger" style="text-align:right">' + totalBalance + '</td>';
                                mhtml += '<td class="text-danger" style="text-align:right">' + totalExpense + '</td>';
                                
                                mhtml += '<td class="text-default" style="font-weight:bold; text-align:right">'+ totalTransaction + '</td>';
                                
                                mhtml += '<td style="text-align:right">'+ yestertill +'</td>';
                                mhtml += '<td style="text-align:right">'+ additionalamount +'</td>';
                                
                                mhtml += '<td style="text-align:right">'+ totaltillamounts +'</td>';
                                mhtml += '<td class="text-primary" style="text-align:right">'+ collection + '</td>';
                                mhtml += '<td class="text-primary" style="text-align:right">'+ cashReceived +'</td>';
                                mhtml += '<td class="text-primary" style="text-align:right">'+ cashReturned +'</td>';
                                mhtml += '<td class="text-primary" style="text-align:right">'+ totalCash +'</td>';
                                mhtml += '<td class="text-primary" style="text-align:right">'+ totalCard +'</td>';
                                mhtml += '<td class="text-primary" style="text-align:right">'+ totalCheck +'</td>';
                                mhtml += '<td class="text-primary" style="text-align:right">'+ parseFloat(cashInHand).toFixed(2) +'</td>';
                                var c="text-primary";
                                if(parseInt(diff)<0){c="text-danger";} else if(parseInt(diff)>0) {c="text-success";}
                                mhtml += '<td class="'+c+'" style="font-weight:bold; text-align:right;" >' + diff + '</td>';
                                mhtml += '<td>' + denomination[x].remarks + '</td>';
                                
                                mhtml += '</tr>';
                            
                        }
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport tfoot").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                       // $("#tblreport tfoot").append(fhtml);                      



                       $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            
            }
            
            function bank_payments(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                var totalpaid=0; var totalcard=0; var totalcheck=0; var totalonline=0; mhtml="";
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/bank_payments',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        console.log(data);
                        var hhtml = hhtml + "<tr><th>Invoice Id</th><th>Customer</th><th>Cell</th><th>Invoice Date</th><th>Paid Amount</th><th>Payment Mode</th><th>Instrument</th><th>Status</th></tr>";
                        for(x=0; x< data.length;x++){
                            if(data[x]['invoice_status']=='valid'){
                                mhtml += '<tr>';
                            }else{                                
                                mhtml += '<tr class="strikethrough">';
                            }
                            if(data[x]['invoice_type']=="service"){                            
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ data[x]['id_invoice'] +'">' +  data[x]['id_invoice'] + '</a></td>';
                            } else {
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ data[x]['id_invoice'] +'">' +  data[x]['id_invoice'] + '</a></td>';
                            }
                            //mhtml += '<td>'+ data[x]['id_invoice'] +'</td>';
                            mhtml += '<td>'+ data[x]['customer_name'] +'</td>';
                            mhtml += '<td>'+ data[x]['customer_cell'] +'</td>';
                            mhtml += '<td>'+ data[x]['invoice_date'] +'</td>';
                            mhtml += '<td style="text-align:right;">'+ Math.round(parseFloat(data[x]['paid_amount'])*100)/100 +'</td>';
                            if(data[x]['invoice_status']=='valid'){
                                totalpaid= totalpaid+ Math.round(parseFloat(data[x]['paid_amount'])*100)/100;
                            }                            
                            mhtml += '<td>'+ data[x]['payment_mode'] +'</td>';
                            mhtml += '<td>'+ data[x]['instrument_number'] +'</td>';
                            mhtml += '<td>'+ data[x]['invoice_status'] +'</td>';
                            mhtml += '</tr>';
                        }

                        var fhtml="<tr><th></th><th></th><th></th><th></th><th style='text-align:right;'>"+Math.round(totalpaid*100)/100+"</th><th></th><th></th><th></th></tr>";;

                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport tfoot").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").append(fhtml);

                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });


            }

            function payment_breakup(){
            
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                var totalcash=0; var totalcard=0; var totalcheck=0; var totalonline=0;
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/payment_breakup',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                  
                        var paymentdata=data.paymentdata;
                        var workdates = data.workdates;
                        
                        var totalicash=0, totalicard=0,  totalicheck=0;
                        var totalacash=0, totalacard=0,  totalacheck=0;
                        var totalvcash=0, totalvcard=0, totalvcheck=0;
                        var totalrcash=0, totalrcard=0, totalrcheck=0;
                        //console.log(paymentdata);
                        
                        var hhtml = "<tr><th>WorkDate</th><th style='font-weight:bold; text-align:center;' colspan='5'>Cash </th><th style='font-weight:bold; text-align:center' colspan='5'>Card</th><th colspan='2' style='font-weight:bold; text-align:right'>Bank</th></tr>";
                        var hhtml = hhtml + "<tr><th></th><th>Invoice</th><th>Advance</th><th>Retained</th><th>Voucher</th><th>Total Cash</th><th>Invoice</th><th>Advance</th><th>Retained</th><th>Voucher</th><th>Total Card</th><th style='font-weight:bold; text-align:right'>Check</th><th>Online</th></tr>";
                        var mhtml = "";
                        
                        for(x=0; x< workdates.length;x++){
                              
                                
                                var icash = paymentdata[x] !==null ? paymentdata[x].cash : 0;
                                icash = icash == null ? 0 : icash;
                                var icard = paymentdata[x] !==null ? paymentdata[x].card : 0;
                                icard = icard == null ? 0 : icard;
                                var icheck = paymentdata[x] !==null ? paymentdata[x].bank : 0;
                                icheck = icheck == null ? 0 : icheck;
                                var ionline = paymentdata[x] !==null ? paymentdata[x].online : 0;
                                ionline = ionline == null ? 0 : ionline;
                                var vcash = paymentdata[x] !==null ? paymentdata[x].vcash : 0;
                                vcash = vcash == null ? 0 : vcash;
                                var vcard = paymentdata[x] !==null ? paymentdata[x].vcard : 0;
                                vcard = vcard == null ? 0 : vcard;
                                var vcheck = paymentdata[x] !==null ? paymentdata[x].vcheck : 0;
                                vcheck = vcheck == null ? 0 : vcheck;
                                var vonline = paymentdata[x] !==null ? paymentdata[x].vonline : 0;
                                vonline = vonline == null ? 0 : vonline;
                                var acash = paymentdata[x] !==null ? paymentdata[x].acash : 0;
                                acash = acash == null ? 0 : acash;
                                var acard = paymentdata[x] !==null ? paymentdata[x].acard : 0;
                                acard = acard == null ? 0 : acard;
                                var acheck = paymentdata[x] !==null ? paymentdata[x].acheck : 0;
                                acheck = acheck == null ? 0 : acheck;
                                var aonline = paymentdata[x] !==null ? paymentdata[x].aonline : 0;
                                aonline = aonline == null ? 0 : aonline;
                                var rcash = paymentdata[x] !==null ? paymentdata[x].rcash : 0;
                                rcash = rcash == null ? 0 : rcash;
                                var rcard = paymentdata[x] !==null ? paymentdata[x].rcard : 0;
                                rcard = rcard == null ? 0 : rcard;
                                var rcheck = paymentdata[x] !==null ? paymentdata[x].rcheck : 0;
                                rcheck = rcheck == null ? 0 : rcheck;
                                var ronline = paymentdata[x] !==null ? paymentdata[x].ronline : 0;
                                ronline = ronline == null ? 0 : ronline;
                                
                                var cash = parseFloat(icash)+parseFloat(acash)+parseFloat(rcash)+parseFloat(vcash);
                                var card = parseFloat(icard)+parseFloat(acard)+parseFloat(rcard)+parseFloat(vcard);
                                var check = parseFloat(icheck)+parseFloat(acheck)+parseFloat(rcheck)+parseFloat(vcheck);
                                var online = parseFloat(ionline)+parseFloat(aonline)+parseFloat(vonline)+parseFloat(ronline);
                                
                                mhtml += '<tr>';
                                mhtml += '<td>'+ workdates[x] +'</td>';
                                mhtml += '<td style="text-align:right">'+ Math.round(icash*100)/100 + '</td>';
                                mhtml += '<td style="text-align:right">'+ Math.round(acash*100)/100 + '</td>';
                                mhtml += '<td style="text-align:right">'+ Math.round(rcash*100)/100 + '</td>';
                                mhtml += '<td style="text-align:right">'+ Math.round(vcash*100)/100+ '</td>';
                                mhtml += '<td style="text-align:right">'+ Math.round(cash*100)/100 + '</td>';
                                
                                mhtml += '<td style="text-align:right">'+ Math.round(icard*100)/100 + '</td>';
                                mhtml += '<td style="text-align:right">'+ Math.round(acard*100)/100 + '</td>';
                                mhtml += '<td style="text-align:right">'+ Math.round(rcard*100)/100 + '</td>';
                                mhtml += '<td style="text-align:right">'+ Math.round(vcard*100)/100 + '</td>';
                                mhtml += '<td class="text-default" style="text-align:right">' + Math.round(card*100)/100 + '</td>';
                                mhtml += '<td class="text-success" style="text-align:right">' + Math.round(check*100)/100 + '</td>';
                                mhtml += '<td class="text-success" style="text-align:right">' + Math.round(online*100)/100 + '</td>';
                                mhtml += '</tr>';
                                
                                totalicash=totalicash+parseFloat(icash);
                                totalacash=totalacash+parseFloat(acash);
                                totalvcash=totalvcash+parseFloat(vcash);
                                totalrcash=totalrcash+parseFloat(rcash);
                                
                                totalicard=totalicard+parseFloat(icard);
                                totalacard=totalacard+parseFloat(acard);
                                totalvcard=totalvcard+parseFloat(vcard);
                                totalrcard=totalrcard+parseFloat(rcard);
                                
                                totalicheck=totalicheck+parseFloat(icheck);
                                totalacheck=totalacheck+parseFloat(acheck);
                                totalvcheck=totalvcheck+parseFloat(vcheck);
                                totalrcheck=totalrcheck+parseFloat(rcheck);
                                
                                        
                                totalcash=totalcash+parseFloat(cash);
                                totalcard=totalcard+parseFloat(card);
                                totalcheck=totalcheck+parseFloat(check);
                            
                                totalonline = totalonline+parseFloat(online);
                        }
                        
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        var fhtml = '<tr><th>Totals</th><th style="text-align:right">'+(Math.round(totalicash*100)/100).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th><th style="text-align:right">'+(Math.round(totalacash*100)/100).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th><th style="text-align:right">'+(Math.round(totalrcash*100)/100).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th><th style="text-align:right">'+(Math.round(totalvcash*100)/100).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th><th></th><th style="text-align:right">'+(Math.round(totalicard*100)/100).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th><th style="text-align:right">'+(Math.round(totalacard*100)/100).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th><th style="text-align:right">'+(Math.round(totalrcard*100)/100).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th><th style="text-align:right">'+(Math.round(totalvcard*100)/100).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th><th></th><th></th><th></th></tr>'
                        fhtml += '<tr><th></th><th>Cash Invoices</th><th>Cash Advance</th><th>Cash Retained</th><th>Cash Vouchers</th><th style="text-align:right">'+(Math.round(totalcash*100)/100).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th><th>Card Invoices</th><th>Card Advance</th><th>Card Retained</th><th>Card Vouchers</th><th style="text-align:right">'+(Math.round(totalcard*100)/100).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th><th style="text-align:right">'+(Math.round(totalcheck*100)/100).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th><th style="text-align:right;">'+(Math.round(totalonline*100)/100).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th></tr>';
                        $("#tblreport tfoot").html(fhtml);
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
        
            
            }
            
            function payment_breakup_services(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                var totalcash=0; var totalcard=0; var totalcheck=0;
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/payment_breakup_services',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        
                        var hhtml = "<tr><th>WorkDate</th><th style='font-weight:bold; text-align:right'>Cash </th><th style='font-weight:bold; text-align:right'>Card</th><th style='font-weight:bold; text-align:center;'>Bank</th></tr>";
                        var mhtml = "";
                        
                        for(x=0; x<data.length;x++){
                                
                                mhtml += '<tr>';
                                mhtml += '<td>'+ data[x]['workdate'] +'</td>';
                                mhtml += '<td style="text-align:right">'+ data[x]['cash'] + '</td>';
                                mhtml += '<td class="text-default" style="text-align:right">' + data[x]['card'] + '</td>';
                                mhtml += '<td class="text-success" style="text-align:right">' + data[x]['check'] + '</td>';
                                mhtml += '</tr>';
                                totalcash=totalcash+parseFloat(data[x]['cash']);
                                totalcard=totalcard+parseFloat(data[x]['card']);
                                totalcheck=totalcheck+parseFloat(data[x]['check']);
                            
                        }
                        
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('<tr><th></th><th style="text-align:right">'+totalcash.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th><th style="text-align:right">'+totalcard.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th><th style="text-align:right">'+totalcheck.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th></tr>');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }
            
            function payment_breakup_sale(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                var totalcash=0; var totalcard=0; var totalcheck=0;
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/payment_breakup_sale',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        
                        var hhtml = "<tr><th>WorkDate</th><th style='font-weight:bold; text-align:right'>Cash </th><th style='font-weight:bold; text-align:right'>Card</th><th style='font-weight:bold; text-align:right'>Check</th></tr>";
                        var mhtml = "";
                        
                        for(x=0; x<data.length;x++){
                                
                                mhtml += '<tr>';
                                mhtml += '<td>'+ data[x]['workdate'] +'</td>';
                                mhtml += '<td style="text-align:right">'+ data[x]['cash'] + '</td>';
                                mhtml += '<td class="text-default" style="text-align:right">' + data[x]['card'] + '</td>';
                                mhtml += '<td class="text-success" style="text-align:right">' + data[x]['check'] + '</td>';
                                mhtml += '</tr>';
                                totalcash=totalcash+parseFloat(data[x]['cash']);
                                totalcard=totalcard+parseFloat(data[x]['card']);
                                totalcheck=totalcheck+parseFloat(data[x]['check']);
                            
                        }
                        
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('<tr><th></th><th style="text-align:right">'+totalcash.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th><th style="text-align:right">'+totalcard.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th><th style="text-align:right">'+totalcheck.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'</th></tr>');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }
            
            function customer_profile(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/customer_profile',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        
                        var hhtml = "<tr><th>Name</th><th>Cell</th><th>Card</th><th>Address</th><th>Birthday</th>\n\
                        <th>Anniversary</th><th>Points Earned</th><th>Points Used</th><th>Available Points</th><th>Alerts</th><th>Allergies</th><th>Invoices</th><th>Purchases</th><th>Discount Given</th><th>Credit Given</th></tr>"

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                            mhtml += '<td>' + data[x]['card'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_address'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_birthday'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_anniversary'] + '</td>';
                            mhtml += '<td>' + data[x]['earned'] + '</td>';
                            mhtml += '<td>' + data[x]['used'] + '</td>';
                            mhtml += '<td>' + data[x]['loyalty_points'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_alert'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_allergies'] + '</td>';
                            mhtml += '<td><form target="_blank" method="post" action="<?php echo base_url();?>invoice_controller/todayinvoices"><input name="mDate" type="hidden" value=""><input name="customer_id" type="hidden" value="'+data[x]['id_customers']+'"><button class="btn-link" type="submit">' + data[x]['invoices'] + '</button></form></td>';
                            mhtml += '<td>' + data[x]['Purchases'] + '</td>';
                            mhtml += '<td>' + data[x]['Discounts'] + '</td>';
                            mhtml += '<td>' + data[x]['balance'] + '</td>';
                            mhtml += '</tr>';
                        }
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }
            
            function new_customers(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/new_customers',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        
                        var hhtml = "<tr><th>Name</th><th>Cell</th><th>Email</th><th>Address</th><th>Birthday</th><th>Anniversary</th><th>Alerts</th><th>Allergies</th><th>Added</th><th>By</th></tr>"

                        var mhtml = "";
                        var i=0;
                        for (x = 0; x < data.length; x++) {
                            mhtml += '<tr>';
                            
                            mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_email'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_address'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_birthday'] + '</td>';
                            mhtml += '<td>' + data[x]['anv'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_alert'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_allergies'] + '</td>';
                            //mhtml += '<td>' + data[x]['m'] + '</td>';
                            mhtml += '<td>' + data[x]['created'] + '</td>';
                            mhtml += '<td>' + data[x]['created_by'] + '</td>';
                            mhtml += '</tr>';
                            i++;
                        }
                        //console.log(mhtml);
                        $("#summary").html(i);
                        
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }            
            
            function new_customer_invoices(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/new_customer_invoices',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        
                        var hhtml = "<tr><th>Customer ID</th><th>Invoice ID</th><th>Customer</th><th>Created On</th><th>Category</th><th>Service</th><th>Paid</th><th>Staff</th>";

                        var mhtml = "";
                        var i=0;
                        for (x = 0; x < data.length; x++) {
                            mhtml += '<tr>';
                            if(data[x]['invoice_type']=="service"){                            
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ data[x]['id_invoice'] +'">' +  data[x]['id_invoice'] + '</a></td>';
                            } else {
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ data[x]['id_invoice'] +'">' +  data[x]['id_invoice'] + '</a></td>';
                            }
                            
                            mhtml += '<td>' + data[x]['id_customers'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td>' + data[x]['created_on'] + '</td>';
                            mhtml += '<td>' + data[x]['service_category'] + '</td>';
                            mhtml += '<td>' + data[x]['service_name'] + '</td>';
                            mhtml += '<td style="text-align:right;">' + data[x]['paid'] + '</td>';
                            mhtml += '<td>' + data[x]['staff_name'] + '</td>';
                           
                            mhtml += '</tr>';
                            i++;
                        }
                        //console.log(mhtml);
                       
                        
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }      
            
            function returning_customers(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/returning_customers',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        
                        var hhtml = "<tr><th>Name</th><th>Invoice Date</th><th>Invoice #</th><th>Cell</th><th>Email</th><th>Address</th><th>Birthday</th><th>Anniversary</th><th>Alerts</th><th>Allergies</th><th>Added</th><th>to</th><th>By</th></tr>";

                        var mhtml = "";
                        var i=0;
                        for (x = 0; x < data.length; x++) {
                            mhtml += '<tr>';
                            mhtml += '<td><form target="_blank" method="post" action="<?php echo base_url();?>invoice_controller/todayinvoices"><input name="mDate" type="hidden" value=""><input name="customer_id" type="hidden" value="'+data[x]['id_customers']+'"><button class="btn-link" type="submit">' + data[x]['customer_name'] + '</button></form></td>';
                            //mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                            mhtml += '<td>' + data[x]['invoice_date'] + '</td>';
                            
                            var res = []; 
                            if(data[x]['invoice_number']){res = data[x]['invoice_number'].split("-")} else {res[2]=''};
                            if(data[x]['invoice_type']=="service"){                            
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existinginvoice/'+ res[2] +'">' +  data[x]['invoice_number'] + '</a></td>';
                            } else {
                                mhtml += '<td><a target="_blank" href="<?php echo base_url();?>existingorderinvoice/'+ res[2] +'">' +  data[x]['invoice_number'] + '</a></td>';
                            }
                            
                            
                            mhtml += '<td>' + data[x]['customer_cell'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_email'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_address'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_birthday'] + '</td>';
                            mhtml += '<td>' + data[x]['anv'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_alert'] + '</td>';
                            mhtml += '<td>' + data[x]['customer_allergies'] + '</td>';
                            //mhtml += '<td>' + data[x]['m'] + '</td>';
                            mhtml += '<td>' + data[x]['created'] + '</td>';
                            mhtml += '<td>' + data[x]['business_name'] + '</td>';
                            mhtml += '<td>' + data[x]['created_by'] + '</td>';
                            mhtml += '</tr>';
                            i++;
                        }
                        //console.log(mhtml);
                        $("#summary").html(i);
                        
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }            
            
            function dispatch() {
            
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/dispatch_report',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        
                        var hhtml = "<tr><th>ID</th><th>Product ID</th><th>Product</th><th>Date</th><th>Qty</th><th>Unit Type</th><th>Dispatch Measure</th><th>Measure Unit</th><th>Value</th><th>Dispatched to</th><th>Comment</th><th>Dispatched by</th></tr>"

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            
                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['id_dispatch_note'] + '</td>';
                            mhtml += '<td>' + data[x]['id_business_products'] + '</td>';
                            mhtml += '<td>' + data[x]['Product'] + '</td>';
                           
                            mhtml += '<td>' + data[x]['Date'] + '</td>';
                            mhtml += '<td>' + data[x]['Qty'] + '</td>';
                             mhtml += '<td>' + data[x]['UnitType'] + '</td>';
                            if(parseFloat(data[x]['dispatch_measure'])>0){
                               mhtml += '<td>' + data[x]['dispatch_measure'] + '</td>';
                            }else{
                                mhtml+="<td>"+parseFloat(data[x]['Qty'])*parseFloat(data[x]['qty_per_unit'])+"</td>";
                            }
                            mhtml += '<td>' + data[x]['measure_unit'] + '</td>';
//                          
                           // mhtml +='<td>'+ Math.round(parseFloat(data[x]['batch_amount']) * parseFloat(data[x]['Qty'])*100)/100 + '</td>';
                            mhtml += '<td>' + data[x]['cog_used'] + '</td>';
                            
                            mhtml += '<td>' + data[x]['staff_fullname'] + '</td>';
                            mhtml += '<td>' + data[x]['dispatch_comment'] + '</td>';
                            mhtml += '<td>' + data[x]['Created_by'] + '</td>';
                            mhtml += '</tr>';
                        }
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
            }
    function dispatch_against_requests(){
        $('#otherview').css('display', 'none');
        $('.atview').css('display', 'none');
        $("#cog").show();
        $.ajax({
            type: 'POST',
            url: 'report_controller/dispatches_against_requests',
            data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
            dataType: "json",
            cache: false,
            //async: true,
            success: function(data) {
                var hhtml = "<tr><th>Req.ID</th><th>Req. PID</th><th>Req. Product</th><th>Req. Qty</th><th>Req. Unit</th><th>Visit Id</th><th>Visit Status</th><th>ID Dispatch</th><th>SID</th><th>Service</th><th>Service Start</th><th>Dispatched PID</th><th>Dispatched Product</th><th>Dispatched Measure</th><th>D.Unit.</th><th>Customer</th><th>Dispatch Created By</th></tr>";

                var mhtml = "";
                var totalvalue=0;
                for (x = 0; x < data.length; x++) {

                    mhtml += '<tr>';
                    mhtml += '<td>' + data[x]['id_dispatch_request'] + '</td>';
                    mhtml += '<td>' + data[x]['req_product_id'] + '</td>';
                    mhtml += '<td>' + data[x]['req_product_name'] + '</td>';
                    mhtml += '<td>' + data[x]['req_qty'] + '</td>';
                    mhtml += '<td>' + data[x]['req_unit'] + '</td>';
                    mhtml += '<td>' + data[x]['id_customer_visits'] + '</td>';
                    mhtml += '<td>' + data[x]['visit_status'] + '</td>';

                    mhtml += '<td>' + data[x]['id_dispatch_note'] + '</td>';                    
                    mhtml += '<td>' + data[x]['service_id'] + '</td>';
                    mhtml += '<td>' + data[x]['service_name'] + '</td>';
                    mhtml += '<td>' + data[x]['service_start'] + '</td>';
                    mhtml += '<td>' + data[x]['product_id'] + '</td>';
                    mhtml += '<td>' + data[x]['product'] + '</td>';                     
                    if(parseFloat(data[x]['dispatch_measure'])>0){
                       mhtml += '<td>' + data[x]['dispatch_measure'] + '</td>';
                    }else{
                        mhtml+="<td>"+parseFloat(data[x]['Qty'])*parseFloat(data[x]['qty_per_unit'])+"</td>";
                    }
                    mhtml += '<td>' + data[x]['measure_unit'] + '</td>';
                    
                    mhtml += '<td>' + data[x]['customer_name'] + '</td>';                                        
                    mhtml += '<td>' + data[x]['created_by'] + '</td>';
                    mhtml += '</tr>';
                    
                    totalvalue=totalvalue+ Math.round(parseFloat(data[x]['cog_used'])*100)/100;
                    
                }
                var fhtml = "<tr><th>Req.ID</th><th>Req. PID</th><th>Req. Product</th><th>Req. Qty</th><th>Req. Unit</th><th>Visit Id</th><th>Visit Status</th><th>ID Dispatch</th><th>SID</th><th>Service</th><th>Service Start</th><th>Dispatched PID</th><th>Dispatched Product</th><th>Dispatched Measure</th><th>D.Unit.</th><th>Customer</th><th>Dispatched Created By</th></tr>";
                //console.log(mhtml);
                $("#tblreport").dataTable().fnDestroy();
                $("#tblreport thead").html('');
                $("#tblreport tbody").html('');
                $("#tblreport thead").append(hhtml);
                $("#tblreport tbody").append(mhtml);
                $("#tblreport tfoot").html(fhtml);

                $.fn.dataTable.moment('DD-MM-YYYY');
                $('#tblreport').DataTable({
                    lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                    stateSave: true, fixedHeader: {header: true},
                    <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                    buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                            extend: "excel",
                            className: "btn-sm"
                        }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                    <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                });
                $("#cog").hide();

            }
        });
    }

    function dispatch_details(){
        $('#otherview').css('display', 'none');
        $('.atview').css('display', 'none');
        $("#cog").show();
        $.ajax({
            type: 'POST',
            url: 'report_controller/dispatch_details',
            data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
            dataType: "json",
            cache: false,
            //async: true,
            success: function(data) {

                var hhtml = "<tr><th>ID</th><th>Product ID</th><th>SID</th><th>Product</th><th>Date</th><th>Qty</th><th>Unit Type</th><th>Dispatch Measure</th><th>Measure Unit</th><th>Value</th><th>Dispatched to</th><th>For Client</th><th>Service</th><th>Comment</th><th>Dispatched by</th></tr>"

                var mhtml = "";
                var totalvalue=0;
                for (x = 0; x < data.length; x++) {

                    mhtml += '<tr>';
                    mhtml += '<td>' + data[x]['id_dispatch_note'] + '</td>';
                    mhtml += '<td>' + data[x]['id_business_products'] + '</td>';
                     mhtml += '<td>' + data[x]['service_id'] + '</td>';
                    mhtml += '<td>' + data[x]['Product'] + '</td>';
                   

                    mhtml += '<td>' + data[x]['Date'] + '</td>';
                    mhtml += '<td>' + data[x]['Qty'] + '</td>';
                     mhtml += '<td>' + data[x]['UnitType'] + '</td>';
                    if(parseFloat(data[x]['dispatch_measure'])>0){
                       mhtml += '<td>' + data[x]['dispatch_measure'] + '</td>';
                    }else{
                        mhtml+="<td>"+parseFloat(data[x]['Qty'])*parseFloat(data[x]['qty_per_unit'])+"</td>";
                    }
                    mhtml += '<td>' + data[x]['measure_unit'] + '</td>';
                         
                    //mhtml +='<td>'+ Math.round(parseFloat(data[x]['batch_amount']) * parseFloat(data[x]['Qty']) * 100)/100 + '</td>';
                    mhtml +='<td>'+ data[x]['cog_used'] + '</td>';
                    mhtml += '<td>' + data[x]['staff_fullname'] + '</td>';
                    mhtml += '<td>' + data[x]['customer_name'] + '</td>';
                    mhtml += '<td>' + data[x]['service_name'] + '</td>';
                    mhtml += '<td>' + data[x]['dispatch_comment'] + '</td>';
                    mhtml += '<td>' + data[x]['Created_by'] + '</td>';
                    mhtml += '</tr>';
                    
                    totalvalue=totalvalue+ Math.round(parseFloat(data[x]['cog_used'])*100)/100;
                    
                }
                var fhtml = "<tr><th>ID</th><th>Product ID</th><th>SID</th><th>Product</th><th>Date</th><th>Qty</th><th>Unit Type</th><th>Dispatch Measure</th><th>Measure Unit</th><th>"+ Math.round(totalvalue * 100)/100+"</th><th>Dispatched to</th><th>For Client</th><th>Service</th><th>Comment</th><th>Dispatched by</th></tr>";
                //console.log(mhtml);
                $("#tblreport").dataTable().fnDestroy();
                $("#tblreport thead").html('');
                $("#tblreport tbody").html('');
                $("#tblreport thead").append(hhtml);
                $("#tblreport tbody").append(mhtml);
                $("#tblreport tfoot").html(fhtml);

                $.fn.dataTable.moment('DD-MM-YYYY');
                $('#tblreport').DataTable({
                    lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                    stateSave: true, fixedHeader: {header: true},
                    <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                    buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                            extend: "excel",
                            className: "btn-sm"
                        }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                    <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                });
                $("#cog").hide();

            }
        });
    }
    
    function staff_retail_sale_summary(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/staff_retail_sale_summary',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD')},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        
                        var hhtml = "<tr><th>Staff</th><th>Products</th><th>Quantity</th><th>Paid</th><th>Recovery</th><th>Total</th></tr>"

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            
                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['staff_name'] + '</td>';
                            mhtml += '<td>' + data[x]['Products'] + '</td>';
                            mhtml += '<td>' + data[x]['Quantity'] + '</td>';
                            mhtml += '<td>' + data[x]['Amount'] + '</td>';
                            mhtml += '<td>' + data[x]['Recovery'] + '</td>';
                            mhtml += '<td>' + data[x]['Total'] + '</td>';
                            
                            mhtml += '</tr>';
                        }
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
    
    }
    
    function staff_blocking(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/staff_blocking',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD'), staffid: $("#selectstaff").val()},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        
                        var hhtml = "<tr><th>Staff</th><th>Reason</th><th>Day</th><th>Blocked From</th><th>Blocked To</th><th>Duration</th><th>Remarks</th>";

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            
                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['staff_name'] + '</td>';
                            mhtml += '<td>' + data[x]['block_event_name'] + '</td>';
                            mhtml += '<td>' + data[x]['day'] + '</td>';
                            mhtml += '<td>' + data[x]['start_time'] + '</td>';
                            mhtml += '<td>' + data[x]['end_time'] + '</td>';
                            mhtml += '<td>' + data[x]['timediff'] + '</td>';
                            mhtml += '<td>' + data[x]['remarks'] + '</td>';
                           
                            
                            mhtml += '</tr>';
                        }
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
    
    }
    
    
    function staff_blocking_summary(){
                $('#otherview').css('display', 'none');
                $('.atview').css('display', 'none');
                $("#cog").show();
                $.ajax({
                    type: 'POST',
                    url: 'report_controller/staff_blocking_summary',
                    data: {startdate: startdate.format('YYYY-MM-DD'), enddate: enddate.format('YYYY-MM-DD'), staffid: $("#selectstaff").val()},
                    dataType: "json",
                    cache: false,
                    //async: true,
                    success: function(data) {
                        
                        var hhtml = "<tr><th>Staff</th><th>Reason</th><th>Total Blockings</th><th>Duration</th>";

                        var mhtml = "";
                        for (x = 0; x < data.length; x++) {
                            
                            mhtml += '<tr>';
                            mhtml += '<td>' + data[x]['staff_name'] + '</td>';
                            mhtml += '<td>' + data[x]['block_event_name'] + '</td>';
                            mhtml += '<td>' + data[x]['blockings'] + '</td>';
                            mhtml += '<td>' + data[x]['total_block_time'] + '</td>';
                        
                            
                            mhtml += '</tr>';
                        }
                        //console.log(mhtml);
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(mhtml);
                        $("#tblreport tfoot").html('');
                        
                        $.fn.dataTable.moment('DD-MM-YYYY');
                        $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                            stateSave: true, fixedHeader: {header: true},
                            <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        dom: "Bfrtlip",
                            buttons: [{extend: "copy", className: "btn-sm"}, {extend: "csv", className: "btn-sm"}, {
                                    extend: "excel",
                                    className: "btn-sm"
                                }, {extend: "pdf", className: "btn-sm"}, {extend: "print", className: "btn-sm"}],
                            <?php } else { ?>
                        dom: "frtlip",
                    <?php } ?>
                    responsive: !0
                        });
                        $("#cog").hide();

                    }
                });
    
    }
    
    
    function open_sked(date1) {
        window.location= "<?php echo base_url().'scheduler/'?>" + date1 + "";
        
    }


    function enable_customers(){
       $("#selectcustomer").select2({
            ajax: {
              url: '<?php echo base_url();?>customer_controller/searchnameforco',
              dataType: 'json',
              quietMillis: 1000,
              data: function (term, page) {
                  
                return {
                    customername: term, // search term
                    page_limit: 30, // page size
                    page: page // page number
                };
              },
              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: 3,
            formatResult: function (option) {
               return option.customer_name+" | "+option.customer_cell ;
            },
            formatSelection: function (option) {
                
                return option.customer_name+" | "+option.customer_cell;
            }
          });
         
    }

        </script>
<?php 


function timeToSeconds ($time) {
    $hours = floor($time);
    $minutes = ($time - $hours) * 100;
    $seconds = ($hours * 3600) +  ($minutes * 60);
    return $seconds;
}

function secondsToTime ($seconds) {
    $hours = floor($seconds / 3600);
    $minutes = ($seconds - ($hours * 3600)) / 60;
    $time = "" . $hours . "." . $minutes;
    return $time;
}

?>