<link href="assets/plugins/switchery/switchery.min.css" rel="stylesheet" />
<style>
    .b{
        color: black !important;
        font-size: 16px;
        text-transform: capitalize;
        padding: 5px;
        margin-bottom: 5px;
    }

    .fa-fingerprint:before {
        content: "\f577";
        }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="wrapper">
    <div class="container">
        <!-- Page-Title -->
        <div class="row">
            <div class="col-sm-12">
                <div class=" pull-right m-t-15">
                    <button type="button"  onclick="openaddnew();" class="btn btn-custom waves-effect waves-light" >Add Staff<span class="m-l-5"><i class="fa fa-plus"></i></span></button>
                    <button onclick="orderplugin();" class="btn btn-pink waves-effect waves-light "> <span>Change Order</span> <i class="fa fa-sort m-l-5"></i> </button>
                                       
                    <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();?>calculatemonthstaffpayment">Monthly Salary Calculation</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>
                            <!--
                            <li><a href="javascript:void(0);" onclick="paysalaries();" >Pay Salaries</a></li>
                            <li><a href="javascript:void(0);" onclick="paycommissions();">Pay Commissions</a></li>
                            -->
                        </ul>
                    </div>
                </div>
                <h4 class="page-title">Staff</h4>
            </div>
        </div>

        <div class="row">
            <div class="col-sm-12">
                <div class="card-box table-responsive">
                    <h4 class="header-title m-t-0 m-b-30">&nbsp;</h4>

                    <table id="tblstaff" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Status</th>
                                <th>Action</th>
                                <th>Image</th>
                                <th>Display Order</th>
                                <th>Scheduler</th>
                                <?php if($this->session->userdata('role')=="Super User"){?>                                    
                                <th>Shared</th>
                                <?php } ?>
                                <th>Emp. ID</th>
                                <th>Name</th>
                                <th>Cell</th>
                                <th>Phone1</th>
                                <th>CNIC</th>
                                <th>Address</th>
                                <th>Email</th>
                                <th>Comments</th>
                                <th>Branch</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($staffs as $staff) { ?>
                                <?php $businessname = $staff['business_name']; ?>
                                <tr data-toggle="tooltip" title="<?php echo $staff['staff_active'] == "N" ? $staff['staff_fullname'] . " Left " . $businessname : $staff['staff_fullname'] . " Current " . $businessname . " Staff "; ?>" >
                                    <td><?php echo $staff['id_staff']; ?></td>
                                   <td>
                                       <button class="btn btn-sm m-b-5 <?php echo $staff['staff_active'] == "N" ? "btn btn-danger" : "btn btn-primary"; ?>" name="staffactive" id="staffactive" onclick="statusForm('<?php echo $staff['id_staff']; ?>','<?php echo $staff['staff_active'] == "Y" ? "Y" : "N"; ?>');"><?php echo $staff['staff_active'] == "Y" ? "Active" : "Inactive"; ?> </button>
                                       <a class="btn btn-pink btn-sm m-b-5" target="_blank" href="<?php echo base_url(); ?>view_staff_attendance_single/<?php echo $staff['id_staff'].'/'.date('m')."/".date('Y'); ?>" >Attendance</a>
                                       <!--<a class="btn btn-warning btn-sm m-b-5" target="_blank" href="<?php echo base_url(); ?>mark_staff_leave/<?php echo $staff['id_staff'].'/'.date('m')."/".date('Y'); ?>" >Leaves</a>-->
                                    </td>
                                    <td class='noprint'>
                                        <button <?php echo $staff['staff_active'] == "N" ? "disabled" : ""; ?> id='btnedit' onclick="openupdate(<?php echo $staff['id_staff']; ?>);" class="btn btn-icon btn-sm waves-effect waves-light btn-info m-b-5"> <i class="fa fa-keyboard-o"></i> </button>  
                                        <!-- <a href="< ? php echo base_url(); ?>staff_account/< ? php echo $staff['id_staff']; ?>" class="btn btn-icon waves-effect waves-light btn-purple m-b-5 color:#fffff;" ><img style="width: 20px;" src="< ? php echo base_url();?>assets/images/fingerprint-white.svg"></a>  -->
                                        <button onclick="javascript:openfingerprintModal(<?php echo $staff['id_staff']; ?>)" class="btn btn-icon waves-effect waves-light btn-purple m-b-5 color:#fffff;" ><img style="width: 20px;" src="<?php echo base_url();?>assets/images/fingerprint-white.svg"></button> 
                                    </td>
                                    <td>
                                        <a onclick="upload_image('<?php echo $staff['id_staff']; ?>', '<?php echo $staff['staff_image'] ? $staff['staff_image'] : NULL; ?>')" href="javascript:void()">
                                            <img width="70px;" src="<?php echo base_url() . 'assets/images/staff/'; ?><?php echo $staff['staff_image'] ? $staff['staff_image'] : "nu.png"; ?>" alt="<?php echo $staff['staff_fullname'] ?>"/>
                                        </a>
                                    </td>
                                    <td>
                                        <div class="row">
                                            <div class="col-lg-10">
                                                <input readonly class="form-control" size="2" type="text" name="orderid" id="orderid_<?php echo $staff['id_staff']; ?>" onblur="orderservicetype('<?php echo $staff['id_staff']; ?>', this.value);" value="<?php echo $staff['staff_order']; ?>" />
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <input id="<?php echo $staff['id_staff']; ?>" class="showscheduler" type="checkbox" <?php if($staff['staff_scheduler']=="On"){echo 'checked';} ?> data-plugin="switchery" data-color="#00b19d" data-size="small"/>
                                    </td>
                                    <?php if($this->session->userdata('role')=="Super User"){?> 
                                    <td>
                                        <input id="<?php echo $staff['id_staff']; ?>" class="sharedstaff" type="checkbox" <?php if($staff['staff_shared']=="Yes"){echo 'checked';} ?> data-plugin="switchery" data-color="#00b19d" data-size="small"/>
                                    </td>
                                    <?php } ?>
                                    <td><?php echo $staff['staff_eid']; ?></td>
                                    <td><?php if($this->session->userdata("ho")=='No'){ echo $staff['staff_fullname'];}else{echo $staff['staff_fullname'].' '.$businessname;} ?></td>
                                    <td><?php echo $staff['staff_cell']; ?></td>
                                    <td><?php echo $staff['staff_phone1']; ?></td>
                                    <td><?php echo $staff['staff_cnic']; ?></td>
                                    <td><?php echo $staff['staff_address']; ?></td>
                                    <td><?php echo $staff['staff_email']; ?></td>
                                    <td><?php echo $staff['staff_comment']; ?></td>
                                    <td><?php echo $staff['business_id']; ?></td>
                                </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>
            </div><!-- end col -->
        </div>
        <!-- end row -->

        <!--Modals-->

        <!--Add Staff Modal-->
        <div id="addstaff" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="addstaff" aria-hidden="true" style="display: none;">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                        <h4 class="modal-title" id="custom-width-modalLabel">Add a new Staff</h4>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-lg-4">
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtstafffirstname" class="control-label">First Name</label>
                                            <input type="text" class="form-control" placeholder="Staff First Name" id="txtstafffirstname" name="txtstafffirstname" tabindex=1>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtstafffullname" class="control-label">Full Name</label>
                                            <input type="text" class="form-control" placeholder="Staff Full Name" id="txtstafffullname" name="txtstafffullname" tabindex=3>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtstaffphone1" class="control-label">Phone 1</label>
                                            <input type="text" class="form-control numeric" placeholder="Staff Phone 1" id="txtstaffphone1" name="txtstaffphone1" tabindex=5>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtstaffaddress" class="control-label">Address</label>
                                            <input type="text" class="form-control" placeholder="Staff Address" id="txtstaffaddress" name="txtstaffaddress" tabindex=7>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtstaffemail" class="control-label">Email</label>
                                            <input type="text" class="form-control" placeholder="Staff Email" id="txtstaffemail" name="txtstaffemail" tabindex=9>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtweekdayoff" class="control-label">Weekly Day Off</label>
                                            <select class="form-control" multiple="multiple" id="txtweekdayoff"  name="txtweekdayoff" tabindex=12>
                                                <option value="None">None</option>
                                                <option value="Mon">Mon</option>
                                                <option value="Tue">Tue</option>
                                                <option value="Wed">Wed</option>
                                                <option value="Thu">Thu</option>
                                                <option value="Fri">Fri</option>
                                                <option value="Sat">Sat</option>
                                                <option value="Sun">Sun</option>
                                            </select>
                                        </div> 
                                    </div>                                     
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtannualleaves" class="control-label">Total Annual Leaves</label>
                                            <input class="form-control" id="txtannualleaves"  name="txtannualleaves" tabindex=12 value="10">
                                        </div> 
                                    </div>                                     
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtdateofbirth" class="control-label">Date of Birth</label>
                                            <input type="date" class="form-control" placeholder="Date of Birth" id="txtdateofbirth"  name="txtdateofbirth" tabindex=16>
                                            
                                        </div> 
                                    </div> 
                                </div>
                                
                            </div>
                            <div class="col-lg-4">
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtstafflastname" class="control-label">Last Name</label>
                                            <input type="text" class="form-control" placeholder="Staff Last Name" id="txtstafflastname" name="txtstafflastname" tabindex=2>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtstaffcell" class="control-label">Cell</label>
                                            <input type="text" class="form-control numeric" placeholder="Staff Cell" id="txtstaffcell" name="txtstaffcell" tabindex=4>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtstaffphone2" class="control-label">Phone 2</label>
                                            <input type="text" class="form-control numeric" placeholder="Phone 2" id="txtstaffphone2" name="txtstaffphone2" tabindex=6>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="txtstaffeid" class="control-label">Employee Id</label>
                                            <input type="text" class="form-control" placeholder="Staff Employee Id" id="txtstaffeid" name="txtstaffeid" tabindex=8>
                                        </div> 
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="txtfloor" class="control-label">Floor (optional)</label>
                                            <select class="form-control" id="txtfloor" name="txtfloor" tabindex=9>
                                                <?php foreach($floors as $floor){?>
                                                <option value="<?php echo $floor['id_business_floors'];?>"><?php echo $floor['floor_name'];?></option>
                                                <?php } ?>
                                            </select>
                                        </div> 
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="txtsalary" class="control-label">Salary</label>
                                            <input type="text" class="form-control numeric" placeholder="Salary" id="txtsalary"  name="txtsalary" tabindex=9>
                                        </div> 
                                    </div> 
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="txtsalarytype" class="control-label">Type</label>
                                            <select class="form-control" id="txtsalarytype"  name="txtsalarytype" tabindex=9>
                                                <option value="daily">Daily</option>
                                                <option value="weekly">Weekly /hr.</option>
                                                <option selected="selected" value="monthly">Monthly</option>
                                            </select>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtmaxworkmin" class="control-label">Max Work Min Per Day</label>
                                            <input type="text" class="form-control numeric" placeholder="Max Work Min Per Day" id="txtmaxworkmin"  name="txtmaxworkmin" tabindex=11 value="480">
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtnextofkinname" class="control-label">Next of Kin</label>
                                            <input type="text" class="form-control numeric" placeholder="Next of Kin" id="txtnextofkinname"  name="txtnextofkinname" tabindex=16>
                                            
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtnextofkinnumber" class="control-label">Next of Kin Number</label>
                                            <input type="text" class="form-control numeric" placeholder="Next of Kin Number" id="txtnextofkinnumber"  name="txtnextofkinnumber" tabindex=16>
                                            
                                        </div> 
                                    </div> 
                                </div>
                               
                            </div>
                            <div class ="col-md-4">
                                
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtcommissionmode" class="control-label">Commission Mode</label>
                                            <select class="form-control" name="txtcommissionmode" id="txtcommissionmode" tabindex="13">
                                                <option value="Services">Services</option>
                                                <option value="Target">Target</option>
                                            </select>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtcommissiontarget" class="control-label">Target To be Achieved For a Commission</label>
                                            <input type="number" min="0" class="form-control numeric" placeholder="Target To be Achieved For a Fixed Commission" id="txtcommissiontarget"  name="txtcommissiontarget" tabindex=14 value="5000">
                                            <p class="text-sm">Only applicable if Commission Mode is Target</p>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtcommissoinperc" class="control-label">Commission %age on achieving Target</label>
                                            <input type="number" class="form-control numeric" min="0" max="99" placeholder="Commission %age on achieving Target" id="txtcommissoinperc"  name="txtcommissoinperc" tabindex=15 value="5">
                                            <p class="text-sm">Only applicable if Commission Mode is Target</p>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtdeductionpolicy" class="control-label">Deduction Policy on Late and Absent</label>
                                            <select class="form-control" id="txtdeductionpolicy"  name="txtdeductionpolicy" tabindex=16>
                                                <?php foreach($deduction_policies as $deductionpolicy){?>
                                                <option value="<?php echo $deductionpolicy['id_deduction_policy'];?>"><?php echo $deductionpolicy['deduction_policy'];?></option>
                                                <?php } ?>
                                            </select>                                            
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtprovidentfund" class="control-label">Provident Fund %age</label>
                                            <input type="number" class="form-control numeric" min="0" max="50" placeholder="Provident Fund %age of Salary" id="txtprovidentfund"  name="txtprovidentfund" tabindex=15 value="3">
                                            
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtsalary_monthly_tax" class="control-label">Monthly Tax Deduction</label>
                                            <input type="number" class="form-control numeric" min="0" placeholder="Monthly Tax Deduction on Salary" id="txtsalary_monthly_tax"  name="txtsalary_monthly_tax" tabindex=15 value="0">
                                            
                                        </div> 
                                    </div> 
                                </div>
                              
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txtcontractvalidity" class="control-label">Contract Validity</label>
                                            <input type="text" class="form-control numeric" placeholder="Contract Validity" id="txtcontractvalidity"  name="txtcontractvalidity" tabindex=17>
                                            
                                        </div> 
                                    </div> 
                                </div>
                               
                            </div>
                        </div>
                        
                        <div class="row" >
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="tbladdallowance" class="control-label" onclick="storeOTblValues();">Allowance</label>
                                    <table class="table" id="tbladdallowance">
                                        <tbody>
                                        <?php if(isset($allowances)){foreach($allowances as $allowance){?>
                                            <tr>
                                                <td><?php echo $allowance->id_allowances; ?></td>
                                                <td><?php echo $allowance->allowance_name; ?></td>
                                                <td><input type="number" name="allowance_<?php echo $allowance->id_allowances;?>" value="0"></td>
                                            </tr>
                                        <?php } }?>
                                        </tbody>
                                    </table>
                                </div> 
                            </div> 
                        </div>
                            
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-default waves-effect" data-dismiss="modal" tabindex=11>Close</button>
                        <button onclick="addnew();" type="button" class="btn btn-custom waves-effect waves-light" tabindex=10>Save</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div>
        <!--End Add Modal-->

        <!--Edit Staff Modal-->
        <div id="editstaff" class="modal  fade in" tabindex="-1" role="dialog" aria-labelledby="editstaff" aria-hidden="true" style="display: none;">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                        <h4 class="modal-title" id="custom-width-modalLabel">Edit Staff</h4>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-lg-3">
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditstafffirstname" class="control-label">First Name</label>
                                            <input type="text" class="form-control" placeholder="Staff First Name" id="txteditstafffirstname" name="txteditstafffirstname" tabindex=1>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditstafffullname" class="control-label">Full Name</label>
                                            <input type="text" class="form-control" placeholder="Staff Full Name" id="txteditstafffullname" name="txteditstafffullname" tabindex=3>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditstaffphone1" class="control-label">Phone 1</label>
                                            <input type="text" class="form-control numeric" placeholder="Staff Phone 1" id="txteditstaffphone1" name="txteditstaffphone1" tabindex=5>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditstaffaddress" class="control-label">Address</label>
                                            <input type="text" class="form-control" placeholder="Staff Address" id="txteditstaffaddress" name="txteditstaffaddress" tabindex=7>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditstaffemail" class="control-label">Email</label>
                                            <input type="text" class="form-control" placeholder="Staff Email" id="txteditstaffemail" name="txteditstaffemail" tabindex=9>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditweekdayoff" class="control-label">Weekly Day Off</label>
                                            <select multiple="multiple" class="form-control" id="txteditweekdayoff"  name="txteditweekdayoff" tabindex=12>
                                                
                                                <option value="Sun">Sun</option>
                                                <option value="Mon">Mon</option>
                                                <option value="Tue">Tue</option>
                                                <option value="Wed">Wed</option>
                                                <option value="Thu">Thu</option>
                                                <option value="Fri">Fri</option>
                                                <option value="Sat">Sat</option>
                                                <option value="None">None</option>
                                            </select>
                                        </div> 
                                    </div>                                     
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditannualleaves" class="control-label">Total Annual Leaves</label>
                                            <input class="form-control" id="txteditannualleaves"  name="txteditannualleaves" tabindex=12>                                              
                                        </div> 
                                    </div>                                     
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditnextofkinname" class="control-label">Next of Kin</label>
                                            <input class="form-control" id="txteditnextofkinname"  name="txteditnextofkinname" tabindex=12>                                              
                                        </div> 
                                    </div>                                     
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditnextofkinnumber" class="control-label">Next of Kin Number</label>
                                            <input class="form-control" id="txteditnextofkinnumber"  name="txteditnextofkinnumber" tabindex=12>                                              
                                        </div> 
                                    </div>                                     
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <?php if($this->session->userdata('role')=='Super User' || $this->session->userdata('role')=='HR' || $this->session->userdata('role')=='Admin'){?>
                                            <button class="btn btn-danger" onclick="reset_app();">Reset App Registration</button>
                                            <?php } ?>
                                            <input readonly="readonly" style="border: none;" id="txtfcm" class="text-warning" value = "Not Set">
                                        </div> 
                                    </div> 
                                </div>
                            </div>
                            <div class="col-lg-3">
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditstafflastname" class="control-label">Last Name</label>
                                            <input type="text" class="form-control" placeholder="Staff Last Name" id="txteditstafflastname" name="txteditstafflastname" tabindex=2>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditstaffcell" class="control-label">Cell</label>
                                            <input type="text" class="form-control numeric" placeholder="Staff Cell" id="txteditstaffcell" name="txteditstaffcell" tabindex=4>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditstaffphone2" class="control-label">Phone 2</label>
                                            <input type="text" class="form-control numeric" placeholder="Phone 2" id="txteditstaffphone2" name="txteditstaffphone2" tabindex=6>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="txteditstaffeid" class="control-label">Employee Id</label>
                                            <input type="text" class="form-control" placeholder="Staff Employee Id" id="txteditstaffeid" name="txteditstaffeid" tabindex=8>
                                        </div> 
                                    </div> 
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="txteditfloor" class="control-label">Floor (optional)</label>
                                            <select class="form-control" id="txteditfloor" name="txteditfloor" tabindex=9>
                                                <?php foreach($floors as $floor){?>
                                                <option value="<?php echo $floor['id_business_floors'];?>"><?php echo $floor['floor_name'];?></option>
                                                <?php } ?>
                                            </select>
                                        </div> 
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="txteditstaffsalary" class="control-label">Staff Salary</label>
                                            <input type="text" class="form-control numeric" placeholder="Staff Salary" id="txteditstaffsalary" name="txteditstaffsalary" tabindex=9>
                                        </div> 
                                    </div>
                                     <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="txteditsalarytype" class="control-label">Type</label>
                                            <select class="form-control" id="txteditsalarytype"  name="txteditsalarytype" tabindex=9>
                                                <option value="daily">Daily</option>
                                                <option value="weekly">Weekly /hr.</option>
                                                <option selected="selected" value="monthly">Monthly</option>
                                            </select>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditmaxworkmin" class="control-label">Max Work Min Per Day</label>
                                            <input type="text" class="form-control numeric" placeholder="Max Work Min Per Day" id="txteditmaxworkmin"  name="txteditmaxworkmin" tabindex=10 >
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditsalary_monthly_tax" class="control-label">Monthly Tax Deduction</label>
                                            <input type="number" class="form-control numeric" min="0" placeholder="Monthly Tax Deduction on Salary" id="txteditsalary_monthly_tax"  name="txteditsalary_monthly_tax" tabindex=15 value="0">
                                            
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditdateofbirth" class="control-label">Date of Birth</label>
                                            <input type="date" class="form-control"  placeholder="Date of Birth" id="txteditdateofbirth"  name="txteditdateofbirth" tabindex=16 >
                                            
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditcontractvalidity" class="control-label">Contract Validity</label>
                                            <input class="form-control"  placeholder="Contract Validity" id="txteditcontractvalidity"  name="txteditcontractvalidity" tabindex=16 >
                                            
                                        </div> 
                                    </div> 
                                </div>
                            </div>
                            
                            <div class ="col-md-3">                                
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditcommissionmode" class="control-label">Commission Mode</label>
                                            <select class="form-control" name="txteditcommissionmode" id="txteditcommissionmode" tabindex="13">
                                                <option value="Services">Services</option>
                                                <option value="Target">Target</option>
                                            </select>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditcommissiontarget" class="control-label">Target To be Achieved For a Commission</label>
                                            <input type="number" min="0" class="form-control numeric" placeholder="Target To be Achieved For a Fixed Commission" id="txteditcommissiontarget"  name="txteditcommissiontarget" tabindex=14 value="5000">
                                            <p class="text-sm">Only applicable if Commission Mode is Target</p>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditcommissionminperc" class="control-label">Commission %age on achieving Target</label>
                                            <input type="number" class="form-control numeric" min="0" max="99" placeholder="Commission %age on achieving Target" id="txteditcommissionperc"  name="txteditcommissionperc" tabindex=15 value="5">
                                            <p class="text-sm">Only applicable if Commission Mode is Target</p>
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditdeductionpolicy" class="control-label">Deduction Policy on Late and Absent</label>
                                            <select class="form-control" id="txteditdeductionpolicy"  name="txteditdeductionpolicy" tabindex=16>
                                                <?php foreach($deduction_policies as $deductionpolicy){?>
                                                <option value="<?php echo $deductionpolicy['id_deduction_policy'];?>"><?php echo $deductionpolicy['deduction_policy'];?></option>
                                                <?php } ?>
                                            </select>                                            
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditprovidentfund" class="control-label">Provident Fund %age</label>
                                            <input type="number" class="form-control numeric" min="0" max="50" placeholder="Provident Fund %age of Salary" id="txteditprovidentfund"  name="txteditprovidentfund" tabindex=15 value="3">
                                            
                                        </div> 
                                    </div> 
                                </div>
                                
                                
                            </div>
                            
                            <div class="col-md-3">
                                 <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditstaff_designation" class="control-label">Designation </label>
                                            <input type="text" class="form-control" placeholder="Designation" id="txteditstaff_designation"  name="txteditstaff_designation" tabindex=20 >                                            
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditstaff_department" class="control-label">Department</label>
                                            <input type="text" class="form-control" placeholder="Department" id="txteditstaff_department"  name="txteditstaff_department" tabindex=21 >                                            
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditstaff_cnic" class="control-label">CNIC</label>
                                            <input type="text" class="form-control" placeholder="CNIC" id="txteditstaff_cnic"  name="txteditstaff_cnic" tabindex=22 >                                            
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditstaff_date_of_joining" class="control-label">Joining Date</label>
                                            <input class="form-control" id="txteditstaff_date_of_joining"  name="txteditstaff_date_of_joining" tabindex=23 >                                            
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditstaff_bank_account" class="control-label">Bank Account Number</label>
                                            <input class="form-control" id="txteditstaff_bank_account" placeholder="Bank Account Number" name="txteditstaff_bank_account" tabindex=24 >                                            
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditstaff_bank_account_title" class="control-label">Bank Account Title</label>
                                            <input class="form-control" id="txteditstaff_bank_account_title" placeholder="Bank Account Title" name="txteditstaff_bank_account_title" tabindex=24 >
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditstaff_bank" class="control-label">Bank Name</label>
                                            <input class="form-control" id="txteditstaff_bank" placeholder="Bank Name"  name="txteditstaff_bank" tabindex=24 >
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditstarttime" class="control-label">Day Start Time</label>
                                            <input class="form-control" id="txteditstarttime" placeholder="Start Time"  name="txteditstarttime" tabindex=25 >
                                        </div> 
                                    </div> 
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="txteditendtime" class="control-label">Day End Time</label>
                                            <input class="form-control" id="txteditendtime" placeholder="End Time"  name="txteditendtime" tabindex=25 >
                                        </div> 
                                    </div> 
                                </div>
                            </div>
                        </div>
                        <div class="row" >
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="tbleditallowance" class="control-label" onclick="storeOTblValues();">Allowance</label>
                                    <table class="table" id="tbleditallowance">
                                        <tbody>
                                        <?php if(isset($allowances)){foreach($allowances as $allowance){?>
                                            <tr>
                                                <td><?php echo $allowance->id_allowances; ?></td>
                                                <td><?php echo $allowance->allowance_name; ?></td>
                                                <td><input type="number" name="allowance_<?php echo $allowance->id_allowances;?>" value="0"></td>
                                            </tr>
                                        <?php } }?>
                                        </tbody>
                                    </table>
                                </div> 
                            </div> 
                        </div>
                    </div>
                    <div class="modal-footer">
                        <input type="hidden" name="txteditstaffid" id="txteditstaffid" />
                        <input type="hidden" name="txteditbusinessid" id="txteditbusinessid" />
                        
                        <button type="button" class="btn btn-default waves-effect" data-dismiss="modal" tabindex=11>Close</button>
                        <button onclick="update();" type="button" class="btn btn-custom waves-effect waves-light" tabindex=10>Save</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div>
        <!--End Edit Staff Modal-->

        <!--start upload image-->
        <div id="addstaffimage" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="addstaffimage" aria-hidden="true" style="display: none;">
            <form action="<?php echo base_url('staffimage'); ?>" method="POST" enctype="multipart/form-data">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                            <h4 class="modal-title" id="custom-width-modalLabel">Add Staff Image</h4>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-lg-6">
                                    <div class="row">
                                        <div class="col-md-12">
                                            <div class="form-group">
                                                <div id="msg">
                                                    <img id="img" width="100px;" src="" />
                                                </div>
                                                <label for="txtstaffimage" class="control-label">Staff Image</label>
                                                <input class="form-control" type="file" id="staff_image" name="staff_image" />
                                                <input type="hidden" name="org_image" id="org_image" />
                                                <input type="hidden" name="id_image_staff" id="id_image_staff" />
                                            </div> 
                                        </div> 
                                    </div>

                                </div>
                            </div>

                            <div class="modal-footer">
                                <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
                                <button type="submit" class="btn btn-custom waves-effect waves-light">Save</button>
                            </div>
                        </div><!-- /.modal-content -->
                    </div><!-- /.modal-dialog -->
                </div>
            </form>
        </div>
        <!--end upload image-->

        <!--Staff Status Remove Start-->
        <div id="remove" class="modal fade bs-modal" tabindex="-1" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="panelt panel-default">
                        <div class="panel-heading">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                            <h3 class="panel-title">Action Confirmation</h3>
                            <p id="p1"></p>
                        </div>
                        <div class="panel-body" >
                            <span id="p2"></span>
                            <div class="form-group">
                                <label for="staff_comments" class="control-label">Reason</label>
                                <input class="form-control" name="staff_comments" id="staff_comments"  />
                            </div>
                            <div class="btn-list ">
                                <button class="btn btn-success pull-right" data-dismiss="modal" class="close"  >No</button>
                                <button class="btn btn-danger pull-right" id="btndel"  >Yes</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!--Staff Status Remove End-->

        <!--ORDER PLUGIN MODAL START-->
        <div id="orderplugin" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="orderplugin" aria-hidden="true" style="display: none;">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                        <h4 class="modal-title" id="custom-width-modalLabel">Display Order</h4>
                    </div>
                    <div class="modal-body">
                        
                        <ul id="sortable" class=" list-unstyled">
                            <?php foreach ($staffs as $staff) { ?>

                                <li id="<?php echo $staff['id_staff']; ?>" class="ui-state-default">
                                    <div class="alert alert-warning b">
                                        <a href="#" class="close"><i class="glyphicon glyphicon-move m-l-5" style="padding-top:13px;"></i></a>
                                        <img height="50px;" width="50px;" src="<?php echo base_url() . 'assets/images/staff/'; ?><?php echo $staff['staff_image'] ? $staff['staff_image'] : "nu.png"; ?>" alt="<?php echo $staff['staff_fullname'] ?>"/>
                                        <?php echo $staff['staff_fullname']; ?>
                                    </div>
                                </li>

                            <?php } ?>
                        </ul>
                    </div>
                    <div class="modal-footer">
                        <input type="hidden" name="neworder" id="neworder" value="" />
                        <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
                        <button onclick="changeorder();" class="btn btn-custom waves-effect waves-light orderloader"><span>Save</span></button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div>
        <!--ORDER PLUGIN MODAL END-->

        <!---Salaries Modal Start-->
        <div id="paysalaries" class="modal fade in " tabindex="-1" role="dialog" aria-labelledby="paysalaries" aria-hidden="true" style="display: none;">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                            <div class="modal-title">
                                <div class="col-md-3">
                                    <h4 class="modal-title" id="custom-width-modalLabel">Pay Salaries for Month: </h4>
                                </div>
                                <div class="col-md-2">
                                    <select class="form-control col-md-4" id="salarymonth">
                                        <?php $month = $lastmonthyear[0]['Month']; ?>
                                            <option value="January" <?php if ($month === '1') {
                                                echo "selected";
                                            } ?> >January</option>
                                            <option value="February" <?php if ($month === '2') {
                                                echo "selected";
                                            } ?>>February</option>
                                                <option value="March" <?php if ($month === '3') {
                                                echo "selected";
                                            } ?>>March</option>
                                                <option value="April" <?php if ($month === '4') {
                                                echo "selected";
                                            } ?>>April</option>
                                                <option value="May" <?php if ($month === '5') {
                                                echo "selected";
                                            } ?>>May</option>
                                                <option value="June" <?php if ($month === '6') {
                                                echo "selected";
                                            } ?>>June</option>
                                                <option value="July" <?php if ($month === '7') {
                                                echo "selected";
                                            } ?>>July</option>
                                                <option value="August" <?php if ($month === '8') {
                                                echo "selected";
                                            } ?>>August</option>
                                                <option value="September" <?php if ($month === '9') {
                                                echo "selected";
                                            } ?>>September</option>
                                                <option value="October" <?php if ($month === '10') {
                                                echo "selected";
                                            } ?>>October</option>
                                                <option value="November" <?php if ($month === '11') {
                                                echo "selected";
                                            } ?>>November</option>
                                                <option value="December" <?php if ($month === '12') {
                                                echo "selected";
                                            } ?>>December</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <select class="form-control" id="salaryyear">
                                        <?php $year=$lastmonthyear[0]['Year']; for($x=1; $x<=4; $x++){?>
                                        <option value="<?php echo $year;?>" <?php if($year===$lastmonthyear[0]['Year']){ echo "selected";} ?>><?php echo $year;?></option>
                                        <?php $year=$year-1; }?>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <select class="form-control" id="salarymode" onchange="mode_changed();">
                                        <option value="cash" >Cash</option>
                                        <option value="check" >Bank</option>
                                    </select>
                                </div>
                                 <?php if(isset($cash_accounts)){?>
                                   <div class="col-md-2" id="salary_cash_mode">
                                        <select type="text" id="cash_accounts" name="cash_accounts" class="form-control" >
                                            <?php foreach ($cash_accounts as $cash_account){ ?>
                                            <option value="<?php echo $cash_account['id_account_heads']; ?>"><?php echo $cash_account['account_head_number']."-".$cash_account['account_head'];?></option>
                                            <?php } ?>
                                        </select>                                       
                                   </div>
                               
                               <?php } ?>
                                 <?php if(isset($bank_accounts)){?>

                                   <div class="col-md-2" id="salary_check_mode" style="display: none;">
                                       
                                        <select type="text" id="bank_accounts" name="bank_accounts" class="form-control" >
                                            <?php foreach ($bank_accounts as $bank_account){ ?>
                                            <option value="<?php echo $bank_account['id_account_heads']; ?>"><?php echo $bank_account['account_head_number']."-".$bank_account['account_head'];?></option>
                                            <?php } ?>
                                        </select>    

                                   </div>
                               
                               <?php } ?>
                               
                            </div>
                    </div>
                    <div class="modal-body">
                        <div class="row m-b-10">
                            <div class="col-sm-12">
                                <div class=" pull-right m-t-15">
                                    <button onclick="unselectall();" type="button" class="btn btn-custom waves-effect waves-light" >Un Select</button>
                                    <button onclick="selectall();" type="button" class="btn btn-primary waves-effect waves-light ">Select All</button>
                                    <button onclick="updatesalaryselected();" type="button" class="btn btn-warning waves-effect waves-light ">Mark Paid</button>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <table class="table table-striped table-bordered" id="salarieslist">
                                <thead>
                                    <tr>
                                        <td>ID</td>
                                        <td>Name</td>
                                        <td>Salary</td>
                                        <td></td>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($staffs as $staff) { if($staff['staff_active']!=="N"){?>
                                    <tr>
                                        <td><?php echo $staff['id_staff'];?></td>
                                        <td><?php echo $staff['staff_fullname'];?></td>
                                        <td><input class="form-control" name="salaryamount" value="<?php echo $staff['staff_salary'];?>" /></td>
                                        <td><input class="checkbox valid" name="salarycheck" type="checkbox" checked="checked " /></td>
                                    </tr>
                                    <?php }} ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>        
        <!---Salaries Modal End-->

        <!---Commissions Modal Start-->
        <div id="paycommissions" class="modal fade in " tabindex="-1" role="dialog" aria-labelledby="paycommissions" aria-hidden="true" style="display: none;">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                            <div class="modal-title">
                                <div class="col-md-3">
                                    <h4 class="modal-title" id="custom-width-modalLabel">Pay Commissions for Month: </h4>
                                </div>
                                <div class="col-md-2">
                                    <select onchange="getcommissions();" class="form-control col-md-4" id="commissionsmonth">
                                        <?php $month = $lastmonthyear[0]['Month']; ?>
                                            <option value="1 January" <?php if ($month === '1') {
                                                echo "selected";
                                            } ?> >January</option>
                                            <option value="2 February" <?php if ($month === '2') {
                                                echo "selected";
                                            } ?>>February</option>
                                                <option value="3 March" <?php if ($month === '3') {
                                                echo "selected";
                                            } ?>>March</option>
                                                <option value="4 April" <?php if ($month === '4') {
                                                echo "selected";
                                            } ?>>April</option>
                                                <option value="5 May" <?php if ($month === '5') {
                                                echo "selected";
                                            } ?>>May</option>
                                                <option value="6 June" <?php if ($month === '6') {
                                                echo "selected";
                                            } ?>>June</option>
                                                <option value="7 July" <?php if ($month === '7') {
                                                echo "selected";
                                            } ?>>July</option>
                                                <option value="8 August" <?php if ($month === '8') {
                                                echo "selected";
                                            } ?>>August</option>
                                                <option value="9 September" <?php if ($month === '9') {
                                                echo "selected";
                                            } ?>>September</option>
                                                <option value="10 October" <?php if ($month === '10') {
                                                echo "selected";
                                            } ?>>October</option>
                                                <option value="11 November" <?php if ($month === '11') {
                                                echo "selected";
                                            } ?>>November</option>
                                                <option value="12 December" <?php if ($month === '12') {
                                                echo "selected";
                                            } ?>>December</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <select onchange="getcommissions();" class="form-control" id="commissionsyear">
                                        <?php $year=$lastmonthyear[0]['Year']; for($x=1; $x<=4; $x++){?>
                                        <option value="<?php echo $year;?>" <?php if($year===$lastmonthyear[0]['Year']){ echo "selected";} ?>><?php echo $year;?></option>
                                        <?php $year=$year-1; }?>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <select class="form-control" id="commissionsmode" onchange="commission_mode_changed();">
                                        <option value="cash" >Cash</option>
                                        <option value="check" >Bank</option>
                                    </select>
                                </div>
                                 <?php if(isset($cash_accounts)){?>
                                   <div class="col-md-2" id="commission_cash_mode">
                                        <select type="text" id="commission_cash_accounts" name="commission_cash_accounts" class="form-control" >
                                            <?php foreach ($cash_accounts as $cash_account){ ?>
                                            <option value="<?php echo $cash_account['id_account_heads']; ?>"><?php echo $cash_account['account_head_number']."-".$cash_account['account_head'];?></option>
                                            <?php } ?>
                                        </select>                                       
                                   </div>
                               
                               <?php } ?>
                                 <?php if(isset($bank_accounts)){?>

                                   <div class="col-md-2" id="commission_check_mode" style="display: none;">
                                       
                                        <select type="text" id="commission_bank_accounts" name="commission_bank_accounts" class="form-control" >
                                            <?php foreach ($bank_accounts as $bank_account){ ?>
                                            <option value="<?php echo $bank_account['id_account_heads']; ?>"><?php echo $bank_account['account_head_number']."-".$bank_account['account_head'];?></option>
                                            <?php } ?>
                                        </select>    

                                   </div>
                               
                               <?php } ?>
                               
                            </div>
                    </div>
                    <div class="modal-body">
                        <div class="row m-b-10">
                            <div class="col-sm-12">
                                <div class=" pull-right m-t-15">
                                    <button onclick="unselectcommissions();" type="button" class="btn btn-custom waves-effect waves-light" >Un Select</button>
                                    <button onclick="selectcommissions();" type="button" class="btn btn-primary waves-effect waves-light ">Select All</button>
                                    <button onclick="updatecommissionselected();" type="button" class="btn btn-warning waves-effect waves-light ">Mark Paid</button>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <table class="table table-striped table-bordered" id="commissionslist">
                                <thead>
                                    <tr>
                                        <td>ID</td>
                                        <td>Name</td>
                                        <td>Services</td>
                                        <td>Commission</td>
                                        <td></td>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($commissions as $commission) { ?>
                                    <tr>
                                        <td><?php echo $commission['staff_id'];?></td>
                                        <td><?php echo $commission['staff_name'];?></td>
                                        <td><?php echo $commission['Total Services'];?></td>
                                        <td><input class="form-control" name="commissionamount" value="<?php echo $commission['Commission'];?>" /></td>
                                        <td><input class="checkbox valid" name="commissioncheck" type="checkbox" checked="checked " /></td>
                                    </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>        
        <!---Commissions Modal End-->
        
        <!--Payments Modal Start-->
        <div id="paymentsmodal" class="modal fade in " tabindex="-1" role="dialog" aria-labelledby="paymentsmodal" aria-hidden="true" style="display: none;">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                            <div class="modal-title">
                                <div class="col-md-3">
                                    <h4 class="modal-title" id="custom-width-modalLabel">Other Payments: </h4>
                                </div>
                                <div class="col-md-2"></div>
                            </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Payments Modal End-->
        <input type='hidden' id=quality size=10 value="100">
        <div class="modal fade" id="fingerprintModal" tabindex="-1" role="dialog" aria-labelledby="fingerprintModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body text-center">
                        <input type="hidden" name="staff_id" id="staff_id_for_fingerprint" >
                        <input type="hidden" name="staff_fingerprint_template_base64" id="staff_fingerprint_template_base64" >
                        <img id ="FPImage" src="<?php echo base_url() . 'assets/images/staff_fingerprint/'; ?>fingerprint_placeholder.jpg" alt="<?php echo $staff['staff_fullname'] ?>" style="height: 50vh;"/>
                        </br>
                        <button id="fingerprint_scan_button" type="button" class="btn btn-icon btn-sm waves-effect waves-light m-t-10 btn-info" onclick="CallSGIFPGetData(SuccessFunc, ErrorFunc)">Click to Scan</button> 
                        <button id="fingerprint_save_button" type="button" class="btn btn-icon btn-sm waves-effect waves-light m-t-10 btn-custom" style="display: none;" onclick="update_fingerprint();">Save</button>
                    </div>
                </div>
            </div>
        </div>

        <!--FPImage Modal Start-->
        <input type='hidden' id=quality size=10 value="100">
        <div class="modal fade" id="fingerprintModal" tabindex="-1" role="dialog" aria-labelledby="fingerprintModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body text-center">
                        <input type="hidden" name="staff_id" id="staff_id_for_fingerprint" >
                        <input type="hidden" name="staff_fingerprint_template_base64" id="staff_fingerprint_template_base64" >
                        <img id ="FPImage" src="<?php echo base_url() . 'assets/images/staff_fingerprint/'; ?>fingerprint_placeholder.jpg" alt="<?php echo $staff['staff_fullname'] ?>" style="height: 50vh;"/>
                        </br>
                        <button id="fingerprint_scan_button" type="button" class="btn btn-icon btn-sm waves-effect waves-light m-t-10 btn-info" onclick="CallSGIFPGetData(SuccessFunc, ErrorFunc)">Click to Scan</button> 
                        <button id="fingerprint_save_button" type="button" class="btn btn-icon btn-sm waves-effect waves-light m-t-10 btn-custom" style="display: none;" onclick="update_fingerprint();">Save</button>
                    </div>
                </div>
            </div>
        </div>
        <!--FPImage Modal Start-->

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-xmlrpc/0.4.3/jquery.xmlrpc.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {

                $("#txteditstarttime").datetimepicker({
                    format: 'HH:mm:00',
                    enabledHours: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
                    allowInputToggle: true,
                    stepping: 5
                });
                
                $("#txteditendtime").datetimepicker({
                    format: 'HH:mm:00',
                    enabledHours: [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
                    allowInputToggle: true,
                    stepping: 5
                });


                $('#tblstaff').DataTable({
                    lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                    stateSave: true,
                    dom: "Bfrtlip",
                    buttons: [{extend: "copy", className: "btn-sm btn-custom btn-trans"}, {extend: "csv", className: "btn-sm btn-pink btn-trans"}, {
                            extend: "excel",
                            className: "btn-sm btn-warning btn-trans"
                        }, {extend: "pdf", className: "btn-sm btn-purple btn-trans"}],
                    responsive: 0,
                    "order": [[ 0, "asc" ]]
                    
                });
                
                $("#txteditstaff_date_of_joining").datepicker({
                     autoclose: true,
                    todayHighlight: true,
                    format: 'yyyy-mm-dd'
                });
                
                $('[data-toggle="tooltip"]').tooltip();


                $('#salarieslist').DataTable({
                    paging:false
                });
                
                $('#commissionslist').DataTable({
                    paging:false
                });
                
                $('#txtweekdayoff').select2();
                $('#txteditweekdayoff').select2();
                
                toastr.options = {
                    "closeButton": true,
                    "debug": true,
                    "newestOnTop": true,
                    "progressBar": true,
                    "positionClass": "toast-bottom-center",
                    "preventDuplicates": true,
                    "onclick": null,
                    "showDuration": "300",
                    "hideDuration": "1000",
                    "timeOut": "5000",
                    "extendedTimeOut": "1000",
                    "showEasing": "swing",
                    "hideEasing": "linear",
                    "showMethod": "fadeIn",
                    "hideMethod": "fadeOut"
                }

                $(".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;
                    }
                });

                //Add form concat function......start
                $('#txtstafffirstname').keyup(function() {
                    var firstname = $(this).val();
                    var lastname = $('#txtstafflastname').val();
                    $('#txtstafffullname').val('');
                    $('#txtstafffullname').val(firstname + ' ' + lastname);
                });

                $('#txtstafflastname').keyup(function() {
                    var lastname = $(this).val();
                    var firstname = $('#txtstafffirstname').val();
                    var concatname = firstname + ' ' + lastname;
                    $('#txtstafffullname').val('');
                    $('#txtstafffullname').val(concatname);
                });
                //Add form concat function......end

                //Edit form concat function......start
                $('#txteditstafffirstname').keyup(function() {
                    var firstname = $(this).val();
                    var lastname = $('#txteditstafflastname').val();
                    $('#txteditstafffullname').val('');
                    $('#txteditstafffullname').val(firstname + ' ' + lastname);
                });

                $('#txteditstafflastname').keyup(function() {
                    var lastname = $(this).val();
                    var firstname = $('#txteditstafffirstname').val();
                    var concatname = firstname + ' ' + lastname;
                    $('#txteditstafffullname').val('');
                    $('#txteditstafffullname').val(concatname);
                });
                //Edit form concat function......end


                $(".showscheduler").change(function (){
                    console.log($(this).prop("checked"));
                    console.log($(this).attr("id"));
                    scheduler_on($(this).attr("id"), $(this).prop("checked"));
                    
                });
                
                $(".sharedstaff").change(function (){
                    console.log($(this).prop("checked"));
                    console.log($(this).attr("id"));
                    sharedstaff($(this).attr("id"), $(this).prop("checked"));
                    
                });

            });
            
            function scheduler_on(id, val){
                if(val===true){
                    val="On";
                } else {val="Off";}
                $.ajax({
                        type: 'POST',
                        url: 'staff_controller/update_staff_scheduler',
                        data: {id_staff: id, staff_scheduler: val},
                        success: function(data) {
                            //console.log(data);
                            var result = data.split("|");
                            if (result[0] === "success") {
                                toastr.success(data, 'Staff Updated');
                                //location.reload();
                            }
                        }
                    });
            }
            
            
            function sharedstaff(id, val){
                if(val===true){
                    val="Yes";
                } else {val="No";}
                $.ajax({
                        type: 'POST',
                        url: 'staff_controller/update_staff_shared',
                        data: {id_staff: id, staff_shared: val},
                        success: function(data) {
                            //console.log(data);
                            var result = data.split("|");
                            if (result[0] === "success") {
                                toastr.success(data, 'Staff Updated');
                                //location.reload();
                            }
                        }
                    });
            }
            
            function openupdate(id) {
                
               
                
                $.ajax({
                    type: 'POST',
                    url: '<?php echo base_url(); ?>staff_controller/edit_staff',
                    data: {id_staff: id},
                    dataType: "json",
                    cache: false,
                    async: true,
                    success: function(result){
                       
                        var data = result.staff;
                        data = data[0];
                        var allowances = result.allowances;
                        allowances = allowances[0];
                        //console.log(data);
                        //console.log(allowances); 
                        $("#txteditbusinessid").val(data.business_id);
                        $("#txteditstaffid").val(id);
                        $("#txteditstafffullname").val(data.staff_fullname);
                        $("#txteditstafffirstname").val(data.staff_firstname);
                        $("#txteditstafflastname").val(data.staff_lastname);
                        $("#txteditstaffcell").val(data.staff_cell);
                        $("#txteditstaffphone1").val(data.staff_phone1);
                        $("#txteditstaffphone2").val(data.staff_phone2);
                        $("#txteditstaffeid").val(data.staff_eid);
                        $("#txteditfloor").val(data.floor_id);
           
                        $("#txteditstaffaddress").val(data.staff_address);
                        $("#txteditstaffemail").val(data.staff_email);
                        $("#txteditstaffsalary").val(data.staff_salary);
                        $("#txteditsalarytype").val(data.salary_type);
                        
                        $("#txteditmaxworkmin").val(data.staff_work_min);
                        $("#txtfcm").val(data.fcm_id);
                        
                        var weekdayoff = data.week_day_off.split(', ');
                        $('#txteditweekdayoff').val(weekdayoff);
                        
                        $('#txteditweekdayoff').trigger('change'); 
                       // $("#txteditweekdayoff").val(data.week_day_off);
                        $("#txteditannualleaves").val(data.staff_annual_leaves);
                        
                        $("#txteditcommissionmode").val(data.commission_mode);
                        $("#txteditcommissionperc").val(data.staff_commission_perc);
                        $("#txteditcommissiontarget").val(data.commission_target);
                        $("#txteditdeductionpolicy").val(data.deduction_policy);
                        $("#txteditprovidentfund").val(data.provident_fund_rate);
                        $("#txteditsalary_monthly_tax").val(data.salary_monthly_tax);
                        
                        
                        $("#txteditstaff_designation").val(data.staff_designation);
                        $("#txteditstaff_department").val(data.staff_department);
                        $("#txteditstaff_cnic").val(data.staff_cnic);
                        $("#txteditstaff_date_of_joining").val(data.staff_date_of_joining);
                        $("#txteditstaff_bank_account").val(data.staff_bank_account);
                        $("#txteditstaff_bank_account_title").val(data.staff_bank_account_title);
                        $("#txteditstaff_bank").val(data.staff_bank);
                        $("#txteditstarttime").val(data.day_start_time);
                        $("#txteditendtime").val(data.day_end_time);
                        
                        $("#txteditnextofkinname").val(data.next_of_kin_name);
                        $("#txteditnextofkinnumber").val(data.next_of_kin_number);
                        $("#txteditdateofbirth").val(data.date_of_birth);
                        $("#txteditcontractvalidity").val(data.contract_validity);

                        
                        var mhtml='';
                        for(x=0; x<allowances.length; x++){
                            
                            mhtml += '<tr>';
                            mhtml += '<td>'+allowances[x]['id_allowances']+'</td>';
                            mhtml += '<td>'+allowances[x]['allowance_name']+'</td>';
                            mhtml += '<td><input type="number" value="'+allowances[x]['allowance_amount']+'" ></td>';
                            mhtml += '</tr>';
                        }   
                        $("#tbleditallowance tbody").html(mhtml);
                        
                        $("#editstaff").modal('show');
                    }
                });
            }
            function update() {
            
                var TableData;
                TableData = storeEditTblValues();
                TableData = $.toJSON(TableData);
                
                if ($("#txteditstafffirstname").val() !== "" && $("#txteditstafflastname").val() !== "" && $("#txteditstafffullname").val() !== "") {
                    var fullname = $("#txteditstafffirstname").val() + ' ' + $("#txteditstafflastname").val();
                    $.ajax({
                        type: 'POST',
                        url: 'staff_controller/update_staff',
                        data: {id_staff: $("#txteditstaffid").val(), 
                            staff_firstname: $("#txteditstafffirstname").val(), 
                            staff_lastname: $("#txteditstafflastname").val(), 
                            staff_fullname: fullname, 
                            staff_cell: $("#txteditstaffcell").val(), 
                            staff_phone1: $("#txteditstaffphone1").val(), 
                            staff_phone2: $("#txteditstaffphone2").val(), 
                            staff_eid: $("#txteditstaffeid").val(), 
                            
                            staff_email: $("#txteditstaffemail").val(), 
                            staff_address: $("#txteditstaffaddress").val(), 
                            staff_salary: $("#txteditstaffsalary").val(),
                            salary_type : $("#txteditsalarytype").val(),
                            staff_work_min: $("#txteditmaxworkmin").val(),
                            week_day_off: $("#txteditweekdayoff").val(),
                            staff_annual_leaves: $("#txteditannualleaves").val(),                            
                            commission_mode: $("#txteditcommissionmode option:selected").val(),
                            staff_commission_perc:  $("#txteditcommissionperc").val(),
                            commission_target : $("#txteditcommissiontarget").val(),
                            deduction_policy: $("#txteditdeductionpolicy option:selected").val(),
                            provident_fund_rate: $("#txteditprovidentfund").val(),
                            salary_monthly_tax: $("#txteditsalary_monthly_tax").val(),
                            staff_designation: $("#txteditstaff_designation").val(),
                            staff_department: $("#txteditstaff_department").val(),
                            staff_date_of_joining: $("#txteditstaff_date_of_joining").val(),
                            staff_cnic: $("#txteditstaff_cnic").val(),
                            staff_bank_account: $("#txteditstaff_bank_account").val(),
                            staff_bank_account_title: $("#txteditstaff_bank_account_title").val(),
                            staff_bank: $("#txteditstaff_bank").val(),
                            start_time: $("#txteditstarttime").val(),
                            end_time: $("#txteditendtime").val(),
                            business_id: $("#txteditbusinessid").val(),
                            floor_id: $("#txteditfloor option:selected").val(), 
                            floor: $("#txteditfloor option:selected").text(), 
                            next_of_kin_name: $("#txteditnextofkinname").val(),
                            next_of_kin_number: $("#txteditnextofkinnumber").val(),
                            date_of_birth: $("#txteditdateofbirth").val(),
                            contract_validity: $("#txteditcontractvalidity").val(),
                            TableData: TableData                
                        },
                        success: function(data) {
                            //console.log(data);
                            var result = data.split("|");
                            if (result[0] === "success") {
                                toastr.success(data, 'Staff Updated');
                                location.reload();
                            }
                        }
                    });
                } else {
                    swal({
                        title: "Required!",
                        text: 'First/last/full name should not be empty!',
                        type: "info",
                        confirmButtonText: 'OK!'
                    });
                }
            }

            function openaddnew() {
                $("#addstaff").modal('show');
            }
            function addnew() {
                
                var TableData;
                TableData = storeOTblValues();
                TableData = $.toJSON(TableData);
                
                
                if ($("#txtstafffirstname").val() !== "" && $("#txtstafflastname").val() !== "" && $("#txtstafffullname").val() !== "" && $("#txtsalary").val() !== "" && $("#txtmaxworkmin").val() !== "") {
                    var fullname = $("#txtstafffirstname").val() + ' ' + $("#txtstafflastname").val();
                    $.ajax({
                        type: 'POST',
                        url: 'staff_controller/add_staff',
                        data: {staff_firstname: $("#txtstafffirstname").val(), 
                            staff_lastname: $("#txtstafflastname").val(), 
                            staff_fullname: fullname, 
                            staff_cell: $("#txtstaffcell").val(), 
                            staff_phone1: $("#txtstaffphone1").val(), 
                            staff_phone2: $("#txtstaffphone2").val(), 
                            staff_address: $("#txtstaffaddress").val(), 
                            staff_eid: $("#txtstaffeid").val(), 
                            staff_email: $("#txtstaffemail").val(), 
                            staff_salary: $("#txtsalary").val(), 
                            salary_type: $("#txtsalarytype").val(), 
                            staff_work_min: $("#txtmaxworkmin").val(),
                            week_day_off: $("#txtweekdayoff").val(),
                            staff_annual_leaves: $("#txtannualleaves").val(),
                            commission_mode: $("#txtcommissionmode option:selected").val(),
                            staff_commission_perc:  $("#txtcommissoinperc").val(),
                            commission_target : $("#txtcommissiontarget").val(),
                            deduction_policy: $("#txtdeductionpolicy option:selected").val(),
                            provident_fund_rate: $("#txtprovidentfund").val(),
                            salary_monthly_tax: $("#txtsalary_monthly_tax").val(),
                            floor_id: $("#txtfloor option:selected").val(),
                            floor: $("#txtfloor option:selected").text(),

                            next_of_kin_name: $("#txtnextofkinname").val(),
                            next_of_kin_number:$("#txtnextofkinnumber").val(),
                            date_of_birth:$("#txtdateofbirth").val(),
                            contract_validity:$("#txtcontractvalidity").val(),

                            TableData: TableData                        
                
                        },
                        success: function(data) {
                            //console.log(data);
                            var result = data.split("|");
                            if (result[0] === "success") {
                                toastr.success(data, 'New Staff Added');
                                location.reload();
                            }
                        }
                    });
                } else {
                    swal({
                        title: "Required!",
                        text: 'First/last/full name/salary should not be empty!',
                        type: "info",
                        confirmButtonText: 'OK!'
                    });
                }
            }

            function upload_image(id_staff, image) { //previously image = null
                if (id_staff && id_staff != null) {
                    $("#org_image").val('');
                    $("#id_image_staff").val('');
                    $("#id_image_staff").val(id_staff);
                    if (image && image != null) {
                        $("#org_image").val(image);
                        $("#msg #img").attr('src', 'assets/images/staff/' + image);
                    } else {
                        $("#msg #img").attr('src', 'assets/images/staff/nu.png');
                    }
                    $("#addstaffimage").modal("show");
                }
            }

            function statusForm(id, status) {
               // console.log (status);
                if (status === "Y") {
                    $("#p1").html('');
                    $("#p1").html("You are about to deactivate this staff!");
                    $("#p2").html('');
                    $("#p2").html("Are you sure ?");
                     $("#staff_comments").val('');
                    status="N";
                } else if (status === "N") {
                    $("#p1").html('');
                    $("#p1").html("You are about to activate this Staff!");
                    $("#p2").html('');
                    $("#p2").html("Are you sure ?");
                     $("#staff_comments").val('');
                    status="Y";
                }

                $('#btndel').attr('onclick', 'status_active("' + status + '","' + id + '")');
                $('#remove').modal({
                    keyboard: false,
                    backdrop: 'static'
                });
            }

            function status_active(status, id) {
               // console.log(status + id);
                $.ajax({
                    url: "<?php echo base_url('staff_status'); ?>",
                    type: "POST",
                    //data: "staffactive=" + status + "&id_staff_status=" + id,
                    data: {staffactive: status, id_staff_status: id, staff_comment: $("#staff_comments").val()},
                    success: function(data) {
                        if (data === "success") {
                            toastr.success(data, 'Staff Status Changed');
                            location.reload();
                        }
                    },
                    error: function(jXHR, textStatus, errorThrown) {
                        alert(errorThrown);
                    }
                });
            }

            function orderservicetype(id, orderid) {
                return false;
                var type = "packagetype";

                if (id && orderid) {
                    $.ajax({
                        type: 'POST',
                        url: '<?php echo base_url(); ?>staff_controller/order_function',
                        data: {id: id, orderid: orderid, type: type},
                        success: function(data) {
                            toastr.success(data, 'Display Order has been updated!');
                            //location.reload();
                        }
                    });
                }
            }

            function orderplugin() {
                $('#orderplugin').modal('show');
            }

            $(function() {
                $("#sortable").sortable({
                    update: function(event, ui) {
                        getOrder();
                    }

                });
            });
            function getOrder() {
                var order = $("#sortable .ui-state-default").map(function() {
                    return this.id;
                }).get();

                $('#neworder').val(order);
            }
            function changeorder() {
                $('.orderloader span').text('');
                $('.orderloader span').addClass('fa fa-spin fa-spinner');
                var ordernew = $('#neworder').val();

                $.ajax({
                    type: 'POST',
                    url: 'staff_controller/changelistorder',
                    data: {staff_order: ordernew},
                    success: function(data) {
                        //console.log(data);return false;
                        var result = data.split("|");
                        if (result[0] === "success") {
                            toastr.success(data, 'Staff Order Changed');
                            setTimeout(function() {
                                location.reload();
                            }, 3000);

                        }
                    }
                });
                
            }

            
            function selectall(){
                $('#salarieslist tr').each(function(row, tr) {
                    $(tr).find('td:eq(3)').find('input[name=salarycheck]').prop('checked', true);
                });
            }
            
            function unselectall(){
                $('#salarieslist tr').each(function(row, tr) {
                   $(tr).find('td:eq(3)').find('input[name=salarycheck]').prop('checked', false);
                });
            }
            
            function paysalaries(){
                $("#paysalaries").modal('show');
            }
            
            function updatesalaryselected(){
                var TableData;
                TableData = storeSalaryTblValues();
                TableData = $.toJSON(TableData);
                if (TableData.length > 2) {
                    $.ajax({
                        type: "POST",
                        url: '<?php echo base_url().'staff_controller/updatesalaries'; ?>',
                        data: {
                            salarydata:TableData, month:$("#salarymonth :selected").val(), year:$("#salaryyear :selected").val()
                            , salarymode:$("#salarymode :selected").val(), bank_accounts:$("#bank_accounts option:selected").val()
                            , cash_accounts:$("#cash_accounts option:selected").val()
                        },
                        success: function(data) {
                            var result = data.split("|");
                            if (result[0] === "success") {
                                toastr.success(result[1]+' Salaries updated!', 'Done!');
                                $("#paysalaries").modal('hide');
                            } else {
                                swal({
                                    title: "Error",
                                    text: result[1],
                                    type: "error",
                                    confirmButtonText: 'OK!'
                                });
                            }
                        }
                    });
                    
                }
            }
            
            
            function storeSalaryTblValues() {
                var TableData = new Array();
                var x=1;
                $('#salarieslist tr').each(function(row, tr) {
                    
                    if($(tr).find('td:eq(3)').find('input[name=salarycheck]').prop('checked')==true){
                        TableData[x] = {
                            "staff_id": $(tr).find('td:eq(0)').text()
                            , "staff_name": $(tr).find('td:eq(1)').text()
                            , "payment_amount": $(tr).find('td:eq(2)').find('input[name=salaryamount]').val()
                            , "payment_type":'Salary'                            
                            , "payment_remarks": 'Monthly Salary'
                        }
                        x++;
                    }
                });
                TableData.shift();  // first row will be empty - so remove
                return TableData;
            }
            
            //commissions
            function selectcommissions(){
                $('#commissionslist tr').each(function(row, tr) {
                    $(tr).find('td:eq(4)').find('input[name=commissioncheck]').prop('checked', true);
                });
            }
            
            function unselectcommissions(){
                console.log('here');
                $('#commissionslist tr').each(function(row, tr) {
                   $(tr).find('td:eq(4)').find('input[name=commissioncheck]').prop('checked', false);
                });
            }
            
            function paycommissions(){
                $("#paycommissions").modal('show');
            }
            
            
            function getcommissions(){
                
                var x  = $("#commissionsmonth :selected").val().split(" ");
                var month= x[0];
                var year = $("#commissionsyear :selected").val();
                $.ajax({
                        type: "POST",
                        url: '<?php echo base_url().'staff_controller/get_commissions'; ?>',
                        data: {month: month, year:year},
                        dataType: "json",
                        success: function(data) {
                            
                            $('#commissionslist').DataTable().destroy;
                            $("#commissionslist tbody").html("");
                            mhtml="";
                            for (x = 0; x < data.length; x++) {
                                mhtml += "<tr>";
                                mhtml += "<td>"+ data[x]['staff_id'] +"</td><td>"+ data[x]['staff_name'] +"</td><td>"+ data[x]['Total Services'] +"</td>";
                                mhtml += '<td><input class="form-control" name="commissionamount" value="'+ data[x]['Commission'] +'" /></td>';
                                mhtml += '<td><input class="checkbox valid" name="commissioncheck" type="checkbox" checked="checked " /></td>';
                                mhtml += "</tr>";
                            }
                            $("#commissionslist tbody").html(mhtml);
                        }
                    });
                
            }
            
            function updatecommissionselected(){
                
                var month=$("#commissionsmonth :selected").val().split(" ");
                
                
                var TableData;
                TableData = storeCommissionsTblValues();
                TableData = $.toJSON(TableData);
                if (TableData.length > 2) {
                    $.ajax({
                        type: "POST",
                        url: '<?php echo base_url().'staff_controller/updatecommissions'; ?>',
                        data: {
                            commissionsdata:TableData, 
                            month:month[1], 
                            year:$("#commissionsyear :selected").val(),
                            paymentmode:$("#commissionsmode :selected").val(),
                            cash_accounts: $('#commission_cash_accounts').val(),
                            bank_accounts: $('#commission_bank_accounts').val()
                        },
                        success: function(data) {
                            var result = data.split("|");
                            if (result[0] === "success") {
                                toastr.success(result[1]+' Commissions updated!', 'Done!');
                                $("#paycommissions").modal('hide');
                            } else {
                                swal({
                                    title: "Error",
                                    text: result[1],
                                    type: "error",
                                    confirmButtonText: 'OK!'
                                });
                            }
                        }
                    });
                    
                }
            }
            
            
            function storeCommissionsTblValues() {
                var TableData = new Array();
                var x=1;
                $('#commissionslist tr').each(function(row, tr) {
                    if($(tr).find('td:eq(4)').find('input[name=commissioncheck]').prop('checked')==true){
                        TableData[x] = {
                            "staff_id": $(tr).find('td:eq(0)').text()
                            , "staff_name": $(tr).find('td:eq(1)').text()
                            , "payment_amount": $(tr).find('td:eq(3)').find('input[name=commissionamount]').val()
                            , "payment_type": 'Commission'                            
                            , "payment_remarks": 'Monthly Commission'
                        }
                        x++;
                    }
                });
                TableData.shift();  // first row will be empty - so remove
                //console.log(TableData);
                return TableData;
            }
            
    function mode_changed(){
        //console.log('here');
        if($("#salarymode").val()=="cash"){
            $("#salary_check_mode").hide();
            $("#salary_cash_mode").show();
        } else {
            $("#salary_cash_mode").hide();
            $("#salary_check_mode").show();
        }        
    }
    
    function commission_mode_changed(){
        //console.log('here');
        if($("#commissionsmode").val()=="cash"){
            $("#commission_check_mode").hide();
            $("#commission_cash_mode").show();
        } else {
            $("#commission_cash_mode").hide();
            $("#commission_check_mode").show();
        }        
    }
    
    
    function reset_app(){
        
        var staffid = $("#txteditstaffid").val();
        
        $.ajax({
            type: "POST",
            url: '<?php echo base_url().'staff_controller/resetappregistration'; ?>',
            data: {
                staffid: staffid
            },
            success: function(data) {
                var result = data.split("|");
                if (result[0] === "success") {
                    
                   updatefcmHRM();
            
                    toastr.success(result[1]+' Staff updated!', 'Done!');
                    $('#txtfcm').val('');
                } else {
                    swal({
                        title: "Error",
                        text: result[1],
                        type: "error",
                        confirmButtonText: 'OK!'
                    });
                }
            }
        });
        
    }
    
    function updatefcmHRM(){  
        
        
        $.xmlrpc({
            url: '<?php echo $serverurl;?>',
            
            methodName: 'updateFCMToken',
            params: [{"idStaff": $("#txteditstaffid").val(), "fcmid":"", "businessid":<?php echo $this->session->userdata('businessid');?>, "cellNumber":$("#txteditstaffcell").val()}],
            //params:[{"idStaff":"1","fcmid":"","businessid":"1","cellNumber":"0303333333"}],
            success: function (response, status, jqXHR) {
               // console.log(response);
            },
            error: function (jqXHR, status, error) {
               // console.log(status + ' ' +error);
            }
        });
    }
    function updateStaffHRM(){  
        
        
        $.xmlrpc({
            url: '<?php echo $serverurl;?>',
            
            methodName: 'updateFCMToken',
            params: [{"idStaff": $("#txteditstaffid").val(), "fcmid":$("#txtfcm").val(), "businessid":<?php echo $this->session->userdata('businessid');?>, "cellNumber":$("#txteditstaffcell").val(), "fullname":$("#txteditstafffullname").val(), "firstname":$("#txteditstafffirstname").val(), "lastname":$("#txteditstafflastname").val(), "eid":$("#txteditstaffeid").val()}],
            //params:[{"idStaff":"1","fcmid":"","businessid":"1","cellNumber":"0303333333"}],
            success: function (response, status, jqXHR) {
               // console.log(response);
            },
            error: function (jqXHR, status, error) {
               // console.log(status + ' ' +error);
            }
        });
    }
    
    
    function storeOTblValues(){
        var TableData = new Array();
        
         $('#tbladdallowance tr').each(function(row, tr) {
            TableData[row] = {
                "allowance_id": $(tr).find('td:eq(0)').text(),
                "allowance_amount":  $(tr).find('td:eq(2) input[type="number"]').val()
            };
         });
         
        
        return TableData;
    }
    function storeEditTblValues(){
        var TableData = new Array();
        
         $('#tbleditallowance tr').each(function(row, tr) {
            TableData[row] = {
                "allowance_id": $(tr).find('td:eq(0)').text(),
                "allowance_amount":  $(tr).find('td:eq(2) input[type="number"]').val()
            };
         });
         
        
        return TableData;
    }
   
