<div class="container-fluid mt-5 mb-5">
    <div class="card bg-light-transparent">  
        <div class="card-header bg-white">
            <h5><?php //echo $title ?> My OT Submission for <?php echo date("F Y",mktime(0,0,0,  $rsOt['month'],1,$rsOt['year'])); ?> </h5>
            <a href="<?php echo base_url('hr/overtime/yearlist')?>" class="btn btn-outline-dark btn-sm" title="Back to My OT List"  >
                <i class="fa fa-angle-double-left"></i> Back to My OT Submission List
            </a>
            <?php 
                $editable = true;
			 if(!empty($_SESSION['user']) 
				&& $_SESSION['user']['id'] == $rsOt['peopleID']
				&& $rsOt['claim_status']==0
				//&& ((date('d') <= 7 && $rsOt['month'] == date('m')) || (date('d') >= 15 && $rsOt['month'] == date('m') + 1))
                ){	?>
                    <button type="button" href="" class="btn btn-outline-dark btn-sm" title="Add New OT" data-toggle="modal" data-target="#add_ot" >
                        <i class="fa fa-plus"></i> Add New OT
                    </button>
                <?php } else { 
                    $editable = false;
                    ?> 
                    <button type="button" href="" class="btn btn-outline-dark btn-sm" title="Add New OT" data-toggle="modal" data-target="#add_ot" disabled>
                        <i class="fa fa-plus"></i> Add New OT
                    </button><?php } ?>
            <!-- <a href="<?php //echo base_url('hr/movement/list_report')?>" target="_blank" class="btn btn-outline-dark btn-sm" title="Print My OT Submission">
                <i class="fa fa-print"></i> Print
            </a> --> 
            <small style="color: red;"><b>*NOTES </b></small><small>Add New OT will be disabled every 8th-15th every month.</small><br>
        </div>

        <div class="tab-content">
            <div class="tab-pane fade active show" id="tableView" role="tabpanel" aria-labelledby="nav-table-tab">
                <div class="card-body">
                    <div class="card text-white bg-dark">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-12 col-md-6">
                                    <div class="row">
                                        <label class="col-12 control-label" for="name" align="left">Name :</label>
                                        <div class="col-12">
                                            <input type="text" name="name" id="name" class="form-control" value="<?php echo $name ?>" readonly/>
                                            <input type="hidden" name="user_id" id="user_id" value="<?php echo $_SESSION['user']['id']; ?>">
                                        </div>
                                    </div>
                                    <div class="row">
                                        <label class="col-6 control-label" for="dept_name" >IC No:</label>
                                        <label class="col-6 control-label" for="dept_name" >Employee ID:</label>
                                        <div class="col-6">
                                            <input type="text" name="dept_name" id="dept_name" class="form-control" value="<?php echo $ic_no ?>" readonly/>
                                        </div>
                                        <div class="col-6">
                                            <input type="text" name="dept_name" id="dept_name" class="form-control" value="<?php echo $staff_id ?>" readonly/>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-12 col-md-6">
                                    <div class="row">
                                        <label class="col-12 control-label" for="name" align="left">Department :</label>
                                        <div class="col-12">
                                            <input type="text" name="name" id="name" class="form-control" value="<?php echo $department_name ?>" readonly/>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <label class="col-12 control-label" for="dept_name" >Designation:</label>
                                        <div class="col-12">
                                            <input type="text" name="dept_name" id="dept_name" class="form-control" value="<?php echo $position_name ?>" readonly/>
                                        </div>
                                    </div>
                                </div>
                            </div>  
                        </div>
                    </div>
                    <div class="card no-shadow">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-bordered p-0 m-0" width="100%" id="OTDetailList">
                                    <thead>
                                        <th class="sorting" tabindex="0" aria-controls="table_contact" rowspan="1" colspan="1" aria-label="#: activate to sort column ascending" style="width: 0px;">
                                            #
                                        </th>
                                        <th class="sorting" tabindex="0" aria-controls="table_contact" rowspan="1" colspan="1" aria-label="Company Code/ Cost Centre: activate to sort column ascending" style="width: 0px;">
                                            Date
                                        </th>
                                        <th class="sorting" tabindex="0" aria-controls="table_contact" rowspan="1" colspan="1" aria-label="Salary/ Wage Month: activate to sort column ascending" style="width: 0px;">
                                            Client
                                        </th>
                                        <th class="sorting" tabindex="0" aria-controls="table_contact" rowspan="1" colspan="1" aria-label="Employee Total Upload: activate to sort column ascending" style="width: 0px;">
                                            Task
                                        </th>
                                        <th class="sorting" tabindex="0" aria-controls="table_contact" rowspan="1" colspan="1" aria-label="Employee Total Upload: activate to sort column ascending" style="width: 0px;">
                                            Start Time
                                        </th>
                                        <th class="sorting" tabindex="0" aria-controls="table_contact" rowspan="1" colspan="1" aria-label="Employee Total Upload: activate to sort column ascending" style="width: 0px;">
                                            End Time
                                        </th>
                                        <th class="sorting" tabindex="0" aria-controls="table_contact" rowspan="1" colspan="1" aria-label="Employee Total Upload: activate to sort column ascending" style="width: 0px;">
                                            Break (minutes)
                                        </th>
                                        <th class="sorting" tabindex="0" aria-controls="table_contact" rowspan="1" colspan="1" aria-label="Employee Total Upload: activate to sort column ascending" style="width: 0px;">
                                            Total Hours
                                        </th>
                                        <th class="sorting" tabindex="0" aria-controls="table_contact" rowspan="1" colspan="1" aria-label="Employee Total Upload: activate to sort column ascending" style="width: 0px;">
                                            Day Type
                                        </th>
                                        <th class="sorting" tabindex="0" aria-controls="table_contact" rowspan="1" colspan="1" aria-label="Employee Total Upload: activate to sort column ascending" style="width: 0px;">
                                            Supervisor
                                        </th>
                                        <th class="sorting" tabindex="0" aria-controls="table_contact" rowspan="1" colspan="1" aria-label="Employee Total Upload: activate to sort column ascending" style="width: 0px;">
                                            Status / Action <small style="color: red;">*Approved OT are not editable.</small>
                                        </th>         
                                    </thead>    
                                    <tbody>
                                        <?php if (!empty($otLists)): 
                                            $totHoursApplied = 0;
                                            $normalDay = 0; 
                                            $restDay = 0; 
                                            $publicHoliday = 0;
                                            $weekend = 0;
                                            $weekdays = 0; ?>
                                            <?php foreach ($otLists as $key => $ot): ?>       
                                            <tr>
                                                <td><?php echo $key+1;?></td>
                                                <td><?php echo date('d/m/Y',strtotime($ot['otDate']));?></td>
                                                <td><?php if($ot['clientID'] > 0 ){ echo $ot['clientName']; }else{ echo 'Others';};?></td>
                                                <td><?php echo $ot['task']; ?></td>                                          
                                                <td><?php echo date("h:i A", strtotime($ot['startTime']));?></td>
                                                <td><?php echo date("h:i A", strtotime($ot['endTime']));?></td>
                                                <td><?php echo $ot['refreshment'];?></td>
                                                <td><?php echo $ot['totalHoursApplied'];?></td>
                                                <td><?php 
                                                    if($ot['dayType'] == 1){
                                                        echo 'Normal Day';
                                                    }else if($ot['dayType'] == 2){
                                                        echo 'Rest Day';
                                                    }else if($ot['dayType'] == 3){
                                                        echo 'Public Holiday';
                                                    }else if($ot['dayType'] == 4){
                                                        echo 'Weekend';
                                                    }else if($ot['dayType'] == 5){
                                                        echo 'Weekdays';
                                                    }
                                                 ?></td>
                                                <td><?php echo $ot['svName'];?> <br><small><b> - <?php echo $ot['svDeptName'];?></b></small></td>
                                                <td class="" otDetailID="<?php echo $ot['ID']; ?>">
                                                    <?php if($ot['status'] == 0) { ?>
                                                        <span class="badge badge-warning text-white">Pending</span><br>
                                                        <small><i><b>*Remarks : </b><?php echo $ot['remarks'];?></i><br></small>
                                                    <?php } else if($ot['status'] == 1) { ?>
                                                        <span class="badge badge-success text-white">Approved</span><br>
                                                        <small><i><b>*Remarks : </b><?php echo $ot['remarks'];?></i><br></small>
                                                        <small><i><b>*Approved by : </b><?php echo $ot['status_by_name'];?></i><br></small>
                                                    <?php }else { ?>
                                                        <span class="badge badge-danger text-white">Rejected</span><br>
                                                        <small><i><b>*Remarks : </b><?php echo $ot['remarks'];?></i><br></small>
                                                        <small><i><b>*Rejected by : </b><?php echo $ot['status_by_name'];?></i><br></small>
                                                    <?php } 
													if($ot['status'] == 0 && $editable == true) { ?>
                                                            <div class="btn-group">
                                                                <a href="#" class="btn btn-info btn-sm" data-tooltip="tooltip" data-placement="bottom" data-trigger="hover" data-original-title="Edit OT" data-toggle="modal" data-target="#edit_ot" data-json="<?php echo base64_encode(json_encode($ot));?>" onclick="fillModal(this);" ><i class="fas fa-edit"></i></a>
                                                                <button id="deleteButton" type="button" class="btn btn-danger btn-sm" onclick="deleteData(<?php echo $ot['ID']; ?>);" data-tooltip="tooltip" data-placement="bottom" data-trigger="hover" data-original-title="Delete OT">
                                                                    <i class="fas fa-trash-alt"></i></button>
                                                            </div>
													<?php } ?>
                                                </td>                                                 
                                            </tr> 
                                            <?php 
                                                if($ot['dayType']){
                                                    if($ot['dayType'] == 1){
                                                        $normalDay++;
                                                    }else if($ot['dayType'] == 2){
                                                        $restDay++;
                                                    }else if($ot['dayType'] == 3){
                                                        $publicHoliday++;
                                                    }else if($ot['dayType'] == 4){
                                                        $weekend++;
                                                    }else if($ot['dayType'] == 5){
                                                        $weekdays++;
                                                    }
                                                }
                                            ?>
                                            <?php endforeach ?>
                                        <?php endif ?>
                                    </tbody> 
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>   

        <div class="card no-shadow">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered">
                        <h5>OT Summary for <?php echo date("F Y",mktime(0,0,0,  $rsOt['month'],1,$rsOt['year'])); ?></h5>
                        <thead>
                            <th></th>
                            <th class="text-center">OT Applied (Hours)</th>
                            <th class="text-center">OT Approved (Hours)</th>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Total OT</td>
                                <td class="text-center"><input type="hidden" value="<?php echo $rsOt['totalHoursApplied']; ?>" id="totalOT"><?php echo $rsOt['totalHoursApplied']; ?></td>
                                <td class="text-center"><?php echo $otHoursApproved['totalHoursApproved']; ?></td>
                            </tr>
                        </tbody>
                        <tfoot>
                                <tr>
                                    <td colspan=""> 
                                        Weekend : 
                                    </td>
                                    <td colspan="2" class="text-center"><?php if(!empty($weekend)){ echo $weekend; }else{ echo "0"; } ?></td>
                                </tr>
                                <tr>
                                    <td colspan=""> 
                                        Weekdays :
                                    </td>
                                    <td colspan="2" class="text-center"><?php if(!empty($weekdays)){ echo $weekdays; }else{ echo "0"; } ?></td>
                                </tr>
                            </tfoot>
                    </table>
                </div>
            </div>
        </div>   
    </div>
