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

// keep parameter in value
$page           = escapeString($_GET['page']) ;
$page_mode      = escapeString($_GET['page_mode']) ;
$type           = escapeString($_GET['type']) ;
$search         = escapeString($_GET['search']) ;
$department_id  = escapeString($_GET['department_id']) ;
$remark         = escapeString($_POST['remark']) ;
$status         = escapeString($_POST['status']) ;
$debug          = escapeString($_GET['debug']) ;

$date_from      = escapeString($_GET['date_from']);
$date_to        = escapeString($_GET['date_to']);

$mysqli_page = $mysqli->query("SELECT * FROM system_user WHERE user_id = '".$_SESSION['system_id']."' ");
if ($mysqli_page->num_rows > 0){
    while($row_page=$mysqli_page->fetch_array(MYSQLI_ASSOC)){
        if($row_page['user_date_format'] == NULL){
            $dateformat = "Y-m-d";
        }
        else{
            $dateformat = $row_page['user_date_format'];
        }
        $date01 = str_replace("d","01",$dateformat);
        $date31 = str_replace("d","t",$dateformat);


// get all branch
$branch     = [] ;
$get_branch = $mysqli->query("SELECT * FROM branch
                              WHERE deleted_at IS NULL".$user_branch_permission_sql) ;
if ( $get_branch->num_rows > 0 ){
    while ( $row_branch = $get_branch->fetch_assoc() ){
        $branch[$row_branch['branch_id']] = $row_branch['branch_name'] ;
    }
}

// mode type | all list | new | edit
switch( $page_mode ){
    case 'record-all':
        include 'includes/Record/record-all.php';
    break;
    case 'record-edit':
        include 'includes/Record/record-edit.php';
    break;

    case 'admend-format-1' :

        /*
        $result      = 'failed' ;
        $data        = [] ;

        $staff_id    = escapeString($_GET['staff_id']) ;
        $check_group = escapeString($_GET['check_group']) ;

        if ( $staff_id != '' && $check_group != '' ){

            $attendances_q = $mysqli->query("SELECT * FROM staff_attendance
                                             WHERE staff_id = '".$staff_id."'AND check_group = '".$check_group."' AND deleted_at IS NULL
                                             ORDER BY created_at ASC") ;

            if ( $attendances_q->num_rows > 0 ){

                $result = 'success' ;

                while ( $attendance = $attendances_q->fetch_assoc() ){
                    $data[] = [
                        'id'   => $attendance['attendance_id'],
                        'type' => ucwords($attendance['type']),
                        'date' => date('Y-m-d', strtotime($attendance['created_at'])),
                        'time' => date('H:i:s', strtotime($attendance['created_at']))
                    ] ;
                }

                $last_inout = '' ;
                $last_date  = '' ;
                for ( $a = 0 ; $a < 8 ; $a++ ){

                    if ( !empty($data[$a]) ){
                        $last_inout = $data[$a]['type'] ;
                        $last_date  = $data[$a]['date'] ;
                    }else{

                        if ( $last_inout == 'In' ){
                            $last_inout = 'Out' ;
                        }else{
                            $last_inout = 'In' ;
                        }

                        $data[$a] = [
                            'id'   => 0,
                            'type' => $last_inout,
                            'date' => $last_date,
                            'time' => ''
                        ] ;

                    }
                }

            }else{

                $result = 'success' ;

                $last_inout = '' ;
                for ( $a = 0 ; $a < 8 ; $a++ ){

                    if ( $last_inout == 'In' && $last_inout != '' ){
                        $last_inout = 'Out' ;
                    }else{
                        $last_inout = 'In' ;
                    }

                    $data[$a] = [
                        'id'   => 0,
                        'type' => $last_inout,
                        'date' => $check_group,
                        'time' => ''
                    ] ;
                }
            }

        }

        echo json_encode([
            'result'  => $result,
            'data'    => $data
        ]) ;
        exit ;
        */

    break ;

    case 'admend-format-2' :

        $result      = 'failed' ;
        $data        = [] ;

        $staff_id    = escapeString($_GET['staff_id']) ;
        $check_group = escapeString($_GET['check_group']) ;

        if ( $staff_id != '' && $check_group != '' ){

            $attendances_q = $mysqli->query("SELECT * FROM staff_attendance
                                             WHERE staff_id = '".$staff_id."'AND created_at LIKE '".$check_group."%' AND deleted_at IS NULL
                                             ORDER BY created_at ASC") ;

            if ( $attendances_q->num_rows > 0 ){

                $result = 'success' ;

                while ( $attendance = $attendances_q->fetch_assoc() ){
                    $data[] = [
                        'id'     => $attendance['attendance_id'],
                        'date'   => date('Y-m-d', strtotime($attendance['created_at'])),
                        'time'   => date('H:i:s', strtotime($attendance['created_at'])),
                        'remark' => dataFilter($attendance['remark'])
                    ] ;
                }

                for ( $a = 0 ; $a < 8 ; $a++ ){

                    if ( !empty($data[$a]) ){
                        $last_date  = $data[$a]['date'] ;
                    }else{

                        $data[$a] = [
                            'id'     => 0,
                            'date'   => $last_date,
                            'time'   => '',
                            'remark' => ''
                        ] ;

                    }
                }

            }else{

                $result = 'success' ;

                $last_inout = '' ;
                for ( $a = 0 ; $a < 8 ; $a++ ){

                    $data[$a] = [
                        'id'     => 0,
                        'date'   => $check_group,
                        'time'   => '',
                        'remark' => ''
                    ] ;
                }
            }

        }

        echo json_encode([
            'result'  => $result,
            'data'    => $data
        ]) ;
        exit ;

    break ;

    case 'list-limit' :

        $path             = 'attendances/check' ;
        $platform         = 'web' ;
        $lang             = 'en' ;
        $branch_id        = $row_branch['branch_id'] ;
        $staff_id         = '' ;
        $token            = '' ;
        $time             = time() ;
        $sign             = hash('sha256', $path.$platform.$lang.$branch_id.$staff_id.$token.$time.APIKEY) ;
        $call         = call( 'curl', PATH.'api/'.$path.'.php', 'POST', [], [
            'input_type'      => 'selfpunch',
            'qrcode'          => $staff_idno,
            'latitude'        => '',
            'longitude'       => '',
            'platform'        => $platform,
            'lang'            => $lang,
            'branch_id'       => $branch_id,
            'staff_id'        => $staff_id,
            'token'           => $token,
            'time'            => $time,
            'sign'            => $sign
        ] ) ;
        echo json_encode( $call ) ;
        exit ;

    break ;

    case 'selfpunch' :

        $status           = '300' ;
        $message          = 'Staff not found.' ;
        $alert            = '' ;
        $data             = [] ;
        $list             = [] ;

        // staff_idno
        $staff_idno       = escapeString( $_GET['staff_idno'] ) ;

        if ( $staff_idno   != '' ){

            $path         = 'attendances/punch' ;
            $platform     = 'web' ;
            $lang         = 'en' ;
            $branch_id    = $row_branch['branch_id'] ;
            $staff_id     = '' ;
            $token        = '' ;
            $time         = time() ;
            $sign         = hash('sha256', $path.$platform.$lang.$branch_id.$staff_id.$token.$time.APIKEY) ;
            $call         = call( 'curl', PATH.'api/'.$path.'.php', 'POST', [], [
                'input_type'      => 'selfpunch',
                'qrcode'          => $staff_idno,
                'latitude'        => '',
                'longitude'       => '',
                'platform'        => $platform,
                'lang'            => $lang,
                'branch_id'       => $branch_id,
                'staff_id'        => $staff_id,
                'token'           => $token,
                'time'            => $time,
                'sign'            => $sign
            ] ) ;

            $status       = $call['status'] ;
            $message      = $call['message'] ;

            if ( $call['status'] == '200' ){
                $alert    = 'Scan success ( '.$staff_idno.' ).' ;
            }
        }

        echo json_encode([
            'status'  => $status,
            'message' => $message,
            'alert'   => $alert
        ]) ;
        exit ;

    break ;

    case 'qrcode-check' :

        $status   = '300' ;
        $message  = 'Code not found.' ;
        $data     = [] ;
        $new_code = '' ;
        $alert    = '' ;
        $boolean  = false ;

        $type     = $_POST['type'] ;
        $qrcode   = $_POST['qrcode'] ;

        // if code not found, generate one
        if ( $qrcode != '' ){

            $get_code = $mysqli->query("SELECT staff_id, code, status, created_at FROM qrcodes
                                        WHERE type = '".$type."' AND code = '".$qrcode."' LIMIT 1") ;

            if ( $get_code->num_rows > 0 ){

                $status    = '220' ;
                $message   = 'Code expired.' ;

                $get       = $get_code->fetch_assoc() ;

                $date_code = $get['created_at'] ;
                $date_time = TODAYDATE ;
                $date_time = date('Y-m-d H:i:s', strtotime($date_time . ' -5 minutes')) ;

                if ( $date_code > $date_time ){

                    $status  = '210' ;
                    $message = 'Code used' ;

                    // check code status
                    if ( $get['status'] == '0' ){

                        $status   = '201' ; // Code used before
                        $message  = 'Code can used back.' ;
                        $generate = $get['code'] ;
                        $boolean  = true ;

                    }elseif ( $get['status'] == '1' ){ // 1 mean scan success

                        // get staff info
                        if ( $get['staff_id'] > 0 ){
                            $get_staff = $mysqli->query("SELECT * FROM staff
                                                         WHERE deleted_at IS NULL AND staff_id = '".$get['staff_id']."' LIMIT 1") ;
                            if ( $get_staff->num_rows > 0 ){
                                $staff = $get_staff->fetch_assoc() ;
                                $alert = 'Scan success ( '.$staff['staff_idno'].' )' ;
                            }
                        }

                    }elseif ( $get['status'] == '2' ){ // 2 mean scan success, but scan too fast
                        $alert = 'Accept rescan only after 15 minutes.' ;
                    }

                }

            }

        }

        $generatecode = generateQrcode( '', $new_code, $new_code ) ;
        $new_code     = $generatecode['url'] ;

        if ( !$boolean ){
            $mysqli->query("INSERT INTO qrcodes
                            (type, status, created_at, updated_at) VALUES
                            ('checkin', '0', '".TODAYDATE."', '".TODAYDATE."')") ;

            // set new code
            $last_id  = $mysqli->insert_id ;
            $new_code = 'PC|'.str_pad($last_id, 6, '0', STR_PAD_LEFT) ;

            $mysqli->query("UPDATE qrcodes SET 
                            code = '".$new_code."' 
                            WHERE qrcode_id = '".$last_id."'") ;

            $status   = '200' ;
            $message  = 'New code generated' ;
        }

            $generatecode = generateQrcode( '', $new_code, $new_code ) ;
            $new_code     = $generatecode['url'] ;

        echo json_encode([
            'status'  => $status,
            'message' => $message,
            'data'    => [
                'alert' => $alert,
                'code' => $new_code
            ]
        ]) ;
        exit ;

    break ;



    case 'qrcode' :

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

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

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

        <style>
        /* The snackbar - position it at the bottom and in the middle of the screen */
        #snackbar {
            visibility: hidden;
            width: 600px;
            margin-left: -200px;
            background-color: #6b6b6b;
            color: #fff;
            text-align: center;
            border-radius: 5px;
            padding: 20px;
            position: fixed;
            z-index: 1;
            left: 50%;
            bottom: 50%;
            font-size: 30px;
            box-shadow: 1px 1px 1px #000;
        }
        /* Show the snackbar when clicking on a button (class added with JavaScript) */
        #snackbar.show {
            visibility: visible; /* Show the snackbar */
            /* Add animation: Take 0.5 seconds to fade in and out the snackbar. 
            However, delay the fade out process for 2.5 seconds */
            -webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s;
            animation: fadein 0.5s, fadeout 0.5s 2.5s;
        }
        /* Animations to fade the snackbar in and out */
        @-webkit-keyframes fadein {
            from {bottom: 0; opacity: 0;} 
            to {bottom: 50%; opacity: 1;}
        }
        @keyframes fadein {
            from {bottom: 0; opacity: 0;}
            to {bottom: 50%; opacity: 1;}
        }
        @-webkit-keyframes fadeout {
            from {bottom: 50%; opacity: 1;} 
            to {bottom: 0; opacity: 0;}
        }
        @keyframes fadeout {
            from {bottom: 50%; opacity: 1;}
            to {bottom: 0; opacity: 0;}
        }

        .left_box{
            float:left;
            width:50%;
        }
        #qrcode_box{
            min-height:200px;
            max-width: 300px;
            width:100%;
            /*height:300px;*/
            margin: 0 20px 0 auto;
        }
        #qrcode_box img{
            width: 100%;
            /*height:300px;*/
            display: block;
            border:1px solid #ccc;
            margin:0 auto;
        }
        .right_box{
            float:left;
            width:50%;
            text-align: center;
            font-weight: 600;
            font-size: 2vw;
        }
        #date_time{
            width:100%;
            max-width:420px;
            padding-left:20px;
            text-align: right;
            line-height: 1.1;
        }
        .clock_time_real{
            font-size:8vw;
        }
        .clock_time_date{
            margin-right:40px;
        }
        .bottom_box{
            text-align: center;
            padding-bottom:50px;
        }
        .bottom_all{
            width: 200px;
            height: 200px;
            border-radius: 200px;
            margin: 30px;
            margin-bottom:0;
            display: inline-block;
            background: #ccc;
            box-shadow: 2px 1px 10px #000;
        }
        .bottom_present{
            background: #528111
        }
        .bottom_late{
            background: #c93f3c
        }
        .bottom_absent{
            background: #971d1b
        }
        .bottom_punch{
            background: #9ec54c
        }
        .bottom_all:hover, .bottom_all:focus{
            text-decoration:none;
        }
        .bottom_all .fa{
            font-size: 45px; 
            margin: 20px;
            margin-top:30px;
            margin-bottom:6px;
            color: #fff
        }
        .bottom_title{
            color: #fff;
            font-size: 18px;
            font-weight: bold;
        }
        .bottom_all_content{
            color: #fff;
            font-weight: bold;
            font-size: 25px;
            margin-top: 10px;
            text-shadow: 1px 1px 1px #4e4e4e;
        }
        .table_title{
            margin-top:30px;
            font-weight:bold;
            font-size:20px;
        }
        </style>

        <script>

        var code = '' ;
        $(document).ready(function() {
            
            // get code
            getCode() ;
            getList() ; 

            setInterval(function(){ getCode() ; }, 3000 ) ;
            setInterval(function(){ getList() ; }, 10000 ) ;

            $('.bottom_punch').on('click', function(){
                $("#staff_idno").val('') ;
                $('#modal-1').modal('show');
                return false ;
            });

            $("#click_to_submit").submit(function(){
                var staff_idno = $("#staff_idno").val() ;
                if ( staff_idno != '' ){

                    $.ajax({
                        url : 'hr-attendance.php?page_mode=selfpunch&staff_idno='+staff_idno,
                        type : 'get',
                        dataType : 'json',
                        success : function(result) {
                            if ( result['status'] == '200' ){
                                $("#staff_idno").val('') ;
                                $('#modal-1').modal('hide');

                                if ( result['alert'] != '' ){
                                    $('#snackbar').text(result['alert']) ;

                                    // Get the snackbar DIV
                                    // Add the "show" class to DIV
                                    // After 3 seconds, remove the show class from DIV
                                    var x = document.getElementById("snackbar") ;
                                    x.className = "show" ;
                                    setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000) ;
                                }

                            }else{
                                alert(result['message']) ;
                            }
                        }
                    }) ;

                }else{
                    alert('Please enter your Staff IDno.') ;
                }
                return false ;
            }) ;

            function getCode(){

                $.ajax({
                    url : 'hr-attendance.php?page_mode=qrcode-check',
                    type : 'post',
                    data : { 'type': 'checkin', 'qrcode': code },
                    dataType : 'json',
                    success : function(result) {

                        var data = result['data'] ;
                
                        if ( result['status'] == '200' ){
                            code = data['code'] ;
                            $("#qrcode_box").html('<img src="'+code+'" />') ;
                        }

                        if ( data['alert'] != '' ){
                            $('#snackbar').text(data['alert']) ;

                            // Get the snackbar DIV
                            // Add the "show" class to DIV
                            // After 3 seconds, remove the show class from DIV
                            var x = document.getElementById("snackbar") ;
                            x.className = "show" ;
                            setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000) ;
                        }

                    }
                }) ;
            }

            // check value
            function checkValue(v){
                var foo = false;
                if( v != null && v != undefined && v != "" ){
                    foo = true;
                }                
                return foo;
            }

            function getList(){

                $.ajax({
                    url  : 'hr-attendance.php?page_mode=list-limit',
                    type : 'get',
                    data : {},
                    dataType : 'json',
                    success : function(result) {
                        if ( result['status'] == '200' ){
                            var data = result['data'] ;
                            $(".bottom_center_present").html( data['present'] ) ;
                            $(".bottom_center_late").html( data['late'] ) ;
                            $(".bottom_center_absent").html( data['absent'] ) ;
                        }
                    }
                }) ;
            }

        }) ;
        </script>

        <script>
        function date_time(id){
            date = new Date;
            year = date.getFullYear();
            month = date.getMonth();
            months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
            d = date.getDate();
            day = date.getDay();
            days = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
            h = date.getHours() ;
            a = 'AM' ;
            if ( h >= 12 ){
                a = 'PM' ;
            }
            if ( h > 12 ){
                h = h - 12 ;
            }
            if ( h < 10 ){
                h = "0"+h ;
            }
            m = date.getMinutes();
            if ( m < 10 ){
                m = "0"+m ;
            }
            s = date.getSeconds();
            if ( s < 10 ){
                s = "0"+s ;
            }
            result  = '' ;
            result += '<div class="clock_time">' ;
                result += '<span class="clock_time_real">'+h+':'+m+'</span>' ;
                result += '<span class="clock_time_ap">'+a+'</span>' ;
            result += '</div>' ;
            result += '<div class="clock_day">' ;
                result += '<span class="clock_time_date">'+d+' '+months[month]+' '+year+'</span>' ;
                result += '<span class="clock_time_day">'+days[day]+'</span>' ;
            result += '</div>' ;
            $('#'+id).html(result) ;
            setTimeout('date_time("'+id+'");','1000');
            return true;
        }
        </script>
        <script type="text/javascript">window.onload = date_time('date_time');</script>

        <!-- Header Ends -->
        <div class="warper container-fluid">    
            <div class="page-header"><h1><?= $lang['Qrcode']?> <small><?= $lang['scan']?></small></h1></div>

                <div class="panel panel-default">
                    <div class="panel-heading"></div>
                    <div class="panel-body">

                        <div class="form-group">
                            <div class="col-sm-12">
                                <div class="clearfix">
                                    <div class="left_box">
                                        <div id="qrcode_box">
                                            <img src="../images/white.jpg" />
                                        </div>
                                    </div>
                                    <div class="right_box">
                                        <div id="date_time">&nbsp;</div>
                                    </div>
                                </div>

                                <br>
                                <br>

                                <div class="bottom_box">
                                    <div>
                                        <a href="#" class="bottom_all bottom_present">
                                            <i class="fa fa-users" aria-hidden="true"></i>
                                            <div class="bottom_title">PRESENT</div>
                                            <div class="bottom_all_content bottom_center_present">0</div>
                                        </a>
                                        <a href="#" class="bottom_all bottom_late">
                                            <i class="fa fa-window-close" aria-hidden="true"></i>
                                            <div class="bottom_title">LATE</div>
                                            <div class="bottom_all_content bottom_center_late">0</div>
                                        </a>
                                        <a href="#" class="bottom_all bottom_absent">
                                            <i class="fa fa-window-close" aria-hidden="true"></i>
                                            <div class="bottom_title">ABSENT</div>
                                            <div class="bottom_all_content bottom_center_absent">0</div>
                                        </a>
                                        <a href="#" class="bottom_all bottom_punch">
                                            <i class="fa fa-id-card" aria-hidden="true"></i>
                                            <div class="bottom_title">PUNCH CARD</div>
                                            <div class="bottom_all_content bottom_center_punch">CLICK</div>
                                        </a>
                                    </div>

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

        <div id="snackbar">&nbsp;</div>

        <div class="modal modal-default fade" id="modal-1">
            <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 modal1title" style="text-align:center;"><?= $lang['Self Punch']?></h4>
                    </div>

                    <form method="post" id="click_to_submit">
                        <div class="modal-body" style="height: 65px;">
                            <div class="form-group clearfix">
                                <label class="control-label col-md-3 col-sm-3 col-xs-12"><?= $lang['Staff'].' '.$lang['ID No']?><font color="red">*</font></label>
                                <div class="col-md-9 col-sm-7 col-xs-12">
                                    <input type="text" class="form-control modaldata" name="staff_idno" id="staff_idno" placeholder="Staff Qrcode" />
                                </div>                  
                            </div>
                        </div>
                        
                        <div class="modal-footer">
                            <div class="form-group clearfix">
                                <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>

                    </form>

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

        <a href="#" class="scrollup"><?= $lang['Scroll']?></a>

        <?php

    break ;

    case 'report' :

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

        $date_array = [
            'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
        ] ;

        $search_name                = escapeString($_GET['search_name']) ;
        $search_idno                = escapeString($_GET['search_idno']) ;
        $search_country             = escapeString($_GET['search_country']) ;
        $search_branch              = escapeString($_GET['search_branch']) ;
        $search_department          = ($_GET['search_department']) ;
        $date_time                  = escapeString($_GET['date_time']) ;
        $date_time                  = ( $date_time != '' ? $date_time : date('Y-m', time()) ) ;
        $month_of_day               = $date_time.'-01' ;
        $month_of_last              = date( 'Y-m-t', strtotime( $month_of_day ) ) ;
        $year_of_day                = date( 'Y-01-01', strtotime( $month_of_day ) ) ;
        $date_from                  = ($date_from == '' ? date("Y-m-01",strtotime($date_time)) : $date_from);
        $date_to                    = ($date_to == '' ? date("Y-m-t",strtotime($date_time)) : $date_to);

        $search_url                 = '&search_name='.$search_name.'&search_idno='.$search_idno.'&search_country='.$search_country.'&search_branch='.$search_branch.'&date_time='.$date_time.'&search_department='.$search_department ;

        $export                     = escapeString($_GET['export']) ;

        $search_query               = '' ;
        $search_join                = '' ;
        $check_department           = false ;
        if ( $search_department    != '' ){
            $check_department       = true ;
            if( arrayCheck($search_department) ){
                $search_join        = 'LEFT JOIN staff_department c ON (b.staff_id = c.staff_id)
                                       LEFT JOIN setting_department_translation d ON (d.department_id = c.department_id)' ;
                $search_query      .= " AND c.department_id IN (".implode(',',$search_department).")" ;
                $search_query      .= " AND c.deleted_at IS NULL AND d.lang = 'en'" ;
                foreach($search_department as $k => $v ){
                    $search_department_url .= '&search_department%5B'.$k.'%5D='.$v;
                }
            }
        }

        if ( $search_name           != '' ){
            $search_query           .= " AND ( b.staff_name LIKE '%".$search_name."%' )" ;
        }
        if ( $search_idno           != '' ){
            $search_query           .= " AND ( b.staff_idno LIKE '%".$search_idno."%' )" ;
        }
        if ( $search_country        != '' ){
            if ( $search_country    == 'local' ){
                $search_query       .= " AND b.country_id = '1'" ;
            }else{
                $search_query       .= " AND b.country_id != '1'" ;
            }
        }
        if ( $search_branch         != '' ){
            $search_query           .= " AND b.branch_id = '".$search_branch."'" ;
        }

        if ( $date_to != '' || $date_from != '' ){
            if ($date_from != '' && $date_to != ''){
                $search_query       .= " AND a.list_date BETWEEN '".$date_from."' and '".$date_to."'" ;
            }else if ( $date_from != '' ){
                $search_query       .= " AND a.list_date >= '".$date_from."'" ;
            }else{
                $search_query       .= " AND a.list_date <= '".$date_to."'" ;
            }
        }

        $mysqli_page      = $mysqli->query("SELECT b.staff_id, b.staff_idno, b.staff_name FROM staff_attendance_list a
                                            LEFT JOIN staff b ON ( a.staff_id = b.staff_id )
                                            ".$search_join."
                                            WHERE b.deleted_at IS NULL AND ( b.staff_date_resigned IS NULL OR b.staff_date_resigned = '0000-00-00' OR b.staff_date_resigned >= '".$date_time."' ) AND a.deleted_at IS NULL AND a.list_date LIKE '%".$date_time."%' ".$search_query.$user_branch_permission_sql_b."
                                            GROUP BY a.staff_id
                                            ORDER BY b.staff_idno") ;

        if ( $export == 'report-month' ){
            include 'hr-attendance-export-by-month.php' ;
        }
        // if ( $export == 'report-daily' ){
        //     include 'hr-attendance-export-by-daily.php' ;
        // }

        // 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' ;
        ?>

        <!-- Header Ends -->
        <div class="warper container-fluid">    
            <div class="page-header">
                <h1><?= $lang['attendance']?> <small><?= $lang['report']?></small></h1>
                <div class="clearfix">
                    <div style="float: right;">
                        <?php if ( permissionCheck($row_user, 'attendance-attendance-reprocessing') ){ ?>
                            [ <a href="hr-attendance.php?page_mode=reprocessing" target="_blank"><?= $lang['Reprocessing']?></a> ]
                            <br />
                        <?php } ?>
                        [ <a href="<?= '?page_mode='.$page_mode.$search_url.$search_department_url.'&date_from='.$date_from.'&date_to='.$date_to.'&export=report-month' ?>" target="_blank">Export Excel By Month</a> ]
                    </div>
                </div>
            </div>

            <div class="panel panel-default" id="basic-table-title">
                <div class="panel-heading"></div>
                <div class="panel-body">

                    <div class="form-group">
                        <div class="col-sm-12 control-label">
                            <form method="get" class="form-horizontal" style="max-width:600px;">
                                <div class="form-group">
                                    <label class="col-sm-2 control-label"><?= $lang['Name']?></label>
                                    <div class="col-sm-9">
                                        <input type="text" name="search_name" value="<?= $search_name ?>" class="form-control" />
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label"><?= $lang['ID No']?></label>
                                    <div class="col-sm-9">
                                        <input type="text" name="search_idno" value="<?= $search_idno ?>" class="form-control" />
                                    </div>
                                </div>
                                <div class="form-group" style="display: none;">
                                    <label class="col-sm-2 control-label"><?= $lang['L_F']?></label>
                                    <div class="col-sm-9">
                                        <select name="search_country" class="form-control">
                                            <option value=""><?= $lang['All']?></option>
                                            <option value="local" <?= $search_country == 'local' ? 'selected' : '' ?> ><?= $lang['Local']?></option>
                                            <option value="foreigner" <?= $search_country == 'foreigner' ? 'selected' : '' ?> ><?= $lang['Foreigner']?></option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group" style="display: none;">
                                    <label class="col-sm-2 control-label"><?= $lang['Department']?></label>
                                    <div class="col-sm-9">
                                        <select name="search_department[]" class="chosen-select select2-basic-single form-control" multiple >
                                            <?php
                                            // department check list
                                            $department     = [] ;
                                            $get_department = $mysqli->query("SELECT a.department_id, b.department_desc FROM setting_department a
                                                                              LEFT JOIN setting_department_translation b ON ( a.department_id = b.department_id )
                                                                              WHERE a.deleted_at IS NULL AND b.lang = 'en'") ;
                                            if ( $get_department->num_rows > 0 ){
                                                while ( $row_department = $get_department->fetch_assoc() ){
                                                    
                                                    $department[$row_department['department_id']] = $row_department['department_desc'] ;
                                                }
                                            }

                                            foreach ( $department as $kk => $vv ){
                                                $selected = '';
                                                
                                                if(arrayCheck($_GET['search_department'])){
                                                    if(in_array("$kk", $_GET['search_department'], TRUE)){
                                                         $selected = 'selected';
                                                    }
                                                }
                                                echo '<option value="'.$kk.'" '.$selected.'>'.$vv.'</option>' ;
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group" style="display: none;">
                                    <label class="col-sm-2 control-label"><?= $lang['branch']?></label>
                                    <div class="col-sm-9">
                                        <select name="search_branch" class="form-control">
                                            <option value=""><?= $lang['All']?></option>
                                            <?php
                                            foreach ( $branch as $kk => $vv ){
                                                echo '<option value="'.$kk.'" '.( $search_branch == $kk ? 'selected' : '' ).' >'.$vv.'</option>' ;
                                            }
                                            ?>
                                        </select>
                                    </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="date_from" value="<?=date('Y-m-d',strtotime($date_from))?>"  class="form-control" min="<?= date("Y-m-01",strtotime($date_time))?>" max="<?=date("Y-m-t",strtotime($date_time))?>"/>
                                    </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="date_to" value="<?=date('Y-m-d',strtotime($date_to))?>"  class="form-control" min="<?= date("Y-m-01",strtotime($date_time))?>" max="<?=date("Y-m-t",strtotime($date_time))?>"/>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-sm-11">
                                        <input type="hidden" name="page_mode" value="<?= $page_mode ?>" />
                                        <input type="hidden" name="date_time" value="<?= $date_time ?>" />
                                        <button type="submit" class="btn btn-purple" style="float:right"><?= $lang['submit']?></button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                </div>
            </div>

            <div class="panel panel-default">
                <div class="panel-heading"></div>
                <div class="panel-body">

                    <div class="form-group">
                        <div class="col-sm-12">

                            <div class="box-tools col-sm-12 col-md-12 col-lg-12" style="text-align: center; margin: 20px;">
                                <a href="?page_mode=<?= $page_mode.$search_url ?>&date_time=<?= date('Y-m', strtotime($date_time.' -1 month')) ?>" class="btn btn-purple width_auto"><?= $lang['Prev Month']?></a>
                                <?php
                                echo '<span style="margin-left:10px; margin-right:10px;">'.$date_time.'</span>' ;
                                if ( $date_time >= date('Y-m', time()) ){}else{
                                    ?>
                                    <a href="?page_mode=<?= $page_mode.$search_url ?>&date_time=<?= date('Y-m', strtotime($date_time.' +1 month')) ?>" class="btn btn-purple width_auto"><?= $lang['Next Month']?></a>
                                    <?php
                                }
                                ?>
                            </div>

                        </div>
                    </div>

                    <div class="form-group">
                        <div class="col-sm-12">

                            <table class="table table-striped jambo_table bulk_action table-bordered" id="basic-datatable-column-2">
                                <thead>
                                    <tr class="headings">
                                        <th class="column-title text-right"><?= $lang['Action']?></th>
                                        <th class="column-title text-center">ID</th>
                                        <th class="column-title text-center"><?= $lang['Staff']?></th>

                                        <?php
                                        $array_typelist = [
                                            'PT' => 'Partime Day',
                                            'WD' => 'Working Day',
                                            'AL' => 'Annual Leave',
                                            'MC' => 'Sick Leave',
                                            'UL' => 'Unpaid Leave',
                                            'AS' => 'Absent',
                                            'HL' => 'Holiday',
                                            'OD' => 'Off Day'
                                        ] ; 
                                        $default_typelist = [] ;
                                        foreach ( $array_typelist as $ktypelist => $vtypelist ){ $default_typelist[$ktypelist] = 0 ; ?> 
                                            <?php if ( $ktypelist != 'PT' && $ktypelist != 'HL' && $ktypelist != 'OD' ){ ?>
                                                <th class="column-title text-center"><?= $vtypelist ?></th>
                                            <?php } ?>
                                        <?php } ?>
                                        <th class="column-title text-center">Late</th>
                                        <th class="column-title text-center">Early Out</th>
                                        <th class="column-title text-center">OT</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $get_result                = 'failed' ;
                                    $get_list                  = '' ;
                                    if ( $mysqli_page->num_rows > 0 ){

                                        $get_result            = 'success' ;

                                        $new_attendance        = array() ;
                                        $staff_ids             = array() ;
                                        while ( $attendance    = $mysqli_page->fetch_assoc() ){
                                            $temp_attendance   = [
                                                'staff_id'     => $attendance['staff_id'],
                                                'idno'         => $attendance['staff_idno'],
                                                'name'         => $attendance['staff_name']
                                            ] ;

                                            $new_attendance[$attendance['staff_id']] = $temp_attendance ;
                                            $staff_ids[]       = $attendance['staff_id'] ;
                                        }




                                        // get working day
                                        $list_workday          = [] ;
                                        $select_attendancelist = $mysqli->query("SELECT staff_id, list_type_remark, COUNT( list_type_remark ) as count_list_type_remark, SUM( list_work_day ) as sum_list_work_day, SUM( list_leave_day ) as sum_list_leave_day FROM staff_attendance_list
                                                                                 WHERE deleted_at IS NULL AND list_date LIKE '".$date_time."%' AND staff_id IN ( ".implode(',', $staff_ids)." )
                                                                                 GROUP BY staff_id, list_type_remark") ;

                                        if ( $select_attendancelist->num_rows > 0 ){
                                            while ( $row_attendancelist = $select_attendancelist->fetch_assoc() ){
                                                $list_workday[$row_attendancelist['staff_id']][$row_attendancelist['list_type_remark']] = $row_attendancelist ;
                                            }
                                        }


                                        // get staff leave
                                        $list_leave            = [] ;
                                        $select_leavelist      = $mysqli->query("SELECT staff_id, leave_type, leave_record_days FROM staff_leave_year
                                                                                 WHERE deleted_at IS NULL AND leave_year LIKE '".date( 'Y', strtotime( $date_time.'-01' ) )."%' AND staff_id IN ( ".implode(',', $staff_ids)." )") ;
                                        if ( $select_leavelist->num_rows > 0 ){
                                            while ( $row_leavelist = $select_leavelist->fetch_assoc() ){
                                                $list_leave[$row_leavelist['staff_id']][$row_leavelist['leave_type']] = $row_leavelist ;
                                            }
                                        }

                                        // get staff given leave
                                        $list_leave_given      = [] ;
                                        $select_leavegivenlist = $mysqli->query("SELECT staff_id, SUM(given_day) as total_given_day FROM staff_leave_month
                                                                                 WHERE deleted_at IS NULL AND given_date BETWEEN '".$year_of_day."' AND '".$month_of_day."' AND staff_id IN ( ".implode(',', $staff_ids)." )
                                                                                 GROUP BY staff_id ") ;
                                        if ( $select_leavegivenlist->num_rows > 0 ){
                                            while ( $row_leavegivenlist = $select_leavegivenlist->fetch_assoc() ){
                                                $list_leave_given[$row_leavegivenlist['staff_id']] = $row_leavegivenlist['total_given_day'] ;
                                            }
                                        }

                                        // get staff total use leave
                                        $list_leave_used       = [] ;
                                        $select_leave_usedlist = $mysqli->query("SELECT staff_id, list_type_remark, SUM( list_leave_day ) as sum_list_leave_day FROM staff_attendance_list
                                                                                 WHERE deleted_at IS NULL AND list_date BETWEEN '".$year_of_day."' AND '".$month_of_last."' AND list_type_remark IN ( 'AL', 'MC' ) AND staff_id IN ( ".implode(',', $staff_ids)." )
                                                                                 GROUP BY staff_id, list_type_remark") ;

                                        if ( $select_leave_usedlist->num_rows > 0 ){
                                            while ( $row_leave_usedlist = $select_leave_usedlist->fetch_assoc() ){
                                                $list_leave_used[$row_leave_usedlist['staff_id']][$row_leave_usedlist['list_type_remark']] = $row_leave_usedlist['sum_list_leave_day'] ;
                                            }
                                        }



                                        // get late
                                        $list_late             = [] ;
                                        $select_latelist       = $mysqli->query("SELECT staff_id, count( list_late ) as count_list_late, SEC_TO_TIME(sum(TIME_TO_SEC(list_late))) as sum_list_late FROM staff_attendance_list
                                                                                 WHERE deleted_at IS NULL AND list_date LIKE '".$date_time."%' AND staff_id IN ( ".implode(',', $staff_ids)." ) AND list_late != '00:00:00'
                                                                                 GROUP BY staff_id") ;

                                        if ( $select_latelist->num_rows > 0 ){
                                            while ( $row_late  = $select_latelist->fetch_assoc() ){
                                                $list_late[$row_late['staff_id']] = [
                                                    'count' => $row_late['count_list_late'],
                                                    'sum'   => $row_late['sum_list_late']
                                                ] ;
                                            }
                                        }


                                        // get early out
                                        $list_earlyout         = [] ;
                                        $select_earlyoutlist   = $mysqli->query("SELECT staff_id, count( list_early_out ) as count_list_early_out, SEC_TO_TIME(sum(TIME_TO_SEC(list_early_out))) as sum_list_early_out FROM staff_attendance_list
                                                                                 WHERE deleted_at IS NULL AND list_date LIKE '".$date_time."%' AND staff_id IN ( ".implode(',', $staff_ids)." ) AND list_early_out != '00:00:00'
                                                                                 GROUP BY staff_id") ;

                                        if ( $select_earlyoutlist->num_rows > 0 ){
                                            while ( $row_earlyoutlist = $select_earlyoutlist->fetch_assoc() ){
                                                $list_earlyout[$row_earlyoutlist['staff_id']] = [
                                                    'count' => $row_earlyoutlist['count_list_early_out'],
                                                    'sum'   => $row_earlyoutlist['sum_list_early_out']
                                                ] ;
                                            }
                                        }


                                        // get ot
                                        $list_ot               = [] ;
                                        $select_otlist         = $mysqli->query("SELECT staff_id, count( list_ot_normal ) as count_list_ot_normal, SEC_TO_TIME(sum(TIME_TO_SEC(list_ot_normal))) as sum_list_ot_normal FROM staff_attendance_list
                                                                                 WHERE deleted_at IS NULL AND list_date LIKE '".$date_time."%' AND staff_id IN ( ".implode(',', $staff_ids)." ) AND list_ot_normal != '00:00:00'
                                                                                 GROUP BY staff_id") ;

                                        if ( $select_otlist->num_rows > 0 ){
                                            while ( $row_otlist = $select_otlist->fetch_assoc() ){
                                                $list_ot[$row_otlist['staff_id']] = [
                                                    'count' => $row_otlist['count_list_ot_normal'],
                                                    'sum'   => $row_otlist['sum_list_ot_normal']
                                                ] ;
                                            }
                                        }

                                        
                                        // render table
                                        foreach ( $new_attendance as $key => $value ){
                                            echo '
                                            <tr>
                                                <td class="text-center">
                                                    <a href="?page_mode=report-list&date_time='.$date_time.'&staff_id='.$value['staff_id'].'" align="center" target="_blank"><i class="fa fa-edit "></i></a>
                                                </td>
                                                <td class="text-center">'.$value['idno'].'</td>
                                                <td>'.ucwords($value['name']).'</td>' ;

                                                $array_tablelist             = [] ;
                                                $total_workday               = 0 ;
                                                $total_realwork              = 0 ;

                                                $get_late                    = checkExists( $list_late[$value['staff_id']]['count'] ) ;
                                                $get_sum_late                = checkExists( $list_late[$value['staff_id']]['sum'] ) ;
                                                $get_earlyout                = checkExists( $list_earlyout[$value['staff_id']]['count'] ) ;
                                                $get_sum_earlyout            = checkExists( $list_earlyout[$value['staff_id']]['sum'] ) ;
                                                $get_ot                      = checkExists( $list_ot[$value['staff_id']]['count'] ) ;
                                                $get_sum_ot                  = checkExists( $list_ot[$value['staff_id']]['sum'] ) ;

                                                $get_leave                   = $list_leave[$value['staff_id']] ;
                                                $get_leave_annual            = $get_leave['annual'] ;
                                                $get_leave_sick              = $get_leave['sick'] ;

                                                $get_leave_used              = $list_leave_used[$value['staff_id']] ;
                                                $get_leave_annual_used       = $get_leave_used['AL'] ;
                                                $get_leave_sick_used         = $get_leave_used['MC'] ;

                                                $get_leave_annual_given      = $list_leave_given[$value['staff_id']] ;

                                                foreach ( $array_typelist as $ktypelist => $vtypelist ){
                                                    $get_workday             = checkExists( $list_workday[$value['staff_id']][$ktypelist] ) ;
                                                    $days                    = 0 ;
                                                    $total_realwork         += $get_workday['sum_list_work_day'] ;

                                                    switch ( $ktypelist ){
                                                        case 'WD' :
                                                        case 'PT' :
                                                        case 'AL' :
                                                        case 'MC' :
                                                        case 'UL' :
                                                        case 'AS' :
                                                            $total_workday  += $get_workday['count_list_type_remark'] ;
                                                        break ;
                                                    }




                                                    switch ( $ktypelist ){
                                                        case 'WD' :
                                                        case 'PT' :
                                                            $days            = $get_workday['sum_list_work_day'] ;
                                                        break ;
                                                        case 'AL' :
                                                        case 'MC' :
                                                        case 'UL' :
                                                            $days            = $get_workday['sum_list_leave_day'] ;
                                                        break ;
                                                        case 'AS' :
                                                        case 'HL' :
                                                        case 'OD' :
                                                            $days            = $get_workday['count_list_type_remark'] ;
                                                        break ;
                                                    }




                                                    if ( $ktypelist != 'WD' && $ktypelist != 'PT' && $ktypelist != 'HL' && $ktypelist != 'OD' ){

                                                        $temp_typelist         = '' ;
                                                        $days                  = ( $days + 0 ) ;

                                                        switch ( $ktypelist ){
                                                            case 'AL' :
                                                                $temp_typelist = '<td class="text-center">' ;
                                                                    if ( $get_leave_annual['leave_record_days'] > 0 ){
                                                                        $temp_typelist .= ( $days > 0 ? '<b style="color:#f00;">'.$days.'</b>' : '-' ) .' / '.( $get_leave_annual_given - $get_leave_annual_used + 0 ) .' / '.( $get_leave_annual['leave_record_days'] + 0 ) . ' ( '.( $get_leave_annual_given + 0 ).' )' ;
                                                                    }
                                                                $temp_typelist     .= '</td>' ;
                                                            break ;
                                                            case 'MC' :
                                                                $temp_typelist = '<td class="text-center">'. ( $days > 0 ? '<b style="color:#f00;">'.$days.'</b>' : '-' ) .' / '.( $get_leave_sick['leave_record_days'] - $get_leave_sick_used + 0 ) .' / '.( $get_leave_sick['leave_record_days'] + 0 ).'</td>' ;
                                                            break ;
                                                            case 'UL' :
                                                                $temp_typelist = '<td class="text-center">'. ( $days > 0 ? '<b style="color:#f00;">'.$days.'</b>' : '' ) .'</td>' ;
                                                            break ;
                                                            default   :
                                                                $temp_typelist = '<td class="text-center">'. ( $days > 0 ? $days : 0 ) .'</td>' ;
                                                        }

                                                        $array_tablelist[]   = $temp_typelist ;
                                                    }    
                                                }

                                                echo '<td class="text-center"><b>' . $total_realwork . ' / ' . $total_workday . '</b></td>' ;
                                                echo implode( '', $array_tablelist ) ;

                                                echo '<td class="text-center">'.( $get_late     > 0 ? $get_late . ' ( ' . $get_sum_late . ' )' : '' ).'</td>' ;
                                                echo '<td class="text-center">'.( $get_earlyout > 0 ? $get_earlyout . ' ( ' . $get_sum_earlyout . ' )' : '' ).'</td>' ;
                                                echo '<td class="text-center">'.( $get_ot > 0 ? $get_ot . ' ( ' . $get_sum_ot . ' )' : '' ).'</td>' ;

                                            echo '
                                            </tr>' ;
                                        }

                                    }
                                    ?>
                                </tbody>
                            </table>

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

        </div>

        <?php

    break ;

    case 'report-list' :

        $staff_id         = escapeString($_GET['staff_id']) ;
        $date_time        = escapeString($_GET['date_time']) ;
        $date_time        = ( $date_time != '' ? $date_time : date('Y-m', time()) ) ;
        $mysqli_page      = $mysqli->query("SELECT * FROM staff_attendance_list a
                                            WHERE a.staff_id = '".$staff_id."' AND a.list_date LIKE '%".$date_time."%' AND a.deleted_at IS NULL ORDER BY a.list_date ASC") ;

        // get staff information
        $staff            = $mysqli->query("SELECT staff_idno, staff_name FROM staff
                                            WHERE staff_id = '".$staff_id."' LIMIT 1") ;
        $staff_name       = '' ;
        $staff_idno       = '' ;
        if ( $staff->num_rows > 0 ){
            $row_staff    = $staff->fetch_assoc() ;
            $staff_name   = $row_staff['staff_name'] ;
            $staff_idno   = $row_staff['staff_idno'] ;
        }

        // get all attendance time
        $attendances      = $mysqli->query("SELECT list_id, created_at FROM staff_attendance
                                            WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' AND check_group LIKE '%".$date_time."%' ORDER BY created_at ASC") ;
        $attendances_list = [] ;
        if ( $attendances->num_rows > 0 ){
            while ( $row  = $attendances->fetch_assoc() ){
                $attendances_list[$row['list_id']][] = $row ;
            }
        }

        // 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' ;
        ?>

        <!-- Header Ends -->
        <div class="warper container-fluid">    
            <div class="page-header"><h1><?= $lang['attendance']?> <small><?= $lang['report']?> <?= $lang['list']?></small></h1></div>

                <div class="panel panel-default">
                    <div class="panel-heading">
                        ID   : <?= $staff_idno ?><br />
                        <?= $lang['Name']?> : <?= $staff_name ?>
                    </div>
                    <div class="panel-body">

                        <div class="form-group">
                            <div class="col-sm-12">

                                <table class="ui-table table table-striped jambo_table bulk_action table-bordered stripe row-border order-column table_hover_change_color" id="basic-datatable-column-2">
                                    <thead>
                                        <tr class="headings">
                                            <th class="column-title text-center">Date</th>
                                            <th class="column-title text-center">Day</th>
                                            <th class="column-title text-center">Work day</th>
                                            <?php for ( $a = 0 ; $a < 8 ; $a++ ){ ?>
                                                <th class="column-title text-center"><?= ( $a%2 == 0 ? 'In' : 'Out' ) ?></th>
                                            <?php } ?>
                                            <?php if (EXCELDETAIL == "YES"){ ?>
                                                <th class="column-title text-center">Work Day</th>
                                                <th class="column-title text-center">T Day</th>
                                            <?php } ?>
                                            <th class="column-title text-center">Work</th>
                                            <th class="column-title text-center">Rest 1</th>
                                            <th class="column-title text-center">Rest Timeout 1</th>
                                            <th class="column-title text-center">Rest 2</th>
                                            <th class="column-title text-center">Rest Timeout 2</th>
                                            <th class="column-title text-center">Early</th>
                                            <th class="column-title text-center">Late</th>
                                            <th class="column-title text-center">Early Out</th>
                                            <th class="column-title text-center">OT</th>
                                            <th class="column-title text-center">Remark</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                        $date_array = [ 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' ] ;
                                        
                                        $total_early      = 0 ;
                                        $total_late       = 0 ;
                                        $total_rest1      = 0 ;
                                        $total_rest2      = 0 ;
                                        $total_work       = 0 ;
                                        $total_ot         = 0 ;
                                        $total_weekend_ot = 0 ;
                                        $total_holiday_ot = 0 ;

                                        if ( $mysqli_page->num_rows > 0 ){
                                            while ( $value        = $mysqli_page->fetch_assoc() ){

                                                $date             = date('w', strtotime($value['list_date'])) ;
                                                $date             = $date_array[$date] ;

                                                $attendances_date = $attendances_list[$value['list_id']] ;

                                                $bg_color         = '' ;

                                                switch ( $value['list_type_remark'] ){
                                                    case 'WD' : $bg_color = '' ;        break ;
                                                    case 'AL' : $bg_color = '#ffccf0' ; break ;
                                                    case 'UL' : $bg_color = '#fff6cc' ; break ;
                                                    case 'MC' : $bg_color = '#ffd9cc' ; break ;
                                                    case 'AS' : $bg_color = '#ffcccc' ; break ;
                                                    case 'HL' : $bg_color = '#ccfffd' ; break ;
                                                    case 'OD' : $bg_color = '#daccff' ; break ;
                                                    case 'PT' : $bg_color = '#ffd5d1' ; break ;
                                                }

                                                echo '
                                                <tr>
                                                    <td class="align_center" '.( $bg_color != '' ? 'style="background-color:'.$bg_color.'"' : '' ).'>'. $value['list_date'] .'</td>
                                                    <td class="align_center">'. $lang[$date] .'</td>
                                                    <td class="align_center">'.( $value['list_work_day'] > 0 ? '<b>'.$value['list_work_day'].'</b>' : $value['list_work_day'] ).'</td>' ;

                                                    for ( $a = 0 ; $a < 8 ; $a++ ){
                                                        $current_time = $attendances_date[$a]['created_at'] ;
                                                        $current_time = ( $current_time != '' ? date('H:i:s', strtotime($current_time)) : '' ) ;
                                                        echo '
                                                        <td class="align_center">
                                                            <div class="dataTable_width">'. $current_time .'</div>
                                                        </td>' ;
                                                    }
                                                    if ( EXCELDETAIL == "YES" ){
                                                        echo ' 
                                                        <td class="align_center">'. ( $value['list_work_day'] != '0.00' ? $value['list_work_day'] : '' ) .'</td>
                                                        <td class="align_center">'. ( $value['list_ot_day'] != '0.00' ? $value['list_ot_day'] : '' ) .'</td> ';
                                                    }

                                                   
                                                   echo '
                                                    <td class="align_center">'. ( $value['list_work'] != '00:00:00' ? $value['list_work'] : '' ) .'</td>
                                                    <td class="align_center">
                                                        '. ( $value['list_rest'] != '00:00:00' ? $value['list_rest'] : '' ) .'
                                                        '. ( $value['list_time_off'] != '00:00:00' ? '( '.$value['list_time_off'].' )' : '' ) .'
                                                    </td>
                                                    <td class="align_center">'. ( $value['list_rest_more'] != '00:00:00' ? $value['list_rest_more'] : '' ) .'</td>
                                                    <td class="align_center">
                                                        '. ( $value['list_rest2'] != '00:00:00' ? $value['list_rest2'] : '' ) .'
                                                        '. ( $value['list_time_off2'] != '00:00:00' ? '( '.$value['list_time_off2'].' )' : '' ) .'
                                                    </td>
                                                    <td class="align_center">'. ( $value['list_rest_more2'] != '00:00:00' ? $value['list_rest_more2'] : '' ) .'</td>
                                                    <td class="align_center">'. ( $value['list_early'] != '00:00:00' ? $value['list_early'] : '' ) .'</td>
                                                    <td class="align_center">'. ( $value['list_late'] != '00:00:00' ? $value['list_late'] : '' ) .'</td>
                                                    <td class="align_center">'. ( $value['list_early_out'] != '00:00:00' ? $value['list_early_out'] : '' ) .'</td>
                                                    <td class="align_center">'. ( $value['list_ot_normal'] != '00:00:00' ? $value['list_ot_normal'] : '' ) .'</td>
                                                    <td class="align_center">'. $value['list_remark'] .'</td>
                                                </tr>' ;
                                            }
                                        }
                                        ?>
                                    </tbody>
                                </table>

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

        <?php

    break ;

    case 'reprocessing-list' :

        $hidden_reprocess = escapeString($_POST['hidden_reprocess']) ;
        $working_hour     = ($_POST['working_hour']) ;
        $staff_id         = escapeString($_GET['staff_id']) ;
        $date_time        = escapeString($_GET['date_time']) ;
        $date_time        = ( $date_time != '' ? $date_time : date('Y-m', time()) ) ;
        $last_day         = date('t', strtotime($date_time)) ;

        $required_reprocess = array();

        if($hidden_reprocess == '1'){
            if(arrayCheck($working_hour)){
                foreach ($working_hour as $key => $value) {
                    if ( $value != '' ){
                        $required_reprocess[$key] = $value ;
                    }                    
                }

                if(arrayCheck($required_reprocess)){
                    foreach ($required_reprocess as $key => $value) {
                        $u_saw = "UPDATE staff_attendance_working SET deleted_at = '".TODAYDATE."' WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' AND working_date = '".$key."'  " ;
                        $mysqli->query($u_saw) ;

                        // get staff working hours
                        $working_q2 = $mysqli->query("SELECT group_id, working_on, working_next_day, working_if_flexi, working_if_include_rest, working_if_ot, working_direct_day, working_if_fixed_work, working_day_calculation, working_morning_start as working_period_from, working_morning_end as working_period_to, working_period_before, working_break_start as working_from, working_break_end as working_to, working_total_hours, working_total_rest_hours, working_rest_range_from, working_rest_range_to, working_rounding_ot, working_if_ot_morning, working_if_offduty, working_count_offduty, working_if_deduct_offduty, working_max_ot,working_total_rest_hours2,working_rest_range_from2,working_rest_range_to2 FROM setting_working
                                                     WHERE deleted_at IS NULL AND group_id = '".$value."' AND working_day = '".date('N', strtotime($key))."' LIMIT 1") ;
                        
                        // check if working setting got set
                        if ( $working_q2->num_rows > 0 ){
                            $working                 = $working_q2->fetch_assoc() ;
                            $mysqli->query("INSERT INTO staff_attendance_working
                                            (staff_id, working_group_id, working_date, working_on, working_next_day, working_if_flexi, working_if_include_rest, working_if_ot, working_direct_day, working_if_fixed_work, working_day_calculation, working_period_from, working_period_to, working_period_before, working_from, working_to, working_total_hours, working_total_rest_hours, working_rest_range_from, working_rest_range_to, working_rounding_ot, working_if_ot_morning, working_if_offduty, working_count_offduty, working_if_deduct_offduty, working_max_ot, created_at, updated_at, working_total_rest_hours2, working_rest_range_from2, working_rest_range_to2) VALUES
                                            ('".$staff_id."', '".$working['group_id']."', '".$key."', '".$working['working_on']."', '".$working['working_next_day']."', '".$working['working_if_flexi']."', '".$working['working_if_include_rest']."', '".$working['working_if_ot']."', '".$working['working_direct_day']."', '".$working['working_if_fixed_work']."', '".$working['working_day_calculation']."', '".$working['working_period_from']."', '".$working['working_period_to']."', '".$working['working_period_before']."', '".$working['working_from']."', '".$working['working_to']."', '".$working['working_total_hours']."', '".$working['working_total_rest_hours']."', ".( $working['working_rest_range_from'] != '' ? "'".$working['working_rest_range_from']."'" : "NULL" ).", ".( $working['working_rest_range_to'] != '' ? "'".$working['working_rest_range_to']."'" : "NULL" ).", '".$working['working_rounding_ot']."', '".$working['working_if_ot_morning']."', '".$working['working_if_offduty']."', '".$working['working_count_offduty']."', '".$working['working_if_deduct_offduty']."', '".$working['working_max_ot']."', '".TODAYDATE."', '".TODAYDATE."','".$working['working_total_rest_hours2']."','".$working['working_rest_range_from2']."','".$working['working_rest_range_to2']."')") ;
                            
                        }

                    }
                }
            }
            header('Location: hr-attendance.php?page_mode=reprocessing-list&date_time='.$date_time.'&staff_id='.$staff_id.'&a=1') ;
            exit ;
        }

        $mysqli_page      = $mysqli->query("SELECT * FROM staff_attendance_list a
                                            WHERE a.staff_id = '".$staff_id."' AND a.list_date LIKE '%".$date_time."%' AND a.deleted_at IS NULL ORDER BY a.list_date ASC") ;

        // get staff information
        $staff            = $mysqli->query("SELECT staff_idno, staff_name FROM staff
                                            WHERE staff_id = '".$staff_id."' LIMIT 1") ;
        $staff_name       = '' ;
        $staff_idno       = '' ;
        if ( $staff->num_rows > 0 ){
            $row_staff    = $staff->fetch_assoc() ;
            $staff_name   = $row_staff['staff_name'] ;
            $staff_idno   = $row_staff['staff_idno'] ;
        }

        // get all attendance time
        $attendances      = $mysqli->query("SELECT staff_id, list_id, created_at FROM staff_attendance
                                            WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' AND check_group LIKE '%".$date_time."%' ORDER BY created_at ASC") ;
        $attendances_list = [] ;
        if ( $attendances->num_rows > 0 ){
            while ( $row  = $attendances->fetch_assoc() ){
                $attendances_list[$row['list_id']][] = $row ;
            }
        }

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

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

        <!-- Header Ends -->
        <div class="warper container-fluid">    
            <div class="page-header"><h1><?= $lang['Reprocessing']?> <small> <?= $lang['list']?></small></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']) ;
                }
                ?>
                <div class="panel panel-default">
                    <div class="panel-heading">
                        ID   : <?= $staff_idno ?><br />
                        <?= $lang['Name']?> : <?= $staff_name ?>
                    </div>
                    <div class="panel-body">

                        <div class="form-group">
                            <div class="col-sm-12">

                                <div class="box-tools col-sm-12 col-md-12 col-lg-12" style="text-align: center; margin: 20px;">
                                    <a href="?page_mode=reprocessing-list&staff_id=<?= $staff_id ?>&date_time=<?= date('Y-m', strtotime($date_time.' -1 month')) ?>" class="width_auto"><?= $lang['Prev Month']?></a>
                                    <div class="datepicker_box" style="display: inline-block;">
                                        <span style="margin-left:10px; margin-right:10px;">
                                            <input type="text" readonly name="date_time" style="text-align: center;" value="<?= $date_time ?>">
                                        </span>
                                    </div>
                                    <a href="?page_mode=reprocessing-list&staff_id=<?= $staff_id ?>&date_time=<?= date('Y-m', strtotime($date_time.' +1 month')) ?>" class="width_auto"><?= $lang['Next Month']?></a>
                                </div>

                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-sm-12">
                                <form method="post" action="hr-attendance.php?page_mode=reprocessing-list&date_time=<?=$date_time?>&staff_id=<?=$staff_id?>">
                                    <table class="ui-table table table-striped jambo_table bulk_action table-bordered stripe row-border order-column" id="basic-datatable-column-2">
                                        <thead>
                                            <tr class="headings">
                                                <th class="column-title text-center"><?= $lang['date']?></th>
                                                <th class="column-title text-center"><?= $lang['Day']?></th>
                                                <th class="column-title text-center"><?= $lang['InOut']?></th>
                                                <th class="column-title text-center"><?= $lang['Working Hour']?></th>
                                                <!--<th class="column-title text-center"><?= $lang['Reprocessing']?></th>-->
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $date_array = [
                                                'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'
                                            ] ;
                                            
                                            $total_early      = 0 ;
                                            $total_late       = 0 ;
                                            $total_rest       = 0 ;
                                            $total_work       = 0 ;
                                            $total_ot         = 0 ;
                                            $total_weekend_ot = 0 ;
                                            $total_holiday_ot = 0 ;

                                            $arr_work = array();
                                            $mysqli_work = "SELECT group_id, group_name FROM setting_working_group
                                                             WHERE deleted_at IS NULL";
                                            $mwk = $mysqli->query($mysqli_work);
                                            if ($mwk->num_rows > 0){
                                                while ($rmwk = $mwk->fetch_array(MYSQLI_ASSOC)){
                                                    $arr_work[] = $rmwk;
                                                }
                                            }

                                            $attendances = [] ;
                                            if ( $mysqli_page->num_rows > 0 ){
                                                while ( $value = $mysqli_page->fetch_assoc() ){
                                                    $attendances[$value['list_date']] = $value ;
                                                }
                                            }

                                            for ( $loop = 1 ; $loop <= $last_day ; $loop++ ){

                                                $select_date      = $date_time.'-'.strPad(2, $loop) ;
                                                $select_day_w     = date('w', strtotime($select_date)) ;
                                                $select_day_w     = $date_array[$select_day_w] ;

                                                $value            = $attendances[$select_date] ;
                                                $attendances_date = $attendances_list[$value['list_id']] ;

                                                echo '
                                                <tr>
                                                
                                                    <td class="align_center">'. $select_date .'</td>
                                                    <td class="align_center">'. $lang[$select_day_w] .'</td>
                                                    <td class="align_center">' ;

                                                        for ( $a = 0 ; $a < 8 ; $a++ ){
                                                            $current_time = $attendances_date[$a]['created_at'] ;
                                                            $current_time = ( $current_time != '' ? date('H:i:s', strtotime($current_time)) : '' ) ;
                                                            echo '<div>'. $current_time .'</div>' ;
                                                        }

                                                    echo '
                                                    </td>
                                                    <td class="align_center">
                                                        <select name="working_hour['.$select_date.']" class="chosen-select form-control select2-basic-single">
                                                            <option value="">'.$lang['Choose Work hour'].'</option>' ;

                                                        $aw  = "SELECT working_group_id FROM staff_attendance_working 
                                                                WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' AND working_date = '".$select_date."' LIMIT 1" ;
                                                        $maw = $mysqli->query($aw) ;
                                                        $selected_group_id = '';
                                                        if ($maw->num_rows > 0){
                                                            $rmaw = $maw->fetch_array(MYSQLI_ASSOC);
                                                            $selected_group_id = $rmaw['working_group_id'];
                                                        }

                                                        if(arrayCheck($arr_work)){
                                                            foreach ( $arr_work as $key => $v ) {
                                                                $selected = '';
                                                                if ( $selected_group_id == $v['group_id']){ $selected = 'selected' ; }
                                                                echo '<option value="'.$v['group_id'].'" '.$selected.'>'.$v['group_name'].'</option>';
                                                            }
                                                        }
                                                        echo '
                                                        </select>
                                                    </td>
                                                    <!--
                                                    <td class="align_center">
                                                        <label style="width:100%;">
                                                            <input type="checkbox" name="checkbox['.$select_date.']" value="'.$select_date.'"/>
                                                        </label>                                                    
                                                    </td>
                                                    -->
                                                
                                                </tr>' ;
                                            }
                                            ?>
                                        </tbody>
                                    </table>
                                    <input type="hidden" name="hidden_reprocess" value="1">
                                    <button type="submit" class="btn btn-purple" style="float: right;"><?= $lang['submit']?></button>
                                </form>
                            </div>
                        </div>
                        
                    </div>
                </div>
            </form>
        </div>

        <?php

    break ;

    case 'list' :

        $redirect_to = 'hr-attendance-format-2.php?sort_by=staff_idno&sort_by_type=ASC' ; 
        header("Location: ".$redirect_to) ;
        exit ;

    break ;

    case 'reprocessing' :

        $redirect_to = 'hr-attendance-reprocessing.php?sort_by=staff_idno&sort_by_type=ASC' ;
        header("Location: ".$redirect_to) ;
        exit ;

    break ;

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