<?php

/**
 * OBG Customizations
 *
 * Copyright (c) 2021 vonRotenberg
 *
 * @license commercial
 */

namespace vonRotenberg\RealEstateListingBundle\EventListener;

use Contao\Config;
use Contao\CoreBundle\DependencyInjection\Attribute\AsHook;
use Contao\Input;
use vonRotenberg\RealEstateListingBundle\Model\RealEstateAssetsModel;

#[AsHook('replaceInsertTags')]
class ReplaceInsertTagsListener
{
    public function __invoke(
        string $insertTag,
        bool $useCache,
        string $cachedValue,
        array $flags,
        array $tags,
        array $cache,
        int $_rit,
        int $_cnt
    )
    {
        $elements = explode('::', $insertTag,2);
        $insertTag = array_shift($elements);

        if ('re_asset' === $insertTag) {
            if (!isset($_GET['items']) && Input::get('auto_item'))
            {
                $varId = Input::get('auto_item');
            } else {
                $varId = Input::get('items');
            }
            if (($Asset = RealEstateAssetsModel::findPublishedByIdOrAlias($varId)) !== null)
            {
                if (isset($elements[0]))
                {
                    switch($elements[0])
                    {
                        case 'category_title':
                            if (($Category = $Asset->getRelated('pid')) !== null)
                            {
                                return $Category->title;
                            }
                    }
                }
            }
        }

        return false;
    }
}
