<?php

namespace Licenzo\Services\ShortcodeParser;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

use Licenzo\Framework\Support\Arr;

class Parser
{
    public static function parse($template = [], $attributes = [])
    {
        // If the template is array, convert to string
        if (is_array($template)) {
            $template = implode('', $template);
        }

        $attributes = array_merge(static::siteCodes(), $attributes);

        // Pattern: { key.path | pipe }
        // Example matches: {customer.name}, {user.first_name|upper}
        return preg_replace_callback('/\{([^|{}]+)((?:\|[^|{}]+)*)\}/', function ($matches) use ($attributes) {

            $path = trim($matches[1]);
            $pipesString = Arr::get($matches, 2, '');
            $pipes = [];

            if ($pipesString) {
                // Remove the leading '|' and split by '|', filter empty entries
                $pipes = array_filter(array_map('trim', explode('|', ltrim($pipesString, '|'))));
            }

            $value = Arr::get($attributes, $path);

            if ($value === null || $value === '') {
                return 'undefined';
            }

            foreach ($pipes as $pipe) {
                $value = static::applyPipe($value, $pipe);
            }

            return $value;
        }, $template);
    }


    public static function applyPipe($content, $pipe)
    {
        return (new HandlePipe())->handle($content, $pipe);
    }

    public static function siteCodes()
    {
        // get admin user
        $admin = get_user_by('email', get_option('admin_email'));

        $adminUser = [
            'name'  => $admin->display_name ?? $admin->user_login ?? 'Admin',
            'email' => get_option('admin_email')
        ];

        $site = [
            'name'        => get_bloginfo('name'),
            'url'         => get_bloginfo('url'),
            'admin_email' => get_option('admin_email'),
        ];

        return [
            'admin' => $adminUser,
            'site'  => $site,
        ];
    }
}
