<?php

namespace Yajny\EventsYj\Traits;

use Illuminate\Database\Eloquent\Model;

/**
 * Template replacement logic central for User and ADmin
 */
trait DynamicTemplate
{
    public function templateVarReplace($varbase, $dataModel)
    {
        // $lang = app()->getLocale();
        if (!($dataModel instanceof Model)) {
            $this->template = str_ireplace('#' . $varbase, $dataModel, $this->template);
        } else {
            foreach ($dataModel->getRelations() as $relKey => $relDataModel)
                $this->templateVarReplace($relKey, $relDataModel);

            foreach ($dataModel->getAttributes() as $attrKey => $attrVal) {

                $this->template = str_ireplace('#' . $varbase . '.' . $attrKey,
                    ($dataModel->translatable && in_array($attrKey, $dataModel->translatable)) ? $dataModel->getAttribute($attrKey) : $attrVal,
                    $this->template);

                if ($this->changeTitle)
                    $this->title = str_ireplace('#' . $varbase . '.' . $attrKey,
                        ($dataModel->translatable && in_array($attrKey, $dataModel->translatable)) ? $dataModel->getAttribute($attrKey) : $attrVal,
                        $this->title);

            }

            if (isset($this->url))
                $this->url = str_ireplace('#' . $varbase . '.' . $dataModel->getKeyName(),
                    $dataModel->getAttribute($dataModel->getKeyName()),
                    $this->url);

        }
    }
}
