<div class="container mt-5 mb-5">
    <div class="card bg-light-transparent">  
            <div class="card-header bg-white">
                <div class="float-left">
                    <h5>My OT Submission List 
                        <span data-trigger="hover" data-tooltip="tooltip" title="" data-original-title="Overtime claim applicable for employee with grade 7 to 26 ONLY." >
                            <i class="fas fa-info-circle"></i> 
                        </span>
                    </h5>

                    <?php //echo $_SESSION['user']['grade']; ?>
                    <?php if($_SESSION['user']['grade'] <= 26){ ?>
                        <button <?php if (date('d') > 7 && date('d') <= 15) echo "disabled"; ?> type="button" href="" class="btn btn-outline-dark btn-sm" title="Add New OT" data-toggle="modal" data-target="#modal_OT_new" >
                            <i class="fa fa-plus"></i> Add New OT Submission
                        </button>
                    <?php }else{?>
                        <button disabled type="button" href="" class="btn btn-outline-dark btn-sm" title="You are not applicable to claim overtime." data-toggle="modal" data-target="#modal_OT_new" >
                            <i class="fa fa-plus"></i> Add New OT Submission
                        </button>
                    <?php } ?>

                    <a href="<?php echo base_url('hr/Overtime_report/myOTSubmissionList_print')?>" target="_blank" class="btn btn-outline-dark btn-sm" title="Print Staff Movement">
                        <i class="fa fa-print"></i>Print
                    </a>
                    <button id="btnShowFilters" type="button" class="btn btn-outline-dark btn-sm collapsed" data-trigger="hover" title="Show Filters Box" data-toggle="collapse" data-target="#collapseFilter" aria-expanded="false">
                        <i class="fas fa-filter"></i>Show Filters
                    </button> <small style="color: red;"><b>*NOTES </b></small><small>Add New OT Submission will be disabled every 8th-15th every month.</small>
                </div>
            </div>
            <div class="collapse" id="collapseFilter">
                <div class="card-header">
                    <div class="row">
                        <div class="col">
                            <div class="card no-shadow">
                                <div class="card-body">
                                    <input type="hidden" name="user_id" id="user_id" value="<?php echo $_SESSION['user']['id']; ?>">
                                    <div class="form-group row">
                                        <label for="filter_year" class="col-lg-3">
                                            Year
                                        </label>                           
                                        <div class="col-lg-4" >
                                            <select class="custom-select" name="filter_year" id="filter_year">
                                                <option value="">[All]</option>
                                                <?php if($yearList) foreach($yearList as $row){
                                                echo '<option value="'.$row->year.'" ';
                                                echo ($row->year == date('Y'))?'selected':''; 
                                                echo ' >'.$row->year.'</option>'; 
                                            }
                                            ?>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="form-group row">
                                        <label for="filter_month" class="col-lg-3">
                                            Month
                                        </label>                           
                                        <div class="col-lg-4" >
                                            <select name="filter_month" id="filter_month" class=" form-control">
                                                <option value="">[All]</option>
                                                    <?php if(!empty($month)) foreach ($month as $row): 
                                                        echo '<option value="'. $row->id.'" ';
                                                        echo ($row->id == date('n'))?'selected':''; 
                                                        echo ' >'. $row->month.'</option>'; 
                                                     endforeach ?>  
                                            </select>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col d-print-none">
                                            <button class="btn btn-info" id="searchBtn">search</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </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 no-shadow">
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-bordered p-0 m-0" width="100%">
                                        <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 text-center" tabindex="0" aria-controls="table_contact" rowspan="1" colspan="1" aria-label="Company Code/ Cost Centre: activate to sort column ascending" style="width: 0px;">
                                                Year
                                            </th>
                                            <th class="sorting text-center" tabindex="0" aria-controls="table_contact" rowspan="1" colspan="1" aria-label="Company Code/ Cost Centre: activate to sort column ascending" style="width: 0px;">
                                                Month
                                            </th>
                                            <th class="sorting text-center" tabindex="0" aria-controls="table_contact" rowspan="1" colspan="1" aria-label="Company Name: activate to sort column ascending" style="width: 0px;">
                                                Total Hours Applied
                                            </th>
                                            <th class="sorting text-center" tabindex="0" aria-controls="table_contact" rowspan="1" colspan="1" aria-label="Salary/ Wage Month: activate to sort column ascending" style="width: 0px;">
                                                Total Hours Approved
                                            </th>
                                            <th class="sorting text-center" tabindex="0" aria-controls="table_contact" rowspan="1" colspan="1" aria-label="Salary/ Wage Month: activate to sort column ascending" style="width: 0px;">
                                                OT Status
                                            </th>
                                            <th class="sorting text-center" tabindex="0" aria-controls="table_contact" rowspan="" colspan="1" aria-label="Total Net Pay: activate to sort column ascending" style="width: 0px;">
                                                Action
                                            </th>           
                                        </thead>
                                        <tbody>
                                            <?php if (!empty($otSubList)): ?>
                                                <?php foreach ($otSubList as $key => $ot): ?>
                                                <tr>
                                                    <td class="text-center"><?php echo $key+1;?></td>
                                                    <td class="text-center"><?php echo $ot->year;?></td>
                                                    <td class="text-center"><?php echo date("F", mktime(0, 0, 0, $ot->month, 10));?></td>
                                                    <td class="text-center"><?php echo $ot->totalHoursApplied;?></td> 
                                                    <td class="text-center"><?php echo $ot->totalHoursApprovedFinal;?></td>  
                                                    <td class="text-center">
                                                        <?php if($ot->Pending == 0 && $ot->Approved == 0 && $ot->Rejected == 0){ ?>
                                                            <span class="badge badge-secondary text-white">DRAFT</span><br>
                                                        <?php } else if($ot->Pending > 0){ ?>
                                                            <span class="badge badge-warning text-white">PENDING BY HOD</span><br>
                                                        <?php } else if($ot->Approved > 0){ ?>
                                                            <span class="badge badge-success text-white">APPROVED BY HOD</span><br>
                                                        <?php } else if($ot->Rejected > 0){ ?>
                                                            <span class="badge badge-danger text-white">REJECTED BY HOD</span><br>
                                                        <?php } else { ?>
                                                            <span class="badge badge-secondary text-white">DRAFT</span><br>
                                                        <?php } ?>

                                                        <?php if($ot->claim_status == 0){ ?>
                                                            <span class="badge badge-danger text-white">CLAIM PENDING</span><br>
                                                        <?php }else if($ot->claim_status == 1){ ?>
                                                            <span class="badge badge-primary text-white">CLAIM SUBMITTED</span><br>
                                                        <?php } else { ?>
                                                            <span class="badge badge-success text-white">CLAIM VERIFIED</span><br>
                                                        <?php } ?>

                                                        <?php if($ot->paid_status == 0){ ?>
                                                            <span class="badge badge-danger text-white">CLAIM UNPAID</span>
                                                        <?php } else { ?> 
                                                            <span class="badge badge-success text-white">CLAIM PAID</span>
                                                        <?php } ?>
                                                    </td>
                                                    <td class="text-center"><a href="<?php echo base_url(); ?>hr/overtime/monthList/<?php echo $ot->ID ?>" class="btn btn-success btn-sm" data-tooltip="tooltip" data-placement="bottom" data-trigger="hover" data-original-title="View OT"><i class="fas fa-sign-in-alt"></i></a></td>     
                                                <?php endforeach ?>
                                            <?php endif ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>      
        </div>
