<?php
$must_login             = true ;
$require_path           = '../../' ;
$require_sub            = '../' ;
require( $require_sub.'header.php' ) ;

// if ( $boolean_login ){
    $status             = '300' ;

    $branch_name        = '' ;

    // Hr       = All staff without branch
    // HrBranch = All staff with branch
    // HrManual = For M&R only

    $is_show            = 'no' ;
    $is_filterbranch    = 'no' ;
    $services           = $mysqli->query( "SELECT a.module FROM app_service a
                                           WHERE a.deleted_at IS NULL AND a.type = 'service' AND a.module IN ( 'Hr', 'HrBranch', 'HrManual' ) AND on_off = 'on' 
                                           LIMIT 2" ) ;

    if ( $services->num_rows > 0 ){
        while ( $row_service = $services->fetch_assoc() ){
            if ( $row_service['module'] == 'Hr' ){
                $is_show         = 'yes' ;
            }
            if ( $row_service['module'] == 'HrBranch' ){
                $is_show         = 'yes' ;
                $is_filterbranch = 'yes' ;
            }
            if ( $row_service['module'] == 'HrManual' ){
                $is_show         = 'manual' ;
                $is_filterbranch = 'yes' ;
            }
        }
    }

    if ( $array['module']   == 'branch' ){
        $is_show         = 'yes' ;
        $is_filterbranch = 'yes' ;

        if ( $array['branch_id'] != '' ){
            $get_branch  = $mysqli->query("SELECT branch_name FROM branch
                                           WHERE deleted_at IS NULL AND branch_id = '".$array['branch_id']."' LIMIT 1") ;
            if ( $get_branch->num_rows > 0 ){
                $branch  = $get_branch->fetch_assoc() ;

                $branch_name = $branch['branch_name'] ;
            }
        }
    }


    $list               = [] ;

    $total_staffs       = 0 ;
    $present            = 0 ;
    $late               = 0 ;
    $rest_late          = 0 ;
    $absent             = 0 ;
    $merit              = 0 ;
    $passionate         = 0 ;
    $in_off             = 0 ;
    $in_mc              = 0 ;
    $in_leave           = 0 ;
    $in_off_working     = 0 ;
    $error              = 0 ;
    $present_list       = [] ;
    $late_list          = [] ;
    $rest_late_list     = [] ;
    $absent_list        = [] ;
    $off_list           = [] ;
    $mc_list            = [] ;
    $leave_list         = [] ;
    $off_working_list   = [] ;
    $merit_list         = [] ;
    $passionate_list    = [] ;

    $yesterday_day      = date('N', strtotime('-1 days')) ;
    $today_day          = date('N', time()) ;
    $date_yesterday     = date('Y-m-d', strtotime('-1 days')) ;
    $date_today         = date('Y-m-d', time()) ;
    $date_next          = date('Y-m-d', strtotime('+1 days')) ;

    if ( $is_show      == 'yes' ){

        // filter department
        $check_department   = false;
        if( $department_id  > 0 ){
            $check_department = true ;           
            $search_query1 .= " AND a.department_id = '".$department_id."'" ; 
        }

        // loop all group
        $working_q      = $mysqli->query("SELECT group_id, working_day, working_next_day, working_on, working_morning_start as working_period_from, working_morning_end as working_period_to, working_break_start as working_from, working_break_end as working_to, working_break_end_include_ot as working_to_include_ot, working_max_ot, working_period_before, working_total_rest_hours FROM setting_working 
                                          WHERE deleted_at IS NULL AND group_id > '0' AND ( working_day = '".$yesterday_day."' OR working_day = '".$today_day."' )") ;
        $row_working = [] ;
        if ( $working_q->num_rows > 0 ){
            while ( $working = $working_q->fetch_assoc() ){
                $row_working[$working['group_id']][$working['working_day']] = $working ;
            }
        }

        // get all last checkin attendace
        $attendance_q   = $mysqli->query( "SELECT staff_id, MAX(created_at) AS created_at FROM staff_attendance
                                           WHERE deleted_at IS NULL 
                                           GROUP BY staff_id" ) ;
        $row_attendance = [] ;
        if ( $attendance_q->num_rows > 0 ){
            while ( $attendance = $attendance_q->fetch_assoc() ){
                $row_attendance[$attendance['staff_id']] = $attendance['created_at'] ;
            }
        }

        // get all last 4 checkin attendace
        $attendance_2days_q   = $mysqli->query( "SELECT staff_id, created_at FROM staff_attendance
                                                 WHERE deleted_at IS NULL AND list_id = '0' AND '".date( 'Y-m-d', time() )." 23:59:59'" ) ;
        $row_attendance_2days = [] ;
        if ( $attendance_2days_q->num_rows > 0 ){
            while ( $attendance_2days = $attendance_2days_q->fetch_assoc() ){
                $row_attendance_2days[$attendance_2days['staff_id']][] = $attendance_2days['created_at'] ;
            }
        }

        // get all mc / unpaid / annual today
        $leave_q = $mysqli->query("SELECT staff_id, leave_type FROM staff_leave_date
                                   WHERE deleted_at IS NULL AND leave_type_mode = 'working' AND leave_date = '".$date_today."'") ;
        $row_leave = [] ;
        if ( $leave_q->num_rows > 0 ){
            while ( $leave = $leave_q->fetch_assoc() ){
                $row_leave[$leave['staff_id']] = $leave['leave_type'] ;
            }
        }

        // get all staff
        $staffs_q = $mysqli->query( "SELECT staff_id, staff_idno, staff_name, staff_image, group_id FROM staff
                                     WHERE ( staff_date_resigned IS NULL || staff_date_resigned = '0000-00-00' || staff_date_resigned >= '".$date_today."' ) AND deleted_at IS NULL ".( $is_filterbranch == 'yes' ? " AND branch_id = '".$array['branch_id']."'" : '' )."
                                     ORDER BY (staff_idno+0)" ) ;


        if ( $staffs_q->num_rows > 0 ){

            $status    = '200' ;

            $row_staff = [] ;
            while ( $staff   = $staffs_q->fetch_assoc() ){

                if( $check_department ){
                    $mysqli_department = $mysqli->query( "SELECT a.department_id, b.department_desc FROM staff_department a
                                                          LEFT JOIN setting_department_translation b ON ( b.department_id = a.department_id )
                                                          WHERE a.deleted_at IS NULL AND b.lang = '".$array['lang']."' AND a.staff_id = '".$staff['staff_id']."'".$search_query1 ) ;
                    $count = 0 ;
                    $department_name = '' ;
                    if( $mysqli_department->num_rows > 0 ){
                        while( $row_department = $mysqli_department->fetch_assoc() ){
                            $count++ ;

                            $break = '' ;
                            if( $count == 3 ){
                                $break = "\n" ;
                                $count = 0 ;
                            }

                            $department_name .= $row_department['department_desc'].', '.$break ;
                        }
                        $department_name = substr( $department_name, 0, -2 ) ;

                        if( $department_name != '' ){
                            $row_staff[] = $staff ;
                        }
                    }
                }else{
                    $row_staff[] = $staff ;
                }
            }


            foreach ( $row_staff as $staff ){

                $total_staffs++ ;

                $this_working   = $row_working[$staff['group_id']] ;
                $this_type      = '' ;
                $attendance     = '' ;
                $last_late      = '' ;

                if ( arrayCheck( $this_working ) ){

                    // get staff attendance
                    $attendance             = $row_attendance[$staff['staff_id']] ;
                    $attendance_all         = $row_attendance_2days[$staff['staff_id']] ;
                    $attendance_first       = ( isset($attendance_all[0]) ? $attendance_all[0] : '' ) ;

                    // check if mc / unpaid / annual leave today
                    $get_leave              = $row_leave[$staff['staff_id']] ;
                    if ( $get_leave        != '' ){

                        if ( $get_leave    == 'sick' ){
                            $in_mc++ ;
                            $this_type      = 'mc' ;
                        }
                        if ( $get_leave    == 'unpaid' ){
                            $in_leave++ ;
                            $this_type      = 'leave' ;
                        }
                        if ( $get_leave    == 'annual' ){
                            $in_leave++ ;
                            $this_type      = 'leave' ;
                        }

                    }else{

                        // check today day working
                        $working                = $this_working[$today_day] ;

                        $check_current_datetime = $date_today.' '.$working['working_period_from'] ;
                        $check_next_datetime    = $date_next.' '.$working['working_period_to'] ;
                        $working_from           = $date_today.' '.$working['working_from'] ;
                        if ( $working['working_period_before'] > 0 ){
                            $working_from       = $date_today.' '.addTime( $working['working_from'], convertToTimes($working['working_period_before']) ) ;
                        }

                        $working_to             = $date_today.' '.$working['working_to'] ;
                        $working_to_include_ot  = $date_today.' '.$working['working_to_include_ot'] ;
                        $working_max_ot         = $working['working_max_ot'] ;

                        if ( $working_from      > $working_to ){
                            $working_to         = $date_next.' '.$working['working_to'] ;
                        }
                        if ( $working['working_to_include_ot'] != '' && $working['working_to_include_ot'] != '00:00:00' ){
                            $working_to         = $date_next.' '.$working['working_to_include_ot'] ;
                        }


                        if ( $working_max_ot   != '' && $working_max_ot != '00:00:00' ){
                            $convertMinutes     = convertMinutes($working_max_ot) ;
                            $working_to         = date("Y-m-d H:i:s", strtotime($working_to . ' + '.$convertMinutes.' minutes')) ;
                        }

                        // check if allow to insert attendances
                        if ( TODAYDATE         >= $check_current_datetime ){

                            // this guys is working within this day

                        }else{

                            if ( $attendance   >= $working_to ){

                                // this guys is working within this day

                            }else{

                                if ( date('Y-m-d', strtotime($attendance)) == $yesterday_day ){

                                    // check yesterday day working
                                    $working                = $this_working[$yesterday_day] ;
                                    $check_current_datetime = $date_yesterday.' '.$working['working_period_from'] ;
                                    $check_next_datetime    = $date_today.' '.$working['working_period_to'] ;
                                    $working_from           = $date_yesterday.' '.$working['working_from'] ;
                                    $working_to             = $date_yesterday.' '.$working['working_to'] ;
                                    $working_max_ot         = $working['working_max_ot'] ;

                                    if ( $working_from > $working_to ){
                                        $working_to         = $date_today.' '.$working['working_to'] ;
                                    }
                                    if ( $working['working_to_include_ot'] != '' && $working['working_to_include_ot'] != '00:00:00' ){
                                        $working_to         = $date_today.' '.$working['working_to_include_ot'] ;
                                    }
                                    
                                }

                            }
                        }

                        $working_to_10      = date("Y-m-d H:i:s", strtotime($working_to . ' + 10 hours')) ;

                        if ( $working['working_if_flexi'] == 'yes' ){
                            $working_from   = $check_current_datetime ;
                            $working_to     = $check_next_datetime ;
                        }

                        if ( $working["working_on"] == "yes" ){

                            // check if within working period
                            if ( TODAYDATE >= $check_current_datetime && TODAYDATE <= $working_to ){

                                if ( $attendance_first >= $check_current_datetime && $attendance_first <= $working_to ){
                                    if ( $attendance_first >= $working_from ){
                                        $late++ ;
                                        $this_type = 'late' ;
                                        $last_late = subtractTime( $attendance_first, $working_from ) ;
                                    }else{

                                        $present++ ;
                                        $this_type = 'working' ;

                                        if ( count( $attendance_all ) == 2 || count( $attendance_all ) == 3 ){
                                            $rest_out         = $attendance_all[1] ;
                                            $rest_in          = ( count( $attendance_all ) == 3 ? $attendance_all[2] : TODAYDATE ) ;

                                            $total_rest       = subtractTime( $rest_in, $rest_out ) ;
                                            if ( $total_rest  > $working['working_total_rest_hours'] ){
                                                $rest_late++ ;
                                                $this_type    = 'rest_late' ;
                                                $last_late    = subtractTime( $rest_in, $rest_out ) ;
                                            }
                                            $attendance_first = $attendance ;
                                        }
                                        
                                    }
                                }else{

                                    if ( TODAYDATE >= $working_from ){
                                        $absent++ ;
                                        $this_type        = 'absent' ;
                                        $attendance_first = $attendance ;
                                    }
                                }

                            }else{

                                // check absent
                                if ( $attendance >= $check_current_datetime && $attendance <= $check_next_datetime ){

                                    // check error
                                    if ( $attendance >= $check_current_datetime && $attendance <= $working_to_10 ){
                                        // do nothing
                                    }else{
                                        $error++ ;
                                        $this_type = 'error' ;
                                    }

                                }else{

                                    if ( TODAYDATE >= $check_current_datetime && TODAYDATE <= $check_next_datetime ){
                                        $absent++ ;
                                        $this_type        = 'absent' ;
                                        $attendance_first = $attendance ;
                                    }
                                }

                            }

                        }else{
                            if ( $attendance >= $working_from && $attendance <= $check_next_datetime ){
                                $in_off_working++ ;
                                $this_type = 'off_working' ;
                            }else{
                                $in_off++ ;
                                $this_type = 'off' ;
                            }
                        }
                    }

                    $temp = [
                        'staff_id'         => $staff['staff_id'],
                        'staff_image'      => PATH . ( $staff['staff_image'] != '' ? 'uploads/Staff/'.$staff['staff_image'] : 'images/NoProduct.jpg' ),
                        'staff_idno'       => $staff['staff_idno'],
                        'staff_name'       => $staff['staff_name'],
                        'last_late'        => ( $last_late != '' ? date( 'H:i', strtotime($last_late) ) : '' ),
                        'last_attendance'  => ( $attendance_first != '' ? $attendance_first : '-' )
                    ] ; 

                    switch ( $this_type ){
                        case 'working'       : $present_list[]       = $temp ; break ;
                        case 'late'          : $late_list[]          = $temp ; break ;
                        case 'rest_late'     : $rest_late_list[]     = $temp ; break ;
                        case 'absent'        : $absent_list[]        = $temp ; break ;
                        case 'off'           : $off_list[]           = $temp ; break ;
                        case 'off_working'   : $off_working_list[]   = $temp ; break ;
                        case 'mc'            : $mc_list[]            = $temp ; break ;
                        case 'leave'         : $leave_list[]         = $temp ; break ;
                        case 'error'         : $error_list[]         = $temp ; break ;
                    }

                }

            }
        }
    }




    if ( $is_show      == 'manual' ){

        $staffs         = $mysqli->query( "SELECT a.type, a.times, b.staff_id, b.staff_image, b.staff_idno, b.staff_name FROM staff_attendance_summary a
                                           LEFT JOIN staff b ON ( a.staff_id = b.staff_id )
                                           WHERE a.deleted_at IS NULL AND b.branch_id = '".$array['branch_id']."'" ) ;
        if ( $staffs->num_rows > 0 ){

            $status    = '200' ;

            while ( $staff = $staffs->fetch_assoc() ){

                $temp = [
                    'staff_id'         => $staff['staff_id'],
                    'staff_image'      => PATH . ( $staff['staff_image'] != '' ? 'uploads/Staff/'.$staff['staff_image'] : 'images/NoProduct.jpg' ),
                    'staff_idno'       => $staff['staff_idno'],
                    'staff_name'       => $staff['staff_name'],
                    'last_attendance'  => $staff['times']
                ] ; 

                if ( $staff['type']   == 'late' ){
                    $late++ ;
                    $late_list[]       = $temp ;
                }

                if ( $staff['type']   == 'absent' ){
                    $absent++ ;
                    $absent_list[]     = $temp ;
                }

                if ( $staff['type']   == 'merit' ){
                    $merit++ ;
                    $merit_list[]      = $temp ;
                }

                if ( $staff['type']   == 'passionate' ){
                    $passionate++ ;
                    $passionate_list[] = $temp ;
                }

            }
        }

    }

    $data = [
        'staff'               => $total_staffs,
        'branch_name'         => dataFilter( $branch_name ),
        'present'             => $present,
        'present_list'        => $present_list,
        'late'                => ( $late + $rest_late ),
        'late_list'           => array_merge( $late_list, $rest_late_list ),
        'absent'              => $absent,
        'absent_list'         => $absent_list,
        'in_off'              => $in_off,
        'off_list'            => $off_list,
        'in_mc'               => $in_mc,
        'mc_list'             => $mc_list,
        'in_leave'            => $in_leave,
        'in_off_working'      => $in_off_working,
        'leave_list'          => $leave_list,
        'off_working_list'    => $off_working_list,
        'merit'               => $merit,
        'merit_list'          => $merit_list,
        'passionate'          => $passionate,
        'passionate_list'     => $passionate_list
    ] ;
// }

require( $require_sub.'footer.php' ) ;
?>