<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
?>
<?php

include("../config.php");
// Headers for CSV download
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=attendance_export.csv");
header("Pragma: no-cache");
header("Expires: 0");

$output = fopen("php://output", "w");

// Column headers
fputcsv($output, ["ID", "Employee ID", "Full Name", "Login Time", "Logout Time"]);

// SQL with JOIN and full name
$sql = "
    SELECT 
        attendance.id,
        attendance.employee_id, 
        CONCAT(register.fname, ' ', register.lname) AS full_name, 
        attendance.login_time, 
        attendance.logout_time 
    FROM attendance
    INNER JOIN register ON attendance.employee_id = register.employee_id
    ORDER BY attendance.id ASC
";

$result = mysqli_query($conn, $sql);

// Output formatted rows
while ($row = mysqli_fetch_assoc($result)) {
    $loginTime  = $row['login_time']  ? date("Y-m-d H:i:s", strtotime($row['login_time'])) : '---';
    $logoutTime = $row['logout_time'] ? date("Y-m-d H:i:s", strtotime($row['logout_time'])) : '---';

    fputcsv($output, [
        $row['id'],
        $row['employee_id'],
        $row['full_name'],
        $loginTime,
        $logoutTime
    ]);
}

fclose($output);
exit;
?>