</div>

<!-- Modal OT Type -->
<div class="modal fade" id="modal_OT_new" 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">Create a new OT Submission : Select Year and Month</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
            </div>

            <form class="form" id="newOTForm" method="">
                <div class="modal-body">
                    <div class="form-group row">
                        <label class="col-lg-3">
                            Year
                        </label>                           
                        <div class="col-lg-4" >
                            <select class="custom-select" id="OT_year" name="OT_year">
                                <?php
                                    //new OT should only for current and future month and year 
                                    //read year from table. akmal 20180724
                                    if(!empty($yearList2)) foreach($yearList2 as $year){
                                    echo '<option value="'.$year.'">'.$year.'</option>';
                                    }
                                ?>
                                <!-- <option><?php //echo date('Y'); ?></option> -->
                            </select>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-lg-3">
                            Month
                        </label>                           
                        <div class="col-lg-4" >
                            <select class="custom-select" id="OT_month" name="OT_month" onchange="checkExistingPeriod()">
                                <?php

                                    // e.g. OT bln Feb boleh key in pada bln Feb dan Mac, current month OT can be submitted in the current month and the next month
                                    $cm = date('m'); //13

                                    if(date('d') <= 7 ){
                                        $cm; //12
                                        $cm2 = $cm+1;
                                        $cm3 = $cm-11; //20191202 farid for bulan 12, january become value=12. 

                                        if ($cm == 12) {
                                            echo '<option value="'.$cm.'">'.date("F",mktime(0,0,0,$cm,1)).'</option>';
                                            echo '<option value="'.$cm3.'">'.date("F",mktime(0,0,0,1,1)).'</option>'; //20191202 farid for bulan 12, january become value=12. 
                                        } else {
                                            echo '<option value="'.$cm.'">'.date("F",mktime(0,0,0,$cm,1)).'</option>';
                                            echo '<option value="'.$cm2.'">'.date("F",mktime(0,0,0,$cm+1,1)).'</option>';
                                        }
                                        
                                    } else {
                                        // $cm; //13
                                        // if($cm > 12) $cm = $cm - 12; //1
                                        $cm2 = $cm+1; //2
                                        $cm3 = $cm-11;
                                        // if($cm2 > 12) $cm2 = $cm2 - 12;

                                        //echo '<option value="'.$cm2.'">'.date("F",mktime(0,0,0,$cm+1,1)).'</option>';

                                        if ($cm == 12) {
                                            // echo '<option value="'.$cm.'">'.date("F",mktime(0,0,0,$cm,1)).'</option>';
                                            echo '<option value="'.$cm3.'">'.date("F",mktime(0,0,0,1,1)).'</option>'; //20191202 farid for bulan 12, january become value=12. 
                                        } else {
                                            // echo '<option value="'.$cm.'">'.date("F",mktime(0,0,0,$cm,1)).'</option>';
                                            echo '<option value="'.$cm2.'">'.date("F",mktime(0,0,0,$cm+1,1)).'</option>';
                                        }
                                    }

                                    // echo '<option value="'.$cm.'">'.date("F",mktime(0,0,0,$cm,1)).'</option>';
                                    // if ($cm2) echo '<option value="'.$cm2.'">'.date("F",mktime(0,0,0,$cm2,1)).'</option>';

                                    // if(date('d') <= 7 && date('m')){
                                    //     //$cm2 = $cm+1; //2
                                    //     $cm; //2
                                    //     if($cm > 12) $cm = $cm - 12; //1
                                    //     $cm2 = $cm+1; //2
                                    //     if($cm2 > 12) $cm2 = $cm2 - 12;
                                    //     echo '<option value="'.$cm.'">'.date("F",mktime(0,0,0,$cm,1)).'</option>';
                                    // } else if(date('d') > 7 && date('m')){
                                    //     $cm; //2
                                    //     if($cm > 12) $cm = $cm - 12; //1
                                    //     $cm2 = $cm+1; //2
                                    //     if($cm2 > 12) $cm2 = $cm2 - 12;
                                    //     //$cm2 = $cm+1;
                                    //     echo '<option value="'.$cm2.'">'.date("F",mktime(0,0,0,$cm2,1)).'</option>';
                                    // }
                                ?>
                            </select>
                        </div>
                        <div class="col-lg-2">
                            <div class="btn-group float-right">
                                <button type="button" class="btn btn-primary" onclick="saveOTSubmission()"> Create </button>
                            </div>
                        </div>
                    </div>            
                </div>
            </form> 

        </div>
    </div>
