<?php

declare(strict_types=1);

namespace PpPhp\Core\DataOps\Formats;

use PpPhp\Core\DataOps\ExportFormat;

/** XML document — one <record> per row, one element per column. */
final class XmlFormat implements ExportFormat
{
    public static function id(): string { return 'xml'; }
    public static function label(): string { return 'XML'; }
    public static function icon(): array { return ['bi-filetype-xml', 'var(--pp-fmt-xml,#7c3aed)']; }
    public static function extension(): string { return 'xml'; }
    public static function contentType(): string { return 'application/xml; charset=utf-8'; }

    public function write(array $rows, array $columns, array $meta): void
    {
        $root = self::tag((string) ($meta['table'] ?? 'records')) ?: 'records';
        echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<{$root}>\n";
        foreach ($rows as $r) {
            echo "  <record>\n";
            foreach (array_keys($columns) as $c) {
                $t = self::tag($c);
                if ($t === '') continue;
                echo "    <{$t}>" . htmlspecialchars((string) ($r[$c] ?? ''), ENT_XML1 | ENT_QUOTES, 'UTF-8') . "</{$t}>\n";
            }
            echo "  </record>\n";
        }
        echo "</{$root}>\n";
    }

    /** Column names are not guaranteed to be legal XML tags — normalise them. */
    private static function tag(string $name): string
    {
        $t = preg_replace('/[^A-Za-z0-9_.-]/', '_', $name) ?? '';
        return preg_match('/^[A-Za-z_]/', $t) ? $t : ($t === '' ? '' : 'f_' . $t);
    }
}
