<?php

namespace App\Services;

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

class ExportService
{
    public function generateXlsx(string $filename, array $headers, array $rows): string
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle('Sheet1');

        $headerStyle = [
            'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
            'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '4472C4']],
            'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER],
            'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN]],
        ];

        $rowStyle = [
            'alignment' => ['vertical' => Alignment::VERTICAL_CENTER, 'wrapText' => true],
            'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN]],
        ];

        $colIdx = 1;
        foreach ($headers as $header) {
            $sheet->setCellValueByColumnAndRow($colIdx, 1, $header);
            $colIdx++;
        }
        $sheet->getStyle('A1:' . $sheet->getHighestColumn() . '1')->applyFromArray($headerStyle);

        $rowNum = 2;
        foreach ($rows as $row) {
            $colIdx = 1;
            foreach ($row as $cell) {
                $value = $cell ?? '';
                if (is_numeric($value) && !is_string($value)) {
                    $sheet->setCellValueByColumnAndRow($colIdx, $rowNum, $value);
                } else {
                    $sheet->setCellValueExplicitByColumnAndRow($colIdx, $rowNum, (string) $value, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
                }
                $colIdx++;
            }
            $rowNum++;
        }

        $lastRow = $rowNum - 1;
        $lastCol = $sheet->getHighestColumn();
        if ($lastRow >= 2) {
            $sheet->getStyle('A2:' . $lastCol . $lastRow)->applyFromArray($rowStyle);
        }

        foreach (range(1, count($headers)) as $colIdx) {
            $sheet->getColumnDimensionByColumn($colIdx)->setAutoSize(true);
        }

        $sheet->setAutoFilter('A1:' . $lastCol . $lastRow);

        $writer = new Xlsx($spreadsheet);
        $tempPath = tempnam(sys_get_temp_dir(), 'export_') . '.xlsx';
        $writer->save($tempPath);

        return $tempPath;
    }
}
