<?php
require_once __DIR__ . '/../config.php';
requireRole(['admin']);
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../lib/logic.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;

$filters = [
    'start_date' => $_GET['start_date'] ?? null,
    'end_date' => $_GET['end_date'] ?? null,
    'supplier' => $_GET['supplier'] ?? null,
    'status' => $_GET['status'] ?? null
];

$orders = exportOrders($filters);

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Orders');

$headers = [
    'OrderID', 'SourceID', 'Buyer', 'Reference', 'ItemCode', 'ItemDescription',
    'UOM', 'ItemCategory', 'ItemGroup', 'GoodType', 'Detail', 'Quantity',
    'UnitPrice', 'GrossPrice', 'Division', 'SupplySource', 'Supplier',
    'Location', 'ReferenceRQ', 'ItemType', 'PO_Date', 'PO_DateApproved',
    'PaymentTerms', 'Source', 'GoodsSupplied'
];

$col = 'A';
foreach ($headers as $header) {
    $sheet->setCellValue($col . '1', $header);
    $col++;
}

$headerStyle = [
    'font' => ['bold' => true],
    'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => 'E0E0E0']],
    'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN]]
];
$sheet->getStyle('A1:' . $col . '1')->applyFromArray($headerStyle);

$rowNum = 2;
foreach ($orders as $o) {
    $col = 'A';
    foreach ($headers as $header) {
        $key = strtolower($header);
        $sheet->setCellValue($col . $rowNum, $o[$key] ?? '');
        $col++;
    }
    $rowNum++;
}

foreach (range('A', $col) as $column) {
    $sheet->getColumnDimension($column)->setAutoSize(true);
}

$filename = 'orders_' . date('Ymd_His') . '.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;