</div>

<!-- Modal -->

<div class="modal fade" id="add_ot" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLongTitle">Add New OT</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post" action="<?php echo base_url('hr/overtime/addOvertimeDetail') ?>">
                <div class="modal-body">
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="Date">Date</label>
                        </div>
                        <div class="col">
                            <input type="text" name="DateNew" class="form-control OTdate" id="DateNew" placeholder="Enter Date" autocomplete="off" required onchange="CheckExistingDate()">
                            <input type="hidden" name="otID" class="form-control" id="otID" value="<?php echo $rsOt['ID'] ?>">
                            <input type="hidden" name="otMonth" class="form-control" id="otMonth" value="<?php echo $rsOt['month'] ?>">
                        </div>
                    </div>  
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="Day Type">Day Type</label>
                        </div>
                        <div class="col">
                            <select name="day_type" id="day_type" class="form-control" onchange="changeStartTime()" required>
                                <option value="" selected>Choose day type</option>
                                <option value="4">Weekend</option>
                                <option value="5">Weekdays</option>
                            </select>
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="client">Client</label>
                        </div>
                        <div class="col">
                            <select class="form-control select" name="client" id="client" placeholder="Select Client" required>
                                <option value="">Select Client</option>
                                <?php if(!empty($clients)) foreach ($clients as $row): ?>
                                    <option value="<?php echo $row->customer_id;?>"><?php echo $row->name;?></option>

                                <?php endforeach ?>
                                <option value="-1">Others</option>                                                        
                            </select>
                        </div> 
                    </div>
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="task">Task</label>
                        </div>
                        <div class="col">
                            <textarea rows="3" name="task" id="task" class="form-control" placeholder="Enter Task description"></textarea>
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="start_time">Start Time</label>
                        </div>
                        <div class="col-lg-4">
                            <input required data-parsley-error-message="Start time is required." type="text" class="timepickerFormat form-control" name="start_time" id="start_time" placeholder="Enter start time" onchange="CheckExistingDate()">
                        </div>
                        <div class="col-lg-2">
                            <label for="end_time">End Time</label>
                        </div>
                        <div class="col">
                            <input required data-parsley-error-message="Start time is required." type="text" onchange="calcTotalHour()" class="timepickerFormat form-control" name="end_time" id="end_time" placeholder="Enter end time">
                        </div>
                    </div>  
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="refreshment">Break Time</label>
                        </div>
                        <div class="col-lg-4">
                           <input type="text" onkeyup="calcTotalHour()" class="form-control" id="refreshment" name="refreshment" placeholder="Enter Break Time(minutes)">
                        </div>
                        <div class="col-lg-2">
                            <label for="total_deducted">Total Deducted</label>
                        </div>
                        <div class="col">
                            <input type="text" onchange="" class="form-control" name="total_deducted" id="total_deducted" placeholder="0" readonly>
                        </div>
                        <div class="col">
                            Hours
                        </div>
                    </div>  
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="total_hour">Total Hours</label>
                        </div>
                        <div class="col-lg-4">
                            <input type="number" class="form-control" name="total_hour" id="total_hour" placeholder="Hours" readonly>
                        </div>
                        <div class="col">
                            <small style="color: red;"><b>*NOTES </b></small>
                            <small>Weekdays OT only eligable maximum 3 hours. Weekend OT only eligable maximum 6 hours. </small>
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="crossDept">Cross-department Job?</label>
                        </div>
                        <div class="col-lg-4">
                            <select name="crossDept" id="crossDept" class="form-control" onchange="changeCrossJob(this)">
                                <option value="0">No</option>
                                <option value="1">Yes</option>
                            </select>
                        </div>
                        <div class="col">
                            <small style="color: red;"><b>*NOTES </b></small>
                            <small>Kindly select supervisor for cross-department job <b>ONLY</b>. OT will be approved by supervisor selected.</small>
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="supervisorDept">Supervisor Dept.</label>
                        </div>
                        <div class="col">
                            <select class="form-control select" name="supervisorDept" id="supervisorDept" placeholder="Select Supervisor Dept." onchange="changeStaffList(this)" disabled>
                                <option value="0">Select Supervisor Dept.</option>
                                    <?php if(!empty($department)) foreach ($department as $row): ?>
                                        <option value="<?php echo $row['id'];?>"><?php echo $row['name']; ?> [<?php echo $row['branch_name']; ?>]</option>
                                    <?php endforeach ?>                                                      
                            </select>
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="supervisor">Supervisor</label>
                        </div>
                        <div class="col">
                            <select class="form-control select" name="supervisor" id="supervisor" placeholder="Select Supervisor" disabled>
                                <option value="0">Select Supervisor</option>
                                <?php if(!empty($supervisor)) foreach ($supervisor as $row): ?>
                                    <option value="<?php echo $row['id'];?>"><?php echo $row['name'];?></option>
                                <?php endforeach ?>                                                       
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" type="button"  class="btn btn-success btn-sm" style="margin-bottom:15px; width: 200px;"><i class="fa fa-plus"></i> Add</button>
                    <button type="button" class="btn btn-danger btn-sm" style="margin-bottom:15px; width: 200px;" data-dismiss="modal"><i class="fa fa-ban"></i> Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="edit_ot" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLongTitle">Edit OT</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form class="form" id="otForm">
                <div class="modal-body">
                    <input type="hidden" name="otID" id="otID">
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="edit_date">Date</label>
                        </div>
                        <div class="col">
                            <input required data-parsley-error-message="Date is required." type="text" name="edit_date" id="edit_date" class="edit_date form-control" onchange="CheckExistingDateEdit()">
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="Day Type">Day Type</label>
                        </div>
                        <div class="col">
                            <select name="edit_day_type" id="edit_day_type" class="form-control" onchange="changeStartTimeEdit()" required>
                                <option value="" selected>Choose day type</option>
                                <option value="4">Weekend</option>
                                <option value="5">Weekdays</option>
                            </select>
                        </div>
                    </div>  
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="edit_client">Client</label>
                        </div>
                        <div class="col">
                            <select required data-parsley-error-message="Client is required." class="form-control select" name="edit_client" id="edit_client" required>
                                <?php foreach ($clients as $key => $client ): ?>
                                    <option value="<?php echo $client->customer_id;?>"><?php echo $client->name;?></option>
                                <?php endforeach ?> 
                                    <option value="-1">Others</option>                                                          
                            </select>
                        </div> 
                    </div>
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="edit_task">Task</label>
                        </div>
                        <div class="col">
                            <textarea required data-parsley-error-message="Task is required." rows="3" class="form-control" name="edit_task" id="edit_task"></textarea>
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="edit_start_time">Start Time</label>
                        </div>
                        <div class="col-lg-4">
                            <input required data-parsley-error-message="Start time is required." type="text" onchange="CheckExistingDateEdit()" class="timepicker form-control" name="edit_start_time" id="edit_start_time">
                        </div>
                        <div class="col-lg-2">
                            <label for="edit_end_time">End Time</label>
                        </div>
                        <div class="col">
                            <input required data-parsley-error-message="End time is required." type="text" onchange="calcEditTotalHour()" class="timepicker form-control" name="edit_end_time" id="edit_end_time">
                        </div>
                    </div>  
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="edit_refreshment">Break Time</label>
                        </div>
                        <div class="col-lg-4">
                            <input type="text" onkeyup="calcEditTotalHour()" class=" form-control" name="edit_refreshment" id="edit_refreshment" placeholder="Enter refreshment">
                        </div>
                        <div class="col-lg-2">
                            <label for="edit_total_deducted">Total Deducted</label>
                        </div>
                        <div class="col">
                            <input type="text" onchange="" class="form-control" name="edit_total_deducted" id="edit_total_deducted" placeholder="0" readonly>
                        </div>
                        <div class="col">
                            Hours
                        </div>
                    </div>  
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="edit_total_hour"> Total Hours</label>
                        </div>
                        <div class="col-lg-4">
                            <input type="text" class="form-control" name="edit_total_hour" id="edit_total_hour" value="<?php echo $rsOt['totalHoursApplied'] ?>" readonly>
                        </div>
                        <div class="col">
                            <small style="color: red;"><b>*NOTES </b></small>
                            <small>Weekdays OT only eligable maximum 3 hours. Weekend OT only eligable maximum 6 hours. </small>
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="edit_crossDept">Cross-department Job?</label>
                        </div>
                        <div class="col-lg-4">
                            <select name="edit_crossDept" id="edit_crossDept" class="form-control" onchange="changeCrossJobEdit(this)">
                                <option value="0">No</option>
                                <option value="1">Yes</option>
                            </select>
                        </div>
                        <div class="col">
                            <small style="color: red;"><b>*NOTES </b></small>
                            <small>Kindly select supervisor for cross-department job <b>ONLY</b>. OT will be approved by supervisor selected.</small>
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="edit_supervisorDept">Supervisor Dept.</label>
                        </div>
                        <div class="col">
                            <select class="form-control select" name="edit_supervisorDept" id="edit_supervisorDept" placeholder="Select Supervisor Dept." onchange="changeStaffListEdit(this)">
                                <option value="">Select Supervisor Dept.</option>
                                    <?php if(!empty($department)) foreach ($department as $row): ?>
                                        <option value="<?php echo $row['id'];?>"><?php echo $row['name']; ?> [<?php echo $row['branch_name']; ?>]</option>
                                    <?php endforeach ?>                                                      
                            </select>
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-lg-3">
                            <label for="edit_supervisor">Supervisor</label>
                        </div>
                        <div class="col">
                            <select class="form-control select" name="edit_supervisor" id="edit_supervisor" placeholder="Select Supervisor" >
                                <option value="">Select Supervisor</option>
                                <?php if(!empty($supervisor)) foreach ($supervisor as $row): ?>
                                    <option value="<?php echo $row['id'];?>"><?php echo $row['name'];?></option>
                                <?php endforeach ?>    
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" onclick="updateData()" class="btn btn-success btn-sm" style="margin-bottom:15px; width: 200px;"><i class="fa fa-save"></i> Save</button>
                    <button type="button" class="btn btn-danger btn-sm" style="margin-bottom:15px; width: 200px;" data-dismiss="modal"><i class="fa fa-ban"></i> Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal -->

