<?php 
// Load the database configuration file 
include_once 'Connection.php'; 
// Fetch records from database 

$filename = 'Users_'.date('Y-m-d').'.csv';

// POST values
$from_date = $_POST['from_date'];
$to_date = $_POST['to_date'];

// Select query
$query = "SELECT L.EMPNO,EM.EMPNAME,B.IMAGENAME as IMAGENAME,L.PROCESS as PROCESS ,L.PASS as PASS, L.startTime as startTime, L.EndTime EndTime, 
LEFT(SEC_TO_TIME(TIMESTAMPDIFF(SECOND, L.startTime, L.EndTime)),8) as TDif,LEFT(SEC_TO_TIME(BM.BTD),8) as BTD , IF(BM.BTD < TIMESTAMPDIFF(SECOND, L.startTime, L.EndTime), 'NO', 'YES') AS FinalStatus ,IF(BM.BTD < TIMESTAMPDIFF(SECOND,L.startTime, L.EndTime), LEFT(SEC_TO_TIME((TIMESTAMPDIFF(SECOND, L.startTime, L.EndTime)-BM.BTD)),8), LEFT(SEC_TO_TIME('0'),8)) AS TIMEEXCEED  from LOGIN_FINAL  L left JOIN BATCHES B ON B.BATCHNO = L.BATCHNO left JOIN MASTER_BENCHMARK BM ON BM.PROCESS = CONCAT(L.PROCESS,L.PASS) left JOIN empmaster EM ON EM.EMPNO = L.EMPNO Where left(starttime,10)  ORDER BY L.startTime ,L.EndTime";


$result = mysqli_query($con,$query) or die(mysqli_error($con));
$user_arr = array();
// file creation
$file = fopen($filename,"w");
// Header row - Remove this code if you don't want a header row in the export file.

$user_arr = array("IMAGENAME","PROCESS","startTime","EndTime","TDif","BTD","FinalStatus","TIMEEXCEED"); 
fputcsv($file,$user_arr); 
while($row = mysqli_fetch_array($result)){
   $id                              = $row['id'];
   $IMAGENAME                       = $row['IMAGENAME'];
   $PROCESS                         = $row['PROCESS'];
   $startTime                       = $row['startTime'];
   $EndTime                         = $row['EndTime'];
   $TDif                            = $row['TDif'];
   $BTD                             = $row[' BTD'];
   $FinalStatus                     = $row['FinalStatus'];
   $TIMEEXCEED                      = $row['TIMEEXCEED'];
   
 
   // Write to file 
   $user_arr = array($id,$IMAGENAME ,$PROCESS,$startTime ,$EndTime ,$TDif,$BTD,$FinalStatus,$TIMEEXCEED);
   fputcsv($file,$user_arr); 
}

fclose($file);

// download
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/csv; ");

readfile($filename);

// deleting file
unlink($filename);
exit();