<?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\SmartTags;

defined('_JEXEC') or die('Restricted access');

use Tassos\Framework\SmartTags\SmartTag;
use Tassos\CodeSnippets\Administrator\Helper\SnippetsHelper;

class Snippet extends SmartTag
{
    /**
     * Fetch snippet value by alias
     * 
     * @param   string  $key
     * 
     * @return  string
     */
    public function fetchValue($key)
    {
        // Key is the snippet alias
        $alias = strtolower($key);

        if (!$snippet = $this->findSnippet($alias))
        {
            return;
        }

        if (!$snippetObj = SnippetsHelper::getSnippetClass($snippet->code_type, $snippet))
        {
            return;
        }

        // Pass shortcode attributes (e.g. --name=Tassos → ['name' => 'Tassos'])
        // so they are available as $name inside the PHP snippet
        $attributes = $this->parsedOptions ? $this->parsedOptions->toArray() : [];
        $snippetObj->setAttributes($attributes);

        return $snippetObj->execute();
    }

    /**
     * Find snippet by alias from already-loaded snippets
     *
     * @param string $alias The snippet alias
     * 
     * @return object|null
     */
    private function findSnippet($alias)
    {
        // Get all snippets from cache (already loaded by LocationManager)
        if (!$snippets = SnippetsHelper::getSnippets())
        {
            return;
        }

        // Find snippet by alias with shortcode insertion method
        foreach ($snippets as $snippet)
        {
            if ($snippet->alias === $alias 
                && $snippet->state == 1 
                && isset($snippet->insertion_method) 
                && $snippet->insertion_method === 'shortcode')
            {
                if (!SnippetsHelper::passesDisplayConditions($snippet))
                {
                    continue;
                }

                return $snippet;
            }
        }
    }
}