<script>
var token = "<?php echo $_SESSION['token'];?>"; 

var ot_year = <?php echo $rsOt['year']; ?>; 
var ot_month = <?php echo $rsOt['month']; ?>; 
var date = new Date();
var full_start_date = date.setFullYear(ot_year,ot_month-1 , 1);
var full_end_date = date.setFullYear(ot_year,ot_month-1,1);

var start_ot = moment(full_start_date).subtract(2,'months').startOf('month').format('DD-MM-YYYY');
var end_ot = moment(full_end_date).subtract(1,'days').format('DD-MM-YYYY');

$(document).ready(function(){

    $( ".OTdate" ).datepicker({
        uiLibrary: 'bootstrap4',
        format: 'dd-mm-yyyy',
        autoclose: true,
        changeMonth: true, 
        changeYear: true,
        startDate :start_ot,
        endDate:end_ot
    });

    $( ".edit_date" ).datepicker({
        uiLibrary: 'bootstrap4',
        format: 'dd-mm-yyyy',
        autoclose: true,
        changeMonth: true, 
        changeYear: true,
        startDate :start_ot,
        endDate:end_ot
    });

});


function changeStaffList(obj) 
{
    var id = obj.value;

    $.ajax({
        type: "POST",
        url: "<?php echo base_url() ?>hr/Overtime/getStaffByDept",
        data: "dept_id=" + id,
        dataType: "json",
        success: function(content) {

            if (content.status == "success") {

                var items = [];
                items.push('<option>Select Supervisor</option>');
                for (var i = 0; i < content.message.length; i++) {
                    items.push('<option value="' + content.message[i].id + '">'
                            + content.message[i].name + '</option>');
                }
                jQuery("#supervisor").empty();
                jQuery("#supervisor").append(items.join('</br>'));
            } else {
                $("#error").html('<p>' + content.message + '</p>');
            }
        }
    });
    return false;
}

