<?php
require 'vendor/autoload.php';
include "koneksi.php";

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

// Ambil tanggal dari form
$tgl1 = $_POST['tanggal1a'];
$tgl2 = $_POST['tanggal2b'];

// Query data
$query = mysqli_query($koneksi, 
    "SELECT tanggal, nama, alamat, tujuan, notel 
     FROM tabtamu 
     WHERE tanggal BETWEEN '$tgl1' AND '$tgl2' 
     ORDER BY id DESC");

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

// ================= HEADER =================
$sheet->setCellValue('A1', 'REKAPITULASI DATA TAMU');
$sheet->mergeCells('A1:F1');

// Header tabel
$sheet->setCellValue('A3', 'No');
$sheet->setCellValue('B3', 'Tanggal');
$sheet->setCellValue('C3', 'Nama');
$sheet->setCellValue('D3', 'Alamat');
$sheet->setCellValue('E3', 'Tujuan');
$sheet->setCellValue('F3', 'No Telepon');

// ================= STYLE HEADER =================
$styleHeader = [
    'font' => [
        'bold' => true,
        'color' => ['rgb' => 'FFFFFF']
    ],
    'fill' => [
        'fillType' => 'solid',
        'startColor' => ['rgb' => '4F81BD']
    ]
];

$sheet->getStyle('A3:F3')->applyFromArray($styleHeader);

// ================= ISI DATA =================
$no = 1;
$row = 4;

while ($data = mysqli_fetch_assoc($query)) {
    $sheet->setCellValue('A'.$row, $no++);
    $sheet->setCellValue('B'.$row, date('d-m-Y', strtotime($data['tanggal'])));
    $sheet->setCellValue('C'.$row, $data['nama']);
    $sheet->setCellValue('D'.$row, $data['alamat']);
    $sheet->setCellValue('E'.$row, $data['tujuan']);
    $sheet->setCellValue('F'.$row, $data['notel']);
    $row++;
}

// ================= AUTO WIDTH =================
foreach(range('A','F') as $col){
    $sheet->getColumnDimension($col)->setAutoSize(true);
}

// ================= OUTPUT =================
$filename = "Data_Tamu.xlsx";

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment; filename=\"$filename\"");
header('Cache-Control: max-age=0');

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