</script>


<!-- Fingerprint -->
<script src="<?php echo base_url(); ?>assets/plugins/fingerprint/js/modernizr-2.6.2.js"></script>
<script type="text/javascript">
    
    var theForm = document.forms['ctl01'];
    if (!theForm) {
        theForm = document.ctl01;
    }
    function __doPostBack(eventTarget, eventArgument) {
        if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
            theForm.__EVENTTARGET.value = eventTarget;
            theForm.__EVENTARGUMENT.value = eventArgument;
            theForm.submit();
        }
    }
    
    function openfingerprintModal(staff_id){
        
        var element = document.getElementById('fingerprint_save_button');
        if (element && element.style.display === '') {
            element.style.display = 'none';  // Reset to default display value (usually block or inline)
        }
        document.getElementById('FPImage').src = "<?php echo base_url() . 'assets/images/staff_fingerprint/'; ?>fingerprint_placeholder.jpg";
        document.getElementById('staff_fingerprint_template_base64').value = "";
        $.ajax({
            type: 'POST',
            url: '<?php echo base_url(); ?>attendance_controller/get_staff_fingerprint',
            data: {id_staff: staff_id},
            dataType: "json",
            cache: false,
            async: true,
            success: function(result){
                console.log(result);
                if(result.staff_fingerprint){
                    document.getElementById('FPImage').src = "data:image/bmp;base64," + result.staff_fingerprint;
                    document.getElementById('staff_fingerprint_template_base64').value = result.staff_fingerprint_template_base64;
                }
                $('#fingerprintModal').modal('show');
                $('#staff_id_for_fingerprint').val(staff_id);
            }
        });
        
    }
    function update_fingerprint(){
        var staffId = document.getElementById('staff_id_for_fingerprint').value;
        var imageSrc = document.getElementById('FPImage').src;
        var staffFingerprintTemplateBase64 = document.getElementById('staff_fingerprint_template_base64').value;
        imageSrc = imageSrc.replace('data:image/bmp;base64,', '');
        $.ajax({
            type: 'POST',
            url: '<?php echo base_url(); ?>attendance_controller/update_staff_fingerprint',
            data: {id_staff: staffId, staff_fingerprint: imageSrc, staff_fingerprint_template_base64: staffFingerprintTemplateBase64},
            success: function(data) {
                console.log(data);
                var result = data.split("|");
                if (result[0] === "success") {
                    $('#fingerprintModal').modal('hide');
                    $('#staff_id_for_fingerprint').val(0);
                    toastr.success(data, 'Staff Fingerprint Updated');
                    //location.reload();
                }
            }
        });
    }
    async function matchFinger() {
        var uri = "https://localhost:8443/SGIFPCapture";
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = async function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                var fpobject = JSON.parse(xmlhttp.responseText);
                var match_found = 0; // Flag to track if a match is found
                var fingerprint_to_be_matched = fpobject.TemplateBase64;
                if (fingerprint_to_be_matched) {
                    $.ajax({
                        type: 'POST',
                        url: '<?php echo base_url(); ?>attendance_controller/get_all_staff_fingerprints',
                        dataType: "json",
                        cache: false,
                        async: true,
                        success: function(result) {
                            var requests = [];  // Array to hold all AJAX promises
                            result.forEach(function(item) {
                                var current_fingerprint = item.staff_fingerprint_template_base64;
                                var staff_id = item.id_staff;
                                var staff = item.staff_firstname;
                                var staffCell = item.staff_cell;
                                var uri = "https://localhost:8443/SGIMatchScore";
                                // Create a Promise for each AJAX request
                                let request = new Promise(function(resolve, reject) {
                                    var xmlhttp = new XMLHttpRequest();
                                    xmlhttp.onreadystatechange = async function () {
                                        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                                            var result = JSON.parse(xmlhttp.responseText);
                                            var idQuality = document.getElementById("quality").value;
                                            if (result.ErrorCode == 0) {
                                                if (result.MatchingScore >= idQuality) {
                                                    match_found = 1;
                                                    var currentDate = new Date();
                                                    var date = `${currentDate.getFullYear()}-${currentDate.getMonth() + 1}-${currentDate.getDate()}`;
                                                    var time = `${currentDate.getHours()}:${currentDate.getMinutes()}:${currentDate.getSeconds()}`;
                                                    const result = await getLocationAndAddress();
                                                    var lat = result.latitude;
                                                    var lng = result.longitude;
                                                    var add = result.address;
                                                    $.ajax({
                                                        type: 'POST',
                                                        url: 'staff_controller/mark_staff_attendance_fingerprint',
                                                        data: {id_staff: staff_id, staff_cell: staffCell, attendance_date: date, attendance_time: time, businessId: <?= $this->session->userdata('businessid'); ?>, latitude: lat, longitude: lng, address: add },
                                                        success: function(data) {
                                                            let parsedData = JSON.parse(data);
                                                            var status = parsedData[0]['status'][0];
                                                            var message = parsedData[0]['message'][0];
                                                            swal({
                                                                  type:status?'success':'error',
                                                                  title: 'Hi '+staff+'!',
                                                                  text: message,
                                                                  timer: 5000
                                                                });
                                                            speak("Hi "+staff+"! "+message)
                                                        }
                                                    });

                                                }
                                            } else {
                                                swal({
                                                      type:"error",
                                                      title: "Error!",
                                                      text: "Error Scanning Fingerprint ErrorCode = " + result.ErrorCode
                                                    });
                                            }
                                            resolve();  // Resolve the promise when the request completes
                                        } else if (xmlhttp.status == 404) {
                                            swal({
                                                  type:"error",
                                                  title: "Error!",
                                                  text: "Error: Not Found"
                                                });
                                            reject("Error: Not Found");
                                        }
                                    };
                                    xmlhttp.onerror = function () {
                                        swal({
                                              type:"error",
                                              title: "Error!",
                                              text: "Error: Network issue"
                                            });
                                        reject("Error: Network issue");
                                    };
                                    var params = "template1=" + encodeURIComponent(fingerprint_to_be_matched);
                                    params += "&template2=" + encodeURIComponent(current_fingerprint);
                                    params += "&licstr=" + encodeURIComponent(secugen_lic);
                                    params += "&templateFormat=" + "ISO";
                                    xmlhttp.open("POST", uri, true);  // Use async true here
                                    xmlhttp.send(params);
                                });
    
                                requests.push(request);  // Add the request promise to the array
                            });
    
                            // After all requests complete, check if a match was found
                            Promise.all(requests).then(function() {
                                if (match_found === 0) {
                                    swal({
                                          type:"warning",
                                          title: "Not Found!",
                                          text: "No match found"
                                        });
                                    speak("No match found");
                                }
                            }).catch(function(error) {
                                console.log(error);  // Handle any errors that might occur in the AJAX requests
                            });
                        }
                    });
                }
            } else if (xmlhttp.status == 404) {
                console.log(xmlhttp.status);
                // failCall(xmlhttp.status)
            }
        };
    
        xmlhttp.onerror = function () {
            console.log(xmlhttp.status);
        };
    
        var params = "Timeout=" + "10000";
        params += "&Quality=" + "50";
        params += "&licstr=" + encodeURIComponent(secugen_lic);
        params += "&templateFormat=" + "ISO";
        xmlhttp.open("POST", uri, true);
        xmlhttp.send(params);
    }
    function speak(text) {
        var msg = new SpeechSynthesisUtterance(text);
        var voices = window.speechSynthesis.getVoices(); // Get list of voices
        msg.voice = voices[0]; // Set voice (optional, you can choose any voice you want)
        window.speechSynthesis.speak(msg);  // Speak the message
    }
    function getLocationAndAddress() {
        return new Promise((resolve, reject) => {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    const latitude = position.coords.latitude;
                    const longitude = position.coords.longitude;
    
                    // Call reverse geocoding to get the address
                    const url = `https://nominatim.openstreetmap.org/reverse?lat=${latitude}&lon=${longitude}&format=json`;
    
                    fetch(url)
                        .then(response => response.json())
                        .then(data => {
                            let address = null;
                            if (data && data.address) {
                                address = `${data.display_name || ''}`;
                            }
    
                            // Resolve with the location and address
                            resolve({
                                latitude: latitude,
                                longitude: longitude,
                                address: address || 'Address not found'
                            });
                        })
                        .catch(error => {
                            // reject('Error fetching address: ' + error);
                            console.log('Error fetching address: ' + error);
                            resolve({
                                latitude: '',
                                longitude: '',
                                address: ''
                            });
                        });
                }, function(error) {
                    // reject('Geolocation error: ' + error.message);
                    console.log('Geolocation error: ' + error.message);
                    resolve({
                            latitude: '',
                            longitude: '',
                            address: ''
                        });
                });
            } else {
                // reject('Geolocation is not supported by this browser.');
                console.log('Geolocation is not supported by this browser.');
                resolve({
                        latitude: '',
                        longitude: '',
                        address: ''
                    });
            }
        });
    }

