<?php

namespace Formatrica\Submission\Rendering;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * Renders templates with placeholders
 */
final class Template_Renderer
{
    /**
     * Render a template with form data
     *
     * @param string $template
     * @param array<string, mixed> $form
     * @param array<string, mixed> $payload
     * @param array<int, array<string, mixed>> $field_meta
     * @return string
     */
    public function render(string $template, array $form, array $payload, array $field_meta): string
    {
        $replacements = [
            '{{form_title}}' => isset($form['title']) ? (string) $form['title'] : '',
            '{{form_id}}' => isset($form['id']) ? (string) $form['id'] : '',
            '{{submission_json}}' => wp_json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) ?: '',
        ];

        $rendered = strtr($template, $replacements);

        $rendered = preg_replace_callback(
            '/{{field:([a-zA-Z0-9_\\-]+)}}/',
            function ($matches) use ($payload) {
                $field_name = $matches[1];
                $value = $payload[$field_name] ?? '';
                return $this->normalise_value($value);
            },
            $rendered
        );

        return trim((string) $rendered);
    }

    /**
     * Normalize a submission value for display
     *
     * @param mixed $value
     * @return string
     */
    public function normalise_value($value): string
    {
        if (is_array($value)) {
            $parts = [];
            foreach ($value as $item) {
                if (is_scalar($item) || $item === null) {
                    $parts[] = (string) $item;
                } elseif (is_array($item) || is_object($item)) {
                    $json = wp_json_encode($item);
                    if ($json !== false) {
                        $parts[] = $json;
                    }
                }
            }

            $parts = array_filter($parts, static function ($part): bool {
                return $part !== '';
            });

            return implode(', ', $parts);
        }

        if (is_bool($value)) {
            return $value ? __('Yes', 'formatrica') : __('No', 'formatrica');
        }

        if (is_scalar($value)) {
            // Edition display override for scalar values. The Pro package
            // registers geolocation flattening here (fields.geolocation);
            // Free ships no paid display code and returns the value verbatim.
            $override = apply_filters('formatrica_display_scalar_value', null, $value);
            return is_string($override) ? $override : (string) $value;
        }

        if (is_object($value)) {
            $json = wp_json_encode($value);
            return $json !== false ? $json : '';
        }

        return '';
    }
}