function changeStaffListEdit(obj) 
{
    var id = obj.value;

    $.ajax({
        type: "POST",
        url: "<?php echo base_url() ?>hr/Overtime/getStaffByDept",
        data: "dept_id=" + id,
        dataType: "json",
        success: function(content) {

            if (content.status == "success") {

                var items = [];
                items.push('<option>Select Supervisor</option>');
                for (var i = 0; i < content.message.length; i++) {
                    items.push('<option value="' + content.message[i].id + '">'
                            + content.message[i].name + '</option>');
                }
                jQuery("#edit_supervisor").empty();
                jQuery("#edit_supervisor").append(items.join('</br>'));
            } else {
                $("#error").html('<p>' + content.message + '</p>');
            }
        }
    });
    return false;
}

function changeCrossJob() 
{
    var crossDept = $('#crossDept').val();

    if(crossDept == 0){
        document.getElementById("supervisorDept").disabled = true;
        document.getElementById("supervisor").disabled = true;
        $("#supervisorDept").val(0).change();
        $("#supervisor").val(0).change();
    } else {
        document.getElementById("supervisorDept").disabled = false;
        document.getElementById("supervisor").disabled = false;
    }
}

function changeCrossJobEdit() 
{
    var crossDept = $('#edit_crossDept').val();

    if(crossDept == 0){
        document.getElementById("edit_supervisorDept").disabled = true;
        document.getElementById("edit_supervisor").disabled = true;
        $("#edit_supervisorDept").val(0).change();
        $("#edit_supervisor").val(0).change();
    } else {
        document.getElementById("edit_supervisorDept").disabled = false;
        document.getElementById("edit_supervisor").disabled = false;
    }
}

