<?php

namespace GriffinForms\Includes\MergeTokens;

class TokenParser
{
    /**
     * Extract JSON merge tokens from content.
     *
     * @param string $content
     * @return array<int,array{raw:string,data:array}>
     */
    public function parse(string $content): array
    {
        if ($content === '') {
            return [];
        }

        $matches = [];
        preg_match_all('/{{json:(.*?})}}/s', $content, $matches);
        if (empty($matches[0])) {
            return [];
        }

        $tokens = [];
        foreach ($matches[0] as $index => $raw) {
            $payload = $matches[1][$index] ?? '';
            $payload = trim($payload);
            if (function_exists('wp_unslash')) {
                $payload = wp_unslash($payload);
            }
            $payload = html_entity_decode($payload, ENT_QUOTES, 'UTF-8');
            $decoded = json_decode($payload, true);
            if (!is_array($decoded)) {
                continue;
            }
            $tokens[] = [
                'raw' => $raw,
                'data' => $decoded,
            ];
        }

        return $tokens;
    }
}
