<?php

declare(strict_types=1);

namespace PpPhp\Core\DataOps\Readers;

use PpPhp\Core\DataOps\ImportReader;

/** XML — repeating child elements become rows, their children become columns. */
final class XmlReader implements ImportReader
{
    public static function id(): string { return 'xml'; }
    public static function label(): string { return 'XML'; }
    public static function extensions(): array { return ['xml']; }
    public static function supportsPaste(): bool { return true; }

    public function read(string $path, array $opts): array
    {
        $prev = libxml_use_internal_errors(true);
        $xml = @simplexml_load_file($path);
        libxml_clear_errors();
        libxml_use_internal_errors($prev);
        if ($xml === false) return [[], []];

        $header = [];
        $records = [];
        foreach ($xml->children() as $node) {
            $row = [];
            foreach ($node->children() as $k => $v) {
                $k = (string) $k;
                $header[$k] = true;
                $row[$k] = trim((string) $v);
            }
            if ($row === []) continue;
            $records[] = $row;
        }
        $header = array_keys($header);
        $rows = [];
        foreach ($records as $r) {
            $line = [];
            foreach ($header as $k) $line[] = (string) ($r[$k] ?? '');
            $rows[] = $line;
        }
        return [$header, $rows];
    }
}
