<?php  
require 'vendor/autoload.php'; // Pastikan untuk memuat autoload dari Composer  
  
use PhpOffice\PhpSpreadsheet\Spreadsheet;  
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;  
  
// Load database connection  
require_once('includes/load.php');  
  
// Function to fetch all overtime records  
function fetch_overtime_records() {  
    global $db;  
    $sql = "SELECT oa.*, e.name as employee_name, e.division as employee_division FROM overtime_attendance oa  
            JOIN employees e ON oa.employee_id = e.id  
            ORDER BY oa.overtime_date DESC";  
    return $db->query($sql);  
}  
  
// Fetch all overtime records  
$records = fetch_overtime_records();  
  
// Create a new Spreadsheet object  
$spreadsheet = new Spreadsheet();  
$sheet = $spreadsheet->getActiveSheet();  
  
// Set the header for the Excel file  
$sheet->setCellValue('A1', 'ID');  
$sheet->setCellValue('B1', 'Employee Name');  
$sheet->setCellValue('C1', 'Division');  
$sheet->setCellValue('D1', 'Overtime Date');  
$sheet->setCellValue('E1', 'Start Time');  
$sheet->setCellValue('F1', 'End Time');  
$sheet->setCellValue('G1', 'Hours Worked');  
$sheet->setCellValue('H1', 'Reason');  
  
// Populate the spreadsheet with data  
$row = 2; // Start from the second row  
if ($records && $db->num_rows($records) > 0) {  
    while ($record = $db->fetch_assoc($records)) {  
        $sheet->setCellValue('A' . $row, $record['id']);  
        $sheet->setCellValue('B' . $row, $record['employee_name']);  
        $sheet->setCellValue('C' . $row, $record['employee_division']);  
        $sheet->setCellValue('D' . $row, $record['overtime_date']);  
        $sheet->setCellValue('E' . $row, $record['start_time']);  
        $sheet->setCellValue('F' . $row, $record['end_time']);  
        $sheet->setCellValue('G' . $row, $record['hours_worked']);  
        $sheet->setCellValue('H' . $row, $record['reason']);  
        $row++;  
    }  
}  
  
// Set the filename and output the file  
$filename = 'overtime_report_' . date('Y-m-d') . '.xlsx';  
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');  
header('Content-Disposition: attachment; filename="' . $filename . '"');  
header('Cache-Control: max-age=0');  
  
// Create the writer and save the file to output  
$writer = new Xlsx($spreadsheet);  
$writer->save('php://output');  
exit();  