function checkMealAllowance() 
{
    var totalHours = $('#total_hour').val();
    var dayType    = $('#day_type').val();

    if(dayType == 1 && totalHours >= 4){
        document.getElementById("meal_allowance").disabled = false;
    } else if(dayType == 2 && totalHours >= 8){
        document.getElementById("meal_allowance").disabled = false;
    } else if(dayType == 3 && totalHours >= 8){
        document.getElementById("meal_allowance").disabled = false;
    } else {
        document.getElementById("meal_allowance").disabled = true;
        document.getElementById("meal_allowance").value    = 3;
        $('#meal_allowance_id').val('3');
    }
}

function checkMealAllowanceEdit() 
{
    var totalHours = $('#edit_total_hour').val();
    var dayType    = $('#edit_day_type').val();

    if(dayType == 1 && totalHours >= 4){
        document.getElementById("edit_meal_allowance").disabled = false;
    } else if(dayType == 2 && totalHours >= 8){
        document.getElementById("edit_meal_allowance").disabled = false;
    } else if(dayType == 3 && totalHours >= 8){
        document.getElementById("edit_meal_allowance").disabled = false;
    } else {
        document.getElementById("edit_meal_allowance").disabled = true;
        document.getElementById("edit_meal_allowance").value    = 3;
    }
}

function fillModal(elem) 
{
    var json = JSON.parse(atob($(elem).data('json')));

    var [h, i] = json.startTime.split(":");
    var [H, I] = json.endTime.split(":");
    var ampm = '';
    var AMPM = '';

    changeStartTimeEdit(json.dayType);

    if(h - 12 < 0){
        if(h-12 == -12){
            h = 12;
        }
        ampm = 'am';
    }else if(h - 12 == 0) {
        ampm = 'pm';
    }else if(h - 12 > 0){
        h = h - 12;
        ampm = 'pm';
    }

    if(H - 12 < 0){
        if(H-12 == -12){
            H = 12;
        }
        AMPM = 'am';
    }else if(H - 12 == 0){
        AMPM = 'pm';
    }else if(H - 12 > 0){
        H = H - 12;
        AMPM = 'pm';
    }

    if(json.dayType == 1){
        $('#edit_day_type').val(1);
    }else if(json.dayType == 2){
        $('#edit_day_type').val(2);
    }else if(json.dayType == 3){
        $('#edit_day_type').val(3);
    }else if(json.dayType == 4){
        $('#edit_day_type').val(4);
    }else if(json.dayType == 5){
        $('#edit_day_type').val(5);
    }

    var [yy, mm, dd] = json.otDate.split("-");
    $('#otID').val(json.ID);
    $('#edit_date').val(dd+'-'+mm+'-'+yy);
    $('#edit_client').val(json.clientID).trigger('change');
    $('#edit_crossDept').val(json.crossDept);
    if(json.crossDept == 0){
        document.getElementById("edit_supervisorDept").disabled = true;
        document.getElementById("edit_supervisor").disabled = true;
        $("#edit_supervisorDept").val(0).change();
        $("#edit_supervisor").val(0).change();
    }else{
        $('#edit_supervisorDept').val(json.svDeptID).trigger('change');
        $('#edit_supervisor').val(json.svID).trigger('change');
    }
    $('#edit_task').val(json.task);
    $('#edit_start_time').val(h+ ':' + i + '' + ampm);
    $('#edit_end_time').val(H+ ':' + I + '' + AMPM);
    $('#edit_refreshment').val(json.refreshment);
    $('#edit_total_hour_final').val(json.totalHoursApplied);

    calcTotalHour();
    calcEditTotalHour();
    
}

