<?php

use App\Libs\Facades\Localization;

trait LanguageSupportTrait
{
    protected $languageAttributes = array();

    public function languages()
    {
        $className = get_class($this);
        return $this->hasMany("{$className}Language");
    }

    public function getAttribute($key)
    {

        if (parent::keyExists($key)) {
            return parent::getAttribute($key);
        }

        if ($this->exists) {

            $activeLang = $this->getActiveLanguage();

            if (!empty($activeLang) && !empty($activeLang->$key)) {
                return $activeLang->$key;
            }

            if (config("app.showDefaultLanguage")) {

                $defaultLang = $this->getDefaultLanguage();

                if (!empty($defaultLang) && !empty($defaultLang->$key)) {
                    return $defaultLang->$key;
                }
            }
        }

        return null;

    }

    public function getDefaultLanguage()
    {
        $languagesData = $this->languages;
        if (empty($languagesData)) {
            return null;
        }
        $language = $languagesData->findByLocale(Localization::getDefaultLocale());
        return $language;
    }

    public function getActiveLanguage()
    {
        $languagesData = $this->languages;
        if (empty($languagesData)) {
            return null;
        }

        $language = $languagesData->findByLocale(Localization::getActiveLocale());
        return $language;
    }

    public function toArray()
    {
        $array = parent::toArray();
        if (isset($this->relations["languages"])) {
            $defaultLanguage = $this->getActiveLanguage();
            $languageAttributes = array_keys($defaultLanguage->getAttributes());

            foreach ($languageAttributes as $languageAttribute) {
                if (!in_array($languageAttribute, $this->hidden)) {
                    $array[$languageAttribute] = $this->$languageAttribute;
                    if ($array[$languageAttribute] instanceof DateTime) {
                        $array[$languageAttribute] = $array[$languageAttribute]->format($this->getDateFormat());
                    }
                }
            }
        }
        return $array;
    }
}

