<?php
require_once '../includes/functions.php';
requireAdmin();

require_once '../vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

// Ambil semua data guru
$gurus = db_fetchAll("
    SELECT g.*, u.username 
    FROM guru g 
    JOIN users u ON u.id = g.user_id 
    ORDER BY g.nama
");

// Buat spreadsheet
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

// Header
$headers = ['NIP', 'Nama Lengkap', 'Jenis Kelamin', 'Tempat Lahir', 'Tanggal Lahir', 'Pendidikan', 'Status', 'Username'];
foreach (range('A', 'H') as $i => $col) {
    $sheet->setCellValue($col . '1', $headers[$i]);
    $sheet->getStyle($col . '1')->getFont()->setBold(true);
}

// Data
$row = 2;
foreach ($gurus as $guru) {
    $sheet->setCellValue('A' . $row, $guru['nip']);
    $sheet->setCellValue('B' . $row, $guru['nama']);
    $sheet->setCellValue('C' . $row, $guru['jenis_kelamin']);
    $sheet->setCellValue('D' . $row, $guru['tempat_lahir']);
    $sheet->setCellValue('E' . $row, $guru['tanggal_lahir']);
    $sheet->setCellValue('F' . $row, $guru['pendidikan']);
    $sheet->setCellValue('G' . $row, $guru['status']);
    $sheet->setCellValue('H' . $row, $guru['username']);
    $row++;
}

// Auto size columns
foreach (range('A', 'H') as $col) {
    $sheet->getColumnDimension($col)->setAutoSize(true);
}

// Download file
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="data_guru_' . date('Y-m-d') . '.xlsx"');
header('Cache-Control: max-age=0');

$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
exit;
?>