function calcEditTotalHour()
{
    var day_type = $('#edit_day_type').val();

    var postData = {
        'startTime': $('#edit_start_time').val(),
        'endTime': $('#edit_end_time').val(),
    };

    var refreshment       = $('#edit_refreshment').val(); 

    var timeStart = moment("01/01/2007 " + postData.startTime, "DD/MM/YYYY HH:mma");
    var timeEnd = moment("01/01/2007 " + postData.endTime, "DD/MM/YYYY HH:mma");

    var diff = (timeEnd - timeStart) / 60000; //dividing by seconds and milliseconds

    if(refreshment){ //minus refreshment time calculation.
        var minutes = diff - refreshment;
    } else {
        var minutes = diff;
    }

    var hours = Math.floor( minutes / 60); 
    var minutes = minutes % 60;

    if(minutes < 0){
        var minutesF = minutes * -1;
        if(minutesF < 30){ //roundoff to nearest half hour
            minutesF = '0';
        } else if(minutesF >= 30) {
            minutesF = '5';
        } else{
            alert('Error');
        }
    } else {
        var minutesF = minutes;
        if(minutesF < 30){
            minutesF = '0';
        } else if(minutesF >= 30) {
            minutesF = '5';
        } else{
            alert('Error');
        }
    }

    if(day_type == 4){ //weekend

        var hoursF = hours;

        if(hours >= 6 && minutes > 0){
            var hoursFL = 6;
            var total_deducted = hoursF - 6;
            $('#edit_total_deducted').val(total_deducted);
            $('#edit_total_hour').val(hoursFL + '.' + 0);
        }else if(hours > 6){
            var hoursFL = 6;
            var total_deducted = hoursF - 6;
            $('#edit_total_deducted').val(total_deducted);
            $('#edit_total_hour').val(hoursFL + '.' + 0);

            if(refreshment > 0){
                $('#edit_refreshment').val(refreshment);
            }else{
                $('#edit_refreshment').val('');
            }
        }else if(hours < 0){ //more than 12 hours calculation.
            var hoursF = hours + 12 + 12;
            if(hoursF > 6){ 
                var hoursFL = 6;
                var total_deducted = hoursF - 6;
                $('#edit_total_deducted').val(total_deducted);
                $('#edit_total_hour').val(hoursFL);

            }else{
                var hoursFL = hoursF;
                $('#edit_total_deducted').val(0);
                $('#edit_total_hour').val(hoursFL + '.' + minutesF);
            }
            //$('#total_hour').val(hoursF + '.' + minutesF);
        }else{
            $('#edit_total_deducted').val(0);
            $('#edit_total_hour').val(hoursF + '.' + minutesF);

            if(refreshment > 0){
                $('#edit_refreshment').val(refreshment);
            }else{
                $('#edit_refreshment').val('');
            }
        }

    }else if(day_type == 5){ //weekdays

        var hoursFL = hours;

        if(hours >= 3 && minutes > 0){
            var total_deducted = 30;
            var hoursFL = 3;
            $('#edit_refreshment').val(total_deducted);
            $('#edit_total_hour').val(hoursFL + '.' + 0)
            document.getElementById("edit_refreshment").readOnly = true;
        }else if(hours == 3 && minutes > 0){
            $('#edit_total_hour').val(hours + '.' + 0);
            $('#edit_refreshment').val(refreshment);
        }else{
            $('#edit_total_deducted').val(0);
            $('#edit_total_hour').val(hoursFL + '.' + minutesF);

            if(refreshment > 0){
                $('#edit_refreshment').val(refreshment);
            }else{
                $('#edit_refreshment').val('');
            }
            
            document.getElementById("edit_refreshment").readOnly = false;
        }

    }else{
        if(hours < 0){ //more than 12 hours calculation.
            var hoursF = hours + 12 + 12;
            if(hoursF > 8){ //deduct 1 hour for OT more than 8 hours.
                var hoursFL = hoursF - 1;
                $('#edit_total_deducted').val(1);
            }else{
                var hoursFL = hoursF;
                $('#edit_total_deducted').val(0);
            }
        } else {
            var hoursF = hours;
            if(hoursF > 8){
                var hoursFL = hoursF - 1;
                $('#edit_total_deducted').val(1);
            }else{
                var hoursFL = hoursF;
                $('#edit_total_deducted').val(0);
            }
        }
    }

}

