<?php
declare(strict_types=1);

namespace App\Modules\Reports\Services;

final class ReportExporter
{
    public static function toCsv(array $data, array $definition): string
    {
        $columns = $data['columns'] ?? [];
        $rows = $data['rows'] ?? [];

        $output = '';
        if (!empty($columns)) {
            $output .= implode(',', array_map(fn($v) => '"' . str_replace('"', '""', $v) . '"', array_values($columns))) . "\n";
        }

        $colKeys = array_keys($columns);
        foreach ($rows as $row) {
            $line = [];
            foreach ($colKeys as $key) {
                $val = $row[$key] ?? '';
                $line[] = '"' . str_replace('"', '""', (string) $val) . '"';
            }
            $output .= implode(',', $line) . "\n";
        }

        return $output;
    }
}