<?php
include 'connect/cms-config.php' ;
include 'requires/function.php' ;
include 'requires/session.php' ;

// check permission
if ( !permissionCheck($row_user, 'attendance-list') &&  !permissionCheck($row_user, 'attendance-attendance-reprocessing') ){
    header('Location: index.php') ;
    exit ;
}

// keep parameter in value
$edit           = escapeString($_GET['edit']) ;
$page           = escapeString($_GET['page']) ;
$page_mode      = escapeString($_GET['page_mode']) ;
$type           = escapeString($_GET['type']) ;

// REPROCESSING
$rsi  = ($_POST['reprocessing_staff_id']) ;
$reprocessing_date_from  = escapeString($_POST['reprocessing_date_from']) ;
$reprocessing_date_to    = escapeString($_POST['reprocessing_date_to']) ;
$reprocessing_reset      = escapeString($_POST['reprocessing_reset']) ;

$get_user_tier           = userTierQuery( $row_user ) ;

$result = 'failed invalid staff';

if ( arrayCheck($rsi) ){

    $result        = 'Failed staff.' ;

    $staffs_q      = $mysqli->query("SELECT staff_id, staff_idno, staff_name, group_id, country_id FROM staff
                                     WHERE deleted_at IS NULL AND staff_id IN (".implode(',', $rsi).")") ;

    if ( $staffs_q->num_rows > 0 ){

        $result = 'Failed invalid date' ;

        if ( $reprocessing_date_from != '' && $reprocessing_date_to != '' ){

            $get_day  = date('N', strtotime($reprocessing_date_from)) ;

            // get all related staff first
            $staffs    = [] ;
            $staffs_id = [] ;
            $group_id  = [] ;
            while ( $row_staff  = $staffs_q->fetch_assoc() ){
                $staffs[]    = $row_staff ;
                $staffs_id[] = $row_staff['staff_id'] ;
                $group_id[]  = $row_staff['group_id'] ;
            }

            // get staff working hours
            $workings   = [] ;
            $working_q  = $mysqli->query("SELECT staff_id, working_period_from, working_period_to, working_period_before FROM staff_attendance_working
                                          WHERE deleted_at IS NULL AND staff_id IN (".implode(',', $staffs_id).") AND working_date = '".$reprocessing_date_from."'") ;
            if ( $working_q->num_rows > 0 ){
                while ( $row_working  = $working_q->fetch_assoc() ){
                    $workings[$row_working['staff_id']] = $row_working ;
                }
            }

            // get staff setting working
            $sworkings  = [] ;
            $working_q  = $mysqli->query("SELECT group_id, working_morning_start as working_period_from, working_morning_end as working_period_to, working_period_before FROM setting_working
                                          WHERE deleted_at IS NULL AND group_id IN (".implode(',', $group_id).") AND working_day = '".$get_day."'") ;
            if ( $working_q->num_rows > 0 ){
                while ( $row_working  = $working_q->fetch_assoc() ){
                    $sworkings[$row_working['group_id']] = $row_working ;
                }
            }

            // loop all staff
            foreach ( $staffs as $staff ){

                $boolean_working = false ;
                $staff_id        = $staff['staff_id'] ;

                if ( arrayCheck($workings[$staff_id]) ){
                    $boolean_working = true ;
                    $working         = $workings[$staff_id] ;
                }else{
                    if ( arrayCheck($sworkings[$staff['group_id']]) ){
                        $boolean_working = true ;
                        $working         = $sworkings[$staff['group_id']] ;
                    }
                }

                if ( $boolean_working ){

                    $date_from    = $reprocessing_date_from . ' ' . $working['working_period_from'] ;
                    $date_to      = date('Y-m-d', strtotime($reprocessing_date_to.' +1 days')) . ' ' . $working['working_period_to'] ;

                    // if ( $working['working_period_before'] > 0 ){
                    //     $date_to  = date( 'Y-m-d H:i:s', strtotime('-'.$working['working_period_before'].' hour', strtotime($date_to)) ) ;
                    // }
                    
                    // get attendance list
                    $attendance_q = $mysqli->query("SELECT attendance_id, list_id, created_at FROM staff_attendance
                                                    WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' AND created_at >= '".$date_from."' AND created_at <= '".$date_to."' ORDER BY created_at ASC") ;
                    if ( $attendance_q->num_rows > 0 ){

                        $result   = 'Success update.' ;

                        $list_id  = [] ;
                        while ( $row = $attendance_q->fetch_assoc() ){
                            $list_id[$row['list_id']] = $row['list_id'] ;
                        }

                        $im_list_id = implode(',', $list_id) ;

                        $u_sal = "UPDATE staff_attendance_list SET deleted_at = '".TODAYDATE."' WHERE deleted_at IS NULL AND list_id IN (".$im_list_id.") AND staff_id = '".$staff_id."'" ;
                        $mysqli->query($u_sal) ;
                        if ( $mysqli->error != '' ){
                            $error++ ;
                            $result = 'Failed update.' ;
                            $_SESSION['system_result'] = $mysqli->error ;
                            exit;                                    
                        }

                        $u_sa = "UPDATE staff_attendance SET list_id = '0' WHERE deleted_at IS NULL AND list_id IN (".$im_list_id.") AND staff_id = '".$staff_id."' AND list_id != '-1'" ;

                        $mysqli->query($u_sa) ;
                        if ( $mysqli->error != '' ){
                            $error++ ;
                            $result = 'Failed update.' ;
                            $_SESSION['system_result'] = $mysqli->error ;
                            exit;                                    
                        }
                    }

                    $period_date_to = $date_to ;
                    $date_to        = date('Y-m-d H:i:s', strtotime($date_to.' -1 days')) ;
                    $u_sal2  = "UPDATE staff_attendance_list SET deleted_at = '".TODAYDATE."' WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' AND list_date >= '".date('Y-m-d', strtotime($date_from))."' AND list_date <= '".date('Y-m-d', strtotime($date_to))."'" ;
                    
                    $mysqli->query($u_sal2) ;
                    if ( $mysqli->error != '' ){
                        $error++ ;
                        $result = 'Failed update.' ;
                        $_SESSION['system_result'] = $mysqli->error ;
                        exit;
                    }

                    if ( $reprocessing_reset == 'yes' ){
                        $u_saw = "UPDATE staff_attendance_working SET deleted_at = '".TODAYDATE."' WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' AND working_date >= '".date('Y-m-d', strtotime($date_from))."' AND working_date <= '".date('Y-m-d', strtotime($date_to))."'" ;
                       
                        $mysqli->query($u_saw) ;
                        if ( $mysqli->error != '' ){
                            $error++ ;
                            $result = 'Failed update.' ;
                            $_SESSION['system_result'] = $mysqli->error ;
                            exit;                                    
                        }
                    }

                    $period = new DatePeriod(
                         new DateTime($date_from),
                         new DateInterval('P1D'),
                         new DateTime($period_date_to)
                    ) ;

                    foreach ( $period as $key => $value ) { 

                        $params = [ 
                            'get_type'     => 'custom', 
                            'get_date'     => $value->format('Y-m-d'),
                            'get_staff_id' => $staff_id
                        ] ;
                        
                        // callWithoutResponse( PATH, '443', 'GET', '/cron/generate_attendance_2.php', $params ) ;
                        $cronjobHit = cronjobHit( PATH."cron/generate_attendance.php?get_type=custom&get_date=".$value->format('Y-m-d')."&get_staff_id=".$staff_id."" ) ; 

                        // $cronjobHit = cronjobHit( PATH."cron/generate_attendance.php?get_type=custom&get_date=".$value->format('Y-m-d')."&get_staff_id=".$staff_id."" ) ; 
                        // $de = json_decode($cronjobHit,true);
                        // if($de['status'] != '200'){
                        //      $_SESSION['system_result'] .= $de['message'];
                        // }
                    }
                    $_SESSION['system_result'] = 'success update' ;

                }
            }

        }

    }

    header("Location: ".PATH."/hr-attendance-reprocessing.php?sort_by=staff_idno&sort_by_type=ASC") ;
    exit ;
}

$boolean_role = false ;
$boolean_edit = false ;
if ( $_SESSION['system_permission'] == 'admin' ){
    $boolean_role = true ;
    if ( $edit == 'yes' ){
        $boolean_edit = true ;
    }
}

// active page
$active_main_menu = 'hr' ;
$active_sub_menu  = 'hr-attendance' ;
$active_menu      = 'hr-attendance-report' ;    

// start header here
include 'requires/page_header.php' ;
include 'requires/page_top.php' ;

// reset sort by type
$sort_by_type = ( $sort_by_type == 'DESC' ? 'ASC' : 'DESC' ) ;

?>

<style>
.check_in_out_warning{
    background:#f7a6a6;
}
.select_datepicker{
    text-align: center;
}
.datepicker_box{
    display: inline-block;
}
.datepicker_submit{
    border: 0;
    padding: 7px;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
    // Select All Rules Product
    $('.chosen-toggle').each(function(index) {
        $(this).on('click', function(){
            $(this).parent().find('option').prop('selected', $(this).hasClass('select')).parent().trigger("change");
        });
    });
});
</script>
<!-- Header Ends -->
<div class="warper container-fluid">    
    <div class="page-header">
        <h1><?= $lang['Reprocessing']?> </h1>
    </div>

    <?php
    if ($_SESSION['system_result'] != ''){
        if ( $_SESSION['system_result'] == 'success update' ){
            echo '<div class="result_success">'.$_SESSION['system_result'].'</div>' ;
        }else{
            echo '<div class="result_error">'.$_SESSION['system_result'].'</div>' ;
        }
        unset($_SESSION['system_result']) ;
    }

    // get all staff
    $staff_list   = [] ;
    $mysqli_staff = $mysqli->query( "SELECT staff_id, staff_name, staff_idno FROM staff
                                    WHERE deleted_at IS NULL AND ( staff_date_resigned >= '".date("Y-m-d",time())."' OR staff_date_resigned = '0000-00-00' OR staff_date_resigned IS NULL ) ".$user_branch_permission_sql.( $get_user_tier['check'] ? " AND staff_tier IN ( ".implode(', ', $get_user_tier['tiers'])." )" : '' )." ORDER BY staff_idno ASC" ) ;
    if ( $mysqli_staff->num_rows > 0 ){
        while ( $row_staff = $mysqli_staff->fetch_assoc() ){
            $staff_list[$row_staff['staff_id']] = dataFilter($row_staff['staff_name']) . ' ( ' . dataFilter($row_staff['staff_idno']) . ' )' ;
        }
    }
    ?>

    <div class="panel panel-default" id="basic-table-title">
        <div class="panel-heading"></div>
        <div class="panel-body">
            <form method="post" class="form-horizontal" >
                <div class="form-group">
                    <label class="col-sm-2 control-label"><?= $lang['Staff']?></label>
                    <div class="col-sm-9" id='selectall'>
                        <select name="reprocessing_staff_id[]" id="reprocessing_staff_id" class="chosen-select2 form-control tab_index ui-dropdown-select ui-search-input select2-basic-single" multiple required>
                         
                            <?php
                            if ( count($staff_list) > 0 ){
                                foreach ( $staff_list as $k => $v ){
                                    echo '<option value="'.$k.'" '.( $k == $row_page['staff_id'] ? 'selected' : '').'>'.$v.'</option>' ;
                                }
                            }
                            ?>
                        </select>
                         <button style="color:white;background-color: #5e5bd0;" type="button" class="chosen-toggle select btn margin_top_7px"><?= $lang['Select all']?></button>
                        <button style="color:white;background-color: #5e5bd0;" type="button" class="chosen-toggle deselect btn btn-purple margin_top_7px"><?= $lang['Deselect all']?></button>
                    </div>

                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label"><?= $lang['Date From']?></label>
                    <div class="col-sm-9">
                        <input type="date" name="reprocessing_date_from" value="<?= date('Y-m-d', strtotime(TODAYDATE)) ?>" class="form-control tab_index" required />
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label"><?= $lang['Date To']?></label>
                    <div class="col-sm-9">
                        <input type="date" name="reprocessing_date_to" value="<?= date('Y-m-d', strtotime(TODAYDATE)) ?>" class="form-control tab_index" required />
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label"><?= $lang['Reset Working Hours']?></label>
                    <div class="col-sm-9">
                        <label><input type="checkbox" name="reprocessing_reset" value="yes" class="tab_index" /> <?= $lang['Tick to reset the working hours and follow the new one']?></label>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-11">
                        <input type="hidden" name="page_mode" value="<?= $page_mode ?>" />
                        <input type="hidden" name="edit" value="<?= $edit ?>" />
                        <input type="hidden" name="date_time" value="<?= $date_time ?>" />
                        <input type="hidden" name="sort_by" value="<?= $sort_by ?>" />
                        <input type="hidden" name="sort_by_type" value="<?= $sort_by_type ?>" />
                        <button type="submit" class="btn" style="color:white;background-color: #5e5bd0;float:right; margin-top: 5px;width: 100px;" ><?= $lang['submit']?></button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    

</div>





<script type="text/javascript">

    $('.allinfodata').live('click', function(){

        $('.modaldata').val('');
        $('.modal2title').empty();
        $('.modal2title').append('Update');
        var staffid     = $(this).data('staffid');
        var check_group = $(this).data('check_group');
        $('#modal_staff_id').val(staffid);
        $('#modal_check_group').val(check_group);

        // if ( confirm('Confirm update attendance?') ) {

            $.ajax({
                url : 'hr-attendance.php?page_mode=admend-format-2&staff_id='+staffid+'&check_group='+check_group,
                type: 'get',
                dataType: 'json',
                success:function(data) {

                    if ( data['result'] == 'success' ){

                        var content = '' ;

                        // loop all date time
                        $.each( data['data'], function(k, v) {

                            content += '<div class="form-group clearfix">' ;
                                content += '<label class="control-label col-md-2 col-sm-2 col-xs-12"><?= $lang['Time']?> ( '+(k+1)+' )</label>' ;
                                content += '<div class="col-md-10 col-sm-10 col-xs-12">' ;
                                    content += '<div class="form-group">' ;
                                        content += '<div class="col-md-4 col-sm-4 col-xs-4">' ;
                                             content += '<input type="hidden" class="form-control modaldata" name="attendance_id_'+k+'" value="'+v['id']+'" placeholder="<?= $lang['attendance']?>"> ID">' ;
                                            content += '<input type="hidden" class="form-control modaldata" name="attendance_date_'+k+'" value="'+v['date']+'" placeholder="<?= $lang['date']?>">">' ;
                                            content += '<input type="time" class="form-control modaldata" name="attendance_time_'+k+'" value="'+v['time']+'" placeholder="<?= $lang['Time']?>">">' ;
                                        content += '</div>' ;
                                        content += '<div class="col-md-8 col-sm-8 col-xs-8">' ;
                                            content += '<input type="text" class="form-control modaldata" style="padding: 8px; font-size: 13px;" name="attendance_remark_'+k+'" value="'+v['remark']+'" placeholder="<?= $lang['remark']?>">' ;
                                        content += '</div>' ;
                                    content += '</div>' ;
                                content += '</div>' ;                   
                            content += '</div>' ;

                        }) ;

                        // show_all_datetime
                        $(".show_all_datetime").html( content ) ;

                    }else{
                        alert("Failed to get attendance") ;
                        location.reload() ;
                    }

                }
            });
            $('#modal-2').modal('show');

        // }

    });

</script>

<div class="modal modal-default fade" id="modal-2">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title modal2title"></h4>
            </div>

            <form method="post" action="?<?= $search_url ?>"> 

                <input type="hidden" name="modal_staff_id" id="modal_staff_id" class="modaldata" />
                <input type="hidden" name="modal_check_group" id="modal_check_group" class="modaldata" />
                <div class="modal-body">
                    <div class="show_all_datetime clearfix"></div>
                </div>                  
                
                <div class="modal-footer">
                    <div class="form-group clearfix">
                        <div class="col-md-12 col-sm-12 col-xs-12">
                            <div class="form-group">
                                <div class="col-md-12 col-sm-12 col-xs-12">
                                    <button type="submit" class="btn btn-purple addbtn2"><i class="fa fa-check-circle"></i> <?= $lang['Save']?></button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            
            </form>

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

<?php
// footer
include 'requires/page_footer.php' ;
?>