<?php

namespace Hilco\Models;

use \Illuminate\Support\Arr;

/**
 * Trait HasMetadata
 * @package Hilco\Models
 */
trait HasMetadata {
    public function metadata() {
        return $this->morphMany(WebMetadata::class, 'metadatable');
    }

    public function getMetadata($name, $langCode = AvailableLanguage::DEFAULT_LANG_CODE) {
        return Arr::get($this->metadata->where('meta_name', $name)->where('language_code', $langCode)->first(), 'meta_value', '');
    }

    public function setMetadata($name, $value, $langCode = AvailableLanguage::DEFAULT_LANG_CODE) {
        $metadata = $this->metadata()->where('meta_name', $name)->where('language_code', $langCode)->first();

        if (!is_null($value)) {
            if (is_null($metadata)) {
                $this->metadata()->updateOrCreate([
                    'meta_name' => $name,
                    'meta_value' => $value,
                    'language_code' => $langCode,
                ]);
            } else {
                $metadata->meta_value = $value;
                $metadata->save();
            }
        } else {
            if (!is_null($metadata)) {
                $metadata->delete();
            }
        }
    }

    public function getMetadataDescriptionAttribute() {
        return $this->getMetadata('description');
    }

    public function getMetadataTitleAttribute() {
        return $this->getMetadata('title');
    }

    /* Product hierarchy models should override the getMetadataDescriptionAttribute and getMetadataTitleAttribute
     * functions so that they default to the product name/detail or whatever.
     * The override functions are so you can still access the defined metadata value
     */
    public function getMetadataDescriptionOverrideAttribute() {
        return $this->getMetadata('description');
    }

    public function getMetadataTitleOverrideAttribute() {
        return $this->getMetadata('title');
    }

    public function setMetadataDescriptionAttribute($value) {
        $this->setMetadata('description', $value);
    }

    public function setMetadataTitleAttribute($value) {
        $this->setMetadata('title', $value);
    }

    /**
     * Get the value of a metatag field by language code
     * @param $metaName
     * @param $langCode
     * @param $column
     * @return bool|mixed|string
     */
    public function getMetadataAttrForLang ($metaName, $langCode, $column) {
        $value = $this->getMetadata($metaName, $langCode);
        if (strlen($value)) return $value;

        return $this->getTranslation($column, $langCode);
    }
}