<?php

declare(strict_types=1);

namespace PpPhp\Core\DataOps\Formats;

use PpPhp\Core\DataOps\ExportFormat;

/** Comma-separated values — the universal interchange format. */
final class CsvFormat implements ExportFormat
{
    public static function id(): string { return 'csv'; }
    public static function label(): string { return 'CSV'; }
    public static function icon(): array { return ['bi-filetype-csv', 'var(--pp-fmt-csv,#0d9488)']; }
    public static function extension(): string { return 'csv'; }
    public static function contentType(): string { return 'text/csv; charset=utf-8'; }

    public function write(array $rows, array $columns, array $meta): void
    {
        $out = fopen('php://output', 'w');
        if (($meta['includeHeaders'] ?? true) !== false) {
            fputcsv($out, array_values($columns), ',', '"', '\\');
        }
        foreach ($rows as $r) {
            $line = [];
            foreach (array_keys($columns) as $c) $line[] = (string) ($r[$c] ?? '');
            fputcsv($out, $line, ',', '"', '\\');
        }
        fclose($out);
    }
}
