<?php
require 'vendor/autoload.php'; // Pastikan Anda sudah menginstal PhpSpreadsheet melalui Composer

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

// Koneksi ke database
require_once('includes/load.php');

// Fungsi untuk mendapatkan semua data tanpa pagination
function get_all_awbs($start, $end)
{
  global $db;
  try {
    $sql = "SELECT * FROM awb WHERE DATE(scan_status) BETWEEN '{$start}' AND '{$end}' ORDER BY scan_status DESC";
    return find_by_sql($sql);
  } catch (Exception $e) {
    return [];
  }
}

// Ambil data berdasarkan tanggal (bisa disesuaikan)
$dateStart = isset($_GET['start']) ? $_GET['start'] : date('Y-m-d');
$dateEnd = isset($_GET['end']) ? $_GET['end'] : date('Y-m-d');
$data = get_all_awbs($dateStart, $dateEnd);

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

// Header kolom
$headers = ['ID', 'Resi', 'Kurir', 'Part Number', 'Product Name', 'Date Scan', 'Quantity', 'Scan Status', 'Packer No', 'Lokasi'];
$sheet->fromArray($headers, NULL, 'A1');

// Isi data
$row = 2; // Mulai dari baris kedua
foreach ($data as $awb) {
  $sheet->setCellValue('A' . $row, $awb['id']);
  $sheet->setCellValue('B' . $row, $awb['resi']);
  $sheet->setCellValue('C' . $row, get_kurir_by_resi(substr($awb['resi'], 0, 3))); // Fungsi untuk mendapatkan kurir
  $sheet->setCellValue('D' . $row, $awb['part_number']);
  $sheet->setCellValue('E' . $row, $awb['product_name']);
  $sheet->setCellValue('F' . $row, $awb['date_scan']);
  $sheet->setCellValue('G' . $row, $awb['quantity']);
  $sheet->setCellValue('H' . $row, $awb['scan_status']);
  $sheet->setCellValue('I' . $row, $awb['packer_no']);
  $sheet->setCellValue('J' . $row, $awb['loc']);
  $row++;
}

// Set nama file
$fileName = 'AWB_Scanned_' . date('Y-m-d') . '.xlsx';

// Header untuk download file Excel
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="' . $fileName . '"');

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