<?php
namespace Crawl\Services;

class ExportService
{
    public function toCsv(array $rows): string
    {
        if (empty($rows)) {
            return "";
        }

        $fh = fopen('php://temp', 'r+');
        fputcsv($fh, array_keys($rows[0]));

        foreach ($rows as $row) {
            fputcsv($fh, array_map(function ($value) {
                if (is_array($value)) {
                    return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                }
                return $value;
            }, $row));
        }

        rewind($fh);
        $csv = stream_get_contents($fh) ?: '';
        fclose($fh);

        return $csv;
    }
}
