<?php
require_once('includes/load.php');
global $db;

// Pastikan hanya pengguna dengan hak akses tertentu yang dapat mengakses halaman ini
page_require_level(10);

// Mengambil parameter order_sn_list dari permintaan GET
$order_sn_list = isset($_GET['order_sn_list']) ? $_GET['order_sn_list'] : '';

// Mengonversi daftar nomor pesanan menjadi array
$order_sn_array = explode(', ', $order_sn_list);

// Sanitasi input
$order_sn_array = array_map('trim', $order_sn_array);
$order_sn_array = array_filter($order_sn_array, function ($value) {
    return !empty($value);  // Keep only non-empty strings
});
$order_sn_array = array_values($order_sn_array);

// Mempersiapkan kueri SQL
$order_sn_in_clause = "'" . implode("','", $order_sn_array) . "'";
$sql = "SELECT DISTINCT waktu_proses as created_at, invoice, resi, COALESCE(scan_in,'-') as scan_in, COALESCE(scan_status,'-') as scan_status FROM awb WHERE invoice IN ($order_sn_in_clause)";

// Menjalankan kueri
$stmt = $db->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();

// Mengumpulkan data hasil
$data = array();
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}

// Jika tidak ada data, kirim pesan kesalahan
if (empty($data)) {
    http_response_code(404);
    echo json_encode(['error' => 'No data found']);
    exit;
}

// Mengimpor PHPSpreadsheet
require 'vendor/autoload.php';

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

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

// Menambahkan judul kolom
$sheet->setCellValue('A1', 'Created At');
$sheet->setCellValue('B1', 'Invoice');
$sheet->setCellValue('C1', 'Resi');
$sheet->setCellValue('D1', 'Scan In');
$sheet->setCellValue('E1', 'Scan Status');

// Mengisi data ke dalam spreadsheet
$rowIndex = 2;
foreach ($data as $row) {
    $sheet->setCellValue('A' . $rowIndex, $row['created_at']);
    $sheet->setCellValue('B' . $rowIndex, $row['invoice']);
    $sheet->setCellValue('C' . $rowIndex, $row['resi']);
    $sheet->setCellValue('D' . $rowIndex, $row['scan_in']);
    $sheet->setCellValue('E' . $rowIndex, $row['scan_status']);
    $rowIndex++;
}

// Mengatur header untuk mengunduh file Excel
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="order_details.xlsx"');
header('Cache-Control: max-age=0');

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

// Menghancurkan objek Spreadsheet untuk menghemat memori
$spreadsheet->disconnectWorksheets();
unset($spreadsheet);