</div>
<!-- Modal OT Type -->

<script>
    $(document).ready(function(){

        //getData();

        $('#searchBtn').click(function(){
            getData();
        });

    });

    function saveOTSubmission(){

        var postData = {
            'year'      : $('#OT_year').val(),
            'month'     : $('#OT_month').val(),
        };

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: '<?php echo base_url(); ?>hr/Overtime/otMonthSave',
            data: postData,
            success: (data) => {
                    if(data.status == "Success") {
                        localStorage.setItem("status", data.status);
                        localStorage.setItem("msg", data.msg);
                        location.reload();
                    }else{
                        alert('You have already create OT Submission for respective month.');
                    }
                }
        });
    }

    function checkExistingPeriod() {
        
        var year  = $('#OT_year').val();
        var month = $('#OT_month').val();

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

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: '<?php echo base_url(); ?>hr/Overtime/getOTMonth',
            data: postData,
            success: (data) => {
                    if ($.trim(data.status) == "success") {
                        $.each(data.OT_month, function(i, v)
                          {
                            if (year == v.year)
                            {
                                if(month == v.month){
                                    alert('You have already create OT Submission for respective month.');
                                    //
                                } else {
                                    //return true;
                                }
                            } else {
                                //return true;
                            }
                        });
                    }
                }
        });
    }

    function CheckExistingDate() {

        var date   = moment($('#Date').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 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 == v.startTime)
                            {
                                alert("The date and time you choose already in the OT application list. Please choose another date.");
                        
                                $('#Date').val('');
                                $('#start_time').val('');

                            } else {
                                //alert("masuk sini");
                            }
                        }
                    });
                }
            }
        });

    }

    function getData() {
        var table = $('.table').DataTable();
            table.clear().draw();
            var frmData = new FormData();

            frmData.append('filter_year',$('#filter_year').val());
            frmData.append('filter_month',$('#filter_month').val());
            frmData.append('user_id',$('#user_id').val());
            
            $.ajax({
                url:"<?php echo base_url('/hr/api/overtime/getMyOtLists'); ?>",
                type:'post',
                dataType:'json',
                data:frmData,
                processData: false,
                contentType: false,
                success:function(data){

                    iziToast.success({
                        position: 'bottomRight',
                        message: 'filtering data',
                    });

                    if(data.table){
                        for (var i = 0; i < data.table.length; i++) {

                            if(data.table[i].month == 1){
                                var month = "January";
                            }else if(data.table[i].month == 2){
                                var month = "February";
                            }else  if(data.table[i].month == 3){
                                var month = "March";
                            }else  if(data.table[i].month == 4){
                                var month = "April";
                            }else  if(data.table[i].month == 5){
                                var month = "May";
                            }else  if(data.table[i].month == 6){
                                var month = "Jun";
                            }else  if(data.table[i].month == 7){
                                var month = "July";
                            }else  if(data.table[i].month == 8){
                                var month = "August";
                            }else  if(data.table[i].month == 9){
                                var month = "September";
                            }else  if(data.table[i].month == 10){
                                var month = "October";
                            }else  if(data.table[i].month == 11){
                                var month = "November";
                            }else  if(data.table[i].month == 12){
                                var month = "December";
                            }else var month = "Unknown";

                            if(data.table[i].pending == 0 && data.table[i].Approved == 0 && data.table[i].Rejected == 0){
                                var badge = '<span class="badge badge-secondary text-white">DRAFT</span>';
                            }else if(data.table[i].pending > 0){
                                var badge = '<span class="badge badge-warning text-white">PENDING BY HOD</span>';
                            }else if(data.table[i].Approved > 0){
                                var badge = '<span class="badge badge-success text-white">APPROVED BY HOD</span>';
                            }else if(data.table[i].Rejected > 0){
                                var badge = '<span class="badge badge-danger text-white">REJECTED BY HOD</span>';
                            }else var badge = '<span class="badge badge-secondary text-white">DRAFT</span>';

                            if(data.table[i].claim_status == 0){
                                var badge2 = '<span class="badge badge-danger text-white">CLAIM PENDING</span>';
                            }else if(data.table[i].claim_status == 1){
                                var badge2 = '<span class="badge badge-primary text-white">CLAIM SUBMITTED</span>';
                            }else var badge2 = '<span class="badge badge-success text-white">CLAIM VERIFIED</span>';

                            if(data.table[i].paid_status == 0){
                                var badge3 = '<span class="badge badge-danger text-white">CLAIM UNPAID</span>';
                            }else var badge3 = '<span class="badge badge-success text-white">CLAIM PAID</span>';
                            
                            table.row.add({
                                0   : i+1,
                                1   : '<div class="text-center">'+data.table[i].year+'</div>',
                                2   : '<div class="text-center">'+month+'</div>',
                                3   : '<div class="text-center">'+data.table[i].totalHoursApplied+'</div>',
                                4   : '<div class="text-center">'+data.table[i].totalHoursApproved+'</div>',
                                5   : '<div class="text-center">'+badge+'<br>'+badge2+'<br>'+badge3+'</div>',
                                6   : '<div class="text-center"><a href="<?php echo base_url(); ?>/hr/overtime/monthList/'+ data.table[i].otID+'" class="btn btn-success btn-sm" data-tooltip="tooltip" data-placement="bottom" data-trigger="hover" data-original-title="View OT"><i class="fas fa-sign-in-alt"></i></a></div>',
                            }).draw();
                            console.log(data);
                        }
                        
                    }
                    
                },
                error:function(){
                     iziToast.warning({
                        position: 'bottomRight',
                        message: '500 Internal Server Error.'
                    });
                }
            });
    }

    function calcTotalHour(){

         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(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;
                    }else{
                        var hoursFL = hoursF;
                    }
                } else {
                    var hoursF = hours;
                    if(hoursF >= 8){
                        var hoursFL = hoursF - 1;
                    }else{
                        var hoursFL = hoursF;
                    }
                }

                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');
                    }
                }

                $('#total_hour').val(hoursFL + '.' + minutesF);

            }
        });
    }

    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);

    }

</script> 