</script>



<script src="<?php echo base_url(); ?>assets/plugins/fingerprint/js/MsAjaxJs.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/plugins/fingerprint/js/respond.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/plugins/fingerprint/js/WebFormsJs.js" type="text/javascript"></script>
<script type="text/javascript">
    var template_1 = "";
    var template_2 = "";

    function SuccessFunc(result) {
        if (result.ErrorCode == 0) {
            /* 	Display BMP data in image tag
                BMP data is in base 64 format 
            */
            if (result != null && result.BMPBase64.length > 0) {
                document.getElementById('FPImage').src = "data:image/bmp;base64," + result.BMPBase64;
                document.getElementById('staff_fingerprint_template_base64').value = result.TemplateBase64;
                
                var element = document.getElementById('fingerprint_save_button');
                if (element && element.style.display === 'none') {
                    element.style.display = '';  // Reset to default display value (usually block or inline)
                }
            }
            template_1 = result.TemplateBase64;
        }
        else {
            alert("Fingerprint Capture Error Code:  " + result.ErrorCode + ".\nDescription:  " + ErrorCodeToString(result.ErrorCode) + ".");
        }
    }

    function ErrorFunc(status) {
        /* 	
            If you reach here, user is probabaly not running the 
            service. Redirect the user to a page where he can download the
            executable and install it. 
        */
        //alert("Check if SGIBIOSRV is running; status = " + status + ":");
        swal({
            title: "Check if SGIBIOSRV is running; ",
            text: "status = " + status + ":",
            type: "info",
            confirmButtonText: 'OK!'
        });
    }

    function enableFingerPrintScanningButton(){
        var button = document.getElementById('fingerprint_scan_button');
        button.innerHTML = 'Click to Scan';
        button.disabled = false;
    }

    function CallSGIFPGetData(successCall, failCall) {
        console.log('here');
        var button = document.getElementById('fingerprint_scan_button');
        button.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Scanning';
        button.disabled = true;
        var uri = "https://localhost:8443/SGIFPCapture";
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                fpobject = JSON.parse(xmlhttp.responseText);
                successCall(fpobject);
                enableFingerPrintScanningButton();
            }
            else if (xmlhttp.status == 404) {
                failCall(xmlhttp.status);
                enableFingerPrintScanningButton();
            }
        }
        xmlhttp.onerror = function () {
            failCall(xmlhttp.status);
            enableFingerPrintScanningButton();
        }
        var params = "Timeout=" + "10000";
        params += "&Quality=" + "50";
        params += "&licstr=" + encodeURIComponent(secugen_lic);
        params += "&templateFormat=" + "ISO";
        xmlhttp.open("POST", uri, true);
        xmlhttp.send(params);
    }


    function matchScore(succFunction, failFunction) {
        if (template_1 == "" || template_2 == "") {
           // alert("Please scan two fingers to verify!!");
            swal({
                title: "Please scan two fingers to verify!!",
                text: "",
                type: "info",
                confirmButtonText: 'OK!'
            });
            
            return;
        }
        var uri = "https://localhost:8443/SGIMatchScore";

        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                fpobject = JSON.parse(xmlhttp.responseText);
                succFunction(fpobject);
            }
            else if (xmlhttp.status == 404) {
                failFunction(xmlhttp.status)
            }
        }

        xmlhttp.onerror = function () {
            failFunction(xmlhttp.status);
        }
        var params = "template1=" + encodeURIComponent(template_1);
        params += "&template2=" + encodeURIComponent(template_2);
        params += "&licstr=" + encodeURIComponent(secugen_lic);
        params += "&templateFormat=" + "ISO";
        xmlhttp.open("POST", uri, false);
        xmlhttp.send(params);
    }

    function succMatch(result) {
        var idQuality = document.getElementById("quality").value;
        if (result.ErrorCode == 0) {
            if (result.MatchingScore >= idQuality)
                //alert("MATCHED ! (" + result.MatchingScore + ")");
                swal({
                    title: "MATHED !",
                    text: result.MatchingScore,
                    type: "info",
                    confirmButtonText: 'OK!'
                });
            
            else
               // alert("NOT MATCHED ! (" + result.MatchingScore + ")");
                swal({
                    title: "NOT MATHED !",
                    text: result.MatchingScore,
                    type: "info",
                    confirmButtonText: 'OK!'
                });
        }
        else {
           // alert("Error Scanning Fingerprint ErrorCode = " + result.ErrorCode);
            swal({
                title: "ERROR !",
                text: result.ErrorCode,
                type: "error",
                confirmButtonText: 'OK!'
            });
        }
    }

    function failureFunc(error) {
        alert ("On Match Process, failure has been called");
    }