function calcTotalHour()
{
    var day_type = $('#day_type').val();

    var postData = {
        'startTime': $('#start_time').val(),
        'endTime': $('#end_time').val(),
    };

    var refreshment = $('#refreshment').val(); 

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '<?php echo base_url(); ?>hr/Overtime/convertTimestamp',
        data: postData,
        success: function(data) {

            var calculateHours = data.calculateHours;

            var timeStart = new Date("01/01/2007 " + calculateHours['startTime']);
            var timeEnd = new Date("01/01/2007 " + calculateHours['endTime']);

            var diff = (timeEnd - timeStart) / 60000; //dividing by seconds and milliseconds

            if(refreshment){ //minus refreshment time calculation.
                var minutes = diff - refreshment;
            } else {
                var minutes = diff;
            }

            var hours = Math.floor( minutes / 60); 
            var minutes = minutes % 60;

            if(minutes < 0){
                var minutesF = minutes * -1;
                if(minutesF < 30){ //roundoff to nearest half hour
                    minutesF = '0';
                } else if(minutesF >= 30) {
                    minutesF = '5';
                } else{
                    alert('Error');
                }
            } else {
                var minutesF = minutes;
                if(minutesF < 30){
                    minutesF = '0';
                } else if(minutesF >= 30) {
                    minutesF = '5';
                } else{
                    alert('Error');
                }
            }

            if(day_type == 4){ //weekend

                var hoursF = hours;

                if(hours >= 6 && minutes > 0){
                    var hoursFL = 6;
                    var total_deducted = hoursF - 6;
                    $('#total_deducted').val(total_deducted);
                    $('#total_hour').val(hoursFL + '.' + 0);
                }else if(hours > 6){
                    var hoursFL = 6;
                    var total_deducted = hoursF - 6;
                    $('#total_deducted').val(total_deducted);
                    $('#total_hour').val(hoursFL + '.' + 0);

                    if(refreshment > 0){
                        $('#refreshment').val(refreshment);
                    }else{
                        $('#refreshment').val('');
                    }
                }else if(hours < 0){ //more than 12 hours calculation.
                    var hoursF = hours + 12 + 12;
                    if(hoursF > 6){ 
                        var hoursFL = 6;
                        var total_deducted = hoursF - 6;
                        $('#total_deducted').val(total_deducted);
                        $('#total_hour').val(hoursFL);

                    }else{
                        var hoursFL = hoursF;
                        $('#total_deducted').val(0);
                        $('#total_hour').val(hoursFL + '.' + minutesF);
                    }
                    //$('#total_hour').val(hoursF + '.' + minutesF);
                }else{
                    $('#total_deducted').val(0);
                    $('#total_hour').val(hoursF + '.' + minutesF);

                    if(refreshment > 0){
                        $('#refreshment').val(refreshment);
                    }else{
                        $('#refreshment').val('');
                    }
                }

            }else if(day_type == 5){ //weekdays

                var hoursFL = hours;

                if(hours >= 3 && minutes > 0){
                    var total_deducted = 30;
                    var hoursFL = 3;
                    $('#refreshment').val(total_deducted);
                    $('#total_hour').val(hoursFL + '.' + 0);
                    document.getElementById("refreshment").readOnly = true;
                }else if(hours == 3 && minutes > 0){
                    $('#total_hour').val(hours + '.' + 0);
                    $('#refreshment').val(refreshment);
                }else{
                    $('#total_deducted').val(0);
                    $('#total_hour').val(hoursFL + '.' + minutesF);

                    if(refreshment > 0){
                        $('#refreshment').val(refreshment);
                    }else{
                        $('#refreshment').val('');
                    }
                    
                    document.getElementById("refreshment").readOnly = false;
                }

            }else{
                if(hours < 0){ //more than 12 hours calculation.
                    var hoursF = hours + 12 + 12;
                    if(hoursF > 8){ //deduct 1 hour for OT more than 8 hours.
                        var hoursFL = hoursF - 1;
                        $('#total_deducted').val(1);
                    }else{
                        var hoursFL = hoursF;
                        $('#total_deducted').val(0);
                    }
                } else {
                    var hoursF = hours;
                    if(hoursF > 8){
                        var hoursFL = hoursF - 1;
                        $('#total_deducted').val(1);
                    }else{
                        var hoursFL = hoursF;
                        $('#total_deducted').val(0);
                    }
                }
            }

        }
    });
}

function updateData() 
{
    validateForm("#otForm", "Save changes to this OT?", function() {
        $.ajax({
            url:'<?php echo base_url('hr/overtime/editOvertime') ?>',
            data: {

                otID : $('#otID').val(),
                otDate : $('#edit_date').val(),
                dayType : $('#edit_day_type').val(),
                crossDept : $('#edit_crossDept').val(),
                clientID : $('#edit_client').val(),
                supervisor : $('#edit_supervisor').val(),
                supervisorDept : $('#edit_supervisorDept').val(),
                task : $('#edit_task').val(),
                mealAllowance : $('#edit_meal_allowance').val(),
                startTime : $('#edit_start_time').val(),
                endTime : $('#edit_end_time').val(),
                refreshment : $('#edit_refreshment').val(),
                totalHoursApplied : $('#edit_total_hour').val(),
            },
            type: 'post',
            dataType: 'json',
            success: (data) => {
                if(data.status == "Success") {

                localStorage.setItem("status", data.status);
                localStorage.setItem("msg", data.msg);

                location.reload();
                }
            }
        });
    });
}

function deleteData(ID) 
{
    validateForm("#deleteButton", "Delete this OT?", function() {
        $.ajax({
            url:'<?php echo base_url('hr/overtime/deleteOvertime') ?>',
            data: {
                otID : ID,
            },
            type: 'post',
            dataType: 'json',
            success: (data) => {
                if(data.status == "Success") {

                localStorage.setItem("status", data.status);
                localStorage.setItem("msg", data.msg);

                location.reload();
                }
            }
        });
    });
}

function CheckExistingDate() 
{

    var date   = moment($('#DateNew').val(), 'DD/MM/YYYY');
    var otDate = moment(date).format("YYYY-MM-DD");

    var startTime = moment($('#start_time').val(), "h:mm A").format("HH:mm:ss");
    var endTime   = moment($('#end_time').val(), "h:mm A").format("HH:mm:ss");

    var postData = {
        'peopleID': $('#user_id').val()
    };

    $.ajax({
        type: "POST",
        dataType: "json",
        url: "<?php echo base_url(); ?>hr/Overtime/getOTDate",
        data: postData,
        success: function(data) {
            //console.log(data);
            if ($.trim(data.status) == "success") 
            {
                $.each(data.OT_date, function(i, v)
                {
                    if (otDate == v.otDate) {

                        if (startTime != null) {
                            if ((startTime >= v.startTime) && (startTime <= v.endTime)) {
                                alert("The date and time you choose already in the OT application list. Please choose another date/time.A");
                                $('#start_time').val(''); 
                            } else {
                                calcTotalHour();
                            }
                        } 

                        if (endTime != null) {
                            if ((endTime <= v.endTime) && (endTime >= v.startTime)) {
                                alert("The date and time you choose already in the OT application list. Please choose another date/time.B");
                                $('#end_time').val(''); 
                            } else {
                                calcTotalHour();
                            }
                        }

                    } else {
                        calcTotalHour();
                    }
                });
            }
        }
    });

}

