<?php

/**
 * @package         Tassos Code Snippets
 * @version         1.0.1-RC2 Free
 *
 * @author          Tassos Marinos <info@tassos.gr>
 * @link            https://www.tassos.gr
 * @copyright       Copyright © 2026 Tassos Marinos All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
 */

namespace Tassos\CodeSnippets\Administrator\Helper;

defined('_JEXEC') or die;

use Tassos\Framework\SmartTags;
use Tassos\Framework\Extension;

/**
 * Centralised SmartTags runner for the Code Snippets component.
 *
 * Both SnippetsHelper::replaceShortcodes() (outer pass — resolves {tcs snippet.alias})
 * and Snippet::replaceAttrVars() (inner pass — resolves {tcs attr.key}) delegate here
 * to keep SmartTags configuration in one place.
 */
class SmartTagsHelper
{
    /**
     * Run a SmartTags replacement pass over $content.
     *
     * Returns early if $prefixToCheck is not found in $content, so callers do
     * not need to guard against the call themselves.
     *
     * @param   string       $content            The text to process.
     * @param   string       $prefixToCheck      Fast-path guard string (e.g. '{tcs snippet.' or '{tcs attr.').
     * @param   array|null   $attributes         Data passed to registered SmartTag classes via setData().
     *                                           Used by the attr pass to expose shortcode params to {tcs attr.*} tags.
     * @param   mixed        $skipFrameworkTags  When null, framework-level tags (user, date, etc.) are not registered
     *
     * @return  string
     */
    public static function replace(string $content, string $prefixToCheck = '{tcs snippet.', ?array $attributes = null, $skipFrameworkTags = null): string
    {
        // Bail early if there is nothing to replace.
        if (strpos($content, $prefixToCheck) === false)
        {
            return $content;
        }

        $smartTags = new SmartTags([
            'prefix'            => 'tcs',
            'isPro'             => Extension::isPro('com_tassoscodesnippets'),
            'skipFrameworkTags' => $skipFrameworkTags,
        ]);

        // Register the component's own SmartTag classes (Snippet, Attr).
        // $attributes become $this->data inside each SmartTag class via setData().
        $smartTags->register(
            '\Tassos\CodeSnippets\Administrator\SmartTags',
            JPATH_ADMINISTRATOR . '/components/com_tassoscodesnippets/src/SmartTags',
            $attributes ?? []
        );

        return $smartTags->replace($content);
    }
}