<?php

namespace App\Services\Admin;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\StreamedResponse;

/** 将 {@see AdminReportQueryService::reportRows} 的二维数组导出为真实 xlsx。 */
final class AdminReportSpreadsheetExporter
{
    /**
     * @param  list<array<int, string|int|float|null>>  $rows
     */
    public function streamDownload(array $rows, string $filename): StreamedResponse
    {
        return response()->streamDownload(function () use ($rows): void {
            $spreadsheet = new Spreadsheet;
            $sheet = $spreadsheet->getActiveSheet();

            foreach ($rows as $rowIndex => $row) {
                foreach ($row as $colIndex => $cell) {
                    $sheet->setCellValue([$colIndex + 1, $rowIndex + 1], $cell ?? '');
                }
            }

            $writer = new Xlsx($spreadsheet);
            $writer->save('php://output');
            $spreadsheet->disconnectWorksheets();
        }, $filename, [
            'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        ]);
    }
}