function CheckExistingDateEdit() 
{

    var dateValue = $('#edit_date').val();
    var date   = moment($('#edit_date').val(), 'DD/MM/YYYY');
    var otDate = moment(date).format("YYYY-MM-DD");

    var startTimeValue = $('#edit_start_time').val();
    var startTime = moment($('#edit_start_time').val(), "h:mm A").format("HH:mm:ss");
    var endTime   = moment($('#edit_end_time').val(), "h:mm A").format("HH:mm:ss");

    // if(endTime != null){
    //     calcEditTotalHour();
    // }

    var postData = {
        'peopleID': $('#user_id').val()
    }

    $.ajax({
        type: "POST",
        dataType: "json",
        url: "<?php echo base_url(); ?>hr/Overtime/getOTDate",
        data: postData,
        success: function(data) {
            if ($.trim(data.status) == "success") 
            {
                $.each(data.OT_date, function(i, v)
                  {
                    // if (otDate == v.otDate)
                    // {
                    //     if(startTime == v.startTime)
                    //     {
                    //         alert("The date and time you choose already in the OT application list. Please choose another date/time.");
                    
                    //         $('#edit_ot').modal('hide');

                    //     } else {
                    //         calcEditTotalHour();
                    //     }
                    // }

                    if (otDate == v.otDate) {

                        if (startTime != null) {
                            if ((startTime >= v.startTime) && (startTime <= v.endTime)) {
                                alert("The date and time you choose already in the OT application list. Please choose another date/time.A");
                                $('#edit_start_time').val(''); 
                                return false;
                            } else {
                                calcEditTotalHour();
                            }
                        } 

                        if (endTime != null) {
                            if ((endTime <= v.endTime) && (endTime >= v.startTime)) {
                                alert("The date and time you choose already in the OT application list. Please choose another date/time.B");
                                $('#edit_end_time').val(''); 
                                return false;
                            } else {
                                calcEditTotalHour();
                            }
                        }

                    } else {
                        calcEditTotalHour();
                    }
                });
            }
        }
    });

}

function submitOTDetail() 
{

    var oTable = $('#OTDetailList').dataTable();
    var aTrs = oTable.fnGetNodes();

    for (var i=0; i<aTrs.length; i++ ){

        var postData = {
            otDetailID : $('td:nth-child(11)',aTrs[i]).attr('otDetailID')
        }

        $.ajax({
            type: "POST",
            url: "<?php echo base_url(); ?>hr/Overtime/submitOTDetail",
            data: postData,
            dataType:'json',
            success: function(data){
                if(data.status = 'success'){
                    return;
                }
            }
        });
    }
}

function submitOT(otID) 
{

    validateForm("#submit_ot", "Submit this OT?", function() {

        submitOTDetail();

        var postData = {
            'otID' : otID,
            'totalConvertToLeave' : $('#convertAL').val(),
            'totalClaim' : $('#balanceOT').val()
        }

        $.ajax({
            type: "POST",
            dataType: "json",
            url: "<?php echo base_url(); ?>hr/Overtime/submitOT",
            data: postData,
            success: function(data) {
                if ($.trim(data.status) == "success") 
                {
                    localStorage.setItem("status", data.status);
                    localStorage.setItem("msg", data.msg);

                    location.reload();
                }
            }
        });
    });
}

function refreshBalance() 
{
    var totalOT   = $('#totalOT').val();
    var convertAL = $('#convertAL').val();
    var balanceOT = totalOT - convertAL;

    $('#balanceOT').val(balanceOT);
}

function FinalTotalHour()
{

    var total_hour  = $('#total_hour').val();
    var dayType     = $('#day_type').val();

    if(dayType == 1){
        var dayVal = 1.5;
    }else if(dayType == 2){
        var dayVal = 2;
    }else if(dayType == 3){
        var dayVal = 3;
    }else{
        var dayVal = 0;
    }

    $('#total_hour_final').val(total_hour * dayVal);

}

function editFinalTotalHour()
{

    var total_hour  = $('#edit_total_hour').val();
    var dayType     = $('#edit_day_type').val();

    if(dayType == 1){
        var dayVal = 1.5;
    }else if(dayType == 2){
        var dayVal = 2;
    }else if(dayType == 3){
        var dayVal = 3;
    }else{
        var dayVal = 0;
    }

    $('#edit_total_hour_final').val(total_hour * dayVal);

}

function changeStartTime()
{
    var day_type = $('#day_type').val();

    if(day_type == 5){ //weekdays

        $('#start_time').val('').timepicker('remove').timepicker();
        $('#end_time').val('').timepicker('remove').timepicker();

        $('#start_time').timepicker({
            'minTime': '6:00pm',
            'maxTime': '9:30pm', 
        });

        $('#end_time').timepicker({
            'minTime': '6:00pm',
            'maxTime': '9:30pm', 
        });

    }else{ //weekend
        $('#start_time').val('').timepicker('remove').timepicker();
        $('#end_time').val('').timepicker('remove').timepicker();
    }
}

function changeStartTimeEdit(day_type_id)
{

    var day_type1 = $('#edit_day_type').val();

    if(day_type1 === ''){
        day_type = day_type_id;
    }else{
        day_type = day_type1;
    }

    //console.log(day_type);

    if(day_type == 5){ //weekdays

        $('#edit_start_time').val('').timepicker('remove').timepicker();
        $('#edit_end_time').val('').timepicker('remove').timepicker();
        $('#edit_refreshment').val('');
        $('#edit_total_hour').val('');
        $('#edit_total_deducted').val('');

        $('#edit_start_time').timepicker({
            'minTime': '6:00pm',
            'maxTime': '9:30pm', 
        });

        $('#edit_end_time').timepicker({
            'minTime': '6:00pm',
            'maxTime': '9:30pm', 
        });

    }else{ //weekend
        $('#edit_start_time').val('').timepicker('remove').timepicker();
        $('#edit_end_time').val('').timepicker('remove').timepicker();
        $('#edit_refreshment').val('');
        $('#edit_total_hour').val('');
        $('#edit_total_deducted').val('');

         $('#edit_start_time').timepicker({
            'minTime': '12:00am',
            'maxTime': '11:30pm', 
        });

        $('#edit_end_time').timepicker({
            'minTime': '12:00am',
            'maxTime': '11:30pm',
        });
    }
}

</script> 