<?php

namespace FSPoster\App\SocialNetworks\Webhook\Helpers;

class CustomMessageReplacer
{
    public const KEYWORD = '{webhook_custom_message}';

    public static function replace($value, string $message)
    {
        return self::replaceWith($value, $message);
    }

    public static function replaceForUrl($value, string $message)
    {
        return self::replaceWith($value, rawurlencode($message));
    }

    public static function replaceForHeader($value, string $message)
    {
        $message = preg_replace('/[\r\n]+/', ' ', $message);

        return self::replaceWith($value, trim($message));
    }

    private static function replaceWith($value, string $message)
    {
        if (is_array($value)) {
            foreach ($value as $key => $item) {
                $value[$key] = self::replaceWith($item, $message);
            }

            return $value;
        }

        if (is_string($value)) {
            return str_replace(self::KEYWORD, $message, $value);
        }

        return $value;
    }
}
