<?php
/**
 * @package         ReReplacer
 * @version         14.4.1
 * 
 * @author          Peter van Westen <info@regularlabs.com>
 * @link            https://regularlabs.com
 * @copyright       Copyright © 2025 Regular Labs All Rights Reserved
 * @license         GNU General Public License version 2 or later
 */

namespace RegularLabs\Plugin\System\ReReplacer;

defined('_JEXEC') or die;

class Replace
{
    public static function replaceInAreas(&$string)
    {
        if ( ! is_string($string) || $string == '')
        {
            return;
        }

        self::replaceInArea($string, 'head');
        self::replaceInArea($string, 'body');

        self::replaceEverywhere($string);
    }

    public static function replaceInArticle(&$article, $context)
    {
        $items = Items::get('articles', $article);

        foreach ($items as $item)
        {
            $item->replaceInArticle($context);
        }

        return false;
    }

    public static function replaceInComponents(&$string)
    {
        if ( ! is_string($string) || $string == '')
        {
            return;
        }

        $items = Items::get('component');

        self::replaceItemList($string, $items);
    }

    private static function replaceEverywhere(&$string)
    {
        if ( ! is_string($string) || $string == '')
        {
            return;
        }

        $items = Items::get('everywhere');

        self::replaceItemList($string, $items);
    }

    private static function replaceInArea(&$string, $area_type = '')
    {
        if ( ! is_string($string) || $string == '' || ! $area_type)
        {
            return;
        }

        $items = Items::get($area_type);

        if (empty($items))
        {
            return;
        }

        $areas = Tag::getAreaByType($string, $area_type);

        foreach ($areas as $area_type)
        {
            self::replaceItemList($area_type[1], $items);

            $string = str_replace($area_type[0], $area_type[1], $string);
        }

        unset($areas);
    }

    private static function replaceItemList(&$string, $items)
    {
        if (empty($items))
        {
            return;
        }

        if ( ! is_array($items))
        {
            $items = [$items];
        }

        foreach ($items as $item)
        {
            $item->replace($string);
        }
    }
}
