<?php

namespace App\Support;

use Barryvdh\DomPDF\Facade\Pdf;
use Symfony\Component\HttpFoundation\StreamedResponse;

/**
 * Renders a tabular report to CSV (opens in Excel) or PDF, or returns it for
 * on-screen display. Controllers build [title, headings, rows] and pick a format.
 */
class ReportExporter
{
    /** Stream a CSV download. */
    public function csv(string $filename, array $headings, iterable $rows): StreamedResponse
    {
        $headers = [
            'Content-Type' => 'text/csv; charset=UTF-8',
            'Content-Disposition' => 'attachment; filename="'.$filename.'.csv"',
        ];

        return response()->stream(function () use ($headings, $rows) {
            $out = fopen('php://output', 'w');
            fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF)); // UTF-8 BOM for Excel
            fputcsv($out, $headings);
            foreach ($rows as $row) {
                fputcsv($out, $row);
            }
            fclose($out);
        }, 200, $headers);
    }

    /** Build a PDF download from the shared report layout. */
    public function pdf(string $filename, string $title, array $headings, iterable $rows, array $meta = [], string $orientation = 'portrait')
    {
        $pdf = Pdf::loadView('reports.pdf.table', [
            'title' => $title,
            'headings' => $headings,
            'rows' => $rows,
            'meta' => $meta,
            'school' => app(BranchContext::class)->currentId()
                ? \App\Models\Branch::find(app(BranchContext::class)->currentId())?->name
                : config('app.name'),
        ])->setPaper('a4', $orientation);

        return $pdf->download($filename.'.pdf');
    }
}
