<?php
include 'PhpExcel/PHPExcel.php' ;

$page_filename = 'ReportMonth-'.date( str_replace("/","",$dateformat), time() ) ;
$objPHPExcel   = new PHPExcel() ;
$objPHPExcel->getProperties()->setCreator(COMPANY)->setTitle(COMPANY)->setSubject(COMPANY)->setDescription(COMPANY)->setKeywords(COMPANY)->setCategory(COMPANY) ;
$objPHPExcel->getActiveSheet()->setTitle( $page_filename ) ;
$objPHPExcel->setActiveSheetIndex(0);
$objWriter     = PHPExcel_IOFactory::createWriter( $objPHPExcel, 'Excel5' ) ;
$cacheMethod   = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp;
$cacheSettings = array( 
    'memoryCacheSize' => '50MB',
    'cacheTime'       => 1200
) ;
PHPExcel_Settings::setCacheStorageMethod( $cacheMethod, $cacheSettings ) ;

$styleArrayTitle = array(
    'font'  => array(
        'bold'  => true ,
        'color' => array( 'rgb' => '000000' ) ,
        'size'  => 15
    ),
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

$styleArrayDay = array(
    'font'  => array(
        'bold'  => true
    ),
    'borders' => array(
        'outline' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    ),
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
) ;

$styleArrayBg1 = array(
    'fill' => array(
        'type' => PHPExcel_Style_Fill::FILL_SOLID,
        'color' => array('rgb' => 'AFABAB')
    ),
    'borders' => array(
        'outline' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    ),
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
) ;

$styleArrayBg2 = array(
    'fill' => array(
        'type' => PHPExcel_Style_Fill::FILL_SOLID,
        'color' => array('rgb' => 'FFDA65')
    ),
    'borders' => array(
        'outline' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    ),
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
) ;

$styleArray = array(
    'borders' => array(
        'outline' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    ),
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
) ;

$styleArrayLeft = array(
    'borders' => array(
        'outline' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    ),
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
    )
) ;

$styleArray2 = array(
    'alignment' => array(
        //'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
    )
) ;

$styleArrayRed = array(
'font'  => array(
    'color' => array('rgb' => 'FF0000'),
));

$count     = 1 ;
$firstChar = 'A' ;
$lastChar  = 'K';

// title name
$objPHPExcel->getActiveSheet()->mergeCells( $firstChar.$count.':'.$lastChar.$count ) ;
$objPHPExcel->getActiveSheet()->getStyle( $firstChar.$count.':'.$lastChar.$count )->applyFromArray( $styleArrayTitle ) ;
$objPHPExcel->setActiveSheetIndex(0)->setCellValue( $firstChar.$count, 'Attendance Report' ) ;
$count++ ;


$firstChar2        = $firstChar ;
$array_title       = [ 'Employee Code', 'Employee Name', 'Currency Code', 'Rate Type', '#BAS - Basic Salary', '#OT15 - OT 1.5 Hours', '#OT2 - OT 2.0 Hours', '#OT3 - OT 3.0 Hours', '#LTE - Late & Under', '#WDYS - Working Days' ] ;
foreach ( $array_title as $k => $v ){
    $objPHPExcel->setActiveSheetIndex(0)->setCellValue( $firstChar2.$count, $v ) ;
    $firstChar2++ ;
}
$count++ ;










