<div class="wrapper">
    <div class="container">
        <!-- Page-Title -->
        <div class="row">
            <div class="col-sm-10 pull-left">
                <h4 class="page-title">Payable Calculation For : <?php echo $monthName.'-'.$year; ?></h4>
            </div>
            <div class="col-sm-2">
                <div class="pull-right m-t-15">
                     <div class="btn-group">
                        <button type="button" class="btn btn-warning dropdown-toggle waves-effect waves-light" data-toggle="dropdown" aria-expanded="true">Staff Payments<span class="m-l-5"><i class="fa fa-money"></i></span></button>
                        <ul class="dropdown-menu" role="menu">
                            <li><a href="<?php echo base_url(); ?>staff_list">Staff</a></li>
                            <li><a href="<?php echo base_url();?>view_staff_payables_receivables/<?php echo $this->session->userdata('businessid'); ?>">Make Payments To Staff </a></li>
                            <li><a href="<?php echo base_url();?>staff_controller/paymentslips">Payment Slips</a></li>
                            <li class="divider"></li>

                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <div class="row" id="divselection">
            <div class="col-sm-12">
                <div class="card-box ">
                    <h4>Filters:</h4>
                    
                    <div class="row">
                        <form  action="<?php echo base_url()?>calculatemonthstaffpayment" method="post">
                            <div class="col-md-2">
                                <label class="form-label">Month</label>
                                <select class="form-control" name="month">
                                    <?php for($x=1; $x<=12; $x++){
                                        if($x==1){$m = "Jan";}
                                        if($x==2){$m = "Feb";}
                                        if($x==3){$m = "Mar";}
                                        if($x==4){$m = "Apr";}
                                        if($x==5){$m = "May";}
                                        if($x==6){$m = "Jun";}
                                        if($x==7){$m = "Jul";}
                                        if($x==8){$m = "Aug";}
                                        if($x==9){$m = "Sep";}
                                        if($x==10){$m = "Oct";}
                                        if($x==11){$m = "Nov";}
                                        if($x==12){$m = "Dec";}
                                        ?>

                                    <option <?php if($month==$x){echo "selected='selected'";}?>  value="<?php echo $x;?>"><?php echo $m;?></option>
                                    <?php } ?>
                                    </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Year</label>
                                <select class="form-control" name="year">
                                    <?php $tyear = date('Y');?>
                                    <option <?php if($year==$tyear-1){echo "selected='selected'";}?> value="<?php echo $tyear-1; ?>"><?php echo $tyear-1;?></option> 
                                    <option <?php if($year==$tyear){echo "selected='selected'";}?> value="<?php echo $tyear; ?>"><?php echo $tyear;?></option> 

                                </select>
                            </div>
                             <div class="col-md-2">
                                <label class="form-label">Branches</label>
                                <?php if(sizeof($branches)>0){?>
                                <select <?php if($this->session->userdata("ho")=='No'){echo "disabled";}?> class="form-control" name="business_id">
                                    <?php foreach($branches as $branch){?>
                                    <option <?php if($branch['id_business'] == $business[0]['id_business']){ echo "selected='selected'";} ?> value="<?php echo $branch['id_business'];?>">
                                        <?php echo $branch['business_name'];?>
                                    </option>
                                    <?php } ?>
                                </select>
                                <?php }else{ ?>
                                <select class="form-control" name="business_id">
                                    <option value="<?php echo $business[0]['id_business'];?>>">
                                        <?php echo $business[0]['business_name'];?>
                                    </option>
                                </select>
                                <?php } ?>
                            </div>
                            <div class="col-md-2">                                 
                                <div class="form-group">
                                    <label for="account_voucher_date" class=" control-label">Voucher Date</label>

                                        <input class="form-control" required="required" id="account_voucher_date" name="account_voucher_date">                                           

                                </div>
                            </div>
                            <div class="col-md-2">                                 
                                <div class="form-group">
                                    <label for="account_voucher_date" class=" control-label">Staff</label>
                                    <select class="form-control" required="required" id="staff_id" name="staff_id">
                                        <option value="0">Select Staff</option>
                                        <?php foreach($staff as $s){ ?>
                                            <option <?php if($selectedstaff == $s['id_staff']){echo "selected='selected'";}?> value="<?php echo $s['id_staff']; ?>"><?php echo $s['staff_fullname']; ?></option>
                                        <?php } ?>    
                                    </select>    
                                </div>
                            </div>        
                            <div class="col-md-2">
                                <button class="btn btn-pink m-t-20">Run</button>                            
                            </div>
                        </form>
                        
                        
                    </div>
                    <div class="row">
                        <div class="col-md-9"></div>  
                        <div class="col-md-3">                            
                            <button onclick="create_vouchers();" class="btn btn-primary m-t-20" id="btn_create">Create Payable Vouchers</button>                            
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row" id="divselection">
            <div class="col-sm-12">
                <div class="card-box" style="width:100%; ">
                    <div class="row m-b-5">
                        <div class="col-md-12"> 
                        <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                        <button onclick="tableToExcel('tblstaff', 'Payables <?php echo $monthName.'-'.$year; ?>')" class="btn btn-warning pull-right btn-sm m-l-5">Export to Excel</button>
                        <?php } ?>
                        </div>
                    </div>
                    <div class="row"> 
                        <div class="col-md-12" style="overflow-x: scroll;">
                            <table id="tblstaff" class="table table-bordered" style="font-size:12px !important;">
                                <thead>
                                    <tr>
                                        <th >ID</th>
                                        <th>Name</th>
                                        <th class="text-right text-primary">Basic Salary</th>
                                        <th class="text-right text-primary">Salary Type</th>
                                        <th>Commission Mode</th>
                                        <th class="text-right">Income Generated</th>
                                        <th class="text-right">Service Commission</th>
                                        <th class="text-right">Retail Commission</th>
                                        <?php $allowance_list=0; foreach($allowances as $allowance){ ?>                                
                                            <th class="text-right" id="<?php echo $allowance->id_allowances; ?>">
                                                <?php echo $allowance->allowance_name; $allowance_list++;?>
                                            </th>
                                        <?php } ?>
                                        <th class="text-right">Miscellaneous</th>    
                                        <th class="text-right">Reimbursements</th>
                                        <th class="text-right text-success">Provident Fund 'Employer'</th>

                                        <th class="text-right text-danger">Deduction Absents</th>
                                        <th class="text-right text-danger">Deduction Late</th>
                                        <th class="text-right text-danger">Provident Fund 'Employee'</th>                                
                                        <th class="text-right text-danger">Tax Deduction</th>
                                        <th class="text-right text-danger">Other Deduction</th>
                                        <th class="text-right text-danger">Loan Deduction</th>


                                        <th class="text-right text-sucess">Total Payable</th>
                                        <th class="text-right text-danger">Total Deductions</th>
                                        <th class="text-right text-primary">Payable</th>
                                        <th class="text-right text-primary">Decimal Adjustment</th>
                                        <th>Staff Name</th>
                                        <th>View Details</th>
                                    </tr>
                                </thead>
                                <tbody>

                                    <?php $x=1; $totalpayable=0; foreach($payables as $payable){?>
                                    <tr id="<?php echo $payable[0]['id_staff']; ?>">
                                        <td key="staff_id" type="ignore" name="id_staff" onclick="updatetotal(<?php echo $payable[0]['id_staff']; ?>);"><?php echo $payable[0]['id_staff']; ?></td>
                                        <td key="staff_fullname" type="ignore" name="staff_name"><?php if($this->session->userdata("ho")=='No'){echo $payable[0]['staff_fullname'];}else{echo $payable[0]['staff_fullname'].' '.$business[0]['business_name'] ;} ?></td>
                                        
                                        <?php if($payable[0]['salary_type']=='daily'){?>
                                            <td key="staff_salary" type="add" name="salary" salary_type="<?php echo $payable[0]['salary_type'];?>" presents="<?php echo $payable[0]['Present']; ?>" workhours="<?php echo $payable[0]['WorkHours']; ?>" class="text-right"><?php echo $payable[0]['staff_salary'] * $payable[0]['Present']; ?></td>
                                        <?php } elseif($payable[0]['salary_type']=='monthly') { ?>
                                            <td key="staff_salary" type="add" name="salary" salary_type="<?php echo $payable[0]['salary_type'];?>" presents="<?php echo $payable[0]['Present']; ?>" workhours="<?php echo $payable[0]['WorkHours']; ?>" class="text-right"><?php echo $payable[0]['staff_salary']; ?></td>
                                        <?php } elseif($payable[0]['salary_type']=='weekly') { ?>    
                                            <td key="staff_salary" type="add" name="salary" salary_type="<?php echo $payable[0]['salary_type'];?>" presents="<?php echo $payable[0]['Present']; ?>" workhours="<?php echo $payable[0]['WorkHours']; ?>" class="text-right"><?php echo $payable[0]['staff_salary'] * $payable[0]['WorkHours']; ?></td>
                                        <?php } ?>
                                        
                                        <td key="salary_type" type="ignore" name="salary_type"  class="text-right"><?php echo $payable[0]['salary_type'];?></td>
                                        
                                        <td type="ignore" name="commission_mode"><?php echo $payable[1]['commission_mode'];?> <?php echo $payable[1]['commission_mode'] == 'Target' ? $payable[1]['commission_target'] : ' ' ; ?></td>
                                        <td type="ignore" name="income" class="text-right"><?php echo $payable[1]['paid']; ?></td>
                                        <td  key="staff_commission" type="add" salary_type="<?php echo $payable[0]['salary_type'];?>"  presents="<?php echo $payable[0]['Present']; ?>" workhours="<?php echo $payable[0]['WorkHours']; ?>"  name="commission" class="text-right"><?php echo $payable[1]['service_commission']; ?></td>
                                        <td  key="retail_commission" type="add" salary_type="<?php echo $payable[0]['salary_type'];?>"  presents="<?php echo $payable[0]['Present']; ?>" workhours="<?php echo $payable[0]['WorkHours']; ?>"  name="retail_commission" class="text-right"><?php echo $payable[2]['retail_commission']; ?></td>

                                        <?php $allowance_total=0; foreach($allowances as $a){    ?>
                                            <?php $allowance_list=0; $allowance_name=''; foreach($payable['allowances'] as $allowance){ ?>
                                                <?php if($allowance['id_allowances'] == $a->id_allowances){ $allowance_list++; $allowance_name=$allowance['allowance_name'];?>
                                                    <td key="<?php echo $a->entity_name;?>" type="add" salary_type="<?php echo $payable[0]['salary_type'];?>"  presents="<?php echo $payable[0]['Present']; ?>" workhours="<?php echo $payable[0]['WorkHours']; ?>"  name="<?php echo $allowance['allowance_name'];?>" class="text-right"><?php echo $allowance['allowance_amount']; ?></td>
                                                <?php $allowance_total = $allowance_total + $allowance['allowance_amount']; }?>                                    
                                            <?php } ?>
                                            <?php if($allowance_list == 0){ ?>
                                                <td key="<?php echo $a->entity_name;?>" type="add" salary_type="<?php echo $payable[0]['salary_type'];?>"  presents="<?php echo $payable[0]['Present']; ?>" workhours="<?php echo $payable[0]['WorkHours']; ?>"  name="<?php echo $a->allowance_name;?>"  class="text-right">0.00</td>
                                            <?php $allowance_list=0; } ?>
                                        <?php } ?>

                                        <td key="miscellanous" type="add_input" salary_type="<?php echo $payable[0]['salary_type'];?>"  presents="<?php echo $payable[0]['Present']; ?>" workhours="<?php echo $payable[0]['WorkHours']; ?>"  name="miscellaneous" class="text-right "><span class="hidden" id="me_span_<?php echo $payable[0]['id_staff']; ?>"></span><input onchange="updatetotal(<?php echo $payable[0]['id_staff']; ?>); $('#me_span_<?php echo $payable[0]['id_staff']; ?>').html($(this).val());" style="text-align: right; width:80px; border:none;" class="text-primary decimal"  id="miscellaneous_<?php echo $payable[0]['id_staff']; ?>" name="miscellaneous" type="number"  min="0" value="0"></td>
                                        <td key="reimbursements" type="add_input" salary_type="<?php echo $payable[0]['salary_type'];?>"  presents="<?php echo $payable[0]['Present']; ?>" workhours="<?php echo $payable[0]['WorkHours']; ?>"  name="reimbursements" class="text-right"><span class="hidden" id="r_span_<?php echo $payable[0]['id_staff']; ?>"></span><input onchange="updatetotal(<?php echo $payable[0]['id_staff']; ?>); $('#r_span_<?php echo $payable[0]['id_staff']; ?>').html($(this).val());" style="text-align: right; width:80px; border:none;" class="text-primary decimal"  id="reimbursements_<?php echo $payable[0]['id_staff']; ?>" name="reimbursements" type="number" min="0" value="0"></td>        
                                        <td key="provident_fund_employer" type="ignore" name="pf_employer" class="text-right"><?php if($payable[0]['provident_fund']>0){ echo $payable[0]['provident_fund']/2; } else { echo 0;} ?></td>

                                        <td key="deduction_absent"" type="subtract" salary_type="<?php echo $payable[0]['salary_type'];?>"  presents="<?php echo $payable[0]['Present']; ?>" workhours="<?php echo $payable[0]['WorkHours']; ?>"  name="absent" class="text-right"><?php 
                                            if($payable[0]['salary_type']=='monthly'){
                                                echo trim($payable[0]['absent_deduction']); 
                                            }else if($payable[0]['salary_type']=='daily'){
                                                echo 0; 
                                            }else if($payable[0]['salary_type']=='weekly'){
                                                echo 0;
                                            }                                            
                                        ?></td>
                                        <td key="deduction_late" type="subtract" salary_type="<?php echo $payable[0]['salary_type'];?>"  presents="<?php echo $payable[0]['Present']; ?>" workhours="<?php echo $payable[0]['WorkHours']; ?>"  name="late" class="text-right"><?php 
                                         
                                            if($payable[0]['salary_type']=='monthly'){
                                                echo trim($payable[0]['late_deduction']); 
                                            }else if($payable[0]['salary_type']=='daily'){
                                                echo trim($payable[0]['late_deduction']);  
                                            }else if($payable[0]['salary_type']=='weekly'){
                                                echo 0;
                                            }
                                        
                                        ?></td>
                                        <td key="provident_fund_employee"  type="subtract" salary_type="<?php echo $payable[0]['salary_type'];?>"  presents="<?php echo $payable[0]['Present']; ?>" workhours="<?php echo $payable[0]['WorkHours']; ?>"  name="pf_employee" class="text-right"><?php if($payable[0]['provident_fund']>0){ echo $payable[0]['provident_fund']/2; } else { echo 0;}?></td>
                                        <td key="tax_deduction" type="subtract" salary_type="<?php echo $payable[0]['salary_type'];?>"  presents="<?php echo $payable[0]['Present']; ?>" workhours="<?php echo $payable[0]['WorkHours']; ?>"  name="tax" class="text-right"><?php echo $payable[0]['salary_monthly_tax']; ?></td>                                
                                        <td key="other_deduction" type="subtract_input" salary_type="<?php echo $payable[0]['salary_type'];?>"  presents="<?php echo $payable[0]['Present']; ?>" workhours="<?php echo $payable[0]['WorkHours']; ?>"  name="other_deduction" class="text-right"><span class="hidden" id="od_span_<?php echo $payable[0]['id_staff']; ?>"></span><input onchange="updatetotal(<?php echo $payable[0]['id_staff']; ?>); $('#od_span_<?php echo $payable[0]['id_staff']; ?>').html($(this).val());" style="text-align: right; width:80px; border:none;" class="text-primary decimal"  id="other_deduction_<?php echo $payable[0]['id_staff']; ?>" name="other_deduction" type="number" min="0" value="0"></td>
                                        <td key="loan_deduction" type="subtract_input" salary_type="<?php echo $payable[0]['salary_type'];?>"  presents="<?php echo $payable[0]['Present']; ?>" workhours="<?php echo $payable[0]['WorkHours']; ?>"  name="loan_deduction" class="text-right"><span class="hidden" id="ld_span_<?php echo $payable[0]['id_staff']; ?>"></span><input onchange="updatetotal(<?php echo $payable[0]['id_staff']; ?>); $('#od_span_<?php echo $payable[0]['id_staff']; ?>').html($(this).val());" style="text-align: right; width:80px; border:none;" class="text-primary decimal"  id="loan_deduction_<?php echo $payable[0]['id_staff']; ?>" name="loan_deduction" type="number" min="0" value="<?php echo $payable['loan'][0]['balance']; ?>"></td>
                                        

                                        <td key="total_payable" type="ignore" name="total_payable" style="font-weight: bold;" class="text-right text-success" id="payable_<?php echo $payable[0]['id_staff']; ?>"><?php 
                                            $salary = $payable[0]['staff_salary'];
                                            if($payable[0]['salary_type']=='monthly'){$salary = $payable[0]['staff_salary'];}
                                            else if($payable[0]['salary_type']=='daily'){$salary = $payable[0]['staff_salary'] * $payable[0]['Present'];}
                                            else if($payable[0]['salary_type']=='weekly'){$salary = $payable[0]['staff_salary'] * $payable[0]['WorkHours'];}
                                            $tr_payabale = $salary + $payable[1]['service_commission'] + $payable[2]['retail_commission'] + $allowance_total;
                                            echo $tr_payabale;
                                            ?></td>

                                            <?php 
                                                if($payable[0]['salary_type']=='monthly'){
                                                    $tr_deductions = $payable[0]['absent_deduction'] + $payable[0]['late_deduction'] + ($payable[0]['provident_fund']/2) + $payable[0]['salary_monthly_tax'] + $payable['loan'][0]['balance'];
                                                }else if($payable[0]['salary_type']=='daily') {
                                                    $tr_deductions = $payable[0]['late_deduction'] + ($payable[0]['provident_fund']/2) + $payable[0]['salary_monthly_tax'] + $payable['loan'][0]['balance'];
                                                }else if($payable[0]['salary_type']=='hourly') {
                                                    $tr_deductions = ($payable[0]['provident_fund']/2) + $payable[0]['salary_monthly_tax'] + $payable['loan'][0]['balance'];
                                                }
                                            ?>
                                        <td key="total_deductions" type="ignore" name="total_payable" style="font-weight: bold;" class="text-right text-danger" id="deductions_<?php echo $payable[0]['id_staff']; ?>"><?php                                             
                                            echo $tr_deductions;
                                            ?></td>                                        
                                        
                                        
                                        <td  key="final_payable" type="ignore" name="final_payable" style="font-weight: bold;" class="text-right text-primary" id="total_payable_<?php echo $payable[0]['id_staff']; ?>"><?php 
                                            $tr_final_payable = $tr_payabale - $tr_deductions;
                                            echo floor($tr_final_payable);
                                            $totalpayable = $totalpayable + floor($tr_final_payable);
                                            ?></td>

                                        <td  key="rounded_adjustment" type="ignore" name="rounded_adjustment" style="font-weight: bold;" class="text-right text-primary" id="rounded_adjustment_<?php echo $payable[0]['id_staff']; ?>"><?php 
                                            $tr_final_payable = $tr_payabale - $tr_deductions;
                                            echo round($tr_final_payable - floor($tr_final_payable),2);
                                            
                                            ?></td>

                                        <td key="name_repeat" type="ignore" name="name_repeat"><?php echo $payable[0]['staff_fullname']; ?></td>
                                        <td type="ignore">
                                            <a class="btn btn-pink btn-sm" target="_blank" href="<?php echo base_url(); ?>view_staff_attendance_single/<?php echo $payable[0]['id_staff'].'/'.$month."/".$year; ?>" >Attendance</a>
                                            <a class="btn btn-warning btn-sm m-t-5" target="_blank" href="<?php echo base_url(); ?>view_staff_commission_single/<?php echo $payable[0]['id_staff'].'/'.$month."/".$year; ?>" >Service Commission</a>
                                            <a class="btn btn-warning btn-sm m-t-5" target="_blank" href="<?php echo base_url(); ?>view_retail_staff_commission_single/<?php echo $payable[0]['id_staff'].'/'.$month."/".$year; ?>" >Retail commission</a>
                                        </td>
                                    </tr>
                                    <?php } ?>
                                </tbody>
                                <tfoot>
                                    <th >ID</th>
                                    <th>Name</th>                                    
                                    <th class="text-right text-primary">Basic Salary</th>
                                    <th class="text-right text-primary">Salary Type</th>
                                    <th>Commission Mode</th>
                                    <th class="text-right">Income Generated</th>
                                    <th class="text-right">Service Commission</th>
                                    <th class="text-right">Retail Commission</th>
                                     <?php $allowance_list=0; foreach($allowances as $allowance){ ?>                                
                                        <th class="text-right">
                                            <?php echo $allowance->allowance_name; $allowance_list++;?>
                                        </th>
                                    <?php } ?>
                                     <th class="text-right">Miscellaneous</th>    
                                    <th class="text-right">Reimbursements</th>
                                    <th class="text-right text-success">Provident Fund 'Employer'</th>

                                    <th class="text-right text-danger">Deduction Absents</th>
                                    <th class="text-right text-danger">Deduction Late</th>
                                    <th class="text-right text-danger">Provident Fund 'Employee'</th>                                
                                    <th class="text-right text-danger">Tax Deduction</th>
                                    <th class="text-right text-danger">Other Deduction</th>
                                    <th class="text-right text-danger">Loan Deduction</th>

                                    <th class="text-right text-sucess">Total Payable</th>
                                    <th class="text-right text-danger">Total Deductions</th>
                                    <th id="grand_total" class="text-right"><?php echo number_format($totalpayable,2); ?></th>
                                    <th>Decimal Adj</th>
                                    <th >Staff Name</th>
                                    <th ></th>
                                </tfoot>
                            </table>
                
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>

    

    $(document).ready(function() {

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

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

        $("#staff_id").select2();

         $('#account_voucher_date').datepicker({
            autoclose: true,
            todayHighlight: true,
            format: 'yyyy-mm-dd'            
        }).datepicker('setDate', '<?php echo $year;?>-<?php echo $month;?>-28');

        $('#tblstaff').DataTable({
            paging: false,
            info: false,           
            dom: "frtlip",
            
            buttons: [{extend: "copy", className: "btn-sm btn-custom btn-trans"}, {extend: "csv", className: "btn-sm btn-pink btn-trans"}, {
                    extend: "excel",
                    className: "btn-sm btn-warning btn-trans"
                }, {extend: "pdf", className: "btn-sm btn-purple btn-trans"}]
            ,            
            //scrollX: true,
            //"ordering": false,
            stateSave: true
        });
    });
    
    function create_vouchers(){
        $("#btn_create").attr("disabled","disabled");
        
        var TableData;
        TableData = storeOTblValues();
        TableData = $.toJSON(TableData);
        //console.log(TableData);
        if($("#account_voucher_date").val() == ''){
            
            toastr.error('Select the Date you want the vouchers to be created on', 'Info!');
            return false;
        }
        
        if (TableData.length > 2) {

            $.ajax({
               type: "POST",
                    url: '<?php echo base_url().'staff_controller/check_payable'; ?>',
                    data: {
                        month: '<?php echo $monthName;?>',
                        year: '<?php echo $year;?>',
                        voucher_date: $("#account_voucher_date").val(),
                        TableData : TableData
                    },
                    success: function(data) {
                        //console.log(data);
                        $("#btn_create").removeAttr("disabled");
                        if(parseInt(data) > 0){
                            toastr.success('Total vouchers created '+data, 'Done!');
                        } else { 
                            toastr.error('No vouchers created at this time', 'Done!');
                        }   
                    }

            });
        }
            
       
        
    }
    
    function storeOTblValues(){
        var TableData = new Array();
//        $('#tblstaff tr').each(function(row, tr) {
//            TableData[row] = {
//                "staff_id": $(tr).find('td:eq(0)').text()
//                , "staff_fullname": $(tr).find('td:eq(1)').text()
//                , "staff_salary": $(tr).find('td:eq(2)').text()
//                , "deduction_absent": $(tr).find('td:eq(3)').text()
//                , "deduction_late": $(tr).find('td:eq(4)').text()
//                , "provident_fund_employee": $(tr).find('td:eq(5)').text()
//                , "provident_fund_employer": $(tr).find('td:eq(6)').text()
//                , "tax_deduction": $(tr).find('td:eq(7)').text()
//                , "staff_commission": $(tr).find('td:eq(10)').text()
//                , "mobile_allowance": $(tr).find('td:eq(11)').text()
//                , "transport_allowance": $(tr).find('td:eq(12)').text()
//                , "medical_allowance": $(tr).find('td:eq(13)').text()
//                , "miscellanous": $(tr).find('td:eq(14) input[type="number"]').val()
//                , "reimbursements": $(tr).find('td:eq(15) input[type="number"]').val()
//                , "total_payable": $(tr).find('td:eq(17)').text()
//            }      
//        });
        
        $('#tblstaff tr').each(function(row, tr) {
            //console.log(row);
            var a = {};
            $('#tblstaff tr[id="'+$(tr).find('td:eq(0)').text()+'"] td').each(function(col, td) {
               // console.log($(td).attr('key'));
                var elem = $(td).attr('key') ;
                if(typeof $(td).attr('key') != 'undefined' && $(td).attr('key') != ''){
                    //console.log($(td).attr('type'));
                    if($(td).attr('type') !== 'add_input' && $(td).attr('type') !== 'subtract_input'){
                        a[elem] = $(td).text();
                    }else{
                        //console.log($(td).children('input[type="number"]').val());
                        a[elem] = $(td).children('input[type="number"]').val();
                    }
                }
            });
            if(typeof a != 'undefined'){  
                TableData[row] = a;
            }
        });     
        
        TableData.shift();  // first row will be empty - so remove
       
        TableData.pop();    // last row will be empty - so remove
        
        //console.log(TableData);
        return TableData;
        return false;
    }
    
    function updatetotal(id_staff){
        
        
        var payable_elem = "#payable_"+ id_staff;
        var deductions_elem = "#deductions_"+ id_staff;
        var total_payable_elem = "#total_payable_"+ id_staff;
        var rounded_adj_elem = "#rounded_adjustment_"+id_staff;    
        
        
        var payables=0;
        var deductions=0;   
        var total=0;
        $('#tblstaff tr[id="'+id_staff+'"] td').each(function(col, td) {
            

            //console.log($(td).attr('type'));
            if($(td).attr('type')=='add'){
               // console.log($(td).attr('key') + ' ' + $(td).text());
                var mtype = '';
                mtype = $(td).attr('salary_type');
                
                if(mtype=='monthly'){
                    payables = payables + parseFloat($(td).text());
                    total= total + parseFloat($(td).text());
                }else if(mtype=='daily'){
                    payables = payables + (parseFloat($(td).text()) * parseFloat($(td).attr('presents')));
                    total= total + (parseFloat($(td).text()) * parseFloat($(td).attr('presents')));
                }else if(mtype=='weekly'){
                    payables = payables + (parseFloat($(td).text()) * parseFloat($(td).attr('workhours')));
                    total= total + (parseFloat($(td).text()) * parseFloat($(td).attr('workhours')));
                }else{ //not salary
                    payables = payables + parseFloat($(td).text());
                    total= total + parseFloat($(td).text());
                }
            } else if($(td).attr('type')=='subtract'){
                //console.log($(td).text());   
                deductions = deductions + parseFloat($(td).text());
                total= total - parseFloat($(td).text());
            }else if($(td).attr('type')=='add_input'){
               // console.log($(td).attr('key') + ' ' +  $(td).find('input[type="number"]').val());
                payables= payables + parseFloat($(td).find('input[type="number"]').val());
                total= total + parseFloat($(td).find('input[type="number"]').val());
            }else if($(td).attr('type')=='subtract_input'){
                deductions = deductions + parseFloat($(td).find('input[type="number"]').val());               
                total= total - parseFloat($(td).find('input[type="number"]').val());
            }
            
        });
        
        payables = Math.round(payables *1000)/1000;
        //console.log('payables = '+payables);        
        
        deductions = Math.round(deductions *1000)/1000;
        
        total = Math.round(total *1000)/1000;
        
        var rounded_adj = total - Math.floor(total);
        //console.log('adj = '+rounded_adj);
        
        //console.log(total);
        
        $(payable_elem).text(payables);
        $(deductions_elem).text(deductions);
        $(total_payable_elem).text(Math.floor(total));
        $(rounded_adj_elem).text(Math.round(rounded_adj * 1000)/1000);
        
        var grand_total = 0;
        $('#tblstaff tr').each(function(row, tr) {
            $('#tblstaff tr[id="'+$(tr).find('td:eq(0)').text()+'"] td').each(function(col, td) {
               // console.log($(td).attr('key'));
                var elem = $(td).attr('key') ;
                if(typeof $(td).attr('key') != 'undefined' && $(td).attr('key') != ''){
                    if($(td).attr('key') == 'final_payable'){
                        console.log($(td).text());
                        grand_total = grand_total + parseFloat($(td).text());
                    }
                }
            })
        });
        //console.log('grand = '+ grand_total);
        grand_total = Math.round(grand_total*1000)/1000;
        $("#grand_total").html(grand_total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
    }
    
    
        
    var tableToExcel = (function () {
          //  application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
            var uri = 'data:application/vnd.ms-excel;base64,'
              , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
              , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
              , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
            return function (table, name) {
                if (!table.nodeType) table = document.getElementById(table)
                var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
                var link = document.createElement("a");
                
                var d = new Date();
                var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +
                d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);
    
                link.download = ctx.worksheet;
                link.href = uri + base64(format(template, ctx));
                link.click();
                //window.location.href = uri + base64(format(template, ctx))
            }
        })()
    </script>