<?php

namespace App\Helpers;

use Dompdf\Dompdf;

class Exporter
{
    public static function csv(string $filename, array $headers, array $rows): void
    {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
        $out = fopen('php://output', 'w');
        fputcsv($out, $headers);
        foreach ($rows as $row) {
            fputcsv($out, $row);
        }
        fclose($out);
        exit;
    }

    public static function pdf(string $filename, string $html): void
    {
        if (class_exists(Dompdf::class)) {
            $dompdf = new Dompdf();
            $dompdf->loadHtml($html);
            // Pastikan saiz report A4 potrait
            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();
            $dompdf->stream($filename . '.pdf', ['Attachment' => true]);
            exit;
        }

        header('Content-Type: text/html');
        header('Content-Disposition: attachment; filename="' . $filename . '.html"');
        echo $html;
        exit;
    }
}