</script>

<script type="text/javascript">
    // nice global area, so that only 1 location, contains this information
    // var secugen_lic = "hE/78I5oOUJnm5fa5zDDRrEJb5tdqU71AVe+/Jc2RK0=";   // webapi.secugen.com
    var secugen_lic = "";

    function ErrorCodeToString(ErrorCode) {
        var Description;
        switch (ErrorCode) {
            // 0 - 999 - Comes from SgFplib.h
            // 1,000 - 9,999 - SGIBioSrv errors 
            // 10,000 - 99,999 license errors
            case 51:
                Description = "System file load failure";
                break;
            case 52:
                Description = "Sensor chip initialization failed";
                break;
            case 53:
                Description = "Device not found";
                break;
            case 54:
                Description = "Fingerprint image capture timeout";
                break;
            case 55:
                Description = "No device available";
                break;
            case 56:
                Description = "Driver load failed";
                break;
            case 57:
                Description = "Wrong Image";
                break;
            case 58:
                Description = "Lack of bandwidth";
                break;
            case 59:
                Description = "Device Busy";
                break;
            case 60:
                Description = "Cannot get serial number of the device";
                break;
            case 61:
                Description = "Unsupported device";
                break;
            case 63:
                Description = "SgiBioSrv didn't start; Try image capture again";
                break;
            default:
                Description = "Unknown error code or Update code to reflect latest result";
                break;
        }
        return Description;
    }

</script>
<!-- Fingerprint End-->



<script src="assets/plugins/switchery/switchery.min.js"></script>