$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'],
            'staff_salary' => $attendance['staff_salary'],
            'ot_rate_type' => $attendance['ot_rate_type'],
            'work_type_id' => $attendance['work_type_id']
        ] ;

        $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 ;
        }
    }


    $list_time_off         = [] ;
    $select_attendancelist = $mysqli->query("SELECT staff_id, list_type_remark, list_time_off, list_time_off2 FROM staff_attendance_list
                                             WHERE deleted_at IS NULL AND list_date LIKE '".$date_time."%' AND staff_id IN ( ".implode(',', $staff_ids)." ) AND ( list_time_off != '00:00:00' OR list_time_off2 != '00:00:00' )") ;

    if ( $select_attendancelist->num_rows > 0 ){
        while ( $row_attendancelist = $select_attendancelist->fetch_assoc() ){
            $get_sum_timeoff        = $list_time_off[$row_attendancelist['staff_id']]['sum'] ;
            $check_sum_timeoff      = ( $get_sum_timeoff != '' ? $get_sum_timeoff : '00:00:00' ) ;

            if ( $row_attendancelist['list_time_off']  != '00:00:00' ){
                $list_time_off[$row_attendancelist['staff_id']]['count'] = ( $list_time_off[$row_attendancelist['staff_id']]['count'] + 1 );
                $list_time_off[$row_attendancelist['staff_id']]['sum']   = addTime( $check_sum_timeoff, $row_attendancelist['list_time_off'] ) ;
            }
            if ( $row_attendancelist['list_time_off2'] != '00:00:00' ){
                $list_time_off[$row_attendancelist['staff_id']]['count'] = ( $list_time_off[$row_attendancelist['staff_id']]['count'] + 1 );
                $list_time_off[$row_attendancelist['staff_id']]['sum']   = addTime( $check_sum_timeoff, $row_attendancelist['list_time_off2'] ) ;
            }
        }
    }




    // 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(TIME_FORMAT(list_late, '%H:%i')))) 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(TIME_FORMAT(list_early_out, '%H:%i')))) 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 rest more
    $list_rest_more             = [] ;
    $select_rest_morelist       = $mysqli->query("SELECT staff_id, count( list_rest_more ) as count_list_rest_more, SEC_TO_TIME(SUM(TIME_TO_SEC(TIME_FORMAT(list_rest_more, '%H:%i')))) as sum_list_rest_more FROM staff_attendance_list
                                             WHERE deleted_at IS NULL AND list_date LIKE '".$date_time."%' AND staff_id IN ( ".implode(',', $staff_ids)." ) AND list_rest_more != '00:00:00'
                                             GROUP BY staff_id") ;

    if ( $select_rest_morelist->num_rows > 0 ){
        while ( $row_rest_more  = $select_rest_morelist->fetch_assoc() ){
            $list_rest_more[$row_rest_more['staff_id']] = [
                'count' => $row_rest_more['count_list_rest_more'],
                'sum'   => $row_rest_more['sum_list_rest_more']
            ] ;
        }
    }



    // get rest more 2
    $list_rest_more2             = [] ;
    $select_rest_more2list       = $mysqli->query("SELECT staff_id, count( list_rest_more2 ) as count_list_rest_more2, SEC_TO_TIME(SUM(TIME_TO_SEC(TIME_FORMAT(list_rest_more2, '%H:%i')))) as sum_list_rest_more2 FROM staff_attendance_list
                                             WHERE deleted_at IS NULL AND list_date LIKE '".$date_time."%' AND staff_id IN ( ".implode(',', $staff_ids)." ) AND list_rest_more2 != '00:00:00'
                                             GROUP BY staff_id") ;

    if ( $select_rest_more2list->num_rows > 0 ){
        while ( $row_rest_more2  = $select_rest_more2list->fetch_assoc() ){
            $list_rest_more2[$row_rest_more2['staff_id']] = [
                'count' => $row_rest_more2['count_list_rest_more2'],
                'sum'   => $row_rest_more2['sum_list_rest_more']
            ] ;
        }
    }


    // 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(TIME_FORMAT(list_ot_normal, '%H:%i')))) 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 ){
        $firstChar2 = $firstChar ;


        $array_tablelist             = [] ;
        $total_workday               = 0 ;
        $total_realwork              = 0 ;
        $total_realworkdays          = 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_timeoff                 = checkExists( $list_time_off[$value['staff_id']]['count'] ) ;
        $get_sum_timeoff             = checkExists( $list_time_off[$value['staff_id']]['sum'] ) ;
        $get_restmore                = checkExists( $list_rest_more[$value['staff_id']]['count'] ) ;
        $get_sum_restmore            = checkExists( $list_rest_more[$value['staff_id']]['sum'] ) ;
        $get_restmore2               = checkExists( $list_rest_more2[$value['staff_id']]['count'] ) ;
        $get_sum_restmore2           = checkExists( $list_rest_more2[$value['staff_id']]['sum'] ) ;

        $total_over_list             = [] ;
        if ( $get_sum_late          != '' ){ $total_over_list[] = $get_sum_late ; }
        if ( $get_sum_earlyout      != '' ){ $total_over_list[] = $get_sum_earlyout ; }
        if ( $get_sum_restmore      != '' ){ $total_over_list[] = $get_sum_restmore ; }
        if ( $get_sum_restmore2     != '' ){ $total_over_list[] = $get_sum_restmore2 ; }

        $total_over                  = 0 ;
        foreach ( $total_over_list as $kover => $vover ){
            $total_over             += convertMinutes( $vover ) ;
        }

        $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'] ;
            $total_realworkdays     += $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'] ;

                    if ( $ktypelist == 'AL' || $ktypelist == 'MC' ){
                        $total_realworkdays += $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 ;
            }    
        }

        $work_type_id = '' ;
        switch ( $value['work_type_id'] ){
            case '1' :
                $work_type_id = 'NORMAL' ;
            break ;
            case '2' :
                $work_type_id = 'DAILY' ;
            break ;
            case '3' :
                $work_type_id = 'HOURLY' ;
            break ;
        }


        $objPHPExcel->setActiveSheetIndex(0)->setCellValue( $firstChar2.$count, $value['idno'] ) ; $firstChar2++ ;
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue( $firstChar2.$count, ucwords($value['name']) ) ; $firstChar2++ ;
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue( $firstChar2.$count, "RM" ) ; $firstChar2++ ;
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue( $firstChar2.$count, $work_type_id ) ; $firstChar2++ ;
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue( $firstChar2.$count, $value['staff_salary'] ) ; $firstChar2++ ;
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue( $firstChar2.$count, ( $value['ot_rate_type'] == '1.5' ? convertMinutes( $get_sum_ot ) : '' ) ) ; $firstChar2++ ;
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue( $firstChar2.$count, ( $value['ot_rate_type'] == '2.0' ? convertMinutes( $get_sum_ot ) : '' ) ) ; $firstChar2++ ;
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue( $firstChar2.$count, ( $value['ot_rate_type'] == '3.0' ? convertMinutes( $get_sum_ot ) : '' ) ) ; $firstChar2++ ;
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue( $firstChar2.$count, ( $total_over > 0 ? $total_over : '' ) ) ; $firstChar2++ ;
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue( $firstChar2.$count, $total_realworkdays ) ; $firstChar2++ ;
        $count++ ;
    }

    // J column 4 decimal
    $objPHPExcel->getActiveSheet()->getStyle('J2:J' . $objPHPExcel->getActiveSheet()->getHighestRow())->getNumberFormat()->setFormatCode('0.0000');

}


// Submission from
header( 'Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) ; 
header( 'Content-Disposition: attachment;filename="'.$page_filename.'.xls"' ) ;
header( 'Cache-Control: max-age=0' ) ;
// save to pc
$objWriter->save('php://output') ;
// header( "Refresh: 0" ) ;
exit ;
?>