<?php

// default config setting
$boolean_ssl_lock      = true ;

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

$current_times         = date( "H:i:s", time() ) ;
$current_hours         = date( "H", time() ) ;
$current_minutes       = date( "m", time() ) ;

$day_before_3 		   = date( "Y-m-d", strtotime( "-3 days" ) ) ;
$day_before_4 		   = date( "Y-m-d", strtotime( "-4 days" ) ) ;

$today_day 			   = date( "Y-m-d", time() ) ;
$today_datetime        = date( "Ymd", time() ) ;

$search_query          = "" ;
if ( $current_times > '09:40:00' && $current_times <= '14:40:00' ){
	$search_query     .= " AND a.created_at BETWEEN '" . $day_before_3 . " 09:30:00' AND '" . $today_day . " 14:29:59'" ;

	$today_datetime   .= '-1' ;
}else{
	$search_query     .= " AND a.created_at BETWEEN '" . $day_before_4 . " 14:30:00' AND '" . $today_day . " 09:29:59'" ;

	$today_datetime   .= '-2' ;
}

$mysqli_attendances   = $mysqli->query( "SELECT a.created_at, b.staff_idno FROM staff_attendance a
				 				         LEFT JOIN staff b ON ( a.staff_id = b.staff_id )
				 				         WHERE a.deleted_at IS NULL AND CHAR_LENGTH(b.staff_idno) > 6 " . $search_query . "
				 				         ORDER BY a.created_at" ) ;

$filename 			  = '../txt/' . $today_datetime . '.txt' ;
$file 			      = fopen( $filename, "wb" ) ;
fwrite($fp,$content);

if ( $mysqli_attendances->num_rows > 0 ){
	$count 			  = 0 ;
	$total 			  = $mysqli_attendances->num_rows ;

	while ( $row_attendances = $mysqli_attendances->fetch_assoc() ){
		$count++ ;

		$content      = $row_attendances['staff_idno'] . '|' . date( 'Y-m-d', strtotime($row_attendances['created_at']) ) . '|' . date( 'H:i:s', strtotime($row_attendances['created_at']) ) ;

		if ( $count  != $total ){
			$content .= "\n" ;
		}

		fwrite( $file, $content ) ;

	}
}

fclose( $file ) ;




// header("Content-Description: File Transfer"); 
// header("Content-Type: application/octet-stream"); 
// header("Content-Disposition: attachment; filename=\"". basename($filename) ."\"") ; 
// readfile ( $filename ) ;

exit ;

?>