<?php

namespace Hilco\Models;

use Flynsarmy\DbBladeCompiler\Facades\DbView;
use Illuminate\Support\Str;
use Illuminate\Support\Arr;

class WebSiloOverride extends WebModel  {
	protected $table = "WebSiloOverrides";
	protected $fillable = ['websilo_id', 'overrideable_type', 'overrideable_id', 'name', 'is_visible', 'primary_webasset_id', 'detail', 'language_code', 'webproductmenuconfiguration_id'];
	protected $casts = [
	    'is_visible' => 'boolean'
	];

	public function primaryImage() {
	    return $this->belongsTo(WebAsset::class, 'primary_webasset_id', 'id');
    }

    public function webSilo() {
	    return $this->belongsTo(WebSilo::class, 'websilo_id', 'id');
    }

    public function overrideable() {
	    return $this->morphTo();
    }

    public function webProductMenuConfiguration(){
	    return $this->hasOne(WebProductMenuConfiguration::class, 'product_id', 'id')->where('product_type', '=', 'webSiloOverride');
    }

    public function setDetailAttribute($detail) {
        if (Str::contains($detail, 'mceNonEditable')) {
            throw new \InvalidArgumentException(trans('hilco::app.error_while_saving_details_please_try_again'));
        }

        $newDetail = preg_replace_callback('%<!--\\[\\[\\[(.*?)\|(.*?)\\]\\]\\]-->%', function ($matches) {
            return "@include('$matches[1]', " . str_replace(["\n", "\r"], '', var_export(json_decode($matches[2], true), true)) . ")";
        }, $detail);

        $this->attributes['detail'] = $newDetail;
    }

    public function getDetailForEditAttribute() {
        return DbView::make($this)->with(['edit' => true, 'wrap' => true])->render();
    }

    public function getDetailAttribute() {
	    return $this->getWebModelTranslation('detail');
    }

    public function getNameAttribute() {
	    return $this->getWebModelTranslation('name');
    }

    /**
     * Use this instead of HasModelTranslations->translations() because for whatever reason the Laravel morphMany
     * doesn't seem to work and we need this done fairly quickly
     * @return WebModelTranslation
     */
    public function webModelTranslations() {
        return WebModelTranslation::where('translatable_id', $this->id)->where('translatable_type', 'webSiloOverride');
    }

    /**
     * Because we had to write webModelTranslations() up there, need a custom version of getTranslation() now that uses
     * webModelTranslations() instead of translations()
     * @param $columnName
     * @param bool $language
     * @param bool $default
     * @return mixed
     */
    public function getWebModelTranslation($columnName, $language = false, $default = false) {
        if ($language === false) $language = b2b()->activeLanguage();
        if ($default === false) $default = \Illuminate\Support\Arr::get($this->attributes, $columnName, '');
        $translation = $this->webModelTranslations()->where('language', $language)->where('column_name', $columnName)->first();
        return Arr::get($translation, "translation", $default);
    }

    /**
     * Because we had to write webModelTranslations() up there, need a custom version of setTranslation() now that uses
     * webModelTranslations() instead of translations()
     * @param $language
     * @param $columnName
     * @param $translation
     */
    public function setWebModelTranslation($language, $columnName, $translation) {
        $webModelTranslation =
            $this->webModelTranslations()
                ->withTrashed()
                ->where('language', $language)
                ->where('column_name', $columnName)
                ->first()
        ;

        if(isset($webModelTranslation)) {
          if ($webModelTranslation->trashed()) {
              $webModelTranslation->restore();
          }
          $webModelTranslation->update([
              'language'    => $language,
              'column_name' => $columnName,
              'translation' => $translation,
          ]);
        } else {
            $webModelTranslation = new WebModelTranslation();
            $webModelTranslation->translatable_id   = $this->id;
            $webModelTranslation->translatable_type = 'webSiloOverride';
            $webModelTranslation->language          = $language;
            $webModelTranslation->column_name       = $columnName;
            $webModelTranslation->translation       = $translation;
            $webModelTranslation->save();
        }
    }

    use HasModelTranslations;
}
