<?php
declare(strict_types=1);

namespace App\Helpers;

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

class ExportHelper
{
    public static function exportCSV(array $headers, array $rows, string $filename = 'export.csv'): void
    {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');

        $output = fopen('php://output', 'w');
        fputcsv($output, $headers);
        foreach ($rows as $row) {
            fputcsv($output, (array)$row);
        }
        fclose($output);
        exit;
    }

    public static function exportExcel(array $headers, array $rows, string $filename = 'export.xlsx'): void
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

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

        // Add data
        $rowIdx = 2;
        foreach ($rows as $row) {
            $col = 'A';
            foreach ((array)$row as $value) {
                $sheet->setCellValue($col . $rowIdx, $value);
                $col++;
            }
            $rowIdx++;
        }

        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;
    }

    public static function exportPDF(string $html, string $filename = 'report.pdf', string $orientation = 'P'): void
    {
        try {
            $mpdf = new Mpdf([
                'mode' => 'utf-8',
                'format' => 'A4',
                'orientation' => $orientation,
                'margin_left' => 10,
                'margin_right' => 10,
                'margin_top' => 10,
                'margin_bottom' => 10,
            ]);
            
            $mpdf->SetTitle($filename);
            $mpdf->WriteHTML($html);
            $mpdf->Output($filename, 'D');
            exit;
        } catch (\Exception $e) {
            die("PDF Generation Error: " . $e->getMessage());
        }
    }
}
